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