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