forked from cppcheck-opensource/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexprengine.cpp
More file actions
1242 lines (1112 loc) · 47.3 KB
/
Copy pathexprengine.cpp
File metadata and controls
1242 lines (1112 loc) · 47.3 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 "exprengine.h"
#include "astutils.h"
#include "settings.h"
#include "symboldatabase.h"
#include "tokenize.h"
#include <cstdlib>
#include <limits>
#include <memory>
#include <iostream>
#ifdef USE_Z3
#include <z3++.h>
#endif
std::string ExprEngine::str(int128_t value)
{
std::ostringstream ostr;
#ifdef __GNUC__
if (value == (int)value) {
ostr << (int) value;
return ostr.str();
}
if (value < 0) {
ostr << "-";
value = -value;
}
uint64_t high = value >> 64;
uint64_t low = value;
if (high > 0)
ostr << "h" << std::hex << high << "l";
ostr << std::hex << low;
#else
ostr << value;
#endif
return ostr.str();
}
static ExprEngine::ValuePtr getValueRangeFromValueType(const std::string &name, const ValueType *vt, const cppcheck::Platform &platform);
namespace {
class TrackExecution {
public:
TrackExecution() : mDataIndex(0) {}
std::map<const Token *, std::vector<std::string>> map;
int getNewDataIndex() {
return mDataIndex++;
}
void symbolRange(const Token *tok, ExprEngine::ValuePtr value) {
if (!tok || !value)
return;
const std::string &symbolicExpression = value->getSymbolicExpression();
if (symbolicExpression[0] != '$')
return;
if (mSymbols.find(symbolicExpression) != mSymbols.end())
return;
mSymbols.insert(symbolicExpression);
map[tok].push_back(symbolicExpression + "=" + value->getRange());
}
void state(const Token *tok, const std::string &s) {
map[tok].push_back(s);
}
void print(std::ostream &out) {
std::set<std::pair<int,int>> locations;
for (auto it : map) {
locations.insert(std::pair<int,int>(it.first->linenr(), it.first->column()));
}
for (const std::pair<int,int> &loc : locations) {
int lineNumber = loc.first;
int column = loc.second;
for (auto &it : map) {
const Token *tok = it.first;
if (lineNumber != tok->linenr())
continue;
if (column != tok->column())
continue;
const std::vector<std::string> &dumps = it.second;
for (const std::string &dump : dumps)
out << lineNumber << ":" << column << ": " << dump << "\n";
}
}
}
private:
int mDataIndex;
std::set<std::string> mSymbols;
};
class Data : public ExprEngine::DataBase {
public:
Data(int *symbolValueIndex, const Tokenizer *tokenizer, const Settings *settings, const std::vector<ExprEngine::Callback> &callbacks, TrackExecution *trackExecution)
: DataBase(settings)
, symbolValueIndex(symbolValueIndex)
, tokenizer(tokenizer)
, callbacks(callbacks)
, mTrackExecution(trackExecution)
, mDataIndex(trackExecution->getNewDataIndex()) {}
typedef std::map<nonneg int, std::shared_ptr<ExprEngine::Value>> Memory;
Memory memory;
int * const symbolValueIndex;
const Tokenizer * const tokenizer;
const std::vector<ExprEngine::Callback> &callbacks;
std::vector<ExprEngine::ValuePtr> constraints;
void assignValue(const Token *tok, unsigned int varId, ExprEngine::ValuePtr value) {
mTrackExecution->symbolRange(tok, value);
if (value) {
if (auto arr = std::dynamic_pointer_cast<ExprEngine::ArrayValue>(value)) {
mTrackExecution->symbolRange(tok, arr->size);
for (const auto &indexAndValue: arr->data)
mTrackExecution->symbolRange(tok, indexAndValue.value);
} else if (auto s = std::dynamic_pointer_cast<ExprEngine::StructValue>(value)) {
for (const auto &m: s->member)
mTrackExecution->symbolRange(tok, m.second);
}
}
memory[varId] = value;
}
void assignStructMember(const Token *tok, ExprEngine::StructValue *structVal, const std::string &memberName, ExprEngine::ValuePtr value) {
mTrackExecution->symbolRange(tok, value);
structVal->member[memberName] = value;
}
std::string getNewSymbolName() override {
return "$" + std::to_string(++(*symbolValueIndex));
}
std::shared_ptr<ExprEngine::ArrayValue> getArrayValue(const Token *tok) {
const Memory::iterator it = memory.find(tok->varId());
if (it != memory.end())
return std::dynamic_pointer_cast<ExprEngine::ArrayValue>(it->second);
if (tok->varId() == 0)
return std::shared_ptr<ExprEngine::ArrayValue>();
auto val = std::make_shared<ExprEngine::ArrayValue>(this, tok->variable());
assignValue(tok, tok->varId(), val);
return val;
}
ExprEngine::ValuePtr getValue(unsigned int varId, const ValueType *valueType, const Token *tok) {
const Memory::const_iterator it = memory.find(varId);
if (it != memory.end())
return it->second;
if (!valueType)
return ExprEngine::ValuePtr();
ExprEngine::ValuePtr value = getValueRangeFromValueType(getNewSymbolName(), valueType, *settings);
if (value) {
assignValue(tok, varId, value);
}
return value;
}
void trackProgramState(const Token *tok) {
if (memory.empty())
return;
const SymbolDatabase * const symbolDatabase = tokenizer->getSymbolDatabase();
std::ostringstream s;
s << "{"; // << mDataIndex << ":";
for (auto mem : memory) {
ExprEngine::ValuePtr value = mem.second;
const Variable *var = symbolDatabase->getVariableFromVarId(mem.first);
if (!var)
continue;
s << " " << var->name() << "=";
if (!value)
s << "(null)";
else if (value->name[0] == '$' && value->getSymbolicExpression() != value->name)
s << "(" << value->name << "," << value->getSymbolicExpression() << ")";
else
s << value->name;
}
s << "}";
mTrackExecution->state(tok, s.str());
}
ExprEngine::ValuePtr notValue(ExprEngine::ValuePtr v) {
auto b = std::dynamic_pointer_cast<ExprEngine::BinOpResult>(v);
if (b) {
std::string binop;
if (b->binop == "==")
binop = "!=";
else if (b->binop == "!=")
binop = "==";
else if (b->binop == ">=")
binop = "<";
else if (b->binop == "<=")
binop = ">";
else if (b->binop == ">")
binop = "<=";
else if (b->binop == "<")
binop = ">=";
if (!binop.empty())
return std::make_shared<ExprEngine::BinOpResult>(binop, b->op1, b->op2);
}
auto zero = std::make_shared<ExprEngine::IntRange>("0", 0, 0);
return std::make_shared<ExprEngine::BinOpResult>("==", v, zero);
}
void addConstraint(ExprEngine::ValuePtr condValue, bool trueCond) {
if (trueCond)
constraints.push_back(condValue);
else
constraints.push_back(notValue(condValue));
}
private:
TrackExecution * const mTrackExecution;
const int mDataIndex;
};
}
static ExprEngine::ValuePtr simplifyValue(ExprEngine::ValuePtr origValue)
{
auto b = std::dynamic_pointer_cast<ExprEngine::BinOpResult>(origValue);
if (!b)
return origValue;
if (!b->op1 || !b->op2)
return origValue;
auto intRange1 = std::dynamic_pointer_cast<ExprEngine::IntRange>(b->op1);
auto intRange2 = std::dynamic_pointer_cast<ExprEngine::IntRange>(b->op2);
if (intRange1 && intRange2 && intRange1->minValue == intRange1->maxValue && intRange2->minValue == intRange2->maxValue) {
const std::string &binop = b->binop;
int128_t v;
if (binop == "+")
v = intRange1->minValue + intRange2->minValue;
else if (binop == "-")
v = intRange1->minValue - intRange2->minValue;
else if (binop == "*")
v = intRange1->minValue * intRange2->minValue;
else if (binop == "/" && intRange2->minValue != 0)
v = intRange1->minValue / intRange2->minValue;
else if (binop == "%" && intRange2->minValue != 0)
v = intRange1->minValue % intRange2->minValue;
else
return origValue;
return std::make_shared<ExprEngine::IntRange>(ExprEngine::str(v), v, v);
}
return origValue;
}
static ExprEngine::ValuePtr translateUninitValueToRange(ExprEngine::ValuePtr value, const ::ValueType *valueType, Data &data)
{
if (!value)
return value;
if (value->type == ExprEngine::ValueType::UninitValue) {
auto rangeValue = getValueRangeFromValueType(data.getNewSymbolName(), valueType, *data.settings);
if (rangeValue)
return rangeValue;
}
if (auto conditionalValue = std::dynamic_pointer_cast<ExprEngine::ConditionalValue>(value)) {
if (conditionalValue->values.size() == 1 && conditionalValue->values[0].second && conditionalValue->values[0].second->type == ExprEngine::ValueType::UninitValue) {
auto rangeValue = getValueRangeFromValueType(data.getNewSymbolName(), valueType, *data.settings);
if (rangeValue)
return rangeValue;
}
}
return value;
}
static int128_t truncateInt(int128_t value, int bits, char sign)
{
value = value & (((int128_t)1 << bits) - 1);
// Sign extension
if (sign == 's' && value & (1ULL << (bits - 1)))
value |= ~(((int128_t)1 << bits) - 1);
return value;
}
ExprEngine::ArrayValue::ArrayValue(const std::string &name, ExprEngine::ValuePtr size, ExprEngine::ValuePtr value)
: Value(name, ExprEngine::ValueType::ArrayValue)
, size(size)
{
assign(ExprEngine::ValuePtr(), value);
}
ExprEngine::ArrayValue::ArrayValue(DataBase *data, const Variable *var)
: Value(data->getNewSymbolName(), ExprEngine::ValueType::ArrayValue)
{
if (var) {
int sz = 1;
for (const auto &dim : var->dimensions()) {
if (!dim.known) {
sz = -1;
break;
}
sz *= dim.num;
}
if (sz >= 1)
size = std::make_shared<ExprEngine::IntRange>(std::to_string(sz), sz, sz);
}
ValuePtr val;
if (var && !var->isGlobal() && !var->isStatic())
val = std::make_shared<ExprEngine::UninitValue>();
else if (var && var->valueType()) {
::ValueType vt(*var->valueType());
vt.pointer = 0;
val = getValueRangeFromValueType(data->getNewSymbolName(), &vt, *data->settings);
}
assign(ExprEngine::ValuePtr(), val);
}
void ExprEngine::ArrayValue::assign(ExprEngine::ValuePtr index, ExprEngine::ValuePtr value)
{
if (!index)
data.clear();
if (value) {
ExprEngine::ArrayValue::IndexAndValue indexAndValue = {index, value};
data.push_back(indexAndValue);
}
}
void ExprEngine::ArrayValue::clear()
{
data.clear();
ExprEngine::ArrayValue::IndexAndValue indexAndValue = {
ExprEngine::ValuePtr(), std::make_shared<ExprEngine::IntRange>("0", 0, 0)
};
data.push_back(indexAndValue);
}
static bool isEqual(ExprEngine::ValuePtr v1, ExprEngine::ValuePtr v2)
{
if (!v1 || !v2)
return !v1 && !v2;
return v1->name == v2->name;
}
static bool isNonOverlapping(ExprEngine::ValuePtr v1, ExprEngine::ValuePtr v2)
{
if (!v1 || !v2)
return false; // Don't know!
auto intRange1 = std::dynamic_pointer_cast<ExprEngine::IntRange>(v1);
auto intRange2 = std::dynamic_pointer_cast<ExprEngine::IntRange>(v2);
if (intRange1 && intRange2 && (intRange1->minValue > intRange2->maxValue || intRange1->maxValue < intRange2->maxValue))
return true;
return false;
}
ExprEngine::ConditionalValue::Vector ExprEngine::ArrayValue::read(ExprEngine::ValuePtr index) const
{
ExprEngine::ConditionalValue::Vector ret;
for (const auto indexAndValue : data) {
if (isEqual(index, indexAndValue.index))
ret.clear();
if (isNonOverlapping(index, indexAndValue.index))
continue;
// Array contains string literal data...
if (!indexAndValue.index && indexAndValue.value->type == ExprEngine::ValueType::StringLiteralValue) {
auto stringLiteral = std::dynamic_pointer_cast<ExprEngine::StringLiteralValue>(indexAndValue.value);
if (!stringLiteral) {
ret.push_back(std::pair<ValuePtr,ValuePtr>(indexAndValue.index, std::make_shared<ExprEngine::IntRange>("", -128, 128)));
continue;
}
if (auto i = std::dynamic_pointer_cast<ExprEngine::IntRange>(index)) {
if (stringLiteral && i->minValue >= 0 && i->minValue == i->maxValue) {
int c = 0;
if (i->minValue < stringLiteral->size())
c = stringLiteral->string[i->minValue];
ret.push_back(std::pair<ValuePtr,ValuePtr>(indexAndValue.index, std::make_shared<ExprEngine::IntRange>(std::to_string(c), c, c)));
continue;
}
}
int cmin = 0, cmax = 0;
for (char c : stringLiteral->string) {
if (c < cmin)
cmin = c;
else if (c > cmax)
cmax = c;
}
ret.push_back(std::pair<ValuePtr,ValuePtr>(indexAndValue.index, std::make_shared<ExprEngine::IntRange>("", cmin, cmax)));
continue;
}
// Rename IntRange
if (auto i = std::dynamic_pointer_cast<ExprEngine::IntRange>(indexAndValue.value)) {
ret.push_back(std::pair<ValuePtr,ValuePtr>(indexAndValue.index, std::make_shared<ExprEngine::IntRange>(indexAndValue.value->name + ":" + index->name, i->minValue, i->maxValue)));
continue;
}
ret.push_back(std::pair<ValuePtr,ValuePtr>(indexAndValue.index, indexAndValue.value));
}
if (ret.size() == 1)
ret[0].first = ExprEngine::ValuePtr();
else if (ret.size() == 2 && !ret[0].first) {
ret[0].first = std::make_shared<ExprEngine::BinOpResult>("!=", index, ret[1].first);
ret[1].first = std::make_shared<ExprEngine::BinOpResult>("==", index, ret[1].first);
} else {
// FIXME!!
ret.clear();
}
return ret;
}
std::string ExprEngine::ConditionalValue::getSymbolicExpression() const
{
std::ostringstream ostr;
ostr << "{";
bool first = true;
for (auto condvalue : values) {
ValuePtr cond = condvalue.first;
ValuePtr value = condvalue.second;
if (!first)
ostr << ",";
first = false;
ostr << "{"
<< (cond ? cond->getSymbolicExpression() : std::string("(null)"))
<< ","
<< value->getSymbolicExpression()
<< "}";
}
ostr << "}";
return ostr.str();
}
std::string ExprEngine::ArrayValue::getSymbolicExpression() const
{
std::ostringstream ostr;
ostr << "size=" << (size ? size->name : std::string("(null)"));
for (const auto indexAndValue : data) {
ostr << ",["
<< (!indexAndValue.index ? std::string(":") : indexAndValue.index->name)
<< "]="
<< indexAndValue.value->name;
}
return ostr.str();
}
std::string ExprEngine::StructValue::getSymbolicExpression() const
{
std::ostringstream ostr;
ostr << "{";
bool first = true;
for (const auto& m: member) {
const std::string &memberName = m.first;
auto memberValue = m.second;
if (!first)
ostr << ",";
first = false;
ostr << memberName << "=" << (memberValue ? memberValue->getSymbolicExpression() : std::string("(null)"));
}
ostr << "}";
return ostr.str();
}
std::string ExprEngine::PointerValue::getRange() const
{
std::string r;
if (data)
r = "->" + data->getSymbolicExpression();
if (null)
r += std::string(r.empty() ? "" : ",") + "null";
if (uninitData)
r += std::string(r.empty() ? "" : ",") + "->?";
return r;
}
std::string ExprEngine::IntegerTruncation::getSymbolicExpression() const
{
return sign + std::to_string(bits) + "(" + inputValue->getSymbolicExpression() + ")";
}
#ifdef USE_Z3
struct ExprData {
typedef std::map<ExprEngine::ValuePtr, z3::expr> ValueExpr;
typedef std::vector<z3::expr> AssertionList;
z3::context c;
ValueExpr valueExpr;
AssertionList assertionList;
void addAssertions(z3::solver &solver) const {
for (auto assertExpr : assertionList)
solver.add(assertExpr);
}
};
static z3::expr getExpr(ExprEngine::ValuePtr v, ExprData &exprData);
static z3::expr getExpr(const ExprEngine::BinOpResult *b, ExprData &exprData)
{
auto op1 = getExpr(b->op1, exprData);
auto op2 = getExpr(b->op2, exprData);
if (b->binop == "+")
return op1 + op2;
if (b->binop == "-")
return op1 - op2;
if (b->binop == "*")
return op1 * op2;
if (b->binop == "/")
return op1 / op2;
if (b->binop == "%")
return op1 % op2;
if (b->binop == "==")
return op1 == op2;
if (b->binop == "!=")
return op1 != op2;
if (b->binop == ">=")
return op1 >= op2;
if (b->binop == "<=")
return op1 <= op2;
if (b->binop == ">")
return op1 > op2;
if (b->binop == "<")
return op1 < op2;
if (b->binop == "&&")
return op1 && op2;
if (b->binop == "||")
return op1 || op2;
throw std::runtime_error("Internal error: Unhandled operator");
}
static z3::expr getExpr(ExprEngine::ValuePtr v, ExprData &exprData)
{
if (auto intRange = std::dynamic_pointer_cast<ExprEngine::IntRange>(v)) {
if (intRange->name[0] != '$')
return exprData.c.int_val(int64_t(intRange->minValue));
auto it = exprData.valueExpr.find(v);
if (it != exprData.valueExpr.end())
return it->second;
auto e = exprData.c.int_const(("v" + std::to_string(exprData.valueExpr.size())).c_str());
exprData.valueExpr.emplace(v, e);
if (intRange->maxValue <= INT_MAX)
exprData.assertionList.push_back(e <= int(intRange->maxValue));
if (intRange->minValue >= INT_MIN)
exprData.assertionList.push_back(e >= int(intRange->minValue));
return e;
}
if (auto b = std::dynamic_pointer_cast<ExprEngine::BinOpResult>(v)) {
return getExpr(b.get(), exprData);
}
throw std::runtime_error("Internal error: Unhandled value type");
}
#endif
bool ExprEngine::BinOpResult::isIntValueInRange(ExprEngine::DataBase *dataBase, int value) const
{
#ifdef USE_Z3
ExprData exprData;
z3::solver solver(exprData.c);
z3::expr e = ::getExpr(this, exprData);
exprData.addAssertions(solver);
for (auto constraint : dynamic_cast<const Data *>(dataBase)->constraints)
solver.add(::getExpr(constraint, exprData));
solver.add(e == value);
return solver.check() == z3::sat;
#else
(void)dataBase;
(void)value;
return false;
#endif
}
std::string ExprEngine::BinOpResult::getExpr(ExprEngine::DataBase *dataBase) const
{
#ifdef USE_Z3
ExprData exprData;
z3::solver solver(exprData.c);
z3::expr e = ::getExpr(this, exprData);
exprData.addAssertions(solver);
for (auto constraint : dynamic_cast<const Data *>(dataBase)->constraints)
solver.add(::getExpr(constraint, exprData));
solver.add(e);
std::ostringstream os;
os << solver;
return os.str();
#else
(void)dataBase;
return "";
#endif
}
// Todo: This is taken from ValueFlow and modified.. we should reuse it
static int getIntBitsFromValueType(const ValueType *vt, const cppcheck::Platform &platform)
{
if (!vt)
return 0;
switch (vt->type) {
case ValueType::Type::BOOL:
return 1;
case ValueType::Type::CHAR:
return platform.char_bit;
case ValueType::Type::SHORT:
return platform.short_bit;
case ValueType::Type::INT:
return platform.int_bit;
case ValueType::Type::LONG:
return platform.long_bit;
case ValueType::Type::LONGLONG:
return platform.long_long_bit;
default:
return 0;
};
}
static ExprEngine::ValuePtr getValueRangeFromValueType(const std::string &name, const ValueType *vt, const cppcheck::Platform &platform)
{
if (!vt || !(vt->isIntegral() || vt->isFloat()) || vt->pointer)
return ExprEngine::ValuePtr();
int bits = getIntBitsFromValueType(vt, platform);
if (bits == 1) {
return std::make_shared<ExprEngine::IntRange>(name, 0, 1);
} else if (bits > 1) {
if (vt->sign == ValueType::Sign::UNSIGNED) {
return std::make_shared<ExprEngine::IntRange>(name, 0, ((int128_t)1 << bits) - 1);
} else {
return std::make_shared<ExprEngine::IntRange>(name, -((int128_t)1 << (bits - 1)), ((int128_t)1 << (bits - 1)) - 1);
}
}
switch (vt->type) {
case ValueType::Type::FLOAT:
return std::make_shared<ExprEngine::FloatRange>(name, std::numeric_limits<float>::min(), std::numeric_limits<float>::max());
case ValueType::Type::DOUBLE:
return std::make_shared<ExprEngine::FloatRange>(name, std::numeric_limits<double>::min(), std::numeric_limits<double>::max());
case ValueType::Type::LONGDOUBLE:
return std::make_shared<ExprEngine::FloatRange>(name, std::numeric_limits<long double>::min(), std::numeric_limits<long double>::max());
default:
return ExprEngine::ValuePtr();
};
}
static void call(const std::vector<ExprEngine::Callback> &callbacks, const Token *tok, ExprEngine::ValuePtr value, Data *dataBase)
{
if (value) {
for (ExprEngine::Callback f : callbacks) {
f(tok, *value, dataBase);
}
}
}
static ExprEngine::ValuePtr executeExpression(const Token *tok, Data &data);
static ExprEngine::ValuePtr executeReturn(const Token *tok, Data &data)
{
ExprEngine::ValuePtr retval = executeExpression(tok->astOperand1(), data);
call(data.callbacks, tok, retval, &data);
return retval;
}
static ExprEngine::ValuePtr truncateValue(ExprEngine::ValuePtr val, const ValueType *valueType, Data &data)
{
if (!valueType)
return val;
if (valueType->pointer != 0)
return val;
if (!valueType->isIntegral())
return val; // TODO
int bits = getIntBitsFromValueType(valueType, *data.settings);
if (bits == 0)
// TODO
return val;
if (auto range = std::dynamic_pointer_cast<ExprEngine::IntRange>(val)) {
if (range->minValue == range->maxValue) {
int128_t newValue = truncateInt(range->minValue, bits, valueType->sign == ValueType::Sign::SIGNED ? 's' : 'u');
if (newValue == range->minValue)
return val;
return std::make_shared<ExprEngine::IntRange>(ExprEngine::str(newValue), newValue, newValue);
}
if (auto typeRange = getValueRangeFromValueType("", valueType, *data.settings)) {
auto typeIntRange = std::dynamic_pointer_cast<ExprEngine::IntRange>(typeRange);
if (typeIntRange) {
if (range->minValue >= typeIntRange->minValue && range->maxValue <= typeIntRange->maxValue)
return val;
}
}
return std::make_shared<ExprEngine::IntegerTruncation>(data.getNewSymbolName(), val, bits, valueType->sign == ValueType::Sign::SIGNED ? 's' : 'u');
}
// TODO
return val;
}
static ExprEngine::ValuePtr executeAssign(const Token *tok, Data &data)
{
ExprEngine::ValuePtr rhsValue = executeExpression(tok->astOperand2(), data);
ExprEngine::ValuePtr assignValue;
if (tok->str() == "=")
assignValue = rhsValue;
else {
// "+=" => "+"
std::string binop(tok->str());
binop = binop.substr(0, binop.size() - 1);
ExprEngine::ValuePtr lhsValue = executeExpression(tok->astOperand1(), data);
assignValue = simplifyValue(std::make_shared<ExprEngine::BinOpResult>(binop, lhsValue, rhsValue));
}
const Token *lhsToken = tok->astOperand1();
assignValue = truncateValue(assignValue, lhsToken->valueType(), data);
call(data.callbacks, tok, assignValue, &data);
if (lhsToken->varId() > 0) {
data.assignValue(lhsToken, lhsToken->varId(), assignValue);
} else if (lhsToken->str() == "[") {
auto arrayValue = data.getArrayValue(lhsToken->astOperand1());
if (arrayValue) {
// Is it array initialization?
const Token *arrayInit = lhsToken->astOperand1();
if (arrayInit && arrayInit->variable() && arrayInit->variable()->nameToken() == arrayInit) {
if (assignValue->type == ExprEngine::ValueType::StringLiteralValue)
arrayValue->assign(ExprEngine::ValuePtr(), assignValue);
} else {
auto indexValue = executeExpression(lhsToken->astOperand2(), data);
arrayValue->assign(indexValue, assignValue);
}
}
} else if (lhsToken->isUnaryOp("*")) {
auto pval = executeExpression(lhsToken->astOperand1(), data);
if (pval && pval->type == ExprEngine::ValueType::AddressOfValue) {
auto val = std::dynamic_pointer_cast<ExprEngine::AddressOfValue>(pval);
if (val)
data.assignValue(lhsToken, val->varId, assignValue);
} else if (pval && pval->type == ExprEngine::ValueType::BinOpResult) {
auto b = std::dynamic_pointer_cast<ExprEngine::BinOpResult>(pval);
if (b && b->binop == "+") {
std::shared_ptr<ExprEngine::ArrayValue> arr;
ExprEngine::ValuePtr offset;
if (b->op1->type == ExprEngine::ValueType::ArrayValue) {
arr = std::dynamic_pointer_cast<ExprEngine::ArrayValue>(b->op1);
offset = b->op2;
} else {
arr = std::dynamic_pointer_cast<ExprEngine::ArrayValue>(b->op2);
offset = b->op1;
}
if (arr && offset) {
arr->assign(offset, assignValue);
}
}
}
} else if (Token::Match(lhsToken, ". %name%")) {
auto structVal = executeExpression(lhsToken->astOperand1(), data);
if (structVal && structVal->type == ExprEngine::ValueType::StructValue)
data.assignStructMember(tok, &*std::static_pointer_cast<ExprEngine::StructValue>(structVal), lhsToken->strAt(1), assignValue);
}
return assignValue;
}
static ExprEngine::ValuePtr executeFunctionCall(const Token *tok, Data &data)
{
std::vector<ExprEngine::ValuePtr> argValues;
for (const Token *argtok : getArguments(tok)) {
auto val = executeExpression(argtok, data);
argValues.push_back(val);
if (!argtok->valueType() || (argtok->valueType()->constness & 1) == 1)
continue;
if (auto arrayValue = std::dynamic_pointer_cast<ExprEngine::ArrayValue>(val)) {
ValueType vt(*argtok->valueType());
vt.pointer = 0;
auto anyVal = getValueRangeFromValueType(data.getNewSymbolName(), &vt, *data.settings);
arrayValue->assign(ExprEngine::ValuePtr(), anyVal);
} else if (auto addressOf = std::dynamic_pointer_cast<ExprEngine::AddressOfValue>(val)) {
ValueType vt(*argtok->valueType());
vt.pointer = 0;
if (vt.isIntegral() && argtok->valueType()->pointer == 1)
data.assignValue(argtok, addressOf->varId, getValueRangeFromValueType(data.getNewSymbolName(), &vt, *data.settings));
}
}
if (!tok->valueType() && tok->astParent())
throw std::runtime_error("Expression '" + tok->expressionString() + "' has unknown type!");
auto val = getValueRangeFromValueType(data.getNewSymbolName(), tok->valueType(), *data.settings);
call(data.callbacks, tok, val, &data);
return val;
}
static ExprEngine::ValuePtr executeArrayIndex(const Token *tok, Data &data)
{
auto arrayValue = data.getArrayValue(tok->astOperand1());
if (arrayValue) {
auto indexValue = executeExpression(tok->astOperand2(), data);
auto conditionalValues = arrayValue->read(indexValue);
for (auto value: conditionalValues)
call(data.callbacks, tok, value.second, &data);
if (conditionalValues.size() == 1 && !conditionalValues[0].first)
return conditionalValues[0].second;
return std::make_shared<ExprEngine::ConditionalValue>(data.getNewSymbolName(), conditionalValues);
}
// TODO: Pointer value..
executeExpression(tok->astOperand1(), data);
executeExpression(tok->astOperand2(), data);
return ExprEngine::ValuePtr();
}
static ExprEngine::ValuePtr executeCast(const Token *tok, Data &data)
{
const Token *expr = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
auto val = executeExpression(expr, data);
if (expr->valueType() && expr->valueType()->type == ::ValueType::Type::VOID && expr->valueType()->pointer > 0) {
::ValueType vt(*tok->valueType());
vt.pointer = 0;
auto range = getValueRangeFromValueType(data.getNewSymbolName(), &vt, *data.settings);
if (tok->valueType()->pointer == 0)
return range;
bool uninit = false, null = false;
if (val && val->type == ExprEngine::ValueType::PointerValue) {
null = std::static_pointer_cast<ExprEngine::PointerValue>(val)->null;
uninit = std::static_pointer_cast<ExprEngine::PointerValue>(val)->uninitData;
}
return std::make_shared<ExprEngine::PointerValue>(data.getNewSymbolName(), range, null, uninit);
}
if (val)
// TODO: Cast this..
return val;
return getValueRangeFromValueType(data.getNewSymbolName(), tok->valueType(), *data.settings);
}
static ExprEngine::ValuePtr executeDot(const Token *tok, Data &data)
{
if (!tok->astOperand1() || !tok->astOperand1()->varId())
return ExprEngine::ValuePtr();
std::shared_ptr<ExprEngine::StructValue> structValue = std::dynamic_pointer_cast<ExprEngine::StructValue>(data.getValue(tok->astOperand1()->varId(), nullptr, nullptr));
if (!structValue) {
if (tok->originalName() == "->") {
std::shared_ptr<ExprEngine::PointerValue> pointerValue = std::dynamic_pointer_cast<ExprEngine::PointerValue>(data.getValue(tok->astOperand1()->varId(), nullptr, nullptr));
if (pointerValue) {
call(data.callbacks, tok->astOperand1(), pointerValue, &data);
structValue = std::dynamic_pointer_cast<ExprEngine::StructValue>(pointerValue->data);
} else {
call(data.callbacks, tok->astOperand1(), data.getValue(tok->astOperand1()->varId(), nullptr, nullptr), &data);
}
}
if (!structValue)
return ExprEngine::ValuePtr();
}
call(data.callbacks, tok->astOperand1(), structValue, &data);
return structValue->getValueOfMember(tok->astOperand2()->str());
}
static ExprEngine::ValuePtr executeBinaryOp(const Token *tok, Data &data)
{
ExprEngine::ValuePtr v1 = executeExpression(tok->astOperand1(), data);
ExprEngine::ValuePtr v2 = executeExpression(tok->astOperand2(), data);
if (v1 && v2) {
auto result = simplifyValue(std::make_shared<ExprEngine::BinOpResult>(tok->str(), v1, v2));
call(data.callbacks, tok, result, &data);
return result;
}
return ExprEngine::ValuePtr();
}
static ExprEngine::ValuePtr executeAddressOf(const Token *tok, Data &data)
{
auto addr = std::make_shared<ExprEngine::AddressOfValue>(data.getNewSymbolName(), tok->astOperand1()->varId());
call(data.callbacks, tok, addr, &data);
return addr;
}
static ExprEngine::ValuePtr executeDeref(const Token *tok, Data &data)
{
ExprEngine::ValuePtr pval = executeExpression(tok->astOperand1(), data);
if (pval) {
auto addressOf = std::dynamic_pointer_cast<ExprEngine::AddressOfValue>(pval);
if (addressOf) {
auto val = data.getValue(addressOf->varId, tok->valueType(), tok);
call(data.callbacks, tok, val, &data);
return val;
}
auto pointer = std::dynamic_pointer_cast<ExprEngine::PointerValue>(pval);
if (pointer) {
auto val = pointer->data;
call(data.callbacks, tok, val, &data);
return val;
}
}
return ExprEngine::ValuePtr();
}
static ExprEngine::ValuePtr executeVariable(const Token *tok, Data &data)
{
auto val = data.getValue(tok->varId(), tok->valueType(), tok);
call(data.callbacks, tok, val, &data);
return val;
}
static ExprEngine::ValuePtr executeKnownMacro(const Token *tok, Data &data)
{
auto val = std::make_shared<ExprEngine::IntRange>(data.getNewSymbolName(), tok->getKnownIntValue(), tok->getKnownIntValue());
call(data.callbacks, tok, val, &data);
return val;
}
static ExprEngine::ValuePtr executeNumber(const Token *tok)
{
if (tok->valueType()->isFloat()) {
long double value = MathLib::toDoubleNumber(tok->str());
return std::make_shared<ExprEngine::FloatRange>(tok->str(), value, value);
}
int128_t value = MathLib::toLongNumber(tok->str());
return std::make_shared<ExprEngine::IntRange>(tok->str(), value, value);
}
static ExprEngine::ValuePtr executeStringLiteral(const Token *tok, Data &data)
{
std::string s = tok->str();
return std::make_shared<ExprEngine::StringLiteralValue>(data.getNewSymbolName(), s.substr(1, s.size()-2));
}
static ExprEngine::ValuePtr executeExpression1(const Token *tok, Data &data)
{
if (tok->str() == "return")
return executeReturn(tok, data);
if (tok->isAssignmentOp())
// TODO: Handle more operators
return executeAssign(tok, data);
if (tok->astOperand1() && tok->astOperand2() && tok->str() == "[")
return executeArrayIndex(tok, data);
if (tok->str() == "(") {
if (!tok->isCast())
return executeFunctionCall(tok, data);
return executeCast(tok, data);
}
if (tok->str() == ".")
return executeDot(tok, data);
if (tok->astOperand1() && tok->astOperand2())
return executeBinaryOp(tok, data);
if (tok->isUnaryOp("&") && Token::Match(tok->astOperand1(), "%var%"))
return executeAddressOf(tok, data);
if (tok->isUnaryOp("*"))
return executeDeref(tok, data);
if (tok->varId())
return executeVariable(tok, data);
if (tok->isName() && tok->hasKnownIntValue())
return executeKnownMacro(tok, data);
if (tok->isNumber() || tok->tokType() == Token::Type::eChar)
return executeNumber(tok);
if (tok->tokType() == Token::Type::eString)
return executeStringLiteral(tok, data);
return ExprEngine::ValuePtr();
}
static ExprEngine::ValuePtr executeExpression(const Token *tok, Data &data)
{
return translateUninitValueToRange(executeExpression1(tok, data), tok->valueType(), data);
}
static ExprEngine::ValuePtr createVariableValue(const Variable &var, Data &data);
static void execute(const Token *start, const Token *end, Data &data)
{
for (const Token *tok = start; tok != end; tok = tok->next()) {
if (Token::Match(tok, "[;{}]"))
data.trackProgramState(tok);
if (Token::Match(tok, "for|while|switch ("))
// TODO this is a bailout
return;
// Variable declaration..
if (tok->variable() && tok->variable()->nameToken() == tok) {