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