clang API Documentation

UnixAPIChecker.cpp
Go to the documentation of this file.
00001 //= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- C++ -*-//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This defines UnixAPIChecker, which is an assortment of checks on calls
00011 // to various, widely used UNIX/Posix functions.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "ClangSACheckers.h"
00016 #include "clang/Basic/TargetInfo.h"
00017 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
00018 #include "clang/StaticAnalyzer/Core/Checker.h"
00019 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
00020 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
00021 #include "llvm/ADT/Optional.h"
00022 #include "llvm/ADT/STLExtras.h"
00023 #include "llvm/ADT/SmallString.h"
00024 #include "llvm/ADT/StringSwitch.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include <fcntl.h>
00027 
00028 using namespace clang;
00029 using namespace ento;
00030 
00031 namespace {
00032 class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
00033   mutable std::unique_ptr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
00034   mutable Optional<uint64_t> Val_O_CREAT;
00035 
00036 public:
00037   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
00038 
00039   void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
00040   void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
00041   void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
00042   void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
00043   void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
00044   void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
00045   void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
00046   void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
00047 
00048   typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
00049                                              const CallExpr *) const;
00050 private:
00051   bool ReportZeroByteAllocation(CheckerContext &C,
00052                                 ProgramStateRef falseState,
00053                                 const Expr *arg,
00054                                 const char *fn_name) const;
00055   void BasicAllocationCheck(CheckerContext &C,
00056                             const CallExpr *CE,
00057                             const unsigned numArgs,
00058                             const unsigned sizeArg,
00059                             const char *fn) const;
00060   void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
00061     if (BT)
00062       return;
00063     BT.reset(new BugType(this, name, categories::UnixAPI));
00064   }
00065   void ReportOpenBug(CheckerContext &C,
00066                      ProgramStateRef State,
00067                      const char *Msg,
00068                      SourceRange SR) const;
00069 };
00070 } //end anonymous namespace
00071 
00072 //===----------------------------------------------------------------------===//
00073 // "open" (man 2 open)
00074 //===----------------------------------------------------------------------===//
00075 
00076 void UnixAPIChecker::ReportOpenBug(CheckerContext &C,
00077                                    ProgramStateRef State,
00078                                    const char *Msg,
00079                                    SourceRange SR) const {
00080   ExplodedNode *N = C.generateSink(State);
00081   if (!N)
00082     return;
00083 
00084   LazyInitialize(BT_open, "Improper use of 'open'");
00085 
00086   BugReport *Report = new BugReport(*BT_open, Msg, N);
00087   Report->addRange(SR);
00088   C.emitReport(Report);
00089 }
00090 
00091 void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
00092   ProgramStateRef state = C.getState();
00093 
00094   if (CE->getNumArgs() < 2) {
00095     // The frontend should issue a warning for this case, so this is a sanity
00096     // check.
00097     return;
00098   } else if (CE->getNumArgs() == 3) {
00099     const Expr *Arg = CE->getArg(2);
00100     QualType QT = Arg->getType();
00101     if (!QT->isIntegerType()) {
00102       ReportOpenBug(C, state,
00103                     "Third argument to 'open' is not an integer",
00104                     Arg->getSourceRange());
00105       return;
00106     }
00107   } else if (CE->getNumArgs() > 3) {
00108     ReportOpenBug(C, state,
00109                   "Call to 'open' with more than three arguments",
00110                   CE->getArg(3)->getSourceRange());
00111     return;
00112   }
00113 
00114   // The definition of O_CREAT is platform specific.  We need a better way
00115   // of querying this information from the checking environment.
00116   if (!Val_O_CREAT.hasValue()) {
00117     if (C.getASTContext().getTargetInfo().getTriple().getVendor() 
00118                                                       == llvm::Triple::Apple)
00119       Val_O_CREAT = 0x0200;
00120     else {
00121       // FIXME: We need a more general way of getting the O_CREAT value.
00122       // We could possibly grovel through the preprocessor state, but
00123       // that would require passing the Preprocessor object to the ExprEngine.
00124       // See also: MallocChecker.cpp / M_ZERO.
00125       return;
00126     }
00127   }
00128 
00129   // Now check if oflags has O_CREAT set.
00130   const Expr *oflagsEx = CE->getArg(1);
00131   const SVal V = state->getSVal(oflagsEx, C.getLocationContext());
00132   if (!V.getAs<NonLoc>()) {
00133     // The case where 'V' can be a location can only be due to a bad header,
00134     // so in this case bail out.
00135     return;
00136   }
00137   NonLoc oflags = V.castAs<NonLoc>();
00138   NonLoc ocreateFlag = C.getSValBuilder()
00139       .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
00140   SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
00141                                                       oflags, ocreateFlag,
00142                                                       oflagsEx->getType());
00143   if (maskedFlagsUC.isUnknownOrUndef())
00144     return;
00145   DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
00146 
00147   // Check if maskedFlags is non-zero.
00148   ProgramStateRef trueState, falseState;
00149   std::tie(trueState, falseState) = state->assume(maskedFlags);
00150 
00151   // Only emit an error if the value of 'maskedFlags' is properly
00152   // constrained;
00153   if (!(trueState && !falseState))
00154     return;
00155 
00156   if (CE->getNumArgs() < 3) {
00157     ReportOpenBug(C, trueState,
00158                   "Call to 'open' requires a third argument when "
00159                   "the 'O_CREAT' flag is set",
00160                   oflagsEx->getSourceRange());
00161   }
00162 }
00163 
00164 //===----------------------------------------------------------------------===//
00165 // pthread_once
00166 //===----------------------------------------------------------------------===//
00167 
00168 void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
00169                                       const CallExpr *CE) const {
00170 
00171   // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
00172   // They can possibly be refactored.
00173 
00174   if (CE->getNumArgs() < 1)
00175     return;
00176 
00177   // Check if the first argument is stack allocated.  If so, issue a warning
00178   // because that's likely to be bad news.
00179   ProgramStateRef state = C.getState();
00180   const MemRegion *R =
00181     state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
00182   if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
00183     return;
00184 
00185   ExplodedNode *N = C.generateSink(state);
00186   if (!N)
00187     return;
00188 
00189   SmallString<256> S;
00190   llvm::raw_svector_ostream os(S);
00191   os << "Call to 'pthread_once' uses";
00192   if (const VarRegion *VR = dyn_cast<VarRegion>(R))
00193     os << " the local variable '" << VR->getDecl()->getName() << '\'';
00194   else
00195     os << " stack allocated memory";
00196   os << " for the \"control\" value.  Using such transient memory for "
00197   "the control value is potentially dangerous.";
00198   if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
00199     os << "  Perhaps you intended to declare the variable as 'static'?";
00200 
00201   LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
00202 
00203   BugReport *report = new BugReport(*BT_pthreadOnce, os.str(), N);
00204   report->addRange(CE->getArg(0)->getSourceRange());
00205   C.emitReport(report);
00206 }
00207 
00208 //===----------------------------------------------------------------------===//
00209 // "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
00210 // with allocation size 0
00211 //===----------------------------------------------------------------------===//
00212 // FIXME: Eventually these should be rolled into the MallocChecker, but right now
00213 // they're more basic and valuable for widespread use.
00214 
00215 // Returns true if we try to do a zero byte allocation, false otherwise.
00216 // Fills in trueState and falseState.
00217 static bool IsZeroByteAllocation(ProgramStateRef state,
00218                                 const SVal argVal,
00219                                 ProgramStateRef *trueState,
00220                                 ProgramStateRef *falseState) {
00221   std::tie(*trueState, *falseState) =
00222     state->assume(argVal.castAs<DefinedSVal>());
00223   
00224   return (*falseState && !*trueState);
00225 }
00226 
00227 // Generates an error report, indicating that the function whose name is given
00228 // will perform a zero byte allocation.
00229 // Returns false if an error occurred, true otherwise.
00230 bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
00231                                               ProgramStateRef falseState,
00232                                               const Expr *arg,
00233                                               const char *fn_name) const {
00234   ExplodedNode *N = C.generateSink(falseState);
00235   if (!N)
00236     return false;
00237 
00238   LazyInitialize(BT_mallocZero,
00239                  "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
00240 
00241   SmallString<256> S;
00242   llvm::raw_svector_ostream os(S);    
00243   os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
00244   BugReport *report = new BugReport(*BT_mallocZero, os.str(), N);
00245 
00246   report->addRange(arg->getSourceRange());
00247   bugreporter::trackNullOrUndefValue(N, arg, *report);
00248   C.emitReport(report);
00249 
00250   return true;
00251 }
00252 
00253 // Does a basic check for 0-sized allocations suitable for most of the below
00254 // functions (modulo "calloc")
00255 void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
00256                                           const CallExpr *CE,
00257                                           const unsigned numArgs,
00258                                           const unsigned sizeArg,
00259                                           const char *fn) const {
00260   // Sanity check for the correct number of arguments
00261   if (CE->getNumArgs() != numArgs)
00262     return;
00263 
00264   // Check if the allocation size is 0.
00265   ProgramStateRef state = C.getState();
00266   ProgramStateRef trueState = nullptr, falseState = nullptr;
00267   const Expr *arg = CE->getArg(sizeArg);
00268   SVal argVal = state->getSVal(arg, C.getLocationContext());
00269 
00270   if (argVal.isUnknownOrUndef())
00271     return;
00272 
00273   // Is the value perfectly constrained to zero?
00274   if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
00275     (void) ReportZeroByteAllocation(C, falseState, arg, fn); 
00276     return;
00277   }
00278   // Assume the value is non-zero going forward.
00279   assert(trueState);
00280   if (trueState != state)
00281     C.addTransition(trueState);                           
00282 }
00283 
00284 void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
00285                                      const CallExpr *CE) const {
00286   unsigned int nArgs = CE->getNumArgs();
00287   if (nArgs != 2)
00288     return;
00289 
00290   ProgramStateRef state = C.getState();
00291   ProgramStateRef trueState = nullptr, falseState = nullptr;
00292 
00293   unsigned int i;
00294   for (i = 0; i < nArgs; i++) {
00295     const Expr *arg = CE->getArg(i);
00296     SVal argVal = state->getSVal(arg, C.getLocationContext());
00297     if (argVal.isUnknownOrUndef()) {
00298       if (i == 0)
00299         continue;
00300       else
00301         return;
00302     }
00303 
00304     if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
00305       if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
00306         return;
00307       else if (i == 0)
00308         continue;
00309       else
00310         return;
00311     }
00312   }
00313 
00314   // Assume the value is non-zero going forward.
00315   assert(trueState);
00316   if (trueState != state)
00317     C.addTransition(trueState);
00318 }
00319 
00320 void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
00321                                      const CallExpr *CE) const {
00322   BasicAllocationCheck(C, CE, 1, 0, "malloc");
00323 }
00324 
00325 void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
00326                                       const CallExpr *CE) const {
00327   BasicAllocationCheck(C, CE, 2, 1, "realloc");
00328 }
00329 
00330 void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
00331                                        const CallExpr *CE) const {
00332   BasicAllocationCheck(C, CE, 2, 1, "reallocf");
00333 }
00334 
00335 void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
00336                                      const CallExpr *CE) const {
00337   BasicAllocationCheck(C, CE, 1, 0, "alloca");
00338 }
00339 
00340 void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
00341                                      const CallExpr *CE) const {
00342   BasicAllocationCheck(C, CE, 1, 0, "valloc");
00343 }
00344 
00345 
00346 //===----------------------------------------------------------------------===//
00347 // Central dispatch function.
00348 //===----------------------------------------------------------------------===//
00349 
00350 void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
00351                                   CheckerContext &C) const {
00352   const FunctionDecl *FD = C.getCalleeDecl(CE);
00353   if (!FD || FD->getKind() != Decl::Function)
00354     return;
00355 
00356   StringRef FName = C.getCalleeName(FD);
00357   if (FName.empty())
00358     return;
00359 
00360   SubChecker SC =
00361     llvm::StringSwitch<SubChecker>(FName)
00362       .Case("open", &UnixAPIChecker::CheckOpen)
00363       .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
00364       .Case("calloc", &UnixAPIChecker::CheckCallocZero)
00365       .Case("malloc", &UnixAPIChecker::CheckMallocZero)
00366       .Case("realloc", &UnixAPIChecker::CheckReallocZero)
00367       .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
00368       .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZero)
00369       .Case("valloc", &UnixAPIChecker::CheckVallocZero)
00370       .Default(nullptr);
00371 
00372   if (SC)
00373     (this->*SC)(C, CE);
00374 }
00375 
00376 //===----------------------------------------------------------------------===//
00377 // Registration.
00378 //===----------------------------------------------------------------------===//
00379 
00380 void ento::registerUnixAPIChecker(CheckerManager &mgr) {
00381   mgr.registerChecker<UnixAPIChecker>();
00382 }