xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp (revision a97648b93846f163af262b9a0db684c7f5efc43f)
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     toascii
44 //   fread      isalnum   isgraph   isxdigit
45 //   fwrite     isalpha   islower   read
46 //   getc       isascii   isprint   write
47 //   getchar    isblank   ispunct   toupper
48 //   getdelim   iscntrl   isspace   tolower
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     virtual StringRef getName() const = 0;
130 
131   protected:
132     ArgNo ArgN; // Argument to which we apply the constraint.
133 
134     /// Do polymorphic sanity check on the constraint.
135     virtual bool checkSpecificValidity(const FunctionDecl *FD) const {
136       return true;
137     }
138   };
139 
140   /// Given a range, should the argument stay inside or outside this range?
141   enum RangeKind { OutOfRange, WithinRange };
142 
143   /// Encapsulates a range on a single symbol.
144   class RangeConstraint : public ValueConstraint {
145     RangeKind Kind;
146     // A range is formed as a set of intervals (sub-ranges).
147     // E.g. {['A', 'Z'], ['a', 'z']}
148     //
149     // The default constructed RangeConstraint has an empty range set, applying
150     // such constraint does not involve any assumptions, thus the State remains
151     // unchanged. This is meaningful, if the range is dependent on a looked up
152     // type (e.g. [0, Socklen_tMax]). If the type is not found, then the range
153     // is default initialized to be empty.
154     IntRangeVector Ranges;
155 
156   public:
157     StringRef getName() const override { return "Range"; }
158     RangeConstraint(ArgNo ArgN, RangeKind Kind, const IntRangeVector &Ranges)
159         : ValueConstraint(ArgN), Kind(Kind), Ranges(Ranges) {}
160 
161     const IntRangeVector &getRanges() const { return Ranges; }
162 
163   private:
164     ProgramStateRef applyAsOutOfRange(ProgramStateRef State,
165                                       const CallEvent &Call,
166                                       const Summary &Summary) const;
167     ProgramStateRef applyAsWithinRange(ProgramStateRef State,
168                                        const CallEvent &Call,
169                                        const Summary &Summary) const;
170 
171   public:
172     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
173                           const Summary &Summary,
174                           CheckerContext &C) const override {
175       switch (Kind) {
176       case OutOfRange:
177         return applyAsOutOfRange(State, Call, Summary);
178       case WithinRange:
179         return applyAsWithinRange(State, Call, Summary);
180       }
181       llvm_unreachable("Unknown range kind!");
182     }
183 
184     ValueConstraintPtr negate() const override {
185       RangeConstraint Tmp(*this);
186       switch (Kind) {
187       case OutOfRange:
188         Tmp.Kind = WithinRange;
189         break;
190       case WithinRange:
191         Tmp.Kind = OutOfRange;
192         break;
193       }
194       return std::make_shared<RangeConstraint>(Tmp);
195     }
196 
197     bool checkSpecificValidity(const FunctionDecl *FD) const override {
198       const bool ValidArg =
199           getArgType(FD, ArgN)->isIntegralType(FD->getASTContext());
200       assert(ValidArg &&
201              "This constraint should be applied on an integral type");
202       return ValidArg;
203     }
204   };
205 
206   class ComparisonConstraint : public ValueConstraint {
207     BinaryOperator::Opcode Opcode;
208     ArgNo OtherArgN;
209 
210   public:
211     virtual StringRef getName() const override { return "Comparison"; };
212     ComparisonConstraint(ArgNo ArgN, BinaryOperator::Opcode Opcode,
213                          ArgNo OtherArgN)
214         : ValueConstraint(ArgN), Opcode(Opcode), OtherArgN(OtherArgN) {}
215     ArgNo getOtherArgNo() const { return OtherArgN; }
216     BinaryOperator::Opcode getOpcode() const { return Opcode; }
217     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
218                           const Summary &Summary,
219                           CheckerContext &C) const override;
220   };
221 
222   class NotNullConstraint : public ValueConstraint {
223     using ValueConstraint::ValueConstraint;
224     // This variable has a role when we negate the constraint.
225     bool CannotBeNull = true;
226 
227   public:
228     StringRef getName() const override { return "NonNull"; }
229     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
230                           const Summary &Summary,
231                           CheckerContext &C) const override {
232       SVal V = getArgSVal(Call, getArgNo());
233       if (V.isUndef())
234         return State;
235 
236       DefinedOrUnknownSVal L = V.castAs<DefinedOrUnknownSVal>();
237       if (!L.getAs<Loc>())
238         return State;
239 
240       return State->assume(L, CannotBeNull);
241     }
242 
243     ValueConstraintPtr negate() const override {
244       NotNullConstraint Tmp(*this);
245       Tmp.CannotBeNull = !this->CannotBeNull;
246       return std::make_shared<NotNullConstraint>(Tmp);
247     }
248 
249     bool checkSpecificValidity(const FunctionDecl *FD) const override {
250       const bool ValidArg = getArgType(FD, ArgN)->isPointerType();
251       assert(ValidArg &&
252              "This constraint should be applied only on a pointer type");
253       return ValidArg;
254     }
255   };
256 
257   // Represents a buffer argument with an additional size constraint. The
258   // constraint may be a concrete value, or a symbolic value in an argument.
259   // Example 1. Concrete value as the minimum buffer size.
260   //   char *asctime_r(const struct tm *restrict tm, char *restrict buf);
261   //   // `buf` size must be at least 26 bytes according the POSIX standard.
262   // Example 2. Argument as a buffer size.
263   //   ctime_s(char *buffer, rsize_t bufsz, const time_t *time);
264   // Example 3. The size is computed as a multiplication of other args.
265   //   size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
266   //   // Here, ptr is the buffer, and its minimum size is `size * nmemb`.
267   class BufferSizeConstraint : public ValueConstraint {
268     // The concrete value which is the minimum size for the buffer.
269     llvm::Optional<llvm::APSInt> ConcreteSize;
270     // The argument which holds the size of the buffer.
271     llvm::Optional<ArgNo> SizeArgN;
272     // The argument which is a multiplier to size. This is set in case of
273     // `fread` like functions where the size is computed as a multiplication of
274     // two arguments.
275     llvm::Optional<ArgNo> SizeMultiplierArgN;
276     // The operator we use in apply. This is negated in negate().
277     BinaryOperator::Opcode Op = BO_LE;
278 
279   public:
280     StringRef getName() const override { return "BufferSize"; }
281     BufferSizeConstraint(ArgNo Buffer, llvm::APSInt BufMinSize)
282         : ValueConstraint(Buffer), ConcreteSize(BufMinSize) {}
283     BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize)
284         : ValueConstraint(Buffer), SizeArgN(BufSize) {}
285     BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize, ArgNo BufSizeMultiplier)
286         : ValueConstraint(Buffer), SizeArgN(BufSize),
287           SizeMultiplierArgN(BufSizeMultiplier) {}
288 
289     ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
290                           const Summary &Summary,
291                           CheckerContext &C) const override {
292       SValBuilder &SvalBuilder = C.getSValBuilder();
293       // The buffer argument.
294       SVal BufV = getArgSVal(Call, getArgNo());
295 
296       // Get the size constraint.
297       const SVal SizeV = [this, &State, &Call, &Summary, &SvalBuilder]() {
298         if (ConcreteSize) {
299           return SVal(SvalBuilder.makeIntVal(*ConcreteSize));
300         } else if (SizeArgN) {
301           // The size argument.
302           SVal SizeV = getArgSVal(Call, *SizeArgN);
303           // Multiply with another argument if given.
304           if (SizeMultiplierArgN) {
305             SVal SizeMulV = getArgSVal(Call, *SizeMultiplierArgN);
306             SizeV = SvalBuilder.evalBinOp(State, BO_Mul, SizeV, SizeMulV,
307                                           Summary.getArgType(*SizeArgN));
308           }
309           return SizeV;
310         } else {
311           llvm_unreachable("The constraint must be either a concrete value or "
312                            "encoded in an arguement.");
313         }
314       }();
315 
316       // The dynamic size of the buffer argument, got from the analyzer engine.
317       SVal BufDynSize = getDynamicSizeWithOffset(State, BufV);
318 
319       SVal Feasible = SvalBuilder.evalBinOp(State, Op, SizeV, BufDynSize,
320                                             SvalBuilder.getContext().BoolTy);
321       if (auto F = Feasible.getAs<DefinedOrUnknownSVal>())
322         return State->assume(*F, true);
323 
324       // We can get here only if the size argument or the dynamic size is
325       // undefined. But the dynamic size should never be undefined, only
326       // unknown. So, here, the size of the argument is undefined, i.e. we
327       // cannot apply the constraint. Actually, other checkers like
328       // CallAndMessage should catch this situation earlier, because we call a
329       // function with an uninitialized argument.
330       llvm_unreachable("Size argument or the dynamic size is Undefined");
331     }
332 
333     ValueConstraintPtr negate() const override {
334       BufferSizeConstraint Tmp(*this);
335       Tmp.Op = BinaryOperator::negateComparisonOp(Op);
336       return std::make_shared<BufferSizeConstraint>(Tmp);
337     }
338 
339     bool checkSpecificValidity(const FunctionDecl *FD) const override {
340       const bool ValidArg = getArgType(FD, ArgN)->isPointerType();
341       assert(ValidArg &&
342              "This constraint should be applied only on a pointer type");
343       return ValidArg;
344     }
345   };
346 
347   /// The complete list of constraints that defines a single branch.
348   typedef std::vector<ValueConstraintPtr> ConstraintSet;
349 
350   using ArgTypes = std::vector<Optional<QualType>>;
351   using RetType = Optional<QualType>;
352 
353   // A placeholder type, we use it whenever we do not care about the concrete
354   // type in a Signature.
355   const QualType Irrelevant{};
356   bool static isIrrelevant(QualType T) { return T.isNull(); }
357 
358   // The signature of a function we want to describe with a summary. This is a
359   // concessive signature, meaning there may be irrelevant types in the
360   // signature which we do not check against a function with concrete types.
361   // All types in the spec need to be canonical.
362   class Signature {
363     using ArgQualTypes = std::vector<QualType>;
364     ArgQualTypes ArgTys;
365     QualType RetTy;
366     // True if any component type is not found by lookup.
367     bool Invalid = false;
368 
369   public:
370     // Construct a signature from optional types. If any of the optional types
371     // are not set then the signature will be invalid.
372     Signature(ArgTypes ArgTys, RetType RetTy) {
373       for (Optional<QualType> Arg : ArgTys) {
374         if (!Arg) {
375           Invalid = true;
376           return;
377         } else {
378           assertArgTypeSuitableForSignature(*Arg);
379           this->ArgTys.push_back(*Arg);
380         }
381       }
382       if (!RetTy) {
383         Invalid = true;
384         return;
385       } else {
386         assertRetTypeSuitableForSignature(*RetTy);
387         this->RetTy = *RetTy;
388       }
389     }
390 
391     bool isInvalid() const { return Invalid; }
392     bool matches(const FunctionDecl *FD) const;
393 
394   private:
395     static void assertArgTypeSuitableForSignature(QualType T) {
396       assert((T.isNull() || !T->isVoidType()) &&
397              "We should have no void types in the spec");
398       assert((T.isNull() || T.isCanonical()) &&
399              "We should only have canonical types in the spec");
400     }
401     static void assertRetTypeSuitableForSignature(QualType T) {
402       assert((T.isNull() || T.isCanonical()) &&
403              "We should only have canonical types in the spec");
404     }
405   };
406 
407   static QualType getArgType(const FunctionDecl *FD, ArgNo ArgN) {
408     assert(FD && "Function must be set");
409     QualType T = (ArgN == Ret)
410                      ? FD->getReturnType().getCanonicalType()
411                      : FD->getParamDecl(ArgN)->getType().getCanonicalType();
412     return T;
413   }
414 
415   using Cases = std::vector<ConstraintSet>;
416 
417   /// A summary includes information about
418   ///   * function prototype (signature)
419   ///   * approach to invalidation,
420   ///   * a list of branches - a list of list of ranges -
421   ///     A branch represents a path in the exploded graph of a function (which
422   ///     is a tree). So, a branch is a series of assumptions. In other words,
423   ///     branches represent split states and additional assumptions on top of
424   ///     the splitting assumption.
425   ///     For example, consider the branches in `isalpha(x)`
426   ///       Branch 1)
427   ///         x is in range ['A', 'Z'] or in ['a', 'z']
428   ///         then the return value is not 0. (I.e. out-of-range [0, 0])
429   ///       Branch 2)
430   ///         x is out-of-range ['A', 'Z'] and out-of-range ['a', 'z']
431   ///         then the return value is 0.
432   ///   * a list of argument constraints, that must be true on every branch.
433   ///     If these constraints are not satisfied that means a fatal error
434   ///     usually resulting in undefined behaviour.
435   ///
436   /// Application of a summary:
437   ///   The signature and argument constraints together contain information
438   ///   about which functions are handled by the summary. The signature can use
439   ///   "wildcards", i.e. Irrelevant types. Irrelevant type of a parameter in
440   ///   a signature means that type is not compared to the type of the parameter
441   ///   in the found FunctionDecl. Argument constraints may specify additional
442   ///   rules for the given parameter's type, those rules are checked once the
443   ///   signature is matched.
444   class Summary {
445     // FIXME Probably the Signature should not be part of the Summary,
446     // We can remove once all overload of addToFunctionSummaryMap requires the
447     // Signature explicitly given.
448     Optional<Signature> Sign;
449     const InvalidationKind InvalidationKd;
450     Cases CaseConstraints;
451     ConstraintSet ArgConstraints;
452 
453     // The function to which the summary applies. This is set after lookup and
454     // match to the signature.
455     const FunctionDecl *FD = nullptr;
456 
457   public:
458     Summary(ArgTypes ArgTys, RetType RetTy, InvalidationKind InvalidationKd)
459         : Sign(Signature(ArgTys, RetTy)), InvalidationKd(InvalidationKd) {}
460 
461     Summary(InvalidationKind InvalidationKd) : InvalidationKd(InvalidationKd) {}
462 
463     // FIXME Remove, once all overload of addToFunctionSummaryMap requires the
464     // Signature explicitly given.
465     Summary &setSignature(const Signature &S) {
466       Sign = S;
467       return *this;
468     }
469 
470     Summary &Case(ConstraintSet &&CS) {
471       CaseConstraints.push_back(std::move(CS));
472       return *this;
473     }
474     Summary &ArgConstraint(ValueConstraintPtr VC) {
475       assert(VC->getArgNo() != Ret &&
476              "Arg constraint should not refer to the return value");
477       ArgConstraints.push_back(VC);
478       return *this;
479     }
480 
481     InvalidationKind getInvalidationKd() const { return InvalidationKd; }
482     const Cases &getCaseConstraints() const { return CaseConstraints; }
483     const ConstraintSet &getArgConstraints() const { return ArgConstraints; }
484 
485     QualType getArgType(ArgNo ArgN) const {
486       return StdLibraryFunctionsChecker::getArgType(FD, ArgN);
487     }
488 
489     // Returns true if the summary should be applied to the given function.
490     // And if yes then store the function declaration.
491     bool matchesAndSet(const FunctionDecl *FD) {
492       assert(Sign &&
493              "Signature must be set before comparing to a FunctionDecl");
494       bool Result = Sign->matches(FD) && validateByConstraints(FD);
495       if (Result) {
496         assert(!this->FD && "FD must not be set more than once");
497         this->FD = FD;
498       }
499       return Result;
500     }
501 
502     // FIXME Remove, once all overload of addToFunctionSummaryMap requires the
503     // Signature explicitly given.
504     bool hasInvalidSignature() {
505       assert(Sign && "Signature must be set before this query");
506       return Sign->isInvalid();
507     }
508 
509   private:
510     // Once we know the exact type of the function then do sanity check on all
511     // the given constraints.
512     bool validateByConstraints(const FunctionDecl *FD) const {
513       for (const ConstraintSet &Case : CaseConstraints)
514         for (const ValueConstraintPtr &Constraint : Case)
515           if (!Constraint->checkValidity(FD))
516             return false;
517       for (const ValueConstraintPtr &Constraint : ArgConstraints)
518         if (!Constraint->checkValidity(FD))
519           return false;
520       return true;
521     }
522   };
523 
524   // The map of all functions supported by the checker. It is initialized
525   // lazily, and it doesn't change after initialization.
526   using FunctionSummaryMapType = llvm::DenseMap<const FunctionDecl *, Summary>;
527   mutable FunctionSummaryMapType FunctionSummaryMap;
528 
529   mutable std::unique_ptr<BugType> BT_InvalidArg;
530 
531   static SVal getArgSVal(const CallEvent &Call, ArgNo ArgN) {
532     return ArgN == Ret ? Call.getReturnValue() : Call.getArgSVal(ArgN);
533   }
534 
535 public:
536   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
537   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
538   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
539 
540   enum CheckKind {
541     CK_StdCLibraryFunctionArgsChecker,
542     CK_StdCLibraryFunctionsTesterChecker,
543     CK_NumCheckKinds
544   };
545   DefaultBool ChecksEnabled[CK_NumCheckKinds];
546   CheckerNameRef CheckNames[CK_NumCheckKinds];
547 
548   bool DisplayLoadedSummaries = false;
549   bool ModelPOSIX = false;
550 
551 private:
552   Optional<Summary> findFunctionSummary(const FunctionDecl *FD,
553                                         CheckerContext &C) const;
554   Optional<Summary> findFunctionSummary(const CallEvent &Call,
555                                         CheckerContext &C) const;
556 
557   void initFunctionSummaries(CheckerContext &C) const;
558 
559   void reportBug(const CallEvent &Call, ExplodedNode *N,
560                  const ValueConstraint *VC, CheckerContext &C) const {
561     if (!ChecksEnabled[CK_StdCLibraryFunctionArgsChecker])
562       return;
563     // TODO Add more detailed diagnostic.
564     std::string Msg =
565         (Twine("Function argument constraint is not satisfied, constraint: ") +
566          VC->getName().data() + ", ArgN: " + Twine(VC->getArgNo()))
567             .str();
568     if (!BT_InvalidArg)
569       BT_InvalidArg = std::make_unique<BugType>(
570           CheckNames[CK_StdCLibraryFunctionArgsChecker],
571           "Unsatisfied argument constraints", categories::LogicError);
572     auto R = std::make_unique<PathSensitiveBugReport>(*BT_InvalidArg, Msg, N);
573     bugreporter::trackExpressionValue(N, Call.getArgExpr(VC->getArgNo()), *R);
574 
575     // Highlight the range of the argument that was violated.
576     R->addRange(Call.getArgSourceRange(VC->getArgNo()));
577 
578     C.emitReport(std::move(R));
579   }
580 };
581 
582 const StdLibraryFunctionsChecker::ArgNo StdLibraryFunctionsChecker::Ret =
583     std::numeric_limits<ArgNo>::max();
584 
585 } // end of anonymous namespace
586 
587 ProgramStateRef StdLibraryFunctionsChecker::RangeConstraint::applyAsOutOfRange(
588     ProgramStateRef State, const CallEvent &Call,
589     const Summary &Summary) const {
590   if (Ranges.empty())
591     return State;
592 
593   ProgramStateManager &Mgr = State->getStateManager();
594   SValBuilder &SVB = Mgr.getSValBuilder();
595   BasicValueFactory &BVF = SVB.getBasicValueFactory();
596   ConstraintManager &CM = Mgr.getConstraintManager();
597   QualType T = Summary.getArgType(getArgNo());
598   SVal V = getArgSVal(Call, getArgNo());
599 
600   if (auto N = V.getAs<NonLoc>()) {
601     const IntRangeVector &R = getRanges();
602     size_t E = R.size();
603     for (size_t I = 0; I != E; ++I) {
604       const llvm::APSInt &Min = BVF.getValue(R[I].first, T);
605       const llvm::APSInt &Max = BVF.getValue(R[I].second, T);
606       assert(Min <= Max);
607       State = CM.assumeInclusiveRange(State, *N, Min, Max, false);
608       if (!State)
609         break;
610     }
611   }
612 
613   return State;
614 }
615 
616 ProgramStateRef StdLibraryFunctionsChecker::RangeConstraint::applyAsWithinRange(
617     ProgramStateRef State, const CallEvent &Call,
618     const Summary &Summary) const {
619   if (Ranges.empty())
620     return State;
621 
622   ProgramStateManager &Mgr = State->getStateManager();
623   SValBuilder &SVB = Mgr.getSValBuilder();
624   BasicValueFactory &BVF = SVB.getBasicValueFactory();
625   ConstraintManager &CM = Mgr.getConstraintManager();
626   QualType T = Summary.getArgType(getArgNo());
627   SVal V = getArgSVal(Call, getArgNo());
628 
629   // "WithinRange R" is treated as "outside [T_MIN, T_MAX] \ R".
630   // We cut off [T_MIN, min(R) - 1] and [max(R) + 1, T_MAX] if necessary,
631   // and then cut away all holes in R one by one.
632   //
633   // E.g. consider a range list R as [A, B] and [C, D]
634   // -------+--------+------------------+------------+----------->
635   //        A        B                  C            D
636   // Then we assume that the value is not in [-inf, A - 1],
637   // then not in [D + 1, +inf], then not in [B + 1, C - 1]
638   if (auto N = V.getAs<NonLoc>()) {
639     const IntRangeVector &R = getRanges();
640     size_t E = R.size();
641 
642     const llvm::APSInt &MinusInf = BVF.getMinValue(T);
643     const llvm::APSInt &PlusInf = BVF.getMaxValue(T);
644 
645     const llvm::APSInt &Left = BVF.getValue(R[0].first - 1ULL, T);
646     if (Left != PlusInf) {
647       assert(MinusInf <= Left);
648       State = CM.assumeInclusiveRange(State, *N, MinusInf, Left, false);
649       if (!State)
650         return nullptr;
651     }
652 
653     const llvm::APSInt &Right = BVF.getValue(R[E - 1].second + 1ULL, T);
654     if (Right != MinusInf) {
655       assert(Right <= PlusInf);
656       State = CM.assumeInclusiveRange(State, *N, Right, PlusInf, false);
657       if (!State)
658         return nullptr;
659     }
660 
661     for (size_t I = 1; I != E; ++I) {
662       const llvm::APSInt &Min = BVF.getValue(R[I - 1].second + 1ULL, T);
663       const llvm::APSInt &Max = BVF.getValue(R[I].first - 1ULL, T);
664       if (Min <= Max) {
665         State = CM.assumeInclusiveRange(State, *N, Min, Max, false);
666         if (!State)
667           return nullptr;
668       }
669     }
670   }
671 
672   return State;
673 }
674 
675 ProgramStateRef StdLibraryFunctionsChecker::ComparisonConstraint::apply(
676     ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
677     CheckerContext &C) const {
678 
679   ProgramStateManager &Mgr = State->getStateManager();
680   SValBuilder &SVB = Mgr.getSValBuilder();
681   QualType CondT = SVB.getConditionType();
682   QualType T = Summary.getArgType(getArgNo());
683   SVal V = getArgSVal(Call, getArgNo());
684 
685   BinaryOperator::Opcode Op = getOpcode();
686   ArgNo OtherArg = getOtherArgNo();
687   SVal OtherV = getArgSVal(Call, OtherArg);
688   QualType OtherT = Summary.getArgType(OtherArg);
689   // Note: we avoid integral promotion for comparison.
690   OtherV = SVB.evalCast(OtherV, T, OtherT);
691   if (auto CompV = SVB.evalBinOp(State, Op, V, OtherV, CondT)
692                        .getAs<DefinedOrUnknownSVal>())
693     State = State->assume(*CompV, true);
694   return State;
695 }
696 
697 void StdLibraryFunctionsChecker::checkPreCall(const CallEvent &Call,
698                                               CheckerContext &C) const {
699   Optional<Summary> FoundSummary = findFunctionSummary(Call, C);
700   if (!FoundSummary)
701     return;
702 
703   const Summary &Summary = *FoundSummary;
704   ProgramStateRef State = C.getState();
705 
706   ProgramStateRef NewState = State;
707   for (const ValueConstraintPtr &Constraint : Summary.getArgConstraints()) {
708     ProgramStateRef SuccessSt = Constraint->apply(NewState, Call, Summary, C);
709     ProgramStateRef FailureSt =
710         Constraint->negate()->apply(NewState, Call, Summary, C);
711     // The argument constraint is not satisfied.
712     if (FailureSt && !SuccessSt) {
713       if (ExplodedNode *N = C.generateErrorNode(NewState))
714         reportBug(Call, N, Constraint.get(), C);
715       break;
716     } else {
717       // We will apply the constraint even if we cannot reason about the
718       // argument. This means both SuccessSt and FailureSt can be true. If we
719       // weren't applying the constraint that would mean that symbolic
720       // execution continues on a code whose behaviour is undefined.
721       assert(SuccessSt);
722       NewState = SuccessSt;
723     }
724   }
725   if (NewState && NewState != State)
726     C.addTransition(NewState);
727 }
728 
729 void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call,
730                                                CheckerContext &C) const {
731   Optional<Summary> FoundSummary = findFunctionSummary(Call, C);
732   if (!FoundSummary)
733     return;
734 
735   // Now apply the constraints.
736   const Summary &Summary = *FoundSummary;
737   ProgramStateRef State = C.getState();
738 
739   // Apply case/branch specifications.
740   for (const ConstraintSet &Case : Summary.getCaseConstraints()) {
741     ProgramStateRef NewState = State;
742     for (const ValueConstraintPtr &Constraint : Case) {
743       NewState = Constraint->apply(NewState, Call, Summary, C);
744       if (!NewState)
745         break;
746     }
747 
748     if (NewState && NewState != State)
749       C.addTransition(NewState);
750   }
751 }
752 
753 bool StdLibraryFunctionsChecker::evalCall(const CallEvent &Call,
754                                           CheckerContext &C) const {
755   Optional<Summary> FoundSummary = findFunctionSummary(Call, C);
756   if (!FoundSummary)
757     return false;
758 
759   const Summary &Summary = *FoundSummary;
760   switch (Summary.getInvalidationKd()) {
761   case EvalCallAsPure: {
762     ProgramStateRef State = C.getState();
763     const LocationContext *LC = C.getLocationContext();
764     const auto *CE = cast_or_null<CallExpr>(Call.getOriginExpr());
765     SVal V = C.getSValBuilder().conjureSymbolVal(
766         CE, LC, CE->getType().getCanonicalType(), C.blockCount());
767     State = State->BindExpr(CE, LC, V);
768     C.addTransition(State);
769     return true;
770   }
771   case NoEvalCall:
772     // Summary tells us to avoid performing eval::Call. The function is possibly
773     // evaluated by another checker, or evaluated conservatively.
774     return false;
775   }
776   llvm_unreachable("Unknown invalidation kind!");
777 }
778 
779 bool StdLibraryFunctionsChecker::Signature::matches(
780     const FunctionDecl *FD) const {
781   assert(!isInvalid());
782   // Check the number of arguments.
783   if (FD->param_size() != ArgTys.size())
784     return false;
785 
786   // The "restrict" keyword is illegal in C++, however, many libc
787   // implementations use the "__restrict" compiler intrinsic in functions
788   // prototypes. The "__restrict" keyword qualifies a type as a restricted type
789   // even in C++.
790   // In case of any non-C99 languages, we don't want to match based on the
791   // restrict qualifier because we cannot know if the given libc implementation
792   // qualifies the paramter type or not.
793   auto RemoveRestrict = [&FD](QualType T) {
794     if (!FD->getASTContext().getLangOpts().C99)
795       T.removeLocalRestrict();
796     return T;
797   };
798 
799   // Check the return type.
800   if (!isIrrelevant(RetTy)) {
801     QualType FDRetTy = RemoveRestrict(FD->getReturnType().getCanonicalType());
802     if (RetTy != FDRetTy)
803       return false;
804   }
805 
806   // Check the argument types.
807   for (size_t I = 0, E = ArgTys.size(); I != E; ++I) {
808     QualType ArgTy = ArgTys[I];
809     if (isIrrelevant(ArgTy))
810       continue;
811     QualType FDArgTy =
812         RemoveRestrict(FD->getParamDecl(I)->getType().getCanonicalType());
813     if (ArgTy != FDArgTy)
814       return false;
815   }
816 
817   return true;
818 }
819 
820 Optional<StdLibraryFunctionsChecker::Summary>
821 StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD,
822                                                 CheckerContext &C) const {
823   if (!FD)
824     return None;
825 
826   initFunctionSummaries(C);
827 
828   auto FSMI = FunctionSummaryMap.find(FD->getCanonicalDecl());
829   if (FSMI == FunctionSummaryMap.end())
830     return None;
831   return FSMI->second;
832 }
833 
834 Optional<StdLibraryFunctionsChecker::Summary>
835 StdLibraryFunctionsChecker::findFunctionSummary(const CallEvent &Call,
836                                                 CheckerContext &C) const {
837   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
838   if (!FD)
839     return None;
840   return findFunctionSummary(FD, C);
841 }
842 
843 void StdLibraryFunctionsChecker::initFunctionSummaries(
844     CheckerContext &C) const {
845   if (!FunctionSummaryMap.empty())
846     return;
847 
848   SValBuilder &SVB = C.getSValBuilder();
849   BasicValueFactory &BVF = SVB.getBasicValueFactory();
850   const ASTContext &ACtx = BVF.getContext();
851 
852   // Helper class to lookup a type by its name.
853   class LookupType {
854     const ASTContext &ACtx;
855 
856   public:
857     LookupType(const ASTContext &ACtx) : ACtx(ACtx) {}
858 
859     // Find the type. If not found then the optional is not set.
860     llvm::Optional<QualType> operator()(StringRef Name) {
861       IdentifierInfo &II = ACtx.Idents.get(Name);
862       auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II);
863       if (LookupRes.size() == 0)
864         return None;
865 
866       // Prioritze typedef declarations.
867       // This is needed in case of C struct typedefs. E.g.:
868       //   typedef struct FILE FILE;
869       // In this case, we have a RecordDecl 'struct FILE' with the name 'FILE'
870       // and we have a TypedefDecl with the name 'FILE'.
871       for (Decl *D : LookupRes)
872         if (auto *TD = dyn_cast<TypedefNameDecl>(D))
873           return ACtx.getTypeDeclType(TD).getCanonicalType();
874 
875       // Find the first TypeDecl.
876       // There maybe cases when a function has the same name as a struct.
877       // E.g. in POSIX: `struct stat` and the function `stat()`:
878       //   int stat(const char *restrict path, struct stat *restrict buf);
879       for (Decl *D : LookupRes)
880         if (auto *TD = dyn_cast<TypeDecl>(D))
881           return ACtx.getTypeDeclType(TD).getCanonicalType();
882       return None;
883     }
884   } lookupTy(ACtx);
885 
886   // Below are auxiliary classes to handle optional types that we get as a
887   // result of the lookup.
888   class GetRestrictTy {
889     const ASTContext &ACtx;
890 
891   public:
892     GetRestrictTy(const ASTContext &ACtx) : ACtx(ACtx) {}
893     QualType operator()(QualType Ty) {
894       return ACtx.getLangOpts().C99 ? ACtx.getRestrictType(Ty) : Ty;
895     }
896     Optional<QualType> operator()(Optional<QualType> Ty) {
897       if (Ty)
898         return operator()(*Ty);
899       return None;
900     }
901   } getRestrictTy(ACtx);
902   class GetPointerTy {
903     const ASTContext &ACtx;
904 
905   public:
906     GetPointerTy(const ASTContext &ACtx) : ACtx(ACtx) {}
907     QualType operator()(QualType Ty) { return ACtx.getPointerType(Ty); }
908     Optional<QualType> operator()(Optional<QualType> Ty) {
909       if (Ty)
910         return operator()(*Ty);
911       return None;
912     }
913   } getPointerTy(ACtx);
914   class {
915   public:
916     Optional<QualType> operator()(Optional<QualType> Ty) {
917       return Ty ? Optional<QualType>(Ty->withConst()) : None;
918     }
919     QualType operator()(QualType Ty) { return Ty.withConst(); }
920   } getConstTy;
921   class GetMaxValue {
922     BasicValueFactory &BVF;
923 
924   public:
925     GetMaxValue(BasicValueFactory &BVF) : BVF(BVF) {}
926     Optional<RangeInt> operator()(QualType Ty) {
927       return BVF.getMaxValue(Ty).getLimitedValue();
928     }
929     Optional<RangeInt> operator()(Optional<QualType> Ty) {
930       if (Ty) {
931         return operator()(*Ty);
932       }
933       return None;
934     }
935   } getMaxValue(BVF);
936 
937   // These types are useful for writing specifications quickly,
938   // New specifications should probably introduce more types.
939   // Some types are hard to obtain from the AST, eg. "ssize_t".
940   // In such cases it should be possible to provide multiple variants
941   // of function summary for common cases (eg. ssize_t could be int or long
942   // or long long, so three summary variants would be enough).
943   // Of course, function variants are also useful for C++ overloads.
944   const QualType VoidTy = ACtx.VoidTy;
945   const QualType CharTy = ACtx.CharTy;
946   const QualType WCharTy = ACtx.WCharTy;
947   const QualType IntTy = ACtx.IntTy;
948   const QualType UnsignedIntTy = ACtx.UnsignedIntTy;
949   const QualType LongTy = ACtx.LongTy;
950   const QualType LongLongTy = ACtx.LongLongTy;
951   const QualType SizeTy = ACtx.getSizeType();
952 
953   const QualType VoidPtrTy = getPointerTy(VoidTy); // void *
954   const QualType IntPtrTy = getPointerTy(IntTy);   // int *
955   const QualType UnsignedIntPtrTy =
956       getPointerTy(UnsignedIntTy); // unsigned int *
957   const QualType VoidPtrRestrictTy = getRestrictTy(VoidPtrTy);
958   const QualType ConstVoidPtrTy =
959       getPointerTy(getConstTy(VoidTy));            // const void *
960   const QualType CharPtrTy = getPointerTy(CharTy); // char *
961   const QualType CharPtrRestrictTy = getRestrictTy(CharPtrTy);
962   const QualType ConstCharPtrTy =
963       getPointerTy(getConstTy(CharTy)); // const char *
964   const QualType ConstCharPtrRestrictTy = getRestrictTy(ConstCharPtrTy);
965   const QualType Wchar_tPtrTy = getPointerTy(WCharTy); // wchar_t *
966   const QualType ConstWchar_tPtrTy =
967       getPointerTy(getConstTy(WCharTy)); // const wchar_t *
968   const QualType ConstVoidPtrRestrictTy = getRestrictTy(ConstVoidPtrTy);
969   const QualType SizePtrTy = getPointerTy(SizeTy);
970   const QualType SizePtrRestrictTy = getRestrictTy(SizePtrTy);
971 
972   const RangeInt IntMax = BVF.getMaxValue(IntTy).getLimitedValue();
973   const RangeInt UnsignedIntMax =
974       BVF.getMaxValue(UnsignedIntTy).getLimitedValue();
975   const RangeInt LongMax = BVF.getMaxValue(LongTy).getLimitedValue();
976   const RangeInt LongLongMax = BVF.getMaxValue(LongLongTy).getLimitedValue();
977   const RangeInt SizeMax = BVF.getMaxValue(SizeTy).getLimitedValue();
978 
979   // Set UCharRangeMax to min of int or uchar maximum value.
980   // The C standard states that the arguments of functions like isalpha must
981   // be representable as an unsigned char. Their type is 'int', so the max
982   // value of the argument should be min(UCharMax, IntMax). This just happen
983   // to be true for commonly used and well tested instruction set
984   // architectures, but not for others.
985   const RangeInt UCharRangeMax =
986       std::min(BVF.getMaxValue(ACtx.UnsignedCharTy).getLimitedValue(), IntMax);
987 
988   // The platform dependent value of EOF.
989   // Try our best to parse this from the Preprocessor, otherwise fallback to -1.
990   const auto EOFv = [&C]() -> RangeInt {
991     if (const llvm::Optional<int> OptInt =
992             tryExpandAsInteger("EOF", C.getPreprocessor()))
993       return *OptInt;
994     return -1;
995   }();
996 
997   // Auxiliary class to aid adding summaries to the summary map.
998   struct AddToFunctionSummaryMap {
999     const ASTContext &ACtx;
1000     FunctionSummaryMapType &Map;
1001     bool DisplayLoadedSummaries;
1002     AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType &FSM,
1003                             bool DisplayLoadedSummaries)
1004         : ACtx(ACtx), Map(FSM), DisplayLoadedSummaries(DisplayLoadedSummaries) {
1005     }
1006 
1007     // Add a summary to a FunctionDecl found by lookup. The lookup is performed
1008     // by the given Name, and in the global scope. The summary will be attached
1009     // to the found FunctionDecl only if the signatures match.
1010     //
1011     // Returns true if the summary has been added, false otherwise.
1012     // FIXME remove all overloads without the explicit Signature parameter.
1013     bool operator()(StringRef Name, Summary S) {
1014       if (S.hasInvalidSignature())
1015         return false;
1016       IdentifierInfo &II = ACtx.Idents.get(Name);
1017       auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II);
1018       if (LookupRes.size() == 0)
1019         return false;
1020       for (Decl *D : LookupRes) {
1021         if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1022           if (S.matchesAndSet(FD)) {
1023             auto Res = Map.insert({FD->getCanonicalDecl(), S});
1024             assert(Res.second && "Function already has a summary set!");
1025             (void)Res;
1026             if (DisplayLoadedSummaries) {
1027               llvm::errs() << "Loaded summary for: ";
1028               FD->print(llvm::errs());
1029               llvm::errs() << "\n";
1030             }
1031             return true;
1032           }
1033         }
1034       }
1035       return false;
1036     }
1037     // Add the summary with the Signature explicitly given.
1038     bool operator()(StringRef Name, Signature Sign, Summary Sum) {
1039       return operator()(Name, Sum.setSignature(Sign));
1040     }
1041     // Add several summaries for the given name.
1042     void operator()(StringRef Name, const std::vector<Summary> &Summaries) {
1043       for (const Summary &S : Summaries)
1044         operator()(Name, S);
1045     }
1046     // Add the same summary for different names with the Signature explicitly
1047     // given.
1048     void operator()(std::vector<StringRef> Names, Signature Sign, Summary Sum) {
1049       for (StringRef Name : Names)
1050         operator()(Name, Sign, Sum);
1051     }
1052   } addToFunctionSummaryMap(ACtx, FunctionSummaryMap, DisplayLoadedSummaries);
1053 
1054   // Below are helpers functions to create the summaries.
1055   auto ArgumentCondition = [](ArgNo ArgN, RangeKind Kind,
1056                               IntRangeVector Ranges) {
1057     return std::make_shared<RangeConstraint>(ArgN, Kind, Ranges);
1058   };
1059   auto BufferSize = [](auto... Args) {
1060     return std::make_shared<BufferSizeConstraint>(Args...);
1061   };
1062   struct {
1063     auto operator()(RangeKind Kind, IntRangeVector Ranges) {
1064       return std::make_shared<RangeConstraint>(Ret, Kind, Ranges);
1065     }
1066     auto operator()(BinaryOperator::Opcode Op, ArgNo OtherArgN) {
1067       return std::make_shared<ComparisonConstraint>(Ret, Op, OtherArgN);
1068     }
1069   } ReturnValueCondition;
1070   struct {
1071     auto operator()(RangeInt b, RangeInt e) {
1072       return IntRangeVector{std::pair<RangeInt, RangeInt>{b, e}};
1073     }
1074     auto operator()(RangeInt b, Optional<RangeInt> e) {
1075       if (e)
1076         return IntRangeVector{std::pair<RangeInt, RangeInt>{b, *e}};
1077       return IntRangeVector{};
1078     }
1079   } Range;
1080   auto SingleValue = [](RangeInt v) {
1081     return IntRangeVector{std::pair<RangeInt, RangeInt>{v, v}};
1082   };
1083   auto LessThanOrEq = BO_LE;
1084   auto NotNull = [&](ArgNo ArgN) {
1085     return std::make_shared<NotNullConstraint>(ArgN);
1086   };
1087 
1088   Optional<QualType> FileTy = lookupTy("FILE");
1089   Optional<QualType> FilePtrTy = getPointerTy(FileTy);
1090   Optional<QualType> FilePtrRestrictTy = getRestrictTy(FilePtrTy);
1091 
1092   // Templates for summaries that are reused by many functions.
1093   auto Getc = [&]() {
1094     return Summary(ArgTypes{FilePtrTy}, RetType{IntTy}, NoEvalCall)
1095         .Case({ReturnValueCondition(WithinRange,
1096                                     {{EOFv, EOFv}, {0, UCharRangeMax}})});
1097   };
1098   auto Read = [&](RetType R, RangeInt Max) {
1099     return Summary(ArgTypes{Irrelevant, Irrelevant, SizeTy}, RetType{R},
1100                    NoEvalCall)
1101         .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)),
1102                ReturnValueCondition(WithinRange, Range(-1, Max))});
1103   };
1104   auto Fread = [&]() {
1105     return Summary(
1106                ArgTypes{VoidPtrRestrictTy, SizeTy, SizeTy, FilePtrRestrictTy},
1107                RetType{SizeTy}, NoEvalCall)
1108         .Case({
1109             ReturnValueCondition(LessThanOrEq, ArgNo(2)),
1110         })
1111         .ArgConstraint(NotNull(ArgNo(0)));
1112   };
1113   auto Fwrite = [&]() {
1114     return Summary(ArgTypes{ConstVoidPtrRestrictTy, SizeTy, SizeTy,
1115                             FilePtrRestrictTy},
1116                    RetType{SizeTy}, NoEvalCall)
1117         .Case({
1118             ReturnValueCondition(LessThanOrEq, ArgNo(2)),
1119         })
1120         .ArgConstraint(NotNull(ArgNo(0)));
1121   };
1122   auto Getline = [&](RetType R, RangeInt Max) {
1123     return Summary(ArgTypes{Irrelevant, Irrelevant, Irrelevant}, RetType{R},
1124                    NoEvalCall)
1125         .Case({ReturnValueCondition(WithinRange, {{-1, -1}, {1, Max}})});
1126   };
1127 
1128   // We are finally ready to define specifications for all supported functions.
1129   //
1130   // Argument ranges should always cover all variants. If return value
1131   // is completely unknown, omit it from the respective range set.
1132   //
1133   // Every item in the list of range sets represents a particular
1134   // execution path the analyzer would need to explore once
1135   // the call is modeled - a new program state is constructed
1136   // for every range set, and each range line in the range set
1137   // corresponds to a specific constraint within this state.
1138 
1139   // The isascii() family of functions.
1140   // The behavior is undefined if the value of the argument is not
1141   // representable as unsigned char or is not equal to EOF. See e.g. C99
1142   // 7.4.1.2 The isalpha function (p: 181-182).
1143   addToFunctionSummaryMap(
1144       "isalnum",
1145       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1146           // Boils down to isupper() or islower() or isdigit().
1147           .Case({ArgumentCondition(0U, WithinRange,
1148                                    {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}}),
1149                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1150           // The locale-specific range.
1151           // No post-condition. We are completely unaware of
1152           // locale-specific return values.
1153           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1154           .Case(
1155               {ArgumentCondition(
1156                    0U, OutOfRange,
1157                    {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}),
1158                ReturnValueCondition(WithinRange, SingleValue(0))})
1159           .ArgConstraint(ArgumentCondition(
1160               0U, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})));
1161   addToFunctionSummaryMap(
1162       "isalpha",
1163       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1164           .Case({ArgumentCondition(0U, WithinRange, {{'A', 'Z'}, {'a', 'z'}}),
1165                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1166           // The locale-specific range.
1167           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1168           .Case({ArgumentCondition(
1169                      0U, OutOfRange,
1170                      {{'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}),
1171                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1172   addToFunctionSummaryMap(
1173       "isascii",
1174       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1175           .Case({ArgumentCondition(0U, WithinRange, Range(0, 127)),
1176                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1177           .Case({ArgumentCondition(0U, OutOfRange, Range(0, 127)),
1178                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1179   addToFunctionSummaryMap(
1180       "isblank",
1181       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1182           .Case({ArgumentCondition(0U, WithinRange, {{'\t', '\t'}, {' ', ' '}}),
1183                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1184           .Case({ArgumentCondition(0U, OutOfRange, {{'\t', '\t'}, {' ', ' '}}),
1185                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1186   addToFunctionSummaryMap(
1187       "iscntrl",
1188       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1189           .Case({ArgumentCondition(0U, WithinRange, {{0, 32}, {127, 127}}),
1190                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1191           .Case({ArgumentCondition(0U, OutOfRange, {{0, 32}, {127, 127}}),
1192                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1193   addToFunctionSummaryMap(
1194       "isdigit",
1195       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1196           .Case({ArgumentCondition(0U, WithinRange, Range('0', '9')),
1197                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1198           .Case({ArgumentCondition(0U, OutOfRange, Range('0', '9')),
1199                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1200   addToFunctionSummaryMap(
1201       "isgraph",
1202       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1203           .Case({ArgumentCondition(0U, WithinRange, Range(33, 126)),
1204                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1205           .Case({ArgumentCondition(0U, OutOfRange, Range(33, 126)),
1206                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1207   addToFunctionSummaryMap(
1208       "islower",
1209       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1210           // Is certainly lowercase.
1211           .Case({ArgumentCondition(0U, WithinRange, Range('a', 'z')),
1212                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1213           // Is ascii but not lowercase.
1214           .Case({ArgumentCondition(0U, WithinRange, Range(0, 127)),
1215                  ArgumentCondition(0U, OutOfRange, Range('a', 'z')),
1216                  ReturnValueCondition(WithinRange, SingleValue(0))})
1217           // The locale-specific range.
1218           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1219           // Is not an unsigned char.
1220           .Case({ArgumentCondition(0U, OutOfRange, Range(0, UCharRangeMax)),
1221                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1222   addToFunctionSummaryMap(
1223       "isprint",
1224       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1225           .Case({ArgumentCondition(0U, WithinRange, Range(32, 126)),
1226                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1227           .Case({ArgumentCondition(0U, OutOfRange, Range(32, 126)),
1228                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1229   addToFunctionSummaryMap(
1230       "ispunct",
1231       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1232           .Case({ArgumentCondition(
1233                      0U, WithinRange,
1234                      {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}),
1235                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1236           .Case({ArgumentCondition(
1237                      0U, OutOfRange,
1238                      {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}),
1239                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1240   addToFunctionSummaryMap(
1241       "isspace",
1242       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1243           // Space, '\f', '\n', '\r', '\t', '\v'.
1244           .Case({ArgumentCondition(0U, WithinRange, {{9, 13}, {' ', ' '}}),
1245                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1246           // The locale-specific range.
1247           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1248           .Case({ArgumentCondition(0U, OutOfRange,
1249                                    {{9, 13}, {' ', ' '}, {128, UCharRangeMax}}),
1250                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1251   addToFunctionSummaryMap(
1252       "isupper",
1253       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1254           // Is certainly uppercase.
1255           .Case({ArgumentCondition(0U, WithinRange, Range('A', 'Z')),
1256                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1257           // The locale-specific range.
1258           .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})})
1259           // Other.
1260           .Case({ArgumentCondition(0U, OutOfRange,
1261                                    {{'A', 'Z'}, {128, UCharRangeMax}}),
1262                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1263   addToFunctionSummaryMap(
1264       "isxdigit",
1265       Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1266           .Case({ArgumentCondition(0U, WithinRange,
1267                                    {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}),
1268                  ReturnValueCondition(OutOfRange, SingleValue(0))})
1269           .Case({ArgumentCondition(0U, OutOfRange,
1270                                    {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}),
1271                  ReturnValueCondition(WithinRange, SingleValue(0))}));
1272   addToFunctionSummaryMap(
1273       "toupper", Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1274                      .ArgConstraint(ArgumentCondition(
1275                          0U, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})));
1276   addToFunctionSummaryMap(
1277       "tolower", Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1278                      .ArgConstraint(ArgumentCondition(
1279                          0U, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})));
1280   addToFunctionSummaryMap(
1281       "toascii", Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
1282                      .ArgConstraint(ArgumentCondition(
1283                          0U, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})));
1284 
1285   // The getc() family of functions that returns either a char or an EOF.
1286     addToFunctionSummaryMap("getc", Getc());
1287     addToFunctionSummaryMap("fgetc", Getc());
1288   addToFunctionSummaryMap(
1289       "getchar", Summary(ArgTypes{}, RetType{IntTy}, NoEvalCall)
1290                      .Case({ReturnValueCondition(
1291                          WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})}));
1292 
1293   // read()-like functions that never return more than buffer size.
1294     addToFunctionSummaryMap("fread", Fread());
1295     addToFunctionSummaryMap("fwrite", Fwrite());
1296 
1297   // We are not sure how ssize_t is defined on every platform, so we
1298   // provide three variants that should cover common cases.
1299   // FIXME these are actually defined by POSIX and not by the C standard, we
1300   // should handle them together with the rest of the POSIX functions.
1301   addToFunctionSummaryMap("read", {Read(IntTy, IntMax), Read(LongTy, LongMax),
1302                                    Read(LongLongTy, LongLongMax)});
1303   addToFunctionSummaryMap("write", {Read(IntTy, IntMax), Read(LongTy, LongMax),
1304                                     Read(LongLongTy, LongLongMax)});
1305 
1306   // getline()-like functions either fail or read at least the delimiter.
1307   // FIXME these are actually defined by POSIX and not by the C standard, we
1308   // should handle them together with the rest of the POSIX functions.
1309   addToFunctionSummaryMap("getline",
1310                           {Getline(IntTy, IntMax), Getline(LongTy, LongMax),
1311                            Getline(LongLongTy, LongLongMax)});
1312   addToFunctionSummaryMap("getdelim",
1313                           {Getline(IntTy, IntMax), Getline(LongTy, LongMax),
1314                            Getline(LongLongTy, LongLongMax)});
1315 
1316   if (ModelPOSIX) {
1317 
1318     // long a64l(const char *str64);
1319     addToFunctionSummaryMap(
1320         "a64l", Summary(ArgTypes{ConstCharPtrTy}, RetType{LongTy}, NoEvalCall)
1321                     .ArgConstraint(NotNull(ArgNo(0))));
1322 
1323     // char *l64a(long value);
1324     addToFunctionSummaryMap(
1325         "l64a", Summary(ArgTypes{LongTy}, RetType{CharPtrTy}, NoEvalCall)
1326                     .ArgConstraint(
1327                         ArgumentCondition(0, WithinRange, Range(0, LongMax))));
1328 
1329     // int access(const char *pathname, int amode);
1330     addToFunctionSummaryMap("access", Summary(ArgTypes{ConstCharPtrTy, IntTy},
1331                                               RetType{IntTy}, NoEvalCall)
1332                                           .ArgConstraint(NotNull(ArgNo(0))));
1333 
1334     // int faccessat(int dirfd, const char *pathname, int mode, int flags);
1335     addToFunctionSummaryMap(
1336         "faccessat", Summary(ArgTypes{IntTy, ConstCharPtrTy, IntTy, IntTy},
1337                              RetType{IntTy}, NoEvalCall)
1338                          .ArgConstraint(NotNull(ArgNo(1))));
1339 
1340     // int dup(int fildes);
1341     addToFunctionSummaryMap(
1342         "dup", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1343                    .ArgConstraint(
1344                        ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1345 
1346     // int dup2(int fildes1, int filedes2);
1347     addToFunctionSummaryMap(
1348         "dup2",
1349         Summary(ArgTypes{IntTy, IntTy}, RetType{IntTy}, NoEvalCall)
1350             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1351             .ArgConstraint(
1352                 ArgumentCondition(1, WithinRange, Range(0, IntMax))));
1353 
1354     // int fdatasync(int fildes);
1355     addToFunctionSummaryMap(
1356         "fdatasync", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1357                          .ArgConstraint(ArgumentCondition(0, WithinRange,
1358                                                           Range(0, IntMax))));
1359 
1360     // int fnmatch(const char *pattern, const char *string, int flags);
1361     addToFunctionSummaryMap(
1362         "fnmatch", Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, IntTy},
1363                            RetType{IntTy}, EvalCallAsPure)
1364                        .ArgConstraint(NotNull(ArgNo(0)))
1365                        .ArgConstraint(NotNull(ArgNo(1))));
1366 
1367     // int fsync(int fildes);
1368     addToFunctionSummaryMap(
1369         "fsync", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1370                      .ArgConstraint(
1371                          ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1372 
1373     Optional<QualType> Off_tTy = lookupTy("off_t");
1374 
1375     // int truncate(const char *path, off_t length);
1376     addToFunctionSummaryMap(
1377         "truncate",
1378         Summary(ArgTypes{ConstCharPtrTy, Off_tTy}, RetType{IntTy}, NoEvalCall)
1379             .ArgConstraint(NotNull(ArgNo(0))));
1380 
1381     // int symlink(const char *oldpath, const char *newpath);
1382     addToFunctionSummaryMap("symlink",
1383                             Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1384                                     RetType{IntTy}, NoEvalCall)
1385                                 .ArgConstraint(NotNull(ArgNo(0)))
1386                                 .ArgConstraint(NotNull(ArgNo(1))));
1387 
1388     // int symlinkat(const char *oldpath, int newdirfd, const char *newpath);
1389     addToFunctionSummaryMap(
1390         "symlinkat",
1391         Summary(ArgTypes{ConstCharPtrTy, IntTy, ConstCharPtrTy}, RetType{IntTy},
1392                 NoEvalCall)
1393             .ArgConstraint(NotNull(ArgNo(0)))
1394             .ArgConstraint(ArgumentCondition(1, WithinRange, Range(0, IntMax)))
1395             .ArgConstraint(NotNull(ArgNo(2))));
1396 
1397     // int lockf(int fd, int cmd, off_t len);
1398     addToFunctionSummaryMap(
1399         "lockf",
1400         Summary(ArgTypes{IntTy, IntTy, Off_tTy}, RetType{IntTy}, NoEvalCall)
1401             .ArgConstraint(
1402                 ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1403 
1404     Optional<QualType> Mode_tTy = lookupTy("mode_t");
1405 
1406     // int creat(const char *pathname, mode_t mode);
1407     addToFunctionSummaryMap("creat", Summary(ArgTypes{ConstCharPtrTy, Mode_tTy},
1408                                              RetType{IntTy}, NoEvalCall)
1409                                          .ArgConstraint(NotNull(ArgNo(0))));
1410 
1411     // unsigned int sleep(unsigned int seconds);
1412     addToFunctionSummaryMap(
1413         "sleep",
1414         Summary(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}, NoEvalCall)
1415             .ArgConstraint(
1416                 ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax))));
1417 
1418     Optional<QualType> DirTy = lookupTy("DIR");
1419     Optional<QualType> DirPtrTy = getPointerTy(DirTy);
1420 
1421     // int dirfd(DIR *dirp);
1422     addToFunctionSummaryMap(
1423         "dirfd", Summary(ArgTypes{DirPtrTy}, RetType{IntTy}, NoEvalCall)
1424                      .ArgConstraint(NotNull(ArgNo(0))));
1425 
1426     // unsigned int alarm(unsigned int seconds);
1427     addToFunctionSummaryMap(
1428         "alarm",
1429         Summary(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}, NoEvalCall)
1430             .ArgConstraint(
1431                 ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax))));
1432 
1433     // int closedir(DIR *dir);
1434     addToFunctionSummaryMap(
1435         "closedir", Summary(ArgTypes{DirPtrTy}, RetType{IntTy}, NoEvalCall)
1436                         .ArgConstraint(NotNull(ArgNo(0))));
1437 
1438     // char *strdup(const char *s);
1439     addToFunctionSummaryMap("strdup", Summary(ArgTypes{ConstCharPtrTy},
1440                                               RetType{CharPtrTy}, NoEvalCall)
1441                                           .ArgConstraint(NotNull(ArgNo(0))));
1442 
1443     // char *strndup(const char *s, size_t n);
1444     addToFunctionSummaryMap(
1445         "strndup", Summary(ArgTypes{ConstCharPtrTy, SizeTy}, RetType{CharPtrTy},
1446                            NoEvalCall)
1447                        .ArgConstraint(NotNull(ArgNo(0)))
1448                        .ArgConstraint(ArgumentCondition(1, WithinRange,
1449                                                         Range(0, SizeMax))));
1450 
1451     // wchar_t *wcsdup(const wchar_t *s);
1452     addToFunctionSummaryMap("wcsdup", Summary(ArgTypes{ConstWchar_tPtrTy},
1453                                               RetType{Wchar_tPtrTy}, NoEvalCall)
1454                                           .ArgConstraint(NotNull(ArgNo(0))));
1455 
1456     // int mkstemp(char *template);
1457     addToFunctionSummaryMap(
1458         "mkstemp", Summary(ArgTypes{CharPtrTy}, RetType{IntTy}, NoEvalCall)
1459                        .ArgConstraint(NotNull(ArgNo(0))));
1460 
1461     // char *mkdtemp(char *template);
1462     addToFunctionSummaryMap(
1463         "mkdtemp", Summary(ArgTypes{CharPtrTy}, RetType{CharPtrTy}, NoEvalCall)
1464                        .ArgConstraint(NotNull(ArgNo(0))));
1465 
1466     // char *getcwd(char *buf, size_t size);
1467     addToFunctionSummaryMap(
1468         "getcwd",
1469         Summary(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}, NoEvalCall)
1470             .ArgConstraint(
1471                 ArgumentCondition(1, WithinRange, Range(0, SizeMax))));
1472 
1473     // int mkdir(const char *pathname, mode_t mode);
1474     addToFunctionSummaryMap("mkdir", Summary(ArgTypes{ConstCharPtrTy, Mode_tTy},
1475                                              RetType{IntTy}, NoEvalCall)
1476                                          .ArgConstraint(NotNull(ArgNo(0))));
1477 
1478     // int mkdirat(int dirfd, const char *pathname, mode_t mode);
1479     addToFunctionSummaryMap("mkdirat",
1480                             Summary(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy},
1481                                     RetType{IntTy}, NoEvalCall)
1482                                 .ArgConstraint(NotNull(ArgNo(1))));
1483 
1484     Optional<QualType> Dev_tTy = lookupTy("dev_t");
1485 
1486     // int mknod(const char *pathname, mode_t mode, dev_t dev);
1487     addToFunctionSummaryMap("mknod",
1488                             Summary(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy},
1489                                     RetType{IntTy}, NoEvalCall)
1490                                 .ArgConstraint(NotNull(ArgNo(0))));
1491 
1492     // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
1493     addToFunctionSummaryMap(
1494         "mknodat", Summary(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, Dev_tTy},
1495                            RetType{IntTy}, NoEvalCall)
1496                        .ArgConstraint(NotNull(ArgNo(1))));
1497 
1498     // int chmod(const char *path, mode_t mode);
1499     addToFunctionSummaryMap("chmod", Summary(ArgTypes{ConstCharPtrTy, Mode_tTy},
1500                                              RetType{IntTy}, NoEvalCall)
1501                                          .ArgConstraint(NotNull(ArgNo(0))));
1502 
1503     // int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);
1504     addToFunctionSummaryMap(
1505         "fchmodat",
1506         Summary(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, IntTy},
1507                 RetType{IntTy}, NoEvalCall)
1508             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1509             .ArgConstraint(NotNull(ArgNo(1))));
1510 
1511     // int fchmod(int fildes, mode_t mode);
1512     addToFunctionSummaryMap(
1513         "fchmod", Summary(ArgTypes{IntTy, Mode_tTy}, RetType{IntTy}, NoEvalCall)
1514                       .ArgConstraint(
1515                           ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1516 
1517     Optional<QualType> Uid_tTy = lookupTy("uid_t");
1518     Optional<QualType> Gid_tTy = lookupTy("gid_t");
1519 
1520     // int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group,
1521     //              int flags);
1522     addToFunctionSummaryMap(
1523         "fchownat",
1524         Summary(ArgTypes{IntTy, ConstCharPtrTy, Uid_tTy, Gid_tTy, IntTy},
1525                 RetType{IntTy}, NoEvalCall)
1526             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1527             .ArgConstraint(NotNull(ArgNo(1))));
1528 
1529     // int chown(const char *path, uid_t owner, gid_t group);
1530     addToFunctionSummaryMap("chown",
1531                             Summary(ArgTypes{ConstCharPtrTy, Uid_tTy, Gid_tTy},
1532                                     RetType{IntTy}, NoEvalCall)
1533                                 .ArgConstraint(NotNull(ArgNo(0))));
1534 
1535     // int lchown(const char *path, uid_t owner, gid_t group);
1536     addToFunctionSummaryMap("lchown",
1537                             Summary(ArgTypes{ConstCharPtrTy, Uid_tTy, Gid_tTy},
1538                                     RetType{IntTy}, NoEvalCall)
1539                                 .ArgConstraint(NotNull(ArgNo(0))));
1540 
1541     // int fchown(int fildes, uid_t owner, gid_t group);
1542     addToFunctionSummaryMap(
1543         "fchown",
1544         Summary(ArgTypes{IntTy, Uid_tTy, Gid_tTy}, RetType{IntTy}, NoEvalCall)
1545             .ArgConstraint(
1546                 ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1547 
1548     // int rmdir(const char *pathname);
1549     addToFunctionSummaryMap(
1550         "rmdir", Summary(ArgTypes{ConstCharPtrTy}, RetType{IntTy}, NoEvalCall)
1551                      .ArgConstraint(NotNull(ArgNo(0))));
1552 
1553     // int chdir(const char *path);
1554     addToFunctionSummaryMap(
1555         "chdir", Summary(ArgTypes{ConstCharPtrTy}, RetType{IntTy}, NoEvalCall)
1556                      .ArgConstraint(NotNull(ArgNo(0))));
1557 
1558     // int link(const char *oldpath, const char *newpath);
1559     addToFunctionSummaryMap("link",
1560                             Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1561                                     RetType{IntTy}, NoEvalCall)
1562                                 .ArgConstraint(NotNull(ArgNo(0)))
1563                                 .ArgConstraint(NotNull(ArgNo(1))));
1564 
1565     // int linkat(int fd1, const char *path1, int fd2, const char *path2,
1566     //            int flag);
1567     addToFunctionSummaryMap(
1568         "linkat",
1569         Summary(ArgTypes{IntTy, ConstCharPtrTy, IntTy, ConstCharPtrTy, IntTy},
1570                 RetType{IntTy}, NoEvalCall)
1571             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1572             .ArgConstraint(NotNull(ArgNo(1)))
1573             .ArgConstraint(ArgumentCondition(2, WithinRange, Range(0, IntMax)))
1574             .ArgConstraint(NotNull(ArgNo(3))));
1575 
1576     // int unlink(const char *pathname);
1577     addToFunctionSummaryMap(
1578         "unlink", Summary(ArgTypes{ConstCharPtrTy}, RetType{IntTy}, NoEvalCall)
1579                       .ArgConstraint(NotNull(ArgNo(0))));
1580 
1581     // int unlinkat(int fd, const char *path, int flag);
1582     addToFunctionSummaryMap(
1583         "unlinkat",
1584         Summary(ArgTypes{IntTy, ConstCharPtrTy, IntTy}, RetType{IntTy},
1585                 NoEvalCall)
1586             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1587             .ArgConstraint(NotNull(ArgNo(1))));
1588 
1589     Optional<QualType> StructStatTy = lookupTy("stat");
1590     Optional<QualType> StructStatPtrTy = getPointerTy(StructStatTy);
1591     Optional<QualType> StructStatPtrRestrictTy = getRestrictTy(StructStatPtrTy);
1592 
1593     // int fstat(int fd, struct stat *statbuf);
1594     addToFunctionSummaryMap(
1595         "fstat",
1596         Summary(ArgTypes{IntTy, StructStatPtrTy}, RetType{IntTy}, NoEvalCall)
1597             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1598             .ArgConstraint(NotNull(ArgNo(1))));
1599 
1600     // int stat(const char *restrict path, struct stat *restrict buf);
1601     addToFunctionSummaryMap("stat", Summary(ArgTypes{ConstCharPtrRestrictTy,
1602                                                      StructStatPtrRestrictTy},
1603                                             RetType{IntTy}, NoEvalCall)
1604                                         .ArgConstraint(NotNull(ArgNo(0)))
1605                                         .ArgConstraint(NotNull(ArgNo(1))));
1606 
1607     // int lstat(const char *restrict path, struct stat *restrict buf);
1608     addToFunctionSummaryMap("lstat", Summary(ArgTypes{ConstCharPtrRestrictTy,
1609                                                       StructStatPtrRestrictTy},
1610                                              RetType{IntTy}, NoEvalCall)
1611                                          .ArgConstraint(NotNull(ArgNo(0)))
1612                                          .ArgConstraint(NotNull(ArgNo(1))));
1613 
1614     // int fstatat(int fd, const char *restrict path,
1615     //             struct stat *restrict buf, int flag);
1616     addToFunctionSummaryMap(
1617         "fstatat",
1618         Summary(ArgTypes{IntTy, ConstCharPtrRestrictTy, StructStatPtrRestrictTy,
1619                          IntTy},
1620                 RetType{IntTy}, NoEvalCall)
1621             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1622             .ArgConstraint(NotNull(ArgNo(1)))
1623             .ArgConstraint(NotNull(ArgNo(2))));
1624 
1625     // DIR *opendir(const char *name);
1626     addToFunctionSummaryMap("opendir", Summary(ArgTypes{ConstCharPtrTy},
1627                                                RetType{DirPtrTy}, NoEvalCall)
1628                                            .ArgConstraint(NotNull(ArgNo(0))));
1629 
1630     // DIR *fdopendir(int fd);
1631     addToFunctionSummaryMap(
1632         "fdopendir", Summary(ArgTypes{IntTy}, RetType{DirPtrTy}, NoEvalCall)
1633                          .ArgConstraint(ArgumentCondition(0, WithinRange,
1634                                                           Range(0, IntMax))));
1635 
1636     // int isatty(int fildes);
1637     addToFunctionSummaryMap(
1638         "isatty", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1639                       .ArgConstraint(
1640                           ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1641 
1642     // FILE *popen(const char *command, const char *type);
1643     addToFunctionSummaryMap("popen",
1644                             Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
1645                                     RetType{FilePtrTy}, NoEvalCall)
1646                                 .ArgConstraint(NotNull(ArgNo(0)))
1647                                 .ArgConstraint(NotNull(ArgNo(1))));
1648 
1649     // int pclose(FILE *stream);
1650     addToFunctionSummaryMap(
1651         "pclose", Summary(ArgTypes{FilePtrTy}, RetType{IntTy}, NoEvalCall)
1652                       .ArgConstraint(NotNull(ArgNo(0))));
1653 
1654     // int close(int fildes);
1655     addToFunctionSummaryMap(
1656         "close", Summary(ArgTypes{IntTy}, RetType{IntTy}, NoEvalCall)
1657                      .ArgConstraint(
1658                          ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1659 
1660     // long fpathconf(int fildes, int name);
1661     addToFunctionSummaryMap(
1662         "fpathconf",
1663         Summary(ArgTypes{IntTy, IntTy}, RetType{LongTy}, NoEvalCall)
1664             .ArgConstraint(
1665                 ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1666 
1667     // long pathconf(const char *path, int name);
1668     addToFunctionSummaryMap("pathconf", Summary(ArgTypes{ConstCharPtrTy, IntTy},
1669                                                 RetType{LongTy}, NoEvalCall)
1670                                             .ArgConstraint(NotNull(ArgNo(0))));
1671 
1672     // FILE *fdopen(int fd, const char *mode);
1673     addToFunctionSummaryMap(
1674         "fdopen",
1675         Summary(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}, NoEvalCall)
1676             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1677             .ArgConstraint(NotNull(ArgNo(1))));
1678 
1679     // void rewinddir(DIR *dir);
1680     addToFunctionSummaryMap(
1681         "rewinddir", Summary(ArgTypes{DirPtrTy}, RetType{VoidTy}, NoEvalCall)
1682                          .ArgConstraint(NotNull(ArgNo(0))));
1683 
1684     // void seekdir(DIR *dirp, long loc);
1685     addToFunctionSummaryMap("seekdir", Summary(ArgTypes{DirPtrTy, LongTy},
1686                                                RetType{VoidTy}, NoEvalCall)
1687                                            .ArgConstraint(NotNull(ArgNo(0))));
1688 
1689     // int rand_r(unsigned int *seedp);
1690     addToFunctionSummaryMap("rand_r", Summary(ArgTypes{UnsignedIntPtrTy},
1691                                               RetType{IntTy}, NoEvalCall)
1692                                           .ArgConstraint(NotNull(ArgNo(0))));
1693 
1694     // int fileno(FILE *stream);
1695     addToFunctionSummaryMap(
1696         "fileno", Summary(ArgTypes{FilePtrTy}, RetType{IntTy}, NoEvalCall)
1697                       .ArgConstraint(NotNull(ArgNo(0))));
1698 
1699     // int fseeko(FILE *stream, off_t offset, int whence);
1700     addToFunctionSummaryMap(
1701         "fseeko",
1702         Summary(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}, NoEvalCall)
1703             .ArgConstraint(NotNull(ArgNo(0))));
1704 
1705     // off_t ftello(FILE *stream);
1706     addToFunctionSummaryMap(
1707         "ftello", Summary(ArgTypes{FilePtrTy}, RetType{Off_tTy}, NoEvalCall)
1708                       .ArgConstraint(NotNull(ArgNo(0))));
1709 
1710     Optional<RangeInt> Off_tMax = getMaxValue(Off_tTy);
1711     // void *mmap(void *addr, size_t length, int prot, int flags, int fd,
1712     // off_t offset);
1713     addToFunctionSummaryMap(
1714         "mmap",
1715         Summary(ArgTypes{VoidPtrTy, SizeTy, IntTy, IntTy, IntTy, Off_tTy},
1716                 RetType{VoidPtrTy}, NoEvalCall)
1717             .ArgConstraint(ArgumentCondition(1, WithinRange, Range(1, SizeMax)))
1718             .ArgConstraint(
1719                 ArgumentCondition(4, WithinRange, Range(0, Off_tMax))));
1720 
1721     Optional<QualType> Off64_tTy = lookupTy("off64_t");
1722     Optional<RangeInt> Off64_tMax = getMaxValue(Off_tTy);
1723     // void *mmap64(void *addr, size_t length, int prot, int flags, int fd,
1724     // off64_t offset);
1725     addToFunctionSummaryMap(
1726         "mmap64",
1727         Summary(ArgTypes{VoidPtrTy, SizeTy, IntTy, IntTy, IntTy, Off64_tTy},
1728                 RetType{VoidPtrTy}, NoEvalCall)
1729             .ArgConstraint(ArgumentCondition(1, WithinRange, Range(1, SizeMax)))
1730             .ArgConstraint(
1731                 ArgumentCondition(4, WithinRange, Range(0, Off64_tMax))));
1732 
1733     // int pipe(int fildes[2]);
1734     addToFunctionSummaryMap(
1735         "pipe", Summary(ArgTypes{IntPtrTy}, RetType{IntTy}, NoEvalCall)
1736                     .ArgConstraint(NotNull(ArgNo(0))));
1737 
1738     // off_t lseek(int fildes, off_t offset, int whence);
1739     addToFunctionSummaryMap(
1740         "lseek",
1741         Summary(ArgTypes{IntTy, Off_tTy, IntTy}, RetType{Off_tTy}, NoEvalCall)
1742             .ArgConstraint(
1743                 ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1744 
1745     Optional<QualType> Ssize_tTy = lookupTy("ssize_t");
1746 
1747     // ssize_t readlink(const char *restrict path, char *restrict buf,
1748     //                  size_t bufsize);
1749     addToFunctionSummaryMap(
1750         "readlink",
1751         Summary(ArgTypes{ConstCharPtrRestrictTy, CharPtrRestrictTy, SizeTy},
1752                 RetType{Ssize_tTy}, NoEvalCall)
1753             .ArgConstraint(NotNull(ArgNo(0)))
1754             .ArgConstraint(NotNull(ArgNo(1)))
1755             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
1756                                       /*BufSize=*/ArgNo(2)))
1757             .ArgConstraint(
1758                 ArgumentCondition(2, WithinRange, Range(0, SizeMax))));
1759 
1760     // ssize_t readlinkat(int fd, const char *restrict path,
1761     //                    char *restrict buf, size_t bufsize);
1762     addToFunctionSummaryMap(
1763         "readlinkat",
1764         Summary(
1765             ArgTypes{IntTy, ConstCharPtrRestrictTy, CharPtrRestrictTy, SizeTy},
1766             RetType{Ssize_tTy}, NoEvalCall)
1767             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1768             .ArgConstraint(NotNull(ArgNo(1)))
1769             .ArgConstraint(NotNull(ArgNo(2)))
1770             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(2),
1771                                       /*BufSize=*/ArgNo(3)))
1772             .ArgConstraint(
1773                 ArgumentCondition(3, WithinRange, Range(0, SizeMax))));
1774 
1775     // int renameat(int olddirfd, const char *oldpath, int newdirfd, const char
1776     // *newpath);
1777     addToFunctionSummaryMap("renameat", Summary(ArgTypes{IntTy, ConstCharPtrTy,
1778                                                          IntTy, ConstCharPtrTy},
1779                                                 RetType{IntTy}, NoEvalCall)
1780                                             .ArgConstraint(NotNull(ArgNo(1)))
1781                                             .ArgConstraint(NotNull(ArgNo(3))));
1782 
1783     // char *realpath(const char *restrict file_name,
1784     //                char *restrict resolved_name);
1785     addToFunctionSummaryMap(
1786         "realpath", Summary(ArgTypes{ConstCharPtrRestrictTy, CharPtrRestrictTy},
1787                             RetType{CharPtrTy}, NoEvalCall)
1788                         .ArgConstraint(NotNull(ArgNo(0))));
1789 
1790     QualType CharPtrConstPtr = getPointerTy(getConstTy(CharPtrTy));
1791 
1792     // int execv(const char *path, char *const argv[]);
1793     addToFunctionSummaryMap("execv",
1794                             Summary(ArgTypes{ConstCharPtrTy, CharPtrConstPtr},
1795                                     RetType{IntTy}, NoEvalCall)
1796                                 .ArgConstraint(NotNull(ArgNo(0))));
1797 
1798     // int execvp(const char *file, char *const argv[]);
1799     addToFunctionSummaryMap("execvp",
1800                             Summary(ArgTypes{ConstCharPtrTy, CharPtrConstPtr},
1801                                     RetType{IntTy}, NoEvalCall)
1802                                 .ArgConstraint(NotNull(ArgNo(0))));
1803 
1804     // int getopt(int argc, char * const argv[], const char *optstring);
1805     addToFunctionSummaryMap(
1806         "getopt",
1807         Summary(ArgTypes{IntTy, CharPtrConstPtr, ConstCharPtrTy},
1808                 RetType{IntTy}, NoEvalCall)
1809             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1810             .ArgConstraint(NotNull(ArgNo(1)))
1811             .ArgConstraint(NotNull(ArgNo(2))));
1812 
1813     Optional<QualType> StructSockaddrTy = lookupTy("sockaddr");
1814     Optional<QualType> StructSockaddrPtrTy = getPointerTy(StructSockaddrTy);
1815     Optional<QualType> ConstStructSockaddrPtrTy =
1816         getPointerTy(getConstTy(StructSockaddrTy));
1817     Optional<QualType> StructSockaddrPtrRestrictTy =
1818         getRestrictTy(StructSockaddrPtrTy);
1819     Optional<QualType> ConstStructSockaddrPtrRestrictTy =
1820         getRestrictTy(ConstStructSockaddrPtrTy);
1821     Optional<QualType> Socklen_tTy = lookupTy("socklen_t");
1822     Optional<QualType> Socklen_tPtrTy = getPointerTy(Socklen_tTy);
1823     Optional<QualType> Socklen_tPtrRestrictTy = getRestrictTy(Socklen_tPtrTy);
1824     Optional<RangeInt> Socklen_tMax = getMaxValue(Socklen_tTy);
1825 
1826     // In 'socket.h' of some libc implementations with C99, sockaddr parameter
1827     // is a transparent union of the underlying sockaddr_ family of pointers
1828     // instead of being a pointer to struct sockaddr. In these cases, the
1829     // standardized signature will not match, thus we try to match with another
1830     // signature that has the joker Irrelevant type. We also remove those
1831     // constraints which require pointer types for the sockaddr param.
1832     auto Accept =
1833         Summary(NoEvalCall)
1834             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)));
1835     if (!addToFunctionSummaryMap(
1836             "accept",
1837             // int accept(int socket, struct sockaddr *restrict address,
1838             //            socklen_t *restrict address_len);
1839             Signature(ArgTypes{IntTy, StructSockaddrPtrRestrictTy,
1840                                Socklen_tPtrRestrictTy},
1841                       RetType{IntTy}),
1842             Accept))
1843       addToFunctionSummaryMap(
1844           "accept",
1845           Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrRestrictTy},
1846                     RetType{IntTy}),
1847           Accept);
1848 
1849     // int bind(int socket, const struct sockaddr *address, socklen_t
1850     //          address_len);
1851     if (!addToFunctionSummaryMap(
1852             "bind",
1853             Summary(ArgTypes{IntTy, ConstStructSockaddrPtrTy, Socklen_tTy},
1854                     RetType{IntTy}, NoEvalCall)
1855                 .ArgConstraint(
1856                     ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1857                 .ArgConstraint(NotNull(ArgNo(1)))
1858                 .ArgConstraint(
1859                     BufferSize(/*Buffer=*/ArgNo(1), /*BufSize=*/ArgNo(2)))
1860                 .ArgConstraint(
1861                     ArgumentCondition(2, WithinRange, Range(0, Socklen_tMax)))))
1862       // Do not add constraints on sockaddr.
1863       addToFunctionSummaryMap(
1864           "bind", Summary(ArgTypes{IntTy, Irrelevant, Socklen_tTy},
1865                           RetType{IntTy}, NoEvalCall)
1866                       .ArgConstraint(
1867                           ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1868                       .ArgConstraint(ArgumentCondition(
1869                           2, WithinRange, Range(0, Socklen_tMax))));
1870 
1871     // int getpeername(int socket, struct sockaddr *restrict address,
1872     //                 socklen_t *restrict address_len);
1873     if (!addToFunctionSummaryMap(
1874             "getpeername", Summary(ArgTypes{IntTy, StructSockaddrPtrRestrictTy,
1875                                             Socklen_tPtrRestrictTy},
1876                                    RetType{IntTy}, NoEvalCall)
1877                                .ArgConstraint(ArgumentCondition(
1878                                    0, WithinRange, Range(0, IntMax)))
1879                                .ArgConstraint(NotNull(ArgNo(1)))
1880                                .ArgConstraint(NotNull(ArgNo(2)))))
1881       addToFunctionSummaryMap(
1882           "getpeername",
1883           Summary(ArgTypes{IntTy, Irrelevant, Socklen_tPtrRestrictTy},
1884                   RetType{IntTy}, NoEvalCall)
1885               .ArgConstraint(
1886                   ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1887 
1888     // int getsockname(int socket, struct sockaddr *restrict address,
1889     //                 socklen_t *restrict address_len);
1890     if (!addToFunctionSummaryMap(
1891             "getsockname", Summary(ArgTypes{IntTy, StructSockaddrPtrRestrictTy,
1892                                             Socklen_tPtrRestrictTy},
1893                                    RetType{IntTy}, NoEvalCall)
1894                                .ArgConstraint(ArgumentCondition(
1895                                    0, WithinRange, Range(0, IntMax)))
1896                                .ArgConstraint(NotNull(ArgNo(1)))
1897                                .ArgConstraint(NotNull(ArgNo(2)))))
1898       addToFunctionSummaryMap(
1899           "getsockname",
1900           Summary(ArgTypes{IntTy, Irrelevant, Socklen_tPtrRestrictTy},
1901                   RetType{IntTy}, NoEvalCall)
1902               .ArgConstraint(
1903                   ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1904 
1905     // int connect(int socket, const struct sockaddr *address, socklen_t
1906     //             address_len);
1907     if (!addToFunctionSummaryMap(
1908             "connect",
1909             Summary(ArgTypes{IntTy, ConstStructSockaddrPtrTy, Socklen_tTy},
1910                     RetType{IntTy}, NoEvalCall)
1911                 .ArgConstraint(
1912                     ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1913                 .ArgConstraint(NotNull(ArgNo(1)))))
1914       addToFunctionSummaryMap(
1915           "connect", Summary(ArgTypes{IntTy, Irrelevant, Socklen_tTy},
1916                              RetType{IntTy}, NoEvalCall)
1917                          .ArgConstraint(ArgumentCondition(0, WithinRange,
1918                                                           Range(0, IntMax))));
1919 
1920     auto Recvfrom =
1921         Summary(NoEvalCall)
1922             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1923             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
1924                                       /*BufSize=*/ArgNo(2)));
1925     if (!addToFunctionSummaryMap(
1926             "recvfrom",
1927             // ssize_t recvfrom(int socket, void *restrict buffer,
1928             //                  size_t length,
1929             //                  int flags, struct sockaddr *restrict address,
1930             //                  socklen_t *restrict address_len);
1931             Signature(ArgTypes{IntTy, VoidPtrRestrictTy, SizeTy, IntTy,
1932                                StructSockaddrPtrRestrictTy,
1933                                Socklen_tPtrRestrictTy},
1934                       RetType{Ssize_tTy}),
1935             Recvfrom))
1936       addToFunctionSummaryMap(
1937           "recvfrom",
1938           Signature(ArgTypes{IntTy, VoidPtrRestrictTy, SizeTy, IntTy,
1939                              Irrelevant, Socklen_tPtrRestrictTy},
1940                     RetType{Ssize_tTy}),
1941           Recvfrom);
1942 
1943     auto Sendto =
1944         Summary(NoEvalCall)
1945             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1946             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
1947                                       /*BufSize=*/ArgNo(2)));
1948     if (!addToFunctionSummaryMap(
1949             "sendto",
1950             // ssize_t sendto(int socket, const void *message, size_t length,
1951             //                int flags, const struct sockaddr *dest_addr,
1952             //                socklen_t dest_len);
1953             Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy, IntTy,
1954                                ConstStructSockaddrPtrTy, Socklen_tTy},
1955                       RetType{Ssize_tTy}),
1956             Sendto))
1957       addToFunctionSummaryMap(
1958           "sendto",
1959           Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy, IntTy, Irrelevant,
1960                              Socklen_tTy},
1961                     RetType{Ssize_tTy}),
1962           Sendto);
1963 
1964     // int listen(int sockfd, int backlog);
1965     addToFunctionSummaryMap(
1966         "listen", Summary(ArgTypes{IntTy, IntTy}, RetType{IntTy}, NoEvalCall)
1967                       .ArgConstraint(
1968                           ArgumentCondition(0, WithinRange, Range(0, IntMax))));
1969 
1970     // ssize_t recv(int sockfd, void *buf, size_t len, int flags);
1971     addToFunctionSummaryMap(
1972         "recv",
1973         Summary(ArgTypes{IntTy, VoidPtrTy, SizeTy, IntTy}, RetType{Ssize_tTy},
1974                 NoEvalCall)
1975             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
1976             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
1977                                       /*BufSize=*/ArgNo(2))));
1978 
1979     Optional<QualType> StructMsghdrTy = lookupTy("msghdr");
1980     Optional<QualType> StructMsghdrPtrTy = getPointerTy(StructMsghdrTy);
1981     Optional<QualType> ConstStructMsghdrPtrTy =
1982         getPointerTy(getConstTy(StructMsghdrTy));
1983 
1984     // ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
1985     addToFunctionSummaryMap(
1986         "recvmsg", Summary(ArgTypes{IntTy, StructMsghdrPtrTy, IntTy},
1987                            RetType{Ssize_tTy}, NoEvalCall)
1988                        .ArgConstraint(ArgumentCondition(0, WithinRange,
1989                                                         Range(0, IntMax))));
1990 
1991     // ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
1992     addToFunctionSummaryMap(
1993         "sendmsg", Summary(ArgTypes{IntTy, ConstStructMsghdrPtrTy, IntTy},
1994                            RetType{Ssize_tTy}, NoEvalCall)
1995                        .ArgConstraint(ArgumentCondition(0, WithinRange,
1996                                                         Range(0, IntMax))));
1997 
1998     // int setsockopt(int socket, int level, int option_name,
1999     //                const void *option_value, socklen_t option_len);
2000     addToFunctionSummaryMap(
2001         "setsockopt",
2002         Summary(ArgTypes{IntTy, IntTy, IntTy, ConstVoidPtrTy, Socklen_tTy},
2003                 RetType{IntTy}, NoEvalCall)
2004             .ArgConstraint(NotNull(ArgNo(3)))
2005             .ArgConstraint(
2006                 BufferSize(/*Buffer=*/ArgNo(3), /*BufSize=*/ArgNo(4)))
2007             .ArgConstraint(
2008                 ArgumentCondition(4, WithinRange, Range(0, Socklen_tMax))));
2009 
2010     // int getsockopt(int socket, int level, int option_name,
2011     //                void *restrict option_value,
2012     //                socklen_t *restrict option_len);
2013     addToFunctionSummaryMap(
2014         "getsockopt", Summary(ArgTypes{IntTy, IntTy, IntTy, VoidPtrRestrictTy,
2015                                        Socklen_tPtrRestrictTy},
2016                               RetType{IntTy}, NoEvalCall)
2017                           .ArgConstraint(NotNull(ArgNo(3)))
2018                           .ArgConstraint(NotNull(ArgNo(4))));
2019 
2020     // ssize_t send(int sockfd, const void *buf, size_t len, int flags);
2021     addToFunctionSummaryMap(
2022         "send",
2023         Summary(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy, IntTy},
2024                 RetType{Ssize_tTy}, NoEvalCall)
2025             .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
2026             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
2027                                       /*BufSize=*/ArgNo(2))));
2028 
2029     // int socketpair(int domain, int type, int protocol, int sv[2]);
2030     addToFunctionSummaryMap("socketpair",
2031                             Summary(ArgTypes{IntTy, IntTy, IntTy, IntPtrTy},
2032                                     RetType{IntTy}, NoEvalCall)
2033                                 .ArgConstraint(NotNull(ArgNo(3))));
2034 
2035     // int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
2036     //                 char *restrict node, socklen_t nodelen,
2037     //                 char *restrict service,
2038     //                 socklen_t servicelen, int flags);
2039     //
2040     // This is defined in netdb.h. And contrary to 'socket.h', the sockaddr
2041     // parameter is never handled as a transparent union in netdb.h
2042     addToFunctionSummaryMap(
2043         "getnameinfo",
2044         Summary(ArgTypes{ConstStructSockaddrPtrRestrictTy, Socklen_tTy,
2045                          CharPtrRestrictTy, Socklen_tTy, CharPtrRestrictTy,
2046                          Socklen_tTy, IntTy},
2047                 RetType{IntTy}, NoEvalCall)
2048             .ArgConstraint(
2049                 BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1)))
2050             .ArgConstraint(
2051                 ArgumentCondition(1, WithinRange, Range(0, Socklen_tMax)))
2052             .ArgConstraint(
2053                 BufferSize(/*Buffer=*/ArgNo(2), /*BufSize=*/ArgNo(3)))
2054             .ArgConstraint(
2055                 ArgumentCondition(3, WithinRange, Range(0, Socklen_tMax)))
2056             .ArgConstraint(
2057                 BufferSize(/*Buffer=*/ArgNo(4), /*BufSize=*/ArgNo(5)))
2058             .ArgConstraint(
2059                 ArgumentCondition(5, WithinRange, Range(0, Socklen_tMax))));
2060 
2061     Optional<QualType> StructUtimbufTy = lookupTy("utimbuf");
2062     Optional<QualType> StructUtimbufPtrTy = getPointerTy(StructUtimbufTy);
2063 
2064     // int utime(const char *filename, struct utimbuf *buf);
2065     addToFunctionSummaryMap(
2066         "utime", Summary(ArgTypes{ConstCharPtrTy, StructUtimbufPtrTy},
2067                          RetType{IntTy}, NoEvalCall)
2068                      .ArgConstraint(NotNull(ArgNo(0))));
2069 
2070     Optional<QualType> StructTimespecTy = lookupTy("timespec");
2071     Optional<QualType> StructTimespecPtrTy = getPointerTy(StructTimespecTy);
2072     Optional<QualType> ConstStructTimespecPtrTy =
2073         getPointerTy(getConstTy(StructTimespecTy));
2074 
2075     // int futimens(int fd, const struct timespec times[2]);
2076     addToFunctionSummaryMap(
2077         "futimens", Summary(ArgTypes{IntTy, ConstStructTimespecPtrTy},
2078                             RetType{IntTy}, NoEvalCall)
2079                         .ArgConstraint(ArgumentCondition(0, WithinRange,
2080                                                          Range(0, IntMax))));
2081 
2082     // int utimensat(int dirfd, const char *pathname,
2083     //               const struct timespec times[2], int flags);
2084     addToFunctionSummaryMap("utimensat",
2085                             Summary(ArgTypes{IntTy, ConstCharPtrTy,
2086                                              ConstStructTimespecPtrTy, IntTy},
2087                                     RetType{IntTy}, NoEvalCall)
2088                                 .ArgConstraint(NotNull(ArgNo(1))));
2089 
2090     Optional<QualType> StructTimevalTy = lookupTy("timeval");
2091     Optional<QualType> ConstStructTimevalPtrTy =
2092         getPointerTy(getConstTy(StructTimevalTy));
2093 
2094     // int utimes(const char *filename, const struct timeval times[2]);
2095     addToFunctionSummaryMap(
2096         "utimes", Summary(ArgTypes{ConstCharPtrTy, ConstStructTimevalPtrTy},
2097                           RetType{IntTy}, NoEvalCall)
2098                       .ArgConstraint(NotNull(ArgNo(0))));
2099 
2100     // int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
2101     addToFunctionSummaryMap(
2102         "nanosleep",
2103         Summary(ArgTypes{ConstStructTimespecPtrTy, StructTimespecPtrTy},
2104                 RetType{IntTy}, NoEvalCall)
2105             .ArgConstraint(NotNull(ArgNo(0))));
2106 
2107     Optional<QualType> Time_tTy = lookupTy("time_t");
2108     Optional<QualType> ConstTime_tPtrTy = getPointerTy(getConstTy(Time_tTy));
2109     Optional<QualType> ConstTime_tPtrRestrictTy =
2110         getRestrictTy(ConstTime_tPtrTy);
2111 
2112     Optional<QualType> StructTmTy = lookupTy("tm");
2113     Optional<QualType> StructTmPtrTy = getPointerTy(StructTmTy);
2114     Optional<QualType> StructTmPtrRestrictTy = getRestrictTy(StructTmPtrTy);
2115     Optional<QualType> ConstStructTmPtrTy =
2116         getPointerTy(getConstTy(StructTmTy));
2117     Optional<QualType> ConstStructTmPtrRestrictTy =
2118         getRestrictTy(ConstStructTmPtrTy);
2119 
2120     // struct tm * localtime(const time_t *tp);
2121     addToFunctionSummaryMap(
2122         "localtime",
2123         Summary(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}, NoEvalCall)
2124             .ArgConstraint(NotNull(ArgNo(0))));
2125 
2126     // struct tm *localtime_r(const time_t *restrict timer,
2127     //                        struct tm *restrict result);
2128     addToFunctionSummaryMap(
2129         "localtime_r",
2130         Summary(ArgTypes{ConstTime_tPtrRestrictTy, StructTmPtrRestrictTy},
2131                 RetType{StructTmPtrTy}, NoEvalCall)
2132             .ArgConstraint(NotNull(ArgNo(0)))
2133             .ArgConstraint(NotNull(ArgNo(1))));
2134 
2135     // char *asctime_r(const struct tm *restrict tm, char *restrict buf);
2136     addToFunctionSummaryMap(
2137         "asctime_r",
2138         Summary(ArgTypes{ConstStructTmPtrRestrictTy, CharPtrRestrictTy},
2139                 RetType{CharPtrTy}, NoEvalCall)
2140             .ArgConstraint(NotNull(ArgNo(0)))
2141             .ArgConstraint(NotNull(ArgNo(1)))
2142             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1),
2143                                       /*MinBufSize=*/BVF.getValue(26, IntTy))));
2144 
2145     // char *ctime_r(const time_t *timep, char *buf);
2146     addToFunctionSummaryMap("ctime_r",
2147                             Summary(ArgTypes{ConstTime_tPtrTy, CharPtrTy},
2148                                     RetType{CharPtrTy}, NoEvalCall)
2149                                 .ArgConstraint(NotNull(ArgNo(0)))
2150                                 .ArgConstraint(NotNull(ArgNo(1)))
2151                                 .ArgConstraint(BufferSize(
2152                                     /*Buffer=*/ArgNo(1),
2153                                     /*MinBufSize=*/BVF.getValue(26, IntTy))));
2154 
2155     // struct tm *gmtime_r(const time_t *restrict timer,
2156     //                     struct tm *restrict result);
2157     addToFunctionSummaryMap(
2158         "gmtime_r",
2159         Summary(ArgTypes{ConstTime_tPtrRestrictTy, StructTmPtrRestrictTy},
2160                 RetType{StructTmPtrTy}, NoEvalCall)
2161             .ArgConstraint(NotNull(ArgNo(0)))
2162             .ArgConstraint(NotNull(ArgNo(1))));
2163 
2164     // struct tm * gmtime(const time_t *tp);
2165     addToFunctionSummaryMap(
2166         "gmtime",
2167         Summary(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}, NoEvalCall)
2168             .ArgConstraint(NotNull(ArgNo(0))));
2169 
2170     Optional<QualType> Clockid_tTy = lookupTy("clockid_t");
2171 
2172     // int clock_gettime(clockid_t clock_id, struct timespec *tp);
2173     addToFunctionSummaryMap("clock_gettime",
2174                             Summary(ArgTypes{Clockid_tTy, StructTimespecPtrTy},
2175                                     RetType{IntTy}, NoEvalCall)
2176                                 .ArgConstraint(NotNull(ArgNo(1))));
2177 
2178     Optional<QualType> StructItimervalTy = lookupTy("itimerval");
2179     Optional<QualType> StructItimervalPtrTy = getPointerTy(StructItimervalTy);
2180 
2181     // int getitimer(int which, struct itimerval *curr_value);
2182     addToFunctionSummaryMap("getitimer",
2183                             Summary(ArgTypes{IntTy, StructItimervalPtrTy},
2184                                     RetType{IntTy}, NoEvalCall)
2185                                 .ArgConstraint(NotNull(ArgNo(1))));
2186 
2187     Optional<QualType> Pthread_cond_tTy = lookupTy("pthread_cond_t");
2188     Optional<QualType> Pthread_cond_tPtrTy = getPointerTy(Pthread_cond_tTy);
2189     Optional<QualType> Pthread_tTy = lookupTy("pthread_t");
2190     Optional<QualType> Pthread_tPtrTy = getPointerTy(Pthread_tTy);
2191     Optional<QualType> Pthread_tPtrRestrictTy = getRestrictTy(Pthread_tPtrTy);
2192     Optional<QualType> Pthread_mutex_tTy = lookupTy("pthread_mutex_t");
2193     Optional<QualType> Pthread_mutex_tPtrTy = getPointerTy(Pthread_mutex_tTy);
2194     Optional<QualType> Pthread_mutex_tPtrRestrictTy =
2195         getRestrictTy(Pthread_mutex_tPtrTy);
2196     Optional<QualType> Pthread_attr_tTy = lookupTy("pthread_attr_t");
2197     Optional<QualType> Pthread_attr_tPtrTy = getPointerTy(Pthread_attr_tTy);
2198     Optional<QualType> ConstPthread_attr_tPtrTy =
2199         getPointerTy(getConstTy(Pthread_attr_tTy));
2200     Optional<QualType> ConstPthread_attr_tPtrRestrictTy =
2201         getRestrictTy(ConstPthread_attr_tPtrTy);
2202     Optional<QualType> Pthread_mutexattr_tTy = lookupTy("pthread_mutexattr_t");
2203     Optional<QualType> ConstPthread_mutexattr_tPtrTy =
2204         getPointerTy(getConstTy(Pthread_mutexattr_tTy));
2205     Optional<QualType> ConstPthread_mutexattr_tPtrRestrictTy =
2206         getRestrictTy(ConstPthread_mutexattr_tPtrTy);
2207 
2208     QualType PthreadStartRoutineTy = getPointerTy(
2209         ACtx.getFunctionType(/*ResultTy=*/VoidPtrTy, /*Args=*/VoidPtrTy,
2210                              FunctionProtoType::ExtProtoInfo()));
2211 
2212     // int pthread_cond_signal(pthread_cond_t *cond);
2213     // int pthread_cond_broadcast(pthread_cond_t *cond);
2214     addToFunctionSummaryMap(
2215         {"pthread_cond_signal", "pthread_cond_broadcast"},
2216         Signature(ArgTypes{Pthread_cond_tPtrTy}, RetType{IntTy}),
2217         Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0))));
2218 
2219     // int pthread_create(pthread_t *restrict thread,
2220     //                    const pthread_attr_t *restrict attr,
2221     //                    void *(*start_routine)(void*), void *restrict arg);
2222     addToFunctionSummaryMap(
2223         "pthread_create",
2224         Signature(ArgTypes{Pthread_tPtrRestrictTy,
2225                            ConstPthread_attr_tPtrRestrictTy,
2226                            PthreadStartRoutineTy, VoidPtrRestrictTy},
2227                   RetType{IntTy}),
2228         Summary(NoEvalCall)
2229             .ArgConstraint(NotNull(ArgNo(0)))
2230             .ArgConstraint(NotNull(ArgNo(2))));
2231 
2232     // int pthread_attr_destroy(pthread_attr_t *attr);
2233     // int pthread_attr_init(pthread_attr_t *attr);
2234     addToFunctionSummaryMap(
2235         {"pthread_attr_destroy", "pthread_attr_init"},
2236         Signature(ArgTypes{Pthread_attr_tPtrTy}, RetType{IntTy}),
2237         Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0))));
2238 
2239     // int pthread_attr_getstacksize(const pthread_attr_t *restrict attr,
2240     //                               size_t *restrict stacksize);
2241     // int pthread_attr_getguardsize(const pthread_attr_t *restrict attr,
2242     //                               size_t *restrict guardsize);
2243     addToFunctionSummaryMap(
2244         {"pthread_attr_getstacksize", "pthread_attr_getguardsize"},
2245         Signature(ArgTypes{ConstPthread_attr_tPtrRestrictTy, SizePtrRestrictTy},
2246                   RetType{IntTy}),
2247         Summary(NoEvalCall)
2248             .ArgConstraint(NotNull(ArgNo(0)))
2249             .ArgConstraint(NotNull(ArgNo(1))));
2250 
2251     // int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
2252     // int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
2253     addToFunctionSummaryMap(
2254         {"pthread_attr_setstacksize", "pthread_attr_setguardsize"},
2255         Signature(ArgTypes{Pthread_attr_tPtrTy, SizeTy}, RetType{IntTy}),
2256         Summary(NoEvalCall)
2257             .ArgConstraint(NotNull(ArgNo(0)))
2258             .ArgConstraint(
2259                 ArgumentCondition(1, WithinRange, Range(0, SizeMax))));
2260 
2261     // int pthread_mutex_init(pthread_mutex_t *restrict mutex, const
2262     //                        pthread_mutexattr_t *restrict attr);
2263     addToFunctionSummaryMap(
2264         "pthread_mutex_init",
2265         Signature(ArgTypes{Pthread_mutex_tPtrRestrictTy,
2266                            ConstPthread_mutexattr_tPtrRestrictTy},
2267                   RetType{IntTy}),
2268         Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0))));
2269 
2270     // int pthread_mutex_destroy(pthread_mutex_t *mutex);
2271     // int pthread_mutex_lock(pthread_mutex_t *mutex);
2272     // int pthread_mutex_trylock(pthread_mutex_t *mutex);
2273     // int pthread_mutex_unlock(pthread_mutex_t *mutex);
2274     addToFunctionSummaryMap(
2275         {"pthread_mutex_destroy", "pthread_mutex_lock", "pthread_mutex_trylock",
2276          "pthread_mutex_unlock"},
2277         Signature(ArgTypes{Pthread_mutex_tPtrTy}, RetType{IntTy}),
2278         Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0))));
2279   }
2280 
2281   // Functions for testing.
2282   if (ChecksEnabled[CK_StdCLibraryFunctionsTesterChecker]) {
2283     addToFunctionSummaryMap(
2284         "__two_constrained_args",
2285         Summary(ArgTypes{IntTy, IntTy}, RetType{IntTy}, EvalCallAsPure)
2286             .ArgConstraint(ArgumentCondition(0U, WithinRange, SingleValue(1)))
2287             .ArgConstraint(ArgumentCondition(1U, WithinRange, SingleValue(1))));
2288     addToFunctionSummaryMap(
2289         "__arg_constrained_twice",
2290         Summary(ArgTypes{IntTy}, RetType{IntTy}, EvalCallAsPure)
2291             .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(1)))
2292             .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(2))));
2293     addToFunctionSummaryMap(
2294         "__defaultparam",
2295         Summary(ArgTypes{Irrelevant, IntTy}, RetType{IntTy}, EvalCallAsPure)
2296             .ArgConstraint(NotNull(ArgNo(0))));
2297     addToFunctionSummaryMap("__variadic",
2298                             Summary(ArgTypes{VoidPtrTy, ConstCharPtrTy},
2299                                     RetType{IntTy}, EvalCallAsPure)
2300                                 .ArgConstraint(NotNull(ArgNo(0)))
2301                                 .ArgConstraint(NotNull(ArgNo(1))));
2302     addToFunctionSummaryMap(
2303         "__buf_size_arg_constraint",
2304         Summary(ArgTypes{ConstVoidPtrTy, SizeTy}, RetType{IntTy},
2305                 EvalCallAsPure)
2306             .ArgConstraint(
2307                 BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1))));
2308     addToFunctionSummaryMap(
2309         "__buf_size_arg_constraint_mul",
2310         Summary(ArgTypes{ConstVoidPtrTy, SizeTy, SizeTy}, RetType{IntTy},
2311                 EvalCallAsPure)
2312             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1),
2313                                       /*BufSizeMultiplier=*/ArgNo(2))));
2314     addToFunctionSummaryMap(
2315         "__buf_size_arg_constraint_concrete",
2316         Summary(ArgTypes{ConstVoidPtrTy}, RetType{IntTy}, EvalCallAsPure)
2317             .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0),
2318                                       /*BufSize=*/BVF.getValue(10, IntTy))));
2319     addToFunctionSummaryMap(
2320         {"__test_restrict_param_0", "__test_restrict_param_1",
2321          "__test_restrict_param_2"},
2322         Signature(ArgTypes{VoidPtrRestrictTy}, RetType{VoidTy}),
2323         Summary(EvalCallAsPure));
2324   }
2325 }
2326 
2327 void ento::registerStdCLibraryFunctionsChecker(CheckerManager &mgr) {
2328   auto *Checker = mgr.registerChecker<StdLibraryFunctionsChecker>();
2329   Checker->DisplayLoadedSummaries =
2330       mgr.getAnalyzerOptions().getCheckerBooleanOption(
2331           Checker, "DisplayLoadedSummaries");
2332   Checker->ModelPOSIX =
2333       mgr.getAnalyzerOptions().getCheckerBooleanOption(Checker, "ModelPOSIX");
2334 }
2335 
2336 bool ento::shouldRegisterStdCLibraryFunctionsChecker(
2337     const CheckerManager &mgr) {
2338   return true;
2339 }
2340 
2341 #define REGISTER_CHECKER(name)                                                 \
2342   void ento::register##name(CheckerManager &mgr) {                             \
2343     StdLibraryFunctionsChecker *checker =                                      \
2344         mgr.getChecker<StdLibraryFunctionsChecker>();                          \
2345     checker->ChecksEnabled[StdLibraryFunctionsChecker::CK_##name] = true;      \
2346     checker->CheckNames[StdLibraryFunctionsChecker::CK_##name] =               \
2347         mgr.getCurrentCheckerName();                                           \
2348   }                                                                            \
2349                                                                                \
2350   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
2351 
2352 REGISTER_CHECKER(StdCLibraryFunctionArgsChecker)
2353 REGISTER_CHECKER(StdCLibraryFunctionsTesterChecker)
2354