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