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