diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index c97642b9930..688516e2bf7 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -1175,6 +1175,9 @@ void CheckBufferOverrunImpl::objectIndex() const Token *idx = tok->astOperand2(); if (!idx || !obj) continue; + // An object such as a view can refer to a variable but indexing it calls operator[] + if (obj->valueType() && obj->valueType()->pointer == 0) + continue; if (const ValueFlow::Value* v = idx->getKnownValue(ValueFlow::Value::ValueType::INT)) { if (v->intvalue == 0) continue; diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp index 26801640e99..29bfaf048bd 100644 --- a/lib/symboldatabase.cpp +++ b/lib/symboldatabase.cpp @@ -888,6 +888,30 @@ void SymbolDatabase::createSymbolDatabaseClassInfo() } +namespace { + struct LifetimeBoundParam { + nonneg int index; + Token::LifetimeAttrMode mode; + }; +} + +static std::vector findLifetimeBoundParams(const Token* argStart) +{ + std::vector result; + if (!Token::simpleMatch(argStart, "(")) + return result; + nonneg int index = 0; + for (const Token* tok = argStart->next(); tok && tok != argStart->link(); tok = tok->next()) { + if (tok->link() && Token::Match(tok, "(|[|{|<")) + tok = tok->link(); + if (tok->str() == ",") + index++; + else if (tok->isAttributeLifetimeBound() && (result.empty() || result.back().index != index)) + result.push_back({index, tok->getAttributeLifetimeBound()}); + } + return result; +} + void SymbolDatabase::createSymbolDatabaseVariableInfo() { // fill in variable info @@ -901,6 +925,14 @@ void SymbolDatabase::createSymbolDatabaseVariableInfo() for (auto func = scope.functionList.begin(); func != scope.functionList.end(); ++func) { // add arguments func->addArguments(&scope); + + // the attribute can be on the declaration, the definition or both + for (const Token* argStart : {func->argDef, func->arg}) { + for (const LifetimeBoundParam& arg : findLifetimeBoundParams(argStart)) { + if (arg.index < func->argumentList.size()) + std::next(func->argumentList.begin(), arg.index)->mLifetimeBound = arg.mode; + } + } } } } @@ -2502,6 +2534,7 @@ Variable& Variable::operator=(const Variable &var) & mIndex = var.mIndex; mAccess = var.mAccess; mFlags = var.mFlags; + mLifetimeBound = var.mLifetimeBound; mType = var.mType; mScope = var.mScope; mDimensions = var.mDimensions; diff --git a/lib/symboldatabase.h b/lib/symboldatabase.h index 832bcddeab3..bcb4cbe3979 100644 --- a/lib/symboldatabase.h +++ b/lib/symboldatabase.h @@ -648,6 +648,14 @@ class CPPCHECKLIB Variable { return getFlag(fIsMaybeUnused); } + /** + * Is this a function argument marked [[clang::lifetimebound]]? + * The return value of the function (or the constructed object) may refer to it. + */ + bool isLifetimeBound() const { + return mLifetimeBound != Token::LifetimeAttrMode::NONE; + } + const ValueType *valueType() const { return mValueType; } @@ -690,6 +698,9 @@ class CPPCHECKLIB Variable { /** @brief flags */ unsigned int mFlags; + /** @brief function argument marked [[clang::lifetimebound]] */ + Token::LifetimeAttrMode mLifetimeBound = Token::LifetimeAttrMode::NONE; + /** @brief pointer to user defined type info (for known types) */ const Type *mType; @@ -831,6 +842,10 @@ class CPPCHECKLIB Function { bool isAttributeMaybeUnused() const { return tokenDef->isAttributeMaybeUnused(); } + /** The implicit object parameter is marked [[clang::lifetimebound]] */ + bool isAttributeLifetimeBound() const { + return tokenDef->isAttributeLifetimeBound() || (token && token->isAttributeLifetimeBound()); + } bool hasBody() const { return getFlag(fHasBody); diff --git a/lib/token.h b/lib/token.h index 5e200f63b9c..877aa0ef928 100644 --- a/lib/token.h +++ b/lib/token.h @@ -84,6 +84,8 @@ class CPPCHECKLIB Token { public: enum CppcheckAttributesType : std::uint8_t { LOW, HIGH }; enum class Cpp11init : std::uint8_t { UNKNOWN, CPP11INIT, NOINIT }; + /** What a lifetime attribute such as [[clang::lifetimebound]] applies to. OBJECT is the object that is passed. */ + enum class LifetimeAttrMode : std::uint8_t { NONE, OBJECT }; private: struct Impl { @@ -164,6 +166,9 @@ class CPPCHECKLIB Token { std::string mAttributeCleanup; + // [[clang::lifetimebound]], __attribute__((lifetimebound)) + LifetimeAttrMode mAttributeLifetimeBound{LifetimeAttrMode::NONE}; + // For memoization, to speed up parsing of huge arrays #8897 Cpp11init mCpp11init{Cpp11init::UNKNOWN}; @@ -586,6 +591,19 @@ class CPPCHECKLIB Token { void isAttributeFallthrough(const bool value) { setFlag(fIsAttributeFallthrough, value); } + bool isAttributeLifetimeBound() const { + return mImpl->mAttributeLifetimeBound != LifetimeAttrMode::NONE; + } + LifetimeAttrMode getAttributeLifetimeBound() const { + return mImpl->mAttributeLifetimeBound; + } + void setAttributeLifetimeBound(LifetimeAttrMode mode) { + mImpl->mAttributeLifetimeBound = mode; + } + /** Copy the lifetime attributes. They are not a part of flags(). */ + void copyLifetimeAttributes(const Token& tok) { + mImpl->mAttributeLifetimeBound = tok.mImpl->mAttributeLifetimeBound; + } std::vector getAttributeAlignas() const { return mImpl->mAttributeAlignas ? *mImpl->mAttributeAlignas : std::vector(); } diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index 60fbe92968c..2f4d8bdda1f 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -9737,6 +9737,46 @@ static Token* getVariableTokenAfterAttributes(Token* tok) { return vartok; } +// An attribute after the function declarator applies to the implicit object parameter, so the function +// name is returned. Otherwise a token of the parameter declaration is returned. +static Token* getLifetimeBoundTok(Token* attr, Token* after) +{ + Token* const prev = attr->previous(); + Token* declEnd = prev; + while (declEnd) { + if (Token::Match(declEnd, "const|volatile|&|&&|noexcept")) + declEnd = declEnd->previous(); + else if (Token::simpleMatch(declEnd, ")") && Token::simpleMatch(declEnd->link()->previous(), "noexcept")) + declEnd = declEnd->link()->tokAt(-2); + else + break; + } + if (Token::simpleMatch(declEnd, ")")) { + Token* const ftok = declEnd->link()->previous(); + if (Token::simpleMatch(ftok, ")") && Token::simpleMatch(ftok->tokAt(-2), "operator (")) + return ftok->tokAt(-2); + for (Token* tok = ftok; tok && !Token::Match(tok, "[;{}()]"); tok = tok->previous()) { + if (tok->str() == "operator") + return tok; + } + return Token::Match(ftok, "%name%") ? ftok : nullptr; + } + if (Token::Match(prev, "(|,")) { + Token* end = after; + while (end && !Token::Match(end, "[,)=;]")) { + if (end->link() && Token::Match(end, "(|[|{")) + end = end->link(); + else if (end->str() == "<" && end->findClosingBracket()) + end = end->findClosingBracket(); + end = end->next(); + } + if (!Token::Match(end, "[,)=]") || end == after) + return nullptr; + return end->previous(); + } + return Token::Match(prev, "%name%|]|*|&|&&|>") ? prev : nullptr; +} + Token* Tokenizer::getAttributeFuncTok(Token* tok, bool gccattr) const { if (!Token::Match(tok, "%name% (")) return nullptr; @@ -9860,6 +9900,11 @@ void Tokenizer::simplifyAttribute() else if (Token::Match(attr, "[(,] packed [,)]") && Token::simpleMatch(tok->previous(), "}")) tok->previous()->isAttributePacked(true); + else if (Token::Match(attr, "[(,] lifetimebound|__lifetimebound__ [,)]")) { + if (Token* lifetimeBoundTok = getLifetimeBoundTok(tok, getTokenAfterAttributes(tok, true))) + lifetimeBoundTok->setAttributeLifetimeBound(Token::LifetimeAttrMode::OBJECT); + } + else if (functok && Token::simpleMatch(attr, "( __visibility__ ( \"default\" ) )")) functok->isAttributeExport(true); @@ -9940,6 +9985,13 @@ void Tokenizer::simplifyCPPAttribute() tok = skipCPPOrAlignAttribute(tok)->next(); continue; } + if (Token::findmatch(tok->tokAt(2), "lifetimebound|__lifetimebound__", tok->link())) { + Token* head = skipCPPOrAlignAttribute(tok)->next(); + while (isCPPAttribute(head) || isAlignAttribute(head)) + head = skipCPPOrAlignAttribute(head)->next(); + if (Token* lifetimeBoundTok = getLifetimeBoundTok(tok, head)) + lifetimeBoundTok->setAttributeLifetimeBound(Token::LifetimeAttrMode::OBJECT); + } if (Token::findsimplematch(tok->tokAt(2), "noreturn", tok->link())) { Token * head = skipCPPOrAlignAttribute(tok)->next(); while (isCPPAttribute(head) || isAlignAttribute(head)) diff --git a/lib/tokenlist.cpp b/lib/tokenlist.cpp index 26b24d649c8..5531d6fc9ee 100644 --- a/lib/tokenlist.cpp +++ b/lib/tokenlist.cpp @@ -198,6 +198,7 @@ void TokenList::addtoken(const Token * tok, const nonneg int lineno, const nonne mTokensFrontBack->back->column(column); mTokensFrontBack->back->fileIndex(fileno); mTokensFrontBack->back->flags(tok->flags()); + mTokensFrontBack->back->copyLifetimeAttributes(*tok); mTokensFrontBack->back->tokType(tok->tokType()); } @@ -217,6 +218,7 @@ void TokenList::addtoken(const Token *tok, const Token *locationTok) } mTokensFrontBack->back->flags(tok->flags()); + mTokensFrontBack->back->copyLifetimeAttributes(*tok); mTokensFrontBack->back->linenr(locationTok->linenr()); mTokensFrontBack->back->column(locationTok->column()); mTokensFrontBack->back->fileIndex(locationTok->fileIndex()); @@ -241,6 +243,7 @@ void TokenList::addtoken(const Token *tok) } mTokensFrontBack->back->flags(tok->flags()); + mTokensFrontBack->back->copyLifetimeAttributes(*tok); mTokensFrontBack->back->linenr(tok->linenr()); mTokensFrontBack->back->column(tok->column()); mTokensFrontBack->back->fileIndex(tok->fileIndex()); @@ -265,6 +268,7 @@ Token *TokenList::copyTokens(Token *dest, const Token *first, const Token *last, tok2->linenr(linenr); tok2->tokType(tok->tokType()); tok2->flags(tok->flags()); + tok2->copyLifetimeAttributes(*tok); tok2->varId(tok->varId()); tok2->setTokenDebug(tok->getTokenDebug()); @@ -317,6 +321,7 @@ void TokenList::insertTokens(Token *dest, const Token *src, nonneg int n) dest->varId(src->varId()); dest->tokType(src->tokType()); dest->flags(src->flags()); + dest->copyLifetimeAttributes(*src); if (!src->getMacroName().empty()) dest->setMacroName(src->getMacroName()); src = src->next(); @@ -424,6 +429,7 @@ std::size_t TokenList::calculateHash() const std::string hashData; for (const Token* tok = front(); tok; tok = tok->next()) { hashData += std::to_string(tok->flags()); + hashData += std::to_string(static_cast(tok->getAttributeLifetimeBound())); hashData += std::to_string(tok->varId()); hashData += std::to_string(tok->tokType()); hashData += tok->str(); diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 7f4cd5584e8..e1f171d1f1d 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -1481,13 +1481,341 @@ static bool checkDotLifetime(const Token* dot, const Token* tok) return true; } +static const Token* skipCV(const Token* tok) +{ + while (Token::Match(tok, "const|volatile")) + tok = tok->next(); + return tok; +} + +// Returns the token after the type at typeTok when it is the same type as the template argument at argTok. +// The tokens are compared so that types that are not declared in the translation unit can be matched. +static const Token* skipSameType(const Token* typeTok, const Token* argTok) +{ + typeTok = skipCV(typeTok); + argTok = skipCV(argTok); + if (!Token::Match(argTok, "%name%|::")) + return nullptr; + int depth = 0; + for (; typeTok && argTok; typeTok = typeTok->next(), argTok = argTok->next()) { + if (depth == 0 && Token::Match(argTok, ",|>")) + return typeTok; + if (typeTok->str() != argTok->str() || !compareTokenFlags(typeTok, argTok, false)) + return nullptr; + if (typeTok->str() == "<") + depth++; + else if (typeTok->str() == ">") + depth--; + } + return nullptr; +} + +static bool isSameTemplateArg(const Token* tok1, const Token* tok2) +{ + if (!tok1 || !tok2) + return tok1 == tok2; + return Token::Match(skipSameType(tok1, tok2), ",|>"); +} + +static bool isSameKnownType(const ValueType& vt1, const ValueType& vt2) +{ + if (!vt1.isTypeEqual(&vt2)) + return false; + if (vt1.isPrimitive()) + return vt1.type != ValueType::Type::UNKNOWN_INT && vt1.sign == vt2.sign; + if (vt1.type == ValueType::Type::RECORD) + return vt1.typeScope != nullptr; + if (vt1.type == ValueType::Type::CONTAINER || vt1.type == ValueType::Type::ITERATOR) + return vt1.container && isSameTemplateArg(vt1.containerTypeToken, vt2.containerTypeToken); + return false; +} + +static bool returnsElementOf(const Function* f, const ValueType& container, const ValueType& result, bool reference) +{ + if (!container.containerTypeToken) + return container.container->stdStringLike && result.pointer == 0 && + (result.type == ValueType::Type::CHAR || result.type == ValueType::Type::WCHAR_T); + const Token* tok = skipCV(skipSameType(f->retDef, container.containerTypeToken)); + if (!tok || tok->str() != (reference ? "&" : "*")) + return false; + tok = skipCV(tok->next()); + return tok && !Token::Match(tok, "*|&|&&"); +} + +static bool isViewOf(const ValueType& view, const ValueType& container) +{ + if (view.type != ValueType::Type::CONTAINER || view.pointer != 0 || !view.container || !view.container->view || + container.container->view) + return false; + if (!view.containerTypeToken && !container.containerTypeToken) + return view.container->stdStringLike && container.container->stdStringLike; + return isSameTemplateArg(view.containerTypeToken, container.containerTypeToken); +} + +// What the result of a call refers to in the object that is bound to a lifetimebound parameter +enum class LifetimeBoundRelation : std::uint8_t { + // Not known from the types. This is not treated as a reference to the contents of a container. + Unknown, + // The object itself + Same, + // An element of the container or a view of its elements + Element, + // An iterator to the container + Iterator +}; + +// The bound object is the argument when byRef is set, otherwise it is what the argument points to +static LifetimeBoundRelation getLifetimeBoundRelation(const ValueType* objType, + bool byRef, + const Token* call, + const Function* f) +{ + const nonneg int objIndirect = byRef ? 0 : 1; + const ValueType* resultType = call->valueType(); + if (!objType || !resultType || objType->pointer < objIndirect) + return LifetimeBoundRelation::Unknown; + const bool reference = Function::returnsReference(f); + ValueType obj = *objType; + obj.pointer -= objIndirect; + const bool isContainer = obj.type == ValueType::Type::CONTAINER && obj.pointer == 0 && obj.container; + if (resultType->type == ValueType::Type::ITERATOR) { + if (isContainer && !reference && resultType->pointer == 0 && resultType->container == obj.container && + isSameTemplateArg(resultType->containerTypeToken, obj.containerTypeToken)) + return LifetimeBoundRelation::Iterator; + return LifetimeBoundRelation::Unknown; + } + if (isContainer && !reference && isViewOf(*resultType, obj)) + return LifetimeBoundRelation::Element; + // A returned pointer refers to the object it points to + const nonneg int resultIndirect = reference ? 0 : 1; + if (resultType->pointer < resultIndirect) + return LifetimeBoundRelation::Unknown; + ValueType result = *resultType; + result.pointer -= resultIndirect; + if (isSameKnownType(result, obj)) + return LifetimeBoundRelation::Same; + if (isContainer && returnsElementOf(f, obj, result, reference)) + return LifetimeBoundRelation::Element; + return LifetimeBoundRelation::Unknown; +} + +// The expression is a member or an element of the object that the lifetime token refers to. An element of an array +// is not included since a pointer to it has the same kind of lifetime as a pointer to the array. +static bool isInteriorLifetimeToken(const ValueFlow::LifetimeToken& lt) +{ + return !lt.addressOf && !astIsPointer(lt.token); +} + +static bool isInteriorArgument(const Token* argtok, const Settings& settings) +{ + const std::vector lts = ValueFlow::getLifetimeTokens(argtok, settings); + return std::any_of(lts.cbegin(), lts.cend(), &isInteriorLifetimeToken); +} + +static bool isInteriorLifetimeKind(ValueFlow::Value::LifetimeKind kind) +{ + return kind == ValueFlow::Value::LifetimeKind::Object || kind == ValueFlow::Value::LifetimeKind::Iterator; +} + +// The object or lambda with this lifetime stores a pointer or an iterator to the contents of the variable +static bool hasInteriorCapture(const ValueFlow::Value& v, int depth = 4) +{ + if (depth < 0 || !v.capturetok || !v.tokvalue || v.tokvalue->varId() == 0) + return false; + return std::any_of(v.capturetok->values().cbegin(), v.capturetok->values().cend(), [&](const ValueFlow::Value& inner) { + if (!inner.isLifetimeValue() || !inner.tokvalue || inner.tokvalue->varId() != v.tokvalue->varId()) + return false; + return isInteriorLifetimeKind(inner.lifetimeKind) || hasInteriorCapture(inner, depth - 1); + }); +} + +// The kind of lifetime that the result of a call has for an object when the returned expression has the lifetime v +// for the parameter that the object is bound to +static ValueFlow::Value::LifetimeKind getReturnedLifetimeKind(const ValueFlow::Value& v, bool interior) +{ + const ValueFlow::Value::LifetimeKind kind = v.lifetimeKind; + if (kind == ValueFlow::Value::LifetimeKind::Address && interior) + return ValueFlow::Value::LifetimeKind::Object; + // The captured token is in the called function so the capture cannot be followed from the result + if ((kind == ValueFlow::Value::LifetimeKind::SubObject || kind == ValueFlow::Value::LifetimeKind::Lambda) && + hasInteriorCapture(v)) + return ValueFlow::Value::LifetimeKind::Object; + return kind; +} + +// The kind of lifetime that the result of a call has for an object that is bound to a lifetimebound parameter +static ValueFlow::Value::LifetimeKind getLifetimeBoundKind(LifetimeBoundRelation relation, bool interior) +{ + switch (relation) { + case LifetimeBoundRelation::Iterator: + return ValueFlow::Value::LifetimeKind::Iterator; + case LifetimeBoundRelation::Element: + return ValueFlow::Value::LifetimeKind::Object; + case LifetimeBoundRelation::Same: + return interior ? ValueFlow::Value::LifetimeKind::Object : ValueFlow::Value::LifetimeKind::Address; + case LifetimeBoundRelation::Unknown: + // Address is not used since checks assume that such a pointer is exactly the address of the object + return interior ? ValueFlow::Value::LifetimeKind::Object : ValueFlow::Value::LifetimeKind::SubObject; + } + cppcheck::unreachable(); +} + +// Maps the kind of lifetime that an argument passed by value has to the kind of lifetime that the result has +struct LifetimeBoundByValKind { + LifetimeBoundRelation relation; + bool iteratorResult; + + ValueFlow::Value::LifetimeKind operator()(ValueFlow::Value::LifetimeKind argKind) const + { + switch (argKind) { + case ValueFlow::Value::LifetimeKind::Address: + return getLifetimeBoundKind(relation, false); + case ValueFlow::Value::LifetimeKind::Iterator: + case ValueFlow::Value::LifetimeKind::Object: + return iteratorResult ? ValueFlow::Value::LifetimeKind::Iterator : ValueFlow::Value::LifetimeKind::Object; + case ValueFlow::Value::LifetimeKind::SubObject: + return ValueFlow::Value::LifetimeKind::SubObject; + case ValueFlow::Value::LifetimeKind::Lambda: + return relation == LifetimeBoundRelation::Same ? ValueFlow::Value::LifetimeKind::Lambda + : ValueFlow::Value::LifetimeKind::SubObject; + } + cppcheck::unreachable(); + } +}; + +struct LifetimeBoundArg { + const Token* tok; + // null for the implicit object parameter + const Variable* param; + // the result refers to the argument itself, otherwise it refers to what the argument refers to + bool byRef; + LifetimeBoundRelation relation; +}; + +static bool hasLifetimeBound(const Function* f) +{ + return f->isAttributeLifetimeBound() || + std::any_of(f->argumentList.cbegin(), f->argumentList.cend(), [](const Variable& param) { + return param.isLifetimeBound(); + }); +} + +// The arguments that are passed to parameters marked with the lifetimebound attribute. call is the token of the result. +static std::vector getLifetimeBoundArgs(const Function* f, + const std::vector& args, + const Token* call) +{ + std::vector result; + for (const Variable& param : f->argumentList) { + // TODO: Track lifetimes of default parameters + if (!param.isLifetimeBound() || param.index() >= args.size()) + continue; + const bool byRef = param.isReference() || param.isRValueReference(); + result.push_back({args[param.index()], ¶m, byRef, getLifetimeBoundRelation(param.valueType(), byRef, call, f)}); + } + return result; +} + +// The arguments in the function call that are bound by the lifetimebound attribute. This includes the object that +// a member function with the attribute is called on. +static std::vector getLifetimeBoundArgs(const Token* ftok, const Function* f) +{ + std::vector result; + if (!hasLifetimeBound(f)) + return result; + if (f->isAttributeLifetimeBound() && Token::Match(ftok->astParent(), ". %name% (") && astIsRHS(ftok)) { + const Token* objTok = ftok->astParent()->astOperand1(); + const bool byRef = !derefShared(ftok->astParent()); + result.push_back({objTok, nullptr, byRef, getLifetimeBoundRelation(objTok->valueType(), byRef, ftok->next(), f)}); + } + const std::vector paramArgs = getLifetimeBoundArgs(f, getArguments(ftok), ftok->next()); + result.insert(result.end(), paramArgs.cbegin(), paramArgs.cend()); + return result; +} + template static std::vector getLifetimeTokens(const Token* tok, bool escape, ErrorPath errorPath, Predicate pred, const Settings& settings, - int depth = 20) + int depth = 20); + +// The lifetimes that the reference returned by the call at tok has from the lifetimebound attribute +template +static std::vector getLifetimeBoundTokens(const Token* tok, + const Function* f, + bool escape, + const ErrorPath& errorPath, + Predicate pred, + const Settings& settings, + int depth) +{ + std::vector result; + const std::vector boundArgs = getLifetimeBoundArgs(tok->previous(), f); + for (const LifetimeBoundArg& boundArg : boundArgs) { + const std::string argExpr = boundArg.tok->expressionString(); + const ErrorPathItem errorPathItem{ + tok->previous(), + boundArg.param ? "Called function passing '" + argExpr + "' to lifetimebound parameter." + : "Calling lifetimebound member function on '" + argExpr + "'."}; + std::vector arglts; + if (boundArg.byRef) { + ErrorPath er = errorPath; + er.push_back(errorPathItem); + arglts = getLifetimeTokens(boundArg.tok, escape, std::move(er), pred, settings, depth - 1); + for (ValueFlow::LifetimeToken& lt : arglts) { + if (isInteriorLifetimeKind(getLifetimeBoundKind(boundArg.relation, isInteriorLifetimeToken(lt)))) + lt.addressOf = false; + } + } else if (boundArg.param) { + const LifetimeBoundByValKind byValKind{boundArg.relation, false}; + for (const ValueFlow::Value& v : boundArg.tok->values()) { + if (!v.isLocalLifetimeValue()) + continue; + ErrorPath er = errorPath; + er.insert(er.end(), v.errorPath.cbegin(), v.errorPath.cend()); + er.push_back(errorPathItem); + std::vector vallts = + getLifetimeTokens(v.tokvalue, escape, std::move(er), pred, settings, depth - 1); + if (isInteriorLifetimeKind(byValKind(v.lifetimeKind))) + vallts = ValueFlow::LifetimeToken::setAddressOf(std::move(vallts), false); + arglts.insert(arglts.end(), vallts.cbegin(), vallts.cend()); + } + } + arglts = ValueFlow::LifetimeToken::setInconclusive(std::move(arglts), boundArgs.size() > 1); + result.insert(result.end(), arglts.cbegin(), arglts.cend()); + } + return result; +} + +// Adds the lifetimes from the lifetimebound attribute to the lifetimes from the function body. +// A lifetime that both have is kept as the function body has it. +static std::vector addLifetimeBoundTokens(std::vector result, + const std::vector& boundlts) +{ + const std::size_t bodyCount = result.size(); + for (const ValueFlow::LifetimeToken& boundlt : boundlts) { + bool found = false; + for (std::size_t i = 0; i < bodyCount; i++) { + if (result[i].token != boundlt.token) + continue; + found = true; + result[i].inconclusive = result[i].inconclusive && boundlt.inconclusive; + } + if (!found) + result.push_back(boundlt); + } + return result; +} + +template +static std::vector getLifetimeTokens(const Token* tok, + bool escape, + ErrorPath errorPath, + Predicate pred, + const Settings& settings, + int depth) { if (!tok) return std::vector {}; @@ -1539,6 +1867,8 @@ static std::vector getLifetimeTokens(const Token* tok, if (f) { if (!Function::returnsReference(f)) return {{tok, std::move(errorPath)}}; + std::vector boundlts = + getLifetimeBoundTokens(tok, f, escape, errorPath, pred, settings, depth); std::vector result; std::vector returns = Function::findReturns(f); for (const Token* returnTok : returns) { @@ -1548,20 +1878,24 @@ static std::vector getLifetimeTokens(const Token* tok, const Token* argvarTok = lt.token; const Variable* argvar = argvarTok->variable(); const Token* argTok = nullptr; + bool returnsObject = lt.addressOf; if (argvar && argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) { const int n = getArgumentPos(argvar, f); if (n < 0) - return std::vector {}; + return boundlts; std::vector args = getArguments(tok->previous()); // TODO: Track lifetimes of default parameters if (n >= args.size()) - return std::vector {}; + return boundlts; argTok = args[n]; lt.errorPath.emplace_back(returnTok, "Return reference."); lt.errorPath.emplace_back(tok->previous(), "Called function passing '" + argTok->expressionString() + "'."); } else if (Token::Match(tok->tokAt(-2), ". %name% (") && !derefShared(tok->tokAt(-2)) && exprDependsOnThis(argvarTok)) { argTok = tok->tokAt(-2)->astOperand1(); + // A member is a part of the object + returnsObject = returnsObject && argvarTok->isUnaryOp("*") && + Token::simpleMatch(argvarTok->astOperand1(), "this"); lt.errorPath.emplace_back(returnTok, "Return reference that depends on 'this'."); lt.errorPath.emplace_back(tok->previous(), "Calling member function on '" + argTok->expressionString() + "'."); @@ -1570,11 +1904,13 @@ static std::vector getLifetimeTokens(const Token* tok, std::vector arglts = ValueFlow::LifetimeToken::setInconclusive( getLifetimeTokens(argTok, escape, std::move(lt.errorPath), pred, settings, depth - returns.size()), returns.size() > 1); + for (ValueFlow::LifetimeToken& arglt : arglts) + arglt.addressOf = arglt.addressOf && returnsObject; result.insert(result.end(), arglts.cbegin(), arglts.cend()); } } } - return result; + return addLifetimeBoundTokens(std::move(result), boundlts); } if (Token::Match(tok->tokAt(-2), ". %name% (") && tok->tokAt(-2)->originalName() != "->" && astIsContainer(tok->tokAt(-2)->astOperand1())) { const Library::Container* library = getLibraryContainer(tok->tokAt(-2)->astOperand1()); @@ -1589,14 +1925,17 @@ static std::vector getLifetimeTokens(const Token* tok, } else if (Token::Match(tok, ".|::|[") || tok->isUnaryOp("*")) { const Token *vartok = tok; + bool member = false; + int derefs = 0; while (vartok) { - if (vartok->str() == "[" || vartok->isUnaryOp("*")) + if (vartok->str() == "[" || vartok->isUnaryOp("*")) { vartok = vartok->astOperand1(); - else if (vartok->str() == ".") { - if (checkDotLifetime(vartok, tok)) - vartok = vartok->astOperand1(); - else + derefs++; + } else if (vartok->str() == ".") { + if (!checkDotLifetime(vartok, tok)) break; + vartok = vartok->astOperand1(); + member = true; } else if (vartok->str() == "::") vartok = vartok->astOperand2(); @@ -1613,13 +1952,19 @@ static std::vector getLifetimeTokens(const Token* tok, if (v.tokvalue == tok) continue; errorPath.insert(errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend()); - return ValueFlow::LifetimeToken::setAddressOf( - getLifetimeTokens(v.tokvalue, escape, std::move(errorPath), pred, settings, depth - 1), - false); + std::vector result = + getLifetimeTokens(v.tokvalue, escape, std::move(errorPath), pred, settings, depth - 1); + // Only a dereferenced pointer to the object is the object itself + if (member || derefs > 1 || v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address) + result = ValueFlow::LifetimeToken::setAddressOf(std::move(result), false); + return result; } } else { - return ValueFlow::LifetimeToken::setAddressOf( - getLifetimeTokens(vartok, escape, std::move(errorPath), pred, settings, depth - 1), false); + std::vector result = + getLifetimeTokens(vartok, escape, std::move(errorPath), pred, settings, depth - 1); + if (member || derefs > 0) + result = ValueFlow::LifetimeToken::setAddressOf(std::move(result), false); + return result; } } else if (Token::simpleMatch(tok, "{") && getArgumentStart(tok) && !Token::simpleMatch(getArgumentStart(tok), ",") && getArgumentStart(tok)->valueType()) { @@ -2044,6 +2389,10 @@ struct LifetimeStore { ErrorPath errorPath; bool inconclusive{}; bool forward = true; + // When set, byVal stores the kind that this returns for the kind of the argument's lifetime instead of `type` + std::function byValKind; + // When set, a lifetime gets the kind of the lifetime that is already stored for the same token + bool keepKind = false; LifetimeStore() = default; @@ -2128,7 +2477,7 @@ struct LifetimeStore { value.lifetimeScope = ValueFlow::Value::LifetimeScope::Local; value.tokvalue = lt.token; value.errorPath = std::move(er); - value.lifetimeKind = type; + value.lifetimeKind = getKind(tok, lt.token, type); value.setInconclusive(lt.inconclusive || inconclusive); // Don't add the value a second time if (std::find(tok->values().cbegin(), tok->values().cend(), value) != tok->values().cend()) @@ -2187,7 +2536,7 @@ struct LifetimeStore { value.tokvalue = lt.token; value.capturetok = argtok; value.errorPath = er; - value.lifetimeKind = type; + value.lifetimeKind = getKind(tok, lt.token, type); value.setInconclusive(inconclusive || lt.inconclusive); value.lifetimeScope = ValueFlow::Value::LifetimeScope::Argument; @@ -2223,7 +2572,7 @@ struct LifetimeStore { value.tokvalue = lt.token; value.capturetok = argtok; value.errorPath = std::move(er); - value.lifetimeKind = type; + value.lifetimeKind = getKind(tok, lt.token, byValKind ? byValKind(v.lifetimeKind) : type); value.setInconclusive(lt.inconclusive || v.isInconclusive() || inconclusive); // Don't add the value a second time if (std::find(tok->values().cbegin(), tok->values().cend(), value) != tok->values().cend()) @@ -2319,6 +2668,18 @@ struct LifetimeStore { forwardTok = tok; valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings); } + + ValueFlow::Value::LifetimeKind getKind(const Token* tok, + const Token* lifetimeTok, + ValueFlow::Value::LifetimeKind kind) const + { + if (!keepKind) + return kind; + const auto it = std::find_if(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) { + return v.isLifetimeValue() && v.tokvalue == lifetimeTok; + }); + return it == tok->values().cend() ? kind : it->lifetimeKind; + } }; static bool hasBorrowingVariables(const std::list& vars, const std::vector& args, int depth = 10) @@ -2350,6 +2711,27 @@ static bool hasBorrowingVariables(const std::list& vars, const std::ve }); } +// Stores the lifetimes that the result of a call has for an argument that is bound by the lifetimebound attribute. +// The lifetimes from the function body have to be stored before this so that their kind is kept. +static bool valueFlowLifetimeBoundArg(Token* tok, + const LifetimeBoundArg& boundArg, + std::string message, + bool inconclusive, + const TokenList& tokenlist, + ErrorLogger& errorLogger, + const Settings& settings) +{ + LifetimeStore ls{boundArg.tok, std::move(message), ValueFlow::Value::LifetimeKind::Object, inconclusive}; + ls.forward = false; + ls.keepKind = true; + if (boundArg.byRef) { + ls.type = getLifetimeBoundKind(boundArg.relation, isInteriorArgument(boundArg.tok, settings)); + return ls.byRef(tok, tokenlist, errorLogger, settings); + } + ls.byValKind = LifetimeBoundByValKind{boundArg.relation, astIsIterator(tok)}; + return ls.byVal(tok, tokenlist, errorLogger, settings); +} + static void valueFlowLifetimeUserConstructor(Token* tok, const Function* constructor, const std::string& name, @@ -2434,14 +2816,26 @@ static void valueFlowLifetimeUserConstructor(Token* tok, "Passed to constructor of '" + name + "'.", ValueFlow::Value::LifetimeKind::SubObject, [&](LifetimeStore& ls) { - ls.inconclusive = true; const Variable* var = argToParam.at(ls.argtok); + // The lifetimes of a bound argument are stored below and are not inconclusive + if (var && var->isLifetimeBound()) + return; + ls.inconclusive = true; if (var && !var->isConst() && var->isReference()) ls.byRef(tok, tokenlist, errorLogger, settings); else ls.byVal(tok, tokenlist, errorLogger, settings); }); } + // The constructed object can refer to every bound argument so the lifetimes are not inconclusive + for (const LifetimeBoundArg& boundArg : getLifetimeBoundArgs(constructor, args, tok)) + valueFlowLifetimeBoundArg(tok, + boundArg, + "Passed to constructor of '" + name + "'.", + false, + tokenlist, + errorLogger, + settings); } static void valueFlowLifetimeFunction(Token *tok, const TokenList &tokenlist, ErrorLogger &errorLogger, const Settings &settings) @@ -2514,13 +2908,18 @@ static void valueFlowLifetimeFunction(Token *tok, const TokenList &tokenlist, Er for (const Token* returnTok : returns) { if (returnTok == tok) continue; - if (!ValueFlow::isLifetimeBorrowed(returnTok, settings)) - return; + if (!ValueFlow::isLifetimeBorrowed(returnTok, settings)) { + update = false; + break; + } const Variable *returnVar = ValueFlow::getLifetimeVariable(returnTok, settings); if (returnVar && returnVar->isArgument() && (returnVar->isConst() || !isVariableChanged(returnVar, settings))) { LifetimeStore ls = LifetimeStore::fromFunctionArg(f, tok, returnVar, tokenlist, settings, errorLogger); ls.inconclusive = inconclusive; ls.forward = false; + // The result is the argument when the parameter itself is returned + if (returnTok->variable() == returnVar) + ls.byValKind = LifetimeBoundByValKind{LifetimeBoundRelation::Same, astIsIterator(tok->next())}; update |= ls.byVal(tok->next(), tokenlist, errorLogger, settings); } for (const ValueFlow::Value &v : returnTok->values()) { @@ -2532,9 +2931,10 @@ static void valueFlowLifetimeFunction(Token *tok, const TokenList &tokenlist, Er (contains({ValueFlow::Value::LifetimeScope::ThisPointer, ValueFlow::Value::LifetimeScope::ThisValue}, v.lifetimeScope) || exprDependsOnThis(v.tokvalue))) { + // The returned expression refers to a member so it is a part of the object LifetimeStore ls = LifetimeStore{memtok, "Passed to member function '" + tok->expressionString() + "'.", - ValueFlow::Value::LifetimeKind::Object}; + getReturnedLifetimeKind(v, true)}; ls.inconclusive = inconclusive; ls.forward = false; ls.errorPath = v.errorPath; @@ -2559,12 +2959,27 @@ static void valueFlowLifetimeFunction(Token *tok, const TokenList &tokenlist, Er ls.errorPath = v.errorPath; ls.errorPath.emplace_front(returnTok, "Return " + lifetimeType(returnTok, &v) + "."); if (!v.isArgumentLifetimeValue() && (var->isReference() || var->isRValueReference())) { + const bool interior = v.lifetimeKind == ValueFlow::Value::LifetimeKind::Address && + isInteriorArgument(ls.argtok, settings); + ls.type = getReturnedLifetimeKind(v, interior); update |= ls.byRef(tok->next(), tokenlist, errorLogger, settings); } else if (v.isArgumentLifetimeValue()) { + ls.type = getReturnedLifetimeKind(v, false); update |= ls.byVal(tok->next(), tokenlist, errorLogger, settings); } } } + const std::vector boundArgs = getLifetimeBoundArgs(tok, f); + for (const LifetimeBoundArg& boundArg : boundArgs) + update |= valueFlowLifetimeBoundArg( + tok->next(), + boundArg, + boundArg.param ? "Passed to '" + tok->expressionString() + "'." + : "Passed to member function '" + tok->expressionString() + "'.", + boundArgs.size() > 1, + tokenlist, + errorLogger, + settings); if (update) valueFlowForwardLifetime(tok->next(), tokenlist, errorLogger, settings); } else if (tok->valueType()) { @@ -2748,7 +3163,8 @@ static void valueFlowLifetimeConstructor(Token* tok, const TokenList& tokenlist, } else if (vt.container && vt.type == ValueType::CONTAINER) { std::vector args = getArguments(tok); if (args.size() == 1 && vt.container->view && astIsContainerOwned(args.front())) { - LifetimeStore{args.front(), "Passed to container view.", ValueFlow::Value::LifetimeKind::SubObject} + // A view refers to the contents of the container + LifetimeStore{args.front(), "Passed to container view.", ValueFlow::Value::LifetimeKind::Object} .byRef(tok, tokenlist, errorLogger, settings); } else if (args.size() == 2 && (astIsIterator(args[0]) || astIsIterator(args[1]))) { LifetimeStore::forEach( @@ -3015,7 +3431,7 @@ static void valueFlowLifetime(TokenList &tokenlist, ErrorLogger &errorLogger, co value.lifetimeScope = ValueFlow::Value::LifetimeScope::Local; value.tokvalue = lt.token; value.errorPath = std::move(errorPath); - if (lt.addressOf || astIsPointer(lt.token) || !Token::Match(lt.token->astParent(), ".|[")) + if (!isInteriorLifetimeToken(lt)) value.lifetimeKind = ValueFlow::Value::LifetimeKind::Address; value.setInconclusive(lt.inconclusive); setTokenValue(tok, std::move(value), settings); @@ -3026,7 +3442,7 @@ static void valueFlowLifetime(TokenList &tokenlist, ErrorLogger &errorLogger, co // Converting to container view else if (astIsContainerOwned(tok) && isConvertedToView(tok, settings)) { LifetimeStore ls = - LifetimeStore{tok, "Converted to container view", ValueFlow::Value::LifetimeKind::SubObject}; + LifetimeStore{tok, "Converted to container view", ValueFlow::Value::LifetimeKind::Object}; ls.byRef(tok, tokenlist, errorLogger, settings); valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings); } diff --git a/lib/valueflow.h b/lib/valueflow.h index f701f55c418..9f42153e42e 100644 --- a/lib/valueflow.h +++ b/lib/valueflow.h @@ -71,7 +71,9 @@ namespace ValueFlow { struct LifetimeToken { const Token* token{}; ErrorPath errorPath; - bool addressOf{}; + // The expression is the object that the token refers to. When this is false, the expression is a part of that + // object such as a member or an element. + bool addressOf = true; bool inconclusive{}; LifetimeToken() = default; diff --git a/man/lifetimebound.md b/man/lifetimebound.md new file mode 100644 index 00000000000..154bf99d7d9 --- /dev/null +++ b/man/lifetimebound.md @@ -0,0 +1,442 @@ +--- +title: The lifetimebound attribute +subtitle: Version 2.23 dev +author: Cppcheck team +lang: en +documentclass: report +--- + +# Introduction + +This document describes how Cppcheck uses the `lifetimebound` attribute, what the attribute leaves unsaid, and how Cppcheck fills in the missing information. + +# The attribute + +The attribute says that the result of a function refers to an argument, so the result should not be used after the argument is gone. Cppcheck needs this when it cannot see the body of the function: + + const int* get(const int& x [[clang::lifetimebound]]); + + const int* f() { + int x = 0; + return get(x); + } + +Without the attribute Cppcheck does not know that the returned pointer has anything to do with `x`. With it we get: + + test.cpp:5:15: error: Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime] + +## Spelling + +These spellings are recognized: + + [[clang::lifetimebound]] + [[msvc::lifetimebound]] + __attribute__((lifetimebound)) + __attribute__((__lifetimebound__)) + +The attribute can be written on the declaration, on the definition, or on both. + +## Where it can be placed + +On a parameter, either after the parameter or before its type: + + const int& h(const int& x [[clang::lifetimebound]]); + const int& h([[clang::lifetimebound]] const int& x); + +After the declarator of a member function. It then applies to the object that the function is called on. On a parameter of a constructor, the constructed object refers to the argument. This example uses both: + + #include + + struct A { + const int& get() const [[clang::lifetimebound]]; + int x; + }; + + const int& f1() { + A a{}; + return a.get(); + } + + struct View { + View(const std::vector& v [[clang::lifetimebound]]); + const int* p; + }; + + View f2() { + std::vector v = {1}; + return View(v); + } + +In `f1` the returned reference is bound to `a`, and in `f2` the returned `View` is bound to `v`: + + test.cpp:10:17: error: Reference to local variable returned. [returnReference] + test.cpp:20:16: error: Returning object that points to local variable 'v' that will be invalid when returning. [returnDanglingLifetime] + +## Reference and value parameters + +When the parameter is a reference, the result refers to the argument itself. When the parameter is passed by value, such as a pointer, an iterator or a `std::string_view`, the result refers to whatever the argument refers to: + + const int* next(const int* p [[clang::lifetimebound]]); + + const int* f() { + int x = 0; + return next(&x); + } + +Here the result is bound to `x` and not to the temporary pointer `&x`: + + test.cpp:5:16: error: Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime] + +## Checks that use it + +The result of an annotated function is treated like any other pointer or reference with a known lifetime. So it is used by the checks for returning or storing something that refers to a local variable(`returnDanglingLifetime`, `returnReference`, `danglingLifetime`), for using it after the variable is out of scope(`invalidLifetime`), for references to temporaries(`danglingTempReference`), and for using it after a container has been modified(`invalidContainer`, `invalidContainerReference`). + +# The ambiguity + +The attribute says that the result refers to the argument. It does not say which part of the argument. Let's look at two functions that return a struct. One struct stores a pointer to the vector, and the other stores a pointer to the elements of the vector: + + #include + #include + + struct VectorRef { + const std::vector* vec; + }; + + struct DataRef { + const int* data; + }; + + VectorRef make_vector_ref(const std::vector& v [[clang::lifetimebound]]); + DataRef make_data_ref(const std::vector& v [[clang::lifetimebound]]); + + std::size_t f1() { + std::vector v = {1}; + VectorRef r = make_vector_ref(v); + v.push_back(2); + return r.vec->size(); + } + + int f2() { + std::vector v = {1}; + DataRef r = make_data_ref(v); + v.push_back(2); + return *r.data; + } + +Both functions have the same annotation, and it says the same thing for both: the result is bound to `v`. If either result outlives `v` then it is dangling, and Cppcheck reports that for both. + +However, `f1` and `f2` do exactly the same thing with the result, and only one of them is a bug: + +- `f1` is fine. `r.vec` points to the vector, and the vector is still at the same address after `push_back`. +- `f2` is a bug. `r.data` points to the elements, and `push_back` can move the elements to a new allocation. + +So the lifetime association is the same but the outcome is different. The attribute has no way to say which of the two a function returns, and this is why it is ambiguous. If Cppcheck assumed that the result always points to the contents, it would warn about `f1`. If it assumed that the result always points to the object itself, it would miss `f2`. + +# How Cppcheck resolves it + +By default Cppcheck assumes that the result refers to the object itself and not to its contents. This means the result is checked for dangling but not for invalidation. Cppcheck would rather miss a bug than report a false positive. + +For the example above this means that nothing is reported. `VectorRef` and `DataRef` do not show what they refer to, so `f2` is missed. + +The result is treated as referring to the contents only when there is evidence for it. The evidence comes from the types, from the argument, or from the function body. + +## Types + +When the function returns a pointer instead of a struct, the return type shows what it points to: + + #include + #include + + const std::vector* addr(const std::vector& v [[clang::lifetimebound]]); + const int* first(const std::vector& v [[clang::lifetimebound]]); + + std::size_t f1() { + std::vector v = {1}; + const std::vector* p = addr(v); + v.push_back(2); + return p->size(); + } + + int f2() { + std::vector v = {1}; + const int* p = first(v); + v.push_back(2); + return *p; + } + +This is the same pair as before, but now the types are different. `addr` returns a pointer to the type of the parameter, so the result is the vector itself. `first` returns a pointer to the element type of the vector, so the result points to the contents. Only `f2` is reported: + + test.cpp:18:13: error: Using pointer to local variable 'v' that may be invalid. [invalidContainer] + +The same works for iterators and references: + + #include + + std::vector::const_iterator find_first(const std::vector& v [[clang::lifetimebound]]); + const int& front(const std::vector& v [[clang::lifetimebound]]); + const std::vector& same(const std::vector& v [[clang::lifetimebound]]); + + int f1() { + std::vector v = {1}; + auto it = find_first(v); + v.push_back(2); + return *it; + } + + int f2() { + std::vector v = {1}; + const int& r = front(v); + v.push_back(2); + return r; + } + + int f3() { + std::vector v = {1}; + const std::vector& r = same(v); + v.push_back(2); + return r[0]; + } + +`find_first` returns an iterator of the container and `front` returns a reference to the element type, so `f1` and `f2` are reported. `same` returns a reference to the vector itself, so `f3` is not: + + test.cpp:11:13: error: Using iterator to local container 'v' that may be invalid. [invalidContainer] + test.cpp:18:12: error: Reference to v that may be invalid. [invalidContainerReference] + +A view such as `std::string_view` or `std::span` refers to the contents when it has the same element type as the container: + + #include + #include + #include + + std::string_view trim(const std::string& s [[clang::lifetimebound]]); + + std::size_t f() { + std::string s = " a "; + std::string_view sv = trim(s); + s += "b"; + return sv.size(); + } + +Appending to `s` can reallocate the characters that `sv` refers to: + + test.cpp:11:12: error: Using object that points to local variable 's' that may be invalid. [invalidContainer] + +These are the rules that Cppcheck uses when it compares the return type with the type of the bound parameter: + +| Return type | Parameter | The result refers to | +|---|---|---| +| iterator of the container | the same container type | the contents, as an iterator | +| pointer or reference to the element type | container | the contents | +| view with the same element type | container | the contents | +| pointer or reference to the same type | any type | the object itself | +| anything else | any type | the object itself, since nothing is known | + +The last row is the default. Here the return type does not show that the result points to an element: + + #include + + const void* raw(const std::vector& v [[clang::lifetimebound]]); + void write(const void* p); + + void f() { + std::vector v = {1}; + const void* p = raw(v); + v.push_back(2); + write(p); + } + +Nothing is reported for this. The structs in the previous section are in the last row as well. + +## The argument + +When the parameter is passed by value, the result refers to the same thing as the argument, in the same way. So what is known about the argument is carried over to the result: + + #include + #include + + const int* skip(const int* p [[clang::lifetimebound]]); + const std::vector* pass(const std::vector* p [[clang::lifetimebound]]); + + int f1() { + std::vector v = {1, 2}; + const int* p = skip(v.data()); + v.push_back(3); + return *p; + } + + std::size_t f2() { + std::vector v = {1, 2}; + const std::vector* p = pass(&v); + v.push_back(3); + return p->size(); + } + +`skip(v.data())` points to the contents of `v` because `v.data()` does. `pass(&v)` points to `v` itself because `&v` does. So only `f1` is reported: + + test.cpp:11:13: error: Using pointer to local variable 'v' that may be invalid. [invalidContainer] + +A view parameter always refers to the contents of the container that it was created from: + + #include + #include + #include + + std::string_view trim(std::string_view sv [[clang::lifetimebound]]); + + std::size_t f() { + std::string s = " a "; + std::string_view sv = trim(s); + s += "b"; + return sv.size(); + } + +The result of `trim` refers to the characters of `s`: + + test.cpp:11:12: error: Using object that points to local variable 's' that may be invalid. [invalidContainer] + +The same applies when a reference parameter is bound to an element of a container: + + #include + + const int& clamp(const int& x [[clang::lifetimebound]]); + + int f() { + std::vector v = {1}; + const int& r = clamp(v[0]); + v.push_back(2); + return r; + } + +The result is the same `int` as the argument, and the argument is an element of `v`: + + test.cpp:9:12: error: Reference to v that may be invalid. [invalidContainerReference] + +## The function body + +When the body of the function is available, Cppcheck also looks at what it returns. The body shows which part of the argument is returned even when the types do not. Let's go back to the two structs and add the function bodies: + + #include + #include + + struct VectorRef { + const std::vector* vec; + }; + + struct DataRef { + const int* data; + }; + + VectorRef make_vector_ref(const std::vector& v [[clang::lifetimebound]]) { + return VectorRef{&v}; + } + + DataRef make_data_ref(const std::vector& v [[clang::lifetimebound]]) { + return DataRef{v.data()}; + } + + std::size_t f1() { + std::vector v = {1}; + VectorRef r = make_vector_ref(v); + v.push_back(2); + return r.vec->size(); + } + + int f2() { + std::vector v = {1}; + DataRef r = make_data_ref(v); + v.push_back(2); + return *r.data; + } + +Now Cppcheck can see that `VectorRef` stores the address of the vector and that `DataRef` stores a pointer to the elements. So `f2` is reported and `f1` is not: + + test.cpp:31:13: error: Using object that points to local variable 'v' that may be invalid. [invalidContainer] + +The attribute and the body are combined like this: + +- When both say that the result refers to the same variable, the body decides whether it refers to the object itself or to its contents. +- The result refers to everything that either of them finds. +- A function with several return statements normally gives inconclusive results. When the attribute says the same thing as one of the return statements, the result is not inconclusive. + +In this example the body cannot be followed for `p`, since `lookup` is not defined, but the attribute covers it: + + const int* lookup(const int* p); + + const int* pick(const int* p [[clang::lifetimebound]], const int* q, bool b) { + if (b) + return lookup(p); + return q; + } + + const int* f1(const int* q) { + int x = 0; + return pick(&x, q, true); + } + + const int* f2(const int* p) { + int y = 0; + return pick(p, &y, false); + } + +The result of `pick` is bound to `p` because of the attribute, and to `q` because of the body. So `f1` is reported: + + test.cpp:11:16: error: Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime] + +`f2` is only reported with `--inconclusive`, because `q` is returned from one of two return statements and it has no attribute: + + test.cpp:16:16: error, inconclusive: Returning pointer to local variable 'y' that will be invalid when returning. [returnDanglingLifetime] + +When the parameter has the attribute, the result is not inconclusive even though there are two return statements: + + const int* find(const int* p [[clang::lifetimebound]], bool b) { + if (b) + return nullptr; + return p; + } + + const int* f() { + int x = 0; + return find(&x, false); + } + +This is reported without `--inconclusive`: + + test.cpp:9:16: error: Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime] + +## Several annotated parameters + +When more than one parameter has the attribute, Cppcheck does not know which one the result refers to: + + const int& max(const int& x [[clang::lifetimebound]], const int& y [[clang::lifetimebound]]); + + const int& f(const int& x) { + int y = 0; + return max(x, y); + } + +This is only reported with `--inconclusive`: + + test.cpp:5:15: error, inconclusive: Reference to local variable returned. [returnReference] + +Constructors are different, because the constructed object can refer to all of the annotated arguments: + + struct Pair { + Pair(const int& a [[clang::lifetimebound]], const int& b [[clang::lifetimebound]]); + const int* a; + const int* b; + }; + + Pair f(const int& a) { + int b = 0; + return Pair(a, b); + } + +This is reported without `--inconclusive`: + + test.cpp:9:16: error: Returning object that points to local variable 'b' that will be invalid when returning. [returnDanglingLifetime] + +# Limitations + +- The type comparison only works when the types are written the same way. `std::basic_string_view` from a `std::string` is not recognized as a view of the contents. +- A result that points to the contents but does not show it in its type, such as `const void*` or a struct, is only checked for invalidation when the function body is available. +- The attribute cannot say that the result refers to the contents. When the types do not show it and there is no body, invalidation bugs are missed. diff --git a/releasenotes.txt b/releasenotes.txt index 0212aab7a25..4f67cf5fcc8 100644 --- a/releasenotes.txt +++ b/releasenotes.txt @@ -13,7 +13,9 @@ New checks: - C/C++ support: -- +- The lifetime analysis now uses the lifetimebound attribute ([[clang::lifetimebound]], [[msvc::lifetimebound]] + and __attribute__((lifetimebound))) on function parameters, constructor parameters and member functions. + This finds dangling references and pointers when the body of the called function is not available. GUI: - diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index d5ab5855c32..bf55e223e54 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -161,6 +161,7 @@ class TestAutoVariables : public TestFixture { TEST_CASE(danglingLifetimeUniquePtr); TEST_CASE(danglingLifetime); TEST_CASE(danglingLifetimeFunction); + TEST_CASE(danglingLifetimeBound); TEST_CASE(danglingLifetimeUserConstructor); TEST_CASE(danglingLifetimeAggregateConstructor); TEST_CASE(danglingLifetimeInitList); @@ -941,6 +942,26 @@ class TestAutoVariables : public TestFixture { " free(p);\n" "}\n"); ASSERT_EQUALS("", errout_str()); + + // Only the function that returns the object itself gives the address of the variable + check("struct S {\n" + " S& self() { return *this; }\n" + " int& get() { return x; }\n" + " int x;\n" + "};\n" + "void f() {\n" + " S s;\n" + " S* p = &s.self();\n" + " delete p;\n" + "}\n" + "void g() {\n" + " S s;\n" + " int* p = &s.get();\n" + " delete p;\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:9:12]: (error) Deallocation of an auto-variable (s) results in undefined behaviour. [autovarInvalidDeallocation]\n", + errout_str()); } void testinvaliddealloc_string() { @@ -3646,7 +3667,7 @@ class TestAutoVariables : public TestFixture { " return by_value(v.begin());\n" "}\n"); ASSERT_EQUALS( - "[test.cpp:7:28] -> [test.cpp:7:28] -> [test.cpp:3:12] -> [test.cpp:3:25] -> [test.cpp:6:22] -> [test.cpp:7:20]: (error) Returning object that points to local variable 'v' that will be invalid when returning. [returnDanglingLifetime]\n", + "[test.cpp:7:28] -> [test.cpp:7:28] -> [test.cpp:3:12] -> [test.cpp:3:25] -> [test.cpp:6:22] -> [test.cpp:7:20]: (error) Returning lambda that captures local variable 'v' that will be invalid when returning. [returnDanglingLifetime]\n", errout_str()); check("template\n" @@ -3658,7 +3679,7 @@ class TestAutoVariables : public TestFixture { " return by_value(v.begin());\n" "}\n"); ASSERT_EQUALS( - "[test.cpp:7:28] -> [test.cpp:7:28] -> [test.cpp:3:12] -> [test.cpp:3:25] -> [test.cpp:6:22] -> [test.cpp:7:20]: (error) Returning object that points to local variable 'v' that will be invalid when returning. [returnDanglingLifetime]\n", + "[test.cpp:7:28] -> [test.cpp:7:28] -> [test.cpp:3:12] -> [test.cpp:3:25] -> [test.cpp:6:22] -> [test.cpp:7:20]: (error) Returning lambda that captures local variable 'v' that will be invalid when returning. [returnDanglingLifetime]\n", errout_str()); check("auto by_ref(int& x) {\n" @@ -3669,7 +3690,7 @@ class TestAutoVariables : public TestFixture { " return by_ref(i);\n" "}\n"); ASSERT_EQUALS( - "[test.cpp:2:12] -> [test.cpp:1:19] -> [test.cpp:2:25] -> [test.cpp:6:19] -> [test.cpp:5:9] -> [test.cpp:6:18]: (error) Returning object that points to local variable 'i' that will be invalid when returning. [returnDanglingLifetime]\n", + "[test.cpp:2:12] -> [test.cpp:1:19] -> [test.cpp:2:25] -> [test.cpp:6:19] -> [test.cpp:5:9] -> [test.cpp:6:18]: (error) Returning lambda that captures local variable 'i' that will be invalid when returning. [returnDanglingLifetime]\n", errout_str()); check("auto by_ref(const int& x) {\n" @@ -3709,6 +3730,398 @@ class TestAutoVariables : public TestFixture { ASSERT_EQUALS("", errout_str()); } + void danglingLifetimeBound() { + check("struct A { int x; };\n" + "const A& g(const A& a [[clang::lifetimebound]], const A& b);\n" + "const A& f(const A& b) {\n" + " A a{1};\n" + " return g(a, b);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:5:12] -> [test.cpp:5:13]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("struct A { int x; };\n" + "const A& g(const A& a [[clang::lifetimebound]], const A& b);\n" + "const A& f(const A& a) {\n" + " A b{1};\n" + " return g(a, b);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("struct A { int x; };\n" + "const int* g(const struct A* a __attribute__((lifetimebound)));\n" + "const int* f(void) {\n" + " struct A a = {1};\n" + " return g(&a);\n" + "}\n", dinit(CheckOptions, $.cpp = false)); + ASSERT_EQUALS( + "[test.c:5:14] -> [test.c:5:14] -> [test.c:4:14] -> [test.c:5:13]: (error) Returning pointer to local variable 'a' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("struct A { int x; };\n" + "const int* g(int n, [[clang::lifetimebound]] const A&);\n" + "const int* f() {\n" + " A a{1};\n" + " return g(0, a);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:5:17] -> [test.cpp:4:7] -> [test.cpp:5:13]: (error) Returning pointer to local variable 'a' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("const int& g(const int& x [[clang::lifetimebound]], bool b);\n" + "const int& g(const int& x, bool b) {\n" + " static int y = 0;\n" + " if (b)\n" + " return y;\n" + " return *std::addressof(x);\n" + "}\n" + "const int& f() {\n" + " int x = 0;\n" + " return g(x, false);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:10:12] -> [test.cpp:10:13]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("const int& max(const int& x [[clang::lifetimebound]], const int& y [[clang::lifetimebound]]);\n" + "const int& f(const int& x) {\n" + " int y = 0;\n" + " return max(x, y);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:12] -> [test.cpp:4:15]: (error, inconclusive) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("const int& max(const int& x [[clang::lifetimebound]], const int& y [[clang::lifetimebound]]);\n" + "const int& f(const int& x) {\n" + " int y = 0;\n" + " return max(x, y);\n" + "}\n", dinit(CheckOptions, $.inconclusive = false)); + ASSERT_EQUALS("", errout_str()); + + check("const int* g(const int* p [[clang::lifetimebound]]);\n" + "const int* f() {\n" + " int x = 0;\n" + " return g(&x);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:14] -> [test.cpp:4:14] -> [test.cpp:3:9] -> [test.cpp:4:13]: (error) Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("int& g(int* p [[clang::lifetimebound]]);\n" + "int& f() {\n" + " int x = 0;\n" + " int* p = &x;\n" + " return g(p);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:14] -> [test.cpp:5:12] -> [test.cpp:5:13]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("const int* g(const int* p [[clang::lifetimebound]], const int* q);\n" + "const int* f(const int* p) {\n" + " int x = 0;\n" + " return g(p, &x);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("std::string_view g(std::string_view sv [[clang::lifetimebound]]);\n" + "std::string_view f() {\n" + " std::string s;\n" + " return g(s);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:14] -> [test.cpp:4:14] -> [test.cpp:3:17] -> [test.cpp:4:13]: (error) Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("std::string_view g(const std::string& s [[clang::lifetimebound]]);\n" + "std::string_view f() {\n" + " std::string s;\n" + " return g(s);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:14] -> [test.cpp:3:17] -> [test.cpp:4:13]: (error) Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("const int* g(const int& x [[clang::lifetimebound]]);\n" + "void f(std::vector& v) {\n" + " int x = 0;\n" + " v.push_back(g(x));\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:19] -> [test.cpp:4:18] -> [test.cpp:3:9] -> [test.cpp:4:5]: (error) Non-local variable 'v' will use object that points to local variable 'x'. [danglingLifetime]\n", + errout_str()); + + check("struct A { int x; };\n" + "const A& g(const A& a [[clang::lifetimebound]]);\n" + "int f() {\n" + " const A& r = g(A{1});\n" + " return r.x;\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:4:16] -> [test.cpp:4:18] -> [test.cpp:5:12]: (error) Using reference to dangling temporary. [danglingTempReference]\n", + errout_str()); + + check("struct A { int x; };\n" + "const A& g(const A& a [[clang::lifetimebound]]);\n" + "int f() {\n" + " A a{1};\n" + " const A& r = g(a);\n" + " return r.x;\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("const int* g(const int& x [[clang::lifetimebound]]);\n" + "int f() {\n" + " const int* p = nullptr;\n" + " {\n" + " int x = 0;\n" + " p = g(x);\n" + " }\n" + " return *p;\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:6:15] -> [test.cpp:5:13] -> [test.cpp:8:13]: (error) Using pointer to local variable 'x' that is out of scope. [invalidLifetime]\n", + errout_str()); + + check("struct S {\n" + " const int& get() const [[clang::lifetimebound]];\n" + " const int* data() const __attribute__((lifetimebound));\n" + " int m;\n" + "};\n" + "const int& f1() {\n" + " S s{};\n" + " return s.get();\n" + "}\n" + "const int* f2() {\n" + " S s{};\n" + " return s.data();\n" + "}\n" + "const int& f3(const S& s) {\n" + " return s.get();\n" + "}\n" + "const int* f4(const S* s) {\n" + " return s->data();\n" + "}\n" + "const int& f5() {\n" + " static S s{};\n" + " return s.get();\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:8:14] -> [test.cpp:8:17]: (error) Reference to local variable returned. [returnReference]\n" + "[test.cpp:12:12] -> [test.cpp:11:7] -> [test.cpp:12:18]: (error) Returning pointer to local variable 's' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("struct S;\n" + "const int& lookup(const S& s);\n" + "struct S {\n" + " const int& get() const;\n" + " int m;\n" + "};\n" + "const int& S::get() const [[clang::lifetimebound]] {\n" + " return lookup(*this);\n" + "}\n" + "const int& f() {\n" + " S s{};\n" + " return s.get();\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:12:14] -> [test.cpp:12:17]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("struct S {\n" + " const int* find(const int& x) const [[clang::lifetimebound]];\n" + " const int* at(const int& x [[clang::lifetimebound]]) const;\n" + "};\n" + "const int* f1(const S& s) {\n" + " int x = 0;\n" + " return s.find(x);\n" + "}\n" + "const int* f2(const S& s) {\n" + " int x = 0;\n" + " return s.at(x);\n" + "}\n" + "const int* f3(const int& x) {\n" + " S s;\n" + " return s.at(x);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:11:17] -> [test.cpp:10:9] -> [test.cpp:11:16]: (error) Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("template\n" + "struct Opt {\n" + " const T& value() const [[clang::lifetimebound]];\n" + " T t;\n" + "};\n" + "const int& f() {\n" + " Opt o{};\n" + " return o.value();\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:8:14] -> [test.cpp:8:19]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("template\n" + "struct Opt {\n" + " const T& value_or(const T& d [[clang::lifetimebound]]) const;\n" + " T t;\n" + "};\n" + "const int& f(const Opt& o) {\n" + " int d = 0;\n" + " return o.value_or(d);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:8:14] -> [test.cpp:8:22]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("struct View {\n" + " View(const std::string& s [[clang::lifetimebound]], int n);\n" + " const char* p;\n" + "};\n" + "View f1() {\n" + " std::string s;\n" + " return View(s, 1);\n" + "}\n" + "View f2() {\n" + " std::string s;\n" + " View v(s, 1);\n" + " return v;\n" + "}\n" + "View f3(const std::string& s) {\n" + " int n = 1;\n" + " return View(s, n);\n" + "}\n", dinit(CheckOptions, $.inconclusive = false)); + ASSERT_EQUALS( + "[test.cpp:7:17] -> [test.cpp:6:17] -> [test.cpp:7:16]: (error) Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]\n" + "[test.cpp:11:12] -> [test.cpp:10:17] -> [test.cpp:12:12]: (error) Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("struct View {\n" + " View(const std::string& s, const int* p [[clang::lifetimebound]]);\n" + " const int* p;\n" + "};\n" + "View f1() {\n" + " std::string s;\n" + " static int x = 0;\n" + " return View(s, &x);\n" + "}\n" + "View f2(const std::string& s) {\n" + " int x = 0;\n" + " return View(s, &x);\n" + "}\n", dinit(CheckOptions, $.inconclusive = false)); + ASSERT_EQUALS( + "[test.cpp:12:20] -> [test.cpp:12:20] -> [test.cpp:11:9] -> [test.cpp:12:16]: (error) Returning object that points to local variable 'x' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + // The lifetimes from the function body and from the attribute are both used + check("const int* h(const int* p);\n" + "const int* g(const int* p [[clang::lifetimebound]], const int* q, bool b) {\n" + " if (b)\n" + " return h(p);\n" + " return q;\n" + "}\n" + "const int* f1(const int* q) {\n" + " int x = 0;\n" + " return g(&x, q, true);\n" + "}\n" + "const int* f2(const int* p) {\n" + " int y = 0;\n" + " return g(p, &y, false);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:9:14] -> [test.cpp:9:14] -> [test.cpp:8:9] -> [test.cpp:9:13]: (error) Returning pointer to local variable 'x' that will be invalid when returning. [returnDanglingLifetime]\n" + "[test.cpp:13:17] -> [test.cpp:13:17] -> [test.cpp:12:9] -> [test.cpp:13:13]: (error, inconclusive) Returning pointer to local variable 'y' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + check("const int& h(const int& x);\n" + "const int& g(const int& x [[clang::lifetimebound]], const int& y, bool b) {\n" + " if (b)\n" + " return h(x);\n" + " return y;\n" + "}\n" + "const int& f1(const int& y) {\n" + " int x = 0;\n" + " return g(x, y, true);\n" + "}\n" + "const int& f2(const int& x) {\n" + " int y = 0;\n" + " return g(x, y, false);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:9:12] -> [test.cpp:9:13]: (error) Reference to local variable returned. [returnReference]\n" + "[test.cpp:2:65] -> [test.cpp:5:12] -> [test.cpp:13:12] -> [test.cpp:13:13]: (error, inconclusive) Reference to local variable returned. [returnReference]\n", + errout_str()); + + // The attribute makes a lifetime from one of several return statements conclusive + check("const int& g(const int& x [[clang::lifetimebound]], bool b) {\n" + " static int y = 0;\n" + " if (b)\n" + " return y;\n" + " return x;\n" + "}\n" + "const int& f() {\n" + " int x = 0;\n" + " return g(x, false);\n" + "}\n", dinit(CheckOptions, $.inconclusive = false)); + ASSERT_EQUALS( + "[test.cpp:1:51] -> [test.cpp:5:12] -> [test.cpp:9:12] -> [test.cpp:9:13]: (error) Reference to local variable returned. [returnReference]\n", + errout_str()); + + check("const char* get(const std::string& s);\n" + "struct View {\n" + " View(const std::string& s [[clang::lifetimebound]], const int* q) : mq(q) { mp = get(s); }\n" + " const char* mp;\n" + " const int* mq;\n" + "};\n" + "View f1(const std::string& s) {\n" + " int x = 0;\n" + " return View(s, &x);\n" + "}\n" + "View f2(const int* q) {\n" + " std::string s;\n" + " return View(s, q);\n" + "}\n", dinit(CheckOptions, $.inconclusive = false)); + ASSERT_EQUALS( + "[test.cpp:9:20] -> [test.cpp:9:20] -> [test.cpp:8:9] -> [test.cpp:9:16]: (error) Returning object that points to local variable 'x' that will be invalid when returning. [returnDanglingLifetime]\n" + "[test.cpp:13:17] -> [test.cpp:12:17] -> [test.cpp:13:16]: (error) Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + // The constructed object can refer to both arguments so this is not inconclusive + check("struct Pair {\n" + " Pair(const int& a [[clang::lifetimebound]], const int& b [[clang::lifetimebound]]);\n" + " const int* a;\n" + " const int* b;\n" + "};\n" + "Pair f(const int& a) {\n" + " int b = 0;\n" + " return Pair(a, b);\n" + "}\n", dinit(CheckOptions, $.inconclusive = false)); + ASSERT_EQUALS( + "[test.cpp:8:20] -> [test.cpp:7:9] -> [test.cpp:8:16]: (error) Returning object that points to local variable 'b' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + + // An argument for a parameter without the attribute is still inconclusive + check("struct Pair {\n" + " Pair(const int& a [[clang::lifetimebound]], const int* b);\n" + " const int* a;\n" + " const int* b;\n" + "};\n" + "Pair f1(const int& a) {\n" + " int b = 0;\n" + " return Pair(a, &b);\n" + "}\n" + "Pair f2(const int* b) {\n" + " int a = 0;\n" + " return Pair(a, b);\n" + "}\n"); + ASSERT_EQUALS( + "[test.cpp:8:20] -> [test.cpp:8:20] -> [test.cpp:7:9] -> [test.cpp:8:16]: (error, inconclusive) Returning object that points to local variable 'b' that will be invalid when returning. [returnDanglingLifetime]\n" + "[test.cpp:12:17] -> [test.cpp:11:9] -> [test.cpp:12:16]: (error) Returning object that points to local variable 'a' that will be invalid when returning. [returnDanglingLifetime]\n", + errout_str()); + } + void danglingLifetimeUserConstructor() { check("struct A {\n" @@ -4427,7 +4840,7 @@ class TestAutoVariables : public TestFixture { " return y();\n" "}\n"); ASSERT_EQUALS( - "[test.cpp:3:12] -> [test.cpp:2:13] -> [test.cpp:4:16] -> [test.cpp:8:16] -> [test.cpp:8:16] -> [test.cpp:9:12]: (error) Using object that is a temporary. [danglingTemporaryLifetime]\n", + "[test.cpp:3:12] -> [test.cpp:2:13] -> [test.cpp:4:16] -> [test.cpp:8:16] -> [test.cpp:8:16] -> [test.cpp:9:12]: (error) Using lambda that is a temporary. [danglingTemporaryLifetime]\n", errout_str()); } @@ -4643,7 +5056,7 @@ class TestAutoVariables : public TestFixture { " return A().f();\n" "}\n"); ASSERT_EQUALS( - "[test.cpp:4:16] -> [test.cpp:4:28] -> [test.cpp:8:13] -> [test.cpp:8:17]: (error) Returning object that will be invalid when returning. [returnDanglingLifetime]\n", + "[test.cpp:4:16] -> [test.cpp:4:28] -> [test.cpp:8:13] -> [test.cpp:8:17]: (error) Returning lambda that will be invalid when returning. [returnDanglingLifetime]\n", errout_str()); check("struct A {\n" @@ -4668,7 +5081,7 @@ class TestAutoVariables : public TestFixture { " return A{&i}.f();\n" "}\n"); ASSERT_EQUALS( - "[test.cpp:9:14] -> [test.cpp:9:14] -> [test.cpp:9:13] -> [test.cpp:4:16] -> [test.cpp:4:18] -> [test.cpp:8:9] -> [test.cpp:9:19]: (error) Returning object that points to local variable 'i' that will be invalid when returning. [returnDanglingLifetime]\n", + "[test.cpp:9:14] -> [test.cpp:9:14] -> [test.cpp:9:13] -> [test.cpp:4:16] -> [test.cpp:4:18] -> [test.cpp:8:9] -> [test.cpp:9:19]: (error) Returning lambda that captures local variable 'i' that will be invalid when returning. [returnDanglingLifetime]\n", errout_str()); check("struct S {\n" diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index d639ec142eb..7883a8e6f9b 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -6163,6 +6163,18 @@ class TestBufferOverrun : public TestFixture { " g(q);\n" "}\n"); ASSERT_EQUALS("", errout_str()); + + check("struct W {\n" + " const int* p;\n" + " int operator[](int i) const;\n" + "};\n" + "W wrap(const int& x) { return W{&x}; }\n" + "int f() {\n" + " int x = 0;\n" + " W w = wrap(x);\n" + " return w[1];\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); } void checkPipeParameterSize() { // #3521 diff --git a/test/teststl.cpp b/test/teststl.cpp index a6a133af13f..a47a7cf0ffd 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -176,6 +176,8 @@ class TestStl : public TestFixture { TEST_CASE(loopAlgoMultipleReturn); TEST_CASE(invalidContainer); + TEST_CASE(invalidContainerLifetimeBound); + TEST_CASE(invalidContainerFunction); TEST_CASE(invalidContainerLoop); TEST_CASE(findInsert); @@ -7166,6 +7168,639 @@ class TestStl : public TestFixture { ASSERT_EQUALS( "[test.cpp:7:17] -> [test.cpp:7:24] -> [test.cpp:8:10] -> [test.cpp:9:18]: (error) Reference to vec1 that may be invalid. [invalidContainerReference]\n", errout_str()); + + // A reference to the container itself stays valid + check("int f() {\n" + " std::vector v = {1};\n" + " const std::vector& r = v;\n" + " v.push_back(1);\n" + " return r.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("int f() {\n" + " std::vector v = {1};\n" + " std::vector* p = &v;\n" + " const std::vector& r = *p;\n" + " v.push_back(1);\n" + " return r.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("int f() {\n" + " std::vector v = {1};\n" + " std::vector* p = &v;\n" + " const int* q = &(*p)[0];\n" + " v.push_back(1);\n" + " return *q;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:3:27] -> [test.cpp:4:20] -> [test.cpp:5:7] -> [test.cpp:2:22] -> [test.cpp:6:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("int f() {\n" + " std::vector v = {1};\n" + " const int* q = &*std::begin(v);\n" + " v.push_back(1);\n" + " return *q;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:3:32] -> [test.cpp:3:20] -> [test.cpp:3:20] -> [test.cpp:4:7] -> [test.cpp:2:22] -> [test.cpp:5:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + // A view refers to the contents of the container + check("int f() {\n" + " std::string s = \"a\";\n" + " std::string_view sv = s;\n" + " s += \"x\";\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:3:27] -> [test.cpp:4:7] -> [test.cpp:2:17] -> [test.cpp:5:12]: (error) Using object that points to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("int f() {\n" + " std::vector v = {1};\n" + " std::span sp = v;\n" + " v.push_back(1);\n" + " return sp[0];\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:3:25] -> [test.cpp:4:7] -> [test.cpp:2:22] -> [test.cpp:5:12]: (error) Using object that points to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("int f() {\n" + " std::string s = \"a\";\n" + " std::string_view sv = s;\n" + " s[0] = 'b';\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("int f() {\n" + " std::string s = \"a\";\n" + " std::string_view sv = s;\n" + " s += \"x\";\n" + " sv = s;\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("struct T { std::string_view sv; };\n" + "int f() {\n" + " std::string s = \"a\";\n" + " T t{s};\n" + " s += \"x\";\n" + " return t.sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:9] -> [test.cpp:5:7] -> [test.cpp:3:17] -> [test.cpp:6:12]: (error) Using object that points to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + } + + void invalidContainerLifetimeBound() { + // The types show that the result refers to the contents of the container + check("const int* first(const std::vector& v [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int* p = first(v);\n" + " v.push_back(1);\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:26] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("std::vector::const_iterator iter(const std::vector& v [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " auto it = iter(v);\n" + " v.push_back(1);\n" + " return *it;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:20] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:13]: (error) Using iterator to local container 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const int& front(const std::vector& v [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int& r = front(v);\n" + " v.push_back(1);\n" + " return r;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:18] -> [test.cpp:4:20] -> [test.cpp:5:7] -> [test.cpp:6:12]: (error) Reference to v that may be invalid. [invalidContainerReference]\n", + errout_str()); + + check("const int* at(const std::vector* p [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int* p = at(&v);\n" + " v.push_back(1);\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:23] -> [test.cpp:4:23] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + // The element type is not declared + check("const A* first(const std::vector& v [[clang::lifetimebound]]);\n" + "int f(const A& a) {\n" + " std::vector v = {a};\n" + " const A* p = first(v);\n" + " v.push_back(a);\n" + " return p->x;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:24] -> [test.cpp:5:7] -> [test.cpp:3:20] -> [test.cpp:6:12]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const char* str(const std::string& s [[clang::lifetimebound]]);\n" + "char f() {\n" + " std::string s;\n" + " const char* p = str(s);\n" + " s += \"x\";\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:25] -> [test.cpp:5:7] -> [test.cpp:3:17] -> [test.cpp:6:13]: (error) Using pointer to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + + // The argument already refers to the contents of the container + check("const int* fwd(const int* p [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int* p = fwd(v.data());\n" + " v.push_back(1);\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:30] -> [test.cpp:4:30] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("std::vector::const_iterator next(std::vector::const_iterator it [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " auto it = next(v.begin());\n" + " v.push_back(1);\n" + " return *it;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:27] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:13]: (error) Using iterator to local container 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const int& ref(const int& x [[clang::lifetimebound]]);\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int& r = ref(v[0]);\n" + " v.push_back(1);\n" + " return r;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:18] -> [test.cpp:4:20] -> [test.cpp:5:7] -> [test.cpp:6:12]: (error) Reference to v that may be invalid. [invalidContainerReference]\n", + errout_str()); + + // The result refers to the container itself + check("const std::vector* addr(const std::vector& v [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector* p = addr(v);\n" + " v.push_back(1);\n" + " return p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const std::vector& same(const std::vector& v [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector& r = same(v);\n" + " v.push_back(1);\n" + " return r.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const std::vector* fwd(const std::vector* p [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector* p = fwd(&v);\n" + " v.push_back(1);\n" + " return p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + // The types do not show what the result refers to + check("const long* get(const std::vector& v [[clang::lifetimebound]]);\n" + "long f() {\n" + " std::vector v = {1};\n" + " const long* p = get(v);\n" + " v.push_back(1);\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("std::vector::const_iterator iter(const std::vector& v [[clang::lifetimebound]]);\n" + "long f() {\n" + " std::vector v = {1};\n" + " auto it = iter(v);\n" + " v.push_back(1);\n" + " return *it;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + // A view of the elements of the container + check("std::string_view view(const std::string& s [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::string s;\n" + " std::string_view sv = view(s);\n" + " s += \"x\";\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:32] -> [test.cpp:5:7] -> [test.cpp:3:17] -> [test.cpp:6:12]: (error) Using object that points to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("std::span view(const std::vector& v [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " std::span s = view(v);\n" + " v.push_back(1);\n" + " return s.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:35] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:12]: (error) Using object that points to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + // A view that is passed by value refers to the contents of the container + check("std::string_view trim(std::string_view sv [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::string s;\n" + " std::string_view sv = trim(s);\n" + " s += \"x\";\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:32] -> [test.cpp:4:32] -> [test.cpp:5:7] -> [test.cpp:3:17] -> [test.cpp:6:12]: (error) Using object that points to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const char* ptr(std::string_view sv [[clang::lifetimebound]]);\n" + "char f() {\n" + " std::string s;\n" + " const char* p = ptr(s);\n" + " s += \"x\";\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:4:25] -> [test.cpp:4:25] -> [test.cpp:5:7] -> [test.cpp:3:17] -> [test.cpp:6:13]: (error) Using pointer to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + + // The view has a different element type + check("std::string_view name(const std::vector& v [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " std::string_view sv = name(v);\n" + " v.push_back(1);\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("std::span view(const std::vector& v [[clang::lifetimebound]]);\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " std::span s = view(v);\n" + " v.push_back(1);\n" + " return s.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + // The types do not show that the result refers to an element but the function body does + check("const void* raw(const std::vector& v [[clang::lifetimebound]]);\n" + "void use(const void*);\n" + "void f() {\n" + " std::vector v = {1};\n" + " const void* p = raw(v);\n" + " v.push_back(1);\n" + " use(p);\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const void* raw(const std::vector& v [[clang::lifetimebound]]) {\n" + " return v.data();\n" + "}\n" + "void use(const void*);\n" + "void f() {\n" + " std::vector v = {1};\n" + " const void* p = raw(v);\n" + " v.push_back(1);\n" + " use(p);\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:2:18] -> [test.cpp:1:67] -> [test.cpp:2:18] -> [test.cpp:7:25] -> [test.cpp:8:7] -> [test.cpp:6:22] -> [test.cpp:9:9]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + // The lifetime is conclusive because of the attribute and it has the kind from the function body + check("const void* raw(const std::vector& v [[clang::lifetimebound]]) {\n" + " if (v.empty())\n" + " return nullptr;\n" + " return v.data();\n" + "}\n" + "void use(const void*);\n" + "void f() {\n" + " std::vector v = {1};\n" + " const void* p = raw(v);\n" + " v.push_back(1);\n" + " use(p);\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:9:25] -> [test.cpp:10:7] -> [test.cpp:8:22] -> [test.cpp:11:9]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const std::vector* addr(const std::vector& v [[clang::lifetimebound]]) {\n" + " return &v;\n" + "}\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector* p = addr(v);\n" + " v.push_back(1);\n" + " return p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const long& get(const std::map& m [[clang::lifetimebound]]) {\n" + " return m.at(0);\n" + "}\n" + "long f(std::map& m) {\n" + " const long& r = get(m);\n" + " m.clear();\n" + " return r;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:5:19] -> [test.cpp:2:14] -> [test.cpp:1:70] -> [test.cpp:2:16] -> [test.cpp:5:21] -> [test.cpp:4:30] -> [test.cpp:6:7] -> [test.cpp:7:12]: (error) Reference to m that may be invalid. [invalidContainerReference]\n", + errout_str()); + + // Constructors + check("struct ElemRef {\n" + " ElemRef(const int& x [[clang::lifetimebound]]);\n" + " const int* p;\n" + "};\n" + "int f() {\n" + " std::vector v = {1};\n" + " ElemRef r(v[0]);\n" + " v.push_back(2);\n" + " return *r.p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:7:16] -> [test.cpp:8:7] -> [test.cpp:6:22] -> [test.cpp:9:13]: (error) Using object that points to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("struct DataPtr {\n" + " DataPtr(const int* p [[clang::lifetimebound]]);\n" + " const int* p;\n" + "};\n" + "int f() {\n" + " std::vector v = {1};\n" + " DataPtr r(v.data());\n" + " v.push_back(2);\n" + " return *r.p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:7:21] -> [test.cpp:7:21] -> [test.cpp:8:7] -> [test.cpp:6:22] -> [test.cpp:9:13]: (error) Using object that points to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("struct VecRef {\n" + " VecRef(const std::vector& v [[clang::lifetimebound]]);\n" + " const std::vector* p;\n" + "};\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " VecRef r(v);\n" + " v.push_back(2);\n" + " return r.p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("struct VecPtr {\n" + " VecPtr(const std::vector* p [[clang::lifetimebound]]);\n" + " const std::vector* p;\n" + "};\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " VecPtr r(&v);\n" + " v.push_back(2);\n" + " return r.p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + } + + // The result of a call has the kind of lifetime that the returned expression has + void invalidContainerFunction() { + check("const std::vector* addr(const std::vector& v) {\n" + " return &v;\n" + "}\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector* p = addr(v);\n" + " v.push_back(1);\n" + " return p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const std::vector& same(const std::vector& v) {\n" + " return v;\n" + "}\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector& r = same(v);\n" + " v.push_back(1);\n" + " return r.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const std::vector* fwd(const std::vector* p) {\n" + " return p;\n" + "}\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " const std::vector* p = fwd(&v);\n" + " v.push_back(1);\n" + " return p->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("const int* fwd(const int* p) {\n" + " return p;\n" + "}\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int* p = fwd(v.data());\n" + " v.push_back(1);\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:6:30] -> [test.cpp:6:30] -> [test.cpp:7:7] -> [test.cpp:5:22] -> [test.cpp:8:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const int* first(const std::vector& v) {\n" + " return v.data();\n" + "}\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int* p = first(v);\n" + " v.push_back(1);\n" + " return *p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:2:18] -> [test.cpp:1:43] -> [test.cpp:2:18] -> [test.cpp:6:26] -> [test.cpp:7:7] -> [test.cpp:5:22] -> [test.cpp:8:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("std::vector::const_iterator iter(const std::vector& v) {\n" + " return v.begin();\n" + "}\n" + "int f() {\n" + " std::vector v = {1};\n" + " auto it = iter(v);\n" + " v.push_back(1);\n" + " return *it;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:2:19] -> [test.cpp:1:64] -> [test.cpp:2:19] -> [test.cpp:6:20] -> [test.cpp:7:7] -> [test.cpp:5:22] -> [test.cpp:8:13]: (error) Using iterator to local container 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("const int& front(const std::vector& v) {\n" + " return v[0];\n" + "}\n" + "int f(std::vector& v) {\n" + " const int& r = front(v);\n" + " v.push_back(1);\n" + " return r;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:5:18] -> [test.cpp:1:43] -> [test.cpp:2:13] -> [test.cpp:5:20] -> [test.cpp:4:26] -> [test.cpp:6:7] -> [test.cpp:7:12]: (error) Reference to v that may be invalid. [invalidContainerReference]\n", + errout_str()); + + check("std::string_view view(const std::string& s) {\n" + " return s;\n" + "}\n" + "std::size_t f() {\n" + " std::string s;\n" + " std::string_view sv = view(s);\n" + " s += \"x\";\n" + " return sv.size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:2:12] -> [test.cpp:1:43] -> [test.cpp:2:12] -> [test.cpp:6:32] -> [test.cpp:7:7] -> [test.cpp:5:17] -> [test.cpp:8:12]: (error) Using object that points to local variable 's' that may be invalid. [invalidContainer]\n", + errout_str()); + + // The returned object stores a pointer or an iterator to the contents of the container + check("struct P { const int* p; };\n" + "P mk(const std::vector& v) {\n" + " return P{v.data()};\n" + "}\n" + "int f() {\n" + " std::vector v = {1};\n" + " P x = mk(v);\n" + " v.push_back(1);\n" + " return *x.p;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:3:13] -> [test.cpp:2:31] -> [test.cpp:3:20] -> [test.cpp:2:31] -> [test.cpp:3:20] -> [test.cpp:7:14] -> [test.cpp:8:7] -> [test.cpp:6:22] -> [test.cpp:9:13]: (error) Using object that points to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("auto lam(const std::vector& v) {\n" + " auto it = v.begin();\n" + " return [=] { return *it; };\n" + "}\n" + "int f() {\n" + " std::vector v = {1};\n" + " auto g = lam(v);\n" + " v.push_back(1);\n" + " return g();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:3:12] -> [test.cpp:1:35] -> [test.cpp:2:22] -> [test.cpp:1:35] -> [test.cpp:3:26] -> [test.cpp:7:18] -> [test.cpp:8:7] -> [test.cpp:6:22] -> [test.cpp:9:12]: (error) Using object that points to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("auto lam(const std::vector& v) {\n" + " return [&] { return v.size(); };\n" + "}\n" + "std::size_t f() {\n" + " std::vector v = {1};\n" + " auto g = lam(v);\n" + " v.push_back(1);\n" + " return g();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); + + check("int& first(std::vector& x) { return x[0]; }\n" + "int f() {\n" + " std::vector v = {1};\n" + " const int* q = &first(v);\n" + " v.push_back(1);\n" + " return *q;\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS( + "[test.cpp:1:31] -> [test.cpp:1:43] -> [test.cpp:4:21] -> [test.cpp:4:20] -> [test.cpp:5:7] -> [test.cpp:3:22] -> [test.cpp:6:13]: (error) Using pointer to local variable 'v' that may be invalid. [invalidContainer]\n", + errout_str()); + + check("std::vector& same(std::vector& x) { return x; }\n" + "int f() {\n" + " std::vector v = {1};\n" + " const std::vector* q = &same(v);\n" + " v.push_back(1);\n" + " return q->size();\n" + "}\n", + dinit(CheckOptions, $.inconclusive = true)); + ASSERT_EQUALS("", errout_str()); } void invalidContainerLoop() { diff --git a/test/testsymboldatabase.cpp b/test/testsymboldatabase.cpp index 85ee8430a77..b494ce7c362 100644 --- a/test/testsymboldatabase.cpp +++ b/test/testsymboldatabase.cpp @@ -574,6 +574,7 @@ class TestSymbolDatabase : public TestFixture { TEST_CASE(noreturnAttributeFunction); TEST_CASE(nodiscardAttributeFunction); + TEST_CASE(lifetimeBoundAttribute); TEST_CASE(varTypesIntegral); // known integral TEST_CASE(varTypesFloating); // known floating @@ -9609,6 +9610,83 @@ class TestSymbolDatabase : public TestFixture { ASSERT_EQUALS(true, func->isAttributeNodiscard()); } + void lifetimeBoundAttribute() { + GET_SYMBOL_DB("struct A { int x; };\n" + "const A& func1(const A& a [[clang::lifetimebound]], const A& b);\n" + "const A& func2(int n, [[clang::lifetimebound]] const A& a);\n" + "const A& func3(const A& a __attribute__((lifetimebound)), const A& b);\n" + "const A& func4(__attribute__((lifetimebound)) const A&, const A&);\n" + "const A& func5(const std::map& m [[_Clang::__lifetimebound__]], std::map n);\n" + "const A& func6(const A& a [[clang::lifetimebound]], const A& b);\n" + "const A& func6(const A& a, const A& b) { return a.x ? a : b; }\n" + "const A& func7(const A& a, const A& b);\n" + "const A& func7(const A& a, const A& b [[clang::lifetimebound]]) { return a.x ? a : b; }\n" + "template const T& func8(const T& a [[clang::lifetimebound]] = T{}, const T& b = T{}) { return a; }\n" + "void func9() { int i = 0; func8(i); }\n" + "struct S {\n" + " S(const A& a [[clang::lifetimebound]], const A& b);\n" + " const int& mem1() const [[clang::lifetimebound]];\n" + " const int* mem2(const A& a) const noexcept __attribute__((lifetimebound));\n" + " const int& mem3(const A& a [[clang::lifetimebound]]) const;\n" + " const int& mem4() const;\n" + " int i;\n" + "};\n" + "const int& S::mem4() const [[clang::lifetimebound]] { return i; }\n"); + ASSERT_EQUALS("", errout_str()); + ASSERT(db != nullptr); + + const Scope* const globalScope = &db->scopeList.front(); + const struct { + const char* name; + bool arg0; + bool arg1; + } funcs[] = { + {"func1", true, false}, + {"func2", false, true}, + {"func3", true, false}, + {"func4", true, false}, + {"func5", true, false}, + {"func6", true, false}, + {"func7", false, true}, + {"func8 < int >", true, false}, + }; + for (const auto& expected : funcs) { + const Function* func = findFunctionByName(expected.name, globalScope); + ASSERT_MSG(func != nullptr, expected.name); + ASSERT_EQUALS_MSG(false, func->isAttributeLifetimeBound(), expected.name); + ASSERT_EQUALS_MSG(2U, func->argCount(), expected.name); + ASSERT_EQUALS_MSG(expected.arg0, func->getArgumentVar(0)->isLifetimeBound(), expected.name); + ASSERT_EQUALS_MSG(expected.arg1, func->getArgumentVar(1)->isLifetimeBound(), expected.name); + } + + const Scope* const classScope = db->findScopeByName("S"); + ASSERT(classScope != nullptr); + + const Function* func = findFunctionByName("S", classScope); + ASSERT(func != nullptr); + ASSERT_EQUALS(false, func->isAttributeLifetimeBound()); + ASSERT_EQUALS(true, func->getArgumentVar(0)->isLifetimeBound()); + ASSERT_EQUALS(false, func->getArgumentVar(1)->isLifetimeBound()); + + func = findFunctionByName("mem1", classScope); + ASSERT(func != nullptr); + ASSERT_EQUALS(true, func->isAttributeLifetimeBound()); + + func = findFunctionByName("mem2", classScope); + ASSERT(func != nullptr); + ASSERT_EQUALS(true, func->isAttributeLifetimeBound()); + ASSERT_EQUALS(false, func->getArgumentVar(0)->isLifetimeBound()); + + func = findFunctionByName("mem3", classScope); + ASSERT(func != nullptr); + ASSERT_EQUALS(false, func->isAttributeLifetimeBound()); + ASSERT_EQUALS(true, func->getArgumentVar(0)->isLifetimeBound()); + + func = findFunctionByName("mem4", classScope); + ASSERT(func != nullptr); + ASSERT_EQUALS(true, func->isAttributeLifetimeBound()); + } + void varTypesIntegral() { GET_SYMBOL_DB("void f() { bool b; char c; unsigned char uc; short s; unsigned short us; int i; unsigned u; unsigned int ui; long l; unsigned long ul; long long ll; }\n"); const Variable *b = db->getVariableFromVarId(1); diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 8822a66fc27..587e1626fcc 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -299,6 +299,7 @@ class TestTokenizer : public TestFixture { TEST_CASE(cppMaybeUnusedAfter2); TEST_CASE(cppMaybeUnusedAfter3); TEST_CASE(cppMaybeUnusedStructuredBinding); + TEST_CASE(lifetimeBoundAttribute); TEST_CASE(attributeAlignasBefore); TEST_CASE(attributeAlignasAfter); @@ -4622,6 +4623,109 @@ class TestTokenizer : public TestFixture { ASSERT(var2 && var2->isAttributeMaybeUnused()); } + void lifetimeBoundAttribute() { + { + const char code[] = "const int& f(const int& x [[clang::lifetimebound]], [[clang::lifetimebound]] const int& y, const int& z);\n"; + const char expected[] = "const int & f ( const int & x , const int & y , const int & z ) ;"; + + SimpleTokenizer tokenizer(settingsDefault, *this); + ASSERT(tokenizer.tokenize(code)); + + ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false)); + + const Token* f = Token::findsimplematch(tokenizer.tokens(), "f"); + ASSERT(f && !f->isAttributeLifetimeBound()); + const Token* x = Token::findsimplematch(tokenizer.tokens(), "x"); + ASSERT(x && x->isAttributeLifetimeBound()); + const Token* y = Token::findsimplematch(tokenizer.tokens(), "y"); + ASSERT(y && y->isAttributeLifetimeBound()); + const Token* z = Token::findsimplematch(tokenizer.tokens(), "z"); + ASSERT(z && !z->isAttributeLifetimeBound()); + } + { + const char code[] = "const int* f(const int* x __attribute__((lifetimebound)), __attribute__((__lifetimebound__)) const int* y, const int* z);\n"; + const char expected[] = "const int * f ( const int * x , const int * y , const int * z ) ;"; + + SimpleTokenizer tokenizer(settingsDefault, *this, false); + ASSERT(tokenizer.tokenize(code)); + + ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false)); + + const Token* f = Token::findsimplematch(tokenizer.tokens(), "f"); + ASSERT(f && !f->isAttributeLifetimeBound()); + const Token* x = Token::findsimplematch(tokenizer.tokens(), "x"); + ASSERT(x && x->isAttributeLifetimeBound()); + const Token* y = Token::findsimplematch(tokenizer.tokens(), "y"); + ASSERT(y && y->isAttributeLifetimeBound()); + const Token* z = Token::findsimplematch(tokenizer.tokens(), "z"); + ASSERT(z && !z->isAttributeLifetimeBound()); + } + { + const char code[] = "struct S {\n" + " const int& f(const int& x) const noexcept [[clang::lifetimebound]];\n" + " const int* g(const int& y) const noexcept(true) __attribute__((lifetimebound));\n" + " int& operator[](int z) & [[clang::lifetimebound]];\n" + "};\n"; + const char expected[] = "struct S { " + "const int & f ( const int & x ) const noexcept ; " + "const int * g ( const int & y ) const noexcept ( true ) ; " + "int & operator[] ( int z ) & ; " + "} ;"; + + SimpleTokenizer tokenizer(settingsDefault, *this); + ASSERT(tokenizer.tokenize(code)); + + ASSERT_EQUALS(expected, tokenizer.tokens()->stringifyList(nullptr, false)); + + const Token* f = Token::findsimplematch(tokenizer.tokens(), "f"); + ASSERT(f && f->isAttributeLifetimeBound()); + const Token* g = Token::findsimplematch(tokenizer.tokens(), "g"); + ASSERT(g && g->isAttributeLifetimeBound()); + const Token* op = Token::findsimplematch(tokenizer.tokens(), "operator[]"); + ASSERT(op && op->isAttributeLifetimeBound()); + const Token* x = Token::findsimplematch(tokenizer.tokens(), "x"); + ASSERT(x && !x->isAttributeLifetimeBound()); + const Token* y = Token::findsimplematch(tokenizer.tokens(), "y"); + ASSERT(y && !y->isAttributeLifetimeBound()); + const Token* z = Token::findsimplematch(tokenizer.tokens(), "z"); + ASSERT(z && !z->isAttributeLifetimeBound()); + } + { + const char code[] = "const int& f(const int& x [[clang::lifetimebound]], const int& y);\n"; + + SimpleTokenizer tokenizer(settingsDefault, *this); + ASSERT(tokenizer.tokenize(code)); + + const Token* x = Token::findsimplematch(tokenizer.tokens(), "x"); + ASSERT(x && x->getAttributeLifetimeBound() == Token::LifetimeAttrMode::OBJECT); + const Token* y = Token::findsimplematch(tokenizer.tokens(), "y"); + ASSERT(y && y->getAttributeLifetimeBound() == Token::LifetimeAttrMode::NONE); + + // the attribute is the only difference so it has to be a part of the hash + SimpleTokenizer tokenizer2(settingsDefault, *this); + ASSERT(tokenizer2.tokenize("const int& f(const int& x, const int& y);\n")); + ASSERT(tokenizer.list.calculateHash() != tokenizer2.list.calculateHash()); + } + { + // the tokens of the instantiated template are copies + const char code[] = "template\n" + "struct Opt {\n" + " const T& value_or(const T& d [[clang::lifetimebound]]) const [[clang::lifetimebound]];\n" + "};\n" + "Opt o;\n"; + + SimpleTokenizer tokenizer(settingsDefault, *this); + ASSERT(tokenizer.tokenize(code)); + + ASSERT(!Token::findsimplematch(tokenizer.tokens(), "template")); + ASSERT(Token::findsimplematch(tokenizer.tokens(), "const int & value_or (")); + const Token* f = Token::findsimplematch(tokenizer.tokens(), "value_or"); + ASSERT(f && f->isAttributeLifetimeBound()); + const Token* d = Token::findsimplematch(tokenizer.tokens(), "d"); + ASSERT(d && d->isAttributeLifetimeBound()); + } + } + void attributeAlignasBefore() { const char code[] = "alignas(long) unsigned char buffer[sizeof(long)];\n"; const char expected[] = "char buffer [ sizeof ( long ) ] ;";