forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecktype.cpp
428 lines (360 loc) · 16.7 KB
/
checktype.cpp
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
427
428
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2019 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 "checktype.h"
#include "errorlogger.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include <cstddef>
#include <list>
#include <ostream>
#include <stack>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckType instance;
}
//---------------------------------------------------------------------------
// Checking for shift by too many bits
//---------------------------------------------------------------------------
//
// CWE ids used:
static const struct CWE CWE195(195U); // Signed to Unsigned Conversion Error
static const struct CWE CWE197(197U); // Numeric Truncation Error
static const struct CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const struct CWE CWE190(190U); // Integer Overflow or Wraparound
void CheckType::checkTooBigBitwiseShift()
{
// unknown sizeof(int) => can't run this checker
if (mSettings->platformType == Settings::Unspecified)
return;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
// C++ and macro: OUT(x<<y)
if (mTokenizer->isCPP() && Token::Match(tok, "[;{}] %name% (") && Token::simpleMatch(tok->linkAt(2), ") ;") && tok->next()->isUpperCaseName() && !tok->next()->function())
tok = tok->linkAt(2);
if (!tok->astOperand1() || !tok->astOperand2())
continue;
if (!Token::Match(tok, "<<|>>|<<=|>>="))
continue;
// get number of bits of lhs
const ValueType * const lhstype = tok->astOperand1()->valueType();
if (!lhstype || !lhstype->isIntegral() || lhstype->pointer >= 1U)
continue;
// C11 Standard, section 6.5.7 Bitwise shift operators, states:
// The integer promotions are performed on each of the operands.
// The type of the result is that of the promoted left operand.
int lhsbits;
if ((lhstype->type == ValueType::Type::CHAR) ||
(lhstype->type == ValueType::Type::SHORT) ||
(lhstype->type == ValueType::Type::WCHAR_T) ||
(lhstype->type == ValueType::Type::BOOL) ||
(lhstype->type == ValueType::Type::INT))
lhsbits = mSettings->int_bit;
else if (lhstype->type == ValueType::Type::LONG)
lhsbits = mSettings->long_bit;
else if (lhstype->type == ValueType::Type::LONGLONG)
lhsbits = mSettings->long_long_bit;
else
continue;
// Get biggest rhs value. preferably a value which doesn't have 'condition'.
const ValueFlow::Value * value = tok->astOperand2()->getValueGE(lhsbits, mSettings);
if (value && mSettings->isEnabled(value, false))
tooBigBitwiseShiftError(tok, lhsbits, *value);
else if (lhstype->sign == ValueType::Sign::SIGNED) {
value = tok->astOperand2()->getValueGE(lhsbits-1, mSettings);
if (value && mSettings->isEnabled(value, false))
tooBigSignedBitwiseShiftError(tok, lhsbits, *value);
}
}
}
void CheckType::tooBigBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits)
{
const char id[] = "shiftTooManyBits";
if (!tok) {
reportError(tok, Severity::error, id, "Shifting 32-bit value by 40 bits is undefined behaviour", CWE758, false);
return;
}
const ErrorPath errorPath = getErrorPath(tok, &rhsbits, "Shift");
std::ostringstream errmsg;
errmsg << "Shifting " << lhsbits << "-bit value by " << rhsbits.intvalue << " bits is undefined behaviour";
if (rhsbits.condition)
errmsg << ". See condition at line " << rhsbits.condition->linenr() << ".";
reportError(errorPath, rhsbits.errorSeverity() ? Severity::error : Severity::warning, id, errmsg.str(), CWE758, rhsbits.isInconclusive());
}
void CheckType::tooBigSignedBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits)
{
const char id[] = "shiftTooManyBitsSigned";
if (!tok) {
reportError(tok, Severity::error, id, "Shifting signed 32-bit value by 31 bits is undefined behaviour", CWE758, false);
return;
}
const ErrorPath errorPath = getErrorPath(tok, &rhsbits, "Shift");
std::ostringstream errmsg;
errmsg << "Shifting signed " << lhsbits << "-bit value by " << rhsbits.intvalue << " bits is undefined behaviour";
if (rhsbits.condition)
errmsg << ". See condition at line " << rhsbits.condition->linenr() << ".";
reportError(errorPath, rhsbits.errorSeverity() ? Severity::error : Severity::warning, id, errmsg.str(), CWE758, rhsbits.isInconclusive());
}
//---------------------------------------------------------------------------
// Checking for integer overflow
//---------------------------------------------------------------------------
void CheckType::checkIntegerOverflow()
{
// unknown sizeof(int) => can't run this checker
if (mSettings->platformType == Settings::Unspecified || mSettings->int_bit >= MathLib::bigint_bits)
return;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isArithmeticalOp())
continue;
// is result signed integer?
const ValueType *vt = tok->valueType();
if (!vt || !vt->isIntegral() || vt->sign != ValueType::Sign::SIGNED)
continue;
unsigned int bits;
if (vt->type == ValueType::Type::INT)
bits = mSettings->int_bit;
else if (vt->type == ValueType::Type::LONG)
bits = mSettings->long_bit;
else if (vt->type == ValueType::Type::LONGLONG)
bits = mSettings->long_long_bit;
else
continue;
if (bits >= MathLib::bigint_bits)
continue;
// max value according to platform settings.
const MathLib::bigint maxvalue = (((MathLib::bigint)1) << (bits - 1)) - 1;
// is there a overflow result value
const ValueFlow::Value *value = tok->getValueGE(maxvalue + 1, mSettings);
if (!value)
value = tok->getValueLE(-maxvalue - 2, mSettings);
if (!value || !mSettings->isEnabled(value,false))
continue;
// For left shift, it's common practice to shift into the sign bit
if (tok->str() == "<<" && value->intvalue > 0 && value->intvalue < (((MathLib::bigint)1) << bits))
continue;
integerOverflowError(tok, *value);
}
}
void CheckType::integerOverflowError(const Token *tok, const ValueFlow::Value &value)
{
const std::string expr(tok ? tok->expressionString() : "");
std::string msg;
if (value.condition)
msg = ValueFlow::eitherTheConditionIsRedundant(value.condition) +
" or there is signed integer overflow for expression '" + expr + "'.";
else
msg = "Signed integer overflow for expression '" + expr + "'.";
reportError(getErrorPath(tok, &value, "Integer overflow"),
value.errorSeverity() ? Severity::error : Severity::warning,
(value.condition == nullptr) ? "integerOverflow" : "integerOverflowCond",
msg,
CWE190,
value.isInconclusive());
}
//---------------------------------------------------------------------------
// Checking for sign conversion when operand can be negative
//---------------------------------------------------------------------------
void CheckType::checkSignConversion()
{
if (!mSettings->isEnabled(Settings::WARNING))
return;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isArithmeticalOp() || Token::Match(tok,"+|-"))
continue;
// Is result unsigned?
if (!(tok->valueType() && tok->valueType()->sign == ValueType::Sign::UNSIGNED))
continue;
// Check if an operand can be negative..
std::stack<const Token *> tokens;
tokens.push(tok->astOperand1());
tokens.push(tok->astOperand2());
while (!tokens.empty()) {
const Token *tok1 = tokens.top();
tokens.pop();
if (!tok1)
continue;
if (!tok1->getValueLE(-1,mSettings))
continue;
if (tok1->valueType() && tok1->valueType()->sign != ValueType::Sign::UNSIGNED)
signConversionError(tok1, tok1->isNumber());
}
}
}
void CheckType::signConversionError(const Token *tok, const bool constvalue)
{
const std::string expr(tok ? tok->expressionString() : "var");
std::ostringstream msg;
if (tok && tok->isName())
msg << "$symbol:" << expr << "\n";
if (constvalue)
msg << "Suspicious code: sign conversion of '" << expr << "' in calculation because '" << expr << "' has a negative value";
else
msg << "Suspicious code: sign conversion of '" << expr << "' in calculation, even though '" << expr << "' can have a negative value";
reportError(tok, Severity::warning, "signConversion", msg.str(), CWE195, false);
}
//---------------------------------------------------------------------------
// Checking for long cast of int result const long x = var1 * var2;
//---------------------------------------------------------------------------
void CheckType::checkLongCast()
{
if (!mSettings->isEnabled(Settings::STYLE))
return;
// Assignments..
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "=" || !Token::Match(tok->astOperand2(), "*|<<"))
continue;
if (tok->astOperand2()->hasKnownIntValue()) {
const ValueFlow::Value &v = tok->astOperand2()->values().front();
if (mSettings->isIntValue(v.intvalue))
continue;
}
const ValueType *lhstype = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr;
const ValueType *rhstype = tok->astOperand2()->valueType();
if (!lhstype || !rhstype)
continue;
// assign int result to long/longlong const nonpointer?
if (rhstype->type == ValueType::Type::INT &&
rhstype->pointer == 0U &&
rhstype->originalTypeName.empty() &&
(lhstype->type == ValueType::Type::LONG || lhstype->type == ValueType::Type::LONGLONG) &&
lhstype->pointer == 0U &&
lhstype->constness == 1U &&
lhstype->originalTypeName.empty())
longCastAssignError(tok);
}
// Return..
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
// function must return long data
const Token * def = scope->classDef;
bool islong = false;
while (Token::Match(def, "%type%|::")) {
if (def->str() == "long" && def->originalName().empty()) {
islong = true;
break;
}
def = def->previous();
}
if (!islong)
continue;
// return statements
const Token *ret = nullptr;
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "return") {
if (Token::Match(tok->astOperand1(), "<<|*")) {
const ValueType *type = tok->astOperand1()->valueType();
if (type && type->type == ValueType::Type::INT && type->pointer == 0U && type->originalTypeName.empty())
ret = tok;
}
// All return statements must have problem otherwise no warning
if (ret != tok) {
ret = nullptr;
break;
}
}
}
if (ret)
longCastReturnError(ret);
}
}
void CheckType::longCastAssignError(const Token *tok)
{
reportError(tok,
Severity::style,
"truncLongCastAssignment",
"int result is assigned to long variable. If the variable is long to avoid loss of information, then you have loss of information.\n"
"int result is assigned to long variable. If the variable is long to avoid loss of information, then there is loss of information. To avoid loss of information you must cast a calculation operand to long, for example 'l = a * b;' => 'l = (long)a * b;'.", CWE197, false);
}
void CheckType::longCastReturnError(const Token *tok)
{
reportError(tok,
Severity::style,
"truncLongCastReturn",
"int result is returned as long value. If the return value is long to avoid loss of information, then you have loss of information.\n"
"int result is returned as long value. If the return value is long to avoid loss of information, then there is loss of information. To avoid loss of information you must cast a calculation operand to long, for example 'return a*b;' => 'return (long)a*b'.", CWE197, false);
}
//---------------------------------------------------------------------------
// Checking for float to integer overflow
//---------------------------------------------------------------------------
void CheckType::checkFloatToIntegerOverflow()
{
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
const ValueType *vtint, *vtfloat;
const std::list<ValueFlow::Value> *floatValues;
// Explicit cast
if (Token::Match(tok, "( %name%") && tok->astOperand1() && !tok->astOperand2()) {
vtint = tok->valueType();
vtfloat = tok->astOperand1()->valueType();
floatValues = &tok->astOperand1()->values();
}
// Assignment
else if (tok->str() == "=" && tok->astOperand1() && tok->astOperand2()) {
vtint = tok->astOperand1()->valueType();
vtfloat = tok->astOperand2()->valueType();
floatValues = &tok->astOperand2()->values();
}
// TODO: function call
else
continue;
// Conversion of float to integer?
if (!vtint || !vtint->isIntegral())
continue;
if (!vtfloat || !vtfloat->isFloat())
continue;
for (const ValueFlow::Value &f : *floatValues) {
if (f.valueType != ValueFlow::Value::FLOAT)
continue;
if (!mSettings->isEnabled(&f, false))
continue;
if (f.floatValue > ~0ULL)
floatToIntegerOverflowError(tok, f);
else if ((-f.floatValue) > (1ULL<<62))
floatToIntegerOverflowError(tok, f);
else if (mSettings->platformType != Settings::Unspecified) {
int bits = 0;
if (vtint->type == ValueType::Type::CHAR)
bits = mSettings->char_bit;
else if (vtint->type == ValueType::Type::SHORT)
bits = mSettings->short_bit;
else if (vtint->type == ValueType::Type::INT)
bits = mSettings->int_bit;
else if (vtint->type == ValueType::Type::LONG)
bits = mSettings->long_bit;
else if (vtint->type == ValueType::Type::LONGLONG)
bits = mSettings->long_long_bit;
else
continue;
if (bits < MathLib::bigint_bits && f.floatValue >= (((MathLib::biguint)1) << bits))
floatToIntegerOverflowError(tok, f);
}
}
}
}
void CheckType::floatToIntegerOverflowError(const Token *tok, const ValueFlow::Value &value)
{
std::ostringstream errmsg;
errmsg << "Undefined behaviour: float (" << value.floatValue << ") to integer conversion overflow.";
reportError(getErrorPath(tok, &value, "float to integer conversion"),
value.errorSeverity() ? Severity::error : Severity::warning,
"floatConversionOverflow",
errmsg.str(), CWE190, value.isInconclusive());
}