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