-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cpp
760 lines (673 loc) · 26.7 KB
/
Utils.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
//=--Utils.cpp----------------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
// Implementation of Utils methods.
//===----------------------------------------------------------------------===//
#include "clang/CheckMate/Utils.h"
#include "clang/CheckMate/CheckMateGlobalOptions.h"
#include "clang/AST/FormatString.h"
#include "clang/Sema/Sema.h"
#include "llvm/Support/Path.h"
#include <errno.h>
//#include <clang/3C/ConstraintResolver.h>
using namespace llvm;
using namespace clang;
const clang::Type *getNextTy(const clang::Type *Ty) {
if (Ty->isPointerType()) {
// TODO: how to keep the qualifiers around, and what qualifiers do
// we want to keep?
QualType Qtmp = Ty->getLocallyUnqualifiedSingleStepDesugaredType();
return Qtmp.getTypePtr()->getPointeeType().getTypePtr();
}
return Ty;
}
// Walk the list of declarations and find a declaration that is NOT
// a definition and does NOT have a body.
FunctionDecl *getDeclaration(FunctionDecl *FD) {
// optimization
if (!FD->isThisDeclarationADefinition()) {
return FD;
}
for (const auto &D : FD->redecls())
if (FunctionDecl *TFD = dyn_cast<FunctionDecl>(D))
if (!TFD->isThisDeclarationADefinition())
return TFD;
return nullptr;
}
// Walk the list of declarations and find a declaration accompanied by
// a definition and a function body.
FunctionDecl *getDefinition(FunctionDecl *FD) {
// optimization
if (FD->isThisDeclarationADefinition() && FD->hasBody()) {
return FD;
}
for (const auto &D : FD->redecls())
if (FunctionDecl *TFD = dyn_cast<FunctionDecl>(D))
if (TFD->isThisDeclarationADefinition() && TFD->hasBody())
return TFD;
return nullptr;
}
// Walk the list of declarations and find a declaration that is NOT
// a definition and does NOT have a body.
FunctionDecl *getTaintedDeclaration(FunctionDecl *FD) {
// optimization
if (!FD->isThisDeclarationADefinition()) {
return FD;
}
for (const auto &D : FD->redecls())
if (FunctionDecl *TFD = dyn_cast<FunctionDecl>(D))
if ((!TFD->isThisDeclarationADefinition()) && (TFD->isTainted()))
return TFD;
return nullptr;
}
// Walk the list of declarations and find a declaration accompanied by
// a definition and a function body.
FunctionDecl *getTaintedDefinition(FunctionDecl *FD) {
// optimization
if ((FD->isThisDeclarationADefinition() && FD->hasBody()) &&
(FD->isTainted())){
return FD;
}
for (const auto &D : FD->redecls())
if (FunctionDecl *TFD = dyn_cast<FunctionDecl>(D))
if ((TFD->isThisDeclarationADefinition() && TFD->hasBody()) && (TFD->isTainted()))
return TFD;
return nullptr;
}
//This should only be used as a fall back for when the clang library function
// FunctionTypeLoc::getRParenLoc cannot be called due to a null FunctionTypeLoc
// or for when the function returns an invalid source location.
SourceLocation getFunctionDeclRParen(FunctionDecl *FD, SourceManager &S) {
const FunctionDecl *OFd = nullptr;
if (FD->hasBody(OFd) && OFd == FD) {
// Replace everything up to the beginning of the body.
const Stmt *Body = FD->getBody(OFd);
return locationPrecedingChar(Body->getBeginLoc(), S, ')');
}
return FD->getSourceRange().getEnd();
}
// Find the source location of the first character C preceding the given source
// location. Because this uses the character buffer directly, it sees character
// data prior to preprocessing. This means characters that are in comments,
// macros or otherwise not part of the final preprocessed source code are seen
// and can cause this function to give an incorrect result. This should only be
// used as a fall back for when clang library function for obtaining source
// locations are not available or return invalid results.
SourceLocation locationPrecedingChar(SourceLocation SL, SourceManager &S,
char C) {
int Offset = 0;
const char *Buf = S.getCharacterData(SL);
while (*Buf != C) {
Buf--;
Offset--;
}
return SL.getLocWithOffset(Offset);
}
clang::CheckCBox_PointerKind getCheckCBox_PointerKind(InteropTypeExpr *ItypeExpr) {
TypeSourceInfo *InteropTypeInfo = ItypeExpr->getTypeInfoAsWritten();
const clang::Type *InnerType = InteropTypeInfo->getType().getTypePtr();
if (InnerType->isCheckedPointerNtArrayType()) {
return CheckCBox_PointerKind::NtArray;
}
if (InnerType->isCheckedPointerArrayType()) {
return CheckCBox_PointerKind::Array;
}
if (InnerType->isCheckedPointerType()) {
return CheckCBox_PointerKind::Ptr;
}
if(InnerType->isTaintedPointerNtArrayType()){
return CheckCBox_PointerKind::t_nt_array;
}
if(InnerType->isTaintedArrayType()){
return CheckCBox_PointerKind::t_array;
}
if(InnerType->isTaintedPointerNtArrayType()){
return CheckCBox_PointerKind::t_nt_array;
}
if(InnerType->isTaintedPointerPtrType()){
return CheckCBox_PointerKind::t_ptr;
}
return CheckCBox_PointerKind::Unchecked;
}
static std::string storageClassToString(StorageClass SC) {
switch (SC) {
case StorageClass::SC_Static:
return "static ";
case StorageClass::SC_Extern:
return "extern ";
case StorageClass::SC_Register:
return "register ";
// For all other cases, we do not care.
default:
return "";
}
}
// This method gets the storage qualifier for the
// provided declaration including any trailing space, i.e., "static ",
// "extern ", etc., or "" if none.
std::string getStorageQualifierString(Decl *D) {
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
return storageClassToString(FD->getStorageClass());
}
if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
return storageClassToString(VD->getStorageClass());
}
if (isa<TypedefDecl>(D)) {
// `typedef` goes in the same syntactic position as a storage qualifier and
// needs to be inserted when breaking up a multi-decl, just like a real
// storage qualifier.
return "typedef ";
}
return "";
}
bool isNULLExpression(clang::Expr *E, ASTContext &C) {
QualType Typ = E->getType();
E = removeAuxillaryCasts(E);
return Typ->isPointerType() && E->isIntegerConstantExpr(C) &&
E->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNotNull);
}
std::error_code tryGetCanonicalFilePath(const std::string &FileName,
std::string &AbsoluteFp) {
SmallString<255> AbsPath;
std::error_code EC;
if (FileName.empty()) {
// Strangely, llvm::sys::fs::real_path successfully returns the empty string
// in this case. Return ENOENT, as realpath(3) would.
EC = std::error_code(ENOENT, std::generic_category());
} else {
EC = llvm::sys::fs::real_path(FileName, AbsPath);
}
if (EC) {
return EC;
}
AbsoluteFp = std::string(AbsPath.str());
return EC;
}
bool filePathStartsWith(const std::string &Path, const std::string &Prefix) {
// If the path exactly equals the prefix, don't ruin it by appending a
// separator to the prefix. (This may never happen in 3C, but let's get it
// right.)
if (Prefix.empty() || Path == Prefix) {
return true;
}
StringRef Separator = llvm::sys::path::get_separator();
std::string PrefixWithTrailingSeparator = Prefix;
if (!StringRef(Prefix).endswith(Separator)) {
PrefixWithTrailingSeparator += Separator;
}
return Path.substr(0, PrefixWithTrailingSeparator.size()) ==
PrefixWithTrailingSeparator;
}
bool functionHasVarArgs(clang::FunctionDecl *FD) {
if (FD && FD->getFunctionType()->isFunctionProtoType()) {
const FunctionProtoType *SrcType =
FD->getFunctionType()->getAs<FunctionProtoType>();
return SrcType->isVariadic();
}
return false;
}
bool isFunctionAllocator(std::string FuncName) {
return std::find(_CheckMateOpts.AllocatorFunctions.begin(),
_CheckMateOpts.AllocatorFunctions.end(),
FuncName) != _CheckMateOpts.AllocatorFunctions.end() ||
llvm::StringSwitch<bool>(FuncName)
.Cases("malloc", "calloc", "realloc", true)
.Default(false);
}
bool isFunctionTaintedAllocator(std::string FuncName){
return std::find(_CheckMateOpts.AllocatorFunctions.begin(),
_CheckMateOpts.AllocatorFunctions.end(),
FuncName) != _CheckMateOpts.AllocatorFunctions.end() ||
llvm::StringSwitch<bool>(FuncName)
.Cases("t_malloc", "t_calloc", "t_realloc", true)
.Default(false);
}
float getTimeSpentInSeconds(clock_t StartTime) {
return float(clock() - StartTime) / CLOCKS_PER_SEC;
}
bool isPointerType(clang::ValueDecl *VD) {
return VD->getType().getTypePtr()->isPointerType();
}
bool isPtrOrArrayType(const clang::QualType &QT) {
return QT->isPointerType() || QT->isArrayType();
}
bool isArrayType(const QualType &QT) {
// This is an array type. Just return true.
if (QT->isArrayType())
return true;
// It might instead be an array which has decayed to a pointer. We still want
// to treat this as an array.
const DecayedType *T = QT->getAs<DecayedType>();
if (T && T->getOriginalType()->isArrayType())
return true;
return false;
}
bool isNullableType(const clang::QualType &QT) {
if (QT.getTypePtrOrNull())
return QT->isPointerType() || QT->isArrayType() || QT->isIntegerType();
return false;
}
bool canBeNtArray(const clang::QualType &QT) {
// First get the canonical type so that the following checks will not have to
// account for ParenType, DecayedType, or other variants used by clang.
QualType Canon = QT.getCanonicalType();
if (const auto &Ptr = dyn_cast<clang::PointerType>(Canon))
return isNullableType(Ptr->getPointeeType());
if (const auto &Arr = dyn_cast<clang::ArrayType>(Canon))
return isNullableType(Arr->getElementType());
return false;
}
bool isStructOrUnionType(clang::DeclaratorDecl *DD) {
return DD->getType().getTypePtr()->isStructureType() ||
DD->getType().getTypePtr()->isUnionType();
}
bool isTaintedStruct(clang::DeclaratorDecl *DD) {
return DD->getType()->isTaintedStructureType();
}
std::string qtyToStr(clang::QualType QT, const std::string &Name) {
std::string S = Name;
QT.getAsStringInternal(S, LangOptions());
return S;
}
std::string tyToStr(const clang::Type *T, const std::string &Name) {
return qtyToStr(QualType(T, 0), Name);
}
Expr *removeAuxillaryCasts(Expr *E) {
bool NeedStrip = true;
while (NeedStrip) {
NeedStrip = false;
E = E->IgnoreParenImpCasts();
if (CStyleCastExpr *C = dyn_cast<CStyleCastExpr>(E)) {
E = C->getSubExpr();
NeedStrip = true;
}
}
return E;
}
//Expr *getNormalizedExpr(Expr *CE) {
// while (true) {
// if (CHKCBindTemporaryExpr *E = dyn_cast<CHKCBindTemporaryExpr>(CE)) {
// CE = E->getSubExpr();
// continue;
// }
// if (ParenExpr *E = dyn_cast <ParenExpr>(CE)) {
// CE = E->getSubExpr();
// continue;
// }
// break;
// }
// return CE;
//}
bool isTypeHasVoid(clang::QualType QT) {
const clang::Type *CurrType = QT.getTypePtrOrNull();
if (CurrType != nullptr) {
if (CurrType->isVoidType())
return true;
const clang::Type *InnerType = getNextTy(CurrType);
while (InnerType != CurrType) {
CurrType = InnerType;
InnerType = getNextTy(InnerType);
}
return InnerType->isVoidType();
}
return false;
}
bool isVarArgType(const std::string &TypeName) {
return TypeName == "struct __va_list_tag *" || TypeName == "va_list" ||
TypeName == "struct __va_list_tag";
}
bool hasVoidType(clang::ValueDecl *D) { return isTypeHasVoid(D->getType()); }
//// Check the equality of VTy and UTy. There are some specific rules that
//// fire, and a general check is yet to be implemented.
//bool checkStructuralEquality(std::set<ConstraintVariable *> V,
// std::set<ConstraintVariable *> U,
// QualType VTy,
// QualType UTy)
//{
// // First specific rule: Are these types directly equal?
// if (VTy == UTy) {
// return true;
// } else {
// // Further structural checking is TODO.
// return false;
// }
//}
//
//bool checkStructuralEquality(QualType D, QualType S) {
// if (D == S)
// return true;
//
// return D->isPointerType() == S->isPointerType();
//}
static bool castCheck(clang::QualType DstType, clang::QualType SrcType) {
// Check if both types are same.
if (SrcType == DstType)
return true;
const clang::Type *SrcTypePtr = SrcType.getCanonicalType().getTypePtr();
const clang::Type *DstTypePtr = DstType.getCanonicalType().getTypePtr();
const clang::PointerType *SrcPtrTypePtr =
dyn_cast<clang::PointerType>(SrcTypePtr);
const clang::PointerType *DstPtrTypePtr =
dyn_cast<clang::PointerType>(DstTypePtr);
// Both are pointers? check their pointee
if (SrcPtrTypePtr && DstPtrTypePtr) {
return castCheck(DstPtrTypePtr->getPointeeType(),
SrcPtrTypePtr->getPointeeType());
}
if (SrcPtrTypePtr || DstPtrTypePtr)
return false;
// Check function cast by comparing parameter and return types individually.
const auto *SrcFnType = dyn_cast<clang::FunctionProtoType>(SrcTypePtr);
const auto *DstFnType = dyn_cast<clang::FunctionProtoType>(DstTypePtr);
if (SrcFnType && DstFnType) {
if (SrcFnType->getNumParams() != DstFnType->getNumParams())
return false;
for (unsigned I = 0; I < SrcFnType->getNumParams(); I++)
if (!castCheck(SrcFnType->getParamType(I),
DstFnType->getParamType(I)))
return false;
return castCheck(SrcFnType->getReturnType(), DstFnType->getReturnType());
}
// If both are not scalar types? Then the types must be exactly same.
if (!(SrcTypePtr->isScalarType() && DstTypePtr->isScalarType()))
return SrcTypePtr == DstTypePtr;
// Check if both types are compatible.
bool BothNotChar = SrcTypePtr->isCharType() ^ DstTypePtr->isCharType();
bool BothNotInt =
(SrcTypePtr->isIntegerType() && SrcTypePtr->isUnsignedIntegerType()) ^
(DstTypePtr->isIntegerType() && DstTypePtr->isUnsignedIntegerType());
bool BothNotFloat =
SrcTypePtr->isFloatingType() ^ DstTypePtr->isFloatingType();
return !(BothNotChar || BothNotInt || BothNotFloat);
}
bool isCastSafe(clang::QualType DstType, clang::QualType SrcType) {
const clang::Type *DstTypePtr = DstType.getTypePtr();
const clang::PointerType *DstPtrTypePtr =
dyn_cast<clang::PointerType>(DstTypePtr);
if (!DstPtrTypePtr) // Safe to cast to a non-pointer.
return true;
return castCheck(DstType, SrcType);
}
bool canWrite(const std::string &FilePath) {
// Was this file explicitly provided on the command line?
if (FilePaths.count(FilePath) > 0)
return true;
// Get the absolute path of the file and check that
// the file path starts with the base directory.
return filePathStartsWith(FilePath, _CheckMateOpts.BaseDir);
}
bool isInSysHeader(clang::Decl *D) {
if (D != nullptr) {
auto &C = D->getASTContext();
FullSourceLoc FL = C.getFullLoc(D->getBeginLoc());
return FL.isInSystemHeader();
}
return false;
}
std::string getSourceText(const clang::SourceRange &SR,
const clang::ASTContext &C) {
return getSourceText(CharSourceRange::getTokenRange(SR), C);
}
std::string getSourceText(const clang::CharSourceRange &SR,
const clang::ASTContext &C) {
assert(SR.isValid() && "Invalid Source Range requested.");
auto &SM = C.getSourceManager();
auto LO = C.getLangOpts();
llvm::StringRef Srctxt = Lexer::getSourceText(SR, SM, LO);
return Srctxt.str();
}
unsigned longestCommonSubsequence(const char *Str1, const char *Str2,
unsigned long Str1Len,
unsigned long Str2Len) {
if (Str1Len == 0 || Str2Len == 0)
return 0;
if (Str1[Str1Len - 1] == Str2[Str2Len - 1])
return 1 + longestCommonSubsequence(Str1, Str2, Str1Len - 1, Str2Len - 1);
return std::max(longestCommonSubsequence(Str1, Str2, Str1Len, Str2Len - 1),
longestCommonSubsequence(Str1, Str2, Str1Len - 1, Str2Len));
}
bool isTypeAnonymous(const clang::Type *T) {
return T->isRecordType() &&
!(T->getAsRecordDecl()->getIdentifier() ||
T->getAsRecordDecl()->getTypedefNameForAnonDecl());
}
unsigned int getParameterIndex(ParmVarDecl *PV, FunctionDecl *FD) {
// This is kind of hacky, maybe we should record the index of the
// parameter when we find it, instead of re-discovering it here.
unsigned int PIdx = 0;
for (const auto &I : FD->parameters()) {
if (I == PV)
return PIdx;
PIdx++;
}
llvm_unreachable("Parameter declaration not found in function declaration.");
}
bool evaluateToInt(Expr *E, const ASTContext &C, int &Result) {
Expr::EvalResult ER;
E->EvaluateAsInt(ER, C, clang::Expr::SE_NoSideEffects, false);
if (ER.Val.isInt()) {
Result = ER.Val.getInt().getExtValue();
return true;
}
return false;
}
bool isZeroBoundsExpr(BoundsExpr *BE, const ASTContext &C) {
if (auto *CBE = dyn_cast<CountBoundsExpr>(BE)) {
// count(0) and byte_count(0)
Expr *E = CBE->getCountExpr();
int Result;
if (evaluateToInt(E, C, Result))
return Result == 0;
}
// Range bounds and empty bounds are ignored. I suppose range bounds could be
// size zero bounds, but checking this would be considerably more complicated
// and it seems unlikely to show up in real code.
return false;
}
TypeLoc getBaseTypeLoc(TypeLoc T) {
assert(!T.isNull() && "Can't get base location from Null.");
while (!T.getNextTypeLoc().isNull() &&
(!T.getAs<ParenTypeLoc>().isNull() ||
T.getTypePtr()->isPointerType() || T.getTypePtr()->isArrayType()))
T = T.getNextTypeLoc();
return T;
}
Expr *ignoreCheckedCImplicit(Expr *E) {
Expr *Old = nullptr;
Expr *New = E;
while (Old != New) {
Old = New;
New = Old->IgnoreExprTmp()->IgnoreImplicit();
}
return New;
}
FunctionTypeLoc getFunctionTypeLoc(TypeLoc TLoc) {
TLoc = getBaseTypeLoc(TLoc);
auto ATLoc = TLoc.getAs<AttributedTypeLoc>();
if (!ATLoc.isNull())
TLoc = ATLoc.getNextTypeLoc();
return TLoc.getAs<FunctionTypeLoc>();
}
FunctionTypeLoc getFunctionTypeLoc(DeclaratorDecl *Decl) {
if (auto *TSInfo = Decl->getTypeSourceInfo())
return getFunctionTypeLoc(TSInfo->getTypeLoc());
return FunctionTypeLoc();
}
bool isKAndRFunctionDecl(FunctionDecl *FD) {
return !FD->hasPrototype() && FD->getNumParams();
}
namespace {
// See clang/docs/checkedc/3C/clang-tidy.md#_3c-name-prefix
// NOLINTNEXTLINE(readability-identifier-naming)
class _CheckMateFormatStringHandler
: public analyze_format_string::FormatStringHandler {
unsigned DataStartIdx;
std::set<unsigned> &StringArgIndices;
public:
_CheckMateFormatStringHandler(unsigned DataStartIdx,
std::set<unsigned> &StringArgIndices)
: DataStartIdx(DataStartIdx), StringArgIndices(StringArgIndices) {}
bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
const char *StartSpecifier,
unsigned SpecifierLen) override {
if (FS.consumesDataArgument() &&
FS.getConversionSpecifier().getKind() ==
analyze_printf::PrintfConversionSpecifier::sArg)
StringArgIndices.insert(DataStartIdx + FS.getArgIndex());
return true;
}
};
} // namespace
// Unfortunately, this duplicates some logic from different parts of
// SemaChecking.cpp. We handle only the common case. If we get this wrong, it's
// not a big deal: CheckMate may just infer some checked pointer types incorrectly.
void getPrintfStringArgIndices(const CallExpr *CE, const FunctionDecl *Callee,
const clang::ASTContext &Context,
std::set<unsigned> &StringArgIndices) {
for (const FormatAttr *Attr : Callee->specific_attrs<FormatAttr>()) {
if (Sema::GetFormatStringType(Attr) != Sema::FST_Printf)
continue;
if (Attr->getFirstArg() == 0)
// This means the data arguments are not available to check.
continue;
unsigned FormatIdx = Attr->getFormatIdx() - 1;
unsigned DataStartIdx = Attr->getFirstArg() - 1;
if (FormatIdx >= CE->getNumArgs())
continue;
const Expr *FormatExpr =
CE->getArg(FormatIdx)->IgnoreImpCasts()->IgnoreExprTmp();
const clang::StringLiteral *FormatLiteral =
dyn_cast<clang::StringLiteral>(FormatExpr);
if (!FormatLiteral || FormatLiteral->getCharByteWidth() != 1)
continue;
StringRef Str = FormatLiteral->getString();
_CheckMateFormatStringHandler Handler(DataStartIdx, StringArgIndices);
analyze_format_string::ParsePrintfString(
Handler, Str.data(), Str.data() + Str.size(), Context.getLangOpts(),
Context.getTargetInfo(), false);
}
}
int64_t getStmtIdWorkaround(const Stmt *St, const ASTContext &Context) {
// Stmt::getID uses Context.getAllocator().identifyKnownAlignedObject(St) to
// derive a unique ID for St from its pointer in a way that should be
// reproducible if the exact same source file is loaded in the exact same
// environment, since if AST building is deterministic, the sequence of memory
// allocations should be identical.
// Context.getAllocator().identifyKnownObject(St) generates an ID that is
// normally the offset of the Stmt object within the allocator's memory slabs,
// so it is divisible by alignof(Stmt). identifyKnownAlignedObject wraps
// identifyKnownObject to divide the ID by alignof(Stmt) (after asserting that
// it is divisible), probably in an effort to produce smaller IDs to make some
// data structures more efficient. However, if the Stmt is allocated in a
// custom-size slab because it exceeds the default slab size of 4096, then
// identifyKnownObject returns -1 minus the offset, which is _not_ divisible
// by alignof(Stmt) because of the -1. Unfortunately,
// identifyKnownAlignedObject doesn't account for this rare case, and its
// assertion fails (https://bugs.llvm.org/show_bug.cgi?id=49926).
//
// Since 3C doesn't currently use the ID in a data structure that benefits
// from smaller IDs, we may as well just use identifyKnownObject. If we wanted
// smaller IDs, the solution would probably be to have
// identifyKnownAlignedObject fix the alignment of negative IDs by subtracting
// (alignof(Stmt) - 1) before dividing.
return Context.getAllocator().identifyKnownObject(St);
}
// Get the SourceLocation for the end of any Checked C bounds or interop type
// annotations on a declaration. Returns an invalid source location if no
// Checked C annotations are present.
SourceLocation getCheckedCAnnotationsEnd(const Decl *D) {
SourceManager &SM = D->getASTContext().getSourceManager();
SourceLocation End;
// Update the current end SourceLocation to the new SourceLocation if the new
// location is valid and comes after the current end location.
auto UpdateEnd = [&SM, &End](SourceLocation SL) {
if (SL.isValid() &&
(!End.isValid() || SM.isBeforeInTranslationUnit(End, SL)))
End = SL;
};
if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
if (auto *InteropE = DD->getInteropTypeExpr())
UpdateEnd(InteropE->getEndLoc());
if (auto *BoundsE = DD->getBoundsExpr())
UpdateEnd(BoundsE->getEndLoc());
}
return End;
}
SourceLocation getLocationAfterToken(SourceLocation SL, const SourceManager &SM,
const LangOptions &LO) {
return Lexer::getLocForEndOfToken(SL, 0, SM, LO);
}
SourceRange getDeclSourceRangeWithAnnotations(const clang::Decl *D,
bool IncludeInitializer) {
SourceManager &SM = D->getASTContext().getSourceManager();
SourceRange SR;
const VarDecl *VD;
// Only a VarDecl can have an initializer. VarDecl's implementation of the
// getSourceRange virtual method includes the initializer, but we can manually
// call DeclaratorDecl's implementation, which excludes the initializer.
if (!IncludeInitializer && (VD = dyn_cast<VarDecl>(D)) != nullptr)
SR = VD->DeclaratorDecl::getSourceRange();
else
SR = D->getSourceRange();
if (!SR.isValid())
return SR;
SourceLocation DeclEnd = SR.getEnd();
// Partial workaround for a compiler bug where if D has certain checked
// pointer types such as `_Ptr<int *(void)>` (seen in the partial_checked.c
// regression test), D->getSourceRange() returns only the _Ptr token. (As of
// this writing on 2021-11-18, no bug report has been filed against the
// compiler, but https://github.com/correctcomputation/checkedc-clang/pull/723
// tracks our work on the bug.)
//
// Always extend the range at least through the name (given by
// D->getLocation()). That fixes the `_Ptr<int *(void)> x` case but not cases
// with additional syntax after the name, such as `_Ptr<int *(void)> x[10]`.
SourceLocation DeclLoc = D->getLocation();
if (SM.isBeforeInTranslationUnit(DeclEnd, DeclLoc))
DeclEnd = DeclLoc;
SourceLocation AnnotationsEnd = getCheckedCAnnotationsEnd(D);
if (AnnotationsEnd.isValid() &&
SM.isBeforeInTranslationUnit(DeclEnd, AnnotationsEnd))
DeclEnd = AnnotationsEnd;
SR.setEnd(DeclEnd);
return SR;
}
SourceRange getDeclSourceRangeWithAnnotations(const clang::RecordDecl *D,
bool IncludeInitializer) {
SourceManager &SM = D->getASTContext().getSourceManager();
SourceRange SR;
const VarDecl *VD;
// Only a VarDecl can have an initializer. VarDecl's implementation of the
// getSourceRange virtual method includes the initializer, but we can manually
// call DeclaratorDecl's implementation, which excludes the initializer.
if (!IncludeInitializer && (VD = dyn_cast<VarDecl>(D)) != nullptr)
SR = VD->DeclaratorDecl::getSourceRange();
else
SR = D->getSourceRange();
if (!SR.isValid())
return SR;
SourceLocation DeclEnd = SR.getEnd();
// Partial workaround for a compiler bug where if D has certain checked
// pointer types such as `_Ptr<int *(void)>` (seen in the partial_checked.c
// regression test), D->getSourceRange() returns only the _Ptr token. (As of
// this writing on 2021-11-18, no bug report has been filed against the
// compiler, but https://github.com/correctcomputation/checkedc-clang/pull/723
// tracks our work on the bug.)
//
// Always extend the range at least through the name (given by
// D->getLocation()). That fixes the `_Ptr<int *(void)> x` case but not cases
// with additional syntax after the name, such as `_Ptr<int *(void)> x[10]`.
SourceLocation DeclLoc = D->getLocation();
if (SM.isBeforeInTranslationUnit(DeclEnd, DeclLoc))
DeclEnd = DeclLoc;
SourceLocation AnnotationsEnd = getCheckedCAnnotationsEnd(D);
if (AnnotationsEnd.isValid() &&
SM.isBeforeInTranslationUnit(DeclEnd, AnnotationsEnd))
DeclEnd = AnnotationsEnd;
SR.setEnd(DeclEnd);
return SR;
}