xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
1 //= UnixAPIChecker.h - Checks preconditions for various Unix APIs --*- C++ -*-//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This defines UnixAPIChecker, which is an assortment of checks on calls
10 // to various, widely used UNIX/Posix functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15 #include "clang/Basic/TargetInfo.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.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 enum class OpenVariant {
32   /// The standard open() call:
33   ///    int open(const char *path, int oflag, ...);
34   Open,
35 
36   /// The variant taking a directory file descriptor and a relative path:
37   ///    int openat(int fd, const char *path, int oflag, ...);
38   OpenAt
39 };
40 
41 namespace {
42 class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
43   mutable std::unique_ptr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
44   mutable Optional<uint64_t> Val_O_CREAT;
45 
46 public:
47   DefaultBool CheckMisuse, CheckPortability;
48 
49   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
50 
51   void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
52   void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
53 
54   void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
55   void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
56   void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
57   void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
58   void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
59   void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
60   void CheckAllocaWithAlignZero(CheckerContext &C, const CallExpr *CE) const;
61   void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
62 
63   typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
64                                              const CallExpr *) const;
65 private:
66 
67   void CheckOpenVariant(CheckerContext &C,
68                         const CallExpr *CE, OpenVariant Variant) const;
69 
70   bool ReportZeroByteAllocation(CheckerContext &C,
71                                 ProgramStateRef falseState,
72                                 const Expr *arg,
73                                 const char *fn_name) const;
74   void BasicAllocationCheck(CheckerContext &C,
75                             const CallExpr *CE,
76                             const unsigned numArgs,
77                             const unsigned sizeArg,
78                             const char *fn) const;
79   void LazyInitialize(std::unique_ptr<BugType> &BT, const char *name) const {
80     if (BT)
81       return;
82     BT.reset(new BugType(this, name, categories::UnixAPI));
83   }
84   void ReportOpenBug(CheckerContext &C,
85                      ProgramStateRef State,
86                      const char *Msg,
87                      SourceRange SR) const;
88 };
89 } //end anonymous namespace
90 
91 //===----------------------------------------------------------------------===//
92 // "open" (man 2 open)
93 //===----------------------------------------------------------------------===//
94 
95 void UnixAPIChecker::ReportOpenBug(CheckerContext &C,
96                                    ProgramStateRef State,
97                                    const char *Msg,
98                                    SourceRange SR) const {
99   ExplodedNode *N = C.generateErrorNode(State);
100   if (!N)
101     return;
102 
103   LazyInitialize(BT_open, "Improper use of 'open'");
104 
105   auto Report = llvm::make_unique<BugReport>(*BT_open, Msg, N);
106   Report->addRange(SR);
107   C.emitReport(std::move(Report));
108 }
109 
110 void UnixAPIChecker::CheckOpen(CheckerContext &C, const CallExpr *CE) const {
111   CheckOpenVariant(C, CE, OpenVariant::Open);
112 }
113 
114 void UnixAPIChecker::CheckOpenAt(CheckerContext &C, const CallExpr *CE) const {
115   CheckOpenVariant(C, CE, OpenVariant::OpenAt);
116 }
117 
118 void UnixAPIChecker::CheckOpenVariant(CheckerContext &C,
119                                       const CallExpr *CE,
120                                       OpenVariant Variant) const {
121   // The index of the argument taking the flags open flags (O_RDONLY,
122   // O_WRONLY, O_CREAT, etc.),
123   unsigned int FlagsArgIndex;
124   const char *VariantName;
125   switch (Variant) {
126   case OpenVariant::Open:
127     FlagsArgIndex = 1;
128     VariantName = "open";
129     break;
130   case OpenVariant::OpenAt:
131     FlagsArgIndex = 2;
132     VariantName = "openat";
133     break;
134   };
135 
136   // All calls should at least provide arguments up to the 'flags' parameter.
137   unsigned int MinArgCount = FlagsArgIndex + 1;
138 
139   // If the flags has O_CREAT set then open/openat() require an additional
140   // argument specifying the file mode (permission bits) for the created file.
141   unsigned int CreateModeArgIndex = FlagsArgIndex + 1;
142 
143   // The create mode argument should be the last argument.
144   unsigned int MaxArgCount = CreateModeArgIndex + 1;
145 
146   ProgramStateRef state = C.getState();
147 
148   if (CE->getNumArgs() < MinArgCount) {
149     // The frontend should issue a warning for this case, so this is a sanity
150     // check.
151     return;
152   } else if (CE->getNumArgs() == MaxArgCount) {
153     const Expr *Arg = CE->getArg(CreateModeArgIndex);
154     QualType QT = Arg->getType();
155     if (!QT->isIntegerType()) {
156       SmallString<256> SBuf;
157       llvm::raw_svector_ostream OS(SBuf);
158       OS << "The " << CreateModeArgIndex + 1
159          << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
160          << " argument to '" << VariantName << "' is not an integer";
161 
162       ReportOpenBug(C, state,
163                     SBuf.c_str(),
164                     Arg->getSourceRange());
165       return;
166     }
167   } else if (CE->getNumArgs() > MaxArgCount) {
168     SmallString<256> SBuf;
169     llvm::raw_svector_ostream OS(SBuf);
170     OS << "Call to '" << VariantName << "' with more than " << MaxArgCount
171        << " arguments";
172 
173     ReportOpenBug(C, state,
174                   SBuf.c_str(),
175                   CE->getArg(MaxArgCount)->getSourceRange());
176     return;
177   }
178 
179   // The definition of O_CREAT is platform specific.  We need a better way
180   // of querying this information from the checking environment.
181   if (!Val_O_CREAT.hasValue()) {
182     if (C.getASTContext().getTargetInfo().getTriple().getVendor()
183                                                       == llvm::Triple::Apple)
184       Val_O_CREAT = 0x0200;
185     else {
186       // FIXME: We need a more general way of getting the O_CREAT value.
187       // We could possibly grovel through the preprocessor state, but
188       // that would require passing the Preprocessor object to the ExprEngine.
189       // See also: MallocChecker.cpp / M_ZERO.
190       return;
191     }
192   }
193 
194   // Now check if oflags has O_CREAT set.
195   const Expr *oflagsEx = CE->getArg(FlagsArgIndex);
196   const SVal V = C.getSVal(oflagsEx);
197   if (!V.getAs<NonLoc>()) {
198     // The case where 'V' can be a location can only be due to a bad header,
199     // so in this case bail out.
200     return;
201   }
202   NonLoc oflags = V.castAs<NonLoc>();
203   NonLoc ocreateFlag = C.getSValBuilder()
204       .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
205   SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
206                                                       oflags, ocreateFlag,
207                                                       oflagsEx->getType());
208   if (maskedFlagsUC.isUnknownOrUndef())
209     return;
210   DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
211 
212   // Check if maskedFlags is non-zero.
213   ProgramStateRef trueState, falseState;
214   std::tie(trueState, falseState) = state->assume(maskedFlags);
215 
216   // Only emit an error if the value of 'maskedFlags' is properly
217   // constrained;
218   if (!(trueState && !falseState))
219     return;
220 
221   if (CE->getNumArgs() < MaxArgCount) {
222     SmallString<256> SBuf;
223     llvm::raw_svector_ostream OS(SBuf);
224     OS << "Call to '" << VariantName << "' requires a "
225        << CreateModeArgIndex + 1
226        << llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
227        << " argument when the 'O_CREAT' flag is set";
228     ReportOpenBug(C, trueState,
229                   SBuf.c_str(),
230                   oflagsEx->getSourceRange());
231   }
232 }
233 
234 //===----------------------------------------------------------------------===//
235 // pthread_once
236 //===----------------------------------------------------------------------===//
237 
238 void UnixAPIChecker::CheckPthreadOnce(CheckerContext &C,
239                                       const CallExpr *CE) const {
240 
241   // This is similar to 'CheckDispatchOnce' in the MacOSXAPIChecker.
242   // They can possibly be refactored.
243 
244   if (CE->getNumArgs() < 1)
245     return;
246 
247   // Check if the first argument is stack allocated.  If so, issue a warning
248   // because that's likely to be bad news.
249   ProgramStateRef state = C.getState();
250   const MemRegion *R = C.getSVal(CE->getArg(0)).getAsRegion();
251   if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
252     return;
253 
254   ExplodedNode *N = C.generateErrorNode(state);
255   if (!N)
256     return;
257 
258   SmallString<256> S;
259   llvm::raw_svector_ostream os(S);
260   os << "Call to 'pthread_once' uses";
261   if (const VarRegion *VR = dyn_cast<VarRegion>(R))
262     os << " the local variable '" << VR->getDecl()->getName() << '\'';
263   else
264     os << " stack allocated memory";
265   os << " for the \"control\" value.  Using such transient memory for "
266   "the control value is potentially dangerous.";
267   if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
268     os << "  Perhaps you intended to declare the variable as 'static'?";
269 
270   LazyInitialize(BT_pthreadOnce, "Improper use of 'pthread_once'");
271 
272   auto report = llvm::make_unique<BugReport>(*BT_pthreadOnce, os.str(), N);
273   report->addRange(CE->getArg(0)->getSourceRange());
274   C.emitReport(std::move(report));
275 }
276 
277 //===----------------------------------------------------------------------===//
278 // "calloc", "malloc", "realloc", "reallocf", "alloca" and "valloc"
279 // with allocation size 0
280 //===----------------------------------------------------------------------===//
281 // FIXME: Eventually these should be rolled into the MallocChecker, but right now
282 // they're more basic and valuable for widespread use.
283 
284 // Returns true if we try to do a zero byte allocation, false otherwise.
285 // Fills in trueState and falseState.
286 static bool IsZeroByteAllocation(ProgramStateRef state,
287                                 const SVal argVal,
288                                 ProgramStateRef *trueState,
289                                 ProgramStateRef *falseState) {
290   std::tie(*trueState, *falseState) =
291     state->assume(argVal.castAs<DefinedSVal>());
292 
293   return (*falseState && !*trueState);
294 }
295 
296 // Generates an error report, indicating that the function whose name is given
297 // will perform a zero byte allocation.
298 // Returns false if an error occurred, true otherwise.
299 bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
300                                               ProgramStateRef falseState,
301                                               const Expr *arg,
302                                               const char *fn_name) const {
303   ExplodedNode *N = C.generateErrorNode(falseState);
304   if (!N)
305     return false;
306 
307   LazyInitialize(BT_mallocZero,
308                  "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
309 
310   SmallString<256> S;
311   llvm::raw_svector_ostream os(S);
312   os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
313   auto report = llvm::make_unique<BugReport>(*BT_mallocZero, os.str(), N);
314 
315   report->addRange(arg->getSourceRange());
316   bugreporter::trackExpressionValue(N, arg, *report);
317   C.emitReport(std::move(report));
318 
319   return true;
320 }
321 
322 // Does a basic check for 0-sized allocations suitable for most of the below
323 // functions (modulo "calloc")
324 void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
325                                           const CallExpr *CE,
326                                           const unsigned numArgs,
327                                           const unsigned sizeArg,
328                                           const char *fn) const {
329   // Sanity check for the correct number of arguments
330   if (CE->getNumArgs() != numArgs)
331     return;
332 
333   // Check if the allocation size is 0.
334   ProgramStateRef state = C.getState();
335   ProgramStateRef trueState = nullptr, falseState = nullptr;
336   const Expr *arg = CE->getArg(sizeArg);
337   SVal argVal = C.getSVal(arg);
338 
339   if (argVal.isUnknownOrUndef())
340     return;
341 
342   // Is the value perfectly constrained to zero?
343   if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
344     (void) ReportZeroByteAllocation(C, falseState, arg, fn);
345     return;
346   }
347   // Assume the value is non-zero going forward.
348   assert(trueState);
349   if (trueState != state)
350     C.addTransition(trueState);
351 }
352 
353 void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
354                                      const CallExpr *CE) const {
355   unsigned int nArgs = CE->getNumArgs();
356   if (nArgs != 2)
357     return;
358 
359   ProgramStateRef state = C.getState();
360   ProgramStateRef trueState = nullptr, falseState = nullptr;
361 
362   unsigned int i;
363   for (i = 0; i < nArgs; i++) {
364     const Expr *arg = CE->getArg(i);
365     SVal argVal = C.getSVal(arg);
366     if (argVal.isUnknownOrUndef()) {
367       if (i == 0)
368         continue;
369       else
370         return;
371     }
372 
373     if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
374       if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
375         return;
376       else if (i == 0)
377         continue;
378       else
379         return;
380     }
381   }
382 
383   // Assume the value is non-zero going forward.
384   assert(trueState);
385   if (trueState != state)
386     C.addTransition(trueState);
387 }
388 
389 void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
390                                      const CallExpr *CE) const {
391   BasicAllocationCheck(C, CE, 1, 0, "malloc");
392 }
393 
394 void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
395                                       const CallExpr *CE) const {
396   BasicAllocationCheck(C, CE, 2, 1, "realloc");
397 }
398 
399 void UnixAPIChecker::CheckReallocfZero(CheckerContext &C,
400                                        const CallExpr *CE) const {
401   BasicAllocationCheck(C, CE, 2, 1, "reallocf");
402 }
403 
404 void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
405                                      const CallExpr *CE) const {
406   BasicAllocationCheck(C, CE, 1, 0, "alloca");
407 }
408 
409 void UnixAPIChecker::CheckAllocaWithAlignZero(CheckerContext &C,
410                                               const CallExpr *CE) const {
411   BasicAllocationCheck(C, CE, 2, 0, "__builtin_alloca_with_align");
412 }
413 
414 void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
415                                      const CallExpr *CE) const {
416   BasicAllocationCheck(C, CE, 1, 0, "valloc");
417 }
418 
419 
420 //===----------------------------------------------------------------------===//
421 // Central dispatch function.
422 //===----------------------------------------------------------------------===//
423 
424 void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
425                                   CheckerContext &C) const {
426   const FunctionDecl *FD = C.getCalleeDecl(CE);
427   if (!FD || FD->getKind() != Decl::Function)
428     return;
429 
430   // Don't treat functions in namespaces with the same name a Unix function
431   // as a call to the Unix function.
432   const DeclContext *NamespaceCtx = FD->getEnclosingNamespaceContext();
433   if (NamespaceCtx && isa<NamespaceDecl>(NamespaceCtx))
434     return;
435 
436   StringRef FName = C.getCalleeName(FD);
437   if (FName.empty())
438     return;
439 
440   if (CheckMisuse) {
441     if (SubChecker SC =
442             llvm::StringSwitch<SubChecker>(FName)
443                 .Case("open", &UnixAPIChecker::CheckOpen)
444                 .Case("openat", &UnixAPIChecker::CheckOpenAt)
445                 .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
446                 .Default(nullptr)) {
447       (this->*SC)(C, CE);
448     }
449   }
450   if (CheckPortability) {
451     if (SubChecker SC =
452             llvm::StringSwitch<SubChecker>(FName)
453                 .Case("calloc", &UnixAPIChecker::CheckCallocZero)
454                 .Case("malloc", &UnixAPIChecker::CheckMallocZero)
455                 .Case("realloc", &UnixAPIChecker::CheckReallocZero)
456                 .Case("reallocf", &UnixAPIChecker::CheckReallocfZero)
457                 .Cases("alloca", "__builtin_alloca",
458                        &UnixAPIChecker::CheckAllocaZero)
459                 .Case("__builtin_alloca_with_align",
460                       &UnixAPIChecker::CheckAllocaWithAlignZero)
461                 .Case("valloc", &UnixAPIChecker::CheckVallocZero)
462                 .Default(nullptr)) {
463       (this->*SC)(C, CE);
464     }
465   }
466 }
467 
468 //===----------------------------------------------------------------------===//
469 // Registration.
470 //===----------------------------------------------------------------------===//
471 
472 #define REGISTER_CHECKER(Name)                                                 \
473   void ento::registerUnixAPI##Name##Checker(CheckerManager &mgr) {             \
474     mgr.registerChecker<UnixAPIChecker>()->Check##Name = true;                 \
475   }
476 
477 REGISTER_CHECKER(Misuse)
478 REGISTER_CHECKER(Portability)
479