forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnsafeBufferUsage.cpp
4419 lines (3905 loc) · 160 KB
/
UnsafeBufferUsage.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
//===- UnsafeBufferUsage.cpp - Replace pointers with modern C++ -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
#include "clang/AST/APValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/FormatString.h"
#include "clang/AST/ParentMapContext.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/Type.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include <cstddef>
#include <optional>
#include <queue>
#include <set>
#include <sstream>
using namespace llvm;
using namespace clang;
#ifndef NDEBUG
namespace {
class StmtDebugPrinter
: public ConstStmtVisitor<StmtDebugPrinter, std::string> {
public:
std::string VisitStmt(const Stmt *S) { return S->getStmtClassName(); }
std::string VisitBinaryOperator(const BinaryOperator *BO) {
return "BinaryOperator(" + BO->getOpcodeStr().str() + ")";
}
std::string VisitUnaryOperator(const UnaryOperator *UO) {
return "UnaryOperator(" + UO->getOpcodeStr(UO->getOpcode()).str() + ")";
}
std::string VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
return "ImplicitCastExpr(" + std::string(ICE->getCastKindName()) + ")";
}
};
// Returns a string of ancestor `Stmt`s of the given `DRE` in such a form:
// "DRE ==> parent-of-DRE ==> grandparent-of-DRE ==> ...".
static std::string getDREAncestorString(const DeclRefExpr *DRE,
ASTContext &Ctx) {
std::stringstream SS;
const Stmt *St = DRE;
StmtDebugPrinter StmtPriner;
do {
SS << StmtPriner.Visit(St);
DynTypedNodeList StParents = Ctx.getParents(*St);
if (StParents.size() > 1)
return "unavailable due to multiple parents";
if (StParents.empty())
break;
St = StParents.begin()->get<Stmt>();
if (St)
SS << " ==> ";
} while (St);
return SS.str();
}
} // namespace
#endif /* NDEBUG */
namespace {
// Using a custom `FastMatcher` instead of ASTMatchers to achieve better
// performance. FastMatcher uses simple function `matches` to find if a node
// is a match, avoiding the dependency on the ASTMatchers framework which
// provide a nice abstraction, but incur big performance costs.
class FastMatcher {
public:
virtual bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
const UnsafeBufferUsageHandler &Handler) = 0;
virtual ~FastMatcher() = default;
};
class MatchResult {
public:
template <typename T> const T *getNodeAs(StringRef ID) const {
auto It = Nodes.find(ID);
if (It == Nodes.end()) {
return nullptr;
}
return It->second.get<T>();
}
void addNode(StringRef ID, const DynTypedNode &Node) { Nodes[ID] = Node; }
private:
llvm::StringMap<DynTypedNode> Nodes;
};
} // namespace
// A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
// except for those belonging to a different callable of "n".
class MatchDescendantVisitor : public DynamicRecursiveASTVisitor {
public:
// Creates an AST visitor that matches `Matcher` on all
// descendants of a given node "n" except for the ones
// belonging to a different callable of "n".
MatchDescendantVisitor(ASTContext &Context, FastMatcher &Matcher,
bool FindAll, bool ignoreUnevaluatedContext,
const UnsafeBufferUsageHandler &NewHandler)
: Matcher(&Matcher), FindAll(FindAll), Matches(false),
ignoreUnevaluatedContext(ignoreUnevaluatedContext),
ActiveASTContext(&Context), Handler(&NewHandler) {
ShouldVisitTemplateInstantiations = true;
ShouldVisitImplicitCode = false; // TODO: let's ignore implicit code for now
}
// Returns true if a match is found in a subtree of `DynNode`, which belongs
// to the same callable of `DynNode`.
bool findMatch(const DynTypedNode &DynNode) {
Matches = false;
if (const Stmt *StmtNode = DynNode.get<Stmt>()) {
TraverseStmt(const_cast<Stmt *>(StmtNode));
return Matches;
}
return false;
}
// The following are overriding methods from the base visitor class.
// They are public only to allow CRTP to work. They are *not *part
// of the public API of this class.
// For the matchers so far used in safe buffers, we only need to match
// `Stmt`s. To override more as needed.
bool TraverseDecl(Decl *Node) override {
if (!Node)
return true;
if (!match(*Node))
return false;
// To skip callables:
if (isa<FunctionDecl, BlockDecl, ObjCMethodDecl>(Node))
return true;
// Traverse descendants
return DynamicRecursiveASTVisitor::TraverseDecl(Node);
}
bool TraverseGenericSelectionExpr(GenericSelectionExpr *Node) override {
// These are unevaluated, except the result expression.
if (ignoreUnevaluatedContext)
return TraverseStmt(Node->getResultExpr());
return DynamicRecursiveASTVisitor::TraverseGenericSelectionExpr(Node);
}
bool
TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return DynamicRecursiveASTVisitor::TraverseUnaryExprOrTypeTraitExpr(Node);
}
bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return DynamicRecursiveASTVisitor::TraverseTypeOfExprTypeLoc(Node);
}
bool TraverseDecltypeTypeLoc(DecltypeTypeLoc Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return DynamicRecursiveASTVisitor::TraverseDecltypeTypeLoc(Node);
}
bool TraverseCXXNoexceptExpr(CXXNoexceptExpr *Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return DynamicRecursiveASTVisitor::TraverseCXXNoexceptExpr(Node);
}
bool TraverseCXXTypeidExpr(CXXTypeidExpr *Node) override {
// Unevaluated context.
if (ignoreUnevaluatedContext)
return true;
return DynamicRecursiveASTVisitor::TraverseCXXTypeidExpr(Node);
}
bool TraverseCXXDefaultInitExpr(CXXDefaultInitExpr *Node) override {
if (!TraverseStmt(Node->getExpr()))
return false;
return DynamicRecursiveASTVisitor::TraverseCXXDefaultInitExpr(Node);
}
bool TraverseStmt(Stmt *Node) override {
if (!Node)
return true;
if (!match(*Node))
return false;
return DynamicRecursiveASTVisitor::TraverseStmt(Node);
}
private:
// Sets 'Matched' to true if 'Matcher' matches 'Node'
//
// Returns 'true' if traversal should continue after this function
// returns, i.e. if no match is found or 'Bind' is 'BK_All'.
template <typename T> bool match(const T &Node) {
if (Matcher->matches(DynTypedNode::create(Node), *ActiveASTContext,
*Handler)) {
Matches = true;
if (!FindAll)
return false; // Abort as soon as a match is found.
}
return true;
}
FastMatcher *const Matcher;
// When true, finds all matches. When false, finds the first match and stops.
const bool FindAll;
bool Matches;
bool ignoreUnevaluatedContext;
ASTContext *ActiveASTContext;
const UnsafeBufferUsageHandler *Handler;
};
// Because we're dealing with raw pointers, let's define what we mean by that.
static bool hasPointerType(const Expr &E) {
return isa<PointerType>(E.getType().getCanonicalType());
}
static bool hasArrayType(const Expr &E) {
return isa<ArrayType>(E.getType().getCanonicalType());
}
static void
forEachDescendantEvaluatedStmt(const Stmt *S, ASTContext &Ctx,
const UnsafeBufferUsageHandler &Handler,
FastMatcher &Matcher) {
MatchDescendantVisitor Visitor(Ctx, Matcher, /*FindAll=*/true,
/*ignoreUnevaluatedContext=*/true, Handler);
Visitor.findMatch(DynTypedNode::create(*S));
}
static void forEachDescendantStmt(const Stmt *S, ASTContext &Ctx,
const UnsafeBufferUsageHandler &Handler,
FastMatcher &Matcher) {
MatchDescendantVisitor Visitor(Ctx, Matcher, /*FindAll=*/true,
/*ignoreUnevaluatedContext=*/false, Handler);
Visitor.findMatch(DynTypedNode::create(*S));
}
// Matches a `Stmt` node iff the node is in a safe-buffer opt-out region
static bool notInSafeBufferOptOut(const Stmt &Node,
const UnsafeBufferUsageHandler *Handler) {
return !Handler->isSafeBufferOptOut(Node.getBeginLoc());
}
static bool
ignoreUnsafeBufferInContainer(const Stmt &Node,
const UnsafeBufferUsageHandler *Handler) {
return Handler->ignoreUnsafeBufferInContainer(Node.getBeginLoc());
}
static bool ignoreUnsafeLibcCall(const ASTContext &Ctx, const Stmt &Node,
const UnsafeBufferUsageHandler *Handler) {
if (Ctx.getLangOpts().CPlusPlus)
return Handler->ignoreUnsafeBufferInLibcCall(Node.getBeginLoc());
return true; /* Only warn about libc calls for C++ */
}
// Finds any expression 'e' such that `OnResult`
// matches 'e' and 'e' is in an Unspecified Lvalue Context.
static void findStmtsInUnspecifiedLvalueContext(
const Stmt *S, const llvm::function_ref<void(const Expr *)> OnResult) {
if (const auto *CE = dyn_cast<ImplicitCastExpr>(S);
CE && CE->getCastKind() == CastKind::CK_LValueToRValue)
OnResult(CE->getSubExpr());
if (const auto *BO = dyn_cast<BinaryOperator>(S);
BO && BO->getOpcode() == BO_Assign)
OnResult(BO->getLHS());
}
/// Note: Copied and modified from ASTMatchers.
/// Matches all arguments and their respective types for a \c CallExpr.
/// It is very similar to \c forEachArgumentWithParam but
/// it works on calls through function pointers as well.
///
/// The difference is, that function pointers do not provide access to a
/// \c ParmVarDecl, but only the \c QualType for each argument.
///
/// Given
/// \code
/// void f(int i);
/// int y;
/// f(y);
/// void (*f_ptr)(int) = f;
/// f_ptr(y);
/// \endcode
/// callExpr(
/// forEachArgumentWithParamType(
/// declRefExpr(to(varDecl(hasName("y")))),
/// qualType(isInteger()).bind("type)
/// ))
/// matches f(y) and f_ptr(y)
/// with declRefExpr(...)
/// matching int y
/// and qualType(...)
/// matching int
static void forEachArgumentWithParamType(
const CallExpr &Node,
const llvm::function_ref<void(QualType /*Param*/, const Expr * /*Arg*/)>
OnParamAndArg) {
// The first argument of an overloaded member operator is the implicit object
// argument of the method which should not be matched against a parameter, so
// we skip over it here.
unsigned ArgIndex = 0;
if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(&Node)) {
const auto *MD = dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee());
if (MD && !MD->isExplicitObjectMemberFunction()) {
// This is an overloaded operator call.
// We need to skip the first argument, which is the implicit object
// argument of the method which should not be matched against a
// parameter.
++ArgIndex;
}
}
const FunctionProtoType *FProto = nullptr;
if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
if (const auto *Value =
dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
QualType QT = Value->getType().getCanonicalType();
// This does not necessarily lead to a `FunctionProtoType`,
// e.g. K&R functions do not have a function prototype.
if (QT->isFunctionPointerType())
FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
if (QT->isMemberFunctionPointerType()) {
const auto *MP = QT->getAs<MemberPointerType>();
assert(MP && "Must be member-pointer if its a memberfunctionpointer");
FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
assert(FProto &&
"The call must have happened through a member function "
"pointer");
}
}
}
unsigned ParamIndex = 0;
unsigned NumArgs = Node.getNumArgs();
if (FProto && FProto->isVariadic())
NumArgs = std::min(NumArgs, FProto->getNumParams());
const auto GetParamType =
[&FProto, &Node](unsigned int ParamIndex) -> std::optional<QualType> {
if (FProto && FProto->getNumParams() > ParamIndex) {
return FProto->getParamType(ParamIndex);
}
const auto *FD = Node.getDirectCallee();
if (FD && FD->getNumParams() > ParamIndex) {
return FD->getParamDecl(ParamIndex)->getType();
}
return std::nullopt;
};
for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
auto ParamType = GetParamType(ParamIndex);
if (ParamType)
OnParamAndArg(*ParamType, Node.getArg(ArgIndex)->IgnoreParenCasts());
}
}
// Finds any expression `e` such that `InnerMatcher` matches `e` and
// `e` is in an Unspecified Pointer Context (UPC).
static void findStmtsInUnspecifiedPointerContext(
const Stmt *S, llvm::function_ref<void(const Stmt *)> InnerMatcher) {
// A UPC can be
// 1. an argument of a function call (except the callee has [[unsafe_...]]
// attribute), or
// 2. the operand of a pointer-to-(integer or bool) cast operation; or
// 3. the operand of a comparator operation; or
// 4. the operand of a pointer subtraction operation
// (i.e., computing the distance between two pointers); or ...
if (auto *CE = dyn_cast<CallExpr>(S)) {
if (const auto *FnDecl = CE->getDirectCallee();
FnDecl && FnDecl->hasAttr<UnsafeBufferUsageAttr>())
return;
forEachArgumentWithParamType(
*CE, [&InnerMatcher](QualType Type, const Expr *Arg) {
if (Type->isAnyPointerType())
InnerMatcher(Arg);
});
}
if (auto *CE = dyn_cast<CastExpr>(S)) {
if (CE->getCastKind() != CastKind::CK_PointerToIntegral &&
CE->getCastKind() != CastKind::CK_PointerToBoolean)
return;
if (!hasPointerType(*CE->getSubExpr()))
return;
InnerMatcher(CE->getSubExpr());
}
// Pointer comparison operator.
if (const auto *BO = dyn_cast<BinaryOperator>(S);
BO && (BO->getOpcode() == BO_EQ || BO->getOpcode() == BO_NE ||
BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE ||
BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE)) {
auto *LHS = BO->getLHS();
if (hasPointerType(*LHS))
InnerMatcher(LHS);
auto *RHS = BO->getRHS();
if (hasPointerType(*RHS))
InnerMatcher(RHS);
}
// Pointer subtractions.
if (const auto *BO = dyn_cast<BinaryOperator>(S);
BO && BO->getOpcode() == BO_Sub && hasPointerType(*BO->getLHS()) &&
hasPointerType(*BO->getRHS())) {
// Note that here we need both LHS and RHS to be
// pointer. Then the inner matcher can match any of
// them:
InnerMatcher(BO->getLHS());
InnerMatcher(BO->getRHS());
}
// FIXME: any more cases? (UPC excludes the RHS of an assignment. For now
// we don't have to check that.)
}
// Finds statements in unspecified untyped context i.e. any expression 'e' such
// that `InnerMatcher` matches 'e' and 'e' is in an unspecified untyped context
// (i.e the expression 'e' isn't evaluated to an RValue). For example, consider
// the following code:
// int *p = new int[4];
// int *q = new int[4];
// if ((p = q)) {}
// p = q;
// The expression `p = q` in the conditional of the `if` statement
// `if ((p = q))` is evaluated as an RValue, whereas the expression `p = q;`
// in the assignment statement is in an untyped context.
static void findStmtsInUnspecifiedUntypedContext(
const Stmt *S, llvm::function_ref<void(const Stmt *)> InnerMatcher) {
// An unspecified context can be
// 1. A compound statement,
// 2. The body of an if statement
// 3. Body of a loop
if (auto *CS = dyn_cast<CompoundStmt>(S)) {
for (auto *Child : CS->body())
InnerMatcher(Child);
}
if (auto *IfS = dyn_cast<IfStmt>(S)) {
if (IfS->getThen())
InnerMatcher(IfS->getThen());
if (IfS->getElse())
InnerMatcher(IfS->getElse());
}
// FIXME: Handle loop bodies.
}
// Returns true iff integer E1 is equivalent to integer E2.
//
// For now we only support such expressions:
// expr := DRE | const-value | expr BO expr
// BO := '*' | '+'
//
// FIXME: We can reuse the expression comparator of the interop analysis after
// it has been upstreamed.
static bool areEqualIntegers(const Expr *E1, const Expr *E2, ASTContext &Ctx);
static bool areEqualIntegralBinaryOperators(const BinaryOperator *E1,
const Expr *E2_LHS,
BinaryOperatorKind BOP,
const Expr *E2_RHS,
ASTContext &Ctx) {
if (E1->getOpcode() == BOP) {
switch (BOP) {
// Commutative operators:
case BO_Mul:
case BO_Add:
return (areEqualIntegers(E1->getLHS(), E2_LHS, Ctx) &&
areEqualIntegers(E1->getRHS(), E2_RHS, Ctx)) ||
(areEqualIntegers(E1->getLHS(), E2_RHS, Ctx) &&
areEqualIntegers(E1->getRHS(), E2_LHS, Ctx));
default:
return false;
}
}
return false;
}
static bool areEqualIntegers(const Expr *E1, const Expr *E2, ASTContext &Ctx) {
E1 = E1->IgnoreParenImpCasts();
E2 = E2->IgnoreParenImpCasts();
if (!E1->getType()->isIntegerType() || E1->getType() != E2->getType())
return false;
Expr::EvalResult ER1, ER2;
// If both are constants:
if (E1->EvaluateAsInt(ER1, Ctx) && E2->EvaluateAsInt(ER2, Ctx))
return ER1.Val.getInt() == ER2.Val.getInt();
// Otherwise, they should have identical stmt kind:
if (E1->getStmtClass() != E2->getStmtClass())
return false;
switch (E1->getStmtClass()) {
case Stmt::DeclRefExprClass:
return cast<DeclRefExpr>(E1)->getDecl() == cast<DeclRefExpr>(E2)->getDecl();
case Stmt::BinaryOperatorClass: {
auto BO2 = cast<BinaryOperator>(E2);
return areEqualIntegralBinaryOperators(cast<BinaryOperator>(E1),
BO2->getLHS(), BO2->getOpcode(),
BO2->getRHS(), Ctx);
}
default:
return false;
}
}
// Given a two-param std::span construct call, matches iff the call has the
// following forms:
// 1. `std::span<T>{new T[n], n}`, where `n` is a literal or a DRE
// 2. `std::span<T>{new T, 1}`
// 3. `std::span<T>{&var, 1}` or `std::span<T>{std::addressof(...), 1}`
// 4. `std::span<T>{a, n}`, where `a` is of an array-of-T with constant size
// `n`
// 5. `std::span<T>{any, 0}`
// 6. `std::span<T>{ (char *)f(args), args[N] * arg*[M]}`, where
// `f` is a function with attribute `alloc_size(N, M)`;
// `args` represents the list of arguments;
// `N, M` are parameter indexes to the allocating element number and size.
// Sometimes, there is only one parameter index representing the total
// size.
static bool isSafeSpanTwoParamConstruct(const CXXConstructExpr &Node,
ASTContext &Ctx) {
assert(Node.getNumArgs() == 2 &&
"expecting a two-parameter std::span constructor");
const Expr *Arg0 = Node.getArg(0)->IgnoreParenImpCasts();
const Expr *Arg1 = Node.getArg(1)->IgnoreParenImpCasts();
auto HaveEqualConstantValues = [&Ctx](const Expr *E0, const Expr *E1) {
if (auto E0CV = E0->getIntegerConstantExpr(Ctx))
if (auto E1CV = E1->getIntegerConstantExpr(Ctx)) {
return APSInt::compareValues(*E0CV, *E1CV) == 0;
}
return false;
};
auto AreSameDRE = [](const Expr *E0, const Expr *E1) {
if (auto *DRE0 = dyn_cast<DeclRefExpr>(E0))
if (auto *DRE1 = dyn_cast<DeclRefExpr>(E1)) {
return DRE0->getDecl() == DRE1->getDecl();
}
return false;
};
std::optional<APSInt> Arg1CV = Arg1->getIntegerConstantExpr(Ctx);
if (Arg1CV && Arg1CV->isZero())
// Check form 5:
return true;
// Check forms 1-3:
switch (Arg0->getStmtClass()) {
case Stmt::CXXNewExprClass:
if (auto Size = cast<CXXNewExpr>(Arg0)->getArraySize()) {
// Check form 1:
return AreSameDRE((*Size)->IgnoreImplicit(), Arg1) ||
HaveEqualConstantValues(*Size, Arg1);
}
// TODO: what's placeholder type? avoid it for now.
if (!cast<CXXNewExpr>(Arg0)->hasPlaceholderType()) {
// Check form 2:
return Arg1CV && Arg1CV->isOne();
}
break;
case Stmt::UnaryOperatorClass:
if (cast<UnaryOperator>(Arg0)->getOpcode() ==
UnaryOperator::Opcode::UO_AddrOf)
// Check form 3:
return Arg1CV && Arg1CV->isOne();
break;
case Stmt::CallExprClass:
// Check form 3:
if (const auto *CE = dyn_cast<CallExpr>(Arg0)) {
const auto FnDecl = CE->getDirectCallee();
if (FnDecl && FnDecl->getNameAsString() == "addressof" &&
FnDecl->isInStdNamespace()) {
return Arg1CV && Arg1CV->isOne();
}
}
break;
default:
break;
}
QualType Arg0Ty = Arg0->IgnoreImplicit()->getType();
if (auto *ConstArrTy = Ctx.getAsConstantArrayType(Arg0Ty)) {
const APSInt ConstArrSize = APSInt(ConstArrTy->getSize());
// Check form 4:
return Arg1CV && APSInt::compareValues(ConstArrSize, *Arg1CV) == 0;
}
// Check form 6:
if (auto CCast = dyn_cast<CStyleCastExpr>(Arg0)) {
if (!CCast->getType()->isPointerType())
return false;
QualType PteTy = CCast->getType()->getPointeeType();
if (!(PteTy->isConstantSizeType() && Ctx.getTypeSizeInChars(PteTy).isOne()))
return false;
if (const auto *Call = dyn_cast<CallExpr>(CCast->getSubExpr())) {
if (const FunctionDecl *FD = Call->getDirectCallee())
if (auto *AllocAttr = FD->getAttr<AllocSizeAttr>()) {
const Expr *EleSizeExpr =
Call->getArg(AllocAttr->getElemSizeParam().getASTIndex());
// NumElemIdx is invalid if AllocSizeAttr has 1 argument:
ParamIdx NumElemIdx = AllocAttr->getNumElemsParam();
if (!NumElemIdx.isValid())
return areEqualIntegers(Arg1, EleSizeExpr, Ctx);
const Expr *NumElesExpr = Call->getArg(NumElemIdx.getASTIndex());
if (auto BO = dyn_cast<BinaryOperator>(Arg1))
return areEqualIntegralBinaryOperators(BO, NumElesExpr, BO_Mul,
EleSizeExpr, Ctx);
}
}
}
return false;
}
static bool isSafeArraySubscript(const ArraySubscriptExpr &Node,
const ASTContext &Ctx) {
// FIXME: Proper solution:
// - refactor Sema::CheckArrayAccess
// - split safe/OOB/unknown decision logic from diagnostics emitting code
// - e. g. "Try harder to find a NamedDecl to point at in the note."
// already duplicated
// - call both from Sema and from here
uint64_t limit;
if (const auto *CATy =
dyn_cast<ConstantArrayType>(Node.getBase()
->IgnoreParenImpCasts()
->getType()
->getUnqualifiedDesugaredType())) {
limit = CATy->getLimitedSize();
} else if (const auto *SLiteral = dyn_cast<clang::StringLiteral>(
Node.getBase()->IgnoreParenImpCasts())) {
limit = SLiteral->getLength() + 1;
} else {
return false;
}
Expr::EvalResult EVResult;
const Expr *IndexExpr = Node.getIdx();
if (!IndexExpr->isValueDependent() &&
IndexExpr->EvaluateAsInt(EVResult, Ctx)) {
llvm::APSInt ArrIdx = EVResult.Val.getInt();
// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's a
// bug
if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < limit)
return true;
} else if (const auto *BE = dyn_cast<BinaryOperator>(IndexExpr)) {
// For an integer expression `e` and an integer constant `n`, `e & n` and
// `n & e` are bounded by `n`:
if (BE->getOpcode() != BO_And)
return false;
const Expr *LHS = BE->getLHS();
const Expr *RHS = BE->getRHS();
if ((!LHS->isValueDependent() &&
LHS->EvaluateAsInt(EVResult, Ctx)) || // case: `n & e`
(!RHS->isValueDependent() &&
RHS->EvaluateAsInt(EVResult, Ctx))) { // `e & n`
llvm::APSInt result = EVResult.Val.getInt();
if (result.isNonNegative() && result.getLimitedValue() < limit)
return true;
}
return false;
}
return false;
}
namespace libc_func_matchers {
// Under `libc_func_matchers`, define a set of matchers that match unsafe
// functions in libc and unsafe calls to them.
// A tiny parser to strip off common prefix and suffix of libc function names
// in real code.
//
// Given a function name, `matchName` returns `CoreName` according to the
// following grammar:
//
// LibcName := CoreName | CoreName + "_s"
// MatchingName := "__builtin_" + LibcName |
// "__builtin___" + LibcName + "_chk" |
// "__asan_" + LibcName
//
struct LibcFunNamePrefixSuffixParser {
StringRef matchName(StringRef FunName, bool isBuiltin) {
// Try to match __builtin_:
if (isBuiltin && FunName.starts_with("__builtin_"))
// Then either it is __builtin_LibcName or __builtin___LibcName_chk or
// no match:
return matchLibcNameOrBuiltinChk(
FunName.drop_front(10 /* truncate "__builtin_" */));
// Try to match __asan_:
if (FunName.starts_with("__asan_"))
return matchLibcName(FunName.drop_front(7 /* truncate of "__asan_" */));
return matchLibcName(FunName);
}
// Parameter `Name` is the substring after stripping off the prefix
// "__builtin_".
StringRef matchLibcNameOrBuiltinChk(StringRef Name) {
if (Name.starts_with("__") && Name.ends_with("_chk"))
return matchLibcName(
Name.drop_front(2).drop_back(4) /* truncate "__" and "_chk" */);
return matchLibcName(Name);
}
StringRef matchLibcName(StringRef Name) {
if (Name.ends_with("_s"))
return Name.drop_back(2 /* truncate "_s" */);
return Name;
}
};
// A pointer type expression is known to be null-terminated, if it has the
// form: E.c_str(), for any expression E of `std::string` type.
static bool isNullTermPointer(const Expr *Ptr) {
if (isa<clang::StringLiteral>(Ptr->IgnoreParenImpCasts()))
return true;
if (isa<PredefinedExpr>(Ptr->IgnoreParenImpCasts()))
return true;
if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Ptr->IgnoreParenImpCasts())) {
const CXXMethodDecl *MD = MCE->getMethodDecl();
const CXXRecordDecl *RD = MCE->getRecordDecl()->getCanonicalDecl();
if (MD && RD && RD->isInStdNamespace())
if (MD->getName() == "c_str" && RD->getName() == "basic_string")
return true;
}
return false;
}
// Return true iff at least one of following cases holds:
// 1. Format string is a literal and there is an unsafe pointer argument
// corresponding to an `s` specifier;
// 2. Format string is not a literal and there is least an unsafe pointer
// argument (including the formatter argument).
//
// `UnsafeArg` is the output argument that will be set only if this function
// returns true.
static bool hasUnsafeFormatOrSArg(const CallExpr *Call, const Expr *&UnsafeArg,
const unsigned FmtArgIdx, ASTContext &Ctx,
bool isKprintf = false) {
class StringFormatStringHandler
: public analyze_format_string::FormatStringHandler {
const CallExpr *Call;
unsigned FmtArgIdx;
const Expr *&UnsafeArg;
public:
StringFormatStringHandler(const CallExpr *Call, unsigned FmtArgIdx,
const Expr *&UnsafeArg)
: Call(Call), FmtArgIdx(FmtArgIdx), UnsafeArg(UnsafeArg) {}
bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen,
const TargetInfo &Target) override {
if (FS.getConversionSpecifier().getKind() ==
analyze_printf::PrintfConversionSpecifier::sArg) {
unsigned ArgIdx = FS.getPositionalArgIndex() + FmtArgIdx;
if (0 < ArgIdx && ArgIdx < Call->getNumArgs())
if (!isNullTermPointer(Call->getArg(ArgIdx))) {
UnsafeArg = Call->getArg(ArgIdx); // output
// returning false stops parsing immediately
return false;
}
}
return true; // continue parsing
}
};
const Expr *Fmt = Call->getArg(FmtArgIdx);
if (auto *SL = dyn_cast<clang::StringLiteral>(Fmt->IgnoreParenImpCasts())) {
StringRef FmtStr;
if (SL->getCharByteWidth() == 1)
FmtStr = SL->getString();
else if (auto EvaledFmtStr = SL->tryEvaluateString(Ctx))
FmtStr = *EvaledFmtStr;
else
goto CHECK_UNSAFE_PTR;
StringFormatStringHandler Handler(Call, FmtArgIdx, UnsafeArg);
return analyze_format_string::ParsePrintfString(
Handler, FmtStr.begin(), FmtStr.end(), Ctx.getLangOpts(),
Ctx.getTargetInfo(), isKprintf);
}
CHECK_UNSAFE_PTR:
// If format is not a string literal, we cannot analyze the format string.
// In this case, this call is considered unsafe if at least one argument
// (including the format argument) is unsafe pointer.
return llvm::any_of(
llvm::make_range(Call->arg_begin() + FmtArgIdx, Call->arg_end()),
[&UnsafeArg](const Expr *Arg) -> bool {
if (Arg->getType()->isPointerType() && !isNullTermPointer(Arg)) {
UnsafeArg = Arg;
return true;
}
return false;
});
}
// Matches a FunctionDecl node such that
// 1. It's name, after stripping off predefined prefix and suffix, is
// `CoreName`; and
// 2. `CoreName` or `CoreName[str/wcs]` is one of the `PredefinedNames`, which
// is a set of libc function names.
//
// Note: For predefined prefix and suffix, see `LibcFunNamePrefixSuffixParser`.
// The notation `CoreName[str/wcs]` means a new name obtained from replace
// string "wcs" with "str" in `CoreName`.
static bool isPredefinedUnsafeLibcFunc(const FunctionDecl &Node) {
static std::unique_ptr<std::set<StringRef>> PredefinedNames = nullptr;
if (!PredefinedNames)
PredefinedNames =
std::make_unique<std::set<StringRef>, std::set<StringRef>>({
// numeric conversion:
"atof",
"atoi",
"atol",
"atoll",
"strtol",
"strtoll",
"strtoul",
"strtoull",
"strtof",
"strtod",
"strtold",
"strtoimax",
"strtoumax",
// "strfromf", "strfromd", "strfroml", // C23?
// string manipulation:
"strcpy",
"strncpy",
"strlcpy",
"strcat",
"strncat",
"strlcat",
"strxfrm",
"strdup",
"strndup",
// string examination:
"strlen",
"strnlen",
"strcmp",
"strncmp",
"stricmp",
"strcasecmp",
"strcoll",
"strchr",
"strrchr",
"strspn",
"strcspn",
"strpbrk",
"strstr",
"strtok",
// "mem-" functions
"memchr",
"wmemchr",
"memcmp",
"wmemcmp",
"memcpy",
"memccpy",
"mempcpy",
"wmemcpy",
"memmove",
"wmemmove",
"memset",
"wmemset",
// IO:
"fread",
"fwrite",
"fgets",
"fgetws",
"gets",
"fputs",
"fputws",
"puts",
// others
"strerror_s",
"strerror_r",
"bcopy",
"bzero",
"bsearch",
"qsort",
});
auto *II = Node.getIdentifier();
if (!II)
return false;
StringRef Name = LibcFunNamePrefixSuffixParser().matchName(
II->getName(), Node.getBuiltinID());
// Match predefined names:
if (PredefinedNames->find(Name) != PredefinedNames->end())
return true;
std::string NameWCS = Name.str();
size_t WcsPos = NameWCS.find("wcs");
while (WcsPos != std::string::npos) {
NameWCS[WcsPos++] = 's';
NameWCS[WcsPos++] = 't';
NameWCS[WcsPos++] = 'r';
WcsPos = NameWCS.find("wcs", WcsPos);
}
if (PredefinedNames->find(NameWCS) != PredefinedNames->end())
return true;
// All `scanf` functions are unsafe (including `sscanf`, `vsscanf`, etc.. They
// all should end with "scanf"):
return Name.ends_with("scanf");
}
// Match a call to one of the `v*printf` functions taking `va_list`. We cannot
// check safety for these functions so they should be changed to their
// non-va_list versions.
static bool isUnsafeVaListPrintfFunc(const FunctionDecl &Node) {
auto *II = Node.getIdentifier();
if (!II)
return false;
StringRef Name = LibcFunNamePrefixSuffixParser().matchName(
II->getName(), Node.getBuiltinID());
if (!Name.ends_with("printf"))
return false; // neither printf nor scanf
return Name.starts_with("v");
}
// Matches a call to one of the `sprintf` functions as they are always unsafe
// and should be changed to `snprintf`.
static bool isUnsafeSprintfFunc(const FunctionDecl &Node) {
auto *II = Node.getIdentifier();
if (!II)
return false;
StringRef Name = LibcFunNamePrefixSuffixParser().matchName(
II->getName(), Node.getBuiltinID());
if (!Name.ends_with("printf") ||
// Let `isUnsafeVaListPrintfFunc` check for cases with va-list:
Name.starts_with("v"))
return false;
StringRef Prefix = Name.drop_back(6);
if (Prefix.ends_with("w"))
Prefix = Prefix.drop_back(1);
return Prefix == "s";
}