forked from mathieu/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckstl.cpp
More file actions
426 lines (370 loc) · 14.6 KB
/
checkstl.cpp
File metadata and controls
426 lines (370 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2009 Daniel Marjamäki and Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/
*/
#include "checkstl.h"
#include "tokenize.h"
#include "token.h"
// Register this check class (by creating a static instance of it)
namespace
{
CheckStl instance;
}
// Error message for bad iterator usage..
void CheckStl::iteratorsError(const Token *tok, const std::string &container1, const std::string &container2)
{
reportError(tok, Severity::error, "iterators", "Same iterator is used with both " + container1 + " and " + container2);
}
// Error message used when dereferencing an iterator that has been erased..
void CheckStl::dereferenceErasedError(const Token *tok, const std::string &itername)
{
reportError(tok, Severity::error, "eraseDereference", "Dereferenced iterator '" + itername + "' has been erased");
}
void CheckStl::iterators()
{
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (!Token::Match(tok, "%var% = %var% . begin ( ) ;|+"))
continue;
const unsigned int iteratorId(tok->varId());
const unsigned int containerId(tok->tokAt(2)->varId());
if (iteratorId == 0 || containerId == 0)
continue;
bool validIterator = true;
for (const Token *tok2 = tok->tokAt(7); tok2; tok2 = tok2->next())
{
if (tok2->str() == "}")
break;
if (Token::Match(tok2, "%varid% != %var% . end ( )", iteratorId) && tok2->tokAt(2)->varId() != containerId)
{
iteratorsError(tok2, tok->strAt(2), tok2->strAt(2));
tok2 = tok2->tokAt(6);
}
else if (Token::Match(tok2, "%var% . insert|erase ( %varid%", iteratorId))
{
if (tok2->varId() != containerId)
iteratorsError(tok2, tok->strAt(2), tok2->str());
else if (tok2->strAt(2) == std::string("erase"))
validIterator = false;
tok2 = tok2->tokAt(4);
}
else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId))
{
dereferenceErasedError(tok2, tok2->strAt(1));
tok2 = tok2->next();
}
else if (!validIterator && Token::Match(tok2, "%varid% . %var%", iteratorId))
{
dereferenceErasedError(tok2, tok2->strAt(0));
tok2 = tok2->tokAt(2);
}
}
}
}
void CheckStl::stlOutOfBounds()
{
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (!Token::simpleMatch(tok, "for ("))
continue;
unsigned int indent = 0;
for (const Token *tok2 = tok; tok2; tok2 = tok2->next())
{
if (tok2->str() == "(")
++indent;
else if (tok2->str() == ")")
{
if (indent == 0)
break;
--indent;
}
if (Token::Match(tok2, "; %var% <= %var% . size ( ) ;"))
{
indent = 0;
const std::string num(tok2->strAt(1));
const std::string varname(tok2->strAt(3));
for (const Token *tok3 = tok2->tokAt(8); tok3; tok3 = tok3->next())
{
if (tok3->str() == "{")
++indent;
else if (tok3->str() == "}")
{
if (indent == 0)
break;
--indent;
}
else if (tok3->str() == varname)
{
if (Token::simpleMatch(tok3->next(), ". size ( )"))
break;
else if (Token::simpleMatch(tok3->next(), ("[ " + num + " ]").c_str()))
stlOutOfBoundsError(tok3, num, varname);
}
}
break;
}
}
}
}
// Error message for bad iterator usage..
void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, const std::string &var)
{
reportError(tok, Severity::error, "stlOutOfBounds", "When " + num + "==" + var + ".size(), " + var + "[" + num + "] is out of bounds");
}
void CheckStl::erase()
{
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (Token::simpleMatch(tok, "for ("))
{
for (const Token *tok2 = tok->tokAt(2); tok2 && tok2->str() != ";"; tok2 = tok2->next())
{
if (Token::Match(tok2, "%var% = %var% . begin ( ) ; %var% != %var% . end ( ) ") &&
tok2->str() == tok2->tokAt(8)->str() &&
tok2->tokAt(2)->str() == tok2->tokAt(10)->str())
{
eraseCheckLoop(tok2);
break;
}
}
}
if (Token::Match(tok, "while ( %var% != %var% . end ( )"))
{
eraseCheckLoop(tok->tokAt(2));
}
}
}
void CheckStl::eraseCheckLoop(const Token *it)
{
const Token *tok = it;
// Search for the start of the loop body..
int indentlevel = 1;
while (indentlevel > 0 && 0 != (tok = tok->next()))
{
if (tok->str() == "(")
++indentlevel;
else if (tok->str() == ")")
--indentlevel;
}
if (! Token::simpleMatch(tok, ") {"))
return;
// Parse loop..
// Error if it contains "erase(it)" but neither "break;" nor "it="
indentlevel = 0;
const Token *tok2 = 0;
while (0 != (tok = tok->next()))
{
if (tok->str() == "{")
++indentlevel;
else if (tok->str() == "}")
{
--indentlevel;
if (indentlevel <= 0)
break;
}
else if (Token::Match(tok, "break|return|goto") || Token::simpleMatch(tok, (it->str() + " =").c_str()))
{
tok2 = 0;
break;
}
else if (Token::simpleMatch(tok, ("erase ( " + it->str() + " )").c_str()))
tok2 = tok;
}
// Write error message..
if (tok2)
eraseError(tok2);
}
// Error message for bad iterator usage..
void CheckStl::eraseError(const Token *tok)
{
reportError(tok, Severity::error, "erase", "Dangerous usage of erase\nAfter erase has been used the iterator may be invalid so dereferencing it or comparing it with other iterator is invalid.");
}
void CheckStl::pushback()
{
// Pointer can become invalid after push_back or push_front..
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (Token::Match(tok, "%var% = & %var% ["))
{
const unsigned int pointerId(tok->varId());
const unsigned int containerId(tok->tokAt(3)->varId());
if (pointerId == 0 || containerId == 0)
continue;
int indent = 0;
bool invalidPointer = false;
for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next())
{
if (tok2->str() == "{" || tok2->str() == "(")
++indent;
else if (tok2->str() == "}" || tok2->str() == ")")
{
if (indent == 0 && Token::simpleMatch(tok2, ") {"))
tok2 = tok2->next();
else
--indent;
}
// push_back on vector..
if (Token::Match(tok2, "%varid% . push_front|push_back", containerId))
invalidPointer = true;
// Using invalid pointer..
if (invalidPointer && tok2->varId() == pointerId)
{
if (tok2->previous()->str() == "*")
invalidPointerError(tok2, tok2->str());
else if (tok2->next()->str() == ".")
invalidPointerError(tok2, tok2->str());
break;
}
}
}
}
// Iterator becomes invalid after push_back or push_front..
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
if (Token::simpleMatch(tok, "vector <"))
{
while (tok && tok->str() != ">")
tok = tok->next();
if (!tok)
break;
if (Token::Match(tok, "> :: iterator|const_iterator %var% =|;"))
{
const unsigned int iteratorid(tok->tokAt(3)->varId());
if (iteratorid == 0)
continue;
std::string vectorname;
int indent = 0;
bool invalidIterator = false;
for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next())
{
if (tok2->str() == "{" || tok2->str() == "(")
++indent;
else if (tok2->str() == "}" || tok2->str() == ")")
{
if (indent == 0 && Token::simpleMatch(tok2, ") {"))
tok2 = tok2->next();
else
--indent;
}
// Using push_back or push_front inside a loop..
if (Token::Match(tok2, "for ( %varid% = %var% . begin ( ) ; %varid% != %var% . end ( ) ; ++ %varid% ) {", iteratorid))
{
const unsigned int vectorid(tok2->tokAt(4)->varId());
if (vectorid == 0)
continue;
const Token *pushback = 0;
int indent3 = 0;
for (const Token *tok3 = tok2->tokAt(22); tok3; tok3 = tok3->next())
{
if (tok3->str() == "{")
++indent3;
else if (tok3->str() == "}")
{
if (indent3 == 0)
break;
--indent3;
}
else if (tok3->str() == "break")
{
pushback = 0;
break;
}
else if (Token::Match(tok3, "%varid% . push_front|push_back (", vectorid))
{
pushback = tok3;
}
}
if (pushback)
pushbackError(pushback, tok2->strAt(2));
}
// Assigning iterator..
if (Token::Match(tok2, "%varid% = %var% . begin ( )", iteratorid))
{
vectorname = tok2->strAt(2);
invalidIterator = false;
}
// push_back on vector..
if (vectorname.size() && Token::Match(tok2, (vectorname + " . push_front|push_back").c_str()))
invalidIterator = true;
// Using invalid iterator..
if (invalidIterator)
{
if (Token::Match(tok2, "++|--|*|+|-|(|, %varid%", iteratorid))
pushbackError(tok2, tok2->strAt(1));
if (Token::Match(tok2, "%varid% ++|--|+|-", iteratorid))
pushbackError(tok2, tok2->str());
}
}
}
}
}
}
// Error message for bad iterator usage..
void CheckStl::pushbackError(const Token *tok, const std::string &iterator_name)
{
reportError(tok, Severity::error, "pushback", "After push_back or push_front, the iterator '" + iterator_name + "' may be invalid");
}
// Error message for bad iterator usage..
void CheckStl::invalidPointerError(const Token *tok, const std::string &pointer_name)
{
reportError(tok, Severity::error, "pushback", "Invalid pointer '" + pointer_name + "' after push_back / push_front");
}
void CheckStl::stlBoundries()
{
// containers (not the vector)..
static const char STL_CONTAINER_LIST[] = "bitset|deque|list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set";
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
// Declaring iterator..
const std::string checkStr = (std::string(STL_CONTAINER_LIST) + " <");
if (Token::Match(tok, checkStr.c_str()))
{
const std::string container_name(tok->strAt(0));
while (tok && tok->str() != ">")
tok = tok->next();
if (!tok)
break;
if (Token::Match(tok, "> :: iterator|const_iterator %var% =|;"))
{
const unsigned int iteratorid(tok->tokAt(3)->varId());
if (iteratorid == 0)
continue;
// Using "iterator < ..." is not allowed
unsigned int indentlevel = 0;
for (const Token *tok2 = tok; tok2; tok2 = tok2->next())
{
if (tok2->str() == "{")
++indentlevel;
else if (tok2->str() == "}")
{
if (indentlevel == 0)
break;
--indentlevel;
}
else if (Token::Match(tok2, "!!* %varid% <", iteratorid))
{
stlBoundriesError(tok2, container_name);
}
}
}
}
}
}
// Error message for bad boundry usage..
void CheckStl::stlBoundriesError(const Token *tok, const std::string &container_name)
{
reportError(tok, Severity::error, "stlBoundries", container_name + " range check should use != and not < since the order of the pointers isn't guaranteed");
}