-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathEffectiveSan.cpp
More file actions
4520 lines (4226 loc) · 154 KB
/
EffectiveSan.cpp
File metadata and controls
4520 lines (4226 loc) · 154 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
/*
* __ __ _ _ ____
* ___ / _|/ _| ___ ___| |_(_)_ _____/ ___| __ _ _ __
* / _ \ |_| |_ / _ \/ __| __| \ \ / / _ \___ \ / _` | '_ \
* | __/ _| _| __/ (__| |_| |\ V / __/___) | (_| | | | |
* \___|_| |_| \___|\___|\__|_| \_/ \___|____/ \__,_|_| |_|
*
* Gregory J. Duck.
*
* Copyright (c) 2018 The National University of Singapore.
* All rights reserved.
*
* This file is distributed under the University of Illinois Open Source
* License. See the LICENSE file for details.
*/
/*
* This is the EffectiveSan LLVM IR pass. It is responsible for:
* - Inserting type and bounds instrumentation
* - Replacing memory allocation (heap/stack/global) with a "typed" version
* - Generating type meta data.
*
* For more information, see the paper:
* Gregory J. Duck and Roland H. C. Yap. 2018. EffectiveSan: Type and
* Memory Error Detection using Dynamically Typed C/C++. In Proceedings
* of 39th ACM SIGPLAN Conference on Programming Language Design and
* Implementation (PLDI’18). ACM, New York, NY, USA, 15 pages.
* https://doi.org/10.1145/3192366.3192388
*/
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#pragma clang diagnostic ignored "-Wc99-extensions"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <cxxabi.h>
#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/SpecialCaseList.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MD5.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Transforms/Utils/Local.h"
extern "C"
{
#include "effective.h"
#include "lowfat_config.inc"
}
// #define EFFECTIVE_INSTRUMENTATION_DEBUG 1
// #define EFFECTIVE_LAYOUT_DEBUG 1
#ifndef EFFECTIVE_INSTRUMENTATION_DEBUG
#define EFFECTIVE_DEBUG_PRINT(...) /* NOP */
#else
#define EFFECTIVE_DEBUG_PRINT(msg, ...) fprintf(stderr, (msg), ##__VA_ARGS__)
#endif
#define EFFECTIVE_FATAL_ERROR(message) \
llvm::report_fatal_error(message, /*GenCrashDiag=*/false)
#define EFFECTIVE_LOG2(x) (64 - clzll((x)-1))
#define EFFECTIVE_BSWAP64(x) __builtin_bswap64(x)
#define EFFECTIVE_CLZLL(x) clzll(x)
#define TYPE_META_PREFIX "EFFECTIVE_TYPE_"
#define TYPE_INFO_PREFIX "EFFECTIVE_INFO_"
#define BASIC_TYPE_TAG "EFFECTIVE_BASIC_TYPE_"
#define ENUM_TYPE_TAG "EFFECTIVE_ENUM_TYPE_"
#define POINTER_TYPE_TAG "EFFECTIVE_POINTER_TYPE_"
#define STRUCT_TYPE_TAG "EFFECTIVE_STRUCT_TYPE_"
#define CLASS_TYPE_TAG "EFFECTIVE_CLASS_TYPE_"
#define UNION_TYPE_TAG "EFFECTIVE_UNION_TYPE_"
#define FUNCTION_TYPE_TAG "EFFECTIVE_FUNCTION_TYPE_"
#define NEW_ARRAY_TYPE_TAG "EFFECTIVE_NEW_ARRAY_TYPE_"
#define VPTR_TYPE_TAG "EFFECTIVE_VPTR_TYPE_"
#define LAYOUT_TAG "EFFECTIVE_LAYOUT_"
/*
* Fool-proof "leading zero count" implementation. Also works for "0".
*/
static size_t clzll(uint64_t x)
{
if (x == 0)
return 64;
uint64_t bit = (uint64_t)1 << 63;
size_t count = 0;
while ((x & bit) == 0)
{
count++;
bit >>= 1;
}
return count;
}
/*
* Hash value.
*/
union HashVal
{
uint8_t i8[16];
uint16_t i16[8];
uint32_t i32[4];
uint64_t i64[2];
};
struct HashContext
{
llvm::MD5 cxt;
};
static void update(HashContext &Cxt, const char *data, size_t len)
{
llvm::ArrayRef<uint8_t> array((const uint8_t *)data, len);
Cxt.cxt.update(array);
}
static HashVal final(HashContext &Cxt)
{
HashVal val;
Cxt.cxt.final(val.i8);
return val;
}
/*
* Type information.
*/
struct TypeEntry
{
bool isInt8; // Type is int8_t;
std::string name; // Type human-readable name.
HashVal hash; // Type hash value.
llvm::Constant *typeMeta; // Type meta-data value.
};
typedef std::map<llvm::DIType *, TypeEntry> TypeCache;
typedef std::map<llvm::DIType *, std::string> TypeNames;
typedef std::map<llvm::DIType *, llvm::Constant *> TypeInfos;
typedef std::map<llvm::DIType *, HashVal> TypeHashes;
struct TypeInfo
{
TypeCache cache;
TypeNames names;
TypeInfos infos;
TypeHashes hashes;
};
/*
* Layout information.
*/
struct LayoutEntry
{
size_t offset;
llvm::DIType *type;
uint64_t hash;
uint64_t finalHash;
intptr_t lb;
intptr_t ub;
bool priority;
bool deleted;
};
typedef std::multimap<size_t, LayoutEntry> LayoutInfo;
typedef std::map<size_t, LayoutEntry *> FlattenedLayoutInfo;
/*
* Type/bounds check information.
*/
struct CheckEntry
{
llvm::Value *bounds;
llvm::DIType *allocType;
size_t allocSize;
};
typedef std::map<llvm::Value *, CheckEntry> CheckInfo;
typedef std::map<llvm::Value *, llvm::Value *> ValueInfo;
struct BoundsEntry
{
llvm::Value *bounds;
ssize_t lb; // Sub-object LB
ssize_t ub; // Sub-object UB
};
typedef std::map<llvm::Value *, BoundsEntry> BoundsInfo;
struct BoundsCheckEntry
{
llvm::Value *ptr;
llvm::Instruction *instr;
llvm::Value *widePtr;
intptr_t wideLb;
intptr_t wideUb;
ssize_t accessOffset;
size_t accessSize;
llvm::Value *accessVarSize; // For variable-sized access.
bool redundant;
};
typedef std::map<llvm::Value *, std::vector<BoundsCheckEntry>>
BoundsCheckInfo;
/*
* Flexible Array Members (FAMs).
*/
struct FAM
{
llvm::DIType *type;
size_t offset;
};
/*
* Insertion point.
*/
struct InsertPoint
{
llvm::BasicBlock *bb;
llvm::BasicBlock::iterator itr;
};
/*
* Options.
*/
static llvm::cl::opt<bool> option_no_escapes("effective-no-escapes",
llvm::cl::desc("Do not instrument pointer escapes"));
static llvm::cl::opt<bool> option_no_globals("effective-no-globals",
llvm::cl::desc("Do not instrument global variables"));
static llvm::cl::opt<bool> option_no_stack("effective-no-stack",
llvm::cl::desc("Do not instrument stack objects"));
static llvm::cl::opt<std::string> option_blacklist("effective-blacklist",
llvm::cl::desc("Do not instrument code based on the given blacklist"),
llvm::cl::init("-"));
static llvm::cl::opt<bool> option_warnings("effective-warnings",
llvm::cl::desc("Enable warning messages"));
static llvm::cl::opt<unsigned> option_max_sub_objs("effective-max-sub-objs",
llvm::cl::desc("Maximum number of allowable sub-objects per type"),
llvm::cl::init(10000));
static llvm::cl::opt<bool> option_debug("effective-debug",
llvm::cl::desc("Enable debug output"));
/*
* Pre-defined types and objects.
*/
static llvm::Type *BoundsTy = nullptr;
static llvm::StructType *EntryTy = nullptr;
static llvm::StructType *TypeTy = nullptr;
static llvm::StructType *InfoTy = nullptr;
static llvm::StructType *InfoEntryTy = nullptr;
static llvm::StructType *ObjMetaTy = nullptr;
static llvm::Constant *EmptyEntry = nullptr;
static llvm::Constant *Int8TyMeta = nullptr;
static llvm::Constant *BoundsNonFat = nullptr;
static llvm::DIType *Int8Ty = nullptr;
static llvm::DIType *Int16Ty = nullptr;
static llvm::DIType *Int32Ty = nullptr;
static llvm::DIType *Int64Ty = nullptr;
static llvm::DIType *Int128Ty = nullptr;
static llvm::DIType *Int8PtrTy = nullptr;
static llvm::Module *Module = nullptr; // Used by normalizePointerType()
// (not ideal but too messy to fix).
static std::unique_ptr<llvm::SpecialCaseList> Blacklist = nullptr;
static std::map<size_t, llvm::StructType *> metaCache;
static std::map<size_t, llvm::StructType *> infoCache;
/*
* Prototypes.
*/
static llvm::DIType *normalizeType(llvm::DIType *Ty);
static void buildMemberLayout(llvm::DIType *Ty, size_t offset, const FAM &fam,
intptr_t lb, intptr_t ub, bool priority, bool inherited, TypeInfo &tInfo,
LayoutInfo &layout);
static void buildTypeHumanName(llvm::DIType *Ty, std::string &humanName,
TypeInfo &tInfo);
static HashVal buildTypeHash(llvm::DIType *Ty, TypeInfo &tInfo);
static std::pair<intptr_t, intptr_t> calculateBoundsConstant(
const llvm::DataLayout &DL, llvm::Constant *Ptr);
static const BoundsEntry &calculateBounds(llvm::Module &M, llvm::Function &F,
llvm::Value *Ptr, TypeInfo &tInfo, CheckInfo &cInfo, BoundsInfo &bInfo);
static bool canInstrumentGlobal(llvm::GlobalVariable &GV);
/*
* Test if something is blacklisted or not.
*/
static bool isBlacklisted(const char *section, llvm::StringRef Name)
{
if (Blacklist == nullptr)
return false;
if (Blacklist->inSection(section, Name))
return true;
return false;
}
/*
* Test if a type represents a vptr or not.
*/
static bool isVPtrType(llvm::DIType *Ty)
{
auto DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty);
if (DerivedTy == nullptr)
return false;
if (DerivedTy->getTag() != llvm::dwarf::DW_TAG_member)
return false;
llvm::StringRef name = DerivedTy->getName();
const char prefix[] = "_vptr$";
return (name.str().compare(0, sizeof(prefix)-1, prefix) == 0);
}
/*
* Test if a type represents a C++ new[] wrapper.
*/
static bool isNewArrayType(llvm::DIType *Ty)
{
if (Ty == nullptr)
return false;
auto CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty);
if (CompositeTy == nullptr)
return false;
if (CompositeTy->getTag() != llvm::dwarf::DW_TAG_structure_type)
return false;
llvm::StringRef name = CompositeTy->getName();
const char prefix[] = "new ";
return (name.str().compare(0, sizeof(prefix)-1, prefix) == 0);
}
/*
* Test if a type is anonymous or not.
*/
static bool isAnonymousType(llvm::DIType *Ty)
{
auto CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty);
if (CompositeTy == nullptr)
return false;
switch (CompositeTy->getTag())
{
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type:
case llvm::dwarf::DW_TAG_union_type:
break;
default:
return false;
}
llvm::StringRef name = CompositeTy->getName();
if (name != "")
return false;
llvm::StringRef ident = CompositeTy->getIdentifier();
if (ident == "")
return true;
if (ident.size() >= 4 && ident[0] == '_' && ident[1] == 'Z' &&
ident[2] == 'T' && ident[3] == 'S' &&
ident.find("Ut", 4) != std::string::npos)
{
int status = 0;
char* res = abi::__cxa_demangle(ident.str().c_str(), NULL, NULL,
&status);
if (status != 0)
return false;
bool isAnon = (strstr(res, "unnamed type#") != NULL);
free(res);
return isAnon;
}
return false;
}
/*
* Normalize an integer type.
*/
static llvm::DIType *normalizeIntegerType(llvm::DIType *Ty)
{
if (Ty == nullptr)
return Int8Ty;
if (auto *BasicTy = llvm::dyn_cast<llvm::DIBasicType>(Ty))
{
switch (BasicTy->getEncoding())
{
case llvm::dwarf::DW_ATE_signed_char:
case llvm::dwarf::DW_ATE_unsigned_char:
case llvm::dwarf::DW_ATE_boolean:
return Int8Ty;
case llvm::dwarf::DW_ATE_signed:
case llvm::dwarf::DW_ATE_unsigned:
case llvm::dwarf::DW_ATE_UTF:
switch (BasicTy->getSizeInBits())
{
case 8:
return Int8Ty;
case 16:
return Int16Ty;
case 32:
return Int32Ty;
case 64:
return Int64Ty;
case 128:
return Int128Ty;
default:
return Ty;
}
default:
return Ty;
}
}
else if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty))
{
if (CompositeTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
return Int32Ty;
else
return Ty;
}
else
return Ty;
}
/*
* Normalize a pointer type.
*/
static llvm::DIType *normalizePointerType(llvm::DIType *Ty)
{
if (Ty == nullptr)
return Int8PtrTy;
auto DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty);
if (DerivedTy == nullptr)
return Int8PtrTy;
switch (DerivedTy->getTag())
{
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_rvalue_reference_type:
break;
default:
return Int8PtrTy;
}
Ty = DerivedTy->getBaseType().resolve();
if (Ty == nullptr)
return Int8PtrTy;
Ty = normalizeType(Ty);
llvm::DIBuilder builder(*Module);
Ty = builder.createPointerType(Ty, sizeof(void *)*CHAR_BIT);
return Ty;
}
/*
* "Normalize" a type.
*/
static llvm::DIType *normalizeType(llvm::DIType *Ty)
{
while (Ty != nullptr)
{
if (isVPtrType(Ty))
return Int8PtrTy;
else if (llvm::isa<llvm::DIBasicType>(Ty))
return normalizeIntegerType(Ty);
else if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty))
{
switch (DerivedTy->getTag())
{
case llvm::dwarf::DW_TAG_ptr_to_member_type:
{
// C++ pointers-to-member types are treated as size_t.
return Int64Ty;
}
case llvm::dwarf::DW_TAG_typedef:
case llvm::dwarf::DW_TAG_member:
case llvm::dwarf::DW_TAG_inheritance:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_volatile_type:
case llvm::dwarf::DW_TAG_atomic_type:
case llvm::dwarf::DW_TAG_restrict_type:
break;
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_rvalue_reference_type:
return normalizePointerType(Ty);
default:
return Ty;
}
Ty = DerivedTy->getBaseType().resolve();
}
else if (auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty))
{
switch (CompositeTy->getTag())
{
case llvm::dwarf::DW_TAG_enumeration_type:
return Int32Ty;
case llvm::dwarf::DW_TAG_array_type:
Ty = CompositeTy->getBaseType().resolve();
break;
default:
return Ty;
}
}
else
return Ty;
}
return Int8Ty; // Give up
}
/*
* Determine if two types are equivalent or not. Note that this function
* need not be complete, since it is only used for optimization. It
* currently does not handle some tricky cases like anonymous types.
*/
static bool isTypeEquivalent(llvm::DIType *Ty1, llvm::DIType *Ty2)
{
if (Ty1 == Ty2)
return true;
Ty1 = normalizeType(Ty1);
Ty2 = normalizeType(Ty2);
if (Ty1 == Ty2)
return true;
if (Ty1 == nullptr || Ty2 == nullptr)
return false;
auto *BasicTy1 = llvm::dyn_cast<llvm::DIBasicType>(Ty1);
auto *BasicTy2 = llvm::dyn_cast<llvm::DIBasicType>(Ty2);
if (BasicTy1 != nullptr && BasicTy2 != nullptr)
{
if (BasicTy1->getSizeInBits() != BasicTy2->getSizeInBits())
return false;
unsigned encoding = BasicTy1->getEncoding();
switch (encoding)
{
case llvm::dwarf::DW_ATE_signed_char:
case llvm::dwarf::DW_ATE_unsigned_char:
case llvm::dwarf::DW_ATE_boolean:
encoding = llvm::dwarf::DW_ATE_signed_char;
break;
case llvm::dwarf::DW_ATE_signed:
case llvm::dwarf::DW_ATE_unsigned:
case llvm::dwarf::DW_ATE_UTF:
encoding = llvm::dwarf::DW_ATE_signed;
break;
default:
break;
}
switch (BasicTy2->getEncoding())
{
case llvm::dwarf::DW_ATE_signed_char:
case llvm::dwarf::DW_ATE_unsigned_char:
case llvm::dwarf::DW_ATE_boolean:
return (encoding == llvm::dwarf::DW_ATE_signed_char);
case llvm::dwarf::DW_ATE_signed:
case llvm::dwarf::DW_ATE_unsigned:
case llvm::dwarf::DW_ATE_UTF:
return (encoding == llvm::dwarf::DW_ATE_signed);
default:
return (encoding == BasicTy2->getEncoding());
}
}
auto *DerivedTy1 = llvm::dyn_cast<llvm::DIDerivedType>(Ty1);
auto *DerivedTy2 = llvm::dyn_cast<llvm::DIDerivedType>(Ty2);
if (DerivedTy1 != nullptr && DerivedTy2 != nullptr)
{
switch (DerivedTy1->getTag())
{
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_rvalue_reference_type:
break;
default:
return false;
}
switch (DerivedTy2->getTag())
{
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_rvalue_reference_type:
return isTypeEquivalent(DerivedTy1->getBaseType().resolve(),
DerivedTy2->getBaseType().resolve());
default:
return false;
}
}
return false;
}
/*
* Get a type's size in bytes.
*/
static size_t getSizeOfType(llvm::DIType *Ty)
{
size_t size = Ty->getSizeInBits() / CHAR_BIT;
return size;
}
/*
* Get T from a T[N] type, else return nullptr.
*/
static llvm::DIType *getArrayElementType(llvm::DIType *Ty)
{
if (Ty == nullptr)
return nullptr;
auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty);
if (CompositeTy == nullptr)
return nullptr;
if (CompositeTy->getTag() != llvm::dwarf::DW_TAG_array_type)
return nullptr;
return CompositeTy->getBaseType().resolve();
}
/*
* Get the inner sub-range of a (multidim) array.
*/
static std::pair<ssize_t, ssize_t> getArrayRange(llvm::DIType *Ty)
{
auto EMPTY = std::make_pair<ssize_t, ssize_t>(1, 0);
if (Ty == nullptr)
return EMPTY;
auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty);
if (CompositeTy == nullptr)
return EMPTY;
if (CompositeTy->getTag() != llvm::dwarf::DW_TAG_array_type)
return EMPTY;
auto Elements = CompositeTy->getElements();
if (Elements.size() < 1)
return EMPTY;
auto Element = Elements[Elements.size()-1];
auto SubRange = llvm::dyn_cast<llvm::DISubrange>(Element);
if (SubRange == nullptr)
return EMPTY;
return std::make_pair<ssize_t, ssize_t>(SubRange->getLowerBound(),
SubRange->getCount());
}
/*
* Get the composite type of a struct/class/union type, else return nullptr.
*/
static llvm::DICompositeType *getStructType(llvm::DIType *Ty)
{
auto *CompositeTy = llvm::dyn_cast<llvm::DICompositeType>(Ty);
if (CompositeTy == nullptr)
return nullptr;
switch (CompositeTy->getTag())
{
case llvm::dwarf::DW_TAG_structure_type:
case llvm::dwarf::DW_TAG_class_type:
case llvm::dwarf::DW_TAG_union_type:
return CompositeTy;
default:
return nullptr;
}
}
/*
* Hash a string value.
*/
static HashVal hashString(const char *tag, const char *s)
{
HashContext cxt;
size_t len = strlen(tag);
update(cxt, tag, len);
len = strlen(s);
update(cxt, s, len);
return final(cxt);
}
/*
* Hash a hash value.
*/
static HashVal hashHash(const char *tag, HashVal val)
{
HashContext cxt;
size_t len = strlen(tag);
update(cxt, tag, len);
update(cxt, (char *)val.i8, sizeof(val.i8));
return final(cxt);
}
/*****************************************************************************/
/* WARNINGS */
/*****************************************************************************/
class DiagnosticInfoEffectiveSan : public llvm::DiagnosticInfo
{
private:
static int DK;
std::string msg;
public:
DiagnosticInfoEffectiveSan(const std::string &msg) :
llvm::DiagnosticInfo(DK, llvm::DS_Warning), msg(msg) { }
void print(llvm::DiagnosticPrinter &dp) const override;
static void init()
{
DK = llvm::getNextAvailablePluginDiagnosticKind();
}
};
int DiagnosticInfoEffectiveSan::DK = 0;
void DiagnosticInfoEffectiveSan::print(llvm::DiagnosticPrinter &dp) const
{
dp << "[EffectiveSan] " << msg << "\n";
}
static void warning(llvm::Module &M, const std::string &msg)
{
if (option_warnings)
M.getContext().diagnose(DiagnosticInfoEffectiveSan(msg));
}
/*****************************************************************************/
/* META DATA */
/*****************************************************************************/
/*
* Type meta data generation.
*
* There are currently two kinds of type meta data:
* - EFFECTIVE_TYPE: is the type meta data used for type checking; and
* - EFFECTIVE_INFO: is the type meta data used for error messages.
*
* The "TYPE" version is used for runtime type checking so is designed for
* speed, whereas the "INFO" version is designed for error messages.
*/
static llvm::StructType *makeTypeMetaType(llvm::Module &M, size_t len)
{
auto i = metaCache.find(len);
if (i != metaCache.end())
return i->second;
llvm::LLVMContext &Cxt = M.getContext();
std::string name("EFFECTIVE_TYPE");
if (len > 0)
{
name += '_';
name += std::to_string(len);
}
llvm::StructType *Ty = llvm::StructType::create(Cxt, name);
if (len == 0)
TypeTy = Ty;
std::vector<llvm::Type *> Fields;
Fields.push_back(llvm::Type::getInt64Ty(Cxt)); /* hash */
Fields.push_back(llvm::Type::getInt64Ty(Cxt)); /* hash2 */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* size */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* size_fam */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* offset_fam */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* sanity */
Fields.push_back(llvm::Type::getInt64Ty(Cxt)); /* magic */
Fields.push_back(llvm::Type::getInt64Ty(Cxt)); /* mask */
Fields.push_back(InfoTy->getPointerTo()); /* info */
Fields.push_back(llvm::Type::getInt64Ty(Cxt)); /* next */
llvm::ArrayType *LayoutTy = llvm::ArrayType::get(EntryTy, len);
Fields.push_back(LayoutTy); /* layout */
Ty->setBody(Fields);
metaCache.insert(std::make_pair(len, Ty));
return Ty;
}
static llvm::StructType *makeTypeInfoType(llvm::Module &M, size_t len)
{
auto i = infoCache.find(len);
if (i != infoCache.end())
return i->second;
llvm::LLVMContext &Cxt = M.getContext();
std::string name("EFFECTIVE_INFO");
if (len > 0)
{
name += '_';
name += std::to_string(len);
}
llvm::StructType *Ty = llvm::StructType::create(Cxt, name);
if (len == 0)
InfoTy = Ty;
std::vector<llvm::Type *> Fields;
Fields.push_back(llvm::Type::getInt8PtrTy(Cxt)); /* name */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* size */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* num_entries */
Fields.push_back(llvm::Type::getInt32Ty(Cxt)); /* flags */
Fields.push_back(InfoTy->getPointerTo()); /* next */
llvm::ArrayType *EntriesTy = llvm::ArrayType::get(InfoEntryTy, len);
Fields.push_back(EntriesTy); /* entries */
Ty->setBody(Fields);
infoCache.insert(std::make_pair(len, Ty));
return Ty;
}
static TypeEntry &addTypeEntry(TypeInfo &tInfo, llvm::DIType *Ty,
std::string &name, HashVal hash, llvm::Constant *Meta,
bool isInt8 = false)
{
TypeEntry entry = {isInt8, name, hash, Meta};
auto i = tInfo.cache.insert(std::make_pair(Ty, entry));
return i.first->second;
}
static uint64_t getTypeHash(llvm::DIType *Ty, HashVal hash)
{
if (Ty == nullptr || Ty == Int8Ty)
return EFFECTIVE_TYPE_INT8_HASH;
if (Ty == Int8PtrTy)
return EFFECTIVE_TYPE_INT8_PTR_HASH;
return EFFECTIVE_BSWAP64(hash.i64[0]);
}
/*
* If a type T can be coerced to another type U, then return a special hash
* value representing (U)T. Note that we do not return U's hash to prevent
* transitive coercions, e.g. (int *) -> (void *) -> (float *).
*/
static uint64_t getCoercedTypeHash(llvm::DIType *Ty)
{
if (auto *DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty))
{
switch (DerivedTy->getTag())
{
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_rvalue_reference_type:
return EFFECTIVE_COERCED_INT8_PTR_HASH;
default:
return EFFECTIVE_TYPE_NIL_HASH;
}
}
return EFFECTIVE_TYPE_NIL_HASH;
}
/*
* Add an entry to the layout.
*/
static void addLayoutEntry(LayoutInfo &layout, TypeInfo &tInfo, size_t offset,
llvm::DIType *Ty, intptr_t lb, intptr_t ub, bool priority)
{
Ty = normalizeType(Ty);
HashVal hash = buildTypeHash(Ty, tInfo);
uint64_t hval = getTypeHash(Ty, hash);
// Check for duplicate entries. These can happen for unions, for example.
auto range = layout.equal_range(offset);
bool found = false;
for (auto i = range.first; i != range.second; ++i)
{
if (i->second.hash == hval)
{
// Widen the bounds to accomodate both sub-objects. This is not
// ideal but better than not handling this case entirely.
i->second.lb = std::min(i->second.lb, lb);
i->second.ub = std::max(i->second.ub, ub);
i->second.priority = false;
found = true;
}
}
if (found)
return;
// No existing entry, so create one:
#ifdef EFFECTIVE_LAYOUT_DEBUG
std::string name;
buildTypeHumanName(Ty, name, tInfo);
fprintf(stderr, "\t%s [%+zd] (%zd..%zd) <%.16lX> {%zd} ", name.c_str(),
offset, lb, ub, hval, (intptr_t)hval);
Ty->dump();
#endif
LayoutEntry entry = {offset, Ty, hval, 0, lb, ub, priority, false};
layout.insert(std::make_pair(offset, entry));
// Add entry for any type coercion:
hval = getCoercedTypeHash(Ty);
if (hval == EFFECTIVE_TYPE_NIL_HASH)
return;
found = false;
for (auto i = range.first; i != range.second; ++i)
{
if (i->second.hash == hval)
{
i->second.lb = std::min(i->second.lb, lb);
i->second.ub = std::max(i->second.ub, ub);
found = true;
}
}
if (found)
return;
#ifdef EFFECTIVE_LAYOUT_DEBUG
fprintf(stderr, "\t+coerced <%.16lX> {%zd}\n", hval, (intptr_t)hval);
#endif
LayoutEntry coercedEntry = {offset, Ty, hval, 0, lb, ub, priority, false};
layout.insert(std::make_pair(offset, coercedEntry));
}
/*
* Get the "normalized" type of a struct/class member, and any additional
* information about the member (bit-fielf, inheritance, etc.). Does not
* flatten arrays.
*/
static llvm::DIType *getMemberType(llvm::DIType *Ty, size_t &offset,
bool &isStatic, bool &isBitField, bool &isInheritance, bool &isVirtual)
{
while (true)
{
if (isVPtrType(Ty))
{
Ty = Int8PtrTy;
break;
}
auto DerivedTy = llvm::dyn_cast<llvm::DIDerivedType>(Ty);
if (DerivedTy == nullptr)
break;
if (DerivedTy->isStaticMember())
{
isStatic = true;
break;
}
bool found = false;
switch (DerivedTy->getTag())
{
case llvm::dwarf::DW_TAG_member:
if (DerivedTy->isBitField())
{
// Special handling of bitfields: we want the offset of
// the "containing" integer type. Alternatively we could
// just disallow pointers to bitfields altogether.
llvm::Constant *Offset =
DerivedTy->getStorageOffsetInBits();
if (Offset != nullptr &&
llvm::isa<llvm::ConstantInt>(Offset))
{
auto *Int = llvm::dyn_cast<llvm::ConstantInt>(Offset);
offset += Int->getZExtValue();
Ty = DerivedTy->getBaseType().resolve();
Ty = normalizeIntegerType(Ty);
isBitField = true;
break;
}
}
offset += DerivedTy->getOffsetInBits();
Ty = DerivedTy->getBaseType().resolve();
break;
case llvm::dwarf::DW_TAG_inheritance:
if (Ty->getFlags() & llvm::DINode::DIFlags::FlagVirtual)
isVirtual = true;
isInheritance = true;
offset += DerivedTy->getOffsetInBits();
Ty = DerivedTy->getBaseType().resolve();
break;
case llvm::dwarf::DW_TAG_typedef:
case llvm::dwarf::DW_TAG_const_type:
case llvm::dwarf::DW_TAG_volatile_type:
case llvm::dwarf::DW_TAG_atomic_type:
case llvm::dwarf::DW_TAG_restrict_type:
Ty = DerivedTy->getBaseType().resolve();
break;
case llvm::dwarf::DW_TAG_ptr_to_member_type:
Ty = Int64Ty;
break;
case llvm::dwarf::DW_TAG_pointer_type:
case llvm::dwarf::DW_TAG_reference_type:
case llvm::dwarf::DW_TAG_rvalue_reference_type:
found = true;
break;
default:
EFFECTIVE_FATAL_ERROR("unknown derived type");
}
if (found)
break;
}
return normalizeIntegerType(Ty);