xref: /freebsd-src/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1349cc55cSDimitry Andric //== InvalidPtrChecker.cpp ------------------------------------- -*- C++ -*--=//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This file defines InvalidPtrChecker which finds usages of possibly
10349cc55cSDimitry Andric // invalidated pointer.
11349cc55cSDimitry Andric // CERT SEI Rules ENV31-C and ENV34-C
12349cc55cSDimitry Andric // For more information see:
13349cc55cSDimitry Andric // https://wiki.sei.cmu.edu/confluence/x/8tYxBQ
14349cc55cSDimitry Andric // https://wiki.sei.cmu.edu/confluence/x/5NUxBQ
15349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
16349cc55cSDimitry Andric 
17349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
20349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
22349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24349cc55cSDimitry Andric 
25349cc55cSDimitry Andric using namespace clang;
26349cc55cSDimitry Andric using namespace ento;
27349cc55cSDimitry Andric 
28349cc55cSDimitry Andric namespace {
29349cc55cSDimitry Andric 
30349cc55cSDimitry Andric class InvalidPtrChecker
31349cc55cSDimitry Andric     : public Checker<check::Location, check::BeginFunction, check::PostCall> {
32349cc55cSDimitry Andric private:
33349cc55cSDimitry Andric   BugType BT{this, "Use of invalidated pointer", categories::MemoryError};
34349cc55cSDimitry Andric 
35349cc55cSDimitry Andric   void EnvpInvalidatingCall(const CallEvent &Call, CheckerContext &C) const;
36349cc55cSDimitry Andric 
37349cc55cSDimitry Andric   using HandlerFn = void (InvalidPtrChecker::*)(const CallEvent &Call,
38349cc55cSDimitry Andric                                                 CheckerContext &C) const;
39349cc55cSDimitry Andric 
40349cc55cSDimitry Andric   // SEI CERT ENV31-C
41349cc55cSDimitry Andric   const CallDescriptionMap<HandlerFn> EnvpInvalidatingFunctions = {
42349cc55cSDimitry Andric       {{"setenv", 3}, &InvalidPtrChecker::EnvpInvalidatingCall},
43349cc55cSDimitry Andric       {{"unsetenv", 1}, &InvalidPtrChecker::EnvpInvalidatingCall},
44349cc55cSDimitry Andric       {{"putenv", 1}, &InvalidPtrChecker::EnvpInvalidatingCall},
45349cc55cSDimitry Andric       {{"_putenv_s", 2}, &InvalidPtrChecker::EnvpInvalidatingCall},
46349cc55cSDimitry Andric       {{"_wputenv_s", 2}, &InvalidPtrChecker::EnvpInvalidatingCall},
47349cc55cSDimitry Andric   };
48349cc55cSDimitry Andric 
49349cc55cSDimitry Andric   void postPreviousReturnInvalidatingCall(const CallEvent &Call,
50349cc55cSDimitry Andric                                           CheckerContext &C) const;
51349cc55cSDimitry Andric 
52349cc55cSDimitry Andric   // SEI CERT ENV34-C
53349cc55cSDimitry Andric   const CallDescriptionMap<HandlerFn> PreviousCallInvalidatingFunctions = {
54349cc55cSDimitry Andric       {{"getenv", 1}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall},
55349cc55cSDimitry Andric       {{"setlocale", 2},
56349cc55cSDimitry Andric        &InvalidPtrChecker::postPreviousReturnInvalidatingCall},
57349cc55cSDimitry Andric       {{"strerror", 1}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall},
58349cc55cSDimitry Andric       {{"localeconv", 0},
59349cc55cSDimitry Andric        &InvalidPtrChecker::postPreviousReturnInvalidatingCall},
60349cc55cSDimitry Andric       {{"asctime", 1}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall},
61349cc55cSDimitry Andric   };
62349cc55cSDimitry Andric 
63349cc55cSDimitry Andric public:
64349cc55cSDimitry Andric   // Obtain the environment pointer from 'main()' (if present).
65349cc55cSDimitry Andric   void checkBeginFunction(CheckerContext &C) const;
66349cc55cSDimitry Andric 
67349cc55cSDimitry Andric   // Handle functions in EnvpInvalidatingFunctions, that invalidate environment
68349cc55cSDimitry Andric   // pointer from 'main()'
69349cc55cSDimitry Andric   // Handle functions in PreviousCallInvalidatingFunctions.
70349cc55cSDimitry Andric   // Also, check if invalidated region is passed to a
71349cc55cSDimitry Andric   // conservatively evaluated function call as an argument.
72349cc55cSDimitry Andric   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
73349cc55cSDimitry Andric 
74349cc55cSDimitry Andric   // Check if invalidated region is being dereferenced.
75349cc55cSDimitry Andric   void checkLocation(SVal l, bool isLoad, const Stmt *S,
76349cc55cSDimitry Andric                      CheckerContext &C) const;
77349cc55cSDimitry Andric };
78349cc55cSDimitry Andric 
79349cc55cSDimitry Andric } // namespace
80349cc55cSDimitry Andric 
81349cc55cSDimitry Andric // Set of memory regions that were invalidated
82349cc55cSDimitry Andric REGISTER_SET_WITH_PROGRAMSTATE(InvalidMemoryRegions, const MemRegion *)
83349cc55cSDimitry Andric 
84349cc55cSDimitry Andric // Stores the region of the environment pointer of 'main' (if present).
85*81ad6265SDimitry Andric REGISTER_TRAIT_WITH_PROGRAMSTATE(EnvPtrRegion, const MemRegion *)
86349cc55cSDimitry Andric 
87349cc55cSDimitry Andric // Stores key-value pairs, where key is function declaration and value is
88349cc55cSDimitry Andric // pointer to memory region returned by previous call of this function
89349cc55cSDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(PreviousCallResultMap, const FunctionDecl *,
90349cc55cSDimitry Andric                                const MemRegion *)
91349cc55cSDimitry Andric 
92349cc55cSDimitry Andric void InvalidPtrChecker::EnvpInvalidatingCall(const CallEvent &Call,
93349cc55cSDimitry Andric                                              CheckerContext &C) const {
94349cc55cSDimitry Andric   StringRef FunctionName = Call.getCalleeIdentifier()->getName();
95349cc55cSDimitry Andric   ProgramStateRef State = C.getState();
96*81ad6265SDimitry Andric   const MemRegion *SymbolicEnvPtrRegion = State->get<EnvPtrRegion>();
97*81ad6265SDimitry Andric   if (!SymbolicEnvPtrRegion)
98349cc55cSDimitry Andric     return;
99349cc55cSDimitry Andric 
100349cc55cSDimitry Andric   State = State->add<InvalidMemoryRegions>(SymbolicEnvPtrRegion);
101349cc55cSDimitry Andric 
102349cc55cSDimitry Andric   const NoteTag *Note =
103349cc55cSDimitry Andric       C.getNoteTag([SymbolicEnvPtrRegion, FunctionName](
104349cc55cSDimitry Andric                        PathSensitiveBugReport &BR, llvm::raw_ostream &Out) {
105349cc55cSDimitry Andric         if (!BR.isInteresting(SymbolicEnvPtrRegion))
106349cc55cSDimitry Andric           return;
107349cc55cSDimitry Andric         Out << '\'' << FunctionName
108349cc55cSDimitry Andric             << "' call may invalidate the environment parameter of 'main'";
109349cc55cSDimitry Andric       });
110349cc55cSDimitry Andric 
111349cc55cSDimitry Andric   C.addTransition(State, Note);
112349cc55cSDimitry Andric }
113349cc55cSDimitry Andric 
114349cc55cSDimitry Andric void InvalidPtrChecker::postPreviousReturnInvalidatingCall(
115349cc55cSDimitry Andric     const CallEvent &Call, CheckerContext &C) const {
116349cc55cSDimitry Andric   ProgramStateRef State = C.getState();
117349cc55cSDimitry Andric 
118349cc55cSDimitry Andric   const NoteTag *Note = nullptr;
119349cc55cSDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
120349cc55cSDimitry Andric   // Invalidate the region of the previously returned pointer - if there was
121349cc55cSDimitry Andric   // one.
122349cc55cSDimitry Andric   if (const MemRegion *const *Reg = State->get<PreviousCallResultMap>(FD)) {
123349cc55cSDimitry Andric     const MemRegion *PrevReg = *Reg;
124349cc55cSDimitry Andric     State = State->add<InvalidMemoryRegions>(PrevReg);
125349cc55cSDimitry Andric     Note = C.getNoteTag([PrevReg, FD](PathSensitiveBugReport &BR,
126349cc55cSDimitry Andric                                       llvm::raw_ostream &Out) {
127349cc55cSDimitry Andric       if (!BR.isInteresting(PrevReg))
128349cc55cSDimitry Andric         return;
129349cc55cSDimitry Andric       Out << '\'';
130349cc55cSDimitry Andric       FD->getNameForDiagnostic(Out, FD->getASTContext().getLangOpts(), true);
131*81ad6265SDimitry Andric       Out << "' call may invalidate the result of the previous " << '\'';
132349cc55cSDimitry Andric       FD->getNameForDiagnostic(Out, FD->getASTContext().getLangOpts(), true);
133349cc55cSDimitry Andric       Out << '\'';
134349cc55cSDimitry Andric     });
135349cc55cSDimitry Andric   }
136349cc55cSDimitry Andric 
137349cc55cSDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
138349cc55cSDimitry Andric   const auto *CE = cast<CallExpr>(Call.getOriginExpr());
139349cc55cSDimitry Andric 
140349cc55cSDimitry Andric   // Function call will return a pointer to the new symbolic region.
141349cc55cSDimitry Andric   DefinedOrUnknownSVal RetVal = C.getSValBuilder().conjureSymbolVal(
142349cc55cSDimitry Andric       CE, LCtx, CE->getType(), C.blockCount());
143349cc55cSDimitry Andric   State = State->BindExpr(CE, LCtx, RetVal);
144349cc55cSDimitry Andric 
145349cc55cSDimitry Andric   // Remember to this region.
146349cc55cSDimitry Andric   const auto *SymRegOfRetVal = cast<SymbolicRegion>(RetVal.getAsRegion());
147349cc55cSDimitry Andric   const MemRegion *MR =
148349cc55cSDimitry Andric       const_cast<MemRegion *>(SymRegOfRetVal->getBaseRegion());
149349cc55cSDimitry Andric   State = State->set<PreviousCallResultMap>(FD, MR);
150349cc55cSDimitry Andric 
151349cc55cSDimitry Andric   ExplodedNode *Node = C.addTransition(State, Note);
152349cc55cSDimitry Andric   const NoteTag *PreviousCallNote =
153349cc55cSDimitry Andric       C.getNoteTag([MR](PathSensitiveBugReport &BR, llvm::raw_ostream &Out) {
154349cc55cSDimitry Andric         if (!BR.isInteresting(MR))
155349cc55cSDimitry Andric           return;
156349cc55cSDimitry Andric         Out << '\'' << "'previous function call was here" << '\'';
157349cc55cSDimitry Andric       });
158349cc55cSDimitry Andric 
159349cc55cSDimitry Andric   C.addTransition(State, Node, PreviousCallNote);
160349cc55cSDimitry Andric }
161349cc55cSDimitry Andric 
162349cc55cSDimitry Andric // TODO: This seems really ugly. Simplify this.
163349cc55cSDimitry Andric static const MemRegion *findInvalidatedSymbolicBase(ProgramStateRef State,
164349cc55cSDimitry Andric                                                     const MemRegion *Reg) {
165349cc55cSDimitry Andric   while (Reg) {
166349cc55cSDimitry Andric     if (State->contains<InvalidMemoryRegions>(Reg))
167349cc55cSDimitry Andric       return Reg;
168349cc55cSDimitry Andric     const auto *SymBase = Reg->getSymbolicBase();
169349cc55cSDimitry Andric     if (!SymBase)
170349cc55cSDimitry Andric       break;
171349cc55cSDimitry Andric     const auto *SRV = dyn_cast<SymbolRegionValue>(SymBase->getSymbol());
172349cc55cSDimitry Andric     if (!SRV)
173349cc55cSDimitry Andric       break;
174349cc55cSDimitry Andric     Reg = SRV->getRegion();
175349cc55cSDimitry Andric     if (const auto *VarReg = dyn_cast<VarRegion>(SRV->getRegion()))
176349cc55cSDimitry Andric       Reg = VarReg;
177349cc55cSDimitry Andric   }
178349cc55cSDimitry Andric   return nullptr;
179349cc55cSDimitry Andric }
180349cc55cSDimitry Andric 
181349cc55cSDimitry Andric // Handle functions in EnvpInvalidatingFunctions, that invalidate environment
182349cc55cSDimitry Andric // pointer from 'main()' Also, check if invalidated region is passed to a
183349cc55cSDimitry Andric // function call as an argument.
184349cc55cSDimitry Andric void InvalidPtrChecker::checkPostCall(const CallEvent &Call,
185349cc55cSDimitry Andric                                       CheckerContext &C) const {
186349cc55cSDimitry Andric   // Check if function invalidates 'envp' argument of 'main'
187349cc55cSDimitry Andric   if (const auto *Handler = EnvpInvalidatingFunctions.lookup(Call))
188349cc55cSDimitry Andric     (this->**Handler)(Call, C);
189349cc55cSDimitry Andric 
190349cc55cSDimitry Andric   // Check if function invalidates the result of previous call
191349cc55cSDimitry Andric   if (const auto *Handler = PreviousCallInvalidatingFunctions.lookup(Call))
192349cc55cSDimitry Andric     (this->**Handler)(Call, C);
193349cc55cSDimitry Andric 
194349cc55cSDimitry Andric   // Check if one of the arguments of the function call is invalidated
195349cc55cSDimitry Andric 
196349cc55cSDimitry Andric   // If call was inlined, don't report invalidated argument
197349cc55cSDimitry Andric   if (C.wasInlined)
198349cc55cSDimitry Andric     return;
199349cc55cSDimitry Andric 
200349cc55cSDimitry Andric   ProgramStateRef State = C.getState();
201349cc55cSDimitry Andric 
202349cc55cSDimitry Andric   for (unsigned I = 0, NumArgs = Call.getNumArgs(); I < NumArgs; ++I) {
203349cc55cSDimitry Andric 
204349cc55cSDimitry Andric     if (const auto *SR = dyn_cast_or_null<SymbolicRegion>(
205349cc55cSDimitry Andric             Call.getArgSVal(I).getAsRegion())) {
206349cc55cSDimitry Andric       if (const MemRegion *InvalidatedSymbolicBase =
207349cc55cSDimitry Andric               findInvalidatedSymbolicBase(State, SR)) {
208349cc55cSDimitry Andric         ExplodedNode *ErrorNode = C.generateNonFatalErrorNode();
209349cc55cSDimitry Andric         if (!ErrorNode)
210349cc55cSDimitry Andric           return;
211349cc55cSDimitry Andric 
212349cc55cSDimitry Andric         SmallString<256> Msg;
213349cc55cSDimitry Andric         llvm::raw_svector_ostream Out(Msg);
214349cc55cSDimitry Andric         Out << "use of invalidated pointer '";
215349cc55cSDimitry Andric         Call.getArgExpr(I)->printPretty(Out, /*Helper=*/nullptr,
216349cc55cSDimitry Andric                                         C.getASTContext().getPrintingPolicy());
217349cc55cSDimitry Andric         Out << "' in a function call";
218349cc55cSDimitry Andric 
219349cc55cSDimitry Andric         auto Report =
220349cc55cSDimitry Andric             std::make_unique<PathSensitiveBugReport>(BT, Out.str(), ErrorNode);
221349cc55cSDimitry Andric         Report->markInteresting(InvalidatedSymbolicBase);
222349cc55cSDimitry Andric         Report->addRange(Call.getArgSourceRange(I));
223349cc55cSDimitry Andric         C.emitReport(std::move(Report));
224349cc55cSDimitry Andric       }
225349cc55cSDimitry Andric     }
226349cc55cSDimitry Andric   }
227349cc55cSDimitry Andric }
228349cc55cSDimitry Andric 
229349cc55cSDimitry Andric // Obtain the environment pointer from 'main()', if present.
230349cc55cSDimitry Andric void InvalidPtrChecker::checkBeginFunction(CheckerContext &C) const {
231349cc55cSDimitry Andric   if (!C.inTopFrame())
232349cc55cSDimitry Andric     return;
233349cc55cSDimitry Andric 
234349cc55cSDimitry Andric   const auto *FD = dyn_cast<FunctionDecl>(C.getLocationContext()->getDecl());
235349cc55cSDimitry Andric   if (!FD || FD->param_size() != 3 || !FD->isMain())
236349cc55cSDimitry Andric     return;
237349cc55cSDimitry Andric 
238349cc55cSDimitry Andric   ProgramStateRef State = C.getState();
239349cc55cSDimitry Andric   const MemRegion *EnvpReg =
240349cc55cSDimitry Andric       State->getRegion(FD->parameters()[2], C.getLocationContext());
241349cc55cSDimitry Andric 
242349cc55cSDimitry Andric   // Save the memory region pointed by the environment pointer parameter of
243349cc55cSDimitry Andric   // 'main'.
244*81ad6265SDimitry Andric   C.addTransition(State->set<EnvPtrRegion>(EnvpReg));
245349cc55cSDimitry Andric }
246349cc55cSDimitry Andric 
247349cc55cSDimitry Andric // Check if invalidated region is being dereferenced.
248349cc55cSDimitry Andric void InvalidPtrChecker::checkLocation(SVal Loc, bool isLoad, const Stmt *S,
249349cc55cSDimitry Andric                                       CheckerContext &C) const {
250349cc55cSDimitry Andric   ProgramStateRef State = C.getState();
251349cc55cSDimitry Andric 
252349cc55cSDimitry Andric   // Ignore memory operations involving 'non-invalidated' locations.
253349cc55cSDimitry Andric   const MemRegion *InvalidatedSymbolicBase =
254349cc55cSDimitry Andric       findInvalidatedSymbolicBase(State, Loc.getAsRegion());
255349cc55cSDimitry Andric   if (!InvalidatedSymbolicBase)
256349cc55cSDimitry Andric     return;
257349cc55cSDimitry Andric 
258349cc55cSDimitry Andric   ExplodedNode *ErrorNode = C.generateNonFatalErrorNode();
259349cc55cSDimitry Andric   if (!ErrorNode)
260349cc55cSDimitry Andric     return;
261349cc55cSDimitry Andric 
262349cc55cSDimitry Andric   auto Report = std::make_unique<PathSensitiveBugReport>(
263349cc55cSDimitry Andric       BT, "dereferencing an invalid pointer", ErrorNode);
264349cc55cSDimitry Andric   Report->markInteresting(InvalidatedSymbolicBase);
265349cc55cSDimitry Andric   C.emitReport(std::move(Report));
266349cc55cSDimitry Andric }
267349cc55cSDimitry Andric 
268349cc55cSDimitry Andric void ento::registerInvalidPtrChecker(CheckerManager &Mgr) {
269349cc55cSDimitry Andric   Mgr.registerChecker<InvalidPtrChecker>();
270349cc55cSDimitry Andric }
271349cc55cSDimitry Andric 
272349cc55cSDimitry Andric bool ento::shouldRegisterInvalidPtrChecker(const CheckerManager &) {
273349cc55cSDimitry Andric   return true;
274349cc55cSDimitry Andric }
275