Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion lib/checkcondition.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "checkcondition.h"

#include "astutils.h"
#include "errortypes.h"
#include "library.h"
#include "platform.h"
#include "settings.h"
Expand Down Expand Up @@ -1112,8 +1113,18 @@ static bool parseComparison(const Token *comp, bool &not1, std::string &op, std:

inconclusive = inconclusive || (value[0] == '\'' && !(op == "!=" || op == "=="));

if (value[0] == '\'') {
// Bad character literal
try {
(void)MathLib::toBigNumber(value, expr);
} catch (const InternalError & /*e*/) {
return false;
}
return true;
}

// Only float and int values are currently handled
return MathLib::isInt(value) || MathLib::isFloat(value) || (value[0] == '\'');
return MathLib::isInt(value) || MathLib::isFloat(value);
}

static std::string conditionString(bool not1, const Token *expr1, const std::string &op, const std::string &value1)
Expand Down
6 changes: 5 additions & 1 deletion lib/templatesimplifier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2766,7 +2766,11 @@ bool TemplateSimplifier::simplifyCalculations(Token* frontToken, const Token *ba

if (validTokenEnd(bounded, tok, backToken, 3) &&
Token::Match(tok->previous(), "(|&&|%oror% %char% %comp% %num% &&|%oror%|)")) {
tok->str(MathLib::toString(MathLib::toBigNumber(tok)));
try {
tok->str(MathLib::toString(MathLib::toBigNumber(tok)));
} catch (const InternalError & /*e*/) {
// Bad character literal
}
}

if (validTokenEnd(bounded, tok, backToken, 5) &&
Expand Down
9 changes: 7 additions & 2 deletions lib/tokenize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4192,8 +4192,13 @@ void Tokenizer::simplifyCaseRange()
{
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "case %num%|%char% ... %num%|%char% :")) {
const MathLib::bigint start = MathLib::toBigNumber(tok->tokAt(1));
MathLib::bigint end = MathLib::toBigNumber(tok->tokAt(3));
MathLib::bigint start, end;
try {
start = MathLib::toBigNumber(tok->tokAt(1));
end = MathLib::toBigNumber(tok->tokAt(3));
} catch (const InternalError & /*e*/) {
continue; // Bad character literal
}
end = std::min(start + 50, end); // Simplify it 50 times at maximum
if (start < end) {
tok = tok->tokAt(2);
Expand Down
6 changes: 6 additions & 0 deletions lib/vf_common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include "vf_common.h"

#include "astutils.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "path.h"
Expand Down Expand Up @@ -137,6 +138,8 @@ namespace ValueFlow
setTokenValue(tok, std::move(value), settings);
} catch (const std::exception & /*e*/) {
// Bad character literal
} catch (const InternalError & /*e*/) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

This catches the throw in valueflow. But TemplateSimplifier::simplifyCalculations (templatesimplifier.cpp:2766-2769) also calls MathLib::toBigNumber(tok) on a %char% token with no catch. Inside template arguments the invalid escape still gives an internal error:

template<bool B> struct V {};
V<('\s' == 1)> v;
$ ./cppcheck -q e4.cpp
e4.cpp:2:4: error: Internal Error. MathLib::toBigNumber: characterLiteralToLL('\s') => invalid escape sequence [internalError]

The same happens with U<('\s' > 3)> u2; for template<int N> struct U {};. To fix it, catch the error there too and leave the token unchanged, and add a test for it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

With this catch, valueflow skips the bad literal. Checks that convert %char% tokens themselves still throw, though. CheckConditionImpl::checkIncorrectLogicOperator (checkcondition.cpp:1311) calls MathLib::toBigNumber(value1, expr1) on the string that parseComparison returns, and nothing catches the error:

void f(char c) {
  if (c == '\s' && c == '\q') {}
}
$ cppcheck -q --enable=style b.c
b.c:2:7: error: Internal Error. MathLib::toBigNumber: characterLiteralToLL('\s') => invalid escape sequence [internalError]

if (c > '\s' || c < 'a') {} fails the same way. The base also fails on this input, but there the throw comes from valueflow; the PR only moves the crash. Two possible fixes: make parseComparison reject char literals that can't be converted, or catch the error in checkIncorrectLogicOperator. Add a TestCondition case for it.

// Bad character literal
}
} else if (tok->isNumber() && MathLib::isFloat(tok->str())) {
// A long double literal out of the range of double (1e400L) has no
Expand Down Expand Up @@ -323,6 +326,9 @@ namespace ValueFlow
catch (const std::exception& /*e*/) {
// Bad integer literal
}
catch (const InternalError& /*e*/) {
// Bad character literal
}
}
sz = 0;
break;
Expand Down
8 changes: 8 additions & 0 deletions test/testcondition.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ class TestCondition : public TestFixture {
TEST_CASE(incorrectLogicOperator16); // #10070
TEST_CASE(incorrectLogicOperator17);
TEST_CASE(incorrectLogicOperator18); // #12282
TEST_CASE(incorrectLogicOperatorBadCharLiteral);
TEST_CASE(secondAlwaysTrueFalseWhenFirstTrueError);
TEST_CASE(incorrectLogicOp_condSwapping);
TEST_CASE(testBug5895);
Expand Down Expand Up @@ -1785,6 +1786,13 @@ class TestCondition : public TestFixture {
ASSERT_EQUALS("", errout_str());
}

void incorrectLogicOperatorBadCharLiteral() {
check("void f(char c) {\n"
" if (c == '\\s' && c == '\\q') {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}

void incorrectLogicOperator17() { // #12471
check("struct R {\n"
" void set() { i = 1; }\n"
Expand Down
7 changes: 7 additions & 0 deletions test/testsimplifytemplate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ class TestSimplifyTemplate : public TestFixture {
TEST_CASE(simplifyTemplateArgs1);
TEST_CASE(simplifyTemplateArgs2);
TEST_CASE(simplifyTemplateArgs3);
TEST_CASE(simplifyTemplateArgsInvalidCharLiteral);

TEST_CASE(template_variadic_1); // #9144
TEST_CASE(template_variadic_2); // #4349
Expand Down Expand Up @@ -6368,6 +6369,12 @@ class TestSimplifyTemplate : public TestFixture {
ASSERT_EQUALS("foo<false> = false ; foo<false> ;", tok("template<bool N> foo = N; foo < ( 1 - 1) ? true : false >;\n"));
}

void simplifyTemplateArgsInvalidCharLiteral() {
ASSERT_EQUALS("struct V<('\\s'==1)> ; V<('\\s'==1)> v ; struct V<('\\s'==1)> { } ;",
tok("template<bool B> struct V {};\n"
"V<('\\s' == 1)> v;\n"));
}

void simplifyTemplateArgs2() {
const char code[] = "template<bool T> struct a_t { static const bool t = T; };\n"
"typedef a_t<sizeof(void*) == sizeof(char)> a;\n"
Expand Down
14 changes: 14 additions & 0 deletions test/testtokenize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,8 @@ class TestTokenizer : public TestFixture {
TEST_CASE(simplifyEnum1);

TEST_CASE(simplifyEnum2);

TEST_CASE(nonStandardCharLiteral);
}

class TokenizerTest final : public Tokenizer
Expand Down Expand Up @@ -9547,6 +9549,18 @@ class TestTokenizer : public TestFixture {
ASSERT_EQUALS(tok->column(), 24);
ASSERT_EQUALS(tok->next()->column(), 16);
}

void nonStandardCharLiteral() {
const Settings s = settingsBuilder(settings2).severity(Severity::portability).build();
(void)tokenizeAndStringify("int a = '\\s';\n", s, false);
ASSERT_EQUALS("[test.c:1:9]: (portability) Non-standard character literal '\\s'. invalid escape sequence [nonStandardCharLiteral]\n", errout_str());

(void)tokenizeAndStringify("void f(char c) { switch (c) { case '\\s' ... 'z': break; } }\n", s, false);
ASSERT_EQUALS("[test.c:1:36]: (portability) Non-standard character literal '\\s'. invalid escape sequence [nonStandardCharLiteral]\n", errout_str());

(void)tokenizeAndStringify("int n = sizeof(char['\\s']);\n", s, false);
ASSERT_EQUALS("[test.c:1:21]: (portability) Non-standard character literal '\\s'. invalid escape sequence [nonStandardCharLiteral]\n", errout_str());
}
};

REGISTER_TEST(TestTokenizer)
Loading