UnixAPIChecker.cpp revision ec8605f1d7ec846dbf51047bfd5c56d32d1ff91c
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/StringSwitch.h"
23#include <fcntl.h>
24
25using namespace clang;
26using namespace ento;
27using llvm::Optional;
28
29namespace {
30class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
31  enum SubChecks {
32    OpenFn = 0,
33    PthreadOnceFn = 1,
34    MallocZero = 2,
35    NumChecks
36  };
37
38  mutable BugType *BTypes[NumChecks];
39
40public:
41  mutable Optional<uint64_t> Val_O_CREAT;
42
43public:
44  UnixAPIChecker() { memset(BTypes, 0, sizeof(*BTypes) * NumChecks); }
45  ~UnixAPIChecker() {
46    for (unsigned i=0; i != NumChecks; ++i)
47      delete BTypes[i];
48  }
49
50  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
51};
52} //end anonymous namespace
53
54//===----------------------------------------------------------------------===//
55// Utility functions.
56//===----------------------------------------------------------------------===//
57
58static inline void LazyInitialize(BugType *&BT, const char *name) {
59  if (BT)
60    return;
61  BT = new BugType(name, "Unix API");
62}
63
64//===----------------------------------------------------------------------===//
65// "open" (man 2 open)
66//===----------------------------------------------------------------------===//
67
68static void CheckOpen(CheckerContext &C, const UnixAPIChecker &UC,
69                      const CallExpr *CE, BugType *&BT) {
70  // The definition of O_CREAT is platform specific.  We need a better way
71  // of querying this information from the checking environment.
72  if (!UC.Val_O_CREAT.hasValue()) {
73    if (C.getASTContext().Target.getTriple().getVendor() == llvm::Triple::Apple)
74      UC.Val_O_CREAT = 0x0200;
75    else {
76      // FIXME: We need a more general way of getting the O_CREAT value.
77      // We could possibly grovel through the preprocessor state, but
78      // that would require passing the Preprocessor object to the ExprEngine.
79      return;
80    }
81  }
82
83  LazyInitialize(BT, "Improper use of 'open'");
84
85  // Look at the 'oflags' argument for the O_CREAT flag.
86  const GRState *state = C.getState();
87
88  if (CE->getNumArgs() < 2) {
89    // The frontend should issue a warning for this case, so this is a sanity
90    // check.
91    return;
92  }
93
94  // Now check if oflags has O_CREAT set.
95  const Expr *oflagsEx = CE->getArg(1);
96  const SVal V = state->getSVal(oflagsEx);
97  if (!isa<NonLoc>(V)) {
98    // The case where 'V' can be a location can only be due to a bad header,
99    // so in this case bail out.
100    return;
101  }
102  NonLoc oflags = cast<NonLoc>(V);
103  NonLoc ocreateFlag =
104    cast<NonLoc>(C.getSValBuilder().makeIntVal(UC.Val_O_CREAT.getValue(),
105                                                oflagsEx->getType()));
106  SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
107                                                      oflags, ocreateFlag,
108                                                      oflagsEx->getType());
109  if (maskedFlagsUC.isUnknownOrUndef())
110    return;
111  DefinedSVal maskedFlags = cast<DefinedSVal>(maskedFlagsUC);
112
113  // Check if maskedFlags is non-zero.
114  const GRState *trueState, *falseState;
115  llvm::tie(trueState, falseState) = state->assume(maskedFlags);
116
117  // Only emit an error if the value of 'maskedFlags' is properly
118  // constrained;
119  if (!(trueState && !falseState))
120    return;
121
122  if (CE->getNumArgs() < 3) {
123    ExplodedNode *N = C.generateSink(trueState);
124    if (!N)
125      return;
126
127    EnhancedBugReport *report =
128      new EnhancedBugReport(*BT,
129                            "Call to 'open' requires a third argument when "
130                            "the 'O_CREAT' flag is set", N);
131    report->addRange(oflagsEx->getSourceRange());
132    C.EmitReport(report);
133  }
134}
135
136//===----------------------------------------------------------------------===//
137// pthread_once
138//===----------------------------------------------------------------------===//
139
140static void CheckPthreadOnce(CheckerContext &C, const UnixAPIChecker &,
141                             const CallExpr *CE, BugType *&BT) {
142
143  // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
144  // They can possibly be refactored.
145
146  LazyInitialize(BT, "Improper use of 'pthread_once'");
147
148  if (CE->getNumArgs() < 1)
149    return;
150
151  // Check if the first argument is stack allocated.  If so, issue a warning
152  // because that's likely to be bad news.
153  const GRState *state = C.getState();
154  const MemRegion *R = state->getSVal(CE->getArg(0)).getAsRegion();
155  if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
156    return;
157
158  ExplodedNode *N = C.generateSink(state);
159  if (!N)
160    return;
161
162  llvm::SmallString<256> S;
163  llvm::raw_svector_ostream os(S);
164  os << "Call to 'pthread_once' uses";
165  if (const VarRegion *VR = dyn_cast<VarRegion>(R))
166    os << " the local variable '" << VR->getDecl()->getName() << '\'';
167  else
168    os << " stack allocated memory";
169  os << " for the \"control\" value.  Using such transient memory for "
170  "the control value is potentially dangerous.";
171  if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
172    os << "  Perhaps you intended to declare the variable as 'static'?";
173
174  EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), N);
175  report->addRange(CE->getArg(0)->getSourceRange());
176  C.EmitReport(report);
177}
178
179//===----------------------------------------------------------------------===//
180// "malloc" with allocation size 0
181//===----------------------------------------------------------------------===//
182
183// FIXME: Eventually this should be rolled into the MallocChecker, but this
184// check is more basic and is valuable for widespread use.
185static void CheckMallocZero(CheckerContext &C, const UnixAPIChecker &UC,
186                            const CallExpr *CE, BugType *&BT) {
187
188  // Sanity check that malloc takes one argument.
189  if (CE->getNumArgs() != 1)
190    return;
191
192  // Check if the allocation size is 0.
193  const GRState *state = C.getState();
194  SVal argVal = state->getSVal(CE->getArg(0));
195
196  if (argVal.isUnknownOrUndef())
197    return;
198
199  const GRState *trueState, *falseState;
200  llvm::tie(trueState, falseState) = state->assume(cast<DefinedSVal>(argVal));
201
202  // Is the value perfectly constrained to zero?
203  if (falseState && !trueState) {
204    ExplodedNode *N = C.generateSink(falseState);
205    if (!N)
206      return;
207
208    // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
209    // output.
210
211    LazyInitialize(BT, "Undefined allocation of 0 bytes");
212
213    EnhancedBugReport *report =
214      new EnhancedBugReport(*BT, "Call to 'malloc' has an allocation size"
215                                 " of 0 bytes", N);
216    report->addRange(CE->getArg(0)->getSourceRange());
217    report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
218                              CE->getArg(0));
219    C.EmitReport(report);
220    return;
221  }
222  // Assume the the value is non-zero going forward.
223  assert(trueState);
224  if (trueState != state) {
225    C.addTransition(trueState);
226  }
227}
228
229//===----------------------------------------------------------------------===//
230// Central dispatch function.
231//===----------------------------------------------------------------------===//
232
233typedef void (*SubChecker)(CheckerContext &C, const UnixAPIChecker &UC,
234                           const CallExpr *CE, BugType *&BT);
235namespace {
236  class SubCheck {
237    SubChecker SC;
238    const UnixAPIChecker *UC;
239    BugType **BT;
240  public:
241    SubCheck(SubChecker sc, const UnixAPIChecker *uc, BugType *& bt)
242      : SC(sc), UC(uc), BT(&bt) {}
243    SubCheck() : SC(NULL), UC(NULL), BT(NULL) {}
244
245    void run(CheckerContext &C, const CallExpr *CE) const {
246      if (SC)
247        SC(C, *UC, CE, *BT);
248    }
249  };
250} // end anonymous namespace
251
252void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
253  // Get the callee.  All the functions we care about are C functions
254  // with simple identifiers.
255  const GRState *state = C.getState();
256  const Expr *Callee = CE->getCallee();
257  const FunctionTextRegion *Fn =
258    dyn_cast_or_null<FunctionTextRegion>(state->getSVal(Callee).getAsRegion());
259
260  if (!Fn)
261    return;
262
263  const IdentifierInfo *FI = Fn->getDecl()->getIdentifier();
264  if (!FI)
265    return;
266
267  const SubCheck &SC =
268    llvm::StringSwitch<SubCheck>(FI->getName())
269      .Case("open",
270            SubCheck(CheckOpen, this, BTypes[OpenFn]))
271      .Case("pthread_once",
272            SubCheck(CheckPthreadOnce, this, BTypes[PthreadOnceFn]))
273      .Case("malloc",
274            SubCheck(CheckMallocZero, this, BTypes[MallocZero]))
275      .Default(SubCheck());
276
277  SC.run(C, CE);
278}
279
280//===----------------------------------------------------------------------===//
281// Registration.
282//===----------------------------------------------------------------------===//
283
284void ento::registerUnixAPIChecker(CheckerManager &mgr) {
285  mgr.registerChecker<UnixAPIChecker>();
286}
287