-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdbjson.cpp
5321 lines (5088 loc) · 193 KB
/
dbjson.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
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
#include "main.hpp"
#include "dbjson.hpp"
#include "compat.h"
#include "json.hpp"
#include "clang/AST/RecordLayout.h"
#include <stdlib.h>
#include <random>
#include <algorithm>
int DEBUG_NOTICE;
//disabled useddef feature for now, since no one uses it
constexpr bool DISABLED = false;
thread_local size_t exprOrd;
typedef std::string name_t;
typedef int to_index;
typedef int from_index;
typedef std::multimap<name_t,std::pair<to_index,from_index>> db_t;
typedef std::unordered_map<name_t,std::vector<std::pair<to_index,from_index>>> ndb_t;
int load_taint_function_database(std::string filepath, ndb_t &exact, ndb_t ®ex){
std::fstream f;
f.open(filepath, std::ios_base::in);
std::stringstream s;
s<<f.rdbuf();
auto database = json::JSON::Load(s.str());
// std::cout<<database.dump();
for(auto d : database["exact_name"].ObjectRange()){
name_t name = d.first;
to_index to_index;
from_index from_index;
exact.insert({name,{}});
for(int i=0;i<d.second.size();i++){
to_index = d.second[i][0].ToInt();
from_index = d.second[i][1].ToInt();
exact[name].push_back({to_index,from_index});
// std::cout<<name<<' '<<to_index<<' '<<from_index<<'\n';
}
}
for(auto d : database["regex_name"].ObjectRange()){
name_t name = d.first;
to_index to_index;
from_index from_index;
regex.insert({name,{}});
for(int i=0;i<d.second.size();i++){
to_index = d.second[i][0].ToInt();
from_index = d.second[i][1].ToInt();
regex[name].push_back({to_index,from_index});
// std::cout<<name<<' '<<to_index<<' '<<from_index<<'\n';
}
}
return 0;
}
QualType resolve_Typedef_Integer_Type(QualType T) {
if (T->getTypeClass()==Type::Typedef) {
const TypedefType *tpd = cast<TypedefType>(T);
TypedefNameDecl* D = tpd->getDecl();
return resolve_Typedef_Integer_Type(D->getTypeSourceInfo()->getType());
}
else if (T->getTypeClass()==Type::Builtin) {
return T;
}
else {
llvm::errs() << "UNSUPPORTED enum type: " << T->getTypeClassName() << "\n";
assert(0);
}
}
static std::string getFullFunctionNamespace(const FunctionDecl *D) {
std::list<std::string> nsl;
const DeclContext* DC = D->getEnclosingNamespaceContext();
if ((DC) && (isa<NamespaceDecl>(DC))) {
const NamespaceDecl* ND = static_cast<const NamespaceDecl*>(DC);
nsl.push_front(ND->getNameAsString());
DC = ND->getParent()->getEnclosingNamespaceContext();
while (isa<NamespaceDecl>(DC)) {
const NamespaceDecl* ND = static_cast<const NamespaceDecl*>(DC);
nsl.push_front(ND->getNameAsString());
DC = ND->getParent()->getEnclosingNamespaceContext();
}
}
std::string fns;
for (auto i = nsl.begin(); i!=nsl.end(); ++i) {
if (i==nsl.begin()) {
fns+=*i;
}
else {
fns+="::"+*i;
}
}
return fns;
}
void DbJSONClassConsumer::getFuncDeclSignature(const FunctionDecl* D, std::string& fdecl_sig) {
if(opts.assert && Visitor.CTAList.find(D)!=Visitor.CTAList.end()) {
fdecl_sig += "__compiletime_assert";
}
else {
fdecl_sig += D->getName();
}
fdecl_sig += ' ';
fdecl_sig += walkTypedefType(D->getType()).getAsString();
}
bool isOwnedTagDeclType(QualType DT) {
if (DT->getTypeClass()==Type::Elaborated) {
TagDecl *OwnedTagDecl = cast<ElaboratedType>(DT)->getOwnedTagDecl();
if (OwnedTagDecl) {
if (isa<RecordDecl>(OwnedTagDecl)) {
const RecordDecl* rD = static_cast<RecordDecl*>(OwnedTagDecl);
if (rD->isCompleteDefinition()) {
return true;
}
}
else if (isa<EnumDecl>(OwnedTagDecl)) {
const EnumDecl* eD = static_cast<EnumDecl*>(OwnedTagDecl);
if (eD->isCompleteDefinition()) {
return true;
}
}
}
}
else if (DT->getTypeClass()==Type::Pointer) {
const PointerType *tp = cast<PointerType>(DT);
QualType ptrT = tp->getPointeeType();
return isOwnedTagDeclType(ptrT);
}
else if (DT->getTypeClass()==Type::IncompleteArray) {
const IncompleteArrayType *tp = cast<IncompleteArrayType>(DT);
QualType elT = tp->getElementType();
return isOwnedTagDeclType(elT);
}
else if (DT->getTypeClass()==Type::ConstantArray) {
const ConstantArrayType *tp = cast<ConstantArrayType>(DT);
QualType elT = tp->getElementType();
return isOwnedTagDeclType(elT);
}
return false;
}
bool DbJSONClassVisitor::declGroupHasNamedFields(Decl** Begin, unsigned NumDecls) {
if (NumDecls == 1) {
return isNamedField(*Begin);
}
Decl** End = Begin + NumDecls;
TagDecl* TD = dyn_cast<TagDecl>(*Begin);
if (TD)
++Begin;
for ( ; Begin != End; ++Begin) {
if (isNamedField(*Begin)) return true;
}
return false;
}
bool DbJSONClassVisitor::fieldMatch(Decl* D, const FieldDecl* FD) {
return (D==FD);
}
int DbJSONClassVisitor::fieldIndexInGroup(Decl** Begin, unsigned NumDecls, const FieldDecl* FD, int startIndex) {
int idx = startIndex;
if (NumDecls == 1) {
if (fieldMatch(*Begin,FD)) {
return idx;
}
}
Decl** End = Begin + NumDecls;
TagDecl* TD = dyn_cast<TagDecl>(*Begin);
if (TD) {
++Begin;
++idx;
}
for ( ; Begin != End; ++Begin) {
if (fieldMatch(*Begin,FD)) {
return idx;
}
}
return -1;
}
bool DbJSONClassVisitor::isNamedField(Decl* D) {
if (D->getKind()==Decl::Field) {
FieldDecl* innerD = cast<FieldDecl>(D);
if (innerD->getIdentifier()) return true;
else {
QualType T = innerD->getType();
if (T->getTypeClass()==Type::Record) {
const RecordType *tp = cast<RecordType>(T);
if (hasNamedFields(tp->getDecl())) {
return true;
}
}
}
}
if (D->getKind()==Decl::Record) {
RecordDecl* innerD = cast<RecordDecl>(D);
QualType T = Context.getRecordType(innerD);
if (innerD->isCompleteDefinition()) {
if (innerD->getIdentifier()) {
return true;
}
else {
const RecordType *tp = cast<RecordType>(T);
return hasNamedFields(tp->getDecl());
}
}
}
return false;
}
bool DbJSONClassVisitor::emptyRecordDecl(RecordDecl* rD) {
if (rD->isCompleteDefinition()) {
const DeclContext *DC = cast<DeclContext>(rD);
return DC->decls_begin()==DC->decls_end();
}
return false;
}
bool DbJSONClassVisitor::hasNamedFields(RecordDecl* rD) {
if (rD->isCompleteDefinition()) {
const DeclContext *DC = cast<DeclContext>(rD);
SmallVector<Decl*, 2> Decls;
for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
D != DEnd; ++D) {
if (D->isImplicit())
continue;
QualType CurDeclType = getDeclType(*D);
if (!Decls.empty() && !CurDeclType.isNull()) {
QualType BaseType = GetBaseType(CurDeclType);
if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
if (!BaseType.isNull() && isa<TagType>(BaseType) &&
cast<TagType>(BaseType)->getDecl() == Decls[0]) {
Decls.push_back(*D);
continue;
}
}
if (!Decls.empty()) {
if (declGroupHasNamedFields(Decls.data(), Decls.size())) return true;
Decls.clear();
}
if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
Decls.push_back(*D);
continue;
}
if (isNamedField(*D)) return true;
}
if (!Decls.empty()) {
if (declGroupHasNamedFields(Decls.data(), Decls.size())) return true;
Decls.clear();
}
}
return false;
}
int DbJSONClassVisitor::fieldToIndex(const FieldDecl* FD, const RecordDecl* RD) {
int fieldIndex = 0;
if (RD->isCompleteDefinition()) {
const DeclContext *DC = cast<DeclContext>(RD);
SmallVector<Decl*, 2> Decls;
for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
D != DEnd; ++D) {
if ((isa<TagDecl>(*D))&&(!cast<TagDecl>(*D)->isCompleteDefinition())) {
continue;
}
if (D->isImplicit()) {
if (fieldMatch(*D,FD)) {
return fieldIndex;
}
continue;
}
QualType CurDeclType = getDeclType(*D);
if (!Decls.empty() && !CurDeclType.isNull()) {
QualType BaseType = GetBaseType(CurDeclType);
if (!BaseType.isNull() && isa<ElaboratedType>(BaseType))
BaseType = cast<ElaboratedType>(BaseType)->getNamedType();
if (!BaseType.isNull() && isa<TagType>(BaseType) &&
cast<TagType>(BaseType)->getDecl() == Decls[0]) {
Decls.push_back(*D);
continue;
}
}
if (!Decls.empty()) {
int idx = fieldIndexInGroup(Decls.data(), Decls.size(), FD, fieldIndex);
if (idx>=0) {
return idx;
}
fieldIndex+=Decls.size();
Decls.clear();
}
if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
Decls.push_back(*D);
continue;
}
if (fieldMatch(*D,FD)) {
return fieldIndex;
}
++fieldIndex;
}
if (!Decls.empty()) {
int idx = fieldIndexInGroup(Decls.data(), Decls.size(), FD, fieldIndex);
if (idx>=0) {
return idx;
}
Decls.clear();
}
}
return -1;
}
void DbJSONClassVisitor::setSwitchData(const Expr* caseExpr, int64_t* enumv,
std::string* enumstr, std::string* macroValue, std::string* raw_code, int64_t* exprVal) {
SourceManager& SM = Context.getSourceManager();
if (caseExpr->IgnoreCasts()->getExprLoc().isMacroID()) {
*macroValue = Lexer::getSourceText(CharSourceRange(caseExpr->IgnoreCasts()->getSourceRange(),true),
SM,Context.getLangOpts()).str();
}
llvm::raw_string_ostream cstream(*raw_code);
caseExpr->printPretty(cstream,nullptr,Context.getPrintingPolicy());
cstream.flush();
const DeclRefExpr* DRE = lookForBottomDeclRef(caseExpr);
if (DRE && (DRE->getDecl()->getKind()==Decl::EnumConstant)) {
const EnumConstantDecl* ecd = static_cast<const EnumConstantDecl*>(DRE->getDecl());
*enumv = ecd->getInitVal().extOrTrunc(63).getExtValue();
*enumstr = ecd->getIdentifier()->getName().str();
}
Expr::EvalResult Res;
if((!caseExpr->isValueDependent()) && caseExpr->isEvaluatable(Context) && tryEvaluateIntegerConstantExpr(caseExpr,Res)){
*exprVal = Res.Val.getInt().extOrTrunc(63).getExtValue();
}
}
const DbJSONClassVisitor::callfunc_info_t* DbJSONClassVisitor::handleCallMemberExpr(const MemberExpr* ME,
std::set<ValueHolder> callrefs,
std::set<DbJSONClassVisitor::LiteralHolder> literalRefs,
const QualType* baseType, const CallExpr* CE) {
/* Member function call through a given object {obj.fun()}
*/
std::stringstream protostr;
std::stringstream className;
std::stringstream refObj;
const ValueDecl *VD = ME->getMemberDecl();
if (VD->getKind()==Decl::Field) {
const FieldDecl* FD = static_cast<const FieldDecl*>(VD);
const FunctionProtoType* proto;
if (baseType) {
proto = lookForFunctionType(*baseType);
}
else {
proto = lookForFunctionType(FD->getType());
}
if (proto) {
protostr << " [" << proto->getNumParams() << "] ("
<< ME->getExprLoc().printToString(Context.getSourceManager()) << ") "
<< (const void*)proto;
noticeTypeClass(QualType(proto,0));
}
else {
return 0;
}
const RecordDecl* RD = FD->getParent();
int fieldIndex = fieldToIndex(FD,RD);
QualType RT = Context.getRecordType(RD);
const Type *tp = cast<Type>(RT);
if(RT->getTypeClass()==Type::Record) {
className << "[" << RT.getAsString() << ":" << tp << "]";
}
const DeclRefExpr* DRE = lookForBottomDeclRef(static_cast<const Expr*>(*(ME->child_begin())));
if (DRE) {
refObj << "[" << DRE->getNameInfo().getAsString() << ":" << DRE << "]";
}
DBG(opts.debug, llvm::outs() << " notice MemberRefCall: "
<< refObj.str() << " " << className.str() << " " << FD->getName().str() << "()"
<< " i(" << fieldIndex << ")" << protostr.str() << "\n" );
callfunc_info_t nfo = {};
nfo.FunctionDeclOrProtoType = (void*)proto;
nfo.refObj = (void*)DRE;
if (!DRE) {
nfo.funcproto = true;
}
nfo.classType = RT;
nfo.fieldIndex = fieldIndex;
nfo.callrefs = callrefs;
nfo.literalRefs = literalRefs;
nfo.CE = CE;
nfo.ord = exprOrd++;
/* We might have member function call from implicit (e.g. operator()) function */
if (lastFunctionDef) {
nfo.csid = lastFunctionDef->csIdMap.at(getCurrentCSPtr());
std::pair<std::set<callfunc_info_t>::iterator,bool> rv = lastFunctionDef->funcinfo.insert(nfo);
for(unsigned long i=0; i<proto->getNumParams(); i++) {
QualType T = proto->getParamType(i);
lastFunctionDef->refTypes.insert(T);
}
/* Now save information that for this particular MemberExpr that there was a parent CallExpr involved */
if ((MEHaveParentCE.find(ME)!=MEHaveParentCE.end())&&(MEHaveParentCE[ME]!=CE)) {
llvm::errs() << "Multiple parent CE for MemberExpr\n";
llvm::errs() << "MemberExpr:\n";
ME->dumpColor();
llvm::errs() << "CallExpr involved:\n";
CE->dumpColor();
llvm::errs() << "CallExpr already present:\n";
MEHaveParentCE[ME]->dumpColor();
assert(0);
}
MEHaveParentCE[ME] = CE;
return &(*(rv.first));
}
}
return 0;
}
const DbJSONClassVisitor::callfunc_info_t* DbJSONClassVisitor::handleCallVarDecl(const VarDecl* VD, const DeclRefExpr* DRE,
std::set<ValueHolder> callrefs,
std::set<DbJSONClassVisitor::LiteralHolder> literalRefs,
const QualType* baseType, const CallExpr* CE) {
/* Function call through the pointer to function {(*pfun)()}
*/
const FunctionProtoType* proto;
if (baseType) {
proto = lookForFunctionType(*baseType);
}
else {
proto = lookForFunctionType(VD->getType());
}
/* We could have K&R function prototype without information about its arguments; ignore */
if (!proto) return 0;
std::stringstream protostr;
if (proto) {
protostr << " [" << proto->getNumParams() << "] ("
<< DRE->getExprLoc().printToString(Context.getSourceManager()) << ") "
<< (const void*)proto;
noticeTypeClass(QualType(proto,0));
}
DBG(opts.debug, llvm::outs() << " notice FunctionRefCall: "
<< "(*" << DRE->getNameInfo().getAsString() << ")"
<< protostr.str() << "\n" );
callfunc_info_t nfo = {};
nfo.FunctionDeclOrProtoType = (void*)proto;
nfo.refObj = (void*)DRE;
nfo.callrefs = callrefs;
nfo.literalRefs = literalRefs;
nfo.CE = CE;
nfo.ord = exprOrd++;
/* We might have pfunction call through pointer from implicit (e.g. operator()) function */
if (lastFunctionDef) {
nfo.csid = lastFunctionDef->csIdMap.at(getCurrentCSPtr());
std::pair<std::set<callfunc_info_t>::iterator,bool> rv = lastFunctionDef->funcinfo.insert(nfo);
for(unsigned long i=0; i<proto->getNumParams(); i++) {
QualType T = proto->getParamType(i);
lastFunctionDef->refTypes.insert(T);
}
return &(*(rv.first));
}
return 0;
}
bool DbJSONClassVisitor::handleCallAddress(int64_t Addr,const Expr* AddressExpr,
std::set<ValueHolder> callrefs,
std::set<DbJSONClassVisitor::LiteralHolder> literalRefs, const QualType* baseType,
const CallExpr* CE, const CStyleCastExpr* CSCE) {
/* We've come here when there was a call expression that expands into integer value
*/
const FunctionProtoType* proto;
if (baseType) {
proto = lookForFunctionType(*baseType);
}
else {
return false;
}
/* We could have K&R function prototype without information about its arguments; ignore */
if (!proto) return false;
std::stringstream protostr;
if (proto) {
protostr << " [" << proto->getNumParams() << "] (" << ") "
<< (const void*)proto;
noticeTypeClass(QualType(proto,0));
}
DBG(opts.debug, llvm::outs() << " notice FunctionAddressCall: "
<< "(*" << Addr << ")"
<< protostr.str() << "\n" );
callfunc_info_t nfo = {};
nfo.FunctionDeclOrProtoType = (void*)proto;
nfo.refObj = (void*)AddressExpr;
nfo.callrefs = callrefs;
nfo.literalRefs = literalRefs;
nfo.CE = CE;
nfo.ord = exprOrd++;
/* We might have pfunction call through pointer from implicit (e.g. operator()) function */
if (lastFunctionDef) {
nfo.csid = lastFunctionDef->csIdMap.at(getCurrentCSPtr());
lastFunctionDef->funcinfo.insert(nfo);
for(unsigned long i=0; i<proto->getNumParams(); i++) {
QualType T = proto->getParamType(i);
lastFunctionDef->refTypes.insert(T);
}
VarRef_t VR;
std::vector<VarRef_t> vVR;
CStyleCastOrType valuecast;
if (CSCE) {
valuecast.setCast(const_cast<CStyleCastExpr*>(CSCE));
}
VarRef_t CEVR;
VR.VDCAMUAS.setAddress(Addr,valuecast);
vVR.push_back(VR);
CEVR.VDCAMUAS.setRefCall(CE,Addr,valuecast);
std::pair<std::set<DereferenceInfo_t>::iterator,bool> rv =
lastFunctionDef->derefList.insert(DereferenceInfo_t(CEVR,0,vVR,"",getCurrentCSPtr(),DereferenceFunction));
const_cast<DbJSONClassVisitor::DereferenceInfo_t*>(&(*rv.first))->addOrd(nfo.ord);
const_cast<DbJSONClassVisitor::DereferenceInfo_t*>(&(*rv.first))->evalExprInner =
[CE,this](const DereferenceInfo_t *d){
llvm::raw_string_ostream exprstream(d->Expr);
exprstream << "[" << getAbsoluteLocation(CE->getBeginLoc()) << "]: ";
CE->printPretty(exprstream,nullptr,Context.getPrintingPolicy());
exprstream.flush();
};
return true;
}
return false;
}
bool DbJSONClassVisitor::handleCallStmtExpr(const Expr* E,
std::set<ValueHolder> callrefs,
std::set<DbJSONClassVisitor::LiteralHolder> literalRefs, const QualType* baseType, const CallExpr* CE) {
/* We've come here when there was a call expression that expands into StmtExpr,
* really clear way of invoking a function, like:
* (*({do {} while(0); pfun;}))('x',3.0);
* All things considered there might be many variables that constitute the callee
* (but the StmtExpr last expression value must be a function one way or the other)
*/
const StmtExpr* SE = static_cast<const StmtExpr*>(E);
const CompoundStmt* CS = SE->getSubStmt();
CompoundStmt::const_body_iterator i = CS->body_begin();
if (i!=CS->body_end()) {
/* We have at least one statement in the body; get the last one */
i = CS->body_end()-1;
const Stmt* S = *i;
const Expr* callee = cast<Expr>(S);
if (callee->getStmtClass()==Stmt::ImplicitCastExprClass) {
const ImplicitCastExpr* ICE = static_cast<const ImplicitCastExpr*>(callee);
const Expr* E = lookForDeclReforMemberExpr(static_cast<const Expr*>(ICE));
return (E && (handleCallDeclRefOrMemberExpr(E,callrefs,literalRefs,0,CE)));
}
else if (callee->getStmtClass()==Stmt::ParenExprClass) {
const ParenExpr* PE = static_cast<const ParenExpr*>(callee);
QualType baseType = PE->getType();
const Expr* SubExpr = PE->getSubExpr();
if (SubExpr->getStmtClass()==Stmt::ConditionalOperatorClass) {
const ConditionalOperator* CO = static_cast<const ConditionalOperator*>(SubExpr);
return (handleCallConditionalOperator(CO,callrefs,literalRefs,&baseType,CE));
}
else if (SubExpr->getStmtClass()==Stmt::CStyleCastExprClass) {
const CStyleCastExpr* CSCE = static_cast<const CStyleCastExpr*>(SubExpr);
const Expr* E = lookForDeclReforMemberExpr(static_cast<const Expr*>(SubExpr));
return (E && (handleCallDeclRefOrMemberExpr(E,callrefs,literalRefs,&baseType,CE)));
}
}
}
return false;
}
bool DbJSONClassVisitor::handleCallDeclRefOrMemberExpr(const Expr* E,
std::set<ValueHolder> callrefs,
std::set<DbJSONClassVisitor::LiteralHolder> literalRefs, const QualType* baseType, const CallExpr* CE) {
/* We've come here when there was a call expression that expands into DeclRef or Member expressions
* In the first case it can be ordinary function call {fun()} or function call through the pointer
* to function {(*pfun)()}
* In the second case it's a member function call through a given object {obj.fun()}
*/
if (E->getStmtClass()==Stmt::DeclRefExprClass) {
const DeclRefExpr* DRE = static_cast<const DeclRefExpr*>(E);
const ValueDecl* v = DRE->getDecl();
if (v->getKind()==Decl::Function) {
/* We might be calling some built-in function at declaration scope and
none of the functions were defined yet */
if (lastFunctionDef) {
const FunctionDecl* FD = static_cast<const FunctionDecl*>(v);
if (FD->getIdentifier()!=0) {
// We might be calling some special function (like operator new) in C++ which doesn't have proper identifier
DBG(opts.debug, llvm::outs() << " notice FunctionCall: "
<< FD->getName().str() << "() [" << FD->getNumParams() << "] ("
<< FD->getLocation().printToString(Context.getSourceManager()) << ") "
<< (const void*)FD << "\n" );
callfunc_info_t nfo = {};
if (FD->hasBody()) {
nfo.FunctionDeclOrProtoType = (void*)(FD->getDefinition());
}
else {
nfo.FunctionDeclOrProtoType = (void*)(FD->getCanonicalDecl());
}
nfo.callrefs = callrefs;
nfo.literalRefs = literalRefs;
nfo.CE = CE;
nfo.ord = exprOrd++;
nfo.csid = lastFunctionDef->csIdMap.at(getCurrentCSPtr());
lastFunctionDef->funcinfo.insert(nfo);
/* If we used '*' operator on direct function name place it into the derefs array */
VarRef_t VR;
std::vector<VarRef_t> vVR;
VarRef_t CEVR;
const UnaryOperator* UO = lookForUnaryOperatorInCallExpr(CE);
if (UO) {
VR.VDCAMUAS.setUnary(UO);
vVR.push_back(VR);
CEVR.VDCAMUAS.setCall(CE);
if (lastFunctionDef) {
std::pair<std::set<DereferenceInfo_t>::iterator,bool> rv =
lastFunctionDef->derefList.insert(DereferenceInfo_t(CEVR,0,vVR,"",getCurrentCSPtr(),DereferenceFunction));
const_cast<DbJSONClassVisitor::DereferenceInfo_t*>(&(*rv.first))->addOrd(nfo.ord);
const_cast<DbJSONClassVisitor::DereferenceInfo_t*>(&(*rv.first))->evalExprInner =
[CE,this](const DereferenceInfo_t *d){
llvm::raw_string_ostream exprstream(d->Expr);
exprstream << "[" << getAbsoluteLocation(CE->getBeginLoc()) << "]: ";
CE->printPretty(exprstream,nullptr,Context.getPrintingPolicy());
exprstream.flush();
};
return true;
}
}
return true;
}
}
}
else if ((v->getKind()==Decl::Var)||(v->getKind()==Decl::ParmVar)) {
const VarDecl* VD = static_cast<const VarDecl*>(v);
const DbJSONClassVisitor::callfunc_info_t* nfo = handleCallVarDecl(VD,DRE,callrefs,literalRefs, baseType, CE);
if (nfo) {
VarRef_t VR;
std::vector<VarRef_t> vVR;
VarRef_t CEVR;
const UnaryOperator* UO = lookForUnaryOperatorInCallExpr(CE);
if (UO) {
VR.VDCAMUAS.setUnary(UO);
vVR.push_back(VR);
CEVR.VDCAMUAS.setRefCall(CE,UO);
}
else {
const ArraySubscriptExpr* ASE = lookForArraySubscriptExprInCallExpr(CE);
if (ASE) {
VR.VDCAMUAS.setAS(ASE);
vVR.push_back(VR);
CEVR.VDCAMUAS.setRefCall(CE,ASE);
}
else {
VR.VDCAMUAS.setValue(VD);
vVR.push_back(VR);
CEVR.VDCAMUAS.setRefCall(CE,VD);
}
}
if (lastFunctionDef) {
std::pair<std::set<DereferenceInfo_t>::iterator,bool> rv =
lastFunctionDef->derefList.insert(DereferenceInfo_t(CEVR,0,vVR,"",getCurrentCSPtr(),DereferenceFunction));
const_cast<DbJSONClassVisitor::DereferenceInfo_t*>(&(*rv.first))->addOrd(nfo->ord);
const_cast<DbJSONClassVisitor::DereferenceInfo_t*>(&(*rv.first))->evalExprInner =
[CE,this](const DereferenceInfo_t *d){
llvm::raw_string_ostream exprstream(d->Expr);
exprstream << "[" << getAbsoluteLocation(CE->getBeginLoc()) << "]: ";
CE->printPretty(exprstream,nullptr,Context.getPrintingPolicy());
exprstream.flush();
};
return true;
}
}
return false;
}
}
else if (E->getStmtClass()==Stmt::MemberExprClass) {
const MemberExpr* ME = static_cast<const MemberExpr*>(E);
return handleCallMemberExpr(ME,callrefs,literalRefs, baseType, CE);
}
return false;
}
bool DbJSONClassVisitor::handleCallConditionalOperator(const ConditionalOperator* CO,
std::set<ValueHolder> callrefs,
std::set<DbJSONClassVisitor::LiteralHolder> literalRefs,
const QualType* baseType, const CallExpr* CE) {
const Expr* ELHS = lookForDeclReforMemberExpr(static_cast<const Expr*>(CO->getLHS()));
const Expr* ERHS = lookForDeclReforMemberExpr(static_cast<const Expr*>(CO->getRHS()));
return (ELHS && (handleCallDeclRefOrMemberExpr(ELHS,callrefs,literalRefs,baseType,CE))
&& ERHS && (handleCallDeclRefOrMemberExpr(ERHS,callrefs,literalRefs,baseType,CE)));
}
size_t DbJSONClassVisitor::getFunctionDeclId(const FunctionDecl *FD) {
FD = FD->hasBody() ? FD->getDefinition() : FD->getCanonicalDecl();
if(FD->hasDefiningAttr())
FD = FD->getCanonicalDecl();
// in case of function template instantiations
if(functionTemplateMap.find(FD) != functionTemplateMap.end()){
const FunctionTemplateDecl *FTD = functionTemplateMap.at(FD);
for(auto TD : FTD->redecls()){
if(cast<FunctionTemplateDecl>(TD)->isThisDeclarationADefinition()){
FTD = cast<FunctionTemplateDecl>(TD);
}
}
FD = FTD->getTemplatedDecl();
}
if (FuncMap.find(FD) != FuncMap.end()) {
return FuncMap.at(FD).id;
}
else if (FuncDeclMap.find(FD) != FuncDeclMap.end()) {
return FuncDeclMap.at(FD).id;
}
else if (opts.assert&&(CTAList.find(FD) != CTAList.end())) {
return FuncDeclMap.at(CTA).id;
}
else{
FD->dump();
assert(0 && "Called function not in function maps\n");
}
}
size_t DbJSONClassVisitor::outerFunctionorMethodIdforTagDecl(TagDecl* tD) {
size_t id = SIZE_MAX;
DeclContext* DC = tD->getParentFunctionOrMethod();
if (!DC) return id;
if (isa<FunctionDecl>(DC) || isa<CXXMethodDecl>(DC)) {
const FunctionDecl* FD = static_cast<const FunctionDecl*>(DC);
id = getFunctionDeclId(FD);
}
return id;
}
std::string DbJSONClassVisitor::parentFunctionOrMethodString(TagDecl* tD) {
std::string outerFn;
DeclContext* DC = tD->getParentFunctionOrMethod();
if (!DC) return outerFn;
if (isa<FunctionDecl>(DC)) {
const FunctionDecl* FD = static_cast<const FunctionDecl*>(DC);
if (isCXXTU(Context)) {
std::string nms = getFullFunctionNamespace(FD);
if (!nms.empty()) nms+="::";
outerFn=nms+FD->getNameAsString();
}
else {
outerFn = FD->getNameAsString();
}
}
else if (isa<CXXMethodDecl>(DC)) {
const CXXMethodDecl* MD = static_cast<const CXXMethodDecl*>(DC);
const CXXRecordDecl* RD = MD->getParent();
QualType RT = Context.getRecordType(RD);
std::string _class = RT.getAsString();
outerFn = _class + MD->getNameAsString();
}
return outerFn;
}
std::string DbJSONClassConsumer::getAbsoluteLocation(SourceLocation Loc){
if(Loc.isInvalid())
return "<invalid loc>";
auto &SM = Context.getSourceManager();
SourceLocation ELoc = SM.getExpansionLoc(Loc);
StringRef RPath = SM.getFileEntryForID(SM.getFileID(ELoc))->tryGetRealPathName();
if(RPath.empty()){
//fallback to default
llvm::errs()<<"Failed to get absolute location\n";
llvm::errs()<<Loc.printToString(SM)<<'\n';
return Loc.printToString(SM);
}
PresumedLoc PLoc = SM.getPresumedLoc(ELoc);
if(PLoc.isInvalid())
return "<invalid>";
std::string locstr;
llvm::raw_string_ostream s(locstr);
s << RPath.str() << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
return s.str();
}
std::string DbJSONClassVisitor::getAbsoluteLocation(SourceLocation Loc){
if(Loc.isInvalid())
return "<invalid loc>";
auto &SM = Context.getSourceManager();
SourceLocation ELoc = SM.getExpansionLoc(Loc);
StringRef RPath = SM.getFileEntryForID(SM.getFileID(ELoc))->tryGetRealPathName();
if(RPath.empty()){
//fallback to default
llvm::errs()<<"Failed to get absolute location\n";
llvm::errs()<<Loc.printToString(SM)<<'\n';
return Loc.printToString(SM);
}
PresumedLoc PLoc = SM.getPresumedLoc(ELoc);
if(PLoc.isInvalid())
return "<invalid>";
std::string locstr;
llvm::raw_string_ostream s(locstr);
s << RPath.str() << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
return s.str();
}
std::string DbJSONClassConsumer::render_switch_json(const Expr* cond,
std::vector<std::pair<DbJSONClassVisitor::caseinfo_t,DbJSONClassVisitor::caseinfo_t>>& caselst,
std::string Indent) {
std::stringstream swdata;
std::string condbody;
llvm::raw_string_ostream cstream(condbody);
cond->printPretty(cstream,nullptr,Context.getPrintingPolicy());
cstream.flush();
swdata << Indent << "{\n";
swdata << Indent << "\t\t" << "\"condition\": \"" << json::json_escape(condbody) << "\",\n";
swdata << Indent << "\t\t" << "\"cases\": [\n";
for (auto u = caselst.begin(); u!=caselst.end();) {
swdata << Indent << "\t\t\t\t\t\t\t\t[ ";
DbJSONClassVisitor::caseinfo_t ciLHS = (*u).first;
DbJSONClassVisitor::caseinfo_t ciRHS = (*u).second;
/* Here we have the following entry for single case expression:
* [ expressionValue, enumCodeRepr, macroCodeRepr, rawCodeRepr ]
* expressionValue: this is the computed value of the case constant expression (integer)
* enumCodeRepr: if the case value comes directly from single enum identifier this is the string representation of this identifier
* macroCodeRepr: if the case value comes directly from single macro identifier this is the string representation of this identifier
* rawCodeRepr: this is the raw code representation of the case expression
* ]
* It is possible to use two expressions in the case to represent a interval, i.e. "case 8:12:",
* in this case the case entry looks as follows:
* [ expressionValueLHS, enumCodeReprLHS, macroCodeReprLHS, rawCodeReprLHS,
* expressionValueRHS, enumCodeReprRHS, macroCodeReprRHS, rawCodeReprRHS ]
* where first 4 elements corresponds to the left side of the interval and last 4 elements to the right side of interval
*/
swdata << std::get<3>(ciLHS) << ", " << "\"" << std::get<0>(ciLHS).second << "\", \"" <<
json::json_escape(std::get<1>(ciLHS)) << "\", \"" << json::json_escape(std::get<2>(ciLHS)) << "\"";
if ((!std::get<0>(ciRHS).second.empty()) ||
(!std::get<1>(ciRHS).empty()) || (!std::get<2>(ciRHS).empty())) {
swdata << ", ";
swdata << std::get<3>(ciRHS) << ", " << "\"" << std::get<0>(ciRHS).second << "\", \"" <<
json::json_escape(std::get<1>(ciRHS)) << "\", \"" << json::json_escape(std::get<2>(ciRHS)) << "\"";
}
swdata << " ]";
++u;
if (u!=caselst.end()) swdata << ",";
swdata << "\n";
}
swdata << Indent << "\t\t" << "]\n";
swdata << Indent << "}";
return swdata.str();
}
std::string DbJSONClassVisitor::refvarinfo_t::idString() {
std::stringstream out;
if (type==CALLVAR_FLOATING) {
out << fp;
}
else if (type==CALLVAR_STRING) {
out << "\"" << json::json_escape(s) << "\"";
}
else if (type==CALLVAR_INTEGER) {
int64_t i = (int64_t)id;
out << i;
}
else {
/* MongoDB doesn't take 64bit unsigned values; cast it to signed value then */
int64_t i = (int64_t)id;
out << i;
}
return out.str();
}
std::string DbJSONClassVisitor::refvarinfo_t::LiteralString() {
if (lh.type==LiteralHolder::LiteralChar) {
std::stringstream ss;
ss << lh.prvLiteral.charLiteral;
return ss.str();
}
if (lh.type==LiteralHolder::LiteralInteger) {
std::stringstream ss;
ss << lh.prvLiteral.integerLiteral.extOrTrunc(63).getExtValue();
return ss.str();
}
if (lh.type==LiteralHolder::LiteralString) {
return "\"" + json::json_escape(lh.prvLiteral.stringLiteral) + "\"";
}
if (lh.type==LiteralHolder::LiteralFloat) {
std::stringstream ss;
ss << lh.prvLiteral.floatingLiteral;
return ss.str();
}
return "";
}
void DbJSONClassConsumer::printGlobalArray(int Indentation){
for(auto i = Visitor.getVarMap().begin(); i!=Visitor.getVarMap().end();i++) {
DbJSONClassVisitor::VarData &var_data = i->second;
if(var_data.output == nullptr) continue;
printGlobalEntry(var_data,Indentation);
}
}
void DbJSONClassConsumer::printGlobalEntry(DbJSONClassVisitor::VarData &var_data, int Indentation){
llvm::raw_string_ostream GOut(*var_data.output);
std::string Indent(Indentation,'\t');
const VarDecl *D = var_data.Node;
QualType ST = D->getTypeSourceInfo() ? D->getTypeSourceInfo()->getType() : D->getType();
std::string name = D->getNameAsString();
std::set<QualType> STset;
if (D->getType()!=ST) {
if (ST->getTypeClass()==Type::Typedef) {
/* Clear qualifiers when adding typedef source type to references
* so we could avoid qualification mismatch with global variable type
* and typedef definition
*/
var_data.g_refTypes.insert(ST.withoutLocalFastQualifiers());
STset.insert(ST);
}
}
std::string initstring;
if(D->hasInit()){
llvm::raw_string_ostream initstream(initstring);
D->getInit()->printPretty(initstream,nullptr,Context.getPrintingPolicy());
initstream.flush();
}
std::string def;
clang::PrintingPolicy policy = Context.getPrintingPolicy();
if (opts.adddefs) {
if (isOwnedTagDeclType(ST)) {
policy.IncludeTagDefinition = true;
var_data.g_refTypes.insert(ST);
var_data.g_refTypes.insert(D->getType());
}
llvm::raw_string_ostream defstream(def);
D->print(defstream,policy);
defstream.flush();
}
GOut << Indent << "\t{\n";
GOut << Indent << "\t\t\"name\": \"" << name << "\",\n";
GOut << Indent << "\t\t\"hash\": \"" << var_data.hash << "\",\n";
GOut << Indent << "\t\t\"id\": " << var_data.id << ",\n";
if (opts.adddefs) {
GOut << Indent << "\t\t\"def\": \"" << json::json_escape(def) << "\",\n";
}
std::stringstream globalrefs;
globalrefs << "[ ";
for (auto u = var_data.g_refVars.begin(); u!=var_data.g_refVars.end();) {
globalrefs << " " << Visitor.getVarData(*u).id;
++u;
if (u!=var_data.g_refVars.end()) {
globalrefs << ",";
}
}
globalrefs << " ]";
std::vector<int> decls;
std::stringstream refs;
refs << "[ ";
int n=0;
for (auto u = var_data.g_refTypes.begin(); u!=var_data.g_refTypes.end(); ++n) {
QualType T = *u;
if (isOwnedTagDeclType(T)) decls.push_back(n);
/* Fix for #160
if (STset.find(T)!=STset.end()) decls.push_back(n);*/
refs << " " << Visitor.getTypeData(T).id;
++u;
if (u!=var_data.g_refTypes.end()) {
refs << ",";
}
}