1 //=== StdLibraryFunctionsChecker.cpp - Model standard functions -*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This checker improves modeling of a few simple library functions. 10 // 11 // This checker provides a specification format - `Summary' - and 12 // contains descriptions of some library functions in this format. Each 13 // specification contains a list of branches for splitting the program state 14 // upon call, and range constraints on argument and return-value symbols that 15 // are satisfied on each branch. This spec can be expanded to include more 16 // items, like external effects of the function. 17 // 18 // The main difference between this approach and the body farms technique is 19 // in more explicit control over how many branches are produced. For example, 20 // consider standard C function `ispunct(int x)', which returns a non-zero value 21 // iff `x' is a punctuation character, that is, when `x' is in range 22 // ['!', '/'] [':', '@'] U ['[', '\`'] U ['{', '~']. 23 // `Summary' provides only two branches for this function. However, 24 // any attempt to describe this range with if-statements in the body farm 25 // would result in many more branches. Because each branch needs to be analyzed 26 // independently, this significantly reduces performance. Additionally, 27 // once we consider a branch on which `x' is in range, say, ['!', '/'], 28 // we assume that such branch is an important separate path through the program, 29 // which may lead to false positives because considering this particular path 30 // was not consciously intended, and therefore it might have been unreachable. 31 // 32 // This checker uses eval::Call for modeling pure functions (functions without 33 // side effets), for which their `Summary' is a precise model. This avoids 34 // unnecessary invalidation passes. Conflicts with other checkers are unlikely 35 // because if the function has no other effects, other checkers would probably 36 // never want to improve upon the modeling done by this checker. 37 // 38 // Non-pure functions, for which only partial improvement over the default 39 // behavior is expected, are modeled via check::PostCall, non-intrusively. 40 // 41 //===----------------------------------------------------------------------===// 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 = std::vector<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 } 1358 } 1359 } 1360 1361 void StdLibraryFunctionsChecker::checkPostCall(const CallEvent &Call, 1362 CheckerContext &C) const { 1363 std::optional<Summary> FoundSummary = findFunctionSummary(Call, C); 1364 if (!FoundSummary) 1365 return; 1366 1367 // Now apply the constraints. 1368 const Summary &Summary = *FoundSummary; 1369 ProgramStateRef State = C.getState(); 1370 ExplodedNode *Node = C.getPredecessor(); 1371 1372 // Apply case/branch specifications. 1373 for (const SummaryCase &Case : Summary.getCases()) { 1374 ProgramStateRef NewState = State; 1375 for (const ValueConstraintPtr &Constraint : Case.getConstraints()) { 1376 NewState = Constraint->apply(NewState, Call, Summary, C); 1377 if (!NewState) 1378 break; 1379 } 1380 1381 if (NewState) 1382 NewState = Case.getErrnoConstraint().apply(NewState, Call, Summary, C); 1383 1384 if (!NewState) 1385 continue; 1386 1387 // Here it's possible that NewState == State, e.g. when other checkers 1388 // already applied the same constraints (or stricter ones). 1389 // Still add these note tags, the other checker should add only its 1390 // specialized note tags. These general note tags are handled always by 1391 // StdLibraryFunctionsChecker. 1392 1393 ExplodedNode *Pred = Node; 1394 DeclarationName FunctionName = 1395 cast<NamedDecl>(Call.getDecl())->getDeclName(); 1396 1397 std::string ErrnoNote = Case.getErrnoConstraint().describe(C); 1398 std::string CaseNote; 1399 if (Case.getNote().empty()) { 1400 if (!ErrnoNote.empty()) 1401 ErrnoNote = 1402 llvm::formatv("After calling '{0}' {1}", FunctionName, ErrnoNote); 1403 } else { 1404 CaseNote = llvm::formatv(Case.getNote().str().c_str(), FunctionName); 1405 } 1406 const SVal RV = Call.getReturnValue(); 1407 1408 if (Summary.getInvalidationKd() == EvalCallAsPure) { 1409 // Do not expect that errno is interesting (the "pure" functions do not 1410 // affect it). 1411 if (!CaseNote.empty()) { 1412 const NoteTag *Tag = C.getNoteTag( 1413 [Node, CaseNote, RV](PathSensitiveBugReport &BR) -> std::string { 1414 // Try to omit the note if we know in advance which branch is 1415 // taken (this means, only one branch exists). 1416 // This check is performed inside the lambda, after other 1417 // (or this) checkers had a chance to add other successors. 1418 // Dereferencing the saved node object is valid because it's part 1419 // of a bug report call sequence. 1420 // FIXME: This check is not exact. We may be here after a state 1421 // split that was performed by another checker (and can not find 1422 // the successors). This is why this check is only used in the 1423 // EvalCallAsPure case. 1424 if (BR.isInteresting(RV) && Node->succ_size() > 1) 1425 return CaseNote; 1426 return ""; 1427 }); 1428 Pred = C.addTransition(NewState, Pred, Tag); 1429 } 1430 } else { 1431 if (!CaseNote.empty() || !ErrnoNote.empty()) { 1432 const NoteTag *Tag = 1433 C.getNoteTag([CaseNote, ErrnoNote, 1434 RV](PathSensitiveBugReport &BR) -> std::string { 1435 // If 'errno' is interesting, show the user a note about the case 1436 // (what happened at the function call) and about how 'errno' 1437 // causes the problem. ErrnoChecker sets the errno (but not RV) to 1438 // interesting. 1439 // If only the return value is interesting, show only the case 1440 // note. 1441 std::optional<Loc> ErrnoLoc = 1442 errno_modeling::getErrnoLoc(BR.getErrorNode()->getState()); 1443 bool ErrnoImportant = !ErrnoNote.empty() && ErrnoLoc && 1444 BR.isInteresting(ErrnoLoc->getAsRegion()); 1445 if (ErrnoImportant) { 1446 BR.markNotInteresting(ErrnoLoc->getAsRegion()); 1447 if (CaseNote.empty()) 1448 return ErrnoNote; 1449 return llvm::formatv("{0}; {1}", CaseNote, ErrnoNote); 1450 } else { 1451 if (BR.isInteresting(RV)) 1452 return CaseNote; 1453 } 1454 return ""; 1455 }); 1456 Pred = C.addTransition(NewState, Pred, Tag); 1457 } 1458 } 1459 1460 // Add the transition if no note tag was added. 1461 if (Pred == Node && NewState != State) 1462 C.addTransition(NewState); 1463 } 1464 } 1465 1466 bool StdLibraryFunctionsChecker::evalCall(const CallEvent &Call, 1467 CheckerContext &C) const { 1468 std::optional<Summary> FoundSummary = findFunctionSummary(Call, C); 1469 if (!FoundSummary) 1470 return false; 1471 1472 const Summary &Summary = *FoundSummary; 1473 switch (Summary.getInvalidationKd()) { 1474 case EvalCallAsPure: { 1475 ProgramStateRef State = C.getState(); 1476 const LocationContext *LC = C.getLocationContext(); 1477 const auto *CE = cast<CallExpr>(Call.getOriginExpr()); 1478 SVal V = C.getSValBuilder().conjureSymbolVal( 1479 CE, LC, CE->getType().getCanonicalType(), C.blockCount()); 1480 State = State->BindExpr(CE, LC, V); 1481 1482 C.addTransition(State); 1483 1484 return true; 1485 } 1486 case NoEvalCall: 1487 // Summary tells us to avoid performing eval::Call. The function is possibly 1488 // evaluated by another checker, or evaluated conservatively. 1489 return false; 1490 } 1491 llvm_unreachable("Unknown invalidation kind!"); 1492 } 1493 1494 bool StdLibraryFunctionsChecker::Signature::matches( 1495 const FunctionDecl *FD) const { 1496 assert(!isInvalid()); 1497 // Check the number of arguments. 1498 if (FD->param_size() != ArgTys.size()) 1499 return false; 1500 1501 // The "restrict" keyword is illegal in C++, however, many libc 1502 // implementations use the "__restrict" compiler intrinsic in functions 1503 // prototypes. The "__restrict" keyword qualifies a type as a restricted type 1504 // even in C++. 1505 // In case of any non-C99 languages, we don't want to match based on the 1506 // restrict qualifier because we cannot know if the given libc implementation 1507 // qualifies the paramter type or not. 1508 auto RemoveRestrict = [&FD](QualType T) { 1509 if (!FD->getASTContext().getLangOpts().C99) 1510 T.removeLocalRestrict(); 1511 return T; 1512 }; 1513 1514 // Check the return type. 1515 if (!isIrrelevant(RetTy)) { 1516 QualType FDRetTy = RemoveRestrict(FD->getReturnType().getCanonicalType()); 1517 if (RetTy != FDRetTy) 1518 return false; 1519 } 1520 1521 // Check the argument types. 1522 for (auto [Idx, ArgTy] : llvm::enumerate(ArgTys)) { 1523 if (isIrrelevant(ArgTy)) 1524 continue; 1525 QualType FDArgTy = 1526 RemoveRestrict(FD->getParamDecl(Idx)->getType().getCanonicalType()); 1527 if (ArgTy != FDArgTy) 1528 return false; 1529 } 1530 1531 return true; 1532 } 1533 1534 std::optional<StdLibraryFunctionsChecker::Summary> 1535 StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD, 1536 CheckerContext &C) const { 1537 if (!FD) 1538 return std::nullopt; 1539 1540 initFunctionSummaries(C); 1541 1542 auto FSMI = FunctionSummaryMap.find(FD->getCanonicalDecl()); 1543 if (FSMI == FunctionSummaryMap.end()) 1544 return std::nullopt; 1545 return FSMI->second; 1546 } 1547 1548 std::optional<StdLibraryFunctionsChecker::Summary> 1549 StdLibraryFunctionsChecker::findFunctionSummary(const CallEvent &Call, 1550 CheckerContext &C) const { 1551 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl()); 1552 if (!FD) 1553 return std::nullopt; 1554 return findFunctionSummary(FD, C); 1555 } 1556 1557 void StdLibraryFunctionsChecker::initFunctionSummaries( 1558 CheckerContext &C) const { 1559 if (SummariesInitialized) 1560 return; 1561 SummariesInitialized = true; 1562 1563 SValBuilder &SVB = C.getSValBuilder(); 1564 BasicValueFactory &BVF = SVB.getBasicValueFactory(); 1565 const ASTContext &ACtx = BVF.getContext(); 1566 Preprocessor &PP = C.getPreprocessor(); 1567 1568 // Helper class to lookup a type by its name. 1569 class LookupType { 1570 const ASTContext &ACtx; 1571 1572 public: 1573 LookupType(const ASTContext &ACtx) : ACtx(ACtx) {} 1574 1575 // Find the type. If not found then the optional is not set. 1576 std::optional<QualType> operator()(StringRef Name) { 1577 IdentifierInfo &II = ACtx.Idents.get(Name); 1578 auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II); 1579 if (LookupRes.empty()) 1580 return std::nullopt; 1581 1582 // Prioritze typedef declarations. 1583 // This is needed in case of C struct typedefs. E.g.: 1584 // typedef struct FILE FILE; 1585 // In this case, we have a RecordDecl 'struct FILE' with the name 'FILE' 1586 // and we have a TypedefDecl with the name 'FILE'. 1587 for (Decl *D : LookupRes) 1588 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 1589 return ACtx.getTypeDeclType(TD).getCanonicalType(); 1590 1591 // Find the first TypeDecl. 1592 // There maybe cases when a function has the same name as a struct. 1593 // E.g. in POSIX: `struct stat` and the function `stat()`: 1594 // int stat(const char *restrict path, struct stat *restrict buf); 1595 for (Decl *D : LookupRes) 1596 if (auto *TD = dyn_cast<TypeDecl>(D)) 1597 return ACtx.getTypeDeclType(TD).getCanonicalType(); 1598 return std::nullopt; 1599 } 1600 } lookupTy(ACtx); 1601 1602 // Below are auxiliary classes to handle optional types that we get as a 1603 // result of the lookup. 1604 class GetRestrictTy { 1605 const ASTContext &ACtx; 1606 1607 public: 1608 GetRestrictTy(const ASTContext &ACtx) : ACtx(ACtx) {} 1609 QualType operator()(QualType Ty) { 1610 return ACtx.getLangOpts().C99 ? ACtx.getRestrictType(Ty) : Ty; 1611 } 1612 std::optional<QualType> operator()(std::optional<QualType> Ty) { 1613 if (Ty) 1614 return operator()(*Ty); 1615 return std::nullopt; 1616 } 1617 } getRestrictTy(ACtx); 1618 class GetPointerTy { 1619 const ASTContext &ACtx; 1620 1621 public: 1622 GetPointerTy(const ASTContext &ACtx) : ACtx(ACtx) {} 1623 QualType operator()(QualType Ty) { return ACtx.getPointerType(Ty); } 1624 std::optional<QualType> operator()(std::optional<QualType> Ty) { 1625 if (Ty) 1626 return operator()(*Ty); 1627 return std::nullopt; 1628 } 1629 } getPointerTy(ACtx); 1630 class { 1631 public: 1632 std::optional<QualType> operator()(std::optional<QualType> Ty) { 1633 return Ty ? std::optional<QualType>(Ty->withConst()) : std::nullopt; 1634 } 1635 QualType operator()(QualType Ty) { return Ty.withConst(); } 1636 } getConstTy; 1637 class GetMaxValue { 1638 BasicValueFactory &BVF; 1639 1640 public: 1641 GetMaxValue(BasicValueFactory &BVF) : BVF(BVF) {} 1642 std::optional<RangeInt> operator()(QualType Ty) { 1643 return BVF.getMaxValue(Ty).getLimitedValue(); 1644 } 1645 std::optional<RangeInt> operator()(std::optional<QualType> Ty) { 1646 if (Ty) { 1647 return operator()(*Ty); 1648 } 1649 return std::nullopt; 1650 } 1651 } getMaxValue(BVF); 1652 1653 // These types are useful for writing specifications quickly, 1654 // New specifications should probably introduce more types. 1655 // Some types are hard to obtain from the AST, eg. "ssize_t". 1656 // In such cases it should be possible to provide multiple variants 1657 // of function summary for common cases (eg. ssize_t could be int or long 1658 // or long long, so three summary variants would be enough). 1659 // Of course, function variants are also useful for C++ overloads. 1660 const QualType VoidTy = ACtx.VoidTy; 1661 const QualType CharTy = ACtx.CharTy; 1662 const QualType WCharTy = ACtx.WCharTy; 1663 const QualType IntTy = ACtx.IntTy; 1664 const QualType UnsignedIntTy = ACtx.UnsignedIntTy; 1665 const QualType LongTy = ACtx.LongTy; 1666 const QualType SizeTy = ACtx.getSizeType(); 1667 1668 const QualType VoidPtrTy = getPointerTy(VoidTy); // void * 1669 const QualType IntPtrTy = getPointerTy(IntTy); // int * 1670 const QualType UnsignedIntPtrTy = 1671 getPointerTy(UnsignedIntTy); // unsigned int * 1672 const QualType VoidPtrRestrictTy = getRestrictTy(VoidPtrTy); 1673 const QualType ConstVoidPtrTy = 1674 getPointerTy(getConstTy(VoidTy)); // const void * 1675 const QualType CharPtrTy = getPointerTy(CharTy); // char * 1676 const QualType CharPtrRestrictTy = getRestrictTy(CharPtrTy); 1677 const QualType ConstCharPtrTy = 1678 getPointerTy(getConstTy(CharTy)); // const char * 1679 const QualType ConstCharPtrRestrictTy = getRestrictTy(ConstCharPtrTy); 1680 const QualType Wchar_tPtrTy = getPointerTy(WCharTy); // wchar_t * 1681 const QualType ConstWchar_tPtrTy = 1682 getPointerTy(getConstTy(WCharTy)); // const wchar_t * 1683 const QualType ConstVoidPtrRestrictTy = getRestrictTy(ConstVoidPtrTy); 1684 const QualType SizePtrTy = getPointerTy(SizeTy); 1685 const QualType SizePtrRestrictTy = getRestrictTy(SizePtrTy); 1686 1687 const RangeInt IntMax = BVF.getMaxValue(IntTy).getLimitedValue(); 1688 const RangeInt UnsignedIntMax = 1689 BVF.getMaxValue(UnsignedIntTy).getLimitedValue(); 1690 const RangeInt LongMax = BVF.getMaxValue(LongTy).getLimitedValue(); 1691 const RangeInt SizeMax = BVF.getMaxValue(SizeTy).getLimitedValue(); 1692 1693 // Set UCharRangeMax to min of int or uchar maximum value. 1694 // The C standard states that the arguments of functions like isalpha must 1695 // be representable as an unsigned char. Their type is 'int', so the max 1696 // value of the argument should be min(UCharMax, IntMax). This just happen 1697 // to be true for commonly used and well tested instruction set 1698 // architectures, but not for others. 1699 const RangeInt UCharRangeMax = 1700 std::min(BVF.getMaxValue(ACtx.UnsignedCharTy).getLimitedValue(), IntMax); 1701 1702 // Get platform dependent values of some macros. 1703 // Try our best to parse this from the Preprocessor, otherwise fallback to a 1704 // default value (what is found in a library header). 1705 const auto EOFv = tryExpandAsInteger("EOF", PP).value_or(-1); 1706 const auto AT_FDCWDv = tryExpandAsInteger("AT_FDCWD", PP).value_or(-100); 1707 1708 // Auxiliary class to aid adding summaries to the summary map. 1709 struct AddToFunctionSummaryMap { 1710 const ASTContext &ACtx; 1711 FunctionSummaryMapType ⤅ 1712 bool DisplayLoadedSummaries; 1713 AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType &FSM, 1714 bool DisplayLoadedSummaries) 1715 : ACtx(ACtx), Map(FSM), DisplayLoadedSummaries(DisplayLoadedSummaries) { 1716 } 1717 1718 // Add a summary to a FunctionDecl found by lookup. The lookup is performed 1719 // by the given Name, and in the global scope. The summary will be attached 1720 // to the found FunctionDecl only if the signatures match. 1721 // 1722 // Returns true if the summary has been added, false otherwise. 1723 bool operator()(StringRef Name, Signature Sign, Summary Sum) { 1724 if (Sign.isInvalid()) 1725 return false; 1726 IdentifierInfo &II = ACtx.Idents.get(Name); 1727 auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II); 1728 if (LookupRes.empty()) 1729 return false; 1730 for (Decl *D : LookupRes) { 1731 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1732 if (Sum.matchesAndSet(Sign, FD)) { 1733 auto Res = Map.insert({FD->getCanonicalDecl(), Sum}); 1734 assert(Res.second && "Function already has a summary set!"); 1735 (void)Res; 1736 if (DisplayLoadedSummaries) { 1737 llvm::errs() << "Loaded summary for: "; 1738 FD->print(llvm::errs()); 1739 llvm::errs() << "\n"; 1740 } 1741 return true; 1742 } 1743 } 1744 } 1745 return false; 1746 } 1747 // Add the same summary for different names with the Signature explicitly 1748 // given. 1749 void operator()(std::vector<StringRef> Names, Signature Sign, Summary Sum) { 1750 for (StringRef Name : Names) 1751 operator()(Name, Sign, Sum); 1752 } 1753 } addToFunctionSummaryMap(ACtx, FunctionSummaryMap, DisplayLoadedSummaries); 1754 1755 // Below are helpers functions to create the summaries. 1756 auto ArgumentCondition = [](ArgNo ArgN, RangeKind Kind, IntRangeVector Ranges, 1757 StringRef Desc = "") { 1758 return std::make_shared<RangeConstraint>(ArgN, Kind, Ranges, Desc); 1759 }; 1760 auto BufferSize = [](auto... Args) { 1761 return std::make_shared<BufferSizeConstraint>(Args...); 1762 }; 1763 struct { 1764 auto operator()(RangeKind Kind, IntRangeVector Ranges) { 1765 return std::make_shared<RangeConstraint>(Ret, Kind, Ranges); 1766 } 1767 auto operator()(BinaryOperator::Opcode Op, ArgNo OtherArgN) { 1768 return std::make_shared<ComparisonConstraint>(Ret, Op, OtherArgN); 1769 } 1770 } ReturnValueCondition; 1771 struct { 1772 auto operator()(RangeInt b, RangeInt e) { 1773 return IntRangeVector{std::pair<RangeInt, RangeInt>{b, e}}; 1774 } 1775 auto operator()(RangeInt b, std::optional<RangeInt> e) { 1776 if (e) 1777 return IntRangeVector{std::pair<RangeInt, RangeInt>{b, *e}}; 1778 return IntRangeVector{}; 1779 } 1780 auto operator()(std::pair<RangeInt, RangeInt> i0, 1781 std::pair<RangeInt, std::optional<RangeInt>> i1) { 1782 if (i1.second) 1783 return IntRangeVector{i0, {i1.first, *(i1.second)}}; 1784 return IntRangeVector{i0}; 1785 } 1786 } Range; 1787 auto SingleValue = [](RangeInt v) { 1788 return IntRangeVector{std::pair<RangeInt, RangeInt>{v, v}}; 1789 }; 1790 auto LessThanOrEq = BO_LE; 1791 auto NotNull = [&](ArgNo ArgN) { 1792 return std::make_shared<NotNullConstraint>(ArgN); 1793 }; 1794 auto IsNull = [&](ArgNo ArgN) { 1795 return std::make_shared<NotNullConstraint>(ArgN, false); 1796 }; 1797 auto NotNullBuffer = [&](ArgNo ArgN, ArgNo SizeArg1N, ArgNo SizeArg2N) { 1798 return std::make_shared<NotNullBufferConstraint>(ArgN, SizeArg1N, 1799 SizeArg2N); 1800 }; 1801 1802 std::optional<QualType> FileTy = lookupTy("FILE"); 1803 std::optional<QualType> FilePtrTy = getPointerTy(FileTy); 1804 std::optional<QualType> FilePtrRestrictTy = getRestrictTy(FilePtrTy); 1805 1806 std::optional<QualType> FPosTTy = lookupTy("fpos_t"); 1807 std::optional<QualType> FPosTPtrTy = getPointerTy(FPosTTy); 1808 std::optional<QualType> ConstFPosTPtrTy = getPointerTy(getConstTy(FPosTTy)); 1809 std::optional<QualType> FPosTPtrRestrictTy = getRestrictTy(FPosTPtrTy); 1810 1811 constexpr llvm::StringLiteral GenericSuccessMsg( 1812 "Assuming that '{0}' is successful"); 1813 constexpr llvm::StringLiteral GenericFailureMsg("Assuming that '{0}' fails"); 1814 1815 // We are finally ready to define specifications for all supported functions. 1816 // 1817 // Argument ranges should always cover all variants. If return value 1818 // is completely unknown, omit it from the respective range set. 1819 // 1820 // Every item in the list of range sets represents a particular 1821 // execution path the analyzer would need to explore once 1822 // the call is modeled - a new program state is constructed 1823 // for every range set, and each range line in the range set 1824 // corresponds to a specific constraint within this state. 1825 1826 // The isascii() family of functions. 1827 // The behavior is undefined if the value of the argument is not 1828 // representable as unsigned char or is not equal to EOF. See e.g. C99 1829 // 7.4.1.2 The isalpha function (p: 181-182). 1830 addToFunctionSummaryMap( 1831 "isalnum", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1832 Summary(EvalCallAsPure) 1833 // Boils down to isupper() or islower() or isdigit(). 1834 .Case({ArgumentCondition(0U, WithinRange, 1835 {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}}), 1836 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1837 ErrnoIrrelevant, "Assuming the character is alphanumeric") 1838 // The locale-specific range. 1839 // No post-condition. We are completely unaware of 1840 // locale-specific return values. 1841 .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})}, 1842 ErrnoIrrelevant) 1843 .Case( 1844 {ArgumentCondition( 1845 0U, OutOfRange, 1846 {{'0', '9'}, {'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}), 1847 ReturnValueCondition(WithinRange, SingleValue(0))}, 1848 ErrnoIrrelevant, "Assuming the character is non-alphanumeric") 1849 .ArgConstraint(ArgumentCondition(0U, WithinRange, 1850 {{EOFv, EOFv}, {0, UCharRangeMax}}, 1851 "an unsigned char value or EOF"))); 1852 addToFunctionSummaryMap( 1853 "isalpha", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1854 Summary(EvalCallAsPure) 1855 .Case({ArgumentCondition(0U, WithinRange, {{'A', 'Z'}, {'a', 'z'}}), 1856 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1857 ErrnoIrrelevant, "Assuming the character is alphabetical") 1858 // The locale-specific range. 1859 .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})}, 1860 ErrnoIrrelevant) 1861 .Case({ArgumentCondition( 1862 0U, OutOfRange, 1863 {{'A', 'Z'}, {'a', 'z'}, {128, UCharRangeMax}}), 1864 ReturnValueCondition(WithinRange, SingleValue(0))}, 1865 ErrnoIrrelevant, "Assuming the character is non-alphabetical")); 1866 addToFunctionSummaryMap( 1867 "isascii", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1868 Summary(EvalCallAsPure) 1869 .Case({ArgumentCondition(0U, WithinRange, Range(0, 127)), 1870 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1871 ErrnoIrrelevant, "Assuming the character is an ASCII character") 1872 .Case({ArgumentCondition(0U, OutOfRange, Range(0, 127)), 1873 ReturnValueCondition(WithinRange, SingleValue(0))}, 1874 ErrnoIrrelevant, 1875 "Assuming the character is not an ASCII character")); 1876 addToFunctionSummaryMap( 1877 "isblank", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1878 Summary(EvalCallAsPure) 1879 .Case({ArgumentCondition(0U, WithinRange, {{'\t', '\t'}, {' ', ' '}}), 1880 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1881 ErrnoIrrelevant, "Assuming the character is a blank character") 1882 .Case({ArgumentCondition(0U, OutOfRange, {{'\t', '\t'}, {' ', ' '}}), 1883 ReturnValueCondition(WithinRange, SingleValue(0))}, 1884 ErrnoIrrelevant, 1885 "Assuming the character is not a blank character")); 1886 addToFunctionSummaryMap( 1887 "iscntrl", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1888 Summary(EvalCallAsPure) 1889 .Case({ArgumentCondition(0U, WithinRange, {{0, 32}, {127, 127}}), 1890 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1891 ErrnoIrrelevant, 1892 "Assuming the character is a control character") 1893 .Case({ArgumentCondition(0U, OutOfRange, {{0, 32}, {127, 127}}), 1894 ReturnValueCondition(WithinRange, SingleValue(0))}, 1895 ErrnoIrrelevant, 1896 "Assuming the character is not a control character")); 1897 addToFunctionSummaryMap( 1898 "isdigit", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1899 Summary(EvalCallAsPure) 1900 .Case({ArgumentCondition(0U, WithinRange, Range('0', '9')), 1901 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1902 ErrnoIrrelevant, "Assuming the character is a digit") 1903 .Case({ArgumentCondition(0U, OutOfRange, Range('0', '9')), 1904 ReturnValueCondition(WithinRange, SingleValue(0))}, 1905 ErrnoIrrelevant, "Assuming the character is not a digit")); 1906 addToFunctionSummaryMap( 1907 "isgraph", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1908 Summary(EvalCallAsPure) 1909 .Case({ArgumentCondition(0U, WithinRange, Range(33, 126)), 1910 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1911 ErrnoIrrelevant, 1912 "Assuming the character has graphical representation") 1913 .Case( 1914 {ArgumentCondition(0U, OutOfRange, Range(33, 126)), 1915 ReturnValueCondition(WithinRange, SingleValue(0))}, 1916 ErrnoIrrelevant, 1917 "Assuming the character does not have graphical representation")); 1918 addToFunctionSummaryMap( 1919 "islower", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1920 Summary(EvalCallAsPure) 1921 // Is certainly lowercase. 1922 .Case({ArgumentCondition(0U, WithinRange, Range('a', 'z')), 1923 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1924 ErrnoIrrelevant, "Assuming the character is a lowercase letter") 1925 // Is ascii but not lowercase. 1926 .Case({ArgumentCondition(0U, WithinRange, Range(0, 127)), 1927 ArgumentCondition(0U, OutOfRange, Range('a', 'z')), 1928 ReturnValueCondition(WithinRange, SingleValue(0))}, 1929 ErrnoIrrelevant, 1930 "Assuming the character is not a lowercase letter") 1931 // The locale-specific range. 1932 .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})}, 1933 ErrnoIrrelevant) 1934 // Is not an unsigned char. 1935 .Case({ArgumentCondition(0U, OutOfRange, Range(0, UCharRangeMax)), 1936 ReturnValueCondition(WithinRange, SingleValue(0))}, 1937 ErrnoIrrelevant)); 1938 addToFunctionSummaryMap( 1939 "isprint", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1940 Summary(EvalCallAsPure) 1941 .Case({ArgumentCondition(0U, WithinRange, Range(32, 126)), 1942 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1943 ErrnoIrrelevant, "Assuming the character is printable") 1944 .Case({ArgumentCondition(0U, OutOfRange, Range(32, 126)), 1945 ReturnValueCondition(WithinRange, SingleValue(0))}, 1946 ErrnoIrrelevant, "Assuming the character is non-printable")); 1947 addToFunctionSummaryMap( 1948 "ispunct", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1949 Summary(EvalCallAsPure) 1950 .Case({ArgumentCondition( 1951 0U, WithinRange, 1952 {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}), 1953 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1954 ErrnoIrrelevant, "Assuming the character is a punctuation mark") 1955 .Case({ArgumentCondition( 1956 0U, OutOfRange, 1957 {{'!', '/'}, {':', '@'}, {'[', '`'}, {'{', '~'}}), 1958 ReturnValueCondition(WithinRange, SingleValue(0))}, 1959 ErrnoIrrelevant, 1960 "Assuming the character is not a punctuation mark")); 1961 addToFunctionSummaryMap( 1962 "isspace", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1963 Summary(EvalCallAsPure) 1964 // Space, '\f', '\n', '\r', '\t', '\v'. 1965 .Case({ArgumentCondition(0U, WithinRange, {{9, 13}, {' ', ' '}}), 1966 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1967 ErrnoIrrelevant, 1968 "Assuming the character is a whitespace character") 1969 // The locale-specific range. 1970 .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})}, 1971 ErrnoIrrelevant) 1972 .Case({ArgumentCondition(0U, OutOfRange, 1973 {{9, 13}, {' ', ' '}, {128, UCharRangeMax}}), 1974 ReturnValueCondition(WithinRange, SingleValue(0))}, 1975 ErrnoIrrelevant, 1976 "Assuming the character is not a whitespace character")); 1977 addToFunctionSummaryMap( 1978 "isupper", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1979 Summary(EvalCallAsPure) 1980 // Is certainly uppercase. 1981 .Case({ArgumentCondition(0U, WithinRange, Range('A', 'Z')), 1982 ReturnValueCondition(OutOfRange, SingleValue(0))}, 1983 ErrnoIrrelevant, 1984 "Assuming the character is an uppercase letter") 1985 // The locale-specific range. 1986 .Case({ArgumentCondition(0U, WithinRange, {{128, UCharRangeMax}})}, 1987 ErrnoIrrelevant) 1988 // Other. 1989 .Case({ArgumentCondition(0U, OutOfRange, 1990 {{'A', 'Z'}, {128, UCharRangeMax}}), 1991 ReturnValueCondition(WithinRange, SingleValue(0))}, 1992 ErrnoIrrelevant, 1993 "Assuming the character is not an uppercase letter")); 1994 addToFunctionSummaryMap( 1995 "isxdigit", Signature(ArgTypes{IntTy}, RetType{IntTy}), 1996 Summary(EvalCallAsPure) 1997 .Case({ArgumentCondition(0U, WithinRange, 1998 {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}), 1999 ReturnValueCondition(OutOfRange, SingleValue(0))}, 2000 ErrnoIrrelevant, 2001 "Assuming the character is a hexadecimal digit") 2002 .Case({ArgumentCondition(0U, OutOfRange, 2003 {{'0', '9'}, {'A', 'F'}, {'a', 'f'}}), 2004 ReturnValueCondition(WithinRange, SingleValue(0))}, 2005 ErrnoIrrelevant, 2006 "Assuming the character is not a hexadecimal digit")); 2007 addToFunctionSummaryMap( 2008 "toupper", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2009 Summary(EvalCallAsPure) 2010 .ArgConstraint(ArgumentCondition(0U, WithinRange, 2011 {{EOFv, EOFv}, {0, UCharRangeMax}}, 2012 "an unsigned char value or EOF"))); 2013 addToFunctionSummaryMap( 2014 "tolower", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2015 Summary(EvalCallAsPure) 2016 .ArgConstraint(ArgumentCondition(0U, WithinRange, 2017 {{EOFv, EOFv}, {0, UCharRangeMax}}, 2018 "an unsigned char value or EOF"))); 2019 addToFunctionSummaryMap( 2020 "toascii", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2021 Summary(EvalCallAsPure) 2022 .ArgConstraint(ArgumentCondition(0U, WithinRange, 2023 {{EOFv, EOFv}, {0, UCharRangeMax}}, 2024 "an unsigned char value or EOF"))); 2025 2026 // The getc() family of functions that returns either a char or an EOF. 2027 addToFunctionSummaryMap( 2028 {"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2029 Summary(NoEvalCall) 2030 .Case({ReturnValueCondition(WithinRange, 2031 {{EOFv, EOFv}, {0, UCharRangeMax}})}, 2032 ErrnoIrrelevant)); 2033 addToFunctionSummaryMap( 2034 "getchar", Signature(ArgTypes{}, RetType{IntTy}), 2035 Summary(NoEvalCall) 2036 .Case({ReturnValueCondition(WithinRange, 2037 {{EOFv, EOFv}, {0, UCharRangeMax}})}, 2038 ErrnoIrrelevant)); 2039 2040 // read()-like functions that never return more than buffer size. 2041 auto FreadSummary = 2042 Summary(NoEvalCall) 2043 .Case({ArgumentCondition(1U, WithinRange, Range(1, SizeMax)), 2044 ArgumentCondition(2U, WithinRange, Range(1, SizeMax)), 2045 ReturnValueCondition(BO_LT, ArgNo(2)), 2046 ReturnValueCondition(WithinRange, Range(0, SizeMax))}, 2047 ErrnoNEZeroIrrelevant, GenericFailureMsg) 2048 .Case({ArgumentCondition(1U, WithinRange, Range(1, SizeMax)), 2049 ReturnValueCondition(BO_EQ, ArgNo(2)), 2050 ReturnValueCondition(WithinRange, Range(0, SizeMax))}, 2051 ErrnoMustNotBeChecked, GenericSuccessMsg) 2052 .Case({ArgumentCondition(1U, WithinRange, SingleValue(0)), 2053 ReturnValueCondition(WithinRange, SingleValue(0))}, 2054 ErrnoMustNotBeChecked, 2055 "Assuming that argument 'size' to '{0}' is 0") 2056 .ArgConstraint(NotNullBuffer(ArgNo(0), ArgNo(1), ArgNo(2))) 2057 .ArgConstraint(NotNull(ArgNo(3))) 2058 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1), 2059 /*BufSizeMultiplier=*/ArgNo(2))); 2060 2061 // size_t fread(void *restrict ptr, size_t size, size_t nitems, 2062 // FILE *restrict stream); 2063 addToFunctionSummaryMap( 2064 "fread", 2065 Signature(ArgTypes{VoidPtrRestrictTy, SizeTy, SizeTy, FilePtrRestrictTy}, 2066 RetType{SizeTy}), 2067 FreadSummary); 2068 // size_t fwrite(const void *restrict ptr, size_t size, size_t nitems, 2069 // FILE *restrict stream); 2070 addToFunctionSummaryMap("fwrite", 2071 Signature(ArgTypes{ConstVoidPtrRestrictTy, SizeTy, 2072 SizeTy, FilePtrRestrictTy}, 2073 RetType{SizeTy}), 2074 FreadSummary); 2075 2076 std::optional<QualType> Ssize_tTy = lookupTy("ssize_t"); 2077 std::optional<RangeInt> Ssize_tMax = getMaxValue(Ssize_tTy); 2078 2079 auto ReadSummary = 2080 Summary(NoEvalCall) 2081 .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)), 2082 ReturnValueCondition(WithinRange, Range(-1, Ssize_tMax))}, 2083 ErrnoIrrelevant); 2084 2085 // FIXME these are actually defined by POSIX and not by the C standard, we 2086 // should handle them together with the rest of the POSIX functions. 2087 // ssize_t read(int fildes, void *buf, size_t nbyte); 2088 addToFunctionSummaryMap( 2089 "read", Signature(ArgTypes{IntTy, VoidPtrTy, SizeTy}, RetType{Ssize_tTy}), 2090 ReadSummary); 2091 // ssize_t write(int fildes, const void *buf, size_t nbyte); 2092 addToFunctionSummaryMap( 2093 "write", 2094 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy}, RetType{Ssize_tTy}), 2095 ReadSummary); 2096 2097 auto GetLineSummary = 2098 Summary(NoEvalCall) 2099 .Case({ReturnValueCondition(WithinRange, 2100 Range({-1, -1}, {1, Ssize_tMax}))}, 2101 ErrnoIrrelevant); 2102 2103 QualType CharPtrPtrRestrictTy = getRestrictTy(getPointerTy(CharPtrTy)); 2104 2105 // getline()-like functions either fail or read at least the delimiter. 2106 // FIXME these are actually defined by POSIX and not by the C standard, we 2107 // should handle them together with the rest of the POSIX functions. 2108 // ssize_t getline(char **restrict lineptr, size_t *restrict n, 2109 // FILE *restrict stream); 2110 addToFunctionSummaryMap( 2111 "getline", 2112 Signature( 2113 ArgTypes{CharPtrPtrRestrictTy, SizePtrRestrictTy, FilePtrRestrictTy}, 2114 RetType{Ssize_tTy}), 2115 GetLineSummary); 2116 // ssize_t getdelim(char **restrict lineptr, size_t *restrict n, 2117 // int delimiter, FILE *restrict stream); 2118 addToFunctionSummaryMap( 2119 "getdelim", 2120 Signature(ArgTypes{CharPtrPtrRestrictTy, SizePtrRestrictTy, IntTy, 2121 FilePtrRestrictTy}, 2122 RetType{Ssize_tTy}), 2123 GetLineSummary); 2124 2125 { 2126 Summary GetenvSummary = 2127 Summary(NoEvalCall) 2128 .ArgConstraint(NotNull(ArgNo(0))) 2129 .Case({NotNull(Ret)}, ErrnoIrrelevant, 2130 "Assuming the environment variable exists"); 2131 // In untrusted environments the envvar might not exist. 2132 if (!ShouldAssumeControlledEnvironment) 2133 GetenvSummary.Case({NotNull(Ret)->negate()}, ErrnoIrrelevant, 2134 "Assuming the environment variable does not exist"); 2135 2136 // char *getenv(const char *name); 2137 addToFunctionSummaryMap( 2138 "getenv", Signature(ArgTypes{ConstCharPtrTy}, RetType{CharPtrTy}), 2139 std::move(GetenvSummary)); 2140 } 2141 2142 if (ModelPOSIX) { 2143 const auto ReturnsZeroOrMinusOne = 2144 ConstraintSet{ReturnValueCondition(WithinRange, Range(-1, 0))}; 2145 const auto ReturnsZero = 2146 ConstraintSet{ReturnValueCondition(WithinRange, SingleValue(0))}; 2147 const auto ReturnsMinusOne = 2148 ConstraintSet{ReturnValueCondition(WithinRange, SingleValue(-1))}; 2149 const auto ReturnsEOF = 2150 ConstraintSet{ReturnValueCondition(WithinRange, SingleValue(EOFv))}; 2151 const auto ReturnsNonnegative = 2152 ConstraintSet{ReturnValueCondition(WithinRange, Range(0, IntMax))}; 2153 const auto ReturnsNonZero = 2154 ConstraintSet{ReturnValueCondition(OutOfRange, SingleValue(0))}; 2155 const auto ReturnsFileDescriptor = 2156 ConstraintSet{ReturnValueCondition(WithinRange, Range(-1, IntMax))}; 2157 const auto &ReturnsValidFileDescriptor = ReturnsNonnegative; 2158 2159 auto ValidFileDescriptorOrAtFdcwd = [&](ArgNo ArgN) { 2160 return std::make_shared<RangeConstraint>( 2161 ArgN, WithinRange, Range({AT_FDCWDv, AT_FDCWDv}, {0, IntMax}), 2162 "a valid file descriptor or AT_FDCWD"); 2163 }; 2164 2165 // FILE *fopen(const char *restrict pathname, const char *restrict mode); 2166 addToFunctionSummaryMap( 2167 "fopen", 2168 Signature(ArgTypes{ConstCharPtrRestrictTy, ConstCharPtrRestrictTy}, 2169 RetType{FilePtrTy}), 2170 Summary(NoEvalCall) 2171 .Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg) 2172 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2173 .ArgConstraint(NotNull(ArgNo(0))) 2174 .ArgConstraint(NotNull(ArgNo(1)))); 2175 2176 // FILE *fdopen(int fd, const char *mode); 2177 addToFunctionSummaryMap( 2178 "fdopen", 2179 Signature(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}), 2180 Summary(NoEvalCall) 2181 .Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg) 2182 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2183 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 2184 .ArgConstraint(NotNull(ArgNo(1)))); 2185 2186 // FILE *tmpfile(void); 2187 addToFunctionSummaryMap( 2188 "tmpfile", Signature(ArgTypes{}, RetType{FilePtrTy}), 2189 Summary(NoEvalCall) 2190 .Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg) 2191 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)); 2192 2193 // FILE *freopen(const char *restrict pathname, const char *restrict mode, 2194 // FILE *restrict stream); 2195 addToFunctionSummaryMap( 2196 "freopen", 2197 Signature(ArgTypes{ConstCharPtrRestrictTy, ConstCharPtrRestrictTy, 2198 FilePtrRestrictTy}, 2199 RetType{FilePtrTy}), 2200 Summary(NoEvalCall) 2201 .Case({ReturnValueCondition(BO_EQ, ArgNo(2))}, 2202 ErrnoMustNotBeChecked, GenericSuccessMsg) 2203 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2204 .ArgConstraint(NotNull(ArgNo(1))) 2205 .ArgConstraint(NotNull(ArgNo(2)))); 2206 2207 // int fclose(FILE *stream); 2208 addToFunctionSummaryMap( 2209 "fclose", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2210 Summary(NoEvalCall) 2211 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2212 .Case(ReturnsEOF, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2213 .ArgConstraint(NotNull(ArgNo(0)))); 2214 2215 // int ungetc(int c, FILE *stream); 2216 addToFunctionSummaryMap( 2217 "ungetc", Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}), 2218 Summary(NoEvalCall) 2219 .Case({ReturnValueCondition(BO_EQ, ArgNo(0)), 2220 ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})}, 2221 ErrnoMustNotBeChecked, GenericSuccessMsg) 2222 .Case({ReturnValueCondition(WithinRange, SingleValue(EOFv)), 2223 ArgumentCondition(0, WithinRange, SingleValue(EOFv))}, 2224 ErrnoNEZeroIrrelevant, 2225 "Assuming that 'ungetc' fails because EOF was passed as " 2226 "character") 2227 .Case({ReturnValueCondition(WithinRange, SingleValue(EOFv)), 2228 ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})}, 2229 ErrnoNEZeroIrrelevant, GenericFailureMsg) 2230 .ArgConstraint(ArgumentCondition( 2231 0, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}})) 2232 .ArgConstraint(NotNull(ArgNo(1)))); 2233 2234 std::optional<QualType> Off_tTy = lookupTy("off_t"); 2235 std::optional<RangeInt> Off_tMax = getMaxValue(Off_tTy); 2236 2237 // int fseek(FILE *stream, long offset, int whence); 2238 // FIXME: It can be possible to get the 'SEEK_' values (like EOFv) and use 2239 // these for condition of arg 2. 2240 // Now the range [0,2] is used (the `SEEK_*` constants are usually 0,1,2). 2241 addToFunctionSummaryMap( 2242 "fseek", Signature(ArgTypes{FilePtrTy, LongTy, IntTy}, RetType{IntTy}), 2243 Summary(NoEvalCall) 2244 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2245 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2246 .ArgConstraint(NotNull(ArgNo(0))) 2247 .ArgConstraint(ArgumentCondition(2, WithinRange, {{0, 2}}))); 2248 2249 // int fseeko(FILE *stream, off_t offset, int whence); 2250 addToFunctionSummaryMap( 2251 "fseeko", 2252 Signature(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}), 2253 Summary(NoEvalCall) 2254 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2255 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2256 .ArgConstraint(NotNull(ArgNo(0))) 2257 .ArgConstraint(ArgumentCondition(2, WithinRange, {{0, 2}}))); 2258 2259 // int fgetpos(FILE *restrict stream, fpos_t *restrict pos); 2260 // From 'The Open Group Base Specifications Issue 7, 2018 edition': 2261 // "The fgetpos() function shall not change the setting of errno if 2262 // successful." 2263 addToFunctionSummaryMap( 2264 "fgetpos", 2265 Signature(ArgTypes{FilePtrRestrictTy, FPosTPtrRestrictTy}, 2266 RetType{IntTy}), 2267 Summary(NoEvalCall) 2268 .Case(ReturnsZero, ErrnoUnchanged, GenericSuccessMsg) 2269 .Case(ReturnsNonZero, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2270 .ArgConstraint(NotNull(ArgNo(0))) 2271 .ArgConstraint(NotNull(ArgNo(1)))); 2272 2273 // int fsetpos(FILE *stream, const fpos_t *pos); 2274 // From 'The Open Group Base Specifications Issue 7, 2018 edition': 2275 // "The fsetpos() function shall not change the setting of errno if 2276 // successful." 2277 addToFunctionSummaryMap( 2278 "fsetpos", 2279 Signature(ArgTypes{FilePtrTy, ConstFPosTPtrTy}, RetType{IntTy}), 2280 Summary(NoEvalCall) 2281 .Case(ReturnsZero, ErrnoUnchanged, GenericSuccessMsg) 2282 .Case(ReturnsNonZero, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2283 .ArgConstraint(NotNull(ArgNo(0))) 2284 .ArgConstraint(NotNull(ArgNo(1)))); 2285 2286 // int fflush(FILE *stream); 2287 addToFunctionSummaryMap( 2288 "fflush", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2289 Summary(NoEvalCall) 2290 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2291 .Case(ReturnsEOF, ErrnoNEZeroIrrelevant, GenericFailureMsg)); 2292 2293 // long ftell(FILE *stream); 2294 // From 'The Open Group Base Specifications Issue 7, 2018 edition': 2295 // "The ftell() function shall not change the setting of errno if 2296 // successful." 2297 addToFunctionSummaryMap( 2298 "ftell", Signature(ArgTypes{FilePtrTy}, RetType{LongTy}), 2299 Summary(NoEvalCall) 2300 .Case({ReturnValueCondition(WithinRange, Range(0, LongMax))}, 2301 ErrnoUnchanged, GenericSuccessMsg) 2302 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2303 .ArgConstraint(NotNull(ArgNo(0)))); 2304 2305 // off_t ftello(FILE *stream); 2306 addToFunctionSummaryMap( 2307 "ftello", Signature(ArgTypes{FilePtrTy}, RetType{Off_tTy}), 2308 Summary(NoEvalCall) 2309 .Case({ReturnValueCondition(WithinRange, Range(0, Off_tMax))}, 2310 ErrnoMustNotBeChecked, GenericSuccessMsg) 2311 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2312 .ArgConstraint(NotNull(ArgNo(0)))); 2313 2314 // int fileno(FILE *stream); 2315 addToFunctionSummaryMap( 2316 "fileno", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2317 Summary(NoEvalCall) 2318 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2319 GenericSuccessMsg) 2320 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2321 .ArgConstraint(NotNull(ArgNo(0)))); 2322 2323 // void rewind(FILE *stream); 2324 // This function indicates error only by setting of 'errno'. 2325 addToFunctionSummaryMap("rewind", 2326 Signature(ArgTypes{FilePtrTy}, RetType{VoidTy}), 2327 Summary(NoEvalCall) 2328 .Case({}, ErrnoMustBeChecked) 2329 .ArgConstraint(NotNull(ArgNo(0)))); 2330 2331 // void clearerr(FILE *stream); 2332 addToFunctionSummaryMap( 2333 "clearerr", Signature(ArgTypes{FilePtrTy}, RetType{VoidTy}), 2334 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2335 2336 // int feof(FILE *stream); 2337 addToFunctionSummaryMap( 2338 "feof", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2339 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2340 2341 // int ferror(FILE *stream); 2342 addToFunctionSummaryMap( 2343 "ferror", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2344 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2345 2346 // long a64l(const char *str64); 2347 addToFunctionSummaryMap( 2348 "a64l", Signature(ArgTypes{ConstCharPtrTy}, RetType{LongTy}), 2349 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2350 2351 // char *l64a(long value); 2352 addToFunctionSummaryMap("l64a", 2353 Signature(ArgTypes{LongTy}, RetType{CharPtrTy}), 2354 Summary(NoEvalCall) 2355 .ArgConstraint(ArgumentCondition( 2356 0, WithinRange, Range(0, LongMax)))); 2357 2358 // int open(const char *path, int oflag, ...); 2359 addToFunctionSummaryMap( 2360 "open", Signature(ArgTypes{ConstCharPtrTy, IntTy}, RetType{IntTy}), 2361 Summary(NoEvalCall) 2362 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2363 GenericSuccessMsg) 2364 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2365 .ArgConstraint(NotNull(ArgNo(0)))); 2366 2367 // int openat(int fd, const char *path, int oflag, ...); 2368 addToFunctionSummaryMap( 2369 "openat", 2370 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy}, RetType{IntTy}), 2371 Summary(NoEvalCall) 2372 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2373 GenericSuccessMsg) 2374 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2375 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2376 .ArgConstraint(NotNull(ArgNo(1)))); 2377 2378 // int access(const char *pathname, int amode); 2379 addToFunctionSummaryMap( 2380 "access", Signature(ArgTypes{ConstCharPtrTy, IntTy}, RetType{IntTy}), 2381 Summary(NoEvalCall) 2382 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2383 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2384 .ArgConstraint(NotNull(ArgNo(0)))); 2385 2386 // int faccessat(int dirfd, const char *pathname, int mode, int flags); 2387 addToFunctionSummaryMap( 2388 "faccessat", 2389 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy, IntTy}, 2390 RetType{IntTy}), 2391 Summary(NoEvalCall) 2392 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2393 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2394 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2395 .ArgConstraint(NotNull(ArgNo(1)))); 2396 2397 // int dup(int fildes); 2398 addToFunctionSummaryMap( 2399 "dup", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2400 Summary(NoEvalCall) 2401 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2402 GenericSuccessMsg) 2403 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2404 .ArgConstraint( 2405 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2406 2407 // int dup2(int fildes1, int filedes2); 2408 addToFunctionSummaryMap( 2409 "dup2", Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}), 2410 Summary(NoEvalCall) 2411 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2412 GenericSuccessMsg) 2413 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2414 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 2415 .ArgConstraint( 2416 ArgumentCondition(1, WithinRange, Range(0, IntMax)))); 2417 2418 // int fdatasync(int fildes); 2419 addToFunctionSummaryMap( 2420 "fdatasync", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2421 Summary(NoEvalCall) 2422 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2423 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2424 .ArgConstraint( 2425 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2426 2427 // int fnmatch(const char *pattern, const char *string, int flags); 2428 addToFunctionSummaryMap( 2429 "fnmatch", 2430 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, IntTy}, 2431 RetType{IntTy}), 2432 Summary(NoEvalCall) 2433 .ArgConstraint(NotNull(ArgNo(0))) 2434 .ArgConstraint(NotNull(ArgNo(1)))); 2435 2436 // int fsync(int fildes); 2437 addToFunctionSummaryMap( 2438 "fsync", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2439 Summary(NoEvalCall) 2440 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2441 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2442 .ArgConstraint( 2443 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2444 2445 // int truncate(const char *path, off_t length); 2446 addToFunctionSummaryMap( 2447 "truncate", 2448 Signature(ArgTypes{ConstCharPtrTy, Off_tTy}, RetType{IntTy}), 2449 Summary(NoEvalCall) 2450 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2451 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2452 .ArgConstraint(NotNull(ArgNo(0)))); 2453 2454 // int symlink(const char *oldpath, const char *newpath); 2455 addToFunctionSummaryMap( 2456 "symlink", 2457 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{IntTy}), 2458 Summary(NoEvalCall) 2459 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2460 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2461 .ArgConstraint(NotNull(ArgNo(0))) 2462 .ArgConstraint(NotNull(ArgNo(1)))); 2463 2464 // int symlinkat(const char *oldpath, int newdirfd, const char *newpath); 2465 addToFunctionSummaryMap( 2466 "symlinkat", 2467 Signature(ArgTypes{ConstCharPtrTy, IntTy, ConstCharPtrTy}, 2468 RetType{IntTy}), 2469 Summary(NoEvalCall) 2470 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2471 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2472 .ArgConstraint(NotNull(ArgNo(0))) 2473 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(1))) 2474 .ArgConstraint(NotNull(ArgNo(2)))); 2475 2476 // int lockf(int fd, int cmd, off_t len); 2477 addToFunctionSummaryMap( 2478 "lockf", Signature(ArgTypes{IntTy, IntTy, Off_tTy}, RetType{IntTy}), 2479 Summary(NoEvalCall) 2480 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2481 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2482 .ArgConstraint( 2483 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2484 2485 std::optional<QualType> Mode_tTy = lookupTy("mode_t"); 2486 2487 // int creat(const char *pathname, mode_t mode); 2488 addToFunctionSummaryMap( 2489 "creat", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}), 2490 Summary(NoEvalCall) 2491 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2492 GenericSuccessMsg) 2493 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2494 .ArgConstraint(NotNull(ArgNo(0)))); 2495 2496 // unsigned int sleep(unsigned int seconds); 2497 addToFunctionSummaryMap( 2498 "sleep", Signature(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}), 2499 Summary(NoEvalCall) 2500 .ArgConstraint( 2501 ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax)))); 2502 2503 std::optional<QualType> DirTy = lookupTy("DIR"); 2504 std::optional<QualType> DirPtrTy = getPointerTy(DirTy); 2505 2506 // int dirfd(DIR *dirp); 2507 addToFunctionSummaryMap( 2508 "dirfd", Signature(ArgTypes{DirPtrTy}, RetType{IntTy}), 2509 Summary(NoEvalCall) 2510 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2511 GenericSuccessMsg) 2512 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2513 .ArgConstraint(NotNull(ArgNo(0)))); 2514 2515 // unsigned int alarm(unsigned int seconds); 2516 addToFunctionSummaryMap( 2517 "alarm", Signature(ArgTypes{UnsignedIntTy}, RetType{UnsignedIntTy}), 2518 Summary(NoEvalCall) 2519 .ArgConstraint( 2520 ArgumentCondition(0, WithinRange, Range(0, UnsignedIntMax)))); 2521 2522 // int closedir(DIR *dir); 2523 addToFunctionSummaryMap( 2524 "closedir", Signature(ArgTypes{DirPtrTy}, RetType{IntTy}), 2525 Summary(NoEvalCall) 2526 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2527 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2528 .ArgConstraint(NotNull(ArgNo(0)))); 2529 2530 // char *strdup(const char *s); 2531 addToFunctionSummaryMap( 2532 "strdup", Signature(ArgTypes{ConstCharPtrTy}, RetType{CharPtrTy}), 2533 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2534 2535 // char *strndup(const char *s, size_t n); 2536 addToFunctionSummaryMap( 2537 "strndup", 2538 Signature(ArgTypes{ConstCharPtrTy, SizeTy}, RetType{CharPtrTy}), 2539 Summary(NoEvalCall) 2540 .ArgConstraint(NotNull(ArgNo(0))) 2541 .ArgConstraint( 2542 ArgumentCondition(1, WithinRange, Range(0, SizeMax)))); 2543 2544 // wchar_t *wcsdup(const wchar_t *s); 2545 addToFunctionSummaryMap( 2546 "wcsdup", Signature(ArgTypes{ConstWchar_tPtrTy}, RetType{Wchar_tPtrTy}), 2547 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2548 2549 // int mkstemp(char *template); 2550 addToFunctionSummaryMap( 2551 "mkstemp", Signature(ArgTypes{CharPtrTy}, RetType{IntTy}), 2552 Summary(NoEvalCall) 2553 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 2554 GenericSuccessMsg) 2555 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2556 .ArgConstraint(NotNull(ArgNo(0)))); 2557 2558 // char *mkdtemp(char *template); 2559 addToFunctionSummaryMap( 2560 "mkdtemp", Signature(ArgTypes{CharPtrTy}, RetType{CharPtrTy}), 2561 Summary(NoEvalCall) 2562 .Case({ReturnValueCondition(BO_EQ, ArgNo(0))}, 2563 ErrnoMustNotBeChecked, GenericSuccessMsg) 2564 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2565 .ArgConstraint(NotNull(ArgNo(0)))); 2566 2567 // char *getcwd(char *buf, size_t size); 2568 addToFunctionSummaryMap( 2569 "getcwd", Signature(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}), 2570 Summary(NoEvalCall) 2571 .Case({ArgumentCondition(1, WithinRange, Range(1, SizeMax)), 2572 ReturnValueCondition(BO_EQ, ArgNo(0))}, 2573 ErrnoMustNotBeChecked, GenericSuccessMsg) 2574 .Case({ArgumentCondition(1, WithinRange, SingleValue(0)), 2575 IsNull(Ret)}, 2576 ErrnoNEZeroIrrelevant, "Assuming that argument 'size' is 0") 2577 .Case({ArgumentCondition(1, WithinRange, Range(1, SizeMax)), 2578 IsNull(Ret)}, 2579 ErrnoNEZeroIrrelevant, GenericFailureMsg) 2580 .ArgConstraint(NotNull(ArgNo(0))) 2581 .ArgConstraint( 2582 BufferSize(/*Buffer*/ ArgNo(0), /*BufSize*/ ArgNo(1))) 2583 .ArgConstraint( 2584 ArgumentCondition(1, WithinRange, Range(0, SizeMax)))); 2585 2586 // int mkdir(const char *pathname, mode_t mode); 2587 addToFunctionSummaryMap( 2588 "mkdir", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}), 2589 Summary(NoEvalCall) 2590 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2591 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2592 .ArgConstraint(NotNull(ArgNo(0)))); 2593 2594 // int mkdirat(int dirfd, const char *pathname, mode_t mode); 2595 addToFunctionSummaryMap( 2596 "mkdirat", 2597 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy}, RetType{IntTy}), 2598 Summary(NoEvalCall) 2599 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2600 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2601 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2602 .ArgConstraint(NotNull(ArgNo(1)))); 2603 2604 std::optional<QualType> Dev_tTy = lookupTy("dev_t"); 2605 2606 // int mknod(const char *pathname, mode_t mode, dev_t dev); 2607 addToFunctionSummaryMap( 2608 "mknod", 2609 Signature(ArgTypes{ConstCharPtrTy, Mode_tTy, Dev_tTy}, RetType{IntTy}), 2610 Summary(NoEvalCall) 2611 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2612 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2613 .ArgConstraint(NotNull(ArgNo(0)))); 2614 2615 // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev); 2616 addToFunctionSummaryMap( 2617 "mknodat", 2618 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, Dev_tTy}, 2619 RetType{IntTy}), 2620 Summary(NoEvalCall) 2621 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2622 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2623 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2624 .ArgConstraint(NotNull(ArgNo(1)))); 2625 2626 // int chmod(const char *path, mode_t mode); 2627 addToFunctionSummaryMap( 2628 "chmod", Signature(ArgTypes{ConstCharPtrTy, Mode_tTy}, RetType{IntTy}), 2629 Summary(NoEvalCall) 2630 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2631 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2632 .ArgConstraint(NotNull(ArgNo(0)))); 2633 2634 // int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags); 2635 addToFunctionSummaryMap( 2636 "fchmodat", 2637 Signature(ArgTypes{IntTy, ConstCharPtrTy, Mode_tTy, IntTy}, 2638 RetType{IntTy}), 2639 Summary(NoEvalCall) 2640 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2641 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2642 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2643 .ArgConstraint(NotNull(ArgNo(1)))); 2644 2645 // int fchmod(int fildes, mode_t mode); 2646 addToFunctionSummaryMap( 2647 "fchmod", Signature(ArgTypes{IntTy, Mode_tTy}, RetType{IntTy}), 2648 Summary(NoEvalCall) 2649 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2650 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2651 .ArgConstraint( 2652 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2653 2654 std::optional<QualType> Uid_tTy = lookupTy("uid_t"); 2655 std::optional<QualType> Gid_tTy = lookupTy("gid_t"); 2656 2657 // int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, 2658 // int flags); 2659 addToFunctionSummaryMap( 2660 "fchownat", 2661 Signature(ArgTypes{IntTy, ConstCharPtrTy, Uid_tTy, Gid_tTy, IntTy}, 2662 RetType{IntTy}), 2663 Summary(NoEvalCall) 2664 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2665 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2666 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2667 .ArgConstraint(NotNull(ArgNo(1)))); 2668 2669 // int chown(const char *path, uid_t owner, gid_t group); 2670 addToFunctionSummaryMap( 2671 "chown", 2672 Signature(ArgTypes{ConstCharPtrTy, Uid_tTy, Gid_tTy}, RetType{IntTy}), 2673 Summary(NoEvalCall) 2674 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2675 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2676 .ArgConstraint(NotNull(ArgNo(0)))); 2677 2678 // int lchown(const char *path, uid_t owner, gid_t group); 2679 addToFunctionSummaryMap( 2680 "lchown", 2681 Signature(ArgTypes{ConstCharPtrTy, Uid_tTy, Gid_tTy}, RetType{IntTy}), 2682 Summary(NoEvalCall) 2683 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2684 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2685 .ArgConstraint(NotNull(ArgNo(0)))); 2686 2687 // int fchown(int fildes, uid_t owner, gid_t group); 2688 addToFunctionSummaryMap( 2689 "fchown", Signature(ArgTypes{IntTy, Uid_tTy, Gid_tTy}, RetType{IntTy}), 2690 Summary(NoEvalCall) 2691 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2692 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2693 .ArgConstraint( 2694 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2695 2696 // int rmdir(const char *pathname); 2697 addToFunctionSummaryMap( 2698 "rmdir", Signature(ArgTypes{ConstCharPtrTy}, RetType{IntTy}), 2699 Summary(NoEvalCall) 2700 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2701 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2702 .ArgConstraint(NotNull(ArgNo(0)))); 2703 2704 // int chdir(const char *path); 2705 addToFunctionSummaryMap( 2706 "chdir", Signature(ArgTypes{ConstCharPtrTy}, RetType{IntTy}), 2707 Summary(NoEvalCall) 2708 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2709 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2710 .ArgConstraint(NotNull(ArgNo(0)))); 2711 2712 // int link(const char *oldpath, const char *newpath); 2713 addToFunctionSummaryMap( 2714 "link", 2715 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{IntTy}), 2716 Summary(NoEvalCall) 2717 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2718 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2719 .ArgConstraint(NotNull(ArgNo(0))) 2720 .ArgConstraint(NotNull(ArgNo(1)))); 2721 2722 // int linkat(int fd1, const char *path1, int fd2, const char *path2, 2723 // int flag); 2724 addToFunctionSummaryMap( 2725 "linkat", 2726 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy, ConstCharPtrTy, IntTy}, 2727 RetType{IntTy}), 2728 Summary(NoEvalCall) 2729 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2730 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2731 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2732 .ArgConstraint(NotNull(ArgNo(1))) 2733 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(2))) 2734 .ArgConstraint(NotNull(ArgNo(3)))); 2735 2736 // int unlink(const char *pathname); 2737 addToFunctionSummaryMap( 2738 "unlink", Signature(ArgTypes{ConstCharPtrTy}, RetType{IntTy}), 2739 Summary(NoEvalCall) 2740 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2741 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2742 .ArgConstraint(NotNull(ArgNo(0)))); 2743 2744 // int unlinkat(int fd, const char *path, int flag); 2745 addToFunctionSummaryMap( 2746 "unlinkat", 2747 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy}, RetType{IntTy}), 2748 Summary(NoEvalCall) 2749 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2750 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2751 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2752 .ArgConstraint(NotNull(ArgNo(1)))); 2753 2754 std::optional<QualType> StructStatTy = lookupTy("stat"); 2755 std::optional<QualType> StructStatPtrTy = getPointerTy(StructStatTy); 2756 std::optional<QualType> StructStatPtrRestrictTy = 2757 getRestrictTy(StructStatPtrTy); 2758 2759 // int fstat(int fd, struct stat *statbuf); 2760 addToFunctionSummaryMap( 2761 "fstat", Signature(ArgTypes{IntTy, StructStatPtrTy}, RetType{IntTy}), 2762 Summary(NoEvalCall) 2763 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2764 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2765 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 2766 .ArgConstraint(NotNull(ArgNo(1)))); 2767 2768 // int stat(const char *restrict path, struct stat *restrict buf); 2769 addToFunctionSummaryMap( 2770 "stat", 2771 Signature(ArgTypes{ConstCharPtrRestrictTy, StructStatPtrRestrictTy}, 2772 RetType{IntTy}), 2773 Summary(NoEvalCall) 2774 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2775 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2776 .ArgConstraint(NotNull(ArgNo(0))) 2777 .ArgConstraint(NotNull(ArgNo(1)))); 2778 2779 // int lstat(const char *restrict path, struct stat *restrict buf); 2780 addToFunctionSummaryMap( 2781 "lstat", 2782 Signature(ArgTypes{ConstCharPtrRestrictTy, StructStatPtrRestrictTy}, 2783 RetType{IntTy}), 2784 Summary(NoEvalCall) 2785 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2786 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2787 .ArgConstraint(NotNull(ArgNo(0))) 2788 .ArgConstraint(NotNull(ArgNo(1)))); 2789 2790 // int fstatat(int fd, const char *restrict path, 2791 // struct stat *restrict buf, int flag); 2792 addToFunctionSummaryMap( 2793 "fstatat", 2794 Signature(ArgTypes{IntTy, ConstCharPtrRestrictTy, 2795 StructStatPtrRestrictTy, IntTy}, 2796 RetType{IntTy}), 2797 Summary(NoEvalCall) 2798 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2799 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2800 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2801 .ArgConstraint(NotNull(ArgNo(1))) 2802 .ArgConstraint(NotNull(ArgNo(2)))); 2803 2804 // DIR *opendir(const char *name); 2805 addToFunctionSummaryMap( 2806 "opendir", Signature(ArgTypes{ConstCharPtrTy}, RetType{DirPtrTy}), 2807 Summary(NoEvalCall) 2808 .Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg) 2809 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2810 .ArgConstraint(NotNull(ArgNo(0)))); 2811 2812 // DIR *fdopendir(int fd); 2813 addToFunctionSummaryMap( 2814 "fdopendir", Signature(ArgTypes{IntTy}, RetType{DirPtrTy}), 2815 Summary(NoEvalCall) 2816 .Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg) 2817 .Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2818 .ArgConstraint( 2819 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2820 2821 // int isatty(int fildes); 2822 addToFunctionSummaryMap( 2823 "isatty", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2824 Summary(NoEvalCall) 2825 .Case({ReturnValueCondition(WithinRange, Range(0, 1))}, 2826 ErrnoIrrelevant) 2827 .ArgConstraint( 2828 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2829 2830 // FILE *popen(const char *command, const char *type); 2831 // FIXME: Improve for errno modeling. 2832 addToFunctionSummaryMap( 2833 "popen", 2834 Signature(ArgTypes{ConstCharPtrTy, ConstCharPtrTy}, RetType{FilePtrTy}), 2835 Summary(NoEvalCall) 2836 .ArgConstraint(NotNull(ArgNo(0))) 2837 .ArgConstraint(NotNull(ArgNo(1)))); 2838 2839 // int pclose(FILE *stream); 2840 // FIXME: Improve for errno modeling. 2841 addToFunctionSummaryMap( 2842 "pclose", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}), 2843 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2844 2845 // int close(int fildes); 2846 addToFunctionSummaryMap( 2847 "close", Signature(ArgTypes{IntTy}, RetType{IntTy}), 2848 Summary(NoEvalCall) 2849 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2850 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2851 .ArgConstraint( 2852 ArgumentCondition(0, WithinRange, Range(-1, IntMax)))); 2853 2854 // long fpathconf(int fildes, int name); 2855 addToFunctionSummaryMap("fpathconf", 2856 Signature(ArgTypes{IntTy, IntTy}, RetType{LongTy}), 2857 Summary(NoEvalCall) 2858 .ArgConstraint(ArgumentCondition( 2859 0, WithinRange, Range(0, IntMax)))); 2860 2861 // long pathconf(const char *path, int name); 2862 addToFunctionSummaryMap( 2863 "pathconf", Signature(ArgTypes{ConstCharPtrTy, IntTy}, RetType{LongTy}), 2864 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2865 2866 // void rewinddir(DIR *dir); 2867 addToFunctionSummaryMap( 2868 "rewinddir", Signature(ArgTypes{DirPtrTy}, RetType{VoidTy}), 2869 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2870 2871 // void seekdir(DIR *dirp, long loc); 2872 addToFunctionSummaryMap( 2873 "seekdir", Signature(ArgTypes{DirPtrTy, LongTy}, RetType{VoidTy}), 2874 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2875 2876 // int rand_r(unsigned int *seedp); 2877 addToFunctionSummaryMap( 2878 "rand_r", Signature(ArgTypes{UnsignedIntPtrTy}, RetType{IntTy}), 2879 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2880 2881 // void *mmap(void *addr, size_t length, int prot, int flags, int fd, 2882 // off_t offset); 2883 // FIXME: Improve for errno modeling. 2884 addToFunctionSummaryMap( 2885 "mmap", 2886 Signature(ArgTypes{VoidPtrTy, SizeTy, IntTy, IntTy, IntTy, Off_tTy}, 2887 RetType{VoidPtrTy}), 2888 Summary(NoEvalCall) 2889 .ArgConstraint(ArgumentCondition(1, WithinRange, Range(1, SizeMax))) 2890 .ArgConstraint( 2891 ArgumentCondition(4, WithinRange, Range(-1, IntMax)))); 2892 2893 std::optional<QualType> Off64_tTy = lookupTy("off64_t"); 2894 // void *mmap64(void *addr, size_t length, int prot, int flags, int fd, 2895 // off64_t offset); 2896 // FIXME: Improve for errno modeling. 2897 addToFunctionSummaryMap( 2898 "mmap64", 2899 Signature(ArgTypes{VoidPtrTy, SizeTy, IntTy, IntTy, IntTy, Off64_tTy}, 2900 RetType{VoidPtrTy}), 2901 Summary(NoEvalCall) 2902 .ArgConstraint(ArgumentCondition(1, WithinRange, Range(1, SizeMax))) 2903 .ArgConstraint( 2904 ArgumentCondition(4, WithinRange, Range(-1, IntMax)))); 2905 2906 // int pipe(int fildes[2]); 2907 addToFunctionSummaryMap( 2908 "pipe", Signature(ArgTypes{IntPtrTy}, RetType{IntTy}), 2909 Summary(NoEvalCall) 2910 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2911 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2912 .ArgConstraint(NotNull(ArgNo(0)))); 2913 2914 // off_t lseek(int fildes, off_t offset, int whence); 2915 // In the first case we can not tell for sure if it failed or not. 2916 // A return value different from of the expected offset (that is unknown 2917 // here) may indicate failure. For this reason we do not enforce the errno 2918 // check (can cause false positive). 2919 addToFunctionSummaryMap( 2920 "lseek", Signature(ArgTypes{IntTy, Off_tTy, IntTy}, RetType{Off_tTy}), 2921 Summary(NoEvalCall) 2922 .Case(ReturnsNonnegative, ErrnoIrrelevant) 2923 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2924 .ArgConstraint( 2925 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 2926 2927 // ssize_t readlink(const char *restrict path, char *restrict buf, 2928 // size_t bufsize); 2929 addToFunctionSummaryMap( 2930 "readlink", 2931 Signature(ArgTypes{ConstCharPtrRestrictTy, CharPtrRestrictTy, SizeTy}, 2932 RetType{Ssize_tTy}), 2933 Summary(NoEvalCall) 2934 .Case({ArgumentCondition(2, WithinRange, Range(1, IntMax)), 2935 ReturnValueCondition(LessThanOrEq, ArgNo(2)), 2936 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 2937 ErrnoMustNotBeChecked, GenericSuccessMsg) 2938 .Case({ArgumentCondition(2, WithinRange, SingleValue(0)), 2939 ReturnValueCondition(WithinRange, SingleValue(0))}, 2940 ErrnoMustNotBeChecked, 2941 "Assuming that argument 'bufsize' is 0") 2942 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2943 .ArgConstraint(NotNull(ArgNo(0))) 2944 .ArgConstraint(NotNull(ArgNo(1))) 2945 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), 2946 /*BufSize=*/ArgNo(2))) 2947 .ArgConstraint( 2948 ArgumentCondition(2, WithinRange, Range(0, SizeMax)))); 2949 2950 // ssize_t readlinkat(int fd, const char *restrict path, 2951 // char *restrict buf, size_t bufsize); 2952 addToFunctionSummaryMap( 2953 "readlinkat", 2954 Signature( 2955 ArgTypes{IntTy, ConstCharPtrRestrictTy, CharPtrRestrictTy, SizeTy}, 2956 RetType{Ssize_tTy}), 2957 Summary(NoEvalCall) 2958 .Case({ArgumentCondition(3, WithinRange, Range(1, IntMax)), 2959 ReturnValueCondition(LessThanOrEq, ArgNo(3)), 2960 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 2961 ErrnoMustNotBeChecked, GenericSuccessMsg) 2962 .Case({ArgumentCondition(3, WithinRange, SingleValue(0)), 2963 ReturnValueCondition(WithinRange, SingleValue(0))}, 2964 ErrnoMustNotBeChecked, 2965 "Assuming that argument 'bufsize' is 0") 2966 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2967 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2968 .ArgConstraint(NotNull(ArgNo(1))) 2969 .ArgConstraint(NotNull(ArgNo(2))) 2970 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(2), 2971 /*BufSize=*/ArgNo(3))) 2972 .ArgConstraint( 2973 ArgumentCondition(3, WithinRange, Range(0, SizeMax)))); 2974 2975 // int renameat(int olddirfd, const char *oldpath, int newdirfd, const char 2976 // *newpath); 2977 addToFunctionSummaryMap( 2978 "renameat", 2979 Signature(ArgTypes{IntTy, ConstCharPtrTy, IntTy, ConstCharPtrTy}, 2980 RetType{IntTy}), 2981 Summary(NoEvalCall) 2982 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 2983 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 2984 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(0))) 2985 .ArgConstraint(NotNull(ArgNo(1))) 2986 .ArgConstraint(ValidFileDescriptorOrAtFdcwd(ArgNo(2))) 2987 .ArgConstraint(NotNull(ArgNo(3)))); 2988 2989 // char *realpath(const char *restrict file_name, 2990 // char *restrict resolved_name); 2991 // FIXME: Improve for errno modeling. 2992 addToFunctionSummaryMap( 2993 "realpath", 2994 Signature(ArgTypes{ConstCharPtrRestrictTy, CharPtrRestrictTy}, 2995 RetType{CharPtrTy}), 2996 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 2997 2998 QualType CharPtrConstPtr = getPointerTy(getConstTy(CharPtrTy)); 2999 3000 // int execv(const char *path, char *const argv[]); 3001 addToFunctionSummaryMap( 3002 "execv", 3003 Signature(ArgTypes{ConstCharPtrTy, CharPtrConstPtr}, RetType{IntTy}), 3004 Summary(NoEvalCall) 3005 .Case(ReturnsMinusOne, ErrnoIrrelevant) 3006 .ArgConstraint(NotNull(ArgNo(0)))); 3007 3008 // int execvp(const char *file, char *const argv[]); 3009 addToFunctionSummaryMap( 3010 "execvp", 3011 Signature(ArgTypes{ConstCharPtrTy, CharPtrConstPtr}, RetType{IntTy}), 3012 Summary(NoEvalCall) 3013 .Case(ReturnsMinusOne, ErrnoIrrelevant) 3014 .ArgConstraint(NotNull(ArgNo(0)))); 3015 3016 // int getopt(int argc, char * const argv[], const char *optstring); 3017 addToFunctionSummaryMap( 3018 "getopt", 3019 Signature(ArgTypes{IntTy, CharPtrConstPtr, ConstCharPtrTy}, 3020 RetType{IntTy}), 3021 Summary(NoEvalCall) 3022 .Case({ReturnValueCondition(WithinRange, Range(-1, UCharRangeMax))}, 3023 ErrnoIrrelevant) 3024 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3025 .ArgConstraint(NotNull(ArgNo(1))) 3026 .ArgConstraint(NotNull(ArgNo(2)))); 3027 3028 std::optional<QualType> StructSockaddrTy = lookupTy("sockaddr"); 3029 std::optional<QualType> StructSockaddrPtrTy = 3030 getPointerTy(StructSockaddrTy); 3031 std::optional<QualType> ConstStructSockaddrPtrTy = 3032 getPointerTy(getConstTy(StructSockaddrTy)); 3033 std::optional<QualType> StructSockaddrPtrRestrictTy = 3034 getRestrictTy(StructSockaddrPtrTy); 3035 std::optional<QualType> ConstStructSockaddrPtrRestrictTy = 3036 getRestrictTy(ConstStructSockaddrPtrTy); 3037 std::optional<QualType> Socklen_tTy = lookupTy("socklen_t"); 3038 std::optional<QualType> Socklen_tPtrTy = getPointerTy(Socklen_tTy); 3039 std::optional<QualType> Socklen_tPtrRestrictTy = 3040 getRestrictTy(Socklen_tPtrTy); 3041 std::optional<RangeInt> Socklen_tMax = getMaxValue(Socklen_tTy); 3042 3043 // In 'socket.h' of some libc implementations with C99, sockaddr parameter 3044 // is a transparent union of the underlying sockaddr_ family of pointers 3045 // instead of being a pointer to struct sockaddr. In these cases, the 3046 // standardized signature will not match, thus we try to match with another 3047 // signature that has the joker Irrelevant type. We also remove those 3048 // constraints which require pointer types for the sockaddr param. 3049 3050 // int socket(int domain, int type, int protocol); 3051 addToFunctionSummaryMap( 3052 "socket", Signature(ArgTypes{IntTy, IntTy, IntTy}, RetType{IntTy}), 3053 Summary(NoEvalCall) 3054 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 3055 GenericSuccessMsg) 3056 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)); 3057 3058 auto Accept = 3059 Summary(NoEvalCall) 3060 .Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked, 3061 GenericSuccessMsg) 3062 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3063 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))); 3064 if (!addToFunctionSummaryMap( 3065 "accept", 3066 // int accept(int socket, struct sockaddr *restrict address, 3067 // socklen_t *restrict address_len); 3068 Signature(ArgTypes{IntTy, StructSockaddrPtrRestrictTy, 3069 Socklen_tPtrRestrictTy}, 3070 RetType{IntTy}), 3071 Accept)) 3072 addToFunctionSummaryMap( 3073 "accept", 3074 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrRestrictTy}, 3075 RetType{IntTy}), 3076 Accept); 3077 3078 // int bind(int socket, const struct sockaddr *address, socklen_t 3079 // address_len); 3080 if (!addToFunctionSummaryMap( 3081 "bind", 3082 Signature(ArgTypes{IntTy, ConstStructSockaddrPtrTy, Socklen_tTy}, 3083 RetType{IntTy}), 3084 Summary(NoEvalCall) 3085 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3086 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3087 .ArgConstraint( 3088 ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3089 .ArgConstraint(NotNull(ArgNo(1))) 3090 .ArgConstraint( 3091 BufferSize(/*Buffer=*/ArgNo(1), /*BufSize=*/ArgNo(2))) 3092 .ArgConstraint( 3093 ArgumentCondition(2, WithinRange, Range(0, Socklen_tMax))))) 3094 // Do not add constraints on sockaddr. 3095 addToFunctionSummaryMap( 3096 "bind", 3097 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tTy}, RetType{IntTy}), 3098 Summary(NoEvalCall) 3099 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3100 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3101 .ArgConstraint( 3102 ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3103 .ArgConstraint( 3104 ArgumentCondition(2, WithinRange, Range(0, Socklen_tMax)))); 3105 3106 // int getpeername(int socket, struct sockaddr *restrict address, 3107 // socklen_t *restrict address_len); 3108 if (!addToFunctionSummaryMap( 3109 "getpeername", 3110 Signature(ArgTypes{IntTy, StructSockaddrPtrRestrictTy, 3111 Socklen_tPtrRestrictTy}, 3112 RetType{IntTy}), 3113 Summary(NoEvalCall) 3114 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3115 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3116 .ArgConstraint( 3117 ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3118 .ArgConstraint(NotNull(ArgNo(1))) 3119 .ArgConstraint(NotNull(ArgNo(2))))) 3120 addToFunctionSummaryMap( 3121 "getpeername", 3122 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrRestrictTy}, 3123 RetType{IntTy}), 3124 Summary(NoEvalCall) 3125 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3126 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3127 .ArgConstraint( 3128 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3129 3130 // int getsockname(int socket, struct sockaddr *restrict address, 3131 // socklen_t *restrict address_len); 3132 if (!addToFunctionSummaryMap( 3133 "getsockname", 3134 Signature(ArgTypes{IntTy, StructSockaddrPtrRestrictTy, 3135 Socklen_tPtrRestrictTy}, 3136 RetType{IntTy}), 3137 Summary(NoEvalCall) 3138 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3139 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3140 .ArgConstraint( 3141 ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3142 .ArgConstraint(NotNull(ArgNo(1))) 3143 .ArgConstraint(NotNull(ArgNo(2))))) 3144 addToFunctionSummaryMap( 3145 "getsockname", 3146 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tPtrRestrictTy}, 3147 RetType{IntTy}), 3148 Summary(NoEvalCall) 3149 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3150 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3151 .ArgConstraint( 3152 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3153 3154 // int connect(int socket, const struct sockaddr *address, socklen_t 3155 // address_len); 3156 if (!addToFunctionSummaryMap( 3157 "connect", 3158 Signature(ArgTypes{IntTy, ConstStructSockaddrPtrTy, Socklen_tTy}, 3159 RetType{IntTy}), 3160 Summary(NoEvalCall) 3161 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3162 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3163 .ArgConstraint( 3164 ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3165 .ArgConstraint(NotNull(ArgNo(1))))) 3166 addToFunctionSummaryMap( 3167 "connect", 3168 Signature(ArgTypes{IntTy, Irrelevant, Socklen_tTy}, RetType{IntTy}), 3169 Summary(NoEvalCall) 3170 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3171 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3172 .ArgConstraint( 3173 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3174 3175 auto Recvfrom = 3176 Summary(NoEvalCall) 3177 .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)), 3178 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 3179 ErrnoMustNotBeChecked, GenericSuccessMsg) 3180 .Case({ReturnValueCondition(WithinRange, SingleValue(0)), 3181 ArgumentCondition(2, WithinRange, SingleValue(0))}, 3182 ErrnoMustNotBeChecked, GenericSuccessMsg) 3183 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3184 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3185 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), 3186 /*BufSize=*/ArgNo(2))); 3187 if (!addToFunctionSummaryMap( 3188 "recvfrom", 3189 // ssize_t recvfrom(int socket, void *restrict buffer, 3190 // size_t length, 3191 // int flags, struct sockaddr *restrict address, 3192 // socklen_t *restrict address_len); 3193 Signature(ArgTypes{IntTy, VoidPtrRestrictTy, SizeTy, IntTy, 3194 StructSockaddrPtrRestrictTy, 3195 Socklen_tPtrRestrictTy}, 3196 RetType{Ssize_tTy}), 3197 Recvfrom)) 3198 addToFunctionSummaryMap( 3199 "recvfrom", 3200 Signature(ArgTypes{IntTy, VoidPtrRestrictTy, SizeTy, IntTy, 3201 Irrelevant, Socklen_tPtrRestrictTy}, 3202 RetType{Ssize_tTy}), 3203 Recvfrom); 3204 3205 auto Sendto = 3206 Summary(NoEvalCall) 3207 .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)), 3208 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 3209 ErrnoMustNotBeChecked, GenericSuccessMsg) 3210 .Case({ReturnValueCondition(WithinRange, SingleValue(0)), 3211 ArgumentCondition(2, WithinRange, SingleValue(0))}, 3212 ErrnoMustNotBeChecked, GenericSuccessMsg) 3213 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3214 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3215 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), 3216 /*BufSize=*/ArgNo(2))); 3217 if (!addToFunctionSummaryMap( 3218 "sendto", 3219 // ssize_t sendto(int socket, const void *message, size_t length, 3220 // int flags, const struct sockaddr *dest_addr, 3221 // socklen_t dest_len); 3222 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy, IntTy, 3223 ConstStructSockaddrPtrTy, Socklen_tTy}, 3224 RetType{Ssize_tTy}), 3225 Sendto)) 3226 addToFunctionSummaryMap( 3227 "sendto", 3228 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy, IntTy, Irrelevant, 3229 Socklen_tTy}, 3230 RetType{Ssize_tTy}), 3231 Sendto); 3232 3233 // int listen(int sockfd, int backlog); 3234 addToFunctionSummaryMap( 3235 "listen", Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}), 3236 Summary(NoEvalCall) 3237 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3238 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3239 .ArgConstraint( 3240 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3241 3242 // ssize_t recv(int sockfd, void *buf, size_t len, int flags); 3243 addToFunctionSummaryMap( 3244 "recv", 3245 Signature(ArgTypes{IntTy, VoidPtrTy, SizeTy, IntTy}, 3246 RetType{Ssize_tTy}), 3247 Summary(NoEvalCall) 3248 .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)), 3249 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 3250 ErrnoMustNotBeChecked, GenericSuccessMsg) 3251 .Case({ReturnValueCondition(WithinRange, SingleValue(0)), 3252 ArgumentCondition(2, WithinRange, SingleValue(0))}, 3253 ErrnoMustNotBeChecked, GenericSuccessMsg) 3254 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3255 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3256 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), 3257 /*BufSize=*/ArgNo(2)))); 3258 3259 std::optional<QualType> StructMsghdrTy = lookupTy("msghdr"); 3260 std::optional<QualType> StructMsghdrPtrTy = getPointerTy(StructMsghdrTy); 3261 std::optional<QualType> ConstStructMsghdrPtrTy = 3262 getPointerTy(getConstTy(StructMsghdrTy)); 3263 3264 // ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags); 3265 addToFunctionSummaryMap( 3266 "recvmsg", 3267 Signature(ArgTypes{IntTy, StructMsghdrPtrTy, IntTy}, 3268 RetType{Ssize_tTy}), 3269 Summary(NoEvalCall) 3270 .Case({ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 3271 ErrnoMustNotBeChecked, GenericSuccessMsg) 3272 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3273 .ArgConstraint( 3274 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3275 3276 // ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags); 3277 addToFunctionSummaryMap( 3278 "sendmsg", 3279 Signature(ArgTypes{IntTy, ConstStructMsghdrPtrTy, IntTy}, 3280 RetType{Ssize_tTy}), 3281 Summary(NoEvalCall) 3282 .Case({ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 3283 ErrnoMustNotBeChecked, GenericSuccessMsg) 3284 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3285 .ArgConstraint( 3286 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3287 3288 // int setsockopt(int socket, int level, int option_name, 3289 // const void *option_value, socklen_t option_len); 3290 addToFunctionSummaryMap( 3291 "setsockopt", 3292 Signature(ArgTypes{IntTy, IntTy, IntTy, ConstVoidPtrTy, Socklen_tTy}, 3293 RetType{IntTy}), 3294 Summary(NoEvalCall) 3295 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3296 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3297 .ArgConstraint(NotNull(ArgNo(3))) 3298 .ArgConstraint( 3299 BufferSize(/*Buffer=*/ArgNo(3), /*BufSize=*/ArgNo(4))) 3300 .ArgConstraint( 3301 ArgumentCondition(4, WithinRange, Range(0, Socklen_tMax)))); 3302 3303 // int getsockopt(int socket, int level, int option_name, 3304 // void *restrict option_value, 3305 // socklen_t *restrict option_len); 3306 addToFunctionSummaryMap( 3307 "getsockopt", 3308 Signature(ArgTypes{IntTy, IntTy, IntTy, VoidPtrRestrictTy, 3309 Socklen_tPtrRestrictTy}, 3310 RetType{IntTy}), 3311 Summary(NoEvalCall) 3312 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3313 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3314 .ArgConstraint(NotNull(ArgNo(3))) 3315 .ArgConstraint(NotNull(ArgNo(4)))); 3316 3317 // ssize_t send(int sockfd, const void *buf, size_t len, int flags); 3318 addToFunctionSummaryMap( 3319 "send", 3320 Signature(ArgTypes{IntTy, ConstVoidPtrTy, SizeTy, IntTy}, 3321 RetType{Ssize_tTy}), 3322 Summary(NoEvalCall) 3323 .Case({ReturnValueCondition(LessThanOrEq, ArgNo(2)), 3324 ReturnValueCondition(WithinRange, Range(1, Ssize_tMax))}, 3325 ErrnoMustNotBeChecked, GenericSuccessMsg) 3326 .Case({ReturnValueCondition(WithinRange, SingleValue(0)), 3327 ArgumentCondition(2, WithinRange, SingleValue(0))}, 3328 ErrnoMustNotBeChecked, GenericSuccessMsg) 3329 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3330 .ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax))) 3331 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), 3332 /*BufSize=*/ArgNo(2)))); 3333 3334 // int socketpair(int domain, int type, int protocol, int sv[2]); 3335 addToFunctionSummaryMap( 3336 "socketpair", 3337 Signature(ArgTypes{IntTy, IntTy, IntTy, IntPtrTy}, RetType{IntTy}), 3338 Summary(NoEvalCall) 3339 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3340 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3341 .ArgConstraint(NotNull(ArgNo(3)))); 3342 3343 // int shutdown(int socket, int how); 3344 addToFunctionSummaryMap( 3345 "shutdown", Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}), 3346 Summary(NoEvalCall) 3347 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3348 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3349 .ArgConstraint( 3350 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3351 3352 // int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, 3353 // char *restrict node, socklen_t nodelen, 3354 // char *restrict service, 3355 // socklen_t servicelen, int flags); 3356 // 3357 // This is defined in netdb.h. And contrary to 'socket.h', the sockaddr 3358 // parameter is never handled as a transparent union in netdb.h 3359 addToFunctionSummaryMap( 3360 "getnameinfo", 3361 Signature(ArgTypes{ConstStructSockaddrPtrRestrictTy, Socklen_tTy, 3362 CharPtrRestrictTy, Socklen_tTy, CharPtrRestrictTy, 3363 Socklen_tTy, IntTy}, 3364 RetType{IntTy}), 3365 Summary(NoEvalCall) 3366 .ArgConstraint( 3367 BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1))) 3368 .ArgConstraint( 3369 ArgumentCondition(1, WithinRange, Range(0, Socklen_tMax))) 3370 .ArgConstraint( 3371 BufferSize(/*Buffer=*/ArgNo(2), /*BufSize=*/ArgNo(3))) 3372 .ArgConstraint( 3373 ArgumentCondition(3, WithinRange, Range(0, Socklen_tMax))) 3374 .ArgConstraint( 3375 BufferSize(/*Buffer=*/ArgNo(4), /*BufSize=*/ArgNo(5))) 3376 .ArgConstraint( 3377 ArgumentCondition(5, WithinRange, Range(0, Socklen_tMax)))); 3378 3379 std::optional<QualType> StructUtimbufTy = lookupTy("utimbuf"); 3380 std::optional<QualType> StructUtimbufPtrTy = getPointerTy(StructUtimbufTy); 3381 3382 // int utime(const char *filename, struct utimbuf *buf); 3383 addToFunctionSummaryMap( 3384 "utime", 3385 Signature(ArgTypes{ConstCharPtrTy, StructUtimbufPtrTy}, RetType{IntTy}), 3386 Summary(NoEvalCall) 3387 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3388 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3389 .ArgConstraint(NotNull(ArgNo(0)))); 3390 3391 std::optional<QualType> StructTimespecTy = lookupTy("timespec"); 3392 std::optional<QualType> StructTimespecPtrTy = 3393 getPointerTy(StructTimespecTy); 3394 std::optional<QualType> ConstStructTimespecPtrTy = 3395 getPointerTy(getConstTy(StructTimespecTy)); 3396 3397 // int futimens(int fd, const struct timespec times[2]); 3398 addToFunctionSummaryMap( 3399 "futimens", 3400 Signature(ArgTypes{IntTy, ConstStructTimespecPtrTy}, RetType{IntTy}), 3401 Summary(NoEvalCall) 3402 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3403 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3404 .ArgConstraint( 3405 ArgumentCondition(0, WithinRange, Range(0, IntMax)))); 3406 3407 // int utimensat(int dirfd, const char *pathname, 3408 // const struct timespec times[2], int flags); 3409 addToFunctionSummaryMap( 3410 "utimensat", 3411 Signature( 3412 ArgTypes{IntTy, ConstCharPtrTy, ConstStructTimespecPtrTy, IntTy}, 3413 RetType{IntTy}), 3414 Summary(NoEvalCall) 3415 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3416 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3417 .ArgConstraint(NotNull(ArgNo(1)))); 3418 3419 std::optional<QualType> StructTimevalTy = lookupTy("timeval"); 3420 std::optional<QualType> ConstStructTimevalPtrTy = 3421 getPointerTy(getConstTy(StructTimevalTy)); 3422 3423 // int utimes(const char *filename, const struct timeval times[2]); 3424 addToFunctionSummaryMap( 3425 "utimes", 3426 Signature(ArgTypes{ConstCharPtrTy, ConstStructTimevalPtrTy}, 3427 RetType{IntTy}), 3428 Summary(NoEvalCall) 3429 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3430 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3431 .ArgConstraint(NotNull(ArgNo(0)))); 3432 3433 // int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); 3434 addToFunctionSummaryMap( 3435 "nanosleep", 3436 Signature(ArgTypes{ConstStructTimespecPtrTy, StructTimespecPtrTy}, 3437 RetType{IntTy}), 3438 Summary(NoEvalCall) 3439 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3440 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3441 .ArgConstraint(NotNull(ArgNo(0)))); 3442 3443 std::optional<QualType> Time_tTy = lookupTy("time_t"); 3444 std::optional<QualType> ConstTime_tPtrTy = 3445 getPointerTy(getConstTy(Time_tTy)); 3446 std::optional<QualType> ConstTime_tPtrRestrictTy = 3447 getRestrictTy(ConstTime_tPtrTy); 3448 3449 std::optional<QualType> StructTmTy = lookupTy("tm"); 3450 std::optional<QualType> StructTmPtrTy = getPointerTy(StructTmTy); 3451 std::optional<QualType> StructTmPtrRestrictTy = 3452 getRestrictTy(StructTmPtrTy); 3453 std::optional<QualType> ConstStructTmPtrTy = 3454 getPointerTy(getConstTy(StructTmTy)); 3455 std::optional<QualType> ConstStructTmPtrRestrictTy = 3456 getRestrictTy(ConstStructTmPtrTy); 3457 3458 // struct tm * localtime(const time_t *tp); 3459 addToFunctionSummaryMap( 3460 "localtime", 3461 Signature(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}), 3462 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 3463 3464 // struct tm *localtime_r(const time_t *restrict timer, 3465 // struct tm *restrict result); 3466 addToFunctionSummaryMap( 3467 "localtime_r", 3468 Signature(ArgTypes{ConstTime_tPtrRestrictTy, StructTmPtrRestrictTy}, 3469 RetType{StructTmPtrTy}), 3470 Summary(NoEvalCall) 3471 .ArgConstraint(NotNull(ArgNo(0))) 3472 .ArgConstraint(NotNull(ArgNo(1)))); 3473 3474 // char *asctime_r(const struct tm *restrict tm, char *restrict buf); 3475 addToFunctionSummaryMap( 3476 "asctime_r", 3477 Signature(ArgTypes{ConstStructTmPtrRestrictTy, CharPtrRestrictTy}, 3478 RetType{CharPtrTy}), 3479 Summary(NoEvalCall) 3480 .ArgConstraint(NotNull(ArgNo(0))) 3481 .ArgConstraint(NotNull(ArgNo(1))) 3482 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(1), 3483 /*MinBufSize=*/BVF.getValue(26, IntTy)))); 3484 3485 // char *ctime_r(const time_t *timep, char *buf); 3486 addToFunctionSummaryMap( 3487 "ctime_r", 3488 Signature(ArgTypes{ConstTime_tPtrTy, CharPtrTy}, RetType{CharPtrTy}), 3489 Summary(NoEvalCall) 3490 .ArgConstraint(NotNull(ArgNo(0))) 3491 .ArgConstraint(NotNull(ArgNo(1))) 3492 .ArgConstraint(BufferSize( 3493 /*Buffer=*/ArgNo(1), 3494 /*MinBufSize=*/BVF.getValue(26, IntTy)))); 3495 3496 // struct tm *gmtime_r(const time_t *restrict timer, 3497 // struct tm *restrict result); 3498 addToFunctionSummaryMap( 3499 "gmtime_r", 3500 Signature(ArgTypes{ConstTime_tPtrRestrictTy, StructTmPtrRestrictTy}, 3501 RetType{StructTmPtrTy}), 3502 Summary(NoEvalCall) 3503 .ArgConstraint(NotNull(ArgNo(0))) 3504 .ArgConstraint(NotNull(ArgNo(1)))); 3505 3506 // struct tm * gmtime(const time_t *tp); 3507 addToFunctionSummaryMap( 3508 "gmtime", Signature(ArgTypes{ConstTime_tPtrTy}, RetType{StructTmPtrTy}), 3509 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 3510 3511 std::optional<QualType> Clockid_tTy = lookupTy("clockid_t"); 3512 3513 // int clock_gettime(clockid_t clock_id, struct timespec *tp); 3514 addToFunctionSummaryMap( 3515 "clock_gettime", 3516 Signature(ArgTypes{Clockid_tTy, StructTimespecPtrTy}, RetType{IntTy}), 3517 Summary(NoEvalCall) 3518 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3519 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3520 .ArgConstraint(NotNull(ArgNo(1)))); 3521 3522 std::optional<QualType> StructItimervalTy = lookupTy("itimerval"); 3523 std::optional<QualType> StructItimervalPtrTy = 3524 getPointerTy(StructItimervalTy); 3525 3526 // int getitimer(int which, struct itimerval *curr_value); 3527 addToFunctionSummaryMap( 3528 "getitimer", 3529 Signature(ArgTypes{IntTy, StructItimervalPtrTy}, RetType{IntTy}), 3530 Summary(NoEvalCall) 3531 .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg) 3532 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg) 3533 .ArgConstraint(NotNull(ArgNo(1)))); 3534 3535 std::optional<QualType> Pthread_cond_tTy = lookupTy("pthread_cond_t"); 3536 std::optional<QualType> Pthread_cond_tPtrTy = 3537 getPointerTy(Pthread_cond_tTy); 3538 std::optional<QualType> Pthread_tTy = lookupTy("pthread_t"); 3539 std::optional<QualType> Pthread_tPtrTy = getPointerTy(Pthread_tTy); 3540 std::optional<QualType> Pthread_tPtrRestrictTy = 3541 getRestrictTy(Pthread_tPtrTy); 3542 std::optional<QualType> Pthread_mutex_tTy = lookupTy("pthread_mutex_t"); 3543 std::optional<QualType> Pthread_mutex_tPtrTy = 3544 getPointerTy(Pthread_mutex_tTy); 3545 std::optional<QualType> Pthread_mutex_tPtrRestrictTy = 3546 getRestrictTy(Pthread_mutex_tPtrTy); 3547 std::optional<QualType> Pthread_attr_tTy = lookupTy("pthread_attr_t"); 3548 std::optional<QualType> Pthread_attr_tPtrTy = 3549 getPointerTy(Pthread_attr_tTy); 3550 std::optional<QualType> ConstPthread_attr_tPtrTy = 3551 getPointerTy(getConstTy(Pthread_attr_tTy)); 3552 std::optional<QualType> ConstPthread_attr_tPtrRestrictTy = 3553 getRestrictTy(ConstPthread_attr_tPtrTy); 3554 std::optional<QualType> Pthread_mutexattr_tTy = 3555 lookupTy("pthread_mutexattr_t"); 3556 std::optional<QualType> ConstPthread_mutexattr_tPtrTy = 3557 getPointerTy(getConstTy(Pthread_mutexattr_tTy)); 3558 std::optional<QualType> ConstPthread_mutexattr_tPtrRestrictTy = 3559 getRestrictTy(ConstPthread_mutexattr_tPtrTy); 3560 3561 QualType PthreadStartRoutineTy = getPointerTy( 3562 ACtx.getFunctionType(/*ResultTy=*/VoidPtrTy, /*Args=*/VoidPtrTy, 3563 FunctionProtoType::ExtProtoInfo())); 3564 3565 // int pthread_cond_signal(pthread_cond_t *cond); 3566 // int pthread_cond_broadcast(pthread_cond_t *cond); 3567 addToFunctionSummaryMap( 3568 {"pthread_cond_signal", "pthread_cond_broadcast"}, 3569 Signature(ArgTypes{Pthread_cond_tPtrTy}, RetType{IntTy}), 3570 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 3571 3572 // int pthread_create(pthread_t *restrict thread, 3573 // const pthread_attr_t *restrict attr, 3574 // void *(*start_routine)(void*), void *restrict arg); 3575 addToFunctionSummaryMap( 3576 "pthread_create", 3577 Signature(ArgTypes{Pthread_tPtrRestrictTy, 3578 ConstPthread_attr_tPtrRestrictTy, 3579 PthreadStartRoutineTy, VoidPtrRestrictTy}, 3580 RetType{IntTy}), 3581 Summary(NoEvalCall) 3582 .ArgConstraint(NotNull(ArgNo(0))) 3583 .ArgConstraint(NotNull(ArgNo(2)))); 3584 3585 // int pthread_attr_destroy(pthread_attr_t *attr); 3586 // int pthread_attr_init(pthread_attr_t *attr); 3587 addToFunctionSummaryMap( 3588 {"pthread_attr_destroy", "pthread_attr_init"}, 3589 Signature(ArgTypes{Pthread_attr_tPtrTy}, RetType{IntTy}), 3590 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 3591 3592 // int pthread_attr_getstacksize(const pthread_attr_t *restrict attr, 3593 // size_t *restrict stacksize); 3594 // int pthread_attr_getguardsize(const pthread_attr_t *restrict attr, 3595 // size_t *restrict guardsize); 3596 addToFunctionSummaryMap( 3597 {"pthread_attr_getstacksize", "pthread_attr_getguardsize"}, 3598 Signature(ArgTypes{ConstPthread_attr_tPtrRestrictTy, SizePtrRestrictTy}, 3599 RetType{IntTy}), 3600 Summary(NoEvalCall) 3601 .ArgConstraint(NotNull(ArgNo(0))) 3602 .ArgConstraint(NotNull(ArgNo(1)))); 3603 3604 // int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize); 3605 // int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize); 3606 addToFunctionSummaryMap( 3607 {"pthread_attr_setstacksize", "pthread_attr_setguardsize"}, 3608 Signature(ArgTypes{Pthread_attr_tPtrTy, SizeTy}, RetType{IntTy}), 3609 Summary(NoEvalCall) 3610 .ArgConstraint(NotNull(ArgNo(0))) 3611 .ArgConstraint( 3612 ArgumentCondition(1, WithinRange, Range(0, SizeMax)))); 3613 3614 // int pthread_mutex_init(pthread_mutex_t *restrict mutex, const 3615 // pthread_mutexattr_t *restrict attr); 3616 addToFunctionSummaryMap( 3617 "pthread_mutex_init", 3618 Signature(ArgTypes{Pthread_mutex_tPtrRestrictTy, 3619 ConstPthread_mutexattr_tPtrRestrictTy}, 3620 RetType{IntTy}), 3621 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 3622 3623 // int pthread_mutex_destroy(pthread_mutex_t *mutex); 3624 // int pthread_mutex_lock(pthread_mutex_t *mutex); 3625 // int pthread_mutex_trylock(pthread_mutex_t *mutex); 3626 // int pthread_mutex_unlock(pthread_mutex_t *mutex); 3627 addToFunctionSummaryMap( 3628 {"pthread_mutex_destroy", "pthread_mutex_lock", "pthread_mutex_trylock", 3629 "pthread_mutex_unlock"}, 3630 Signature(ArgTypes{Pthread_mutex_tPtrTy}, RetType{IntTy}), 3631 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0)))); 3632 } 3633 3634 // Functions for testing. 3635 if (AddTestFunctions) { 3636 const RangeInt IntMin = BVF.getMinValue(IntTy).getLimitedValue(); 3637 3638 addToFunctionSummaryMap( 3639 "__not_null", Signature(ArgTypes{IntPtrTy}, RetType{IntTy}), 3640 Summary(EvalCallAsPure).ArgConstraint(NotNull(ArgNo(0)))); 3641 3642 addToFunctionSummaryMap( 3643 "__not_null_buffer", 3644 Signature(ArgTypes{VoidPtrTy, IntTy, IntTy}, RetType{IntTy}), 3645 Summary(EvalCallAsPure) 3646 .ArgConstraint(NotNullBuffer(ArgNo(0), ArgNo(1), ArgNo(2)))); 3647 3648 // Test inside range constraints. 3649 addToFunctionSummaryMap( 3650 "__single_val_0", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3651 Summary(EvalCallAsPure) 3652 .ArgConstraint(ArgumentCondition(0U, WithinRange, SingleValue(0)))); 3653 addToFunctionSummaryMap( 3654 "__single_val_1", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3655 Summary(EvalCallAsPure) 3656 .ArgConstraint(ArgumentCondition(0U, WithinRange, SingleValue(1)))); 3657 addToFunctionSummaryMap( 3658 "__range_1_2", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3659 Summary(EvalCallAsPure) 3660 .ArgConstraint(ArgumentCondition(0U, WithinRange, Range(1, 2)))); 3661 addToFunctionSummaryMap( 3662 "__range_m1_1", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3663 Summary(EvalCallAsPure) 3664 .ArgConstraint(ArgumentCondition(0U, WithinRange, Range(-1, 1)))); 3665 addToFunctionSummaryMap( 3666 "__range_m2_m1", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3667 Summary(EvalCallAsPure) 3668 .ArgConstraint(ArgumentCondition(0U, WithinRange, Range(-2, -1)))); 3669 addToFunctionSummaryMap( 3670 "__range_m10_10", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3671 Summary(EvalCallAsPure) 3672 .ArgConstraint(ArgumentCondition(0U, WithinRange, Range(-10, 10)))); 3673 addToFunctionSummaryMap("__range_m1_inf", 3674 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3675 Summary(EvalCallAsPure) 3676 .ArgConstraint(ArgumentCondition( 3677 0U, WithinRange, Range(-1, IntMax)))); 3678 addToFunctionSummaryMap("__range_0_inf", 3679 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3680 Summary(EvalCallAsPure) 3681 .ArgConstraint(ArgumentCondition( 3682 0U, WithinRange, Range(0, IntMax)))); 3683 addToFunctionSummaryMap("__range_1_inf", 3684 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3685 Summary(EvalCallAsPure) 3686 .ArgConstraint(ArgumentCondition( 3687 0U, WithinRange, Range(1, IntMax)))); 3688 addToFunctionSummaryMap("__range_minf_m1", 3689 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3690 Summary(EvalCallAsPure) 3691 .ArgConstraint(ArgumentCondition( 3692 0U, WithinRange, Range(IntMin, -1)))); 3693 addToFunctionSummaryMap("__range_minf_0", 3694 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3695 Summary(EvalCallAsPure) 3696 .ArgConstraint(ArgumentCondition( 3697 0U, WithinRange, Range(IntMin, 0)))); 3698 addToFunctionSummaryMap("__range_minf_1", 3699 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3700 Summary(EvalCallAsPure) 3701 .ArgConstraint(ArgumentCondition( 3702 0U, WithinRange, Range(IntMin, 1)))); 3703 addToFunctionSummaryMap("__range_1_2__4_6", 3704 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3705 Summary(EvalCallAsPure) 3706 .ArgConstraint(ArgumentCondition( 3707 0U, WithinRange, Range({1, 2}, {4, 6})))); 3708 addToFunctionSummaryMap( 3709 "__range_1_2__4_inf", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3710 Summary(EvalCallAsPure) 3711 .ArgConstraint(ArgumentCondition(0U, WithinRange, 3712 Range({1, 2}, {4, IntMax})))); 3713 3714 // Test out of range constraints. 3715 addToFunctionSummaryMap( 3716 "__single_val_out_0", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3717 Summary(EvalCallAsPure) 3718 .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(0)))); 3719 addToFunctionSummaryMap( 3720 "__single_val_out_1", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3721 Summary(EvalCallAsPure) 3722 .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(1)))); 3723 addToFunctionSummaryMap( 3724 "__range_out_1_2", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3725 Summary(EvalCallAsPure) 3726 .ArgConstraint(ArgumentCondition(0U, OutOfRange, Range(1, 2)))); 3727 addToFunctionSummaryMap( 3728 "__range_out_m1_1", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3729 Summary(EvalCallAsPure) 3730 .ArgConstraint(ArgumentCondition(0U, OutOfRange, Range(-1, 1)))); 3731 addToFunctionSummaryMap( 3732 "__range_out_m2_m1", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3733 Summary(EvalCallAsPure) 3734 .ArgConstraint(ArgumentCondition(0U, OutOfRange, Range(-2, -1)))); 3735 addToFunctionSummaryMap( 3736 "__range_out_m10_10", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3737 Summary(EvalCallAsPure) 3738 .ArgConstraint(ArgumentCondition(0U, OutOfRange, Range(-10, 10)))); 3739 addToFunctionSummaryMap("__range_out_m1_inf", 3740 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3741 Summary(EvalCallAsPure) 3742 .ArgConstraint(ArgumentCondition( 3743 0U, OutOfRange, Range(-1, IntMax)))); 3744 addToFunctionSummaryMap("__range_out_0_inf", 3745 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3746 Summary(EvalCallAsPure) 3747 .ArgConstraint(ArgumentCondition( 3748 0U, OutOfRange, Range(0, IntMax)))); 3749 addToFunctionSummaryMap("__range_out_1_inf", 3750 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3751 Summary(EvalCallAsPure) 3752 .ArgConstraint(ArgumentCondition( 3753 0U, OutOfRange, Range(1, IntMax)))); 3754 addToFunctionSummaryMap("__range_out_minf_m1", 3755 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3756 Summary(EvalCallAsPure) 3757 .ArgConstraint(ArgumentCondition( 3758 0U, OutOfRange, Range(IntMin, -1)))); 3759 addToFunctionSummaryMap("__range_out_minf_0", 3760 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3761 Summary(EvalCallAsPure) 3762 .ArgConstraint(ArgumentCondition( 3763 0U, OutOfRange, Range(IntMin, 0)))); 3764 addToFunctionSummaryMap("__range_out_minf_1", 3765 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3766 Summary(EvalCallAsPure) 3767 .ArgConstraint(ArgumentCondition( 3768 0U, OutOfRange, Range(IntMin, 1)))); 3769 addToFunctionSummaryMap("__range_out_1_2__4_6", 3770 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3771 Summary(EvalCallAsPure) 3772 .ArgConstraint(ArgumentCondition( 3773 0U, OutOfRange, Range({1, 2}, {4, 6})))); 3774 addToFunctionSummaryMap( 3775 "__range_out_1_2__4_inf", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3776 Summary(EvalCallAsPure) 3777 .ArgConstraint( 3778 ArgumentCondition(0U, OutOfRange, Range({1, 2}, {4, IntMax})))); 3779 3780 // Test range kind. 3781 addToFunctionSummaryMap( 3782 "__within", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3783 Summary(EvalCallAsPure) 3784 .ArgConstraint(ArgumentCondition(0U, WithinRange, SingleValue(1)))); 3785 addToFunctionSummaryMap( 3786 "__out_of", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3787 Summary(EvalCallAsPure) 3788 .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(1)))); 3789 3790 addToFunctionSummaryMap( 3791 "__two_constrained_args", 3792 Signature(ArgTypes{IntTy, IntTy}, RetType{IntTy}), 3793 Summary(EvalCallAsPure) 3794 .ArgConstraint(ArgumentCondition(0U, WithinRange, SingleValue(1))) 3795 .ArgConstraint(ArgumentCondition(1U, WithinRange, SingleValue(1)))); 3796 addToFunctionSummaryMap( 3797 "__arg_constrained_twice", Signature(ArgTypes{IntTy}, RetType{IntTy}), 3798 Summary(EvalCallAsPure) 3799 .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(1))) 3800 .ArgConstraint(ArgumentCondition(0U, OutOfRange, SingleValue(2)))); 3801 addToFunctionSummaryMap( 3802 "__defaultparam", 3803 Signature(ArgTypes{Irrelevant, IntTy}, RetType{IntTy}), 3804 Summary(EvalCallAsPure).ArgConstraint(NotNull(ArgNo(0)))); 3805 addToFunctionSummaryMap( 3806 "__variadic", 3807 Signature(ArgTypes{VoidPtrTy, ConstCharPtrTy}, RetType{IntTy}), 3808 Summary(EvalCallAsPure) 3809 .ArgConstraint(NotNull(ArgNo(0))) 3810 .ArgConstraint(NotNull(ArgNo(1)))); 3811 addToFunctionSummaryMap( 3812 "__buf_size_arg_constraint", 3813 Signature(ArgTypes{ConstVoidPtrTy, SizeTy}, RetType{IntTy}), 3814 Summary(EvalCallAsPure) 3815 .ArgConstraint( 3816 BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1)))); 3817 addToFunctionSummaryMap( 3818 "__buf_size_arg_constraint_mul", 3819 Signature(ArgTypes{ConstVoidPtrTy, SizeTy, SizeTy}, RetType{IntTy}), 3820 Summary(EvalCallAsPure) 3821 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0), /*BufSize=*/ArgNo(1), 3822 /*BufSizeMultiplier=*/ArgNo(2)))); 3823 addToFunctionSummaryMap( 3824 "__buf_size_arg_constraint_concrete", 3825 Signature(ArgTypes{ConstVoidPtrTy}, RetType{IntTy}), 3826 Summary(EvalCallAsPure) 3827 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0), 3828 /*BufSize=*/BVF.getValue(10, IntTy)))); 3829 addToFunctionSummaryMap( 3830 {"__test_restrict_param_0", "__test_restrict_param_1", 3831 "__test_restrict_param_2"}, 3832 Signature(ArgTypes{VoidPtrRestrictTy}, RetType{VoidTy}), 3833 Summary(EvalCallAsPure)); 3834 3835 // Test the application of cases. 3836 addToFunctionSummaryMap( 3837 "__test_case_note", Signature(ArgTypes{}, RetType{IntTy}), 3838 Summary(EvalCallAsPure) 3839 .Case({ReturnValueCondition(WithinRange, SingleValue(0))}, 3840 ErrnoIrrelevant, "Function returns 0") 3841 .Case({ReturnValueCondition(WithinRange, SingleValue(1))}, 3842 ErrnoIrrelevant, "Function returns 1")); 3843 addToFunctionSummaryMap( 3844 "__test_case_range_1_2__4_6", 3845 Signature(ArgTypes{IntTy}, RetType{IntTy}), 3846 Summary(EvalCallAsPure) 3847 .Case({ArgumentCondition(0U, WithinRange, 3848 IntRangeVector{{IntMin, 0}, {3, 3}}), 3849 ReturnValueCondition(WithinRange, SingleValue(1))}, 3850 ErrnoIrrelevant) 3851 .Case({ArgumentCondition(0U, WithinRange, 3852 IntRangeVector{{3, 3}, {7, IntMax}}), 3853 ReturnValueCondition(WithinRange, SingleValue(2))}, 3854 ErrnoIrrelevant) 3855 .Case({ArgumentCondition(0U, WithinRange, 3856 IntRangeVector{{IntMin, 0}, {7, IntMax}}), 3857 ReturnValueCondition(WithinRange, SingleValue(3))}, 3858 ErrnoIrrelevant) 3859 .Case({ArgumentCondition( 3860 0U, WithinRange, 3861 IntRangeVector{{IntMin, 0}, {3, 3}, {7, IntMax}}), 3862 ReturnValueCondition(WithinRange, SingleValue(4))}, 3863 ErrnoIrrelevant)); 3864 } 3865 } 3866 3867 void ento::registerStdCLibraryFunctionsChecker(CheckerManager &mgr) { 3868 auto *Checker = mgr.registerChecker<StdLibraryFunctionsChecker>(); 3869 Checker->CheckName = mgr.getCurrentCheckerName(); 3870 const AnalyzerOptions &Opts = mgr.getAnalyzerOptions(); 3871 Checker->DisplayLoadedSummaries = 3872 Opts.getCheckerBooleanOption(Checker, "DisplayLoadedSummaries"); 3873 Checker->ModelPOSIX = Opts.getCheckerBooleanOption(Checker, "ModelPOSIX"); 3874 Checker->ShouldAssumeControlledEnvironment = 3875 Opts.ShouldAssumeControlledEnvironment; 3876 } 3877 3878 bool ento::shouldRegisterStdCLibraryFunctionsChecker( 3879 const CheckerManager &mgr) { 3880 return true; 3881 } 3882 3883 void ento::registerStdCLibraryFunctionsTesterChecker(CheckerManager &mgr) { 3884 auto *Checker = mgr.getChecker<StdLibraryFunctionsChecker>(); 3885 Checker->AddTestFunctions = true; 3886 } 3887 3888 bool ento::shouldRegisterStdCLibraryFunctionsTesterChecker( 3889 const CheckerManager &mgr) { 3890 return true; 3891 } 3892