MCPcopy Create free account
hub / github.com/cppcheck-opensource/cppcheck / checkIntegerOverflow

Method checkIntegerOverflow

lib/checktype.cpp:167–216  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

165//---------------------------------------------------------------------------
166
167void CheckTypeImpl::checkIntegerOverflow()
168{
169 // unknown sizeof(int) => can't run this checker
170 if (mSettings.platform.type == Platform::Type::Unspecified || mSettings.platform.int_bit >= MathLib::bigint_bits)
171 return;
172
173 logChecker("CheckType::checkIntegerOverflow"); // platform
174
175 for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
176 if (!tok->isArithmeticalOp())
177 continue;
178
179 // is result signed integer?
180 const ValueType *vt = tok->valueType();
181 if (!vt || !vt->isIntegral() || vt->sign != ValueType::Sign::SIGNED)
182 continue;
183
184 unsigned int bits;
185 if (vt->type == ValueType::Type::INT)
186 bits = mSettings.platform.int_bit;
187 else if (vt->type == ValueType::Type::LONG)
188 bits = mSettings.platform.long_bit;
189 else if (vt->type == ValueType::Type::LONGLONG)
190 bits = mSettings.platform.long_long_bit;
191 else
192 continue;
193
194 if (bits >= MathLib::bigint_bits)
195 continue;
196
197 // max value according to platform settings.
198 const MathLib::bigint maxvalue = (static_cast<MathLib::biguint>(1) << (bits - 1)) - 1;
199
200 // is there a overflow result value
201 bool isOverflow = true;
202 const ValueFlow::Value *value = tok->getValueGE(maxvalue + 1, mSettings);
203 if (!value) {
204 value = tok->getValueLE(-maxvalue - 2, mSettings);
205 isOverflow = false;
206 }
207 if (!value || !mSettings.isEnabled(value,false))
208 continue;
209
210 // For left shift, it's common practice to shift into the sign bit
211 if (tok->str() == "<<" && value->intvalue > 0 && value->intvalue < (static_cast<MathLib::biguint>(1) << bits))
212 continue;
213
214 integerOverflowError(tok, *value, isOverflow);
215 }
216}
217
218static std::string getMessageId(const ValueFlow::Value &value, const char id[])
219{

Callers 1

runChecksMethod · 0.45

Calls 7

nextMethod · 0.80
isArithmeticalOpMethod · 0.80
isIntegralMethod · 0.80
getValueGEMethod · 0.80
getValueLEMethod · 0.80
isEnabledMethod · 0.45
strMethod · 0.45

Tested by

no test coverage detected