1 //== ValistChecker.cpp - stdarg.h macro usage checker -----------*- C++ -*--==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This defines checkers which detect usage of uninitialized va_list values 11 // and va_start calls with no matching va_end. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ClangSACheckers.h" 16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 17 #include "clang/StaticAnalyzer/Core/Checker.h" 18 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 19 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 21 22 using namespace clang; 23 using namespace ento; 24 25 REGISTER_SET_WITH_PROGRAMSTATE(InitializedVALists, const MemRegion *) 26 27 namespace { 28 typedef SmallVector<const MemRegion *, 2> RegionVector; 29 30 class ValistChecker : public Checker<check::PreCall, check::PreStmt<VAArgExpr>, 31 check::DeadSymbols> { 32 mutable std::unique_ptr<BugType> BT_leakedvalist, BT_uninitaccess; 33 34 struct VAListAccepter { 35 CallDescription Func; 36 int VAListPos; 37 }; 38 static const SmallVector<VAListAccepter, 15> VAListAccepters; 39 static const CallDescription VaStart, VaEnd, VaCopy; 40 41 public: 42 enum CheckKind { 43 CK_Uninitialized, 44 CK_Unterminated, 45 CK_CopyToSelf, 46 CK_NumCheckKinds 47 }; 48 49 DefaultBool ChecksEnabled[CK_NumCheckKinds]; 50 CheckName CheckNames[CK_NumCheckKinds]; 51 52 void checkPreStmt(const VAArgExpr *VAA, CheckerContext &C) const; 53 void checkPreCall(const CallEvent &Call, CheckerContext &C) const; 54 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; 55 56 private: 57 const MemRegion *getVAListAsRegion(SVal SV, const Expr *VAExpr, 58 bool &IsSymbolic, CheckerContext &C) const; 59 StringRef getVariableNameFromRegion(const MemRegion *Reg) const; 60 const ExplodedNode *getStartCallSite(const ExplodedNode *N, 61 const MemRegion *Reg) const; 62 63 void reportUninitializedAccess(const MemRegion *VAList, StringRef Msg, 64 CheckerContext &C) const; 65 void reportLeakedVALists(const RegionVector &LeakedVALists, StringRef Msg1, 66 StringRef Msg2, CheckerContext &C, ExplodedNode *N, 67 bool ForceReport = false) const; 68 69 void checkVAListStartCall(const CallEvent &Call, CheckerContext &C, 70 bool IsCopy) const; 71 void checkVAListEndCall(const CallEvent &Call, CheckerContext &C) const; 72 73 class ValistBugVisitor : public BugReporterVisitorImpl<ValistBugVisitor> { 74 public: 75 ValistBugVisitor(const MemRegion *Reg, bool IsLeak = false) 76 : Reg(Reg), IsLeak(IsLeak) {} 77 void Profile(llvm::FoldingSetNodeID &ID) const override { 78 static int X = 0; 79 ID.AddPointer(&X); 80 ID.AddPointer(Reg); 81 } 82 std::unique_ptr<PathDiagnosticPiece> 83 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode, 84 BugReport &BR) override { 85 if (!IsLeak) 86 return nullptr; 87 88 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath( 89 EndPathNode, BRC.getSourceManager()); 90 // Do not add the statement itself as a range in case of leak. 91 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(), 92 false); 93 } 94 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N, 95 const ExplodedNode *PrevN, 96 BugReporterContext &BRC, 97 BugReport &BR) override; 98 99 private: 100 const MemRegion *Reg; 101 bool IsLeak; 102 }; 103 }; 104 105 const SmallVector<ValistChecker::VAListAccepter, 15> 106 ValistChecker::VAListAccepters = { 107 {{"vfprintf", 3}, 2}, 108 {{"vfscanf", 3}, 2}, 109 {{"vprintf", 2}, 1}, 110 {{"vscanf", 2}, 1}, 111 {{"vsnprintf", 4}, 3}, 112 {{"vsprintf", 3}, 2}, 113 {{"vsscanf", 3}, 2}, 114 {{"vfwprintf", 3}, 2}, 115 {{"vfwscanf", 3}, 2}, 116 {{"vwprintf", 2}, 1}, 117 {{"vwscanf", 2}, 1}, 118 {{"vswprintf", 4}, 3}, 119 // vswprintf is the wide version of vsnprintf, 120 // vsprintf has no wide version 121 {{"vswscanf", 3}, 2}}; 122 const CallDescription ValistChecker::VaStart("__builtin_va_start", 2), 123 ValistChecker::VaCopy("__builtin_va_copy", 2), 124 ValistChecker::VaEnd("__builtin_va_end", 1); 125 } // end anonymous namespace 126 127 void ValistChecker::checkPreCall(const CallEvent &Call, 128 CheckerContext &C) const { 129 if (!Call.isGlobalCFunction()) 130 return; 131 if (Call.isCalled(VaStart)) 132 checkVAListStartCall(Call, C, false); 133 else if (Call.isCalled(VaCopy)) 134 checkVAListStartCall(Call, C, true); 135 else if (Call.isCalled(VaEnd)) 136 checkVAListEndCall(Call, C); 137 else { 138 for (auto FuncInfo : VAListAccepters) { 139 if (!Call.isCalled(FuncInfo.Func)) 140 continue; 141 bool Symbolic; 142 const MemRegion *VAList = 143 getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos), 144 Call.getArgExpr(FuncInfo.VAListPos), Symbolic, C); 145 if (!VAList) 146 return; 147 148 if (C.getState()->contains<InitializedVALists>(VAList)) 149 return; 150 151 // We did not see va_start call, but the source of the region is unknown. 152 // Be conservative and assume the best. 153 if (Symbolic) 154 return; 155 156 SmallString<80> Errmsg("Function '"); 157 Errmsg += FuncInfo.Func.getFunctionName(); 158 Errmsg += "' is called with an uninitialized va_list argument"; 159 reportUninitializedAccess(VAList, Errmsg.c_str(), C); 160 break; 161 } 162 } 163 } 164 165 const MemRegion *ValistChecker::getVAListAsRegion(SVal SV, const Expr *E, 166 bool &IsSymbolic, 167 CheckerContext &C) const { 168 const MemRegion *Reg = SV.getAsRegion(); 169 if (!Reg) 170 return nullptr; 171 // TODO: In the future this should be abstracted away by the analyzer. 172 bool VaListModelledAsArray = false; 173 if (const auto *Cast = dyn_cast<CastExpr>(E)) { 174 QualType Ty = Cast->getType(); 175 VaListModelledAsArray = 176 Ty->isPointerType() && Ty->getPointeeType()->isRecordType(); 177 } 178 if (const auto *DeclReg = Reg->getAs<DeclRegion>()) { 179 if (isa<ParmVarDecl>(DeclReg->getDecl())) 180 Reg = C.getState()->getSVal(SV.castAs<Loc>()).getAsRegion(); 181 } 182 IsSymbolic = Reg && Reg->getAs<SymbolicRegion>(); 183 // Some VarRegion based VA lists reach here as ElementRegions. 184 const auto *EReg = dyn_cast_or_null<ElementRegion>(Reg); 185 return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg; 186 } 187 188 void ValistChecker::checkPreStmt(const VAArgExpr *VAA, 189 CheckerContext &C) const { 190 ProgramStateRef State = C.getState(); 191 const Expr *VASubExpr = VAA->getSubExpr(); 192 SVal VAListSVal = State->getSVal(VASubExpr, C.getLocationContext()); 193 bool Symbolic; 194 const MemRegion *VAList = 195 getVAListAsRegion(VAListSVal, VASubExpr, Symbolic, C); 196 if (!VAList) 197 return; 198 if (Symbolic) 199 return; 200 if (!State->contains<InitializedVALists>(VAList)) 201 reportUninitializedAccess( 202 VAList, "va_arg() is called on an uninitialized va_list", C); 203 } 204 205 void ValistChecker::checkDeadSymbols(SymbolReaper &SR, 206 CheckerContext &C) const { 207 ProgramStateRef State = C.getState(); 208 InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>(); 209 RegionVector LeakedVALists; 210 for (auto Reg : TrackedVALists) { 211 if (SR.isLiveRegion(Reg)) 212 continue; 213 LeakedVALists.push_back(Reg); 214 State = State->remove<InitializedVALists>(Reg); 215 } 216 if (ExplodedNode *N = C.addTransition(State)) 217 reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C, 218 N); 219 } 220 221 // This function traverses the exploded graph backwards and finds the node where 222 // the va_list is initialized. That node is used for uniquing the bug paths. 223 // It is not likely that there are several different va_lists that belongs to 224 // different stack frames, so that case is not yet handled. 225 const ExplodedNode * 226 ValistChecker::getStartCallSite(const ExplodedNode *N, 227 const MemRegion *Reg) const { 228 const LocationContext *LeakContext = N->getLocationContext(); 229 const ExplodedNode *StartCallNode = N; 230 231 bool FoundInitializedState = false; 232 233 while (N) { 234 ProgramStateRef State = N->getState(); 235 if (!State->contains<InitializedVALists>(Reg)) { 236 if (FoundInitializedState) 237 break; 238 } else { 239 FoundInitializedState = true; 240 } 241 const LocationContext *NContext = N->getLocationContext(); 242 if (NContext == LeakContext || NContext->isParentOf(LeakContext)) 243 StartCallNode = N; 244 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 245 } 246 247 return StartCallNode; 248 } 249 250 void ValistChecker::reportUninitializedAccess(const MemRegion *VAList, 251 StringRef Msg, 252 CheckerContext &C) const { 253 if (!ChecksEnabled[CK_Uninitialized]) 254 return; 255 if (ExplodedNode *N = C.generateErrorNode()) { 256 if (!BT_uninitaccess) 257 BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized], 258 "Uninitialized va_list", 259 categories::MemoryError)); 260 auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N); 261 R->markInteresting(VAList); 262 R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList)); 263 C.emitReport(std::move(R)); 264 } 265 } 266 267 void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists, 268 StringRef Msg1, StringRef Msg2, 269 CheckerContext &C, ExplodedNode *N, 270 bool ForceReport) const { 271 if (!(ChecksEnabled[CK_Unterminated] || 272 (ChecksEnabled[CK_Uninitialized] && ForceReport))) 273 return; 274 for (auto Reg : LeakedVALists) { 275 if (!BT_leakedvalist) { 276 BT_leakedvalist.reset(new BugType(CheckNames[CK_Unterminated], 277 "Leaked va_list", 278 categories::MemoryError)); 279 BT_leakedvalist->setSuppressOnSink(true); 280 } 281 282 const ExplodedNode *StartNode = getStartCallSite(N, Reg); 283 PathDiagnosticLocation LocUsedForUniqueing; 284 285 if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode)) 286 LocUsedForUniqueing = PathDiagnosticLocation::createBegin( 287 StartCallStmt, C.getSourceManager(), StartNode->getLocationContext()); 288 289 SmallString<100> Buf; 290 llvm::raw_svector_ostream OS(Buf); 291 OS << Msg1; 292 std::string VariableName = Reg->getDescriptiveName(); 293 if (!VariableName.empty()) 294 OS << " " << VariableName; 295 OS << Msg2; 296 297 auto R = llvm::make_unique<BugReport>( 298 *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing, 299 StartNode->getLocationContext()->getDecl()); 300 R->markInteresting(Reg); 301 R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true)); 302 C.emitReport(std::move(R)); 303 } 304 } 305 306 void ValistChecker::checkVAListStartCall(const CallEvent &Call, 307 CheckerContext &C, bool IsCopy) const { 308 bool Symbolic; 309 const MemRegion *VAList = 310 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C); 311 if (!VAList) 312 return; 313 314 ProgramStateRef State = C.getState(); 315 316 if (IsCopy) { 317 const MemRegion *Arg2 = 318 getVAListAsRegion(Call.getArgSVal(1), Call.getArgExpr(1), Symbolic, C); 319 if (Arg2) { 320 if (ChecksEnabled[CK_CopyToSelf] && VAList == Arg2) { 321 RegionVector LeakedVALists{VAList}; 322 if (ExplodedNode *N = C.addTransition(State)) 323 reportLeakedVALists(LeakedVALists, "va_list", 324 " is copied onto itself", C, N, true); 325 return; 326 } else if (!State->contains<InitializedVALists>(Arg2) && !Symbolic) { 327 if (State->contains<InitializedVALists>(VAList)) { 328 State = State->remove<InitializedVALists>(VAList); 329 RegionVector LeakedVALists{VAList}; 330 if (ExplodedNode *N = C.addTransition(State)) 331 reportLeakedVALists(LeakedVALists, "Initialized va_list", 332 " is overwritten by an uninitialized one", C, N, 333 true); 334 } else { 335 reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C); 336 } 337 return; 338 } 339 } 340 } 341 if (State->contains<InitializedVALists>(VAList)) { 342 RegionVector LeakedVALists{VAList}; 343 if (ExplodedNode *N = C.addTransition(State)) 344 reportLeakedVALists(LeakedVALists, "Initialized va_list", 345 " is initialized again", C, N); 346 return; 347 } 348 349 State = State->add<InitializedVALists>(VAList); 350 C.addTransition(State); 351 } 352 353 void ValistChecker::checkVAListEndCall(const CallEvent &Call, 354 CheckerContext &C) const { 355 bool Symbolic; 356 const MemRegion *VAList = 357 getVAListAsRegion(Call.getArgSVal(0), Call.getArgExpr(0), Symbolic, C); 358 if (!VAList) 359 return; 360 361 // We did not see va_start call, but the source of the region is unknown. 362 // Be conservative and assume the best. 363 if (Symbolic) 364 return; 365 366 if (!C.getState()->contains<InitializedVALists>(VAList)) { 367 reportUninitializedAccess( 368 VAList, "va_end() is called on an uninitialized va_list", C); 369 return; 370 } 371 ProgramStateRef State = C.getState(); 372 State = State->remove<InitializedVALists>(VAList); 373 C.addTransition(State); 374 } 375 376 std::shared_ptr<PathDiagnosticPiece> ValistChecker::ValistBugVisitor::VisitNode( 377 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, 378 BugReport &BR) { 379 ProgramStateRef State = N->getState(); 380 ProgramStateRef StatePrev = PrevN->getState(); 381 382 const Stmt *S = PathDiagnosticLocation::getStmt(N); 383 if (!S) 384 return nullptr; 385 386 StringRef Msg; 387 if (State->contains<InitializedVALists>(Reg) && 388 !StatePrev->contains<InitializedVALists>(Reg)) 389 Msg = "Initialized va_list"; 390 else if (!State->contains<InitializedVALists>(Reg) && 391 StatePrev->contains<InitializedVALists>(Reg)) 392 Msg = "Ended va_list"; 393 394 if (Msg.empty()) 395 return nullptr; 396 397 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 398 N->getLocationContext()); 399 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true); 400 } 401 402 #define REGISTER_CHECKER(name) \ 403 void ento::register##name##Checker(CheckerManager &mgr) { \ 404 ValistChecker *checker = mgr.registerChecker<ValistChecker>(); \ 405 checker->ChecksEnabled[ValistChecker::CK_##name] = true; \ 406 checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \ 407 } 408 409 REGISTER_CHECKER(Uninitialized) 410 REGISTER_CHECKER(Unterminated) 411 REGISTER_CHECKER(CopyToSelf) 412