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 effects), 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//===----------------------------------------------------------------------===//
42
43#include "ErrnoModeling.h"
44#include "clang/Basic/TargetInfo.h"
45#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
46#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
47#include "clang/StaticAnalyzer/Core/Checker.h"
48#include "clang/StaticAnalyzer/Core/CheckerManager.h"
49#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
50#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
51#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
52#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/SmallString.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/FormatVariadic.h"
57
58#include <optional>
59#include <string>
60
61using namespace clang;
62using namespace clang::ento;
63
64namespace {
65class StdLibraryFunctionsChecker
66 : public Checker<check::PreCall, check::PostCall, eval::Call> {
67
68 class Summary;
69
70 /// Specify how much the analyzer engine should entrust modeling this function
71 /// to us.
72 enum InvalidationKind {
73 /// No \c eval::Call for the function, it can be modeled elsewhere.
74 /// This checker checks only pre and post conditions.
75 NoEvalCall,
76 /// The function is modeled completely in this checker.
77 EvalCallAsPure
78 };
79
80 /// Given a range, should the argument stay inside or outside this range?
81 enum RangeKind { OutOfRange, WithinRange };
82
83 static RangeKind negateKind(RangeKind K) {
84 switch (K) {
85 case OutOfRange:
86 return WithinRange;
87 case WithinRange:
88 return OutOfRange;
89 }
90 llvm_unreachable("Unknown range kind");
91 }
92
93 /// The universal integral type to use in value range descriptions.
94 /// Unsigned to make sure overflows are well-defined.
95 typedef uint64_t RangeInt;
96
97 /// Describes a single range constraint. Eg. {{0, 1}, {3, 4}} is
98 /// a non-negative integer, which less than 5 and not equal to 2.
99 typedef std::vector<std::pair<RangeInt, RangeInt>> IntRangeVector;
100
101 /// A reference to an argument or return value by its number.
102 /// ArgNo in CallExpr and CallEvent is defined as Unsigned, but
103 /// obviously uint32_t should be enough for all practical purposes.
104 typedef uint32_t ArgNo;
105 /// Special argument number for specifying the return value.
106 static const ArgNo Ret;
107
108 /// Get a string representation of an argument index.
109 /// E.g.: (1) -> '1st arg', (2) - > '2nd arg'
110 static void printArgDesc(ArgNo, llvm::raw_ostream &Out);
111 /// Print value X of the argument in form " (which is X)",
112 /// if the value is a fixed known value, otherwise print nothing.
113 /// This is used as simple explanation of values if possible.
114 static void printArgValueInfo(ArgNo ArgN, ProgramStateRef State,
115 const CallEvent &Call, llvm::raw_ostream &Out);
116 /// Append textual description of a numeric range [RMin,RMax] to
117 /// \p Out.
118 static void appendInsideRangeDesc(llvm::APSInt RMin, llvm::APSInt RMax,
119 QualType ArgT, BasicValueFactory &BVF,
120 llvm::raw_ostream &Out);
121 /// Append textual description of a numeric range out of [RMin,RMax] to
122 /// \p Out.
123 static void appendOutOfRangeDesc(llvm::APSInt RMin, llvm::APSInt RMax,
124 QualType ArgT, BasicValueFactory &BVF,
125 llvm::raw_ostream &Out);
126
127 class ValueConstraint;
128
129 /// Pointer to the ValueConstraint. We need a copyable, polymorphic and
130 /// default initializable type (vector needs that). A raw pointer was good,
131 /// however, we cannot default initialize that. unique_ptr makes the Summary
132 /// class non-copyable, therefore not an option. Releasing the copyability
133 /// requirement would render the initialization of the Summary map infeasible.
134 /// Mind that a pointer to a new value constraint is created when the negate
135 /// function is used.
136 using ValueConstraintPtr = std::shared_ptr<ValueConstraint>;
137
138 /// Polymorphic base class that represents a constraint on a given argument
139 /// (or return value) of a function. Derived classes implement different kind
140 /// of constraints, e.g range constraints or correlation between two
141 /// arguments.
142 /// These are used as argument constraints (preconditions) of functions, in
143 /// which case a bug report may be emitted if the constraint is not satisfied.
144 /// Another use is as conditions for summary cases, to create different
145 /// classes of behavior for a function. In this case no description of the
146 /// constraint is needed because the summary cases have an own (not generated)
147 /// description string.
148 class ValueConstraint {
149 public:
150 ValueConstraint(ArgNo ArgN) : ArgN(ArgN) {}
151 virtual ~ValueConstraint() {}
152
153 /// Apply the effects of the constraint on the given program state. If null
154 /// is returned then the constraint is not feasible.
155 virtual ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
156 const Summary &Summary,
157 CheckerContext &C) const = 0;
158
159 /// Represents that in which context do we require a description of the
160 /// constraint.
161 enum DescriptionKind {
162 /// Describe a constraint that was violated.
163 /// Description should start with something like "should be".
164 Violation,
165 /// Describe a constraint that was assumed to be true.
166 /// This can be used when a precondition is satisfied, or when a summary
167 /// case is applied.
168 /// Description should start with something like "is".
169 Assumption
170 };
171
172 /// Give a description that explains the constraint to the user. Used when
173 /// a bug is reported or when the constraint is applied and displayed as a
174 /// note. The description should not mention the argument (getArgNo).
175 /// See StdLibraryFunctionsChecker::reportBug about how this function is
176 /// used (this function is used not only there).
177 virtual void describe(DescriptionKind DK, const CallEvent &Call,
178 ProgramStateRef State, const Summary &Summary,
179 llvm::raw_ostream &Out) const {
180 // There are some descendant classes that are not used as argument
181 // constraints, e.g. ComparisonConstraint. In that case we can safely
182 // ignore the implementation of this function.
183 llvm_unreachable(
184 "Description not implemented for summary case constraints");
185 }
186
187 /// Give a description that explains the actual argument value (where the
188 /// current ValueConstraint applies to) to the user. This function should be
189 /// called only when the current constraint is satisfied by the argument.
190 /// It should produce a more precise description than the constraint itself.
191 /// The actual value of the argument and the program state can be used to
192 /// make the description more precise. In the most simple case, if the
193 /// argument has a fixed known value this value can be printed into \p Out,
194 /// this is done by default.
195 /// The function should return true if a description was printed to \p Out,
196 /// otherwise false.
197 /// See StdLibraryFunctionsChecker::reportBug about how this function is
198 /// used.
199 virtual bool describeArgumentValue(const CallEvent &Call,
200 ProgramStateRef State,
201 const Summary &Summary,
202 llvm::raw_ostream &Out) const {
203 if (auto N = getArgSVal(Call, ArgN: getArgNo()).getAs<NonLoc>()) {
204 if (const llvm::APSInt *Int = N->getAsInteger()) {
205 Out << *Int;
206 return true;
207 }
208 }
209 return false;
210 }
211
212 /// Return those arguments that should be tracked when we report a bug about
213 /// argument constraint violation. By default it is the argument that is
214 /// constrained, however, in some special cases we need to track other
215 /// arguments as well. E.g. a buffer size might be encoded in another
216 /// argument.
217 /// The "return value" argument number can not occur as returned value.
218 virtual std::vector<ArgNo> getArgsToTrack() const { return {ArgN}; }
219
220 /// Get a constraint that represents exactly the opposite of the current.
221 virtual ValueConstraintPtr negate() const {
222 llvm_unreachable("Not implemented");
223 };
224
225 /// Check whether the constraint is malformed or not. It is malformed if the
226 /// specified argument has a mismatch with the given FunctionDecl (e.g. the
227 /// arg number is out-of-range of the function's argument list).
228 /// This condition can indicate if a probably wrong or unexpected function
229 /// was found where the constraint is to be applied.
230 bool checkValidity(const FunctionDecl *FD) const {
231 const bool ValidArg = ArgN == Ret || ArgN < FD->getNumParams();
232 assert(ValidArg && "Arg out of range!");
233 if (!ValidArg)
234 return false;
235 // Subclasses may further refine the validation.
236 return checkSpecificValidity(FD);
237 }
238
239 /// Return the argument number (may be placeholder for "return value").
240 ArgNo getArgNo() const { return ArgN; }
241
242 protected:
243 /// Argument to which to apply the constraint. It can be a real argument of
244 /// the function to check, or a special value to indicate the return value
245 /// of the function.
246 /// Every constraint is assigned to one main argument, even if other
247 /// arguments are involved.
248 ArgNo ArgN;
249
250 /// Do constraint-specific validation check.
251 virtual bool checkSpecificValidity(const FunctionDecl *FD) const {
252 return true;
253 }
254 };
255
256 /// Check if a single argument falls into a specific "range".
257 /// A range is formed as a set of intervals.
258 /// E.g. \code {['A', 'Z'], ['a', 'z'], ['_', '_']} \endcode
259 /// The intervals are closed intervals that contain one or more values.
260 ///
261 /// The default constructed RangeConstraint has an empty range, applying
262 /// such constraint does not involve any assumptions, thus the State remains
263 /// unchanged. This is meaningful, if the range is dependent on a looked up
264 /// type (e.g. [0, Socklen_tMax]). If the type is not found, then the range
265 /// is default initialized to be empty.
266 class RangeConstraint : public ValueConstraint {
267 /// The constraint can be specified by allowing or disallowing the range.
268 /// WithinRange indicates allowing the range, OutOfRange indicates
269 /// disallowing it (allowing the complementary range).
270 RangeKind Kind;
271
272 /// A set of intervals.
273 IntRangeVector Ranges;
274
275 /// A textual description of this constraint for the specific case where the
276 /// constraint is used. If empty a generated description will be used that
277 /// is built from the range of the constraint.
278 StringRef Description;
279
280 public:
281 RangeConstraint(ArgNo ArgN, RangeKind Kind, const IntRangeVector &Ranges,
282 StringRef Desc = "")
283 : ValueConstraint(ArgN), Kind(Kind), Ranges(Ranges), Description(Desc) {
284 }
285
286 const IntRangeVector &getRanges() const { return Ranges; }
287
288 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
289 const Summary &Summary,
290 CheckerContext &C) const override;
291
292 void describe(DescriptionKind DK, const CallEvent &Call,
293 ProgramStateRef State, const Summary &Summary,
294 llvm::raw_ostream &Out) const override;
295
296 bool describeArgumentValue(const CallEvent &Call, ProgramStateRef State,
297 const Summary &Summary,
298 llvm::raw_ostream &Out) const override;
299
300 ValueConstraintPtr negate() const override {
301 RangeConstraint Tmp(*this);
302 Tmp.Kind = negateKind(K: Kind);
303 return std::make_shared<RangeConstraint>(args&: Tmp);
304 }
305
306 protected:
307 bool checkSpecificValidity(const FunctionDecl *FD) const override {
308 return getArgType(FD, ArgN)->isIntegralType(Ctx: FD->getASTContext());
309 }
310
311 private:
312 /// A callback function that is used when iterating over the range
313 /// intervals. It gets the begin and end (inclusive) of one interval.
314 /// This is used to make any kind of task possible that needs an iteration
315 /// over the intervals.
316 using RangeApplyFunction =
317 std::function<bool(const llvm::APSInt &Min, const llvm::APSInt &Max)>;
318
319 /// Call a function on the intervals of the range.
320 /// The function is called with all intervals in the range.
321 void applyOnWithinRange(BasicValueFactory &BVF, QualType ArgT,
322 const RangeApplyFunction &F) const;
323 /// Call a function on all intervals in the complementary range.
324 /// The function is called with all intervals that fall out of the range.
325 /// E.g. consider an interval list [A, B] and [C, D]
326 /// \code
327 /// -------+--------+------------------+------------+----------->
328 /// A B C D
329 /// \endcode
330 /// We get the ranges [-inf, A - 1], [D + 1, +inf], [B + 1, C - 1].
331 /// The \p ArgT is used to determine the min and max of the type that is
332 /// used as "-inf" and "+inf".
333 void applyOnOutOfRange(BasicValueFactory &BVF, QualType ArgT,
334 const RangeApplyFunction &F) const;
335 /// Call a function on the intervals of the range or the complementary
336 /// range.
337 void applyOnRange(RangeKind Kind, BasicValueFactory &BVF, QualType ArgT,
338 const RangeApplyFunction &F) const {
339 switch (Kind) {
340 case OutOfRange:
341 applyOnOutOfRange(BVF, ArgT, F);
342 break;
343 case WithinRange:
344 applyOnWithinRange(BVF, ArgT, F);
345 break;
346 };
347 }
348 };
349
350 /// Check relation of an argument to another.
351 class ComparisonConstraint : public ValueConstraint {
352 BinaryOperator::Opcode Opcode;
353 ArgNo OtherArgN;
354
355 public:
356 ComparisonConstraint(ArgNo ArgN, BinaryOperator::Opcode Opcode,
357 ArgNo OtherArgN)
358 : ValueConstraint(ArgN), Opcode(Opcode), OtherArgN(OtherArgN) {}
359 ArgNo getOtherArgNo() const { return OtherArgN; }
360 BinaryOperator::Opcode getOpcode() const { return Opcode; }
361 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
362 const Summary &Summary,
363 CheckerContext &C) const override;
364 };
365
366 /// Check null or non-null-ness of an argument that is of pointer type.
367 class NullnessConstraint : public ValueConstraint {
368 using ValueConstraint::ValueConstraint;
369 // This variable has a role when we negate the constraint.
370 bool CannotBeNull = true;
371
372 public:
373 NullnessConstraint(ArgNo ArgN, bool CannotBeNull = true)
374 : ValueConstraint(ArgN), CannotBeNull(CannotBeNull) {}
375
376 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
377 const Summary &Summary,
378 CheckerContext &C) const override;
379
380 void describe(DescriptionKind DK, const CallEvent &Call,
381 ProgramStateRef State, const Summary &Summary,
382 llvm::raw_ostream &Out) const override;
383
384 bool describeArgumentValue(const CallEvent &Call, ProgramStateRef State,
385 const Summary &Summary,
386 llvm::raw_ostream &Out) const override;
387
388 ValueConstraintPtr negate() const override {
389 NullnessConstraint Tmp(*this);
390 Tmp.CannotBeNull = !this->CannotBeNull;
391 return std::make_shared<NullnessConstraint>(args&: Tmp);
392 }
393
394 protected:
395 bool checkSpecificValidity(const FunctionDecl *FD) const override {
396 const bool ValidArg = getArgType(FD, ArgN)->isPointerType();
397 assert(ValidArg &&
398 "This constraint should be applied only on a pointer type");
399 return ValidArg;
400 }
401 };
402
403 /// Check null or non-null-ness of an argument that is of pointer type.
404 /// The argument is meant to be a buffer that has a size constraint, and it
405 /// is allowed to have a NULL value if the size is 0. The size can depend on
406 /// 1 or 2 additional arguments, if one of these is 0 the buffer is allowed to
407 /// be NULL. Otherwise, the buffer pointer must be non-null. This is useful
408 /// for functions like `fread` which have this special property.
409 class BufferNullnessConstraint : public ValueConstraint {
410 using ValueConstraint::ValueConstraint;
411 ArgNo SizeArg1N;
412 std::optional<ArgNo> SizeArg2N;
413 // This variable has a role when we negate the constraint.
414 bool CannotBeNull = true;
415
416 public:
417 BufferNullnessConstraint(ArgNo ArgN, ArgNo SizeArg1N,
418 std::optional<ArgNo> SizeArg2N,
419 bool CannotBeNull = true)
420 : ValueConstraint(ArgN), SizeArg1N(SizeArg1N), SizeArg2N(SizeArg2N),
421 CannotBeNull(CannotBeNull) {}
422
423 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
424 const Summary &Summary,
425 CheckerContext &C) const override;
426
427 void describe(DescriptionKind DK, const CallEvent &Call,
428 ProgramStateRef State, const Summary &Summary,
429 llvm::raw_ostream &Out) const override;
430
431 bool describeArgumentValue(const CallEvent &Call, ProgramStateRef State,
432 const Summary &Summary,
433 llvm::raw_ostream &Out) const override;
434
435 ValueConstraintPtr negate() const override {
436 BufferNullnessConstraint Tmp(*this);
437 Tmp.CannotBeNull = !this->CannotBeNull;
438 return std::make_shared<BufferNullnessConstraint>(args&: Tmp);
439 }
440
441 protected:
442 bool checkSpecificValidity(const FunctionDecl *FD) const override {
443 const bool ValidArg = getArgType(FD, ArgN)->isPointerType();
444 assert(ValidArg &&
445 "This constraint should be applied only on a pointer type");
446 return ValidArg;
447 }
448 };
449
450 // Represents a buffer argument with an additional size constraint. The
451 // constraint may be a concrete value, or a symbolic value in an argument.
452 // Example 1. Concrete value as the minimum buffer size.
453 // char *asctime_r(const struct tm *restrict tm, char *restrict buf);
454 // // `buf` size must be at least 26 bytes according the POSIX standard.
455 // Example 2. Argument as a buffer size.
456 // ctime_s(char *buffer, rsize_t bufsz, const time_t *time);
457 // Example 3. The size is computed as a multiplication of other args.
458 // size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
459 // // Here, ptr is the buffer, and its minimum size is `size * nmemb`.
460 class BufferSizeConstraint : public ValueConstraint {
461 // The concrete value which is the minimum size for the buffer.
462 std::optional<llvm::APSInt> ConcreteSize;
463 // The argument which holds the size of the buffer.
464 std::optional<ArgNo> SizeArgN;
465 // The argument which is a multiplier to size. This is set in case of
466 // `fread` like functions where the size is computed as a multiplication of
467 // two arguments.
468 std::optional<ArgNo> SizeMultiplierArgN;
469 // The operator we use in apply. This is negated in negate().
470 BinaryOperator::Opcode Op = BO_LE;
471
472 public:
473 BufferSizeConstraint(ArgNo Buffer, llvm::APSInt BufMinSize)
474 : ValueConstraint(Buffer), ConcreteSize(BufMinSize) {}
475 BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize)
476 : ValueConstraint(Buffer), SizeArgN(BufSize) {}
477 BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize, ArgNo BufSizeMultiplier)
478 : ValueConstraint(Buffer), SizeArgN(BufSize),
479 SizeMultiplierArgN(BufSizeMultiplier) {}
480
481 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
482 const Summary &Summary,
483 CheckerContext &C) const override;
484
485 void describe(DescriptionKind DK, const CallEvent &Call,
486 ProgramStateRef State, const Summary &Summary,
487 llvm::raw_ostream &Out) const override;
488
489 bool describeArgumentValue(const CallEvent &Call, ProgramStateRef State,
490 const Summary &Summary,
491 llvm::raw_ostream &Out) const override;
492
493 std::vector<ArgNo> getArgsToTrack() const override {
494 std::vector<ArgNo> Result{ArgN};
495 if (SizeArgN)
496 Result.push_back(x: *SizeArgN);
497 if (SizeMultiplierArgN)
498 Result.push_back(x: *SizeMultiplierArgN);
499 return Result;
500 }
501
502 ValueConstraintPtr negate() const override {
503 BufferSizeConstraint Tmp(*this);
504 Tmp.Op = BinaryOperator::negateComparisonOp(Opc: Op);
505 return std::make_shared<BufferSizeConstraint>(args&: Tmp);
506 }
507
508 protected:
509 bool checkSpecificValidity(const FunctionDecl *FD) const override {
510 const bool ValidArg = getArgType(FD, ArgN)->isPointerType();
511 assert(ValidArg &&
512 "This constraint should be applied only on a pointer type");
513 return ValidArg;
514 }
515 };
516
517 /// The complete list of constraints that defines a single branch.
518 using ConstraintSet = std::vector<ValueConstraintPtr>;
519
520 /// Define how a function affects the system variable 'errno'.
521 /// This works together with the \c ErrnoModeling and \c ErrnoChecker classes.
522 /// Currently 3 use cases exist: success, failure, irrelevant.
523 /// In the future the failure case can be customized to set \c errno to a
524 /// more specific constraint (for example > 0), or new case can be added
525 /// for functions which require check of \c errno in both success and failure
526 /// case.
527 class ErrnoConstraintBase {
528 public:
529 /// Apply specific state changes related to the errno variable.
530 virtual ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
531 const Summary &Summary,
532 CheckerContext &C) const = 0;
533 /// Get a description about what happens with 'errno' here and how it causes
534 /// a later bug report created by ErrnoChecker.
535 /// Empty return value means that 'errno' related bug may not happen from
536 /// the current analyzed function.
537 virtual std::string describe(CheckerContext &C) const { return ""; }
538
539 virtual ~ErrnoConstraintBase() {}
540
541 protected:
542 ErrnoConstraintBase() = default;
543
544 /// This is used for conjure symbol for errno to differentiate from the
545 /// original call expression (same expression is used for the errno symbol).
546 static int Tag;
547 };
548
549 /// Reset errno constraints to irrelevant.
550 /// This is applicable to functions that may change 'errno' and are not
551 /// modeled elsewhere.
552 class ResetErrnoConstraint : public ErrnoConstraintBase {
553 public:
554 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
555 const Summary &Summary,
556 CheckerContext &C) const override {
557 return errno_modeling::setErrnoState(State, EState: errno_modeling::Irrelevant);
558 }
559 };
560
561 /// Do not change errno constraints.
562 /// This is applicable to functions that are modeled in another checker
563 /// and the already set errno constraints should not be changed in the
564 /// post-call event.
565 class NoErrnoConstraint : public ErrnoConstraintBase {
566 public:
567 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
568 const Summary &Summary,
569 CheckerContext &C) const override {
570 return State;
571 }
572 };
573
574 /// Set errno constraint at failure cases of standard functions.
575 /// Failure case: 'errno' becomes not equal to 0 and may or may not be checked
576 /// by the program. \c ErrnoChecker does not emit a bug report after such a
577 /// function call.
578 class FailureErrnoConstraint : public ErrnoConstraintBase {
579 public:
580 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
581 const Summary &Summary,
582 CheckerContext &C) const override {
583 SValBuilder &SVB = C.getSValBuilder();
584 NonLoc ErrnoSVal = SVB.conjureSymbolVal(call: Call, type: C.getASTContext().IntTy,
585 visitCount: C.blockCount(), symbolTag: &Tag)
586 .castAs<NonLoc>();
587 return errno_modeling::setErrnoForStdFailure(State, C, ErrnoSym: ErrnoSVal);
588 }
589 };
590
591 /// Set errno constraint at success cases of standard functions.
592 /// Success case: 'errno' is not allowed to be used because the value is
593 /// undefined after successful call.
594 /// \c ErrnoChecker can emit bug report after such a function call if errno
595 /// is used.
596 class SuccessErrnoConstraint : public ErrnoConstraintBase {
597 public:
598 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
599 const Summary &Summary,
600 CheckerContext &C) const override {
601 return errno_modeling::setErrnoForStdSuccess(State, C);
602 }
603
604 std::string describe(CheckerContext &C) const override {
605 return "'errno' becomes undefined after the call";
606 }
607 };
608
609 /// Set errno constraint at functions that indicate failure only with 'errno'.
610 /// In this case 'errno' is required to be observed.
611 /// \c ErrnoChecker can emit bug report after such a function call if errno
612 /// is overwritten without a read before.
613 class ErrnoMustBeCheckedConstraint : public ErrnoConstraintBase {
614 public:
615 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
616 const Summary &Summary,
617 CheckerContext &C) const override {
618 return errno_modeling::setErrnoStdMustBeChecked(State, C,
619 Elem: Call.getCFGElementRef());
620 }
621
622 std::string describe(CheckerContext &C) const override {
623 return "reading 'errno' is required to find out if the call has failed";
624 }
625 };
626
627 /// A single branch of a function summary.
628 ///
629 /// A branch is defined by a series of constraints - "assumptions" -
630 /// that together form a single possible outcome of invoking the function.
631 /// When static analyzer considers a branch, it tries to introduce
632 /// a child node in the Exploded Graph. The child node has to include
633 /// constraints that define the branch. If the constraints contradict
634 /// existing constraints in the state, the node is not created and the branch
635 /// is dropped; otherwise it's queued for future exploration.
636 /// The branch is accompanied by a note text that may be displayed
637 /// to the user when a bug is found on a path that takes this branch.
638 ///
639 /// For example, consider the branches in `isalpha(x)`:
640 /// Branch 1)
641 /// x is in range ['A', 'Z'] or in ['a', 'z']
642 /// then the return value is not 0. (I.e. out-of-range [0, 0])
643 /// and the note may say "Assuming the character is alphabetical"
644 /// Branch 2)
645 /// x is out-of-range ['A', 'Z'] and out-of-range ['a', 'z']
646 /// then the return value is 0
647 /// and the note may say "Assuming the character is non-alphabetical".
648 class SummaryCase {
649 ConstraintSet Constraints;
650 const ErrnoConstraintBase &ErrnoConstraint;
651 StringRef Note;
652
653 public:
654 SummaryCase(ConstraintSet &&Constraints, const ErrnoConstraintBase &ErrnoC,
655 StringRef Note)
656 : Constraints(std::move(Constraints)), ErrnoConstraint(ErrnoC),
657 Note(Note) {}
658
659 SummaryCase(const ConstraintSet &Constraints,
660 const ErrnoConstraintBase &ErrnoC, StringRef Note)
661 : Constraints(Constraints), ErrnoConstraint(ErrnoC), Note(Note) {}
662
663 const ConstraintSet &getConstraints() const { return Constraints; }
664 const ErrnoConstraintBase &getErrnoConstraint() const {
665 return ErrnoConstraint;
666 }
667 StringRef getNote() const { return Note; }
668 };
669
670 using ArgTypes = ArrayRef<std::optional<QualType>>;
671 using RetType = std::optional<QualType>;
672
673 // A placeholder type, we use it whenever we do not care about the concrete
674 // type in a Signature.
675 const QualType Irrelevant{};
676 bool static isIrrelevant(QualType T) { return T.isNull(); }
677
678 // The signature of a function we want to describe with a summary. This is a
679 // concessive signature, meaning there may be irrelevant types in the
680 // signature which we do not check against a function with concrete types.
681 // All types in the spec need to be canonical.
682 class Signature {
683 using ArgQualTypes = std::vector<QualType>;
684 ArgQualTypes ArgTys;
685 QualType RetTy;
686 // True if any component type is not found by lookup.
687 bool Invalid = false;
688
689 public:
690 // Construct a signature from optional types. If any of the optional types
691 // are not set then the signature will be invalid.
692 Signature(ArgTypes ArgTys, RetType RetTy) {
693 for (std::optional<QualType> Arg : ArgTys) {
694 if (!Arg) {
695 Invalid = true;
696 return;
697 } else {
698 assertArgTypeSuitableForSignature(T: *Arg);
699 this->ArgTys.push_back(x: *Arg);
700 }
701 }
702 if (!RetTy) {
703 Invalid = true;
704 return;
705 } else {
706 assertRetTypeSuitableForSignature(T: *RetTy);
707 this->RetTy = *RetTy;
708 }
709 }
710
711 bool isInvalid() const { return Invalid; }
712 bool matches(const FunctionDecl *FD) const;
713
714 private:
715 static void assertArgTypeSuitableForSignature(QualType T) {
716 assert((T.isNull() || !T->isVoidType()) &&
717 "We should have no void types in the spec");
718 assert((T.isNull() || T.isCanonical()) &&
719 "We should only have canonical types in the spec");
720 }
721 static void assertRetTypeSuitableForSignature(QualType T) {
722 assert((T.isNull() || T.isCanonical()) &&
723 "We should only have canonical types in the spec");
724 }
725 };
726
727 static QualType getArgType(const FunctionDecl *FD, ArgNo ArgN) {
728 assert(FD && "Function must be set");
729 QualType T = (ArgN == Ret)
730 ? FD->getReturnType().getCanonicalType()
731 : FD->getParamDecl(i: ArgN)->getType().getCanonicalType();
732 return T;
733 }
734
735 using SummaryCases = std::vector<SummaryCase>;
736
737 /// A summary includes information about
738 /// * function prototype (signature)
739 /// * approach to invalidation,
740 /// * a list of branches - so, a list of list of ranges,
741 /// * a list of argument constraints, that must be true on every branch.
742 /// If these constraints are not satisfied that means a fatal error
743 /// usually resulting in undefined behaviour.
744 ///
745 /// Application of a summary:
746 /// The signature and argument constraints together contain information
747 /// about which functions are handled by the summary. The signature can use
748 /// "wildcards", i.e. Irrelevant types. Irrelevant type of a parameter in
749 /// a signature means that type is not compared to the type of the parameter
750 /// in the found FunctionDecl. Argument constraints may specify additional
751 /// rules for the given parameter's type, those rules are checked once the
752 /// signature is matched.
753 class Summary {
754 const InvalidationKind InvalidationKd;
755 SummaryCases Cases;
756 ConstraintSet ArgConstraints;
757
758 // The function to which the summary applies. This is set after lookup and
759 // match to the signature.
760 const FunctionDecl *FD = nullptr;
761
762 public:
763 Summary(InvalidationKind InvalidationKd) : InvalidationKd(InvalidationKd) {}
764
765 Summary &Case(ConstraintSet &&CS, const ErrnoConstraintBase &ErrnoC,
766 StringRef Note = "") {
767 Cases.push_back(x: SummaryCase(std::move(CS), ErrnoC, Note));
768 return *this;
769 }
770 Summary &Case(const ConstraintSet &CS, const ErrnoConstraintBase &ErrnoC,
771 StringRef Note = "") {
772 Cases.push_back(x: SummaryCase(CS, ErrnoC, Note));
773 return *this;
774 }
775 Summary &ArgConstraint(ValueConstraintPtr VC) {
776 assert(VC->getArgNo() != Ret &&
777 "Arg constraint should not refer to the return value");
778 ArgConstraints.push_back(x: VC);
779 return *this;
780 }
781
782 InvalidationKind getInvalidationKd() const { return InvalidationKd; }
783 const SummaryCases &getCases() const { return Cases; }
784 const ConstraintSet &getArgConstraints() const { return ArgConstraints; }
785
786 QualType getArgType(ArgNo ArgN) const {
787 return StdLibraryFunctionsChecker::getArgType(FD, ArgN);
788 }
789
790 // Returns true if the summary should be applied to the given function.
791 // And if yes then store the function declaration.
792 bool matchesAndSet(const Signature &Sign, const FunctionDecl *FD) {
793 bool Result = Sign.matches(FD) && validateByConstraints(FD);
794 if (Result) {
795 assert(!this->FD && "FD must not be set more than once");
796 this->FD = FD;
797 }
798 return Result;
799 }
800
801 private:
802 // Once we know the exact type of the function then do validation check on
803 // all the given constraints.
804 bool validateByConstraints(const FunctionDecl *FD) const {
805 for (const SummaryCase &Case : Cases)
806 for (const ValueConstraintPtr &Constraint : Case.getConstraints())
807 if (!Constraint->checkValidity(FD))
808 return false;
809 for (const ValueConstraintPtr &Constraint : ArgConstraints)
810 if (!Constraint->checkValidity(FD))
811 return false;
812 return true;
813 }
814 };
815
816 // The map of all functions supported by the checker. It is initialized
817 // lazily, and it doesn't change after initialization.
818 using FunctionSummaryMapType = llvm::DenseMap<const FunctionDecl *, Summary>;
819 mutable FunctionSummaryMapType FunctionSummaryMap;
820
821 const BugType BT_InvalidArg{this, "Function call with invalid argument"};
822 mutable bool SummariesInitialized = false;
823
824 static SVal getArgSVal(const CallEvent &Call, ArgNo ArgN) {
825 return ArgN == Ret ? Call.getReturnValue() : Call.getArgSVal(Index: ArgN);
826 }
827 static std::string getFunctionName(const CallEvent &Call) {
828 assert(Call.getDecl() &&
829 "Call was found by a summary, should have declaration");
830 return cast<NamedDecl>(Val: Call.getDecl())->getNameAsString();
831 }
832
833public:
834 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
835 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
836 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
837
838 CheckerNameRef CheckName;
839 bool AddTestFunctions = false;
840
841 bool DisplayLoadedSummaries = false;
842 bool ModelPOSIX = false;
843 bool ShouldAssumeControlledEnvironment = false;
844
845private:
846 std::optional<Summary> findFunctionSummary(const FunctionDecl *FD,
847 CheckerContext &C) const;
848 std::optional<Summary> findFunctionSummary(const CallEvent &Call,
849 CheckerContext &C) const;
850
851 LLVM_ATTRIBUTE_MINSIZE void initFunctionSummaries(CheckerContext &C) const;
852
853 void reportBug(const CallEvent &Call, ExplodedNode *N,
854 const ValueConstraint *VC, const ValueConstraint *NegatedVC,
855 const Summary &Summary, CheckerContext &C) const {
856 assert(Call.getDecl() &&
857 "Function found in summary must have a declaration available");
858 SmallString<256> Msg;
859 llvm::raw_svector_ostream MsgOs(Msg);
860
861 MsgOs << "The ";
862 printArgDesc(VC->getArgNo(), Out&: MsgOs);
863 MsgOs << " to '" << getFunctionName(Call) << "' ";
864 bool ValuesPrinted =
865 NegatedVC->describeArgumentValue(Call, State: N->getState(), Summary, Out&: MsgOs);
866 if (ValuesPrinted)
867 MsgOs << " but ";
868 else
869 MsgOs << "is out of the accepted range; it ";
870 VC->describe(DK: ValueConstraint::Violation, Call, State: C.getState(), Summary,
871 Out&: MsgOs);
872 Msg[0] = toupper(c: Msg[0]);
873 auto R = std::make_unique<PathSensitiveBugReport>(args: BT_InvalidArg, args&: Msg, args&: N);
874
875 for (ArgNo ArgN : VC->getArgsToTrack()) {
876 bugreporter::trackExpressionValue(N, E: Call.getArgExpr(Index: ArgN), R&: *R);
877 R->markInteresting(V: Call.getArgSVal(Index: ArgN));
878 // All tracked arguments are important, highlight them.
879 R->addRange(R: Call.getArgSourceRange(Index: ArgN));
880 }
881
882 C.emitReport(R: std::move(R));
883 }
884
885 /// These are the errno constraints that can be passed to summary cases.
886 /// One of these should fit for a single summary case.
887 /// Usually if a failure return value exists for function, that function
888 /// needs different cases for success and failure with different errno
889 /// constraints (and different return value constraints).
890 const NoErrnoConstraint ErrnoUnchanged{};
891 const ResetErrnoConstraint ErrnoIrrelevant{};
892 const ErrnoMustBeCheckedConstraint ErrnoMustBeChecked{};
893 const SuccessErrnoConstraint ErrnoMustNotBeChecked{};
894 const FailureErrnoConstraint ErrnoNEZeroIrrelevant{};
895};
896
897int StdLibraryFunctionsChecker::ErrnoConstraintBase::Tag = 0;
898
899const StdLibraryFunctionsChecker::ArgNo StdLibraryFunctionsChecker::Ret =
900 std::numeric_limits<ArgNo>::max();
901
902static BasicValueFactory &getBVF(ProgramStateRef State) {
903 ProgramStateManager &Mgr = State->getStateManager();
904 SValBuilder &SVB = Mgr.getSValBuilder();
905 return SVB.getBasicValueFactory();
906}
907
908} // end of anonymous namespace
909
910void StdLibraryFunctionsChecker::printArgDesc(
911 StdLibraryFunctionsChecker::ArgNo ArgN, llvm::raw_ostream &Out) {
912 Out << std::to_string(val: ArgN + 1);
913 Out << llvm::getOrdinalSuffix(Val: ArgN + 1);
914 Out << " argument";
915}
916
917void StdLibraryFunctionsChecker::printArgValueInfo(ArgNo ArgN,
918 ProgramStateRef State,
919 const CallEvent &Call,
920 llvm::raw_ostream &Out) {
921 if (const llvm::APSInt *Val =
922 State->getStateManager().getSValBuilder().getKnownValue(
923 state: State, val: getArgSVal(Call, ArgN)))
924 Out << " (which is " << *Val << ")";
925}
926
927void StdLibraryFunctionsChecker::appendInsideRangeDesc(llvm::APSInt RMin,
928 llvm::APSInt RMax,
929 QualType ArgT,
930 BasicValueFactory &BVF,
931 llvm::raw_ostream &Out) {
932 if (RMin.isZero() && RMax.isZero())
933 Out << "zero";
934 else if (RMin == RMax)
935 Out << RMin;
936 else if (RMin == BVF.getMinValue(T: ArgT)) {
937 if (RMax == -1)
938 Out << "< 0";
939 else
940 Out << "<= " << RMax;
941 } else if (RMax == BVF.getMaxValue(T: ArgT)) {
942 if (RMin.isOne())
943 Out << "> 0";
944 else
945 Out << ">= " << RMin;
946 } else if (RMin.isNegative() == RMax.isNegative() &&
947 RMin.getLimitedValue() == RMax.getLimitedValue() - 1) {
948 Out << RMin << " or " << RMax;
949 } else {
950 Out << "between " << RMin << " and " << RMax;
951 }
952}
953
954void StdLibraryFunctionsChecker::appendOutOfRangeDesc(llvm::APSInt RMin,
955 llvm::APSInt RMax,
956 QualType ArgT,
957 BasicValueFactory &BVF,
958 llvm::raw_ostream &Out) {
959 if (RMin.isZero() && RMax.isZero())
960 Out << "nonzero";
961 else if (RMin == RMax) {
962 Out << "not equal to " << RMin;
963 } else if (RMin == BVF.getMinValue(T: ArgT)) {
964 if (RMax == -1)
965 Out << ">= 0";
966 else
967 Out << "> " << RMax;
968 } else if (RMax == BVF.getMaxValue(T: ArgT)) {
969 if (RMin.isOne())
970 Out << "<= 0";
971 else
972 Out << "< " << RMin;
973 } else if (RMin.isNegative() == RMax.isNegative() &&
974 RMin.getLimitedValue() == RMax.getLimitedValue() - 1) {
975 Out << "not " << RMin << " and not " << RMax;
976 } else {
977 Out << "not between " << RMin << " and " << RMax;
978 }
979}
980
981void StdLibraryFunctionsChecker::RangeConstraint::applyOnWithinRange(
982 BasicValueFactory &BVF, QualType ArgT, const RangeApplyFunction &F) const {
983 if (Ranges.empty())
984 return;
985
986 for (auto [Start, End] : getRanges()) {
987 const llvm::APSInt &Min = BVF.getValue(X: Start, T: ArgT);
988 const llvm::APSInt &Max = BVF.getValue(X: End, T: ArgT);
989 assert(Min <= Max);
990 if (!F(Min, Max))
991 return;
992 }
993}
994
995void StdLibraryFunctionsChecker::RangeConstraint::applyOnOutOfRange(
996 BasicValueFactory &BVF, QualType ArgT, const RangeApplyFunction &F) const {
997 if (Ranges.empty())
998 return;
999
1000 const IntRangeVector &R = getRanges();
1001 size_t E = R.size();
1002
1003 const llvm::APSInt &MinusInf = BVF.getMinValue(T: ArgT);
1004 const llvm::APSInt &PlusInf = BVF.getMaxValue(T: ArgT);
1005
1006 const llvm::APSInt &RangeLeft = BVF.getValue(X: R[0].first - 1ULL, T: ArgT);
1007 const llvm::APSInt &RangeRight = BVF.getValue(X: R[E - 1].second + 1ULL, T: ArgT);
1008
1009 // Iterate over the "holes" between intervals.
1010 for (size_t I = 1; I != E; ++I) {
1011 const llvm::APSInt &Min = BVF.getValue(X: R[I - 1].second + 1ULL, T: ArgT);
1012 const llvm::APSInt &Max = BVF.getValue(X: R[I].first - 1ULL, T: ArgT);
1013 if (Min <= Max) {
1014 if (!F(Min, Max))
1015 return;
1016 }
1017 }
1018 // Check the interval [T_MIN, min(R) - 1].
1019 if (RangeLeft != PlusInf) {
1020 assert(MinusInf <= RangeLeft);
1021 if (!F(MinusInf, RangeLeft))
1022 return;
1023 }
1024 // Check the interval [max(R) + 1, T_MAX],
1025 if (RangeRight != MinusInf) {
1026 assert(RangeRight <= PlusInf);
1027 if (!F(RangeRight, PlusInf))
1028 return;
1029 }
1030}
1031
1032ProgramStateRef StdLibraryFunctionsChecker::RangeConstraint::apply(
1033 ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
1034 CheckerContext &C) const {
1035 ConstraintManager &CM = C.getConstraintManager();
1036 SVal V = getArgSVal(Call, ArgN: getArgNo());
1037 QualType T = Summary.getArgType(ArgN: getArgNo());
1038
1039 if (auto N = V.getAs<NonLoc>()) {
1040 auto ExcludeRangeFromArg = [&](const llvm::APSInt &Min,
1041 const llvm::APSInt &Max) {
1042 State = CM.assumeInclusiveRange(State, Value: *N, From: Min, To: Max, InBound: false);
1043 return static_cast<bool>(State);
1044 };
1045 // "OutOfRange R" is handled by excluding all ranges in R.
1046 // "WithinRange R" is treated as "OutOfRange [T_MIN, T_MAX] \ R".
1047 applyOnRange(Kind: negateKind(K: Kind), BVF&: C.getSValBuilder().getBasicValueFactory(), ArgT: T,
1048 F: ExcludeRangeFromArg);
1049 }
1050
1051 return State;
1052}
1053
1054void StdLibraryFunctionsChecker::RangeConstraint::describe(
1055 DescriptionKind DK, const CallEvent &Call, ProgramStateRef State,
1056 const Summary &Summary, llvm::raw_ostream &Out) const {
1057
1058 BasicValueFactory &BVF = getBVF(State);
1059 QualType T = Summary.getArgType(ArgN: getArgNo());
1060
1061 Out << ((DK == Violation) ? "should be " : "is ");
1062 if (!Description.empty()) {
1063 Out << Description;
1064 } else {
1065 unsigned I = Ranges.size();
1066 if (Kind == WithinRange) {
1067 for (const std::pair<RangeInt, RangeInt> &R : Ranges) {
1068 appendInsideRangeDesc(RMin: BVF.getValue(X: R.first, T),
1069 RMax: BVF.getValue(X: R.second, T), ArgT: T, BVF, Out);
1070 if (--I > 0)
1071 Out << " or ";
1072 }
1073 } else {
1074 for (const std::pair<RangeInt, RangeInt> &R : Ranges) {
1075 appendOutOfRangeDesc(RMin: BVF.getValue(X: R.first, T),
1076 RMax: BVF.getValue(X: R.second, T), ArgT: T, BVF, Out);
1077 if (--I > 0)
1078 Out << " and ";
1079 }
1080 }
1081 }
1082}
1083
1084bool StdLibraryFunctionsChecker::RangeConstraint::describeArgumentValue(
1085 const CallEvent &Call, ProgramStateRef State, const Summary &Summary,
1086 llvm::raw_ostream &Out) const {
1087 unsigned int NRanges = 0;
1088 bool HaveAllRanges = true;
1089
1090 ProgramStateManager &Mgr = State->getStateManager();
1091 BasicValueFactory &BVF = Mgr.getSValBuilder().getBasicValueFactory();
1092 ConstraintManager &CM = Mgr.getConstraintManager();
1093 SVal V = getArgSVal(Call, ArgN: getArgNo());
1094
1095 if (auto N = V.getAs<NonLoc>()) {
1096 if (const llvm::APSInt *Int = N->getAsInteger()) {
1097 Out << "is ";
1098 Out << *Int;
1099 return true;
1100 }
1101 QualType T = Summary.getArgType(ArgN: getArgNo());
1102 SmallString<128> MoreInfo;
1103 llvm::raw_svector_ostream MoreInfoOs(MoreInfo);
1104 auto ApplyF = [&](const llvm::APSInt &Min, const llvm::APSInt &Max) {
1105 if (CM.assumeInclusiveRange(State, Value: *N, From: Min, To: Max, InBound: true)) {
1106 if (NRanges > 0)
1107 MoreInfoOs << " or ";
1108 appendInsideRangeDesc(RMin: Min, RMax: Max, ArgT: T, BVF, Out&: MoreInfoOs);
1109 ++NRanges;
1110 } else {
1111 HaveAllRanges = false;
1112 }
1113 return true;
1114 };
1115
1116 applyOnRange(Kind, BVF, ArgT: T, F: ApplyF);
1117 assert(NRanges > 0);
1118 if (!HaveAllRanges || NRanges == 1) {
1119 Out << "is ";
1120 Out << MoreInfo;
1121 return true;
1122 }
1123 }
1124 return false;
1125}
1126
1127ProgramStateRef StdLibraryFunctionsChecker::ComparisonConstraint::apply(
1128 ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
1129 CheckerContext &C) const {
1130
1131 ProgramStateManager &Mgr = State->getStateManager();
1132 SValBuilder &SVB = Mgr.getSValBuilder();
1133 QualType CondT = SVB.getConditionType();
1134 QualType T = Summary.getArgType(ArgN: getArgNo());
1135 SVal V = getArgSVal(Call, ArgN: getArgNo());
1136
1137 BinaryOperator::Opcode Op = getOpcode();
1138 ArgNo OtherArg = getOtherArgNo();
1139 SVal OtherV = getArgSVal(Call, ArgN: OtherArg);
1140 QualType OtherT = Summary.getArgType(ArgN: OtherArg);
1141 // Note: we avoid integral promotion for comparison.
1142 OtherV = SVB.evalCast(V: OtherV, CastTy: T, OriginalTy: OtherT);
1143 if (auto CompV = SVB.evalBinOp(state: State, op: Op, lhs: V, rhs: OtherV, type: CondT)
1144 .getAs<DefinedOrUnknownSVal>())
1145 State = State->assume(Cond: *CompV, Assumption: true);
1146 return State;
1147}
1148
1149ProgramStateRef StdLibraryFunctionsChecker::NullnessConstraint::apply(
1150 ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
1151 CheckerContext &C) const {
1152 SVal V = getArgSVal(Call, ArgN: getArgNo());
1153 if (V.isUndef())
1154 return State;
1155
1156 DefinedOrUnknownSVal L = V.castAs<DefinedOrUnknownSVal>();
1157 if (!isa<Loc>(Val: L))
1158 return State;
1159
1160 return State->assume(Cond: L, Assumption: CannotBeNull);
1161}
1162
1163void StdLibraryFunctionsChecker::NullnessConstraint::describe(
1164 DescriptionKind DK, const CallEvent &Call, ProgramStateRef State,
1165 const Summary &Summary, llvm::raw_ostream &Out) const {
1166 assert(CannotBeNull &&
1167 "'describe' is not implemented when the value must be NULL");
1168 if (DK == Violation)
1169 Out << "should not be NULL";
1170 else
1171 Out << "is not NULL";
1172}
1173
1174bool StdLibraryFunctionsChecker::NullnessConstraint::describeArgumentValue(
1175 const CallEvent &Call, ProgramStateRef State, const Summary &Summary,
1176 llvm::raw_ostream &Out) const {
1177 assert(!CannotBeNull && "'describeArgumentValue' is not implemented when the "
1178 "value must be non-NULL");
1179 Out << "is NULL";
1180 return true;
1181}
1182
1183ProgramStateRef StdLibraryFunctionsChecker::BufferNullnessConstraint::apply(
1184 ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
1185 CheckerContext &C) const {
1186 SVal V = getArgSVal(Call, ArgN: getArgNo());
1187 if (V.isUndef())
1188 return State;
1189 DefinedOrUnknownSVal L = V.castAs<DefinedOrUnknownSVal>();
1190 if (!isa<Loc>(Val: L))
1191 return State;
1192
1193 std::optional<DefinedOrUnknownSVal> SizeArg1 =
1194 getArgSVal(Call, ArgN: SizeArg1N).getAs<DefinedOrUnknownSVal>();
1195 std::optional<DefinedOrUnknownSVal> SizeArg2;
1196 if (SizeArg2N)
1197 SizeArg2 = getArgSVal(Call, ArgN: *SizeArg2N).getAs<DefinedOrUnknownSVal>();
1198
1199 auto IsArgZero = [State](std::optional<DefinedOrUnknownSVal> Val) {
1200 if (!Val)
1201 return false;
1202 auto [IsNonNull, IsNull] = State->assume(Cond: *Val);
1203 return IsNull && !IsNonNull;
1204 };
1205
1206 if (IsArgZero(SizeArg1) || IsArgZero(SizeArg2))
1207 return State;
1208
1209 return State->assume(Cond: L, Assumption: CannotBeNull);
1210}
1211
1212void StdLibraryFunctionsChecker::BufferNullnessConstraint::describe(
1213 DescriptionKind DK, const CallEvent &Call, ProgramStateRef State,
1214 const Summary &Summary, llvm::raw_ostream &Out) const {
1215 assert(CannotBeNull &&
1216 "'describe' is not implemented when the buffer must be NULL");
1217 if (DK == Violation)
1218 Out << "should not be NULL";
1219 else
1220 Out << "is not NULL";
1221}
1222
1223bool StdLibraryFunctionsChecker::BufferNullnessConstraint::
1224 describeArgumentValue(const CallEvent &Call, ProgramStateRef State,
1225 const Summary &Summary,
1226 llvm::raw_ostream &Out) const {
1227 assert(!CannotBeNull && "'describeArgumentValue' is not implemented when the "
1228 "buffer must be non-NULL");
1229 Out << "is NULL";
1230 return true;
1231}
1232
1233ProgramStateRef StdLibraryFunctionsChecker::BufferSizeConstraint::apply(
1234 ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
1235 CheckerContext &C) const {
1236 SValBuilder &SvalBuilder = C.getSValBuilder();
1237 // The buffer argument.
1238 SVal BufV = getArgSVal(Call, ArgN: getArgNo());
1239
1240 // Get the size constraint.
1241 const SVal SizeV = [this, &State, &Call, &Summary, &SvalBuilder]() {
1242 if (ConcreteSize) {
1243 return SVal(SvalBuilder.makeIntVal(integer: *ConcreteSize));
1244 }
1245 assert(SizeArgN && "The constraint must be either a concrete value or "
1246 "encoded in an argument.");
1247 // The size argument.
1248 SVal SizeV = getArgSVal(Call, ArgN: *SizeArgN);
1249 // Multiply with another argument if given.
1250 if (SizeMultiplierArgN) {
1251 SVal SizeMulV = getArgSVal(Call, ArgN: *SizeMultiplierArgN);
1252 SizeV = SvalBuilder.evalBinOp(state: State, op: BO_Mul, lhs: SizeV, rhs: SizeMulV,
1253 type: Summary.getArgType(ArgN: *SizeArgN));
1254 }
1255 return SizeV;
1256 }();
1257
1258 // The dynamic size of the buffer argument, got from the analyzer engine.
1259 SVal BufDynSize = getDynamicExtentWithOffset(State, BufV);
1260
1261 SVal Feasible = SvalBuilder.evalBinOp(state: State, op: Op, lhs: SizeV, rhs: BufDynSize,
1262 type: SvalBuilder.getContext().BoolTy);
1263 if (auto F = Feasible.getAs<DefinedOrUnknownSVal>())
1264 return State->assume(Cond: *F, Assumption: true);
1265
1266 // We can get here only if the size argument or the dynamic size is
1267 // undefined. But the dynamic size should never be undefined, only
1268 // unknown. So, here, the size of the argument is undefined, i.e. we
1269 // cannot apply the constraint. Actually, other checkers like
1270 // CallAndMessage should catch this situation earlier, because we call a
1271 // function with an uninitialized argument.
1272 llvm_unreachable("Size argument or the dynamic size is Undefined");
1273}
1274
1275void StdLibraryFunctionsChecker::BufferSizeConstraint::describe(
1276 DescriptionKind DK, const CallEvent &Call, ProgramStateRef State,
1277 const Summary &Summary, llvm::raw_ostream &Out) const {
1278 Out << ((DK == Violation) ? "should be " : "is ");
1279 Out << "a buffer with size equal to or greater than ";
1280 if (ConcreteSize) {
1281 Out << *ConcreteSize;
1282 } else if (SizeArgN) {
1283 Out << "the value of the ";
1284 printArgDesc(ArgN: *SizeArgN, Out);
1285 printArgValueInfo(ArgN: *SizeArgN, State, Call, Out);
1286 if (SizeMultiplierArgN) {
1287 Out << " times the ";
1288 printArgDesc(ArgN: *SizeMultiplierArgN, Out);
1289 printArgValueInfo(ArgN: *SizeMultiplierArgN, State, Call, Out);
1290 }
1291 }
1292}
1293
1294bool StdLibraryFunctionsChecker::BufferSizeConstraint::describeArgumentValue(
1295 const CallEvent &Call, ProgramStateRef State, const Summary &Summary,
1296 llvm::raw_ostream &Out) const {
1297 SVal BufV = getArgSVal(Call, ArgN: getArgNo());
1298 SVal BufDynSize = getDynamicExtentWithOffset(State, BufV);
1299 if (const llvm::APSInt *Val =
1300 State->getStateManager().getSValBuilder().getKnownValue(state: State,
1301 val: BufDynSize)) {
1302 Out << "is a buffer with size " << *Val;
1303 return true;
1304 }
1305 return false;
1306}
1307
1308void StdLibraryFunctionsChecker::checkPreCall(const CallEvent &Call,
1309 CheckerContext &C) const {
1310 std::optional<Summary> FoundSummary = findFunctionSummary(Call, C);
1311 if (!FoundSummary)
1312 return;
1313
1314 const Summary &Summary = *FoundSummary;
1315 ProgramStateRef State = C.getState();
1316
1317 ProgramStateRef NewState = State;
1318 ExplodedNode *NewNode = C.getPredecessor();
1319 for (const ValueConstraintPtr &Constraint : Summary.getArgConstraints()) {
1320 ValueConstraintPtr NegatedConstraint = Constraint->negate();
1321 ProgramStateRef SuccessSt = Constraint->apply(State: NewState, Call, Summary, C);
1322 ProgramStateRef FailureSt =
1323 NegatedConstraint->apply(State: NewState, Call, Summary, C);
1324 // The argument constraint is not satisfied.
1325 if (FailureSt && !SuccessSt) {
1326 if (ExplodedNode *N = C.addSink(State, Pred: NewNode))
1327 reportBug(Call, N, VC: Constraint.get(), NegatedVC: NegatedConstraint.get(), Summary,
1328 C);
1329 break;
1330 }
1331 // We will apply the constraint even if we cannot reason about the
1332 // argument. This means both SuccessSt and FailureSt can be true. If we
1333 // weren't applying the constraint that would mean that symbolic
1334 // execution continues on a code whose behaviour is undefined.
1335 assert(SuccessSt);
1336 NewState = SuccessSt;
1337 if (NewState != State) {
1338 SmallString<128> Msg;
1339 llvm::raw_svector_ostream Os(Msg);
1340 Os << "Assuming that the ";
1341 printArgDesc(ArgN: Constraint->getArgNo(), Out&: Os);
1342 Os << " to '";
1343 Os << getFunctionName(Call);
1344 Os << "' ";
1345 Constraint->describe(DK: ValueConstraint::Assumption, Call, State: NewState, Summary,
1346 Out&: Os);
1347 const auto ArgSVal = Call.getArgSVal(Index: Constraint->getArgNo());
1348 NewNode = C.addTransition(
1349 State: NewState, Pred: NewNode,
1350 Tag: C.getNoteTag(Cb: [Msg = std::move(Msg), ArgSVal](
1351 PathSensitiveBugReport &BR, llvm::raw_ostream &OS) {
1352 if (BR.isInteresting(V: ArgSVal))
1353 OS << Msg;
1354 }));
1355 }
1356 }
1357}
1358
1359void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call,
1360 CheckerContext &C) const {
1361 std::optional<Summary> FoundSummary = findFunctionSummary(Call, C);
1362 if (!FoundSummary)
1363 return;
1364
1365 // Now apply the constraints.
1366 const Summary &Summary = *FoundSummary;
1367 ProgramStateRef State = C.getState();
1368 ExplodedNode *Node = C.getPredecessor();
1369
1370 // Apply case/branch specifications.
1371 for (const SummaryCase &Case : Summary.getCases()) {
1372 ProgramStateRef NewState = State;
1373 for (const ValueConstraintPtr &Constraint : Case.getConstraints()) {
1374 NewState = Constraint->apply(State: NewState, Call, Summary, C);
1375 if (!NewState)
1376 break;
1377 }
1378
1379 if (NewState)
1380 NewState = Case.getErrnoConstraint().apply(State: NewState, Call, Summary, C);
1381
1382 if (!NewState)
1383 continue;
1384
1385 // Here it's possible that NewState == State, e.g. when other checkers
1386 // already applied the same constraints (or stricter ones).
1387 // Still add these note tags, the other checker should add only its
1388 // specialized note tags. These general note tags are handled always by
1389 // StdLibraryFunctionsChecker.
1390
1391 ExplodedNode *Pred = Node;
1392 DeclarationName FunctionName =
1393 cast<NamedDecl>(Val: Call.getDecl())->getDeclName();
1394
1395 std::string ErrnoNote = Case.getErrnoConstraint().describe(C);
1396 std::string CaseNote;
1397 if (Case.getNote().empty()) {
1398 if (!ErrnoNote.empty())
1399 ErrnoNote =
1400 llvm::formatv(Fmt: "After calling '{0}' {1}", Vals&: FunctionName, Vals&: ErrnoNote);
1401 } else {
1402 // Disable formatv() validation as the case note may not always have the
1403 // {0} placeholder for function name.
1404 CaseNote =
1405 llvm::formatv(Validate: false, Fmt: Case.getNote().str().c_str(), Vals&: FunctionName);
1406 }
1407 const SVal RV = Call.getReturnValue();
1408
1409 if (Summary.getInvalidationKd() == EvalCallAsPure) {
1410 // Do not expect that errno is interesting (the "pure" functions do not
1411 // affect it).
1412 if (!CaseNote.empty()) {
1413 const NoteTag *Tag = C.getNoteTag(
1414 Cb: [Node, CaseNote, RV](PathSensitiveBugReport &BR) -> std::string {
1415 // Try to omit the note if we know in advance which branch is
1416 // taken (this means, only one branch exists).
1417 // This check is performed inside the lambda, after other
1418 // (or this) checkers had a chance to add other successors.
1419 // Dereferencing the saved node object is valid because it's part
1420 // of a bug report call sequence.
1421 // FIXME: This check is not exact. We may be here after a state
1422 // split that was performed by another checker (and can not find
1423 // the successors). This is why this check is only used in the
1424 // EvalCallAsPure case.
1425 if (BR.isInteresting(V: RV) && Node->succ_size() > 1)
1426 return CaseNote;
1427 return "";
1428 });
1429 Pred = C.addTransition(State: NewState, Pred, Tag);
1430 }
1431 } else {
1432 if (!CaseNote.empty() || !ErrnoNote.empty()) {
1433 const NoteTag *Tag =
1434 C.getNoteTag(Cb: [CaseNote, ErrnoNote,
1435 RV](PathSensitiveBugReport &BR) -> std::string {
1436 // If 'errno' is interesting, show the user a note about the case
1437 // (what happened at the function call) and about how 'errno'
1438 // causes the problem. ErrnoChecker sets the errno (but not RV) to
1439 // interesting.
1440 // If only the return value is interesting, show only the case
1441 // note.
1442 std::optional<Loc> ErrnoLoc =
1443 errno_modeling::getErrnoLoc(State: BR.getErrorNode()->getState());
1444 bool ErrnoImportant = !ErrnoNote.empty() && ErrnoLoc &&
1445 BR.isInteresting(R: ErrnoLoc->getAsRegion());
1446 if (ErrnoImportant) {
1447 BR.markNotInteresting(R: ErrnoLoc->getAsRegion());
1448 if (CaseNote.empty())
1449 return ErrnoNote;
1450 return llvm::formatv(Fmt: "{0}; {1}", Vals: CaseNote, Vals: ErrnoNote);
1451 } else {
1452 if (BR.isInteresting(V: RV))
1453 return CaseNote;
1454 }
1455 return "";
1456 });
1457 Pred = C.addTransition(State: NewState, Pred, Tag);
1458 }
1459 }
1460
1461 // Add the transition if no note tag was added.
1462 if (Pred == Node && NewState != State)
1463 C.addTransition(State: NewState);
1464 }
1465}
1466
1467bool StdLibraryFunctionsChecker::evalCall(const CallEvent &Call,
1468 CheckerContext &C) const {
1469 std::optional<Summary> FoundSummary = findFunctionSummary(Call, C);
1470 if (!FoundSummary)
1471 return false;
1472
1473 const Summary &Summary = *FoundSummary;
1474 switch (Summary.getInvalidationKd()) {
1475 case EvalCallAsPure: {
1476 ProgramStateRef State = C.getState();
1477 const auto *CE = cast<CallExpr>(Val: Call.getOriginExpr());
1478 SVal V = C.getSValBuilder().conjureSymbolVal(call: Call, visitCount: C.blockCount());
1479 State = State->BindExpr(E: CE, SF: C.getStackFrame(), V);
1480
1481 C.addTransition(State);
1482
1483 return true;
1484 }
1485 case NoEvalCall:
1486 // Summary tells us to avoid performing eval::Call. The function is possibly
1487 // evaluated by another checker, or evaluated conservatively.
1488 return false;
1489 }
1490 llvm_unreachable("Unknown invalidation kind!");
1491}
1492
1493bool StdLibraryFunctionsChecker::Signature::matches(
1494 const FunctionDecl *FD) const {
1495 assert(!isInvalid());
1496 // Check the number of arguments.
1497 if (FD->param_size() != ArgTys.size())
1498 return false;
1499
1500 auto RemoveRestrict = [](QualType T) {
1501 T = T.getCanonicalType();
1502 T.removeLocalRestrict();
1503 return T;
1504 };
1505
1506 // Check the return type.
1507 if (!isIrrelevant(T: RetTy)) {
1508 QualType FDRetTy = RemoveRestrict(FD->getReturnType());
1509 if (RetTy != FDRetTy)
1510 return false;
1511 }
1512
1513 // Check the argument types.
1514 for (auto [Idx, ArgTy] : llvm::enumerate(First: ArgTys)) {
1515 if (isIrrelevant(T: ArgTy))
1516 continue;
1517 QualType FDArgTy = RemoveRestrict(FD->getParamDecl(i: Idx)->getType());
1518 if (ArgTy != FDArgTy)
1519 return false;
1520 }
1521
1522 return true;
1523}
1524
1525std::optional<StdLibraryFunctionsChecker::Summary>
1526StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD,
1527 CheckerContext &C) const {
1528 if (!FD)
1529 return std::nullopt;
1530
1531 initFunctionSummaries(C);
1532
1533 auto FSMI = FunctionSummaryMap.find(Val: FD->getCanonicalDecl());
1534 if (FSMI == FunctionSummaryMap.end())
1535 return std::nullopt;
1536 return FSMI->second;
1537}
1538
1539std::optional<StdLibraryFunctionsChecker::Summary>
1540StdLibraryFunctionsChecker::findFunctionSummary(const CallEvent &Call,
1541 CheckerContext &C) const {
1542 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Call.getDecl());
1543 if (!FD)
1544 return std::nullopt;
1545 return findFunctionSummary(FD, C);
1546}
1547
1548void StdLibraryFunctionsChecker::initFunctionSummaries(
1549 CheckerContext &C) const {
1550 if (SummariesInitialized)
1551 return;
1552 SummariesInitialized = true;
1553
1554 SValBuilder &SVB = C.getSValBuilder();
1555 BasicValueFactory &BVF = SVB.getBasicValueFactory();
1556 const ASTContext &ACtx = BVF.getContext();
1557 Preprocessor &PP = C.getPreprocessor();
1558
1559 // Helper class to lookup a type by its name.
1560 class LookupType {
1561 const ASTContext &ACtx;
1562
1563 public:
1564 LookupType(const ASTContext &ACtx) : ACtx(ACtx) {}
1565
1566 // Find the type. If not found then the optional is not set.
1567 std::optional<QualType> operator()(StringRef Name) {
1568 IdentifierInfo &II = ACtx.Idents.get(Name);
1569 auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(Name: &II);
1570 if (LookupRes.empty())
1571 return std::nullopt;
1572
1573 // Prioritize typedef declarations.
1574 // This is needed in case of C struct typedefs. E.g.:
1575 // typedef struct FILE FILE;
1576 // In this case, we have a RecordDecl 'struct FILE' with the name 'FILE'
1577 // and we have a TypedefDecl with the name 'FILE'.
1578 for (Decl *D : LookupRes)
1579 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1580 return ACtx.getCanonicalTypeDeclType(TD);
1581
1582 // Find the first TypeDecl.
1583 // There maybe cases when a function has the same name as a struct.
1584 // E.g. in POSIX: `struct stat` and the function `stat()`:
1585 // int stat(const char *restrict path, struct stat *restrict buf);
1586 for (Decl *D : LookupRes)
1587 if (auto *TD = dyn_cast<TypeDecl>(Val: D))
1588 return ACtx.getCanonicalTypeDeclType(TD);
1589 return std::nullopt;
1590 }
1591 } lookupTy(ACtx);
1592
1593 // Below are auxiliary classes to handle optional types that we get as a
1594 // result of the lookup.
1595 class GetPointerTy {
1596 const ASTContext &ACtx;
1597
1598 public:
1599 GetPointerTy(const ASTContext &ACtx) : ACtx(ACtx) {}
1600 QualType operator()(QualType Ty) { return ACtx.getPointerType(T: Ty); }
1601 std::optional<QualType> operator()(std::optional<QualType> Ty) {
1602 if (Ty)
1603 return operator()(Ty: *Ty);
1604 return std::nullopt;
1605 }
1606 } getPointerTy(ACtx);
1607 class {
1608 public:
1609 std::optional<QualType> operator()(std::optional<QualType> Ty) {
1610 return Ty ? std::optional<QualType>(Ty->withConst()) : std::nullopt;
1611 }
1612 QualType operator()(QualType Ty) { return Ty.withConst(); }
1613 } getConstTy;
1614 class GetMaxValue {
1615 BasicValueFactory &BVF;
1616
1617 public:
1618 GetMaxValue(BasicValueFactory &BVF) : BVF(BVF) {}
1619 std::optional<RangeInt> operator()(QualType Ty) {
1620 return BVF.getMaxValue(T: Ty)->getLimitedValue();
1621 }
1622 std::optional<RangeInt> operator()(std::optional<QualType> Ty) {
1623 if (Ty) {
1624 return operator()(Ty: *Ty);
1625 }
1626 return std::nullopt;
1627 }
1628 } getMaxValue(BVF);
1629
1630 // These types are useful for writing specifications quickly,
1631 // New specifications should probably introduce more types.
1632 // Some types are hard to obtain from the AST, eg. "ssize_t".
1633 // In such cases it should be possible to provide multiple variants
1634 // of function summary for common cases (eg. ssize_t could be int or long
1635 // or long long, so three summary variants would be enough).
1636 // Of course, function variants are also useful for C++ overloads.
1637 const QualType VoidTy = ACtx.VoidTy;
1638 const QualType CharTy = ACtx.CharTy;
1639 const QualType WCharTy = ACtx.WCharTy;
1640 const QualType IntTy = ACtx.IntTy;
1641 const QualType UnsignedIntTy = ACtx.UnsignedIntTy;
1642 const QualType LongTy = ACtx.LongTy;
1643 const QualType SizeTyCanonTy = ACtx.getCanonicalSizeType();
1644
1645 const QualType VoidPtrTy = getPointerTy(VoidTy); // void *
1646 const QualType IntPtrTy = getPointerTy(IntTy); // int *
1647 const QualType UnsignedIntPtrTy =
1648 getPointerTy(UnsignedIntTy); // unsigned int *
1649 const QualType ConstVoidPtrTy =
1650 getPointerTy(getConstTy(VoidTy)); // const void *
1651 const QualType CharPtrTy = getPointerTy(CharTy); // char *
1652 const QualType ConstCharPtrTy =
1653 getPointerTy(getConstTy(CharTy)); // const char *
1654 const QualType Wchar_tPtrTy = getPointerTy(WCharTy); // wchar_t *
1655 const QualType ConstWchar_tPtrTy =
1656 getPointerTy(getConstTy(WCharTy)); // const wchar_t *
1657 const QualType SizePtrTy = getPointerTy(SizeTyCanonTy);
1658
1659 const RangeInt IntMax = BVF.getMaxValue(T: IntTy)->getLimitedValue();
1660 const RangeInt UnsignedIntMax =
1661 BVF.getMaxValue(T: UnsignedIntTy)->getLimitedValue();
1662 const RangeInt LongMax = BVF.getMaxValue(T: LongTy)->getLimitedValue();
1663 const RangeInt SizeMax = BVF.getMaxValue(T: SizeTyCanonTy)->getLimitedValue();
1664
1665 // Set UCharRangeMax to min of int or uchar maximum value.
1666 // The C standard states that the arguments of functions like isalpha must
1667 // be representable as an unsigned char. Their type is 'int', so the max
1668 // value of the argument should be min(UCharMax, IntMax). This just happen
1669 // to be true for commonly used and well tested instruction set
1670 // architectures, but not for others.
1671 const RangeInt UCharRangeMax =
1672 std::min(a: BVF.getMaxValue(T: ACtx.UnsignedCharTy)->getLimitedValue(), b: IntMax);
1673
1674 // Get platform dependent values of some macros.
1675 // Try our best to parse this from the Preprocessor, otherwise fallback to a
1676 // default value (what is found in a library header).
1677 const auto EOFv = tryExpandAsInteger(Macro: "EOF", PP).value_or(u: -1);
1678 const auto AT_FDCWDv = tryExpandAsInteger(Macro: "AT_FDCWD", PP).value_or(u: -100);
1679
1680 // Auxiliary class to aid adding summaries to the summary map.
1681 struct AddToFunctionSummaryMap {
1682 const ASTContext &ACtx;
1683 FunctionSummaryMapType &Map;
1684 bool DisplayLoadedSummaries;
1685 AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType &FSM,
1686 bool DisplayLoadedSummaries)
1687 : ACtx(ACtx), Map(FSM), DisplayLoadedSummaries(DisplayLoadedSummaries) {
1688 }
1689
1690 // Add a summary to a FunctionDecl found by lookup. The lookup is performed
1691 // by the given Name, and in the global scope. The summary will be attached
1692 // to the found FunctionDecl only if the signatures match.
1693 //
1694 // Returns true if the summary has been added, false otherwise.
1695 bool operator()(StringRef Name, Signature Sign, Summary Sum) {
1696 if (Sign.isInvalid())
1697 return false;
1698 IdentifierInfo &II = ACtx.Idents.get(Name);
1699 auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(Name: &II);
1700 if (LookupRes.empty())
1701 return false;
1702 for (Decl *D : LookupRes) {
1703 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1704 if (Sum.matchesAndSet(Sign, FD)) {
1705 auto Res = Map.insert(KV: {FD->getCanonicalDecl(), Sum});
1706 assert(Res.second && "Function already has a summary set!");
1707 (void)Res;
1708 if (DisplayLoadedSummaries) {
1709 llvm::errs() << "Loaded summary for: ";
1710 FD->print(Out&: llvm::errs());
1711 llvm::errs() << "\n";
1712 }
1713 return true;
1714 }
1715 }
1716 }
1717 return false;
1718 }
1719 // Add the same summary for different names with the Signature explicitly
1720 // given.
1721 void operator()(ArrayRef<StringRef> Names, Signature Sign, Summary Sum) {
1722 for (StringRef Name : Names)
1723 operator()(Name, Sign, Sum);
1724 }
1725 } addToFunctionSummaryMap(ACtx, FunctionSummaryMap, DisplayLoadedSummaries);
1726
1727 // Below are helpers functions to create the summaries.
1728 auto ArgumentCondition = [](ArgNo ArgN, RangeKind Kind, IntRangeVector Ranges,
1729 StringRef Desc = "") {
1730 return std::make_shared<RangeConstraint>(args&: ArgN, args&: Kind, args&: Ranges, args&: Desc);
1731 };
1732 auto BufferSize = [](auto... Args) {
1733 return std::make_shared<BufferSizeConstraint>(Args...);
1734 };
1735 struct {
1736 auto operator()(RangeKind Kind, IntRangeVector Ranges) {
1737 return std::make_shared<RangeConstraint>(args: Ret, args&: Kind, args&: Ranges);
1738 }
1739 auto operator()(BinaryOperator::Opcode Op, ArgNo OtherArgN) {
1740 return std::make_shared<ComparisonConstraint>(args: Ret, args&: Op, args&: OtherArgN);
1741 }
1742 } ReturnValueCondition;
1743 struct {
1744 auto operator()(RangeInt b, RangeInt e) {
1745 return IntRangeVector{std::pair<RangeInt, RangeInt>{b, e}};
1746 }
1747 auto operator()(RangeInt b, std::optional<RangeInt> e) {
1748 if (e)
1749 return IntRangeVector{std::pair<RangeInt, RangeInt>{b, *e}};
1750 return IntRangeVector{};
1751 }
1752 auto operator()(std::pair<RangeInt, RangeInt> i0,
1753 std::pair<RangeInt, std::optional<RangeInt>> i1) {
1754 if (i1.second)
1755 return IntRangeVector{i0, {i1.first, *(i1.second)}};
1756 return IntRangeVector{i0};
1757 }
1758 } Range;
1759 auto SingleValue = [](RangeInt v) {
1760 return IntRangeVector{std::pair<RangeInt, RangeInt>{v, v}};
1761 };
1762 auto LessThanOrEq = BO_LE;
1763 auto NotNull = [&](ArgNo ArgN) {
1764 return std::make_shared<NullnessConstraint>(args&: ArgN);
1765 };
1766 auto IsNull = [&](ArgNo ArgN) {
1767 return std::make_shared<NullnessConstraint>(args&: ArgN, args: false);
1768 };
1769 auto NotNullBuffer = [&](ArgNo ArgN, ArgNo SizeArg1N,
1770 std::optional<ArgNo> SizeArg2N = std::nullopt) {
1771 return std::make_shared<BufferNullnessConstraint>(args&: ArgN, args&: SizeArg1N,
1772 args&: SizeArg2N);
1773 };
1774
1775 std::optional<QualType> FileTy = lookupTy("FILE");
1776 std::optional<QualType> FilePtrTy = getPointerTy(FileTy);
1777
1778 std::optional<QualType> FPosTTy = lookupTy("fpos_t");
1779 std::optional<QualType> FPosTPtrTy = getPointerTy(FPosTTy);
1780 std::optional<QualType> ConstFPosTPtrTy = getPointerTy(getConstTy(FPosTTy));
1781
1782 constexpr llvm::StringLiteral GenericSuccessMsg(
1783 "Assuming that '{0}' is successful");
1784 constexpr llvm::StringLiteral GenericFailureMsg("Assuming that '{0}' fails");
1785
1786 // We are finally ready to define specifications for all supported functions.
1787 //
1788 // Argument ranges should always cover all variants. If return value
1789 // is completely unknown, omit it from the respective range set.
1790 //
1791 // Every item in the list of range sets represents a particular
1792 // execution path the analyzer would need to explore once
1793 // the call is modeled - a new program state is constructed
1794 // for every range set, and each range line in the range set
1795 // corresponds to a specific constraint within this state.
1796
1797 // The isascii() family of functions.
1798 // The behavior is undefined if the value of the argument is not
1799 // representable as unsigned char or is not equal to EOF. See e.g. C99
1800 // 7.4.1.2 The isalpha function (p: 181-182).
1801 addToFunctionSummaryMap(
1802 "isalnum", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1803 Summary(EvalCallAsPure)
1804 // Boils down to isupper() or islower() or isdigit().
1805 .Case(CS: {ArgumentCondition(0U, WithinRange,
1806 {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}}),
1807 ReturnValueCondition(OutOfRange, SingleValue(0))},
1808 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is alphanumeric")
1809 // The locale-specific range.
1810 // No post-condition. We are completely unaware of
1811 // locale-specific return values.
1812 .Case(CS: {ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})},
1813 ErrnoC: ErrnoIrrelevant)
1814 .Case(
1815 CS: {ArgumentCondition(
1816 0U, OutOfRange,
1817 {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}),
1818 ReturnValueCondition(WithinRange, SingleValue(0))},
1819 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is non-alphanumeric")
1820 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange,
1821 {{EOFv, EOFv}, {0, UCharRangeMax}},
1822 "an unsigned char value or EOF")));
1823 addToFunctionSummaryMap(
1824 "isalpha", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1825 Summary(EvalCallAsPure)
1826 .Case(CS: {ArgumentCondition(0U, WithinRange, {{'A', 'Z'}, {'a', 'z'}}),
1827 ReturnValueCondition(OutOfRange, SingleValue(0))},
1828 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is alphabetical")
1829 // The locale-specific range.
1830 .Case(CS: {ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})},
1831 ErrnoC: ErrnoIrrelevant)
1832 .Case(CS: {ArgumentCondition(
1833 0U, OutOfRange,
1834 {{'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}),
1835 ReturnValueCondition(WithinRange, SingleValue(0))},
1836 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is non-alphabetical"));
1837 addToFunctionSummaryMap(
1838 "isascii", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1839 Summary(EvalCallAsPure)
1840 .Case(CS: {ArgumentCondition(0U, WithinRange, Range(0, 127)),
1841 ReturnValueCondition(OutOfRange, SingleValue(0))},
1842 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is an ASCII character")
1843 .Case(CS: {ArgumentCondition(0U, OutOfRange, Range(0, 127)),
1844 ReturnValueCondition(WithinRange, SingleValue(0))},
1845 ErrnoC: ErrnoIrrelevant,
1846 Note: "Assuming the character is not an ASCII character"));
1847 addToFunctionSummaryMap(
1848 "isblank", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1849 Summary(EvalCallAsPure)
1850 .Case(CS: {ArgumentCondition(0U, WithinRange, {{'\t', '\t'}, {' ', ' '}}),
1851 ReturnValueCondition(OutOfRange, SingleValue(0))},
1852 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is a blank character")
1853 .Case(CS: {ArgumentCondition(0U, OutOfRange, {{'\t', '\t'}, {' ', ' '}}),
1854 ReturnValueCondition(WithinRange, SingleValue(0))},
1855 ErrnoC: ErrnoIrrelevant,
1856 Note: "Assuming the character is not a blank character"));
1857 addToFunctionSummaryMap(
1858 "iscntrl", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1859 Summary(EvalCallAsPure)
1860 .Case(CS: {ArgumentCondition(0U, WithinRange, {{0, 32}, {127, 127}}),
1861 ReturnValueCondition(OutOfRange, SingleValue(0))},
1862 ErrnoC: ErrnoIrrelevant,
1863 Note: "Assuming the character is a control character")
1864 .Case(CS: {ArgumentCondition(0U, OutOfRange, {{0, 32}, {127, 127}}),
1865 ReturnValueCondition(WithinRange, SingleValue(0))},
1866 ErrnoC: ErrnoIrrelevant,
1867 Note: "Assuming the character is not a control character"));
1868 addToFunctionSummaryMap(
1869 "isdigit", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1870 Summary(EvalCallAsPure)
1871 .Case(CS: {ArgumentCondition(0U, WithinRange, Range('0', '9')),
1872 ReturnValueCondition(OutOfRange, SingleValue(0))},
1873 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is a digit")
1874 .Case(CS: {ArgumentCondition(0U, OutOfRange, Range('0', '9')),
1875 ReturnValueCondition(WithinRange, SingleValue(0))},
1876 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is not a digit"));
1877 addToFunctionSummaryMap(
1878 "isgraph", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1879 Summary(EvalCallAsPure)
1880 .Case(CS: {ArgumentCondition(0U, WithinRange, Range(33, 126)),
1881 ReturnValueCondition(OutOfRange, SingleValue(0))},
1882 ErrnoC: ErrnoIrrelevant,
1883 Note: "Assuming the character has graphical representation")
1884 .Case(
1885 CS: {ArgumentCondition(0U, OutOfRange, Range(33, 126)),
1886 ReturnValueCondition(WithinRange, SingleValue(0))},
1887 ErrnoC: ErrnoIrrelevant,
1888 Note: "Assuming the character does not have graphical representation"));
1889 addToFunctionSummaryMap(
1890 "islower", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1891 Summary(EvalCallAsPure)
1892 // Is certainly lowercase.
1893 .Case(CS: {ArgumentCondition(0U, WithinRange, Range('a', 'z')),
1894 ReturnValueCondition(OutOfRange, SingleValue(0))},
1895 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is a lowercase letter")
1896 // Is ascii but not lowercase.
1897 .Case(CS: {ArgumentCondition(0U, WithinRange, Range(0, 127)),
1898 ArgumentCondition(0U, OutOfRange, Range('a', 'z')),
1899 ReturnValueCondition(WithinRange, SingleValue(0))},
1900 ErrnoC: ErrnoIrrelevant,
1901 Note: "Assuming the character is not a lowercase letter")
1902 // The locale-specific range.
1903 .Case(CS: {ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})},
1904 ErrnoC: ErrnoIrrelevant)
1905 // Is not an unsigned char.
1906 .Case(CS: {ArgumentCondition(0U, OutOfRange, Range(0, UCharRangeMax)),
1907 ReturnValueCondition(WithinRange, SingleValue(0))},
1908 ErrnoC: ErrnoIrrelevant));
1909 addToFunctionSummaryMap(
1910 "isprint", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1911 Summary(EvalCallAsPure)
1912 .Case(CS: {ArgumentCondition(0U, WithinRange, Range(32, 126)),
1913 ReturnValueCondition(OutOfRange, SingleValue(0))},
1914 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is printable")
1915 .Case(CS: {ArgumentCondition(0U, OutOfRange, Range(32, 126)),
1916 ReturnValueCondition(WithinRange, SingleValue(0))},
1917 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is non-printable"));
1918 addToFunctionSummaryMap(
1919 "ispunct", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1920 Summary(EvalCallAsPure)
1921 .Case(CS: {ArgumentCondition(
1922 0U, WithinRange,
1923 {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}),
1924 ReturnValueCondition(OutOfRange, SingleValue(0))},
1925 ErrnoC: ErrnoIrrelevant, Note: "Assuming the character is a punctuation mark")
1926 .Case(CS: {ArgumentCondition(
1927 0U, OutOfRange,
1928 {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}),
1929 ReturnValueCondition(WithinRange, SingleValue(0))},
1930 ErrnoC: ErrnoIrrelevant,
1931 Note: "Assuming the character is not a punctuation mark"));
1932 addToFunctionSummaryMap(
1933 "isspace", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1934 Summary(EvalCallAsPure)
1935 // Space, '\f', '\n', '\r', '\t', '\v'.
1936 .Case(CS: {ArgumentCondition(0U, WithinRange, {{9, 13}, {' ', ' '}}),
1937 ReturnValueCondition(OutOfRange, SingleValue(0))},
1938 ErrnoC: ErrnoIrrelevant,
1939 Note: "Assuming the character is a whitespace character")
1940 // The locale-specific range.
1941 .Case(CS: {ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})},
1942 ErrnoC: ErrnoIrrelevant)
1943 .Case(CS: {ArgumentCondition(0U, OutOfRange,
1944 {{9, 13}, {' ', ' '}, {128, UCharRangeMax}}),
1945 ReturnValueCondition(WithinRange, SingleValue(0))},
1946 ErrnoC: ErrnoIrrelevant,
1947 Note: "Assuming the character is not a whitespace character"));
1948 addToFunctionSummaryMap(
1949 "isupper", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1950 Summary(EvalCallAsPure)
1951 // Is certainly uppercase.
1952 .Case(CS: {ArgumentCondition(0U, WithinRange, Range('A', 'Z')),
1953 ReturnValueCondition(OutOfRange, SingleValue(0))},
1954 ErrnoC: ErrnoIrrelevant,
1955 Note: "Assuming the character is an uppercase letter")
1956 // The locale-specific range.
1957 .Case(CS: {ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})},
1958 ErrnoC: ErrnoIrrelevant)
1959 // Other.
1960 .Case(CS: {ArgumentCondition(0U, OutOfRange,
1961 {{'A', 'Z'}, {128, UCharRangeMax}}),
1962 ReturnValueCondition(WithinRange, SingleValue(0))},
1963 ErrnoC: ErrnoIrrelevant,
1964 Note: "Assuming the character is not an uppercase letter"));
1965 addToFunctionSummaryMap(
1966 "isxdigit", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1967 Summary(EvalCallAsPure)
1968 .Case(CS: {ArgumentCondition(0U, WithinRange,
1969 {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}),
1970 ReturnValueCondition(OutOfRange, SingleValue(0))},
1971 ErrnoC: ErrnoIrrelevant,
1972 Note: "Assuming the character is a hexadecimal digit")
1973 .Case(CS: {ArgumentCondition(0U, OutOfRange,
1974 {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}),
1975 ReturnValueCondition(WithinRange, SingleValue(0))},
1976 ErrnoC: ErrnoIrrelevant,
1977 Note: "Assuming the character is not a hexadecimal digit"));
1978 addToFunctionSummaryMap(
1979 "toupper", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1980 Summary(EvalCallAsPure)
1981 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange,
1982 {{EOFv, EOFv}, {0, UCharRangeMax}},
1983 "an unsigned char value or EOF")));
1984 addToFunctionSummaryMap(
1985 "tolower", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1986 Summary(EvalCallAsPure)
1987 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange,
1988 {{EOFv, EOFv}, {0, UCharRangeMax}},
1989 "an unsigned char value or EOF")));
1990 addToFunctionSummaryMap(
1991 "toascii", Signature(ArgTypes{IntTy}, RetType{IntTy}),
1992 Summary(EvalCallAsPure)
1993 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange,
1994 {{EOFv, EOFv}, {0, UCharRangeMax}},
1995 "an unsigned char value or EOF")));
1996
1997 addToFunctionSummaryMap(
1998 "getchar", Signature(ArgTypes{}, RetType{IntTy}),
1999 Summary(NoEvalCall)
2000 .Case(CS: {ReturnValueCondition(WithinRange,
2001 {{EOFv, EOFv}, {0, UCharRangeMax}})},
2002 ErrnoC: ErrnoIrrelevant));
2003
2004 // read()-like functions that never return more than buffer size.
2005 auto FreadSummary =
2006 Summary(NoEvalCall)
2007 .Case(CS: {ArgumentCondition(1U, WithinRange, Range(1, SizeMax)),
2008 ArgumentCondition(2U, WithinRange, Range(1, SizeMax)),
2009 ReturnValueCondition(BO_LT, ArgNo(2)),
2010 ReturnValueCondition(WithinRange, Range(0, SizeMax))},
2011 ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2012 .Case(CS: {ArgumentCondition(1U, WithinRange, Range(1, SizeMax)),
2013 ReturnValueCondition(BO_EQ, ArgNo(2)),
2014 ReturnValueCondition(WithinRange, Range(0, SizeMax))},
2015 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2016 .Case(CS: {ArgumentCondition(1U, WithinRange, SingleValue(0)),
2017 ReturnValueCondition(WithinRange, SingleValue(0))},
2018 ErrnoC: ErrnoMustNotBeChecked,
2019 Note: "Assuming that argument 'size' to '{0}' is 0")
2020 .ArgConstraint(VC: NotNullBuffer(ArgNo(0), ArgNo(1), ArgNo(2)))
2021 .ArgConstraint(VC: NotNull(ArgNo(3)))
2022 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1),
2023 /*BufSizeMultiplier=*/ArgNo(2)));
2024
2025 // size_t fread(void *restrict ptr, size_t size, size_t nitems,
2026 // FILE *restrict stream);
2027 addToFunctionSummaryMap(
2028 "fread",
2029 Signature(ArgTypes{VoidPtrTy, SizeTyCanonTy, SizeTyCanonTy, FilePtrTy},
2030 RetType{SizeTyCanonTy}),
2031 FreadSummary);
2032 // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems,
2033 // FILE *restrict stream);
2034 addToFunctionSummaryMap("fwrite",
2035 Signature(ArgTypes{ConstVoidPtrTy, SizeTyCanonTy,
2036 SizeTyCanonTy, FilePtrTy},
2037 RetType{SizeTyCanonTy}),
2038 FreadSummary);
2039
2040 std::optional<QualType> Ssize_tTy = lookupTy("ssize_t");
2041 std::optional<RangeInt> Ssize_tMax = getMaxValue(Ssize_tTy);
2042
2043 auto ReadSummary =
2044 Summary(NoEvalCall)
2045 .Case(CS: {ReturnValueCondition(LessThanOrEq, ArgNo(2)),
2046 ReturnValueCondition(WithinRange, Range(-1, Ssize_tMax))},
2047 ErrnoC: ErrnoIrrelevant);
2048
2049 // FIXME these are actually defined by POSIX and not by the C standard, we
2050 // should handle them together with the rest of the POSIX functions.
2051 // ssize_t read(int fildes, void *buf, size_t nbyte);
2052 addToFunctionSummaryMap(
2053 "read",
2054 Signature(ArgTypes{IntTy, VoidPtrTy, SizeTyCanonTy}, RetType{Ssize_tTy}),
2055 ReadSummary);
2056 // ssize_t write(int fildes, const void *buf, size_t nbyte);
2057 addToFunctionSummaryMap(
2058 "write",
2059 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTyCanonTy},
2060 RetType{Ssize_tTy}),
2061 ReadSummary);
2062
2063 auto GetLineSummary =
2064 Summary(NoEvalCall)
2065 .Case(CS: {ReturnValueCondition(WithinRange,
2066 Range({-1, -1}, {1, Ssize_tMax}))},
2067 ErrnoC: ErrnoIrrelevant);
2068
2069 QualType CharPtrPtrTy = getPointerTy(CharPtrTy);
2070
2071 // getline()-like functions either fail or read at least the delimiter.
2072 // FIXME these are actually defined by POSIX and not by the C standard, we
2073 // should handle them together with the rest of the POSIX functions.
2074 // ssize_t getline(char **restrict lineptr, size_t *restrict n,
2075 // FILE *restrict stream);
2076 addToFunctionSummaryMap(
2077 "getline",
2078 Signature(ArgTypes{CharPtrPtrTy, SizePtrTy, FilePtrTy},
2079 RetType{Ssize_tTy}),
2080 GetLineSummary);
2081 // ssize_t getdelim(char **restrict lineptr, size_t *restrict n,
2082 // int delimiter, FILE *restrict stream);
2083 addToFunctionSummaryMap(
2084 "getdelim",
2085 Signature(ArgTypes{CharPtrPtrTy, SizePtrTy, IntTy, FilePtrTy},
2086 RetType{Ssize_tTy}),
2087 GetLineSummary);
2088
2089 {
2090 Summary GetenvSummary =
2091 Summary(NoEvalCall)
2092 .ArgConstraint(VC: NotNull(ArgNo(0)))
2093 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoIrrelevant,
2094 Note: "Assuming the environment variable exists");
2095 // In untrusted environments the envvar might not exist.
2096 if (!ShouldAssumeControlledEnvironment)
2097 GetenvSummary.Case(CS: {NotNull(Ret)->negate()}, ErrnoC: ErrnoIrrelevant,
2098 Note: "Assuming the environment variable does not exist");
2099
2100 // char *getenv(const char *name);
2101 addToFunctionSummaryMap(
2102 "getenv", Signature(ArgTypes{ConstCharPtrTy}, RetType{CharPtrTy}),
2103 std::move(GetenvSummary));
2104 }
2105
2106 if (!ModelPOSIX) {
2107 // Without POSIX use of 'errno' is not specified (in these cases).
2108 // Add these functions without 'errno' checks.
2109 addToFunctionSummaryMap(
2110 {"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2111 Summary(NoEvalCall)
2112 .Case(CS: {ReturnValueCondition(WithinRange,
2113 {{EOFv, EOFv}, {0, UCharRangeMax}})},
2114 ErrnoC: ErrnoIrrelevant)
2115 .ArgConstraint(VC: NotNull(ArgNo(0))));
2116 } else {
2117 const auto ReturnsZero =
2118 ConstraintSet{ReturnValueCondition(WithinRange, SingleValue(0))};
2119 const auto ReturnsMinusOne =
2120 ConstraintSet{ReturnValueCondition(WithinRange, SingleValue(-1))};
2121 const auto ReturnsEOF =
2122 ConstraintSet{ReturnValueCondition(WithinRange, SingleValue(EOFv))};
2123 const auto ReturnsNonnegative =
2124 ConstraintSet{ReturnValueCondition(WithinRange, Range(0, IntMax))};
2125 const auto ReturnsNonZero =
2126 ConstraintSet{ReturnValueCondition(OutOfRange, SingleValue(0))};
2127 const auto &ReturnsValidFileDescriptor = ReturnsNonnegative;
2128
2129 auto ValidFileDescriptorOrAtFdcwd = [&](ArgNo ArgN) {
2130 return std::make_shared<RangeConstraint>(
2131 args&: ArgN, args: WithinRange, args: Range({AT_FDCWDv, AT_FDCWDv}, {0, IntMax}),
2132 args: "a valid file descriptor or AT_FDCWD");
2133 };
2134
2135 // FILE *fopen(const char *restrict pathname, const char *restrict mode);
2136 addToFunctionSummaryMap(
2137 "fopen",
2138 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{FilePtrTy}),
2139 Summary(NoEvalCall)
2140 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2141 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2142 .ArgConstraint(VC: NotNull(ArgNo(0)))
2143 .ArgConstraint(VC: NotNull(ArgNo(1))));
2144
2145 // FILE *fdopen(int fd, const char *mode);
2146 addToFunctionSummaryMap(
2147 "fdopen",
2148 Signature(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}),
2149 Summary(NoEvalCall)
2150 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2151 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2152 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
2153 .ArgConstraint(VC: NotNull(ArgNo(1))));
2154
2155 // FILE *tmpfile(void);
2156 addToFunctionSummaryMap(
2157 "tmpfile", Signature(ArgTypes{}, RetType{FilePtrTy}),
2158 Summary(NoEvalCall)
2159 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2160 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg));
2161
2162 // FILE *freopen(const char *restrict pathname, const char *restrict mode,
2163 // FILE *restrict stream);
2164 addToFunctionSummaryMap(
2165 "freopen",
2166 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, FilePtrTy},
2167 RetType{FilePtrTy}),
2168 Summary(NoEvalCall)
2169 .Case(CS: {ReturnValueCondition(BO_EQ, ArgNo(2))},
2170 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2171 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2172 .ArgConstraint(VC: NotNull(ArgNo(1)))
2173 .ArgConstraint(VC: NotNull(ArgNo(2))));
2174
2175 // FILE *popen(const char *command, const char *type);
2176 addToFunctionSummaryMap(
2177 "popen",
2178 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{FilePtrTy}),
2179 Summary(NoEvalCall)
2180 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2181 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2182 .ArgConstraint(VC: NotNull(ArgNo(0)))
2183 .ArgConstraint(VC: NotNull(ArgNo(1))));
2184
2185 // int fclose(FILE *stream);
2186 addToFunctionSummaryMap(
2187 "fclose", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2188 Summary(NoEvalCall)
2189 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2190 .Case(CS: ReturnsEOF, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2191 .ArgConstraint(VC: NotNull(ArgNo(0))));
2192
2193 // int pclose(FILE *stream);
2194 addToFunctionSummaryMap(
2195 "pclose", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2196 Summary(NoEvalCall)
2197 .Case(CS: {ReturnValueCondition(WithinRange, {{0, IntMax}})},
2198 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2199 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2200 .ArgConstraint(VC: NotNull(ArgNo(0))));
2201
2202 std::optional<QualType> Off_tTy = lookupTy("off_t");
2203 std::optional<RangeInt> Off_tMax = getMaxValue(Off_tTy);
2204
2205 // int fgetc(FILE *stream);
2206 // 'getc' is the same as 'fgetc' but may be a macro
2207 addToFunctionSummaryMap(
2208 {"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2209 Summary(NoEvalCall)
2210 .Case(CS: {ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
2211 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2212 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(EOFv))},
2213 ErrnoC: ErrnoIrrelevant, Note: GenericFailureMsg)
2214 .ArgConstraint(VC: NotNull(ArgNo(0))));
2215
2216 // int fputc(int c, FILE *stream);
2217 // 'putc' is the same as 'fputc' but may be a macro
2218 addToFunctionSummaryMap(
2219 {"putc", "fputc"},
2220 Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
2221 Summary(NoEvalCall)
2222 .Case(CS: {ArgumentCondition(0, WithinRange, Range(0, UCharRangeMax)),
2223 ReturnValueCondition(BO_EQ, ArgNo(0))},
2224 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2225 .Case(CS: {ArgumentCondition(0, OutOfRange, Range(0, UCharRangeMax)),
2226 ReturnValueCondition(WithinRange, Range(0, UCharRangeMax))},
2227 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2228 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(EOFv))},
2229 ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2230 .ArgConstraint(VC: NotNull(ArgNo(1))));
2231
2232 // char *fgets(char *restrict s, int n, FILE *restrict stream);
2233 addToFunctionSummaryMap(
2234 "fgets",
2235 Signature(ArgTypes{CharPtrTy, IntTy, FilePtrTy}, RetType{CharPtrTy}),
2236 Summary(NoEvalCall)
2237 .Case(CS: {NotNull(Ret), ReturnValueCondition(BO_EQ, ArgNo(0))},
2238 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2239 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoIrrelevant, Note: GenericFailureMsg)
2240 .ArgConstraint(VC: NotNull(ArgNo(0)))
2241 .ArgConstraint(VC: ArgumentCondition(1, WithinRange, Range(0, IntMax)))
2242 .ArgConstraint(
2243 VC: BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1)))
2244 .ArgConstraint(VC: NotNull(ArgNo(2))));
2245
2246 // int fputs(const char *restrict s, FILE *restrict stream);
2247 addToFunctionSummaryMap(
2248 "fputs", Signature(ArgTypes{ConstCharPtrTy, FilePtrTy}, RetType{IntTy}),
2249 Summary(NoEvalCall)
2250 .Case(CS: ReturnsNonnegative, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2251 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(EOFv))},
2252 ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2253 .ArgConstraint(VC: NotNull(ArgNo(0)))
2254 .ArgConstraint(VC: NotNull(ArgNo(1))));
2255
2256 // int ungetc(int c, FILE *stream);
2257 addToFunctionSummaryMap(
2258 "ungetc", Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
2259 Summary(NoEvalCall)
2260 .Case(CS: {ReturnValueCondition(BO_EQ, ArgNo(0)),
2261 ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})},
2262 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2263 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(EOFv)),
2264 ArgumentCondition(0, WithinRange, SingleValue(EOFv))},
2265 ErrnoC: ErrnoNEZeroIrrelevant,
2266 Note: "Assuming that 'ungetc' fails because EOF was passed as "
2267 "character")
2268 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(EOFv)),
2269 ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})},
2270 ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2271 .ArgConstraint(VC: ArgumentCondition(
2272 0, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}}))
2273 .ArgConstraint(VC: NotNull(ArgNo(1))));
2274
2275 // int fseek(FILE *stream, long offset, int whence);
2276 // FIXME: It can be possible to get the 'SEEK_' values (like EOFv) and use
2277 // these for condition of arg 2.
2278 // Now the range [0,2] is used (the `SEEK_*` constants are usually 0,1,2).
2279 addToFunctionSummaryMap(
2280 "fseek", Signature(ArgTypes{FilePtrTy, LongTy, IntTy}, RetType{IntTy}),
2281 Summary(NoEvalCall)
2282 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2283 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2284 .ArgConstraint(VC: NotNull(ArgNo(0)))
2285 .ArgConstraint(VC: ArgumentCondition(2, WithinRange, {{0, 2}})));
2286
2287 // int fseeko(FILE *stream, off_t offset, int whence);
2288 addToFunctionSummaryMap(
2289 "fseeko",
2290 Signature(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}),
2291 Summary(NoEvalCall)
2292 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2293 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2294 .ArgConstraint(VC: NotNull(ArgNo(0)))
2295 .ArgConstraint(VC: ArgumentCondition(2, WithinRange, {{0, 2}})));
2296
2297 // int fgetpos(FILE *restrict stream, fpos_t *restrict pos);
2298 // From 'The Open Group Base Specifications Issue 7, 2018 edition':
2299 // "The fgetpos() function shall not change the setting of errno if
2300 // successful."
2301 addToFunctionSummaryMap(
2302 "fgetpos", Signature(ArgTypes{FilePtrTy, FPosTPtrTy}, RetType{IntTy}),
2303 Summary(NoEvalCall)
2304 .Case(CS: ReturnsZero, ErrnoC: ErrnoUnchanged, Note: GenericSuccessMsg)
2305 .Case(CS: ReturnsNonZero, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2306 .ArgConstraint(VC: NotNull(ArgNo(0)))
2307 .ArgConstraint(VC: NotNull(ArgNo(1))));
2308
2309 // int fsetpos(FILE *stream, const fpos_t *pos);
2310 // From 'The Open Group Base Specifications Issue 7, 2018 edition':
2311 // "The fsetpos() function shall not change the setting of errno if
2312 // successful."
2313 addToFunctionSummaryMap(
2314 "fsetpos",
2315 Signature(ArgTypes{FilePtrTy, ConstFPosTPtrTy}, RetType{IntTy}),
2316 Summary(NoEvalCall)
2317 .Case(CS: ReturnsZero, ErrnoC: ErrnoUnchanged, Note: GenericSuccessMsg)
2318 .Case(CS: ReturnsNonZero, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2319 .ArgConstraint(VC: NotNull(ArgNo(0)))
2320 .ArgConstraint(VC: NotNull(ArgNo(1))));
2321
2322 // int fflush(FILE *stream);
2323 addToFunctionSummaryMap(
2324 "fflush", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2325 Summary(NoEvalCall)
2326 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2327 .Case(CS: ReturnsEOF, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg));
2328
2329 // long ftell(FILE *stream);
2330 // From 'The Open Group Base Specifications Issue 7, 2018 edition':
2331 // "The ftell() function shall not change the setting of errno if
2332 // successful."
2333 addToFunctionSummaryMap(
2334 "ftell", Signature(ArgTypes{FilePtrTy}, RetType{LongTy}),
2335 Summary(NoEvalCall)
2336 .Case(CS: {ReturnValueCondition(WithinRange, Range(0, LongMax))},
2337 ErrnoC: ErrnoUnchanged, Note: GenericSuccessMsg)
2338 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2339 .ArgConstraint(VC: NotNull(ArgNo(0))));
2340
2341 // off_t ftello(FILE *stream);
2342 addToFunctionSummaryMap(
2343 "ftello", Signature(ArgTypes{FilePtrTy}, RetType{Off_tTy}),
2344 Summary(NoEvalCall)
2345 .Case(CS: {ReturnValueCondition(WithinRange, Range(0, Off_tMax))},
2346 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2347 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2348 .ArgConstraint(VC: NotNull(ArgNo(0))));
2349
2350 // int fileno(FILE *stream);
2351 // According to POSIX 'fileno' may fail and set 'errno'.
2352 // But in Linux it may fail only if the specified file pointer is invalid.
2353 // At many places 'fileno' is used without check for failure and a failure
2354 // case here would produce a large amount of likely false positive warnings.
2355 // To avoid this, we assume here that it does not fail.
2356 addToFunctionSummaryMap(
2357 "fileno", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2358 Summary(NoEvalCall)
2359 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoUnchanged, Note: GenericSuccessMsg)
2360 .ArgConstraint(VC: NotNull(ArgNo(0))));
2361
2362 // void rewind(FILE *stream);
2363 // This function indicates error only by setting of 'errno'.
2364 addToFunctionSummaryMap("rewind",
2365 Signature(ArgTypes{FilePtrTy}, RetType{VoidTy}),
2366 Summary(NoEvalCall)
2367 .Case(CS: {}, ErrnoC: ErrnoMustBeChecked)
2368 .ArgConstraint(VC: NotNull(ArgNo(0))));
2369
2370 // void clearerr(FILE *stream);
2371 addToFunctionSummaryMap(
2372 "clearerr", Signature(ArgTypes{FilePtrTy}, RetType{VoidTy}),
2373 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2374
2375 // int feof(FILE *stream);
2376 addToFunctionSummaryMap(
2377 "feof", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2378 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2379
2380 // int ferror(FILE *stream);
2381 addToFunctionSummaryMap(
2382 "ferror", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
2383 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2384
2385 // long a64l(const char *str64);
2386 addToFunctionSummaryMap(
2387 "a64l", Signature(ArgTypes{ConstCharPtrTy}, RetType{LongTy}),
2388 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2389
2390 // char *l64a(long value);
2391 addToFunctionSummaryMap("l64a",
2392 Signature(ArgTypes{LongTy}, RetType{CharPtrTy}),
2393 Summary(NoEvalCall)
2394 .ArgConstraint(VC: ArgumentCondition(
2395 0, WithinRange, Range(0, LongMax))));
2396
2397 // int open(const char *path, int oflag, ...);
2398 addToFunctionSummaryMap(
2399 "open", Signature(ArgTypes{ConstCharPtrTy, IntTy}, RetType{IntTy}),
2400 Summary(NoEvalCall)
2401 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2402 Note: GenericSuccessMsg)
2403 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2404 .ArgConstraint(VC: NotNull(ArgNo(0))));
2405
2406 // int openat(int fd, const char *path, int oflag, ...);
2407 addToFunctionSummaryMap(
2408 "openat",
2409 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy}, RetType{IntTy}),
2410 Summary(NoEvalCall)
2411 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2412 Note: GenericSuccessMsg)
2413 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2414 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2415 .ArgConstraint(VC: NotNull(ArgNo(1))));
2416
2417 // int access(const char *pathname, int amode);
2418 addToFunctionSummaryMap(
2419 "access", Signature(ArgTypes{ConstCharPtrTy, IntTy}, RetType{IntTy}),
2420 Summary(NoEvalCall)
2421 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2422 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2423 .ArgConstraint(VC: NotNull(ArgNo(0))));
2424
2425 // int faccessat(int dirfd, const char *pathname, int mode, int flags);
2426 addToFunctionSummaryMap(
2427 "faccessat",
2428 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy, IntTy},
2429 RetType{IntTy}),
2430 Summary(NoEvalCall)
2431 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2432 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2433 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2434 .ArgConstraint(VC: NotNull(ArgNo(1))));
2435
2436 // int dup(int fildes);
2437 addToFunctionSummaryMap(
2438 "dup", Signature(ArgTypes{IntTy}, RetType{IntTy}),
2439 Summary(NoEvalCall)
2440 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2441 Note: GenericSuccessMsg)
2442 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2443 .ArgConstraint(
2444 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2445
2446 // int dup2(int fildes1, int filedes2);
2447 addToFunctionSummaryMap(
2448 "dup2", Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}),
2449 Summary(NoEvalCall)
2450 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2451 Note: GenericSuccessMsg)
2452 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2453 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
2454 .ArgConstraint(
2455 VC: ArgumentCondition(1, WithinRange, Range(0, IntMax))));
2456
2457 // int fdatasync(int fildes);
2458 addToFunctionSummaryMap(
2459 "fdatasync", Signature(ArgTypes{IntTy}, RetType{IntTy}),
2460 Summary(NoEvalCall)
2461 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2462 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2463 .ArgConstraint(
2464 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2465
2466 // int fnmatch(const char *pattern, const char *string, int flags);
2467 addToFunctionSummaryMap(
2468 "fnmatch",
2469 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, IntTy},
2470 RetType{IntTy}),
2471 Summary(NoEvalCall)
2472 .ArgConstraint(VC: NotNull(ArgNo(0)))
2473 .ArgConstraint(VC: NotNull(ArgNo(1))));
2474
2475 // int fsync(int fildes);
2476 addToFunctionSummaryMap(
2477 "fsync", Signature(ArgTypes{IntTy}, RetType{IntTy}),
2478 Summary(NoEvalCall)
2479 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2480 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2481 .ArgConstraint(
2482 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2483
2484 // int truncate(const char *path, off_t length);
2485 addToFunctionSummaryMap(
2486 "truncate",
2487 Signature(ArgTypes{ConstCharPtrTy, Off_tTy}, RetType{IntTy}),
2488 Summary(NoEvalCall)
2489 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2490 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2491 .ArgConstraint(VC: NotNull(ArgNo(0))));
2492
2493 // int symlink(const char *oldpath, const char *newpath);
2494 addToFunctionSummaryMap(
2495 "symlink",
2496 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{IntTy}),
2497 Summary(NoEvalCall)
2498 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2499 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2500 .ArgConstraint(VC: NotNull(ArgNo(0)))
2501 .ArgConstraint(VC: NotNull(ArgNo(1))));
2502
2503 // int symlinkat(const char *oldpath, int newdirfd, const char *newpath);
2504 addToFunctionSummaryMap(
2505 "symlinkat",
2506 Signature(ArgTypes{ConstCharPtrTy, IntTy, ConstCharPtrTy},
2507 RetType{IntTy}),
2508 Summary(NoEvalCall)
2509 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2510 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2511 .ArgConstraint(VC: NotNull(ArgNo(0)))
2512 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(1)))
2513 .ArgConstraint(VC: NotNull(ArgNo(2))));
2514
2515 // int lockf(int fd, int cmd, off_t len);
2516 addToFunctionSummaryMap(
2517 "lockf", Signature(ArgTypes{IntTy, IntTy, Off_tTy}, RetType{IntTy}),
2518 Summary(NoEvalCall)
2519 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2520 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2521 .ArgConstraint(
2522 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2523
2524 std::optional<QualType> Mode_tTy = lookupTy("mode_t");
2525
2526 // int creat(const char *pathname, mode_t mode);
2527 addToFunctionSummaryMap(
2528 "creat", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
2529 Summary(NoEvalCall)
2530 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2531 Note: GenericSuccessMsg)
2532 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2533 .ArgConstraint(VC: NotNull(ArgNo(0))));
2534
2535 // unsigned int sleep(unsigned int seconds);
2536 addToFunctionSummaryMap(
2537 "sleep", Signature(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}),
2538 Summary(NoEvalCall)
2539 .ArgConstraint(
2540 VC: ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax))));
2541
2542 std::optional<QualType> DirTy = lookupTy("DIR");
2543 std::optional<QualType> DirPtrTy = getPointerTy(DirTy);
2544
2545 // int dirfd(DIR *dirp);
2546 addToFunctionSummaryMap(
2547 "dirfd", Signature(ArgTypes{DirPtrTy}, RetType{IntTy}),
2548 Summary(NoEvalCall)
2549 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2550 Note: GenericSuccessMsg)
2551 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2552 .ArgConstraint(VC: NotNull(ArgNo(0))));
2553
2554 // unsigned int alarm(unsigned int seconds);
2555 addToFunctionSummaryMap(
2556 "alarm", Signature(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}),
2557 Summary(NoEvalCall)
2558 .ArgConstraint(
2559 VC: ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax))));
2560
2561 // int closedir(DIR *dir);
2562 addToFunctionSummaryMap(
2563 "closedir", Signature(ArgTypes{DirPtrTy}, RetType{IntTy}),
2564 Summary(NoEvalCall)
2565 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2566 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2567 .ArgConstraint(VC: NotNull(ArgNo(0))));
2568
2569 // char *strdup(const char *s);
2570 addToFunctionSummaryMap(
2571 "strdup", Signature(ArgTypes{ConstCharPtrTy}, RetType{CharPtrTy}),
2572 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2573
2574 // char *strndup(const char *s, size_t n);
2575 addToFunctionSummaryMap(
2576 "strndup",
2577 Signature(ArgTypes{ConstCharPtrTy, SizeTyCanonTy}, RetType{CharPtrTy}),
2578 Summary(NoEvalCall)
2579 .ArgConstraint(VC: NotNull(ArgNo(0)))
2580 .ArgConstraint(
2581 VC: ArgumentCondition(1, WithinRange, Range(0, SizeMax))));
2582
2583 // wchar_t *wcsdup(const wchar_t *s);
2584 addToFunctionSummaryMap(
2585 "wcsdup", Signature(ArgTypes{ConstWchar_tPtrTy}, RetType{Wchar_tPtrTy}),
2586 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2587
2588 // int mkstemp(char *template);
2589 addToFunctionSummaryMap(
2590 "mkstemp", Signature(ArgTypes{CharPtrTy}, RetType{IntTy}),
2591 Summary(NoEvalCall)
2592 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
2593 Note: GenericSuccessMsg)
2594 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2595 .ArgConstraint(VC: NotNull(ArgNo(0))));
2596
2597 // char *mkdtemp(char *template);
2598 addToFunctionSummaryMap(
2599 "mkdtemp", Signature(ArgTypes{CharPtrTy}, RetType{CharPtrTy}),
2600 Summary(NoEvalCall)
2601 .Case(CS: {NotNull(Ret), ReturnValueCondition(BO_EQ, ArgNo(0))},
2602 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2603 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2604 .ArgConstraint(VC: NotNull(ArgNo(0))));
2605
2606 // char *getcwd(char *buf, size_t size);
2607 addToFunctionSummaryMap(
2608 "getcwd",
2609 Signature(ArgTypes{CharPtrTy, SizeTyCanonTy}, RetType{CharPtrTy}),
2610 Summary(NoEvalCall)
2611 .Case(CS: {NotNull(0),
2612 ArgumentCondition(1, WithinRange, Range(1, SizeMax)),
2613 ReturnValueCondition(BO_EQ, ArgNo(0)), NotNull(Ret)},
2614 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2615 .Case(CS: {NotNull(0),
2616 ArgumentCondition(1, WithinRange, SingleValue(0)),
2617 IsNull(Ret)},
2618 ErrnoC: ErrnoNEZeroIrrelevant, Note: "Assuming that argument 'size' is 0")
2619 .Case(CS: {NotNull(0),
2620 ArgumentCondition(1, WithinRange, Range(1, SizeMax)),
2621 IsNull(Ret)},
2622 ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2623 .Case(CS: {IsNull(0), NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked,
2624 Note: GenericSuccessMsg)
2625 .Case(CS: {IsNull(0), IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant,
2626 Note: GenericFailureMsg)
2627 .ArgConstraint(
2628 VC: BufferSize(/*Buffer*/ ArgNo(0), /*BufSize*/ ArgNo(1)))
2629 .ArgConstraint(
2630 VC: ArgumentCondition(1, WithinRange, Range(0, SizeMax))));
2631
2632 // int mkdir(const char *pathname, mode_t mode);
2633 addToFunctionSummaryMap(
2634 "mkdir", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
2635 Summary(NoEvalCall)
2636 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2637 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2638 .ArgConstraint(VC: NotNull(ArgNo(0))));
2639
2640 // int mkdirat(int dirfd, const char *pathname, mode_t mode);
2641 addToFunctionSummaryMap(
2642 "mkdirat",
2643 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
2644 Summary(NoEvalCall)
2645 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2646 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2647 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2648 .ArgConstraint(VC: NotNull(ArgNo(1))));
2649
2650 std::optional<QualType> Dev_tTy = lookupTy("dev_t");
2651
2652 // int mknod(const char *pathname, mode_t mode, dev_t dev);
2653 addToFunctionSummaryMap(
2654 "mknod",
2655 Signature(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy}, RetType{IntTy}),
2656 Summary(NoEvalCall)
2657 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2658 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2659 .ArgConstraint(VC: NotNull(ArgNo(0))));
2660
2661 // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
2662 addToFunctionSummaryMap(
2663 "mknodat",
2664 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, Dev_tTy},
2665 RetType{IntTy}),
2666 Summary(NoEvalCall)
2667 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2668 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2669 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2670 .ArgConstraint(VC: NotNull(ArgNo(1))));
2671
2672 // int chmod(const char *path, mode_t mode);
2673 addToFunctionSummaryMap(
2674 "chmod", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}),
2675 Summary(NoEvalCall)
2676 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2677 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2678 .ArgConstraint(VC: NotNull(ArgNo(0))));
2679
2680 // int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);
2681 addToFunctionSummaryMap(
2682 "fchmodat",
2683 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, IntTy},
2684 RetType{IntTy}),
2685 Summary(NoEvalCall)
2686 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2687 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2688 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2689 .ArgConstraint(VC: NotNull(ArgNo(1))));
2690
2691 // int fchmod(int fildes, mode_t mode);
2692 addToFunctionSummaryMap(
2693 "fchmod", Signature(ArgTypes{IntTy, Mode_tTy}, RetType{IntTy}),
2694 Summary(NoEvalCall)
2695 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2696 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2697 .ArgConstraint(
2698 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2699
2700 std::optional<QualType> Uid_tTy = lookupTy("uid_t");
2701 std::optional<QualType> Gid_tTy = lookupTy("gid_t");
2702
2703 // int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group,
2704 // int flags);
2705 addToFunctionSummaryMap(
2706 "fchownat",
2707 Signature(ArgTypes{IntTy, ConstCharPtrTy, Uid_tTy, Gid_tTy, IntTy},
2708 RetType{IntTy}),
2709 Summary(NoEvalCall)
2710 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2711 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2712 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2713 .ArgConstraint(VC: NotNull(ArgNo(1))));
2714
2715 // int chown(const char *path, uid_t owner, gid_t group);
2716 addToFunctionSummaryMap(
2717 "chown",
2718 Signature(ArgTypes{ConstCharPtrTy, Uid_tTy, Gid_tTy}, RetType{IntTy}),
2719 Summary(NoEvalCall)
2720 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2721 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2722 .ArgConstraint(VC: NotNull(ArgNo(0))));
2723
2724 // int lchown(const char *path, uid_t owner, gid_t group);
2725 addToFunctionSummaryMap(
2726 "lchown",
2727 Signature(ArgTypes{ConstCharPtrTy, Uid_tTy, Gid_tTy}, RetType{IntTy}),
2728 Summary(NoEvalCall)
2729 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2730 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2731 .ArgConstraint(VC: NotNull(ArgNo(0))));
2732
2733 // int fchown(int fildes, uid_t owner, gid_t group);
2734 addToFunctionSummaryMap(
2735 "fchown", Signature(ArgTypes{IntTy, Uid_tTy, Gid_tTy}, RetType{IntTy}),
2736 Summary(NoEvalCall)
2737 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2738 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2739 .ArgConstraint(
2740 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2741
2742 // int rmdir(const char *pathname);
2743 addToFunctionSummaryMap(
2744 "rmdir", Signature(ArgTypes{ConstCharPtrTy}, RetType{IntTy}),
2745 Summary(NoEvalCall)
2746 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2747 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2748 .ArgConstraint(VC: NotNull(ArgNo(0))));
2749
2750 // int chdir(const char *path);
2751 addToFunctionSummaryMap(
2752 "chdir", Signature(ArgTypes{ConstCharPtrTy}, RetType{IntTy}),
2753 Summary(NoEvalCall)
2754 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2755 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2756 .ArgConstraint(VC: NotNull(ArgNo(0))));
2757
2758 // int link(const char *oldpath, const char *newpath);
2759 addToFunctionSummaryMap(
2760 "link",
2761 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{IntTy}),
2762 Summary(NoEvalCall)
2763 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2764 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2765 .ArgConstraint(VC: NotNull(ArgNo(0)))
2766 .ArgConstraint(VC: NotNull(ArgNo(1))));
2767
2768 // int linkat(int fd1, const char *path1, int fd2, const char *path2,
2769 // int flag);
2770 addToFunctionSummaryMap(
2771 "linkat",
2772 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy, ConstCharPtrTy, IntTy},
2773 RetType{IntTy}),
2774 Summary(NoEvalCall)
2775 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2776 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2777 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2778 .ArgConstraint(VC: NotNull(ArgNo(1)))
2779 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(2)))
2780 .ArgConstraint(VC: NotNull(ArgNo(3))));
2781
2782 // int unlink(const char *pathname);
2783 addToFunctionSummaryMap(
2784 "unlink", Signature(ArgTypes{ConstCharPtrTy}, RetType{IntTy}),
2785 Summary(NoEvalCall)
2786 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2787 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2788 .ArgConstraint(VC: NotNull(ArgNo(0))));
2789
2790 // int unlinkat(int fd, const char *path, int flag);
2791 addToFunctionSummaryMap(
2792 "unlinkat",
2793 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy}, RetType{IntTy}),
2794 Summary(NoEvalCall)
2795 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2796 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2797 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2798 .ArgConstraint(VC: NotNull(ArgNo(1))));
2799
2800 std::optional<QualType> StructStatTy = lookupTy("stat");
2801 std::optional<QualType> StructStatPtrTy = getPointerTy(StructStatTy);
2802
2803 // int fstat(int fd, struct stat *statbuf);
2804 addToFunctionSummaryMap(
2805 "fstat", Signature(ArgTypes{IntTy, StructStatPtrTy}, RetType{IntTy}),
2806 Summary(NoEvalCall)
2807 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2808 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2809 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
2810 .ArgConstraint(VC: NotNull(ArgNo(1))));
2811
2812 // int stat(const char *restrict path, struct stat *restrict buf);
2813 addToFunctionSummaryMap(
2814 "stat",
2815 Signature(ArgTypes{ConstCharPtrTy, StructStatPtrTy}, RetType{IntTy}),
2816 Summary(NoEvalCall)
2817 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2818 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2819 .ArgConstraint(VC: NotNull(ArgNo(0)))
2820 .ArgConstraint(VC: NotNull(ArgNo(1))));
2821
2822 // int lstat(const char *restrict path, struct stat *restrict buf);
2823 addToFunctionSummaryMap(
2824 "lstat",
2825 Signature(ArgTypes{ConstCharPtrTy, StructStatPtrTy}, RetType{IntTy}),
2826 Summary(NoEvalCall)
2827 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2828 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2829 .ArgConstraint(VC: NotNull(ArgNo(0)))
2830 .ArgConstraint(VC: NotNull(ArgNo(1))));
2831
2832 // int fstatat(int fd, const char *restrict path,
2833 // struct stat *restrict buf, int flag);
2834 addToFunctionSummaryMap(
2835 "fstatat",
2836 Signature(ArgTypes{IntTy, ConstCharPtrTy, StructStatPtrTy, IntTy},
2837 RetType{IntTy}),
2838 Summary(NoEvalCall)
2839 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2840 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2841 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
2842 .ArgConstraint(VC: NotNull(ArgNo(1)))
2843 .ArgConstraint(VC: NotNull(ArgNo(2))));
2844
2845 // DIR *opendir(const char *name);
2846 addToFunctionSummaryMap(
2847 "opendir", Signature(ArgTypes{ConstCharPtrTy}, RetType{DirPtrTy}),
2848 Summary(NoEvalCall)
2849 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2850 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2851 .ArgConstraint(VC: NotNull(ArgNo(0))));
2852
2853 // DIR *fdopendir(int fd);
2854 addToFunctionSummaryMap(
2855 "fdopendir", Signature(ArgTypes{IntTy}, RetType{DirPtrTy}),
2856 Summary(NoEvalCall)
2857 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2858 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2859 .ArgConstraint(
2860 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2861
2862 // int isatty(int fildes);
2863 addToFunctionSummaryMap(
2864 "isatty", Signature(ArgTypes{IntTy}, RetType{IntTy}),
2865 Summary(NoEvalCall)
2866 .Case(CS: {ReturnValueCondition(WithinRange, Range(0, 1))},
2867 ErrnoC: ErrnoIrrelevant)
2868 .ArgConstraint(
2869 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2870
2871 // int close(int fildes);
2872 addToFunctionSummaryMap(
2873 "close", Signature(ArgTypes{IntTy}, RetType{IntTy}),
2874 Summary(NoEvalCall)
2875 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2876 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2877 .ArgConstraint(
2878 VC: ArgumentCondition(0, WithinRange, Range(-1, IntMax))));
2879
2880 // long fpathconf(int fildes, int name);
2881 addToFunctionSummaryMap("fpathconf",
2882 Signature(ArgTypes{IntTy, IntTy}, RetType{LongTy}),
2883 Summary(NoEvalCall)
2884 .ArgConstraint(VC: ArgumentCondition(
2885 0, WithinRange, Range(0, IntMax))));
2886
2887 // long pathconf(const char *path, int name);
2888 addToFunctionSummaryMap(
2889 "pathconf", Signature(ArgTypes{ConstCharPtrTy, IntTy}, RetType{LongTy}),
2890 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2891
2892 // void rewinddir(DIR *dir);
2893 addToFunctionSummaryMap(
2894 "rewinddir", Signature(ArgTypes{DirPtrTy}, RetType{VoidTy}),
2895 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2896
2897 // void seekdir(DIR *dirp, long loc);
2898 addToFunctionSummaryMap(
2899 "seekdir", Signature(ArgTypes{DirPtrTy, LongTy}, RetType{VoidTy}),
2900 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2901
2902 // int rand_r(unsigned int *seedp);
2903 addToFunctionSummaryMap(
2904 "rand_r", Signature(ArgTypes{UnsignedIntPtrTy}, RetType{IntTy}),
2905 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
2906
2907 // void *mmap(void *addr, size_t length, int prot, int flags, int fd,
2908 // off_t offset);
2909 // FIXME: Improve for errno modeling.
2910 auto MmapSignature = Signature(
2911 ArgTypes{VoidPtrTy, SizeTyCanonTy, IntTy, IntTy, IntTy, Off_tTy},
2912 RetType{VoidPtrTy});
2913 auto MmapSummaryWithLengthConstraint =
2914 Summary(NoEvalCall)
2915 .ArgConstraint(
2916 VC: ArgumentCondition(1, WithinRange, Range(1, SizeMax)));
2917
2918 if (ACtx.getTargetInfo().getTriple().isOSDarwin()) {
2919 // On Darwin, MAP_ANON + VM_MAKE_TAG(tag) uses argument 4 (len) for
2920 // the tag, which looks like a large negative signed integer.
2921 // The valid range for fd is not expressible as a simple union of
2922 // ranges so we only constrain the length parameter.
2923 addToFunctionSummaryMap("mmap", MmapSignature,
2924 MmapSummaryWithLengthConstraint);
2925 } else {
2926 // On other platforms, we also constrain the fd parameter (-1 <= fd).
2927 addToFunctionSummaryMap(
2928 "mmap", MmapSignature,
2929 MmapSummaryWithLengthConstraint.ArgConstraint(
2930 VC: ArgumentCondition(4, WithinRange, Range(-1, IntMax))));
2931 }
2932
2933 std::optional<QualType> Off64_tTy = lookupTy("off64_t");
2934 // void *mmap64(void *addr, size_t length, int prot, int flags, int fd,
2935 // off64_t offset);
2936 // FIXME: Improve for errno modeling.
2937 addToFunctionSummaryMap(
2938 "mmap64",
2939 Signature(
2940 ArgTypes{VoidPtrTy, SizeTyCanonTy, IntTy, IntTy, IntTy, Off64_tTy},
2941 RetType{VoidPtrTy}),
2942 Summary(NoEvalCall)
2943 .ArgConstraint(VC: ArgumentCondition(1, WithinRange, Range(1, SizeMax)))
2944 .ArgConstraint(
2945 VC: ArgumentCondition(4, WithinRange, Range(-1, IntMax))));
2946
2947 // int pipe(int fildes[2]);
2948 addToFunctionSummaryMap(
2949 "pipe", Signature(ArgTypes{IntPtrTy}, RetType{IntTy}),
2950 Summary(NoEvalCall)
2951 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2952 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2953 .ArgConstraint(VC: NotNull(ArgNo(0))));
2954
2955 // off_t lseek(int fildes, off_t offset, int whence);
2956 // In the first case we can not tell for sure if it failed or not.
2957 // A return value different from of the expected offset (that is unknown
2958 // here) may indicate failure. For this reason we do not enforce the errno
2959 // check (can cause false positive).
2960 addToFunctionSummaryMap(
2961 "lseek", Signature(ArgTypes{IntTy, Off_tTy, IntTy}, RetType{Off_tTy}),
2962 Summary(NoEvalCall)
2963 .Case(CS: ReturnsNonnegative, ErrnoC: ErrnoIrrelevant)
2964 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2965 .ArgConstraint(
2966 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
2967
2968 // ssize_t readlink(const char *restrict path, char *restrict buf,
2969 // size_t bufsize);
2970 addToFunctionSummaryMap(
2971 "readlink",
2972 Signature(ArgTypes{ConstCharPtrTy, CharPtrTy, SizeTyCanonTy},
2973 RetType{Ssize_tTy}),
2974 Summary(NoEvalCall)
2975 .Case(CS: {ArgumentCondition(2, WithinRange, Range(1, IntMax)),
2976 ReturnValueCondition(LessThanOrEq, ArgNo(2)),
2977 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
2978 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
2979 .Case(CS: {ArgumentCondition(2, WithinRange, SingleValue(0)),
2980 ReturnValueCondition(WithinRange, SingleValue(0))},
2981 ErrnoC: ErrnoMustNotBeChecked,
2982 Note: "Assuming that argument 'bufsize' is 0")
2983 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
2984 .ArgConstraint(VC: NotNull(ArgNo(0)))
2985 .ArgConstraint(VC: NotNull(ArgNo(1)))
2986 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(1),
2987 /*BufSize=*/ArgNo(2)))
2988 .ArgConstraint(
2989 VC: ArgumentCondition(2, WithinRange, Range(0, SizeMax))));
2990
2991 // ssize_t readlinkat(int fd, const char *restrict path,
2992 // char *restrict buf, size_t bufsize);
2993 addToFunctionSummaryMap(
2994 "readlinkat",
2995 Signature(ArgTypes{IntTy, ConstCharPtrTy, CharPtrTy, SizeTyCanonTy},
2996 RetType{Ssize_tTy}),
2997 Summary(NoEvalCall)
2998 .Case(CS: {ArgumentCondition(3, WithinRange, Range(1, IntMax)),
2999 ReturnValueCondition(LessThanOrEq, ArgNo(3)),
3000 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3001 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3002 .Case(CS: {ArgumentCondition(3, WithinRange, SingleValue(0)),
3003 ReturnValueCondition(WithinRange, SingleValue(0))},
3004 ErrnoC: ErrnoMustNotBeChecked,
3005 Note: "Assuming that argument 'bufsize' is 0")
3006 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3007 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
3008 .ArgConstraint(VC: NotNull(ArgNo(1)))
3009 .ArgConstraint(VC: NotNull(ArgNo(2)))
3010 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(2),
3011 /*BufSize=*/ArgNo(3)))
3012 .ArgConstraint(
3013 VC: ArgumentCondition(3, WithinRange, Range(0, SizeMax))));
3014
3015 // int renameat(int olddirfd, const char *oldpath, int newdirfd, const char
3016 // *newpath);
3017 addToFunctionSummaryMap(
3018 "renameat",
3019 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy, ConstCharPtrTy},
3020 RetType{IntTy}),
3021 Summary(NoEvalCall)
3022 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3023 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3024 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(0)))
3025 .ArgConstraint(VC: NotNull(ArgNo(1)))
3026 .ArgConstraint(VC: ValidFileDescriptorOrAtFdcwd(ArgNo(2)))
3027 .ArgConstraint(VC: NotNull(ArgNo(3))));
3028
3029 // char *realpath(const char *restrict file_name,
3030 // char *restrict resolved_name);
3031 // FIXME: If the argument 'resolved_name' is not NULL, macro 'PATH_MAX'
3032 // should be defined in "limits.h" to guarrantee a success.
3033 addToFunctionSummaryMap(
3034 "realpath",
3035 Signature(ArgTypes{ConstCharPtrTy, CharPtrTy}, RetType{CharPtrTy}),
3036 Summary(NoEvalCall)
3037 .Case(CS: {NotNull(Ret)}, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3038 .Case(CS: {IsNull(Ret)}, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3039 .ArgConstraint(VC: NotNull(ArgNo(0))));
3040
3041 QualType CharPtrConstPtr = getPointerTy(getConstTy(CharPtrTy));
3042
3043 // int execv(const char *path, char *const argv[]);
3044 addToFunctionSummaryMap(
3045 "execv",
3046 Signature(ArgTypes{ConstCharPtrTy, CharPtrConstPtr}, RetType{IntTy}),
3047 Summary(NoEvalCall)
3048 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant)
3049 .ArgConstraint(VC: NotNull(ArgNo(0))));
3050
3051 // int execvp(const char *file, char *const argv[]);
3052 addToFunctionSummaryMap(
3053 "execvp",
3054 Signature(ArgTypes{ConstCharPtrTy, CharPtrConstPtr}, RetType{IntTy}),
3055 Summary(NoEvalCall)
3056 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant)
3057 .ArgConstraint(VC: NotNull(ArgNo(0))));
3058
3059 // int getopt(int argc, char * const argv[], const char *optstring);
3060 addToFunctionSummaryMap(
3061 "getopt",
3062 Signature(ArgTypes{IntTy, CharPtrConstPtr, ConstCharPtrTy},
3063 RetType{IntTy}),
3064 Summary(NoEvalCall)
3065 .Case(CS: {ReturnValueCondition(WithinRange, Range(-1, UCharRangeMax))},
3066 ErrnoC: ErrnoIrrelevant)
3067 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3068 .ArgConstraint(VC: NotNull(ArgNo(1)))
3069 .ArgConstraint(VC: NotNull(ArgNo(2))));
3070
3071 std::optional<QualType> StructSockaddrTy = lookupTy("sockaddr");
3072 std::optional<QualType> StructSockaddrPtrTy =
3073 getPointerTy(StructSockaddrTy);
3074 std::optional<QualType> ConstStructSockaddrPtrTy =
3075 getPointerTy(getConstTy(StructSockaddrTy));
3076 std::optional<QualType> Socklen_tTy = lookupTy("socklen_t");
3077 std::optional<QualType> Socklen_tPtrTy = getPointerTy(Socklen_tTy);
3078 std::optional<RangeInt> Socklen_tMax = getMaxValue(Socklen_tTy);
3079
3080 // In 'socket.h' of some libc implementations with C99, sockaddr parameter
3081 // is a transparent union of the underlying sockaddr_ family of pointers
3082 // instead of being a pointer to struct sockaddr. In these cases, the
3083 // standardized signature will not match, thus we try to match with another
3084 // signature that has the joker Irrelevant type. We also remove those
3085 // constraints which require pointer types for the sockaddr param.
3086
3087 // int socket(int domain, int type, int protocol);
3088 addToFunctionSummaryMap(
3089 "socket", Signature(ArgTypes{IntTy, IntTy, IntTy}, RetType{IntTy}),
3090 Summary(NoEvalCall)
3091 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
3092 Note: GenericSuccessMsg)
3093 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg));
3094
3095 auto Accept =
3096 Summary(NoEvalCall)
3097 .Case(CS: ReturnsValidFileDescriptor, ErrnoC: ErrnoMustNotBeChecked,
3098 Note: GenericSuccessMsg)
3099 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3100 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)));
3101 if (!addToFunctionSummaryMap(
3102 "accept",
3103 // int accept(int socket, struct sockaddr *restrict address,
3104 // socklen_t *restrict address_len);
3105 Signature(ArgTypes{IntTy, StructSockaddrPtrTy, Socklen_tPtrTy},
3106 RetType{IntTy}),
3107 Accept))
3108 addToFunctionSummaryMap(
3109 "accept",
3110 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrTy},
3111 RetType{IntTy}),
3112 Accept);
3113
3114 // int bind(int socket, const struct sockaddr *address, socklen_t
3115 // address_len);
3116 if (!addToFunctionSummaryMap(
3117 "bind",
3118 Signature(ArgTypes{IntTy, ConstStructSockaddrPtrTy, Socklen_tTy},
3119 RetType{IntTy}),
3120 Summary(NoEvalCall)
3121 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3122 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3123 .ArgConstraint(
3124 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3125 .ArgConstraint(VC: NotNull(ArgNo(1)))
3126 .ArgConstraint(
3127 VC: BufferSize(/*Buffer=*/ArgNo(1), /*BufSize=*/ArgNo(2)))
3128 .ArgConstraint(
3129 VC: ArgumentCondition(2, WithinRange, Range(0, Socklen_tMax)))))
3130 // Do not add constraints on sockaddr.
3131 addToFunctionSummaryMap(
3132 "bind",
3133 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tTy}, RetType{IntTy}),
3134 Summary(NoEvalCall)
3135 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3136 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3137 .ArgConstraint(
3138 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3139 .ArgConstraint(
3140 VC: ArgumentCondition(2, WithinRange, Range(0, Socklen_tMax))));
3141
3142 // int getpeername(int socket, struct sockaddr *restrict address,
3143 // socklen_t *restrict address_len);
3144 if (!addToFunctionSummaryMap(
3145 "getpeername",
3146 Signature(ArgTypes{IntTy, StructSockaddrPtrTy, Socklen_tPtrTy},
3147 RetType{IntTy}),
3148 Summary(NoEvalCall)
3149 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3150 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3151 .ArgConstraint(
3152 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3153 .ArgConstraint(VC: NotNull(ArgNo(1)))
3154 .ArgConstraint(VC: NotNull(ArgNo(2)))))
3155 addToFunctionSummaryMap(
3156 "getpeername",
3157 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrTy},
3158 RetType{IntTy}),
3159 Summary(NoEvalCall)
3160 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3161 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3162 .ArgConstraint(
3163 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3164
3165 // int getsockname(int socket, struct sockaddr *restrict address,
3166 // socklen_t *restrict address_len);
3167 if (!addToFunctionSummaryMap(
3168 "getsockname",
3169 Signature(ArgTypes{IntTy, StructSockaddrPtrTy, Socklen_tPtrTy},
3170 RetType{IntTy}),
3171 Summary(NoEvalCall)
3172 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3173 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3174 .ArgConstraint(
3175 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3176 .ArgConstraint(VC: NotNull(ArgNo(1)))
3177 .ArgConstraint(VC: NotNull(ArgNo(2)))))
3178 addToFunctionSummaryMap(
3179 "getsockname",
3180 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrTy},
3181 RetType{IntTy}),
3182 Summary(NoEvalCall)
3183 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3184 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3185 .ArgConstraint(
3186 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3187
3188 // int connect(int socket, const struct sockaddr *address, socklen_t
3189 // address_len);
3190 if (!addToFunctionSummaryMap(
3191 "connect",
3192 Signature(ArgTypes{IntTy, ConstStructSockaddrPtrTy, Socklen_tTy},
3193 RetType{IntTy}),
3194 Summary(NoEvalCall)
3195 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3196 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3197 .ArgConstraint(
3198 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3199 .ArgConstraint(VC: NotNull(ArgNo(1)))))
3200 addToFunctionSummaryMap(
3201 "connect",
3202 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tTy}, RetType{IntTy}),
3203 Summary(NoEvalCall)
3204 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3205 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3206 .ArgConstraint(
3207 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3208
3209 auto Recvfrom =
3210 Summary(NoEvalCall)
3211 .Case(CS: {ReturnValueCondition(LessThanOrEq, ArgNo(2)),
3212 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3213 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3214 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(0)),
3215 ArgumentCondition(2, WithinRange, SingleValue(0))},
3216 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3217 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3218 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3219 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(1),
3220 /*BufSize=*/ArgNo(2)));
3221 if (!addToFunctionSummaryMap(
3222 "recvfrom",
3223 // ssize_t recvfrom(int socket, void *restrict buffer,
3224 // size_t length,
3225 // int flags, struct sockaddr *restrict address,
3226 // socklen_t *restrict address_len);
3227 Signature(ArgTypes{IntTy, VoidPtrTy, SizeTyCanonTy, IntTy,
3228 StructSockaddrPtrTy, Socklen_tPtrTy},
3229 RetType{Ssize_tTy}),
3230 Recvfrom))
3231 addToFunctionSummaryMap(
3232 "recvfrom",
3233 Signature(ArgTypes{IntTy, VoidPtrTy, SizeTyCanonTy, IntTy, Irrelevant,
3234 Socklen_tPtrTy},
3235 RetType{Ssize_tTy}),
3236 Recvfrom);
3237
3238 auto Sendto =
3239 Summary(NoEvalCall)
3240 .Case(CS: {ReturnValueCondition(LessThanOrEq, ArgNo(2)),
3241 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3242 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3243 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(0)),
3244 ArgumentCondition(2, WithinRange, SingleValue(0))},
3245 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3246 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3247 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3248 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(1),
3249 /*BufSize=*/ArgNo(2)));
3250 if (!addToFunctionSummaryMap(
3251 "sendto",
3252 // ssize_t sendto(int socket, const void *message, size_t length,
3253 // int flags, const struct sockaddr *dest_addr,
3254 // socklen_t dest_len);
3255 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTyCanonTy, IntTy,
3256 ConstStructSockaddrPtrTy, Socklen_tTy},
3257 RetType{Ssize_tTy}),
3258 Sendto))
3259 addToFunctionSummaryMap(
3260 "sendto",
3261 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTyCanonTy, IntTy,
3262 Irrelevant, Socklen_tTy},
3263 RetType{Ssize_tTy}),
3264 Sendto);
3265
3266 // int listen(int sockfd, int backlog);
3267 addToFunctionSummaryMap(
3268 "listen", Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}),
3269 Summary(NoEvalCall)
3270 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3271 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3272 .ArgConstraint(
3273 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3274
3275 // ssize_t recv(int sockfd, void *buf, size_t len, int flags);
3276 addToFunctionSummaryMap(
3277 "recv",
3278 Signature(ArgTypes{IntTy, VoidPtrTy, SizeTyCanonTy, IntTy},
3279 RetType{Ssize_tTy}),
3280 Summary(NoEvalCall)
3281 .Case(CS: {ReturnValueCondition(LessThanOrEq, ArgNo(2)),
3282 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3283 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3284 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(0)),
3285 ArgumentCondition(2, WithinRange, SingleValue(0))},
3286 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3287 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3288 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3289 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(1),
3290 /*BufSize=*/ArgNo(2))));
3291
3292 std::optional<QualType> StructMsghdrTy = lookupTy("msghdr");
3293 std::optional<QualType> StructMsghdrPtrTy = getPointerTy(StructMsghdrTy);
3294 std::optional<QualType> ConstStructMsghdrPtrTy =
3295 getPointerTy(getConstTy(StructMsghdrTy));
3296
3297 // ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
3298 addToFunctionSummaryMap(
3299 "recvmsg",
3300 Signature(ArgTypes{IntTy, StructMsghdrPtrTy, IntTy},
3301 RetType{Ssize_tTy}),
3302 Summary(NoEvalCall)
3303 .Case(CS: {ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3304 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3305 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3306 .ArgConstraint(
3307 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3308
3309 // ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
3310 addToFunctionSummaryMap(
3311 "sendmsg",
3312 Signature(ArgTypes{IntTy, ConstStructMsghdrPtrTy, IntTy},
3313 RetType{Ssize_tTy}),
3314 Summary(NoEvalCall)
3315 .Case(CS: {ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3316 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3317 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3318 .ArgConstraint(
3319 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3320
3321 // int setsockopt(int socket, int level, int option_name,
3322 // const void *option_value, socklen_t option_len);
3323 addToFunctionSummaryMap(
3324 "setsockopt",
3325 Signature(ArgTypes{IntTy, IntTy, IntTy, ConstVoidPtrTy, Socklen_tTy},
3326 RetType{IntTy}),
3327 Summary(NoEvalCall)
3328 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3329 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3330 .ArgConstraint(VC: NotNullBuffer(ArgNo(3), ArgNo(4)))
3331 .ArgConstraint(
3332 VC: BufferSize(/*Buffer=*/ArgNo(3), /*BufSize=*/ArgNo(4)))
3333 .ArgConstraint(
3334 VC: ArgumentCondition(4, WithinRange, Range(0, Socklen_tMax))));
3335
3336 // int getsockopt(int socket, int level, int option_name,
3337 // void *restrict option_value,
3338 // socklen_t *restrict option_len);
3339 addToFunctionSummaryMap(
3340 "getsockopt",
3341 Signature(ArgTypes{IntTy, IntTy, IntTy, VoidPtrTy, Socklen_tPtrTy},
3342 RetType{IntTy}),
3343 Summary(NoEvalCall)
3344 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3345 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3346 .ArgConstraint(VC: NotNull(ArgNo(3)))
3347 .ArgConstraint(VC: NotNull(ArgNo(4))));
3348
3349 // ssize_t send(int sockfd, const void *buf, size_t len, int flags);
3350 addToFunctionSummaryMap(
3351 "send",
3352 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTyCanonTy, IntTy},
3353 RetType{Ssize_tTy}),
3354 Summary(NoEvalCall)
3355 .Case(CS: {ReturnValueCondition(LessThanOrEq, ArgNo(2)),
3356 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))},
3357 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3358 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(0)),
3359 ArgumentCondition(2, WithinRange, SingleValue(0))},
3360 ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3361 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3362 .ArgConstraint(VC: ArgumentCondition(0, WithinRange, Range(0, IntMax)))
3363 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(1),
3364 /*BufSize=*/ArgNo(2))));
3365
3366 // int socketpair(int domain, int type, int protocol, int sv[2]);
3367 addToFunctionSummaryMap(
3368 "socketpair",
3369 Signature(ArgTypes{IntTy, IntTy, IntTy, IntPtrTy}, RetType{IntTy}),
3370 Summary(NoEvalCall)
3371 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3372 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3373 .ArgConstraint(VC: NotNull(ArgNo(3))));
3374
3375 // int shutdown(int socket, int how);
3376 addToFunctionSummaryMap(
3377 "shutdown", Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}),
3378 Summary(NoEvalCall)
3379 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3380 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3381 .ArgConstraint(
3382 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3383
3384 // int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
3385 // char *restrict node, socklen_t nodelen,
3386 // char *restrict service,
3387 // socklen_t servicelen, int flags);
3388 //
3389 // This is defined in netdb.h. And contrary to 'socket.h', the sockaddr
3390 // parameter is never handled as a transparent union in netdb.h
3391 addToFunctionSummaryMap(
3392 "getnameinfo",
3393 Signature(ArgTypes{ConstStructSockaddrPtrTy, Socklen_tTy, CharPtrTy,
3394 Socklen_tTy, CharPtrTy, Socklen_tTy, IntTy},
3395 RetType{IntTy}),
3396 Summary(NoEvalCall)
3397 .ArgConstraint(
3398 VC: BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1)))
3399 .ArgConstraint(
3400 VC: ArgumentCondition(1, WithinRange, Range(0, Socklen_tMax)))
3401 .ArgConstraint(
3402 VC: BufferSize(/*Buffer=*/ArgNo(2), /*BufSize=*/ArgNo(3)))
3403 .ArgConstraint(
3404 VC: ArgumentCondition(3, WithinRange, Range(0, Socklen_tMax)))
3405 .ArgConstraint(
3406 VC: BufferSize(/*Buffer=*/ArgNo(4), /*BufSize=*/ArgNo(5)))
3407 .ArgConstraint(
3408 VC: ArgumentCondition(5, WithinRange, Range(0, Socklen_tMax))));
3409
3410 std::optional<QualType> StructUtimbufTy = lookupTy("utimbuf");
3411 std::optional<QualType> StructUtimbufPtrTy = getPointerTy(StructUtimbufTy);
3412
3413 // int utime(const char *filename, struct utimbuf *buf);
3414 addToFunctionSummaryMap(
3415 "utime",
3416 Signature(ArgTypes{ConstCharPtrTy, StructUtimbufPtrTy}, RetType{IntTy}),
3417 Summary(NoEvalCall)
3418 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3419 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3420 .ArgConstraint(VC: NotNull(ArgNo(0))));
3421
3422 std::optional<QualType> StructTimespecTy = lookupTy("timespec");
3423 std::optional<QualType> StructTimespecPtrTy =
3424 getPointerTy(StructTimespecTy);
3425 std::optional<QualType> ConstStructTimespecPtrTy =
3426 getPointerTy(getConstTy(StructTimespecTy));
3427
3428 // int futimens(int fd, const struct timespec times[2]);
3429 addToFunctionSummaryMap(
3430 "futimens",
3431 Signature(ArgTypes{IntTy, ConstStructTimespecPtrTy}, RetType{IntTy}),
3432 Summary(NoEvalCall)
3433 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3434 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3435 .ArgConstraint(
3436 VC: ArgumentCondition(0, WithinRange, Range(0, IntMax))));
3437
3438 // int utimensat(int dirfd, const char *pathname,
3439 // const struct timespec times[2], int flags);
3440 addToFunctionSummaryMap(
3441 "utimensat",
3442 Signature(
3443 ArgTypes{IntTy, ConstCharPtrTy, ConstStructTimespecPtrTy, IntTy},
3444 RetType{IntTy}),
3445 Summary(NoEvalCall)
3446 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3447 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3448 .ArgConstraint(VC: NotNull(ArgNo(1))));
3449
3450 std::optional<QualType> StructTimevalTy = lookupTy("timeval");
3451 std::optional<QualType> ConstStructTimevalPtrTy =
3452 getPointerTy(getConstTy(StructTimevalTy));
3453
3454 // int utimes(const char *filename, const struct timeval times[2]);
3455 addToFunctionSummaryMap(
3456 "utimes",
3457 Signature(ArgTypes{ConstCharPtrTy, ConstStructTimevalPtrTy},
3458 RetType{IntTy}),
3459 Summary(NoEvalCall)
3460 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3461 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3462 .ArgConstraint(VC: NotNull(ArgNo(0))));
3463
3464 // int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
3465 addToFunctionSummaryMap(
3466 "nanosleep",
3467 Signature(ArgTypes{ConstStructTimespecPtrTy, StructTimespecPtrTy},
3468 RetType{IntTy}),
3469 Summary(NoEvalCall)
3470 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3471 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3472 .ArgConstraint(VC: NotNull(ArgNo(0))));
3473
3474 std::optional<QualType> Time_tTy = lookupTy("time_t");
3475 std::optional<QualType> ConstTime_tPtrTy =
3476 getPointerTy(getConstTy(Time_tTy));
3477
3478 std::optional<QualType> StructTmTy = lookupTy("tm");
3479 std::optional<QualType> StructTmPtrTy = getPointerTy(StructTmTy);
3480 std::optional<QualType> ConstStructTmPtrTy =
3481 getPointerTy(getConstTy(StructTmTy));
3482
3483 // struct tm * localtime(const time_t *tp);
3484 addToFunctionSummaryMap(
3485 "localtime",
3486 Signature(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}),
3487 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
3488
3489 // struct tm *localtime_r(const time_t *restrict timer,
3490 // struct tm *restrict result);
3491 addToFunctionSummaryMap("localtime_r",
3492 Signature(ArgTypes{ConstTime_tPtrTy, StructTmPtrTy},
3493 RetType{StructTmPtrTy}),
3494 Summary(NoEvalCall)
3495 .ArgConstraint(VC: NotNull(ArgNo(0)))
3496 .ArgConstraint(VC: NotNull(ArgNo(1))));
3497
3498 // char *asctime_r(const struct tm *restrict tm, char *restrict buf);
3499 addToFunctionSummaryMap(
3500 "asctime_r",
3501 Signature(ArgTypes{ConstStructTmPtrTy, CharPtrTy}, RetType{CharPtrTy}),
3502 Summary(NoEvalCall)
3503 .ArgConstraint(VC: NotNull(ArgNo(0)))
3504 .ArgConstraint(VC: NotNull(ArgNo(1)))
3505 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(1),
3506 /*MinBufSize=*/BVF.getValue(X: 26, T: IntTy))));
3507
3508 // char *ctime_r(const time_t *timep, char *buf);
3509 addToFunctionSummaryMap(
3510 "ctime_r",
3511 Signature(ArgTypes{ConstTime_tPtrTy, CharPtrTy}, RetType{CharPtrTy}),
3512 Summary(NoEvalCall)
3513 .ArgConstraint(VC: NotNull(ArgNo(0)))
3514 .ArgConstraint(VC: NotNull(ArgNo(1)))
3515 .ArgConstraint(VC: BufferSize(
3516 /*Buffer=*/ArgNo(1),
3517 /*MinBufSize=*/BVF.getValue(X: 26, T: IntTy))));
3518
3519 // struct tm *gmtime_r(const time_t *restrict timer,
3520 // struct tm *restrict result);
3521 addToFunctionSummaryMap("gmtime_r",
3522 Signature(ArgTypes{ConstTime_tPtrTy, StructTmPtrTy},
3523 RetType{StructTmPtrTy}),
3524 Summary(NoEvalCall)
3525 .ArgConstraint(VC: NotNull(ArgNo(0)))
3526 .ArgConstraint(VC: NotNull(ArgNo(1))));
3527
3528 // struct tm * gmtime(const time_t *tp);
3529 addToFunctionSummaryMap(
3530 "gmtime", Signature(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}),
3531 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
3532
3533 std::optional<QualType> Clockid_tTy = lookupTy("clockid_t");
3534
3535 // int clock_gettime(clockid_t clock_id, struct timespec *tp);
3536 addToFunctionSummaryMap(
3537 "clock_gettime",
3538 Signature(ArgTypes{Clockid_tTy, StructTimespecPtrTy}, RetType{IntTy}),
3539 Summary(NoEvalCall)
3540 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3541 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3542 .ArgConstraint(VC: NotNull(ArgNo(1))));
3543
3544 std::optional<QualType> StructItimervalTy = lookupTy("itimerval");
3545 std::optional<QualType> StructItimervalPtrTy =
3546 getPointerTy(StructItimervalTy);
3547
3548 // int getitimer(int which, struct itimerval *curr_value);
3549 addToFunctionSummaryMap(
3550 "getitimer",
3551 Signature(ArgTypes{IntTy, StructItimervalPtrTy}, RetType{IntTy}),
3552 Summary(NoEvalCall)
3553 .Case(CS: ReturnsZero, ErrnoC: ErrnoMustNotBeChecked, Note: GenericSuccessMsg)
3554 .Case(CS: ReturnsMinusOne, ErrnoC: ErrnoNEZeroIrrelevant, Note: GenericFailureMsg)
3555 .ArgConstraint(VC: NotNull(ArgNo(1))));
3556
3557 std::optional<QualType> Pthread_cond_tTy = lookupTy("pthread_cond_t");
3558 std::optional<QualType> Pthread_cond_tPtrTy =
3559 getPointerTy(Pthread_cond_tTy);
3560 std::optional<QualType> Pthread_tTy = lookupTy("pthread_t");
3561 std::optional<QualType> Pthread_tPtrTy = getPointerTy(Pthread_tTy);
3562 std::optional<QualType> Pthread_mutex_tTy = lookupTy("pthread_mutex_t");
3563 std::optional<QualType> Pthread_mutex_tPtrTy =
3564 getPointerTy(Pthread_mutex_tTy);
3565 std::optional<QualType> Pthread_attr_tTy = lookupTy("pthread_attr_t");
3566 std::optional<QualType> Pthread_attr_tPtrTy =
3567 getPointerTy(Pthread_attr_tTy);
3568 std::optional<QualType> ConstPthread_attr_tPtrTy =
3569 getPointerTy(getConstTy(Pthread_attr_tTy));
3570 std::optional<QualType> Pthread_mutexattr_tTy =
3571 lookupTy("pthread_mutexattr_t");
3572 std::optional<QualType> ConstPthread_mutexattr_tPtrTy =
3573 getPointerTy(getConstTy(Pthread_mutexattr_tTy));
3574
3575 QualType PthreadStartRoutineTy = getPointerTy(
3576 ACtx.getFunctionType(/*ResultTy=*/VoidPtrTy, /*Args=*/VoidPtrTy,
3577 EPI: FunctionProtoType::ExtProtoInfo()));
3578
3579 // int pthread_cond_signal(pthread_cond_t *cond);
3580 // int pthread_cond_broadcast(pthread_cond_t *cond);
3581 addToFunctionSummaryMap(
3582 {"pthread_cond_signal", "pthread_cond_broadcast"},
3583 Signature(ArgTypes{Pthread_cond_tPtrTy}, RetType{IntTy}),
3584 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
3585
3586 // int pthread_create(pthread_t *restrict thread,
3587 // const pthread_attr_t *restrict attr,
3588 // void *(*start_routine)(void*), void *restrict arg);
3589 addToFunctionSummaryMap(
3590 "pthread_create",
3591 Signature(ArgTypes{Pthread_tPtrTy, ConstPthread_attr_tPtrTy,
3592 PthreadStartRoutineTy, VoidPtrTy},
3593 RetType{IntTy}),
3594 Summary(NoEvalCall)
3595 .ArgConstraint(VC: NotNull(ArgNo(0)))
3596 .ArgConstraint(VC: NotNull(ArgNo(2))));
3597
3598 // int pthread_attr_destroy(pthread_attr_t *attr);
3599 // int pthread_attr_init(pthread_attr_t *attr);
3600 addToFunctionSummaryMap(
3601 {"pthread_attr_destroy", "pthread_attr_init"},
3602 Signature(ArgTypes{Pthread_attr_tPtrTy}, RetType{IntTy}),
3603 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
3604
3605 // int pthread_attr_getstacksize(const pthread_attr_t *restrict attr,
3606 // size_t *restrict stacksize);
3607 // int pthread_attr_getguardsize(const pthread_attr_t *restrict attr,
3608 // size_t *restrict guardsize);
3609 addToFunctionSummaryMap(
3610 {"pthread_attr_getstacksize", "pthread_attr_getguardsize"},
3611 Signature(ArgTypes{ConstPthread_attr_tPtrTy, SizePtrTy},
3612 RetType{IntTy}),
3613 Summary(NoEvalCall)
3614 .ArgConstraint(VC: NotNull(ArgNo(0)))
3615 .ArgConstraint(VC: NotNull(ArgNo(1))));
3616
3617 // int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
3618 // int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
3619 addToFunctionSummaryMap(
3620 {"pthread_attr_setstacksize", "pthread_attr_setguardsize"},
3621 Signature(ArgTypes{Pthread_attr_tPtrTy, SizeTyCanonTy}, RetType{IntTy}),
3622 Summary(NoEvalCall)
3623 .ArgConstraint(VC: NotNull(ArgNo(0)))
3624 .ArgConstraint(
3625 VC: ArgumentCondition(1, WithinRange, Range(0, SizeMax))));
3626
3627 // int pthread_mutex_init(pthread_mutex_t *restrict mutex, const
3628 // pthread_mutexattr_t *restrict attr);
3629 addToFunctionSummaryMap(
3630 "pthread_mutex_init",
3631 Signature(ArgTypes{Pthread_mutex_tPtrTy, ConstPthread_mutexattr_tPtrTy},
3632 RetType{IntTy}),
3633 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
3634
3635 // int pthread_mutex_destroy(pthread_mutex_t *mutex);
3636 // int pthread_mutex_lock(pthread_mutex_t *mutex);
3637 // int pthread_mutex_trylock(pthread_mutex_t *mutex);
3638 // int pthread_mutex_unlock(pthread_mutex_t *mutex);
3639 addToFunctionSummaryMap(
3640 {"pthread_mutex_destroy", "pthread_mutex_lock", "pthread_mutex_trylock",
3641 "pthread_mutex_unlock"},
3642 Signature(ArgTypes{Pthread_mutex_tPtrTy}, RetType{IntTy}),
3643 Summary(NoEvalCall).ArgConstraint(VC: NotNull(ArgNo(0))));
3644 }
3645
3646 // Functions for testing.
3647 if (AddTestFunctions) {
3648 const RangeInt IntMin = BVF.getMinValue(T: IntTy)->getLimitedValue();
3649
3650 addToFunctionSummaryMap(
3651 "__not_null", Signature(ArgTypes{IntPtrTy}, RetType{IntTy}),
3652 Summary(EvalCallAsPure).ArgConstraint(VC: NotNull(ArgNo(0))));
3653
3654 addToFunctionSummaryMap(
3655 "__not_null_buffer",
3656 Signature(ArgTypes{VoidPtrTy, IntTy, IntTy}, RetType{IntTy}),
3657 Summary(EvalCallAsPure)
3658 .ArgConstraint(VC: NotNullBuffer(ArgNo(0), ArgNo(1), ArgNo(2))));
3659
3660 // Test inside range constraints.
3661 addToFunctionSummaryMap(
3662 "__single_val_0", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3663 Summary(EvalCallAsPure)
3664 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, SingleValue(0))));
3665 addToFunctionSummaryMap(
3666 "__single_val_1", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3667 Summary(EvalCallAsPure)
3668 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, SingleValue(1))));
3669 addToFunctionSummaryMap(
3670 "__range_1_2", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3671 Summary(EvalCallAsPure)
3672 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, Range(1, 2))));
3673 addToFunctionSummaryMap(
3674 "__range_m1_1", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3675 Summary(EvalCallAsPure)
3676 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, Range(-1, 1))));
3677 addToFunctionSummaryMap(
3678 "__range_m2_m1", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3679 Summary(EvalCallAsPure)
3680 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, Range(-2, -1))));
3681 addToFunctionSummaryMap(
3682 "__range_m10_10", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3683 Summary(EvalCallAsPure)
3684 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, Range(-10, 10))));
3685 addToFunctionSummaryMap("__range_m1_inf",
3686 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3687 Summary(EvalCallAsPure)
3688 .ArgConstraint(VC: ArgumentCondition(
3689 0U, WithinRange, Range(-1, IntMax))));
3690 addToFunctionSummaryMap("__range_0_inf",
3691 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3692 Summary(EvalCallAsPure)
3693 .ArgConstraint(VC: ArgumentCondition(
3694 0U, WithinRange, Range(0, IntMax))));
3695 addToFunctionSummaryMap("__range_1_inf",
3696 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3697 Summary(EvalCallAsPure)
3698 .ArgConstraint(VC: ArgumentCondition(
3699 0U, WithinRange, Range(1, IntMax))));
3700 addToFunctionSummaryMap("__range_minf_m1",
3701 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3702 Summary(EvalCallAsPure)
3703 .ArgConstraint(VC: ArgumentCondition(
3704 0U, WithinRange, Range(IntMin, -1))));
3705 addToFunctionSummaryMap("__range_minf_0",
3706 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3707 Summary(EvalCallAsPure)
3708 .ArgConstraint(VC: ArgumentCondition(
3709 0U, WithinRange, Range(IntMin, 0))));
3710 addToFunctionSummaryMap("__range_minf_1",
3711 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3712 Summary(EvalCallAsPure)
3713 .ArgConstraint(VC: ArgumentCondition(
3714 0U, WithinRange, Range(IntMin, 1))));
3715 addToFunctionSummaryMap("__range_1_2__4_6",
3716 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3717 Summary(EvalCallAsPure)
3718 .ArgConstraint(VC: ArgumentCondition(
3719 0U, WithinRange, Range({1, 2}, {4, 6}))));
3720 addToFunctionSummaryMap(
3721 "__range_1_2__4_inf", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3722 Summary(EvalCallAsPure)
3723 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange,
3724 Range({1, 2}, {4, IntMax}))));
3725
3726 // Test out of range constraints.
3727 addToFunctionSummaryMap(
3728 "__single_val_out_0", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3729 Summary(EvalCallAsPure)
3730 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, SingleValue(0))));
3731 addToFunctionSummaryMap(
3732 "__single_val_out_1", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3733 Summary(EvalCallAsPure)
3734 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, SingleValue(1))));
3735 addToFunctionSummaryMap(
3736 "__range_out_1_2", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3737 Summary(EvalCallAsPure)
3738 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, Range(1, 2))));
3739 addToFunctionSummaryMap(
3740 "__range_out_m1_1", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3741 Summary(EvalCallAsPure)
3742 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, Range(-1, 1))));
3743 addToFunctionSummaryMap(
3744 "__range_out_m2_m1", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3745 Summary(EvalCallAsPure)
3746 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, Range(-2, -1))));
3747 addToFunctionSummaryMap(
3748 "__range_out_m10_10", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3749 Summary(EvalCallAsPure)
3750 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, Range(-10, 10))));
3751 addToFunctionSummaryMap("__range_out_m1_inf",
3752 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3753 Summary(EvalCallAsPure)
3754 .ArgConstraint(VC: ArgumentCondition(
3755 0U, OutOfRange, Range(-1, IntMax))));
3756 addToFunctionSummaryMap("__range_out_0_inf",
3757 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3758 Summary(EvalCallAsPure)
3759 .ArgConstraint(VC: ArgumentCondition(
3760 0U, OutOfRange, Range(0, IntMax))));
3761 addToFunctionSummaryMap("__range_out_1_inf",
3762 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3763 Summary(EvalCallAsPure)
3764 .ArgConstraint(VC: ArgumentCondition(
3765 0U, OutOfRange, Range(1, IntMax))));
3766 addToFunctionSummaryMap("__range_out_minf_m1",
3767 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3768 Summary(EvalCallAsPure)
3769 .ArgConstraint(VC: ArgumentCondition(
3770 0U, OutOfRange, Range(IntMin, -1))));
3771 addToFunctionSummaryMap("__range_out_minf_0",
3772 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3773 Summary(EvalCallAsPure)
3774 .ArgConstraint(VC: ArgumentCondition(
3775 0U, OutOfRange, Range(IntMin, 0))));
3776 addToFunctionSummaryMap("__range_out_minf_1",
3777 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3778 Summary(EvalCallAsPure)
3779 .ArgConstraint(VC: ArgumentCondition(
3780 0U, OutOfRange, Range(IntMin, 1))));
3781 addToFunctionSummaryMap("__range_out_1_2__4_6",
3782 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3783 Summary(EvalCallAsPure)
3784 .ArgConstraint(VC: ArgumentCondition(
3785 0U, OutOfRange, Range({1, 2}, {4, 6}))));
3786 addToFunctionSummaryMap(
3787 "__range_out_1_2__4_inf", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3788 Summary(EvalCallAsPure)
3789 .ArgConstraint(
3790 VC: ArgumentCondition(0U, OutOfRange, Range({1, 2}, {4, IntMax}))));
3791
3792 // Test range kind.
3793 addToFunctionSummaryMap(
3794 "__within", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3795 Summary(EvalCallAsPure)
3796 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, SingleValue(1))));
3797 addToFunctionSummaryMap(
3798 "__out_of", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3799 Summary(EvalCallAsPure)
3800 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, SingleValue(1))));
3801
3802 addToFunctionSummaryMap(
3803 "__two_constrained_args",
3804 Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}),
3805 Summary(EvalCallAsPure)
3806 .ArgConstraint(VC: ArgumentCondition(0U, WithinRange, SingleValue(1)))
3807 .ArgConstraint(VC: ArgumentCondition(1U, WithinRange, SingleValue(1))));
3808 addToFunctionSummaryMap(
3809 "__arg_constrained_twice", Signature(ArgTypes{IntTy}, RetType{IntTy}),
3810 Summary(EvalCallAsPure)
3811 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, SingleValue(1)))
3812 .ArgConstraint(VC: ArgumentCondition(0U, OutOfRange, SingleValue(2))));
3813 addToFunctionSummaryMap(
3814 "__defaultparam",
3815 Signature(ArgTypes{Irrelevant, IntTy}, RetType{IntTy}),
3816 Summary(EvalCallAsPure).ArgConstraint(VC: NotNull(ArgNo(0))));
3817 addToFunctionSummaryMap(
3818 "__variadic",
3819 Signature(ArgTypes{VoidPtrTy, ConstCharPtrTy}, RetType{IntTy}),
3820 Summary(EvalCallAsPure)
3821 .ArgConstraint(VC: NotNull(ArgNo(0)))
3822 .ArgConstraint(VC: NotNull(ArgNo(1))));
3823 addToFunctionSummaryMap(
3824 "__buf_size_arg_constraint",
3825 Signature(ArgTypes{ConstVoidPtrTy, SizeTyCanonTy}, RetType{IntTy}),
3826 Summary(EvalCallAsPure)
3827 .ArgConstraint(
3828 VC: BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1))));
3829 addToFunctionSummaryMap(
3830 "__buf_size_arg_constraint_mul",
3831 Signature(ArgTypes{ConstVoidPtrTy, SizeTyCanonTy, SizeTyCanonTy},
3832 RetType{IntTy}),
3833 Summary(EvalCallAsPure)
3834 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1),
3835 /*BufSizeMultiplier=*/ArgNo(2))));
3836 addToFunctionSummaryMap(
3837 "__buf_size_arg_constraint_concrete",
3838 Signature(ArgTypes{ConstVoidPtrTy}, RetType{IntTy}),
3839 Summary(EvalCallAsPure)
3840 .ArgConstraint(VC: BufferSize(/*Buffer=*/ArgNo(0),
3841 /*BufSize=*/BVF.getValue(X: 10, T: IntTy))));
3842 addToFunctionSummaryMap({"__test_restrict_param_0",
3843 "__test_restrict_param_1",
3844 "__test_restrict_param_2"},
3845 Signature(ArgTypes{VoidPtrTy}, RetType{VoidTy}),
3846 Summary(EvalCallAsPure));
3847
3848 // Test the application of cases.
3849 addToFunctionSummaryMap(
3850 "__test_case_note", Signature(ArgTypes{}, RetType{IntTy}),
3851 Summary(EvalCallAsPure)
3852 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(0))},
3853 ErrnoC: ErrnoIrrelevant, Note: "Function returns 0")
3854 .Case(CS: {ReturnValueCondition(WithinRange, SingleValue(1))},
3855 ErrnoC: ErrnoIrrelevant, Note: "Function returns 1"));
3856 addToFunctionSummaryMap(
3857 "__test_case_range_1_2__4_6",
3858 Signature(ArgTypes{IntTy}, RetType{IntTy}),
3859 Summary(EvalCallAsPure)
3860 .Case(CS: {ArgumentCondition(0U, WithinRange,
3861 IntRangeVector{{IntMin, 0}, {3, 3}}),
3862 ReturnValueCondition(WithinRange, SingleValue(1))},
3863 ErrnoC: ErrnoIrrelevant)
3864 .Case(CS: {ArgumentCondition(0U, WithinRange,
3865 IntRangeVector{{3, 3}, {7, IntMax}}),
3866 ReturnValueCondition(WithinRange, SingleValue(2))},
3867 ErrnoC: ErrnoIrrelevant)
3868 .Case(CS: {ArgumentCondition(0U, WithinRange,
3869 IntRangeVector{{IntMin, 0}, {7, IntMax}}),
3870 ReturnValueCondition(WithinRange, SingleValue(3))},
3871 ErrnoC: ErrnoIrrelevant)
3872 .Case(CS: {ArgumentCondition(
3873 0U, WithinRange,
3874 IntRangeVector{{IntMin, 0}, {3, 3}, {7, IntMax}}),
3875 ReturnValueCondition(WithinRange, SingleValue(4))},
3876 ErrnoC: ErrnoIrrelevant));
3877 }
3878}
3879
3880void ento::registerStdCLibraryFunctionsChecker(CheckerManager &mgr) {
3881 auto *Checker = mgr.registerChecker<StdLibraryFunctionsChecker>();
3882 Checker->CheckName = mgr.getCurrentCheckerName();
3883 const AnalyzerOptions &Opts = mgr.getAnalyzerOptions();
3884 Checker->DisplayLoadedSummaries =
3885 Opts.getCheckerBooleanOption(C: Checker, OptionName: "DisplayLoadedSummaries");
3886 Checker->ModelPOSIX = Opts.getCheckerBooleanOption(C: Checker, OptionName: "ModelPOSIX");
3887 Checker->ShouldAssumeControlledEnvironment =
3888 Opts.ShouldAssumeControlledEnvironment;
3889}
3890
3891bool ento::shouldRegisterStdCLibraryFunctionsChecker(
3892 const CheckerManager &mgr) {
3893 return true;
3894}
3895
3896void ento::registerStdCLibraryFunctionsTesterChecker(CheckerManager &mgr) {
3897 auto *Checker = mgr.getChecker<StdLibraryFunctionsChecker>();
3898 Checker->AddTestFunctions = true;
3899}
3900
3901bool ento::shouldRegisterStdCLibraryFunctionsTesterChecker(
3902 const CheckerManager &mgr) {
3903 return true;
3904}
3905