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