xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp (revision 6cd16c5152afcf00b3097d1326301e84dae55c33)
1 //= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- 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 UnixAPIChecker, which is an assortment of checks on calls
11 // to various, widely used UNIX/Posix functions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include <fcntl.h>
26 
27 using namespace clang;
28 using namespace ento;
29 using llvm::Optional;
30 
31 namespace {
32 class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
33   mutable OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
34   mutable Optional<uint64_t> Val_O_CREAT;
35 
36 public:
37   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
38 
39   void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
40   void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
41   void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
42   void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
43   void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
44   void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
45   void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
46 
47   typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
48                                              const CallExpr *) const;
49 private:
50   bool ReportZeroByteAllocation(CheckerContext &C,
51                                 ProgramStateRef falseState,
52                                 const Expr *arg,
53                                 const char *fn_name) const;
54   void BasicAllocationCheck(CheckerContext &C,
55                             const CallExpr *CE,
56                             const unsigned numArgs,
57                             const unsigned sizeArg,
58                             const char *fn) const;
59 };
60 } //end anonymous namespace
61 
62 //===----------------------------------------------------------------------===//
63 // Utility functions.
64 //===----------------------------------------------------------------------===//
65 
66 static inline void LazyInitialize(OwningPtr<BugType> &BT,
67                                   const char *name) {
68   if (BT)
69     return;
70   BT.reset(new BugType(name, categories::UnixAPI));
71 }
72 
73 //===----------------------------------------------------------------------===//
74 // "open" (man 2 open)
75 //===----------------------------------------------------------------------===//
76 
77 void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
78   // The definition of O_CREAT is platform specific.  We need a better way
79   // of querying this information from the checking environment.
80   if (!Val_O_CREAT.hasValue()) {
81     if (C.getASTContext().getTargetInfo().getTriple().getVendor()
82                                                       == llvm::Triple::Apple)
83       Val_O_CREAT = 0x0200;
84     else {
85       // FIXME: We need a more general way of getting the O_CREAT value.
86       // We could possibly grovel through the preprocessor state, but
87       // that would require passing the Preprocessor object to the ExprEngine.
88       return;
89     }
90   }
91 
92   // Look at the 'oflags' argument for the O_CREAT flag.
93   ProgramStateRef state = C.getState();
94 
95   if (CE->getNumArgs() < 2) {
96     // The frontend should issue a warning for this case, so this is a sanity
97     // check.
98     return;
99   }
100 
101   // Now check if oflags has O_CREAT set.
102   const Expr *oflagsEx = CE->getArg(1);
103   const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
104   if (!isa<NonLoc>(V)) {
105     // The case where 'V' can be a location can only be due to a bad header,
106     // so in this case bail out.
107     return;
108   }
109   NonLoc oflags = cast<NonLoc>(V);
110   NonLoc ocreateFlag =
111     cast<NonLoc>(C.getSValBuilder().makeIntVal(Val_O_CREAT.getValue(),
112                                                 oflagsEx->getType()));
113   SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
114                                                       oflags, ocreateFlag,
115                                                       oflagsEx->getType());
116   if (maskedFlagsUC.isUnknownOrUndef())
117     return;
118   DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
119 
120   // Check if maskedFlags is non-zero.
121   ProgramStateRef trueState, falseState;
122   llvm::tie(trueState, falseState) = state->assume(maskedFlags);
123 
124   // Only emit an error if the value of 'maskedFlags' is properly
125   // constrained;
126   if (!(trueState && !falseState))
127     return;
128 
129   if (CE->getNumArgs() < 3) {
130     ExplodedNode *N = C.generateSink(trueState);
131     if (!N)
132       return;
133 
134     LazyInitialize(BT_open, "Improper use of 'open'");
135 
136     BugReport *report =
137       new BugReport(*BT_open,
138                             "Call to 'open' requires a third argument when "
139                             "the 'O_CREAT' flag is set", N);
140     report->addRange(oflagsEx->getSourceRange());
141     C.EmitReport(report);
142   }
143 }
144 
145 //===----------------------------------------------------------------------===//
146 // pthread_once
147 //===----------------------------------------------------------------------===//
148 
149 void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
150                                       const CallExpr *CE) const {
151 
152   // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
153   // They can possibly be refactored.
154 
155   if (CE->getNumArgs() < 1)
156     return;
157 
158   // Check if the first argument is stack allocated.  If so, issue a warning
159   // because that's likely to be bad news.
160   ProgramStateRef state = C.getState();
161   const MemRegion *R =
162     state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
163   if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
164     return;
165 
166   ExplodedNode *N = C.generateSink(state);
167   if (!N)
168     return;
169 
170   SmallString<256> S;
171   llvm::raw_svector_ostream os(S);
172   os << "Call to 'pthread_once' uses";
173   if (const VarRegion *VR = dyn_cast<VarRegion>(R))
174     os << " the local variable '" << VR->getDecl()->getName() << '\'';
175   else
176     os << " stack allocated memory";
177   os << " for the \"control\" value.  Using such transient memory for "
178   "the control value is potentially dangerous.";
179   if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
180     os << "  Perhaps you intended to declare the variable as 'static'?";
181 
182   LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
183 
184   BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
185   report->addRange(CE->getArg(0)->getSourceRange());
186   C.EmitReport(report);
187 }
188 
189 //===----------------------------------------------------------------------===//
190 // "calloc", "malloc", "realloc", "alloca" and "valloc" with allocation size 0
191 //===----------------------------------------------------------------------===//
192 // FIXME: Eventually these should be rolled into the MallocChecker, but right now
193 // they're more basic and valuable for widespread use.
194 
195 // Returns true if we try to do a zero byte allocation, false otherwise.
196 // Fills in trueState and falseState.
197 static bool IsZeroByteAllocation(ProgramStateRef state,
198                                 const SVal argVal,
199                                 ProgramStateRef *trueState,
200                                 ProgramStateRef *falseState) {
201   llvm::tie(*trueState, *falseState) =
202     state->assume(cast<DefinedSVal>(argVal));
203 
204   return (*falseState && !*trueState);
205 }
206 
207 // Generates an error report, indicating that the function whose name is given
208 // will perform a zero byte allocation.
209 // Returns false if an error occured, true otherwise.
210 bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
211                                               ProgramStateRef falseState,
212                                               const Expr *arg,
213                                               const char *fn_name) const {
214   ExplodedNode *N = C.generateSink(falseState);
215   if (!N)
216     return false;
217 
218   LazyInitialize(BT_mallocZero,
219     "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
220 
221   SmallString<256> S;
222   llvm::raw_svector_ostream os(S);
223   os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
224   BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
225 
226   report->addRange(arg->getSourceRange());
227   report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg,
228                                                                   report));
229   C.EmitReport(report);
230 
231   return true;
232 }
233 
234 // Does a basic check for 0-sized allocations suitable for most of the below
235 // functions (modulo "calloc")
236 void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
237                                           const CallExpr *CE,
238                                           const unsigned numArgs,
239                                           const unsigned sizeArg,
240                                           const char *fn) const {
241   // Sanity check for the correct number of arguments
242   if (CE->getNumArgs() != numArgs)
243     return;
244 
245   // Check if the allocation size is 0.
246   ProgramStateRef state = C.getState();
247   ProgramStateRef trueState = NULL, falseState = NULL;
248   const Expr *arg = CE->getArg(sizeArg);
249   SVal argVal = state->getSVal(arg, C.getLocationContext());
250 
251   if (argVal.isUnknownOrUndef())
252     return;
253 
254   // Is the value perfectly constrained to zero?
255   if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
256     (void) ReportZeroByteAllocation(C, falseState, arg, fn);
257     return;
258   }
259   // Assume the the value is non-zero going forward.
260   assert(trueState);
261   if (trueState != state)
262     C.addTransition(trueState);
263 }
264 
265 void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
266                                      const CallExpr *CE) const {
267   unsigned int nArgs = CE->getNumArgs();
268   if (nArgs != 2)
269     return;
270 
271   ProgramStateRef state = C.getState();
272   ProgramStateRef trueState = NULL, falseState = NULL;
273 
274   unsigned int i;
275   for (i = 0; i < nArgs; i++) {
276     const Expr *arg = CE->getArg(i);
277     SVal argVal = state->getSVal(arg, C.getLocationContext());
278     if (argVal.isUnknownOrUndef()) {
279       if (i == 0)
280         continue;
281       else
282         return;
283     }
284 
285     if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
286       if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
287         return;
288       else if (i == 0)
289         continue;
290       else
291         return;
292     }
293   }
294 
295   // Assume the the value is non-zero going forward.
296   assert(trueState);
297   if (trueState != state)
298     C.addTransition(trueState);
299 }
300 
301 void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
302                                      const CallExpr *CE) const {
303   BasicAllocationCheck(C, CE, 1, 0, "malloc");
304 }
305 
306 void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
307                                       const CallExpr *CE) const {
308   BasicAllocationCheck(C, CE, 2, 1, "realloc");
309 }
310 
311 void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
312                                      const CallExpr *CE) const {
313   BasicAllocationCheck(C, CE, 1, 0, "alloca");
314 }
315 
316 void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
317                                      const CallExpr *CE) const {
318   BasicAllocationCheck(C, CE, 1, 0, "valloc");
319 }
320 
321 
322 //===----------------------------------------------------------------------===//
323 // Central dispatch function.
324 //===----------------------------------------------------------------------===//
325 
326 void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
327                                   CheckerContext &C) const {
328   const FunctionDecl *FD = C.getCalleeDecl(CE);
329   if (!FD || FD->getKind() != Decl::Function)
330     return;
331 
332   StringRef FName = C.getCalleeName(FD);
333   if (FName.empty())
334     return;
335 
336   SubChecker SC =
337     llvm::StringSwitch<SubChecker>(FName)
338       .Case("open", &UnixAPIChecker::CheckOpen)
339       .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
340       .Case("calloc", &UnixAPIChecker::CheckCallocZero)
341       .Case("malloc", &UnixAPIChecker::CheckMallocZero)
342       .Case("realloc", &UnixAPIChecker::CheckReallocZero)
343       .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
344       .Case("valloc", &UnixAPIChecker::CheckVallocZero)
345       .Default(NULL);
346 
347   if (SC)
348     (this->*SC)(C, CE);
349 }
350 
351 //===----------------------------------------------------------------------===//
352 // Registration.
353 //===----------------------------------------------------------------------===//
354 
355 void ento::registerUnixAPIChecker(CheckerManager &mgr) {
356   mgr.registerChecker<UnixAPIChecker>();
357 }
358