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