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, CheckerContext &C) const; 58 StringRef getVariableNameFromRegion(const MemRegion *Reg) const; 59 const ExplodedNode *getStartCallSite(const ExplodedNode *N, 60 const MemRegion *Reg, 61 CheckerContext &C) 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 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 const MemRegion *VAList = 142 getVAListAsRegion(Call.getArgSVal(FuncInfo.VAListPos), C); 143 if (!VAList) 144 return; 145 146 if (C.getState()->contains<InitializedVALists>(VAList)) 147 return; 148 149 SmallString<80> Errmsg("Function '"); 150 Errmsg += FuncInfo.Func.getFunctionName(); 151 Errmsg += "' is called with an uninitialized va_list argument"; 152 reportUninitializedAccess(VAList, Errmsg.c_str(), C); 153 break; 154 } 155 } 156 } 157 158 void ValistChecker::checkPreStmt(const VAArgExpr *VAA, 159 CheckerContext &C) const { 160 ProgramStateRef State = C.getState(); 161 SVal VAListSVal = State->getSVal(VAA->getSubExpr(), C.getLocationContext()); 162 const MemRegion *VAList = getVAListAsRegion(VAListSVal, C); 163 if (!VAList) 164 return; 165 if (!State->contains<InitializedVALists>(VAList)) 166 reportUninitializedAccess( 167 VAList, "va_arg() is called on an uninitialized va_list", C); 168 } 169 170 void ValistChecker::checkDeadSymbols(SymbolReaper &SR, 171 CheckerContext &C) const { 172 ProgramStateRef State = C.getState(); 173 InitializedVAListsTy TrackedVALists = State->get<InitializedVALists>(); 174 RegionVector LeakedVALists; 175 for (auto Reg : TrackedVALists) { 176 if (SR.isLiveRegion(Reg)) 177 continue; 178 LeakedVALists.push_back(Reg); 179 State = State->remove<InitializedVALists>(Reg); 180 } 181 if (ExplodedNode *N = C.addTransition(State)) 182 reportLeakedVALists(LeakedVALists, "Initialized va_list", " is leaked", C, 183 N); 184 } 185 186 const MemRegion *ValistChecker::getVAListAsRegion(SVal SV, 187 CheckerContext &C) const { 188 const MemRegion *Reg = SV.getAsRegion(); 189 const auto *TReg = dyn_cast_or_null<TypedValueRegion>(Reg); 190 // Some VarRegion based VLAs reach here as ElementRegions. 191 const auto *EReg = dyn_cast_or_null<ElementRegion>(TReg); 192 return EReg ? EReg->getSuperRegion() : TReg; 193 } 194 195 // This function traverses the exploded graph backwards and finds the node where 196 // the va_list is initialized. That node is used for uniquing the bug paths. 197 // It is not likely that there are several different va_lists that belongs to 198 // different stack frames, so that case is not yet handled. 199 const ExplodedNode *ValistChecker::getStartCallSite(const ExplodedNode *N, 200 const MemRegion *Reg, 201 CheckerContext &C) const { 202 const LocationContext *LeakContext = N->getLocationContext(); 203 const ExplodedNode *StartCallNode = N; 204 205 bool FoundInitializedState = false; 206 207 while (N) { 208 ProgramStateRef State = N->getState(); 209 if (!State->contains<InitializedVALists>(Reg)) { 210 if (FoundInitializedState) 211 break; 212 } else { 213 FoundInitializedState = true; 214 } 215 const LocationContext *NContext = N->getLocationContext(); 216 if (NContext == LeakContext || NContext->isParentOf(LeakContext)) 217 StartCallNode = N; 218 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 219 } 220 221 return StartCallNode; 222 } 223 224 void ValistChecker::reportUninitializedAccess(const MemRegion *VAList, 225 StringRef Msg, 226 CheckerContext &C) const { 227 if (!ChecksEnabled[CK_Uninitialized]) 228 return; 229 if (ExplodedNode *N = C.generateErrorNode()) { 230 if (!BT_uninitaccess) 231 BT_uninitaccess.reset(new BugType(CheckNames[CK_Uninitialized], 232 "Uninitialized va_list", 233 "Memory Error")); 234 auto R = llvm::make_unique<BugReport>(*BT_uninitaccess, Msg, N); 235 R->markInteresting(VAList); 236 R->addVisitor(llvm::make_unique<ValistBugVisitor>(VAList)); 237 C.emitReport(std::move(R)); 238 } 239 } 240 241 void ValistChecker::reportLeakedVALists(const RegionVector &LeakedVALists, 242 StringRef Msg1, StringRef Msg2, 243 CheckerContext &C, ExplodedNode *N, 244 bool ForceReport) const { 245 if (!(ChecksEnabled[CK_Unterminated] || 246 (ChecksEnabled[CK_Uninitialized] && ForceReport))) 247 return; 248 for (auto Reg : LeakedVALists) { 249 if (!BT_leakedvalist) { 250 BT_leakedvalist.reset(new BugType(CheckNames[CK_Unterminated], 251 "Leaked va_list", "Memory Error")); 252 BT_leakedvalist->setSuppressOnSink(true); 253 } 254 255 const ExplodedNode *StartNode = getStartCallSite(N, Reg, C); 256 PathDiagnosticLocation LocUsedForUniqueing; 257 258 if (const Stmt *StartCallStmt = PathDiagnosticLocation::getStmt(StartNode)) 259 LocUsedForUniqueing = PathDiagnosticLocation::createBegin( 260 StartCallStmt, C.getSourceManager(), StartNode->getLocationContext()); 261 262 SmallString<100> Buf; 263 llvm::raw_svector_ostream OS(Buf); 264 OS << Msg1; 265 std::string VariableName = Reg->getDescriptiveName(); 266 if (!VariableName.empty()) 267 OS << " " << VariableName; 268 OS << Msg2; 269 270 auto R = llvm::make_unique<BugReport>( 271 *BT_leakedvalist, OS.str(), N, LocUsedForUniqueing, 272 StartNode->getLocationContext()->getDecl()); 273 R->markInteresting(Reg); 274 R->addVisitor(llvm::make_unique<ValistBugVisitor>(Reg, true)); 275 C.emitReport(std::move(R)); 276 } 277 } 278 279 void ValistChecker::checkVAListStartCall(const CallEvent &Call, 280 CheckerContext &C, bool IsCopy) const { 281 const MemRegion *VAList = getVAListAsRegion(Call.getArgSVal(0), C); 282 ProgramStateRef State = C.getState(); 283 if (!VAList) 284 return; 285 286 if (IsCopy) { 287 const MemRegion *Arg2 = getVAListAsRegion(Call.getArgSVal(1), C); 288 if (Arg2) { 289 if (ChecksEnabled[CK_CopyToSelf] && VAList == Arg2) { 290 RegionVector LeakedVALists{VAList}; 291 if (ExplodedNode *N = C.addTransition(State)) 292 reportLeakedVALists(LeakedVALists, "va_list", 293 " is copied onto itself", C, N, true); 294 return; 295 } else if (!State->contains<InitializedVALists>(Arg2)) { 296 if (State->contains<InitializedVALists>(VAList)) { 297 State = State->remove<InitializedVALists>(VAList); 298 RegionVector LeakedVALists{VAList}; 299 if (ExplodedNode *N = C.addTransition(State)) 300 reportLeakedVALists(LeakedVALists, "Initialized va_list", 301 " is overwritten by an uninitialized one", C, N, 302 true); 303 } else { 304 reportUninitializedAccess(Arg2, "Uninitialized va_list is copied", C); 305 } 306 return; 307 } 308 } 309 } 310 if (State->contains<InitializedVALists>(VAList)) { 311 RegionVector LeakedVALists{VAList}; 312 if (ExplodedNode *N = C.addTransition(State)) 313 reportLeakedVALists(LeakedVALists, "Initialized va_list", 314 " is initialized again", C, N); 315 return; 316 } 317 318 State = State->add<InitializedVALists>(VAList); 319 C.addTransition(State); 320 } 321 322 void ValistChecker::checkVAListEndCall(const CallEvent &Call, 323 CheckerContext &C) const { 324 const MemRegion *VAList = getVAListAsRegion(Call.getArgSVal(0), C); 325 if (!VAList) 326 return; 327 328 if (!C.getState()->contains<InitializedVALists>(VAList)) { 329 reportUninitializedAccess( 330 VAList, "va_end() is called on an uninitialized va_list", C); 331 return; 332 } 333 ProgramStateRef State = C.getState(); 334 State = State->remove<InitializedVALists>(VAList); 335 C.addTransition(State); 336 } 337 338 PathDiagnosticPiece *ValistChecker::ValistBugVisitor::VisitNode( 339 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, 340 BugReport &BR) { 341 ProgramStateRef State = N->getState(); 342 ProgramStateRef StatePrev = PrevN->getState(); 343 344 const Stmt *S = PathDiagnosticLocation::getStmt(N); 345 if (!S) 346 return nullptr; 347 348 StringRef Msg; 349 if (State->contains<InitializedVALists>(Reg) && 350 !StatePrev->contains<InitializedVALists>(Reg)) 351 Msg = "Initialized va_list"; 352 else if (!State->contains<InitializedVALists>(Reg) && 353 StatePrev->contains<InitializedVALists>(Reg)) 354 Msg = "Ended va_list"; 355 356 if (Msg.empty()) 357 return nullptr; 358 359 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 360 N->getLocationContext()); 361 return new PathDiagnosticEventPiece(Pos, Msg, true); 362 } 363 364 #define REGISTER_CHECKER(name) \ 365 void ento::register##name##Checker(CheckerManager &mgr) { \ 366 ValistChecker *checker = mgr.registerChecker<ValistChecker>(); \ 367 checker->ChecksEnabled[ValistChecker::CK_##name] = true; \ 368 checker->CheckNames[ValistChecker::CK_##name] = mgr.getCurrentCheckName(); \ 369 } 370 371 REGISTER_CHECKER(Uninitialized) 372 REGISTER_CHECKER(Unterminated) 373 REGISTER_CHECKER(CopyToSelf) 374