Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td =================================================================== --- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -23,6 +23,7 @@ def CoreBuiltin : Package<"builtin">, ParentPackage, Hidden; def CoreUninitialized : Package<"uninitialized">, ParentPackage; def CoreAlpha : Package<"core">, ParentPackage; +def CoreAlphaUnitialized : Package<"uninitialized">, ParentPackage; // The OptIn package is for checkers that are not alpha and that would normally // be on by default but where the driver does not have enough information to @@ -439,6 +440,12 @@ } // end "core.uninitialized" +let ParentPackage = CoreAlphaUnitialized in { + def UndefinedNewArraySizeChecker : Checker<"NewArraySize">, + HelpText<"Check if the size of the array in a new[] expression is undefined">, + Documentation; +} // end "core.alpha.uninitialized + //===----------------------------------------------------------------------===// // Unix API checkers. //===----------------------------------------------------------------------===// Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h =================================================================== --- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h +++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h @@ -1033,6 +1033,18 @@ return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs(); } + bool isArray() const { return getOriginExpr()->isArray(); } + + Optional getArraySizeExpr() const { + return getOriginExpr()->getArraySize(); + } + + SVal getArraySizeVal() const { + assert(isArray() && "The allocator call doesn't allocate and array!"); + + return getState()->getSVal(*getArraySizeExpr(), getLocationContext()); + } + const Expr *getArgExpr(unsigned Index) const override { // The first argument of an allocator call is the size of the allocation. if (Index < getNumImplicitArgs()) Index: clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt +++ clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt @@ -120,6 +120,7 @@ UndefResultChecker.cpp UndefinedArraySubscriptChecker.cpp UndefinedAssignmentChecker.cpp + UndefinedNewArraySizeChecker.cpp UninitializedObject/UninitializedObjectChecker.cpp UninitializedObject/UninitializedPointee.cpp UnixAPIChecker.cpp Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -331,8 +331,6 @@ void checkPreCall(const CallEvent &Call, CheckerContext &C) const; void checkPostCall(const CallEvent &Call, CheckerContext &C) const; - void checkUndefinedNewArraySize(const CallEvent &Call, - CheckerContext &C) const; void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) const; void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const; void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const; @@ -364,7 +362,6 @@ mutable std::unique_ptr BT_BadFree[CK_NumCheckKinds]; mutable std::unique_ptr BT_FreeAlloca[CK_NumCheckKinds]; mutable std::unique_ptr BT_MismatchedDealloc; - mutable std::unique_ptr BT_UndefinedArrayElementCount; mutable std::unique_ptr BT_OffsetFree[CK_NumCheckKinds]; mutable std::unique_ptr BT_UseZerroAllocated[CK_NumCheckKinds]; @@ -706,10 +703,6 @@ void HandleFreeAlloca(CheckerContext &C, SVal ArgVal, SourceRange Range) const; - void HandleUndefinedArrayElementCount(CheckerContext &C, SVal ArgVal, - const Expr *Init, SourceRange Range, - AllocationFamily Family) const; - void HandleMismatchedDealloc(CheckerContext &C, SourceRange Range, const Expr *DeallocExpr, const RefState *RS, SymbolRef Sym, bool OwnershipTransferred) const; @@ -1503,7 +1496,6 @@ } if (isStandardNewDelete(Call)) { - checkUndefinedNewArraySize(Call, C); checkCXXNewOrCXXDelete(Call, C); return; } @@ -1511,40 +1503,6 @@ checkOwnershipAttr(Call, C); } -void MallocChecker::checkUndefinedNewArraySize(const CallEvent &Call, - CheckerContext &C) const { - const auto *NE = dyn_cast_or_null(Call.getOriginExpr()); - - if (!NE) - return; - - if (NE->isArray()) { - auto *SizeEx = NE->getArraySize().value_or(nullptr); - - assert(SizeEx && "new[] without a size!?"); - - // Prevent a crash if assertions are not enabled. - if (!SizeEx) - return; - - const auto State = Call.getState(); - const auto *LCtx = Call.getLocationContext(); - const auto Ty = SizeEx->getType(); - - auto SizeVal = State->getSVal(SizeEx, LCtx); - if (Ty->isReferenceType()) { - if (const auto *MR = SizeVal.getAsRegion()) - SizeVal = State->getSVal(SizeVal.getAsRegion()); - else - SizeVal = UnknownVal{}; - } - - if (SizeVal.isUndef()) - HandleUndefinedArrayElementCount( - C, SizeVal, SizeEx, SizeEx->getSourceRange(), AF_CXXNewArray); - } -} - // Performs a 0-sized allocations check. ProgramStateRef MallocChecker::ProcessZeroAllocCheck( const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State, @@ -1791,7 +1749,7 @@ // Fill the region with the initialization value. State = State->bindDefaultInitial(RetVal, Init, LCtx); - // If Size is somehow undefined at this point, this line prevent a crash. + // If Size is somehow undefined at this point, this line prevents a crash. if (Size.isUndef()) Size = UnknownVal(); @@ -2329,57 +2287,6 @@ } } -void MallocChecker::HandleUndefinedArrayElementCount( - CheckerContext &C, SVal ArgVal, const Expr *Init, SourceRange Range, - AllocationFamily Family) const { - if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) { - C.addSink(); - return; - } - - Optional CheckKind = getCheckIfTracked(Family); - if (!CheckKind) - return; - - if (ExplodedNode *N = C.generateErrorNode()) { - if (!BT_UndefinedArrayElementCount) - BT_UndefinedArrayElementCount.reset( - new BugType(CheckNames[*CheckKind], "Undefined array element count", - categories::MemoryError)); - - SmallString<100> buf; - llvm::raw_svector_ostream os(buf); - - os << "Undefined element count! "; - - // Try to be more informative... - os << "The value "; - Init = Init->IgnoreCasts(); - - if (const auto *DRE = dyn_cast(Init)) - os << "stored in '" << *DRE->getDecl() << "' "; - else if (const auto *CE = dyn_cast(Init)) { - os << "returned "; - - if (auto CalleeDecl = dyn_cast_or_null(CE->getCalleeDecl())) - os << "from '" << *CalleeDecl << "' "; - else - os << "'[*here*]' "; - } else - os << "'[*here*]' "; - - os << "is "; - ArgVal.dumpToStream(os); - os << "!"; - - auto R = std::make_unique( - *BT_UndefinedArrayElementCount, os.str(), N); - R->markInteresting(ArgVal); - R->addRange(Range); - C.emitReport(std::move(R)); - } -} - void MallocChecker::HandleMismatchedDealloc(CheckerContext &C, SourceRange Range, const Expr *DeallocExpr, Index: clang/lib/StaticAnalyzer/Checkers/UndefinedNewArraySizeChecker.cpp =================================================================== --- /dev/null +++ clang/lib/StaticAnalyzer/Checkers/UndefinedNewArraySizeChecker.cpp @@ -0,0 +1,79 @@ +//===--- UndefinedNewArraySizeChecker.cpp -----------------------*- C++ -*--==// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This defines UndefinedNewArraySizeChecker, a builtin check in ExprEngine +// that checks if the size of the array in a new[] expression is undefined. +// +//===----------------------------------------------------------------------===// + +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/CheckerManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" + +using namespace clang; +using namespace ento; + +namespace { +class UndefinedNewArraySizeChecker : public Checker { + +private: + BugType BT{this, "Undefined array element count", categories::LogicError}; + +public: + void checkPreCall(const CallEvent &Call, CheckerContext &C) const; + void HandleUndefinedArrayElementCount(CheckerContext &C, SVal ArgVal, + const Expr *Init, + SourceRange Range) const; +}; +} // namespace + +void UndefinedNewArraySizeChecker::checkPreCall(const CallEvent &Call, + CheckerContext &C) const { + if (const auto *AC = dyn_cast(&Call)) { + if (!AC->isArray()) + return; + + auto *SizeEx = *AC->getArraySizeExpr(); + auto SizeVal = AC->getArraySizeVal(); + + if (SizeVal.isUndef()) + HandleUndefinedArrayElementCount(C, SizeVal, SizeEx, + SizeEx->getSourceRange()); + } +} + +void UndefinedNewArraySizeChecker::HandleUndefinedArrayElementCount( + CheckerContext &C, SVal ArgVal, const Expr *Init, SourceRange Range) const { + + if (ExplodedNode *N = C.generateErrorNode()) { + + SmallString<100> buf; + llvm::raw_svector_ostream os(buf); + + os << "Undefined element count"; + + auto R = std::make_unique(BT, os.str(), N); + R->markInteresting(ArgVal); + R->addRange(Range); + bugreporter::trackExpressionValue(N, Init, *R); + + C.emitReport(std::move(R)); + } +} + +void ento::registerUndefinedNewArraySizeChecker(CheckerManager &mgr) { + mgr.registerChecker(); +} + +bool ento::shouldRegisterUndefinedNewArraySizeChecker( + const CheckerManager &mgr) { + return true; +} Index: clang/test/Analysis/undefined-new-element.cpp =================================================================== --- clang/test/Analysis/undefined-new-element.cpp +++ clang/test/Analysis/undefined-new-element.cpp @@ -1,19 +1,19 @@ -// RUN: %clang_analyze_cc1 %s \ -// RUN: -analyzer-checker=cplusplus \ -// RUN: -verify +// RUN: %clang_analyze_cc1 %s -analyzer-checker=alpha.core -verify + +#include "Inputs/system-header-simulator-cxx.h" void checkUndefinedElmenetCountValue() { int n; - int *arr = new int[n]; // expected-warning{{Undefined element count!}} + int *arr = new int[n]; // expected-warning{{Undefined element count}} } void checkUndefinedElmenetCountMultiDimensionalValue() { int n; - auto *arr = new int[n][5]; // expected-warning{{Undefined element count!}} + auto *arr = new int[n][5]; // expected-warning{{Undefined element count}} } void checkUndefinedElmenetCountReference() @@ -22,7 +22,7 @@ int& ref = n; - int *arr = new int[ref]; // expected-warning{{Undefined element count!}} + int *arr = new int[ref]; // expected-warning{{Undefined element count}} } void checkUndefinedElmenetCountMultiDimensionalReference() @@ -31,7 +31,7 @@ int& ref = n; - auto *arr = new int[ref][5]; // expected-warning{{Undefined element count!}} + auto *arr = new int[ref][5]; // expected-warning{{Undefined element count}} } int foo() @@ -43,10 +43,19 @@ void checkUndefinedElmenetCountFunction() { - int *arr = new int[foo()]; // expected-warning{{Undefined element count!}} + int *arr = new int[foo()]; // expected-warning{{Undefined element count}} } void checkUndefinedElmenetCountMultiDimensionalFunction() { - auto *arr = new int[foo()][5]; // expected-warning{{Undefined element count!}} + auto *arr = new int[foo()][5]; // expected-warning{{Undefined element count}} } + +void *malloc(size_t); + +void checkUndefinedPlacementElementCount() +{ + int n; + void *buffer = malloc(sizeof(std::string) * 10); + std::string *p = ::new (buffer) std::string[n]; // expected-warning{{Undefined element count}} +} \ No newline at end of file