1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2021 Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "checkboost.h"
20 
21 #include "symboldatabase.h"
22 #include "token.h"
23 
24 // Register this check class (by creating a static instance of it)
25 namespace {
26     CheckBoost instance;
27 }
28 
29 static const CWE CWE664(664);
30 
checkBoostForeachModification()31 void CheckBoost::checkBoostForeachModification()
32 {
33     const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
34     for (const Scope * scope : symbolDatabase->functionScopes) {
35         for (const Token *tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
36             if (!Token::simpleMatch(tok, "BOOST_FOREACH ("))
37                 continue;
38 
39             const Token *containerTok = tok->next()->link()->previous();
40             if (!Token::Match(containerTok, "%var% ) {"))
41                 continue;
42 
43             const Token *tok2 = containerTok->tokAt(2);
44             const Token *end = tok2->link();
45             for (; tok2 != end; tok2 = tok2->next()) {
46                 if (Token::Match(tok2, "%varid% . insert|erase|push_back|push_front|pop_front|pop_back|clear|swap|resize|assign|merge|remove|remove_if|reverse|sort|splice|unique|pop|push", containerTok->varId())) {
47                     const Token* nextStatement = Token::findsimplematch(tok2->linkAt(3), ";", end);
48                     if (!Token::Match(nextStatement, "; break|return|throw"))
49                         boostForeachError(tok2);
50                     break;
51                 }
52             }
53         }
54     }
55 }
56 
boostForeachError(const Token * tok)57 void CheckBoost::boostForeachError(const Token *tok)
58 {
59     reportError(tok, Severity::error, "boostForeachError",
60                 "BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.", CWE664, Certainty::normal
61                 );
62 }
63