xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp (revision db4d5f7048a26a7708821e46095742aecfd8ba46)
1 //=== StdLibraryFunctionsChecker.cpp - Model standard functions -*- 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 checker improves modeling of a few simple library functions.
10 //
11 // This checker provides a specification format - `Summary' - and
12 // contains descriptions of some library functions in this format. Each
13 // specification contains a list of branches for splitting the program state
14 // upon call, and range constraints on argument and return-value symbols that
15 // are satisfied on each branch. This spec can be expanded to include more
16 // items, like external effects of the function.
17 //
18 // The main difference between this approach and the body farms technique is
19 // in more explicit control over how many branches are produced. For example,
20 // consider standard C function `ispunct(int x)', which returns a non-zero value
21 // iff `x' is a punctuation character, that is, when `x' is in range
22 //   ['!', '/']   [':', '@']  U  ['[', '\`']  U  ['{', '~'].
23 // `Summary' provides only two branches for this function. However,
24 // any attempt to describe this range with if-statements in the body farm
25 // would result in many more branches. Because each branch needs to be analyzed
26 // independently, this significantly reduces performance. Additionally,
27 // once we consider a branch on which `x' is in range, say, ['!', '/'],
28 // we assume that such branch is an important separate path through the program,
29 // which may lead to false positives because considering this particular path
30 // was not consciously intended, and therefore it might have been unreachable.
31 //
32 // This checker uses eval::Call for modeling pure functions (functions without
33 // side effets), for which their `Summary' is a precise model. This avoids
34 // unnecessary invalidation passes. Conflicts with other checkers are unlikely
35 // because if the function has no other effects, other checkers would probably
36 // never want to improve upon the modeling done by this checker.
37 //
38 // Non-pure functions, for which only partial improvement over the default
39 // behavior is expected, are modeled via check::PostCall, non-intrusively.
40 //
41 // The following standard C functions are currently supported:
42 //
43 //   fgetc      getline   isdigit   isupper
44 //   fread      isalnum   isgraph   isxdigit
45 //   fwrite     isalpha   islower   read
46 //   getc       isascii   isprint   write
47 //   getchar    isblank   ispunct
48 //   getdelim   iscntrl   isspace
49 //
50 //===----------------------------------------------------------------------===//
51 
52 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
53 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
54 #include "clang/StaticAnalyzer/Core/Checker.h"
55 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
56 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
57 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
58 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
59 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
60 
61 using namespace clang;
62 using namespace clang::ento;
63 
64 namespace {
65 class StdLibraryFunctionsChecker
66     : public Checker<check::PreCall, check::PostCall, eval::Call> {
67 
68   class Summary;
69 
70   /// Specify how much the analyzer engine should entrust modeling this function
71   /// to us. If he doesn't, he performs additional invalidations.
72   enum InvalidationKind { NoEvalCall, EvalCallAsPure };
73 
74   // The universal integral type to use in value range descriptions.
75   // Unsigned to make sure overflows are well-defined.
76   typedef uint64_t RangeInt;
77 
78   /// Normally, describes a single range constraint, eg. {{0, 1}, {3, 4}} is
79   /// a non-negative integer, which less than 5 and not equal to 2. For
80   /// `ComparesToArgument', holds information about how exactly to compare to
81   /// the argument.
82   typedef std::vector<std::pair<RangeInt, RangeInt>> IntRangeVector;
83 
84   /// A reference to an argument or return value by its number.
85   /// ArgNo in CallExpr and CallEvent is defined as Unsigned, but
86   /// obviously uint32_t should be enough for all practical purposes.
87   typedef uint32_t ArgNo;
88   static const ArgNo Ret;
89 
90   class ValueConstraint;
91 
92   // Pointer to the ValueConstraint. We need a copyable, polymorphic and
93   // default initialize able type (vector needs that). A raw pointer was good,
94   // however, we cannot default initialize that. unique_ptr makes the Summary
95   // class non-copyable, therefore not an option. Releasing the copyability
96   // requirement would render the initialization of the Summary map infeasible.
97   using ValueConstraintPtr = std::shared_ptr<ValueConstraint>;
98 
99   /// Polymorphic base class that represents a constraint on a given argument
100   /// (or return value) of a function. Derived classes implement different kind
101   /// of constraints, e.g range constraints or correlation between two
102   /// arguments.
103   class ValueConstraint {
104   public:
105     ValueConstraint(ArgNo ArgN) : ArgN(ArgN) {}
106     virtual ~ValueConstraint() {}
107     /// Apply the effects of the constraint on the given program state. If null
108     /// is returned then the constraint is not feasible.
109     virtual ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
110                                   const Summary &Summary,
111                                   CheckerContext &C) const = 0;
112     virtual ValueConstraintPtr negate() const {
113       llvm_unreachable("Not implemented");
114     };
115 
116     // Check whether the constraint is malformed or not. It is malformed if the
117     // specified argument has a mismatch with the given FunctionDecl (e.g. the
118     // arg number is out-of-range of the function's argument list).
119     bool checkValidity(const FunctionDecl *FD) const {
120       const bool ValidArg = ArgN == Ret || ArgN < FD->getNumParams();
121       assert(ValidArg && "Arg out of range!");
122       if (!ValidArg)
123         return false;
124       // Subclasses may further refine the validation.
125       return checkSpecificValidity(FD);
126     }
127     ArgNo getArgNo() const { return ArgN; }
128 
129   protected:
130     ArgNo ArgN; // Argument to which we apply the constraint.
131 
132     /// Do polymorphic sanity check on the constraint.
133     virtual bool checkSpecificValidity(const FunctionDecl *FD) const {
134       return true;
135     }
136   };
137 
138   /// Given a range, should the argument stay inside or outside this range?
139   enum RangeKind { OutOfRange, WithinRange };
140 
141   /// Encapsulates a single range on a single symbol within a branch.
142   class RangeConstraint : public ValueConstraint {
143     RangeKind Kind;      // Kind of range definition.
144     IntRangeVector Args; // Polymorphic arguments.
145 
146   public:
147     RangeConstraint(ArgNo ArgN, RangeKind Kind, const IntRangeVector &Args)
148         : ValueConstraint(ArgN), Kind(Kind), Args(Args) {}
149 
150     const IntRangeVector &getRanges() const {
151       return Args;
152     }
153 
154   private:
155     ProgramStateRef applyAsOutOfRange(ProgramStateRef State,
156                                       const CallEvent &Call,
157                                       const Summary &Summary) const;
158     ProgramStateRef applyAsWithinRange(ProgramStateRef State,
159                                        const CallEvent &Call,
160                                        const Summary &Summary) const;
161   public:
162     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
163                           const Summary &Summary,
164                           CheckerContext &C) const override {
165       switch (Kind) {
166       case OutOfRange:
167         return applyAsOutOfRange(State, Call, Summary);
168       case WithinRange:
169         return applyAsWithinRange(State, Call, Summary);
170       }
171       llvm_unreachable("Unknown range kind!");
172     }
173 
174     ValueConstraintPtr negate() const override {
175       RangeConstraint Tmp(*this);
176       switch (Kind) {
177       case OutOfRange:
178         Tmp.Kind = WithinRange;
179         break;
180       case WithinRange:
181         Tmp.Kind = OutOfRange;
182         break;
183       }
184       return std::make_shared<RangeConstraint>(Tmp);
185     }
186 
187     bool checkSpecificValidity(const FunctionDecl *FD) const override {
188       const bool ValidArg =
189           getArgType(FD, ArgN)->isIntegralType(FD->getASTContext());
190       assert(ValidArg &&
191              "This constraint should be applied on an integral type");
192       return ValidArg;
193     }
194   };
195 
196   class ComparisonConstraint : public ValueConstraint {
197     BinaryOperator::Opcode Opcode;
198     ArgNo OtherArgN;
199 
200   public:
201     ComparisonConstraint(ArgNo ArgN, BinaryOperator::Opcode Opcode,
202                          ArgNo OtherArgN)
203         : ValueConstraint(ArgN), Opcode(Opcode), OtherArgN(OtherArgN) {}
204     ArgNo getOtherArgNo() const { return OtherArgN; }
205     BinaryOperator::Opcode getOpcode() const { return Opcode; }
206     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
207                           const Summary &Summary,
208                           CheckerContext &C) const override;
209   };
210 
211   class NotNullConstraint : public ValueConstraint {
212     using ValueConstraint::ValueConstraint;
213     // This variable has a role when we negate the constraint.
214     bool CannotBeNull = true;
215 
216   public:
217     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
218                           const Summary &Summary,
219                           CheckerContext &C) const override {
220       SVal V = getArgSVal(Call, getArgNo());
221       if (V.isUndef())
222         return State;
223 
224       DefinedOrUnknownSVal L = V.castAs<DefinedOrUnknownSVal>();
225       if (!L.getAs<Loc>())
226         return State;
227 
228       return State->assume(L, CannotBeNull);
229     }
230 
231     ValueConstraintPtr negate() const override {
232       NotNullConstraint Tmp(*this);
233       Tmp.CannotBeNull = !this->CannotBeNull;
234       return std::make_shared<NotNullConstraint>(Tmp);
235     }
236 
237     bool checkSpecificValidity(const FunctionDecl *FD) const override {
238       const bool ValidArg = getArgType(FD, ArgN)->isPointerType();
239       assert(ValidArg &&
240              "This constraint should be applied only on a pointer type");
241       return ValidArg;
242     }
243   };
244 
245   // Represents a buffer argument with an additional size argument.
246   // E.g. the first two arguments here:
247   //   ctime_s(char *buffer, rsize_t bufsz, const time_t *time);
248   // Another example:
249   //   size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
250   //   // Here, ptr is the buffer, and its minimum size is `size * nmemb`.
251   class BufferSizeConstraint : public ValueConstraint {
252     // The argument which holds the size of the buffer.
253     ArgNo SizeArgN;
254     // The argument which is a multiplier to size. This is set in case of
255     // `fread` like functions where the size is computed as a multiplication of
256     // two arguments.
257     llvm::Optional<ArgNo> SizeMultiplierArgN;
258     // The operator we use in apply. This is negated in negate().
259     BinaryOperator::Opcode Op = BO_LE;
260 
261   public:
262     BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize)
263         : ValueConstraint(Buffer), SizeArgN(BufSize) {}
264 
265     BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize, ArgNo BufSizeMultiplier)
266         : ValueConstraint(Buffer), SizeArgN(BufSize),
267           SizeMultiplierArgN(BufSizeMultiplier) {}
268 
269     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
270                           const Summary &Summary,
271                           CheckerContext &C) const override {
272       SValBuilder &SvalBuilder = C.getSValBuilder();
273       // The buffer argument.
274       SVal BufV = getArgSVal(Call, getArgNo());
275       // The size argument.
276       SVal SizeV = getArgSVal(Call, SizeArgN);
277       // Multiply with another argument if given.
278       if (SizeMultiplierArgN) {
279         SVal SizeMulV = getArgSVal(Call, *SizeMultiplierArgN);
280         SizeV = SvalBuilder.evalBinOp(State, BO_Mul, SizeV, SizeMulV,
281                                       Summary.getArgType(SizeArgN));
282       }
283       // The dynamic size of the buffer argument, got from the analyzer engine.
284       SVal BufDynSize = getDynamicSizeWithOffset(State, BufV);
285 
286       SVal Feasible = SvalBuilder.evalBinOp(State, Op, SizeV, BufDynSize,
287                                             SvalBuilder.getContext().BoolTy);
288       if (auto F = Feasible.getAs<DefinedOrUnknownSVal>())
289         return State->assume(*F, true);
290 
291       // We can get here only if the size argument or the dynamic size is
292       // undefined. But the dynamic size should never be undefined, only
293       // unknown. So, here, the size of the argument is undefined, i.e. we
294       // cannot apply the constraint. Actually, other checkers like
295       // CallAndMessage should catch this situation earlier, because we call a
296       // function with an uninitialized argument.
297       llvm_unreachable("Size argument or the dynamic size is Undefined");
298     }
299 
300     ValueConstraintPtr negate() const override {
301       BufferSizeConstraint Tmp(*this);
302       Tmp.Op = BinaryOperator::negateComparisonOp(Op);
303       return std::make_shared<BufferSizeConstraint>(Tmp);
304     }
305   };
306 
307   /// The complete list of constraints that defines a single branch.
308   typedef std::vector<ValueConstraintPtr> ConstraintSet;
309 
310   using ArgTypes = std::vector<QualType>;
311 
312   // A placeholder type, we use it whenever we do not care about the concrete
313   // type in a Signature.
314   const QualType Irrelevant{};
315   bool static isIrrelevant(QualType T) { return T.isNull(); }
316 
317   // The signature of a function we want to describe with a summary. This is a
318   // concessive signature, meaning there may be irrelevant types in the
319   // signature which we do not check against a function with concrete types.
320   struct Signature {
321     const ArgTypes ArgTys;
322     const QualType RetTy;
323     Signature(ArgTypes ArgTys, QualType RetTy) : ArgTys(ArgTys), RetTy(RetTy) {
324       assertRetTypeSuitableForSignature(RetTy);
325       for (size_t I = 0, E = ArgTys.size(); I != E; ++I) {
326         QualType ArgTy = ArgTys[I];
327         assertArgTypeSuitableForSignature(ArgTy);
328       }
329     }
330     bool matches(const FunctionDecl *FD) const;
331 
332   private:
333     static void assertArgTypeSuitableForSignature(QualType T) {
334       assert((T.isNull() || !T->isVoidType()) &&
335              "We should have no void types in the spec");
336       assert((T.isNull() || T.isCanonical()) &&
337              "We should only have canonical types in the spec");
338     }
339     static void assertRetTypeSuitableForSignature(QualType T) {
340       assert((T.isNull() || T.isCanonical()) &&
341              "We should only have canonical types in the spec");
342     }
343   };
344 
345   static QualType getArgType(const FunctionDecl *FD, ArgNo ArgN) {
346     assert(FD && "Function must be set");
347     QualType T = (ArgN == Ret)
348                      ? FD->getReturnType().getCanonicalType()
349                      : FD->getParamDecl(ArgN)->getType().getCanonicalType();
350     return T;
351   }
352 
353   using Cases = std::vector<ConstraintSet>;
354 
355   /// A summary includes information about
356   ///   * function prototype (signature)
357   ///   * approach to invalidation,
358   ///   * a list of branches - a list of list of ranges -
359   ///     A branch represents a path in the exploded graph of a function (which
360   ///     is a tree). So, a branch is a series of assumptions. In other words,
361   ///     branches represent split states and additional assumptions on top of
362   ///     the splitting assumption.
363   ///     For example, consider the branches in `isalpha(x)`
364   ///       Branch 1)
365   ///         x is in range ['A', 'Z'] or in ['a', 'z']
366   ///         then the return value is not 0. (I.e. out-of-range [0, 0])
367   ///       Branch 2)
368   ///         x is out-of-range ['A', 'Z'] and out-of-range ['a', 'z']
369   ///         then the return value is 0.
370   ///   * a list of argument constraints, that must be true on every branch.
371   ///     If these constraints are not satisfied that means a fatal error
372   ///     usually resulting in undefined behaviour.
373   ///
374   /// Application of a summary:
375   ///   The signature and argument constraints together contain information
376   ///   about which functions are handled by the summary. The signature can use
377   ///   "wildcards", i.e. Irrelevant types. Irrelevant type of a parameter in
378   ///   a signature means that type is not compared to the type of the parameter
379   ///   in the found FunctionDecl. Argument constraints may specify additional
380   ///   rules for the given parameter's type, those rules are checked once the
381   ///   signature is matched.
382   class Summary {
383     const Signature Sign;
384     const InvalidationKind InvalidationKd;
385     Cases CaseConstraints;
386     ConstraintSet ArgConstraints;
387 
388     // The function to which the summary applies. This is set after lookup and
389     // match to the signature.
390     const FunctionDecl *FD = nullptr;
391 
392   public:
393     Summary(ArgTypes ArgTys, QualType RetTy, InvalidationKind InvalidationKd)
394         : Sign(ArgTys, RetTy), InvalidationKd(InvalidationKd) {}
395 
396     Summary &Case(ConstraintSet&& CS) {
397       CaseConstraints.push_back(std::move(CS));
398       return *this;
399     }
400     Summary &ArgConstraint(ValueConstraintPtr VC) {
401       ArgConstraints.push_back(VC);
402       return *this;
403     }
404 
405     InvalidationKind getInvalidationKd() const { return InvalidationKd; }
406     const Cases &getCaseConstraints() const { return CaseConstraints; }
407     const ConstraintSet &getArgConstraints() const { return ArgConstraints; }
408 
409     QualType getArgType(ArgNo ArgN) const {
410       return StdLibraryFunctionsChecker::getArgType(FD, ArgN);
411     }
412 
413     // Returns true if the summary should be applied to the given function.
414     // And if yes then store the function declaration.
415     bool matchesAndSet(const FunctionDecl *FD) {
416       bool Result = Sign.matches(FD) && validateByConstraints(FD);
417       if (Result) {
418         assert(!this->FD && "FD must not be set more than once");
419         this->FD = FD;
420       }
421       return Result;
422     }
423 
424   private:
425     // Once we know the exact type of the function then do sanity check on all
426     // the given constraints.
427     bool validateByConstraints(const FunctionDecl *FD) const {
428       for (const ConstraintSet &Case : CaseConstraints)
429         for (const ValueConstraintPtr &Constraint : Case)
430           if (!Constraint->checkValidity(FD))
431             return false;
432       for (const ValueConstraintPtr &Constraint : ArgConstraints)
433         if (!Constraint->checkValidity(FD))
434           return false;
435       return true;
436     }
437   };
438 
439   // The map of all functions supported by the checker. It is initialized
440   // lazily, and it doesn't change after initialization.
441   using FunctionSummaryMapType = llvm::DenseMap<const FunctionDecl *, Summary>;
442   mutable FunctionSummaryMapType FunctionSummaryMap;
443 
444   mutable std::unique_ptr<BugType> BT_InvalidArg;
445 
446   static SVal getArgSVal(const CallEvent &Call, ArgNo ArgN) {
447     return ArgN == Ret ? Call.getReturnValue() : Call.getArgSVal(ArgN);
448   }
449 
450 public:
451   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
452   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
453   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
454 
455   enum CheckKind {
456     CK_StdCLibraryFunctionArgsChecker,
457     CK_StdCLibraryFunctionsTesterChecker,
458     CK_NumCheckKinds
459   };
460   DefaultBool ChecksEnabled[CK_NumCheckKinds];
461   CheckerNameRef CheckNames[CK_NumCheckKinds];
462 
463   bool DisplayLoadedSummaries = false;
464   bool ModelPOSIX = false;
465 
466 private:
467   Optional<Summary> findFunctionSummary(const FunctionDecl *FD,
468                                         CheckerContext &C) const;
469   Optional<Summary> findFunctionSummary(const CallEvent &Call,
470                                         CheckerContext &C) const;
471 
472   void initFunctionSummaries(CheckerContext &C) const;
473 
474   void reportBug(const CallEvent &Call, ExplodedNode *N,
475                  CheckerContext &C) const {
476     if (!ChecksEnabled[CK_StdCLibraryFunctionArgsChecker])
477       return;
478     // TODO Add detailed diagnostic.
479     StringRef Msg = "Function argument constraint is not satisfied";
480     if (!BT_InvalidArg)
481       BT_InvalidArg = std::make_unique<BugType>(
482           CheckNames[CK_StdCLibraryFunctionArgsChecker],
483           "Unsatisfied argument constraints", categories::LogicError);
484     auto R = std::make_unique<PathSensitiveBugReport>(*BT_InvalidArg, Msg, N);
485     bugreporter::trackExpressionValue(N, Call.getArgExpr(0), *R);
486     C.emitReport(std::move(R));
487   }
488 };
489 
490 const StdLibraryFunctionsChecker::ArgNo StdLibraryFunctionsChecker::Ret =
491     std::numeric_limits<ArgNo>::max();
492 
493 } // end of anonymous namespace
494 
495 ProgramStateRef StdLibraryFunctionsChecker::RangeConstraint::applyAsOutOfRange(
496     ProgramStateRef State, const CallEvent &Call,
497     const Summary &Summary) const {
498 
499   ProgramStateManager &Mgr = State->getStateManager();
500   SValBuilder &SVB = Mgr.getSValBuilder();
501   BasicValueFactory &BVF = SVB.getBasicValueFactory();
502   ConstraintManager &CM = Mgr.getConstraintManager();
503   QualType T = Summary.getArgType(getArgNo());
504   SVal V = getArgSVal(Call, getArgNo());
505 
506   if (auto N = V.getAs<NonLoc>()) {
507     const IntRangeVector &R = getRanges();
508     size_t E = R.size();
509     for (size_t I = 0; I != E; ++I) {
510       const llvm::APSInt &Min = BVF.getValue(R[I].first, T);
511       const llvm::APSInt &Max = BVF.getValue(R[I].second, T);
512       assert(Min <= Max);
513       State = CM.assumeInclusiveRange(State, *N, Min, Max, false);
514       if (!State)
515         break;
516     }
517   }
518 
519   return State;
520 }
521 
522 ProgramStateRef StdLibraryFunctionsChecker::RangeConstraint::applyAsWithinRange(
523     ProgramStateRef State, const CallEvent &Call,
524     const Summary &Summary) const {
525 
526   ProgramStateManager &Mgr = State->getStateManager();
527   SValBuilder &SVB = Mgr.getSValBuilder();
528   BasicValueFactory &BVF = SVB.getBasicValueFactory();
529   ConstraintManager &CM = Mgr.getConstraintManager();
530   QualType T = Summary.getArgType(getArgNo());
531   SVal V = getArgSVal(Call, getArgNo());
532 
533   // "WithinRange R" is treated as "outside [T_MIN, T_MAX] \ R".
534   // We cut off [T_MIN, min(R) - 1] and [max(R) + 1, T_MAX] if necessary,
535   // and then cut away all holes in R one by one.
536   //
537   // E.g. consider a range list R as [A, B] and [C, D]
538   // -------+--------+------------------+------------+----------->
539   //        A        B                  C            D
540   // Then we assume that the value is not in [-inf, A - 1],
541   // then not in [D + 1, +inf], then not in [B + 1, C - 1]
542   if (auto N = V.getAs<NonLoc>()) {
543     const IntRangeVector &R = getRanges();
544     size_t E = R.size();
545 
546     const llvm::APSInt &MinusInf = BVF.getMinValue(T);
547     const llvm::APSInt &PlusInf = BVF.getMaxValue(T);
548 
549     const llvm::APSInt &Left = BVF.getValue(R[0].first - 1ULL, T);
550     if (Left != PlusInf) {
551       assert(MinusInf <= Left);
552       State = CM.assumeInclusiveRange(State, *N, MinusInf, Left, false);
553       if (!State)
554         return nullptr;
555     }
556 
557     const llvm::APSInt &Right = BVF.getValue(R[E - 1].second + 1ULL, T);
558     if (Right != MinusInf) {
559       assert(Right <= PlusInf);
560       State = CM.assumeInclusiveRange(State, *N, Right, PlusInf, false);
561       if (!State)
562         return nullptr;
563     }
564 
565     for (size_t I = 1; I != E; ++I) {
566       const llvm::APSInt &Min = BVF.getValue(R[I - 1].second + 1ULL, T);
567       const llvm::APSInt &Max = BVF.getValue(R[I].first - 1ULL, T);
568       if (Min <= Max) {
569         State = CM.assumeInclusiveRange(State, *N, Min, Max, false);
570         if (!State)
571           return nullptr;
572       }
573     }
574   }
575 
576   return State;
577 }
578 
579 ProgramStateRef StdLibraryFunctionsChecker::ComparisonConstraint::apply(
580     ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
581     CheckerContext &C) const {
582 
583   ProgramStateManager &Mgr = State->getStateManager();
584   SValBuilder &SVB = Mgr.getSValBuilder();
585   QualType CondT = SVB.getConditionType();
586   QualType T = Summary.getArgType(getArgNo());
587   SVal V = getArgSVal(Call, getArgNo());
588 
589   BinaryOperator::Opcode Op = getOpcode();
590   ArgNo OtherArg = getOtherArgNo();
591   SVal OtherV = getArgSVal(Call, OtherArg);
592   QualType OtherT = Summary.getArgType(OtherArg);
593   // Note: we avoid integral promotion for comparison.
594   OtherV = SVB.evalCast(OtherV, T, OtherT);
595   if (auto CompV = SVB.evalBinOp(State, Op, V, OtherV, CondT)
596                        .getAs<DefinedOrUnknownSVal>())
597     State = State->assume(*CompV, true);
598   return State;
599 }
600 
601 void StdLibraryFunctionsChecker::checkPreCall(const CallEvent &Call,
602                                               CheckerContext &C) const {
603   Optional<Summary> FoundSummary = findFunctionSummary(Call, C);
604   if (!FoundSummary)
605     return;
606 
607   const Summary &Summary = *FoundSummary;
608   ProgramStateRef State = C.getState();
609 
610   ProgramStateRef NewState = State;
611   for (const ValueConstraintPtr &Constraint : Summary.getArgConstraints()) {
612     ProgramStateRef SuccessSt = Constraint->apply(NewState, Call, Summary, C);
613     ProgramStateRef FailureSt =
614         Constraint->negate()->apply(NewState, Call, Summary, C);
615     // The argument constraint is not satisfied.
616     if (FailureSt && !SuccessSt) {
617       if (ExplodedNode *N = C.generateErrorNode(NewState))
618         reportBug(Call, N, C);
619       break;
620     } else {
621       // We will apply the constraint even if we cannot reason about the
622       // argument. This means both SuccessSt and FailureSt can be true. If we
623       // weren't applying the constraint that would mean that symbolic
624       // execution continues on a code whose behaviour is undefined.
625       assert(SuccessSt);
626       NewState = SuccessSt;
627     }
628   }
629   if (NewState && NewState != State)
630     C.addTransition(NewState);
631 }
632 
633 void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call,
634                                                CheckerContext &C) const {
635   Optional<Summary> FoundSummary = findFunctionSummary(Call, C);
636   if (!FoundSummary)
637     return;
638 
639   // Now apply the constraints.
640   const Summary &Summary = *FoundSummary;
641   ProgramStateRef State = C.getState();
642 
643   // Apply case/branch specifications.
644   for (const ConstraintSet &Case : Summary.getCaseConstraints()) {
645     ProgramStateRef NewState = State;
646     for (const ValueConstraintPtr &Constraint : Case) {
647       NewState = Constraint->apply(NewState, Call, Summary, C);
648       if (!NewState)
649         break;
650     }
651 
652     if (NewState && NewState != State)
653       C.addTransition(NewState);
654   }
655 }
656 
657 bool StdLibraryFunctionsChecker::evalCall(const CallEvent &Call,
658                                           CheckerContext &C) const {
659   Optional<Summary> FoundSummary = findFunctionSummary(Call, C);
660   if (!FoundSummary)
661     return false;
662 
663   const Summary &Summary = *FoundSummary;
664   switch (Summary.getInvalidationKd()) {
665   case EvalCallAsPure: {
666     ProgramStateRef State = C.getState();
667     const LocationContext *LC = C.getLocationContext();
668     const auto *CE = cast_or_null<CallExpr>(Call.getOriginExpr());
669     SVal V = C.getSValBuilder().conjureSymbolVal(
670         CE, LC, CE->getType().getCanonicalType(), C.blockCount());
671     State = State->BindExpr(CE, LC, V);
672     C.addTransition(State);
673     return true;
674   }
675   case NoEvalCall:
676     // Summary tells us to avoid performing eval::Call. The function is possibly
677     // evaluated by another checker, or evaluated conservatively.
678     return false;
679   }
680   llvm_unreachable("Unknown invalidation kind!");
681 }
682 
683 bool StdLibraryFunctionsChecker::Signature::matches(
684     const FunctionDecl *FD) const {
685   // Check number of arguments:
686   if (FD->param_size() != ArgTys.size())
687     return false;
688 
689   // Check return type.
690   if (!isIrrelevant(RetTy))
691     if (RetTy != FD->getReturnType().getCanonicalType())
692       return false;
693 
694   // Check argument types.
695   for (size_t I = 0, E = ArgTys.size(); I != E; ++I) {
696     QualType ArgTy = ArgTys[I];
697     if (isIrrelevant(ArgTy))
698       continue;
699     if (ArgTy != FD->getParamDecl(I)->getType().getCanonicalType())
700       return false;
701   }
702 
703   return true;
704 }
705 
706 Optional<StdLibraryFunctionsChecker::Summary>
707 StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD,
708                                                 CheckerContext &C) const {
709   if (!FD)
710     return None;
711 
712   initFunctionSummaries(C);
713 
714   auto FSMI = FunctionSummaryMap.find(FD->getCanonicalDecl());
715   if (FSMI == FunctionSummaryMap.end())
716     return None;
717   return FSMI->second;
718 }
719 
720 Optional<StdLibraryFunctionsChecker::Summary>
721 StdLibraryFunctionsChecker::findFunctionSummary(const CallEvent &Call,
722                                                 CheckerContext &C) const {
723   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
724   if (!FD)
725     return None;
726   return findFunctionSummary(FD, C);
727 }
728 
729 llvm::Optional<QualType> lookupType(StringRef Name, const ASTContext &ACtx) {
730   IdentifierInfo &II = ACtx.Idents.get(Name);
731   auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II);
732   if (LookupRes.size() == 0)
733     return None;
734 
735   // Prioritze typedef declarations.
736   // This is needed in case of C struct typedefs. E.g.:
737   //   typedef struct FILE FILE;
738   // In this case, we have a RecordDecl 'struct FILE' with the name 'FILE' and
739   // we have a TypedefDecl with the name 'FILE'.
740   for (Decl *D : LookupRes)
741     if (auto *TD = dyn_cast<TypedefNameDecl>(D))
742       return ACtx.getTypeDeclType(TD).getCanonicalType();
743 
744   // Find the first TypeDecl.
745   // There maybe cases when a function has the same name as a struct.
746   // E.g. in POSIX: `struct stat` and the function `stat()`:
747   //   int stat(const char *restrict path, struct stat *restrict buf);
748   for (Decl *D : LookupRes)
749     if (auto *TD = dyn_cast<TypeDecl>(D))
750       return ACtx.getTypeDeclType(TD).getCanonicalType();
751   return None;
752 }
753 
754 void StdLibraryFunctionsChecker::initFunctionSummaries(
755     CheckerContext &C) const {
756   if (!FunctionSummaryMap.empty())
757     return;
758 
759   SValBuilder &SVB = C.getSValBuilder();
760   BasicValueFactory &BVF = SVB.getBasicValueFactory();
761   const ASTContext &ACtx = BVF.getContext();
762 
763   // These types are useful for writing specifications quickly,
764   // New specifications should probably introduce more types.
765   // Some types are hard to obtain from the AST, eg. "ssize_t".
766   // In such cases it should be possible to provide multiple variants
767   // of function summary for common cases (eg. ssize_t could be int or long
768   // or long long, so three summary variants would be enough).
769   // Of course, function variants are also useful for C++ overloads.
770   const QualType VoidTy = ACtx.VoidTy;
771   const QualType IntTy = ACtx.IntTy;
772   const QualType UnsignedIntTy = ACtx.UnsignedIntTy;
773   const QualType LongTy = ACtx.LongTy;
774   const QualType LongLongTy = ACtx.LongLongTy;
775   const QualType SizeTy = ACtx.getSizeType();
776 
777   const QualType VoidPtrTy = ACtx.VoidPtrTy; // void *
778   const QualType IntPtrTy = ACtx.getPointerType(IntTy); // int *
779   const QualType UnsignedIntPtrTy =
780       ACtx.getPointerType(UnsignedIntTy); // unsigned int *
781   const QualType VoidPtrRestrictTy =
782       ACtx.getLangOpts().C99 ? ACtx.getRestrictType(VoidPtrTy) // void *restrict
783                              : VoidPtrTy;
784   const QualType ConstVoidPtrTy =
785       ACtx.getPointerType(ACtx.VoidTy.withConst()); // const void *
786   const QualType CharPtrTy = ACtx.getPointerType(ACtx.CharTy); // char *
787   const QualType CharPtrRestrictTy =
788       ACtx.getLangOpts().C99 ? ACtx.getRestrictType(CharPtrTy) // char *restrict
789                              : CharPtrTy;
790   const QualType ConstCharPtrTy =
791       ACtx.getPointerType(ACtx.CharTy.withConst()); // const char *
792   const QualType ConstCharPtrRestrictTy =
793       ACtx.getLangOpts().C99
794           ? ACtx.getRestrictType(ConstCharPtrTy) // const char *restrict
795           : ConstCharPtrTy;
796   const QualType Wchar_tPtrTy = ACtx.getPointerType(ACtx.WCharTy); // wchar_t *
797   const QualType ConstWchar_tPtrTy =
798       ACtx.getPointerType(ACtx.WCharTy.withConst()); // const wchar_t *
799   const QualType ConstVoidPtrRestrictTy =
800       ACtx.getLangOpts().C99
801           ? ACtx.getRestrictType(ConstVoidPtrTy) // const void *restrict
802           : ConstVoidPtrTy;
803 
804   const RangeInt IntMax = BVF.getMaxValue(IntTy).getLimitedValue();
805   const RangeInt UnsignedIntMax =
806       BVF.getMaxValue(UnsignedIntTy).getLimitedValue();
807   const RangeInt LongMax = BVF.getMaxValue(LongTy).getLimitedValue();
808   const RangeInt LongLongMax = BVF.getMaxValue(LongLongTy).getLimitedValue();
809   const RangeInt SizeMax = BVF.getMaxValue(SizeTy).getLimitedValue();
810 
811   // Set UCharRangeMax to min of int or uchar maximum value.
812   // The C standard states that the arguments of functions like isalpha must
813   // be representable as an unsigned char. Their type is 'int', so the max
814   // value of the argument should be min(UCharMax, IntMax). This just happen
815   // to be true for commonly used and well tested instruction set
816   // architectures, but not for others.
817   const RangeInt UCharRangeMax =
818       std::min(BVF.getMaxValue(ACtx.UnsignedCharTy).getLimitedValue(), IntMax);
819 
820   // The platform dependent value of EOF.
821   // Try our best to parse this from the Preprocessor, otherwise fallback to -1.
822   const auto EOFv = [&C]() -> RangeInt {
823     if (const llvm::Optional<int> OptInt =
824             tryExpandAsInteger("EOF", C.getPreprocessor()))
825       return *OptInt;
826     return -1;
827   }();
828 
829   // Auxiliary class to aid adding summaries to the summary map.
830   struct AddToFunctionSummaryMap {
831     const ASTContext &ACtx;
832     FunctionSummaryMapType &Map;
833     bool DisplayLoadedSummaries;
834     AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType &FSM,
835                             bool DisplayLoadedSummaries)
836         : ACtx(ACtx), Map(FSM), DisplayLoadedSummaries(DisplayLoadedSummaries) {
837     }
838 
839     // Add a summary to a FunctionDecl found by lookup. The lookup is performed
840     // by the given Name, and in the global scope. The summary will be attached
841     // to the found FunctionDecl only if the signatures match.
842     void operator()(StringRef Name, Summary S) {
843       IdentifierInfo &II = ACtx.Idents.get(Name);
844       auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II);
845       if (LookupRes.size() == 0)
846         return;
847       for (Decl *D : LookupRes) {
848         if (auto *FD = dyn_cast<FunctionDecl>(D)) {
849           if (S.matchesAndSet(FD)) {
850             auto Res = Map.insert({FD->getCanonicalDecl(), S});
851             assert(Res.second && "Function already has a summary set!");
852             (void)Res;
853             if (DisplayLoadedSummaries) {
854               llvm::errs() << "Loaded summary for: ";
855               FD->print(llvm::errs());
856               llvm::errs() << "\n";
857             }
858             return;
859           }
860         }
861       }
862     }
863     // Add several summaries for the given name.
864     void operator()(StringRef Name, const std::vector<Summary> &Summaries) {
865       for (const Summary &S : Summaries)
866         operator()(Name, S);
867     }
868   } addToFunctionSummaryMap(ACtx, FunctionSummaryMap, DisplayLoadedSummaries);
869 
870   // We are finally ready to define specifications for all supported functions.
871   //
872   // The signature needs to have the correct number of arguments.
873   // However, we insert `Irrelevant' when the type is insignificant.
874   //
875   // Argument ranges should always cover all variants. If return value
876   // is completely unknown, omit it from the respective range set.
877   //
878   // All types in the spec need to be canonical.
879   //
880   // Every item in the list of range sets represents a particular
881   // execution path the analyzer would need to explore once
882   // the call is modeled - a new program state is constructed
883   // for every range set, and each range line in the range set
884   // corresponds to a specific constraint within this state.
885   //
886   // Upon comparing to another argument, the other argument is casted
887   // to the current argument's type. This avoids proper promotion but
888   // seems useful. For example, read() receives size_t argument,
889   // and its return value, which is of type ssize_t, cannot be greater
890   // than this argument. If we made a promotion, and the size argument
891   // is equal to, say, 10, then we'd impose a range of [0, 10] on the
892   // return value, however the correct range is [-1, 10].
893   //
894   // Please update the list of functions in the header after editing!
895 
896   // Below are helpers functions to create the summaries.
897   auto ArgumentCondition = [](ArgNo ArgN, RangeKind Kind,
898                               IntRangeVector Ranges) {
899     return std::make_shared<RangeConstraint>(ArgN, Kind, Ranges);
900   };
901   auto BufferSize = [](auto... Args) {
902     return std::make_shared<BufferSizeConstraint>(Args...);
903   };
904   struct {
905     auto operator()(RangeKind Kind, IntRangeVector Ranges) {
906       return std::make_shared<RangeConstraint>(Ret, Kind, Ranges);
907     }
908     auto operator()(BinaryOperator::Opcode Op, ArgNo OtherArgN) {
909       return std::make_shared<ComparisonConstraint>(Ret, Op, OtherArgN);
910     }
911   } ReturnValueCondition;
912   auto Range = [](RangeInt b, RangeInt e) {
913     return IntRangeVector{std::pair<RangeInt, RangeInt>{b, e}};
914   };
915   auto SingleValue = [](RangeInt v) {
916     return IntRangeVector{std::pair<RangeInt, RangeInt>{v, v}};
917   };
918   auto LessThanOrEq = BO_LE;
919   auto NotNull = [&](ArgNo ArgN) {
920     return std::make_shared<NotNullConstraint>(ArgN);
921   };
922 
923   Optional<QualType> FileTy = lookupType("FILE", ACtx);
924   Optional<QualType> FilePtrTy, FilePtrRestrictTy;
925   if (FileTy) {
926     // FILE *
927     FilePtrTy = ACtx.getPointerType(*FileTy);
928     // FILE *restrict
929     FilePtrRestrictTy =
930         ACtx.getLangOpts().C99 ? ACtx.getRestrictType(*FilePtrTy) : *FilePtrTy;
931   }
932 
933   using RetType = QualType;
934   // Templates for summaries that are reused by many functions.
935   auto Getc = [&]() {
936     return Summary(ArgTypes{*FilePtrTy}, RetType{IntTy}, NoEvalCall)
937         .Case({ReturnValueCondition(WithinRange,
938                                     {{EOFv, EOFv}, {0, UCharRangeMax}})});
939   };
940   auto Read = [&](RetType R, RangeInt Max) {
941     return Summary(ArgTypes{Irrelevant, Irrelevant, SizeTy}, RetType{R},
942                    NoEvalCall)
943         .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)),
944                ReturnValueCondition(WithinRange, Range(-1, Max))});
945   };
946   auto Fread = [&]() {
947     return Summary(
948                ArgTypes{VoidPtrRestrictTy, SizeTy, SizeTy, *FilePtrRestrictTy},
949                RetType{SizeTy}, NoEvalCall)
950         .Case({
951             ReturnValueCondition(LessThanOrEq, ArgNo(2)),
952         })
953         .ArgConstraint(NotNull(ArgNo(0)));
954   };
955   auto Fwrite = [&]() {
956     return Summary(ArgTypes{ConstVoidPtrRestrictTy, SizeTy, SizeTy,
957                             *FilePtrRestrictTy},
958                    RetType{SizeTy}, NoEvalCall)
959         .Case({
960             ReturnValueCondition(LessThanOrEq, ArgNo(2)),
961         })
962         .ArgConstraint(NotNull(ArgNo(0)));
963   };
964   auto Getline = [&](RetType R, RangeInt Max) {
965     return Summary(ArgTypes{Irrelevant, Irrelevant, Irrelevant}, RetType{R},
966                    NoEvalCall)
967         .Case({ReturnValueCondition(WithinRange, {{-1, -1}, {1, Max}})});
968   };
969 
970   // The isascii() family of functions.
971   // The behavior is undefined if the value of the argument is not
972   // representable as unsigned char or is not equal to EOF. See e.g. C99
973   // 7.4.1.2 The isalpha function (p: 181-182).
974   addToFunctionSummaryMap(
975       "isalnum",
976       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
977           // Boils down to isupper() or islower() or isdigit().
978           .Case({ArgumentCondition(0U, WithinRange,
979                                    {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}}),
980                  ReturnValueCondition(OutOfRange, SingleValue(0))})
981           // The locale-specific range.
982           // No post-condition. We are completely unaware of
983           // locale-specific return values.
984           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
985           .Case(
986               {ArgumentCondition(
987                    0U, OutOfRange,
988                    {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}),
989                ReturnValueCondition(WithinRange, SingleValue(0))})
990           .ArgConstraint(ArgumentCondition(
991               0U, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})));
992   addToFunctionSummaryMap(
993       "isalpha",
994       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
995           .Case({ArgumentCondition(0U, WithinRange, {{'A', 'Z'}, {'a', 'z'}}),
996                  ReturnValueCondition(OutOfRange, SingleValue(0))})
997           // The locale-specific range.
998           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
999           .Case({ArgumentCondition(
1000                      0U, OutOfRange,
1001                      {{'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}),
1002                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1003   addToFunctionSummaryMap(
1004       "isascii",
1005       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1006           .Case({ArgumentCondition(0U, WithinRange, Range(0, 127)),
1007                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1008           .Case({ArgumentCondition(0U, OutOfRange, Range(0, 127)),
1009                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1010   addToFunctionSummaryMap(
1011       "isblank",
1012       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1013           .Case({ArgumentCondition(0U, WithinRange, {{'\t', '\t'}, {' ', ' '}}),
1014                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1015           .Case({ArgumentCondition(0U, OutOfRange, {{'\t', '\t'}, {' ', ' '}}),
1016                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1017   addToFunctionSummaryMap(
1018       "iscntrl",
1019       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1020           .Case({ArgumentCondition(0U, WithinRange, {{0, 32}, {127, 127}}),
1021                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1022           .Case({ArgumentCondition(0U, OutOfRange, {{0, 32}, {127, 127}}),
1023                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1024   addToFunctionSummaryMap(
1025       "isdigit",
1026       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1027           .Case({ArgumentCondition(0U, WithinRange, Range('0', '9')),
1028                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1029           .Case({ArgumentCondition(0U, OutOfRange, Range('0', '9')),
1030                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1031   addToFunctionSummaryMap(
1032       "isgraph",
1033       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1034           .Case({ArgumentCondition(0U, WithinRange, Range(33, 126)),
1035                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1036           .Case({ArgumentCondition(0U, OutOfRange, Range(33, 126)),
1037                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1038   addToFunctionSummaryMap(
1039       "islower",
1040       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1041           // Is certainly lowercase.
1042           .Case({ArgumentCondition(0U, WithinRange, Range('a', 'z')),
1043                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1044           // Is ascii but not lowercase.
1045           .Case({ArgumentCondition(0U, WithinRange, Range(0, 127)),
1046                  ArgumentCondition(0U, OutOfRange, Range('a', 'z')),
1047                  ReturnValueCondition(WithinRange, SingleValue(0))})
1048           // The locale-specific range.
1049           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1050           // Is not an unsigned char.
1051           .Case({ArgumentCondition(0U, OutOfRange, Range(0, UCharRangeMax)),
1052                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1053   addToFunctionSummaryMap(
1054       "isprint",
1055       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1056           .Case({ArgumentCondition(0U, WithinRange, Range(32, 126)),
1057                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1058           .Case({ArgumentCondition(0U, OutOfRange, Range(32, 126)),
1059                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1060   addToFunctionSummaryMap(
1061       "ispunct",
1062       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1063           .Case({ArgumentCondition(
1064                      0U, WithinRange,
1065                      {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}),
1066                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1067           .Case({ArgumentCondition(
1068                      0U, OutOfRange,
1069                      {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}),
1070                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1071   addToFunctionSummaryMap(
1072       "isspace",
1073       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1074           // Space, '\f', '\n', '\r', '\t', '\v'.
1075           .Case({ArgumentCondition(0U, WithinRange, {{9, 13}, {' ', ' '}}),
1076                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1077           // The locale-specific range.
1078           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1079           .Case({ArgumentCondition(0U, OutOfRange,
1080                                    {{9, 13}, {' ', ' '}, {128, UCharRangeMax}}),
1081                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1082   addToFunctionSummaryMap(
1083       "isupper",
1084       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1085           // Is certainly uppercase.
1086           .Case({ArgumentCondition(0U, WithinRange, Range('A', 'Z')),
1087                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1088           // The locale-specific range.
1089           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1090           // Other.
1091           .Case({ArgumentCondition(0U, OutOfRange,
1092                                    {{'A', 'Z'}, {128, UCharRangeMax}}),
1093                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1094   addToFunctionSummaryMap(
1095       "isxdigit",
1096       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1097           .Case({ArgumentCondition(0U, WithinRange,
1098                                    {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}),
1099                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1100           .Case({ArgumentCondition(0U, OutOfRange,
1101                                    {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}),
1102                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1103 
1104   // The getc() family of functions that returns either a char or an EOF.
1105   if (FilePtrTy) {
1106     addToFunctionSummaryMap("getc", Getc());
1107     addToFunctionSummaryMap("fgetc", Getc());
1108   }
1109   addToFunctionSummaryMap(
1110       "getchar", Summary(ArgTypes{}, RetType{IntTy}, NoEvalCall)
1111                      .Case({ReturnValueCondition(
1112                          WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})}));
1113 
1114   // read()-like functions that never return more than buffer size.
1115   if (FilePtrRestrictTy) {
1116     addToFunctionSummaryMap("fread", Fread());
1117     addToFunctionSummaryMap("fwrite", Fwrite());
1118   }
1119 
1120   // We are not sure how ssize_t is defined on every platform, so we
1121   // provide three variants that should cover common cases.
1122   // FIXME these are actually defined by POSIX and not by the C standard, we
1123   // should handle them together with the rest of the POSIX functions.
1124   addToFunctionSummaryMap("read", {Read(IntTy, IntMax), Read(LongTy, LongMax),
1125                                    Read(LongLongTy, LongLongMax)});
1126   addToFunctionSummaryMap("write", {Read(IntTy, IntMax), Read(LongTy, LongMax),
1127                                     Read(LongLongTy, LongLongMax)});
1128 
1129   // getline()-like functions either fail or read at least the delimiter.
1130   // FIXME these are actually defined by POSIX and not by the C standard, we
1131   // should handle them together with the rest of the POSIX functions.
1132   addToFunctionSummaryMap("getline",
1133                           {Getline(IntTy, IntMax), Getline(LongTy, LongMax),
1134                            Getline(LongLongTy, LongLongMax)});
1135   addToFunctionSummaryMap("getdelim",
1136                           {Getline(IntTy, IntMax), Getline(LongTy, LongMax),
1137                            Getline(LongLongTy, LongLongMax)});
1138 
1139   if (ModelPOSIX) {
1140 
1141     // long a64l(const char *str64);
1142     addToFunctionSummaryMap(
1143         "a64l", Summary(ArgTypes{ConstCharPtrTy}, RetType{LongTy}, NoEvalCall)
1144                     .ArgConstraint(NotNull(ArgNo(0))));
1145 
1146     // char *l64a(long value);
1147     addToFunctionSummaryMap(
1148         "l64a", Summary(ArgTypes{LongTy}, RetType{CharPtrTy}, NoEvalCall)
1149                     .ArgConstraint(
1150                         ArgumentCondition(0, WithinRange, Range(0, LongMax))));
1151 
1152     // int access(const char *pathname, int amode);
1153     addToFunctionSummaryMap("access", Summary(ArgTypes{ConstCharPtrTy, IntTy},
1154                                               RetType{IntTy}, NoEvalCall)
1155                                           .ArgConstraint(NotNull(ArgNo(0))));
1156 
1157     // int faccessat(int dirfd, const char *pathname, int mode, int flags);
1158     addToFunctionSummaryMap(
1159         "faccessat", Summary(ArgTypes{IntTy, ConstCharPtrTy, IntTy, IntTy},
1160                              RetType{IntTy}, NoEvalCall)
1161                          .ArgConstraint(NotNull(ArgNo(1))));
1162 
1163     // int dup(int fildes);
1164     addToFunctionSummaryMap(
1165         "dup", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1166                    .ArgConstraint(
1167                        ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1168 
1169     // int dup2(int fildes1, int filedes2);
1170     addToFunctionSummaryMap(
1171         "dup2",
1172         Summary(ArgTypes{IntTy, IntTy}, RetType{IntTy}, NoEvalCall)
1173             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1174             .ArgConstraint(
1175                 ArgumentCondition(1, WithinRange, Range(0, IntMax))));
1176 
1177     // int fdatasync(int fildes);
1178     addToFunctionSummaryMap(
1179         "fdatasync", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1180                          .ArgConstraint(ArgumentCondition(0, WithinRange,
1181                                                           Range(0, IntMax))));
1182 
1183     // int fnmatch(const char *pattern, const char *string, int flags);
1184     addToFunctionSummaryMap(
1185         "fnmatch", Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, IntTy},
1186                            RetType{IntTy}, EvalCallAsPure)
1187                        .ArgConstraint(NotNull(ArgNo(0)))
1188                        .ArgConstraint(NotNull(ArgNo(1))));
1189 
1190     // int fsync(int fildes);
1191     addToFunctionSummaryMap(
1192         "fsync", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1193                      .ArgConstraint(
1194                          ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1195 
1196     Optional<QualType> Off_tTy = lookupType("off_t", ACtx);
1197 
1198     if (Off_tTy)
1199       // int truncate(const char *path, off_t length);
1200       addToFunctionSummaryMap("truncate",
1201                               Summary(ArgTypes{ConstCharPtrTy, *Off_tTy},
1202                                       RetType{IntTy}, NoEvalCall)
1203                                   .ArgConstraint(NotNull(ArgNo(0))));
1204 
1205     // int symlink(const char *oldpath, const char *newpath);
1206     addToFunctionSummaryMap("symlink",
1207                             Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1208                                     RetType{IntTy}, NoEvalCall)
1209                                 .ArgConstraint(NotNull(ArgNo(0)))
1210                                 .ArgConstraint(NotNull(ArgNo(1))));
1211 
1212     // int symlinkat(const char *oldpath, int newdirfd, const char *newpath);
1213     addToFunctionSummaryMap(
1214         "symlinkat",
1215         Summary(ArgTypes{ConstCharPtrTy, IntTy, ConstCharPtrTy}, RetType{IntTy},
1216                 NoEvalCall)
1217             .ArgConstraint(NotNull(ArgNo(0)))
1218             .ArgConstraint(ArgumentCondition(1, WithinRange, Range(0, IntMax)))
1219             .ArgConstraint(NotNull(ArgNo(2))));
1220 
1221     if (Off_tTy)
1222       // int lockf(int fd, int cmd, off_t len);
1223       addToFunctionSummaryMap(
1224           "lockf",
1225           Summary(ArgTypes{IntTy, IntTy, *Off_tTy}, RetType{IntTy}, NoEvalCall)
1226               .ArgConstraint(
1227                   ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1228 
1229     Optional<QualType> Mode_tTy = lookupType("mode_t", ACtx);
1230 
1231     if (Mode_tTy)
1232       // int creat(const char *pathname, mode_t mode);
1233       addToFunctionSummaryMap("creat",
1234                               Summary(ArgTypes{ConstCharPtrTy, *Mode_tTy},
1235                                       RetType{IntTy}, NoEvalCall)
1236                                   .ArgConstraint(NotNull(ArgNo(0))));
1237 
1238     // unsigned int sleep(unsigned int seconds);
1239     addToFunctionSummaryMap(
1240         "sleep",
1241         Summary(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}, NoEvalCall)
1242             .ArgConstraint(
1243                 ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax))));
1244 
1245     Optional<QualType> DirTy = lookupType("DIR", ACtx);
1246     Optional<QualType> DirPtrTy;
1247     if (DirTy)
1248       DirPtrTy = ACtx.getPointerType(*DirTy);
1249 
1250     if (DirPtrTy)
1251       // int dirfd(DIR *dirp);
1252       addToFunctionSummaryMap(
1253           "dirfd", Summary(ArgTypes{*DirPtrTy}, RetType{IntTy}, NoEvalCall)
1254                        .ArgConstraint(NotNull(ArgNo(0))));
1255 
1256     // unsigned int alarm(unsigned int seconds);
1257     addToFunctionSummaryMap(
1258         "alarm",
1259         Summary(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}, NoEvalCall)
1260             .ArgConstraint(
1261                 ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax))));
1262 
1263     if (DirPtrTy)
1264       // int closedir(DIR *dir);
1265       addToFunctionSummaryMap(
1266           "closedir", Summary(ArgTypes{*DirPtrTy}, RetType{IntTy}, NoEvalCall)
1267                           .ArgConstraint(NotNull(ArgNo(0))));
1268 
1269     // char *strdup(const char *s);
1270     addToFunctionSummaryMap("strdup", Summary(ArgTypes{ConstCharPtrTy},
1271                                               RetType{CharPtrTy}, NoEvalCall)
1272                                           .ArgConstraint(NotNull(ArgNo(0))));
1273 
1274     // char *strndup(const char *s, size_t n);
1275     addToFunctionSummaryMap(
1276         "strndup", Summary(ArgTypes{ConstCharPtrTy, SizeTy}, RetType{CharPtrTy},
1277                            NoEvalCall)
1278                        .ArgConstraint(NotNull(ArgNo(0)))
1279                        .ArgConstraint(ArgumentCondition(1, WithinRange,
1280                                                         Range(0, SizeMax))));
1281 
1282     // wchar_t *wcsdup(const wchar_t *s);
1283     addToFunctionSummaryMap("wcsdup", Summary(ArgTypes{ConstWchar_tPtrTy},
1284                                               RetType{Wchar_tPtrTy}, NoEvalCall)
1285                                           .ArgConstraint(NotNull(ArgNo(0))));
1286 
1287     // int mkstemp(char *template);
1288     addToFunctionSummaryMap(
1289         "mkstemp", Summary(ArgTypes{CharPtrTy}, RetType{IntTy}, NoEvalCall)
1290                        .ArgConstraint(NotNull(ArgNo(0))));
1291 
1292     // char *mkdtemp(char *template);
1293     addToFunctionSummaryMap(
1294         "mkdtemp", Summary(ArgTypes{CharPtrTy}, RetType{CharPtrTy}, NoEvalCall)
1295                        .ArgConstraint(NotNull(ArgNo(0))));
1296 
1297     // char *getcwd(char *buf, size_t size);
1298     addToFunctionSummaryMap(
1299         "getcwd",
1300         Summary(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}, NoEvalCall)
1301             .ArgConstraint(
1302                 ArgumentCondition(1, WithinRange, Range(0, SizeMax))));
1303 
1304     if (Mode_tTy) {
1305       // int mkdir(const char *pathname, mode_t mode);
1306       addToFunctionSummaryMap("mkdir",
1307                               Summary(ArgTypes{ConstCharPtrTy, *Mode_tTy},
1308                                       RetType{IntTy}, NoEvalCall)
1309                                   .ArgConstraint(NotNull(ArgNo(0))));
1310 
1311       // int mkdirat(int dirfd, const char *pathname, mode_t mode);
1312       addToFunctionSummaryMap(
1313           "mkdirat", Summary(ArgTypes{IntTy, ConstCharPtrTy, *Mode_tTy},
1314                              RetType{IntTy}, NoEvalCall)
1315                          .ArgConstraint(NotNull(ArgNo(1))));
1316     }
1317 
1318     Optional<QualType> Dev_tTy = lookupType("dev_t", ACtx);
1319 
1320     if (Mode_tTy && Dev_tTy) {
1321       // int mknod(const char *pathname, mode_t mode, dev_t dev);
1322       addToFunctionSummaryMap(
1323           "mknod", Summary(ArgTypes{ConstCharPtrTy, *Mode_tTy, *Dev_tTy},
1324                            RetType{IntTy}, NoEvalCall)
1325                        .ArgConstraint(NotNull(ArgNo(0))));
1326 
1327       // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
1328       addToFunctionSummaryMap("mknodat", Summary(ArgTypes{IntTy, ConstCharPtrTy,
1329                                                           *Mode_tTy, *Dev_tTy},
1330                                                  RetType{IntTy}, NoEvalCall)
1331                                              .ArgConstraint(NotNull(ArgNo(1))));
1332     }
1333 
1334     if (Mode_tTy) {
1335       // int chmod(const char *path, mode_t mode);
1336       addToFunctionSummaryMap("chmod",
1337                               Summary(ArgTypes{ConstCharPtrTy, *Mode_tTy},
1338                                       RetType{IntTy}, NoEvalCall)
1339                                   .ArgConstraint(NotNull(ArgNo(0))));
1340 
1341       // int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);
1342       addToFunctionSummaryMap(
1343           "fchmodat", Summary(ArgTypes{IntTy, ConstCharPtrTy, *Mode_tTy, IntTy},
1344                               RetType{IntTy}, NoEvalCall)
1345                           .ArgConstraint(ArgumentCondition(0, WithinRange,
1346                                                            Range(0, IntMax)))
1347                           .ArgConstraint(NotNull(ArgNo(1))));
1348 
1349       // int fchmod(int fildes, mode_t mode);
1350       addToFunctionSummaryMap(
1351           "fchmod",
1352           Summary(ArgTypes{IntTy, *Mode_tTy}, RetType{IntTy}, NoEvalCall)
1353               .ArgConstraint(
1354                   ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1355     }
1356 
1357     Optional<QualType> Uid_tTy = lookupType("uid_t", ACtx);
1358     Optional<QualType> Gid_tTy = lookupType("gid_t", ACtx);
1359 
1360     if (Uid_tTy && Gid_tTy) {
1361       // int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group,
1362       //              int flags);
1363       addToFunctionSummaryMap(
1364           "fchownat",
1365           Summary(ArgTypes{IntTy, ConstCharPtrTy, *Uid_tTy, *Gid_tTy, IntTy},
1366                   RetType{IntTy}, NoEvalCall)
1367               .ArgConstraint(
1368                   ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1369               .ArgConstraint(NotNull(ArgNo(1))));
1370 
1371       // int chown(const char *path, uid_t owner, gid_t group);
1372       addToFunctionSummaryMap(
1373           "chown", Summary(ArgTypes{ConstCharPtrTy, *Uid_tTy, *Gid_tTy},
1374                            RetType{IntTy}, NoEvalCall)
1375                        .ArgConstraint(NotNull(ArgNo(0))));
1376 
1377       // int lchown(const char *path, uid_t owner, gid_t group);
1378       addToFunctionSummaryMap(
1379           "lchown", Summary(ArgTypes{ConstCharPtrTy, *Uid_tTy, *Gid_tTy},
1380                             RetType{IntTy}, NoEvalCall)
1381                         .ArgConstraint(NotNull(ArgNo(0))));
1382 
1383       // int fchown(int fildes, uid_t owner, gid_t group);
1384       addToFunctionSummaryMap(
1385           "fchown", Summary(ArgTypes{IntTy, *Uid_tTy, *Gid_tTy}, RetType{IntTy},
1386                             NoEvalCall)
1387                         .ArgConstraint(ArgumentCondition(0, WithinRange,
1388                                                          Range(0, IntMax))));
1389     }
1390 
1391     // int rmdir(const char *pathname);
1392     addToFunctionSummaryMap(
1393         "rmdir", Summary(ArgTypes{ConstCharPtrTy}, RetType{IntTy}, NoEvalCall)
1394                      .ArgConstraint(NotNull(ArgNo(0))));
1395 
1396     // int chdir(const char *path);
1397     addToFunctionSummaryMap(
1398         "chdir", Summary(ArgTypes{ConstCharPtrTy}, RetType{IntTy}, NoEvalCall)
1399                      .ArgConstraint(NotNull(ArgNo(0))));
1400 
1401     // int link(const char *oldpath, const char *newpath);
1402     addToFunctionSummaryMap("link",
1403                             Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1404                                     RetType{IntTy}, NoEvalCall)
1405                                 .ArgConstraint(NotNull(ArgNo(0)))
1406                                 .ArgConstraint(NotNull(ArgNo(1))));
1407 
1408     // int linkat(int fd1, const char *path1, int fd2, const char *path2,
1409     //            int flag);
1410     addToFunctionSummaryMap(
1411         "linkat",
1412         Summary(ArgTypes{IntTy, ConstCharPtrTy, IntTy, ConstCharPtrTy, IntTy},
1413                 RetType{IntTy}, NoEvalCall)
1414             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1415             .ArgConstraint(NotNull(ArgNo(1)))
1416             .ArgConstraint(ArgumentCondition(2, WithinRange, Range(0, IntMax)))
1417             .ArgConstraint(NotNull(ArgNo(3))));
1418 
1419     // int unlink(const char *pathname);
1420     addToFunctionSummaryMap(
1421         "unlink", Summary(ArgTypes{ConstCharPtrTy}, RetType{IntTy}, NoEvalCall)
1422                       .ArgConstraint(NotNull(ArgNo(0))));
1423 
1424     // int unlinkat(int fd, const char *path, int flag);
1425     addToFunctionSummaryMap(
1426         "unlinkat",
1427         Summary(ArgTypes{IntTy, ConstCharPtrTy, IntTy}, RetType{IntTy},
1428                 NoEvalCall)
1429             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1430             .ArgConstraint(NotNull(ArgNo(1))));
1431 
1432     Optional<QualType> StructStatTy = lookupType("stat", ACtx);
1433     Optional<QualType> StructStatPtrTy, StructStatPtrRestrictTy;
1434     if (StructStatTy) {
1435       StructStatPtrTy = ACtx.getPointerType(*StructStatTy);
1436       StructStatPtrRestrictTy = ACtx.getLangOpts().C99
1437                                     ? ACtx.getRestrictType(*StructStatPtrTy)
1438                                     : *StructStatPtrTy;
1439     }
1440 
1441     if (StructStatPtrTy)
1442       // int fstat(int fd, struct stat *statbuf);
1443       addToFunctionSummaryMap(
1444           "fstat",
1445           Summary(ArgTypes{IntTy, *StructStatPtrTy}, RetType{IntTy}, NoEvalCall)
1446               .ArgConstraint(
1447                   ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1448               .ArgConstraint(NotNull(ArgNo(1))));
1449 
1450     if (StructStatPtrRestrictTy) {
1451       // int stat(const char *restrict path, struct stat *restrict buf);
1452       addToFunctionSummaryMap(
1453           "stat",
1454           Summary(ArgTypes{ConstCharPtrRestrictTy, *StructStatPtrRestrictTy},
1455                   RetType{IntTy}, NoEvalCall)
1456               .ArgConstraint(NotNull(ArgNo(0)))
1457               .ArgConstraint(NotNull(ArgNo(1))));
1458 
1459       // int lstat(const char *restrict path, struct stat *restrict buf);
1460       addToFunctionSummaryMap(
1461           "lstat",
1462           Summary(ArgTypes{ConstCharPtrRestrictTy, *StructStatPtrRestrictTy},
1463                   RetType{IntTy}, NoEvalCall)
1464               .ArgConstraint(NotNull(ArgNo(0)))
1465               .ArgConstraint(NotNull(ArgNo(1))));
1466 
1467       // int fstatat(int fd, const char *restrict path,
1468       //             struct stat *restrict buf, int flag);
1469       addToFunctionSummaryMap(
1470           "fstatat", Summary(ArgTypes{IntTy, ConstCharPtrRestrictTy,
1471                                       *StructStatPtrRestrictTy, IntTy},
1472                              RetType{IntTy}, NoEvalCall)
1473                          .ArgConstraint(ArgumentCondition(0, WithinRange,
1474                                                           Range(0, IntMax)))
1475                          .ArgConstraint(NotNull(ArgNo(1)))
1476                          .ArgConstraint(NotNull(ArgNo(2))));
1477     }
1478 
1479     if (DirPtrTy) {
1480       // DIR *opendir(const char *name);
1481       addToFunctionSummaryMap("opendir", Summary(ArgTypes{ConstCharPtrTy},
1482                                                  RetType{*DirPtrTy}, NoEvalCall)
1483                                              .ArgConstraint(NotNull(ArgNo(0))));
1484 
1485       // DIR *fdopendir(int fd);
1486       addToFunctionSummaryMap(
1487           "fdopendir", Summary(ArgTypes{IntTy}, RetType{*DirPtrTy}, NoEvalCall)
1488                            .ArgConstraint(ArgumentCondition(0, WithinRange,
1489                                                             Range(0, IntMax))));
1490     }
1491 
1492     // int isatty(int fildes);
1493     addToFunctionSummaryMap(
1494         "isatty", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1495                       .ArgConstraint(
1496                           ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1497 
1498     if (FilePtrTy) {
1499       // FILE *popen(const char *command, const char *type);
1500       addToFunctionSummaryMap("popen",
1501                               Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1502                                       RetType{*FilePtrTy}, NoEvalCall)
1503                                   .ArgConstraint(NotNull(ArgNo(0)))
1504                                   .ArgConstraint(NotNull(ArgNo(1))));
1505 
1506       // int pclose(FILE *stream);
1507       addToFunctionSummaryMap(
1508           "pclose", Summary(ArgTypes{*FilePtrTy}, RetType{IntTy}, NoEvalCall)
1509                         .ArgConstraint(NotNull(ArgNo(0))));
1510     }
1511 
1512     // int close(int fildes);
1513     addToFunctionSummaryMap(
1514         "close", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1515                      .ArgConstraint(
1516                          ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1517 
1518     // long fpathconf(int fildes, int name);
1519     addToFunctionSummaryMap(
1520         "fpathconf",
1521         Summary(ArgTypes{IntTy, IntTy}, RetType{LongTy}, NoEvalCall)
1522             .ArgConstraint(
1523                 ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1524 
1525     // long pathconf(const char *path, int name);
1526     addToFunctionSummaryMap("pathconf", Summary(ArgTypes{ConstCharPtrTy, IntTy},
1527                                                 RetType{LongTy}, NoEvalCall)
1528                                             .ArgConstraint(NotNull(ArgNo(0))));
1529 
1530     if (FilePtrTy)
1531       // FILE *fdopen(int fd, const char *mode);
1532       addToFunctionSummaryMap(
1533           "fdopen", Summary(ArgTypes{IntTy, ConstCharPtrTy},
1534                             RetType{*FilePtrTy}, NoEvalCall)
1535                         .ArgConstraint(
1536                             ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1537                         .ArgConstraint(NotNull(ArgNo(1))));
1538 
1539     if (DirPtrTy) {
1540       // void rewinddir(DIR *dir);
1541       addToFunctionSummaryMap(
1542           "rewinddir", Summary(ArgTypes{*DirPtrTy}, RetType{VoidTy}, NoEvalCall)
1543                            .ArgConstraint(NotNull(ArgNo(0))));
1544 
1545       // void seekdir(DIR *dirp, long loc);
1546       addToFunctionSummaryMap("seekdir", Summary(ArgTypes{*DirPtrTy, LongTy},
1547                                                  RetType{VoidTy}, NoEvalCall)
1548                                              .ArgConstraint(NotNull(ArgNo(0))));
1549     }
1550 
1551     // int rand_r(unsigned int *seedp);
1552     addToFunctionSummaryMap("rand_r", Summary(ArgTypes{UnsignedIntPtrTy},
1553                                               RetType{IntTy}, NoEvalCall)
1554                                           .ArgConstraint(NotNull(ArgNo(0))));
1555 
1556     // int strcasecmp(const char *s1, const char *s2);
1557     addToFunctionSummaryMap("strcasecmp",
1558                             Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1559                                     RetType{IntTy}, EvalCallAsPure)
1560                                 .ArgConstraint(NotNull(ArgNo(0)))
1561                                 .ArgConstraint(NotNull(ArgNo(1))));
1562 
1563     // int strncasecmp(const char *s1, const char *s2, size_t n);
1564     addToFunctionSummaryMap(
1565         "strncasecmp", Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, SizeTy},
1566                                RetType{IntTy}, EvalCallAsPure)
1567                            .ArgConstraint(NotNull(ArgNo(0)))
1568                            .ArgConstraint(NotNull(ArgNo(1)))
1569                            .ArgConstraint(ArgumentCondition(
1570                                2, WithinRange, Range(0, SizeMax))));
1571 
1572     if (FilePtrTy && Off_tTy) {
1573 
1574       // int fileno(FILE *stream);
1575       addToFunctionSummaryMap(
1576           "fileno", Summary(ArgTypes{*FilePtrTy}, RetType{IntTy}, NoEvalCall)
1577                         .ArgConstraint(NotNull(ArgNo(0))));
1578 
1579       // int fseeko(FILE *stream, off_t offset, int whence);
1580       addToFunctionSummaryMap("fseeko",
1581                               Summary(ArgTypes{*FilePtrTy, *Off_tTy, IntTy},
1582                                       RetType{IntTy}, NoEvalCall)
1583                                   .ArgConstraint(NotNull(ArgNo(0))));
1584 
1585       // off_t ftello(FILE *stream);
1586       addToFunctionSummaryMap(
1587           "ftello", Summary(ArgTypes{*FilePtrTy}, RetType{*Off_tTy}, NoEvalCall)
1588                         .ArgConstraint(NotNull(ArgNo(0))));
1589     }
1590 
1591     if (Off_tTy) {
1592       Optional<RangeInt> Off_tMax = BVF.getMaxValue(*Off_tTy).getLimitedValue();
1593 
1594       // void *mmap(void *addr, size_t length, int prot, int flags, int fd,
1595       // off_t offset);
1596       addToFunctionSummaryMap(
1597           "mmap",
1598           Summary(ArgTypes{VoidPtrTy, SizeTy, IntTy, IntTy, IntTy, *Off_tTy},
1599                   RetType{VoidPtrTy}, NoEvalCall)
1600               .ArgConstraint(
1601                   ArgumentCondition(1, WithinRange, Range(1, SizeMax)))
1602               .ArgConstraint(
1603                   ArgumentCondition(4, WithinRange, Range(0, *Off_tMax))));
1604     }
1605 
1606     Optional<QualType> Off64_tTy = lookupType("off64_t", ACtx);
1607     Optional<RangeInt> Off64_tMax;
1608     if (Off64_tTy) {
1609       Off64_tMax = BVF.getMaxValue(*Off_tTy).getLimitedValue();
1610       // void *mmap64(void *addr, size_t length, int prot, int flags, int fd,
1611       // off64_t offset);
1612       addToFunctionSummaryMap(
1613           "mmap64",
1614           Summary(ArgTypes{VoidPtrTy, SizeTy, IntTy, IntTy, IntTy, *Off64_tTy},
1615                   RetType{VoidPtrTy}, NoEvalCall)
1616               .ArgConstraint(
1617                   ArgumentCondition(1, WithinRange, Range(1, SizeMax)))
1618               .ArgConstraint(
1619                   ArgumentCondition(4, WithinRange, Range(0, *Off64_tMax))));
1620     }
1621 
1622     // int pipe(int fildes[2]);
1623     addToFunctionSummaryMap(
1624         "pipe", Summary(ArgTypes{IntPtrTy}, RetType{IntTy}, NoEvalCall)
1625                     .ArgConstraint(NotNull(ArgNo(0))));
1626 
1627     if (Off_tTy)
1628       // off_t lseek(int fildes, off_t offset, int whence);
1629       addToFunctionSummaryMap(
1630           "lseek", Summary(ArgTypes{IntTy, *Off_tTy, IntTy}, RetType{*Off_tTy},
1631                            NoEvalCall)
1632                        .ArgConstraint(ArgumentCondition(0, WithinRange,
1633                                                         Range(0, IntMax))));
1634 
1635     Optional<QualType> Ssize_tTy = lookupType("ssize_t", ACtx);
1636 
1637     if (Ssize_tTy) {
1638       // ssize_t readlink(const char *restrict path, char *restrict buf,
1639       //                  size_t bufsize);
1640       addToFunctionSummaryMap(
1641           "readlink",
1642           Summary(ArgTypes{ConstCharPtrRestrictTy, CharPtrRestrictTy, SizeTy},
1643                   RetType{*Ssize_tTy}, NoEvalCall)
1644               .ArgConstraint(NotNull(ArgNo(0)))
1645               .ArgConstraint(NotNull(ArgNo(1)))
1646               .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
1647                                         /*BufSize=*/ArgNo(2)))
1648               .ArgConstraint(
1649                   ArgumentCondition(2, WithinRange, Range(0, SizeMax))));
1650 
1651       // ssize_t readlinkat(int fd, const char *restrict path,
1652       //                    char *restrict buf, size_t bufsize);
1653       addToFunctionSummaryMap(
1654           "readlinkat", Summary(ArgTypes{IntTy, ConstCharPtrRestrictTy,
1655                                          CharPtrRestrictTy, SizeTy},
1656                                 RetType{*Ssize_tTy}, NoEvalCall)
1657                             .ArgConstraint(ArgumentCondition(0, WithinRange,
1658                                                              Range(0, IntMax)))
1659                             .ArgConstraint(NotNull(ArgNo(1)))
1660                             .ArgConstraint(NotNull(ArgNo(2)))
1661                             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(2),
1662                                                       /*BufSize=*/ArgNo(3)))
1663                             .ArgConstraint(ArgumentCondition(
1664                                 3, WithinRange, Range(0, SizeMax))));
1665     }
1666 
1667     // int renameat(int olddirfd, const char *oldpath, int newdirfd, const char
1668     // *newpath);
1669     addToFunctionSummaryMap("renameat", Summary(ArgTypes{IntTy, ConstCharPtrTy,
1670                                                          IntTy, ConstCharPtrTy},
1671                                                 RetType{IntTy}, NoEvalCall)
1672                                             .ArgConstraint(NotNull(ArgNo(1)))
1673                                             .ArgConstraint(NotNull(ArgNo(3))));
1674 
1675     // char *realpath(const char *restrict file_name,
1676     //                char *restrict resolved_name);
1677     addToFunctionSummaryMap(
1678         "realpath", Summary(ArgTypes{ConstCharPtrRestrictTy, CharPtrRestrictTy},
1679                             RetType{CharPtrTy}, NoEvalCall)
1680                         .ArgConstraint(NotNull(ArgNo(0))));
1681 
1682     QualType CharPtrConstPtr = ACtx.getPointerType(CharPtrTy.withConst());
1683 
1684     // int execv(const char *path, char *const argv[]);
1685     addToFunctionSummaryMap("execv",
1686                             Summary(ArgTypes{ConstCharPtrTy, CharPtrConstPtr},
1687                                     RetType{IntTy}, NoEvalCall)
1688                                 .ArgConstraint(NotNull(ArgNo(0))));
1689 
1690     // int execvp(const char *file, char *const argv[]);
1691     addToFunctionSummaryMap("execvp",
1692                             Summary(ArgTypes{ConstCharPtrTy, CharPtrConstPtr},
1693                                     RetType{IntTy}, NoEvalCall)
1694                                 .ArgConstraint(NotNull(ArgNo(0))));
1695 
1696     // int getopt(int argc, char * const argv[], const char *optstring);
1697     addToFunctionSummaryMap(
1698         "getopt",
1699         Summary(ArgTypes{IntTy, CharPtrConstPtr, ConstCharPtrTy},
1700                 RetType{IntTy}, NoEvalCall)
1701             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1702             .ArgConstraint(NotNull(ArgNo(1)))
1703             .ArgConstraint(NotNull(ArgNo(2))));
1704   }
1705 
1706   // Functions for testing.
1707   if (ChecksEnabled[CK_StdCLibraryFunctionsTesterChecker]) {
1708     addToFunctionSummaryMap(
1709         "__two_constrained_args",
1710         Summary(ArgTypes{IntTy, IntTy}, RetType{IntTy}, EvalCallAsPure)
1711             .ArgConstraint(ArgumentCondition(0U, WithinRange, SingleValue(1)))
1712             .ArgConstraint(ArgumentCondition(1U, WithinRange, SingleValue(1))));
1713     addToFunctionSummaryMap(
1714         "__arg_constrained_twice",
1715         Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1716             .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(1)))
1717             .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(2))));
1718     addToFunctionSummaryMap(
1719         "__defaultparam",
1720         Summary(ArgTypes{Irrelevant, IntTy}, RetType{IntTy}, EvalCallAsPure)
1721             .ArgConstraint(NotNull(ArgNo(0))));
1722     addToFunctionSummaryMap("__variadic",
1723                             Summary(ArgTypes{VoidPtrTy, ConstCharPtrTy},
1724                                     RetType{IntTy}, EvalCallAsPure)
1725                                 .ArgConstraint(NotNull(ArgNo(0)))
1726                                 .ArgConstraint(NotNull(ArgNo(1))));
1727     addToFunctionSummaryMap(
1728         "__buf_size_arg_constraint",
1729         Summary(ArgTypes{ConstVoidPtrTy, SizeTy}, RetType{IntTy},
1730                 EvalCallAsPure)
1731             .ArgConstraint(
1732                 BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1))));
1733     addToFunctionSummaryMap(
1734         "__buf_size_arg_constraint_mul",
1735         Summary(ArgTypes{ConstVoidPtrTy, SizeTy, SizeTy}, RetType{IntTy},
1736                 EvalCallAsPure)
1737             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1),
1738                                       /*BufSizeMultiplier=*/ArgNo(2))));
1739   }
1740 }
1741 
1742 void ento::registerStdCLibraryFunctionsChecker(CheckerManager &mgr) {
1743   auto *Checker = mgr.registerChecker<StdLibraryFunctionsChecker>();
1744   Checker->DisplayLoadedSummaries =
1745       mgr.getAnalyzerOptions().getCheckerBooleanOption(
1746           Checker, "DisplayLoadedSummaries");
1747   Checker->ModelPOSIX =
1748       mgr.getAnalyzerOptions().getCheckerBooleanOption(Checker, "ModelPOSIX");
1749 }
1750 
1751 bool ento::shouldRegisterStdCLibraryFunctionsChecker(const CheckerManager &mgr) {
1752   return true;
1753 }
1754 
1755 #define REGISTER_CHECKER(name)                                                 \
1756   void ento::register##name(CheckerManager &mgr) {                             \
1757     StdLibraryFunctionsChecker *checker =                                      \
1758         mgr.getChecker<StdLibraryFunctionsChecker>();                          \
1759     checker->ChecksEnabled[StdLibraryFunctionsChecker::CK_##name] = true;      \
1760     checker->CheckNames[StdLibraryFunctionsChecker::CK_##name] =               \
1761         mgr.getCurrentCheckerName();                                           \
1762   }                                                                            \
1763                                                                                \
1764   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
1765 
1766 REGISTER_CHECKER(StdCLibraryFunctionArgsChecker)
1767 REGISTER_CHECKER(StdCLibraryFunctionsTesterChecker)
1768