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