-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathClamBCWriter.cpp
1629 lines (1458 loc) · 56.4 KB
/
ClamBCWriter.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
/*
* Compile LLVM bytecode to ClamAV bytecode.
*
* Copyright (C) 2009-2010 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "bytecode_api.h"
#include "clambc.h"
#include "ClamBCModule.h"
#include "ClamBCUtilities.h"
#include "ClamBCAnalyzer.h"
#include "ClamBCRegAlloc.h"
#include <llvm/Support/DataTypes.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/Analysis/ConstantFolding.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/Dominators.h>
#include <llvm/Analysis/LoopInfo.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/Analysis/ValueTracking.h>
#include <llvm/IR/Attributes.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/CodeGen/IntrinsicLowering.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include <llvm/Pass.h>
#include <llvm/Passes/PassBuilder.h>
#include <llvm/Passes/PassPlugin.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/IR/GetElementPtrTypeIterator.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/InstVisitor.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Support/MemoryBuffer.h>
#include <sstream>
extern "C" const char *clambc_getversion(void);
// There were some things that were in the previous Module, that may or may not be needed at this time. There
// are ways to share data between passes, will do that if it is necessary.
using namespace llvm;
static cl::opt<std::string> MapFile("clambc-map", cl::desc("Write compilation map"),
cl::value_desc("File to write the map to"),
cl::init(""));
static cl::opt<bool>
DumpDI("clambc-dumpdi", cl::Hidden, cl::init(false),
cl::desc("Dump LLVM IR with debug info to standard output"));
static cl::opt<std::string> outFile("clambc-sigfile", cl::desc("Name of output file"),
cl::value_desc("Name of output file"),
cl::init(""));
/*This is necessary if multiple files are used, and put together with llmv-link*/
static cl::opt<std::string> inputSourceFile("clambc-writer-input-source", cl::desc("File containing source code of signature."),
cl::value_desc("File containing source code of signature."),
cl::init(""));
// checks whether the queried functionality level is between min and max.
// a min/max of 0 means no min/max.
static bool checkFunctionalityLevel(unsigned query, unsigned min, unsigned max)
{
if (min && query < min)
return false;
if (max && query > max)
return false;
return true;
}
/*
* This class will do the writing, the output formatting code is mostly stolen from the previous ClamBCModule.
*/
class ClamBCOutputWriter
{
public:
static ClamBCOutputWriter *createClamBCOutputWriter(llvm::StringRef srFileName,
llvm::Module *pMod,
ClamBCAnalysis *pAnalyzer)
{
std::error_code ec;
raw_fd_ostream *rfo = new raw_fd_ostream(srFileName, ec);
formatted_raw_ostream *fro = new formatted_raw_ostream(*rfo);
if (nullptr == fro) {
assert(0 && "FIGURE OUT THE CORRECT WAY TO DIE");
// ClamBCStop();
}
ClamBCOutputWriter *ret = new ClamBCOutputWriter(*fro, pMod, pAnalyzer);
if (nullptr == ret) {
assert(0 && "FIGURE OUT THE CORRECT WAY TO DIE");
// ClamBCStop();
}
return ret;
}
ClamBCOutputWriter(llvm::formatted_raw_ostream &outStream, llvm::Module *pMod, ClamBCAnalysis *pAnalyzer)
: Out(lineBuffer), OutReal(outStream), maxLineLength(0), lastLinePos(0), pMod(pMod), pAnalyzer(pAnalyzer)
{
printGlobals(pMod, pAnalyzer);
}
virtual ~ClamBCOutputWriter()
{
OutReal.flush();
delete (&OutReal);
}
virtual void printEOL()
{
int diff;
Out << "\n";
diff = lineBuffer.size() - lastLinePos;
lastLinePos = lineBuffer.size();
assert(diff > 0);
if (diff > maxLineLength) {
maxLineLength = diff;
}
}
virtual void printOne(char c)
{
Out << c;
}
void printNumber(uint64_t n, bool constant)
{
printNumber(Out, n, constant);
}
void printFixedNumber(uint64_t n, unsigned fixed)
{
printFixedNumber(Out, n, fixed);
}
void printModuleHeader(Module &M, ClamBCAnalysis *pAnalyzer, unsigned maxLine)
{
NamedMDNode *MinFunc = M.getNamedMetadata("clambc.funcmin");
NamedMDNode *MaxFunc = M.getNamedMetadata("clambc.funcmax");
unsigned minfunc = 0;
unsigned maxfunc = 0;
if (MinFunc) {
const MDOperand &op = MinFunc->getOperand(0)->getOperand(0);
ConstantAsMetadata *cas = llvm::cast<ConstantAsMetadata>(op);
assert(llvm::isa<ConstantInt>(cas->getValue()) && "Then what is it?");
ConstantInt *ci = llvm::cast<ConstantInt>(cas->getValue());
minfunc = ci->getLimitedValue();
}
if (MaxFunc) {
const MDOperand &op = MaxFunc->getOperand(0)->getOperand(0);
ConstantAsMetadata *cas = llvm::cast<ConstantAsMetadata>(op);
assert(llvm::isa<ConstantInt>(cas->getValue()) && "Then what is it?");
ConstantInt *ci = llvm::cast<ConstantInt>(cas->getValue());
maxfunc = ci->getLimitedValue();
}
OutReal << "ClamBC";
// Print functionality level
// 0.96 only knows to skip based on bytecode format level, and has no min/max
// verification.
// So if this bytecode is supposed to load on 0.96 use 0.96's format,
// otherwise use post 0.96 format.
// In both cases we output the min/max functionality level fields (using 2
// unused fields from 0.96).
// 0.96 will ignore these and load it (but we already checked it should load
// at least on 0.96 via bytecode format). Post 0.96 will check the fields and
// load/skip based on that.
// For post 0.96 we use a higher format, so 0.96 will not load it.
if (checkFunctionalityLevel(FUNC_LEVEL_096, minfunc, maxfunc)) {
printNumber(OutReal, BC_FORMAT_096, false);
} else {
printNumber(OutReal, BC_FORMAT_LEVEL, false);
}
// Bytecode compile timestamp
time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
// printNumber(now, false); //IT APPEARS THAT I NEED THIS???
printNumber(OutReal, now, false);
const char *user = getenv("SIGNDUSER");
// fallback to $USER
if (!user) {
user = getenv("USER");
}
// Sigmaker name
printString(OutReal, user, 64);
// Target-exclude. TODO: allow override via a global variable.
printNumber(OutReal, 0, false);
printNumber(OutReal, pAnalyzer->getKind(), false);
// functionality level min, max, unusued in 0.96!
printNumber(OutReal, minfunc, false);
printNumber(OutReal, maxfunc, false);
// Some maximum (unused)
printNumber(OutReal, 0, false);
// Compiler version
printString(OutReal, clambc_getversion(), 64);
printNumber(OutReal, pAnalyzer->getExtraTypes().size() + pAnalyzer->getStartTID() - 64, false);
unsigned count = 0;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (I->isDeclaration()) {
continue;
}
count++;
}
printNumber(OutReal, count, false);
// Print 2 magic number to ensure reader works properly
printNumber(OutReal, 0x53e5493e9f3d1c30ull, false);
printFixedNumber(OutReal, 42, 2);
if (maxLine < 4096) {
maxLine = 4096;
}
OutReal << ":" << maxLine << "\n";
// first line must fit into 8k
assert((OutReal.tell() < 8192) && "OutReal too big");
}
void describeType(llvm::raw_ostream &Out, const Type *Ty, Module *M, ClamBCAnalysis *pAnalyzer)
{
if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
printFixedNumber(Out, 1, 1);
assert(!FTy->isVarArg());
printNumber(Out, FTy->getNumParams() + 1, false);
printNumber(Out, pAnalyzer->getTypeID(FTy->getReturnType()), false);
for (FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
I != E; ++I) {
printNumber(Out, pAnalyzer->getTypeID(*I), false);
}
return;
}
if (const StructType *STy = dyn_cast<StructType>(Ty)) {
// get field offsets and insert explicit padding
std::vector<unsigned> elements;
for (unsigned i = 0; i < STy->getNumElements(); i++) {
Type *Ty = STy->getTypeAtIndex(i);
if (isa<PointerType>(Ty)) {
// WriteTypeSymbolic(errs(), STy, M);
assert(0 && "Find replacement for WriteTypeSymbolic");
STy->dump();
ClamBCStop("Pointers inside structs are not supported\n", M);
}
unsigned abiAlign = M->getDataLayout().getABITypeAlignment(Ty);
unsigned typeBits = M->getDataLayout().getTypeSizeInBits(Ty);
if (Ty->isIntegerTy() && 8 * abiAlign < typeBits) {
Ty->dump();
errs() << 8 * abiAlign << " < " << typeBits << "\n";
// we've set up a targetdata where alignof(32) == 32, alignof(64) == 64,
// so that each type is maximally aligned on all architectures.
ClamBCStop("Internal error: ABI alignment less than typesize for integer!\n",
M);
}
elements.push_back(pAnalyzer->getTypeID(Ty));
}
printFixedNumber(Out, STy->isPacked() ? 2 : 3, 1);
printNumber(Out, elements.size(), false);
for (std::vector<unsigned>::iterator I = elements.begin(), E = elements.end();
I != E; ++I) {
printNumber(Out, *I, false);
}
return;
}
if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
printFixedNumber(Out, 4, 1);
printNumber(Out, ATy->getNumElements(), false);
printNumber(Out, pAnalyzer->getTypeID(ATy->getElementType()), false);
return;
}
if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
printFixedNumber(Out, 5, 1);
const Type *ETy = PTy->getPointerElementType();
// pointers to opaque types are treated as i8*
int id = -1;
if (llvm::isa<StructType>(ETy)) {
const StructType *pst = llvm::cast<StructType>(ETy);
if (pst->isOpaque()) {
id = 8;
}
}
if (-1 == id) {
id = pAnalyzer->getTypeID(ETy);
}
printNumber(Out, id, false);
return;
}
ClamBCStop("Unsupported type ", M);
}
void printConstant(Module &M, Constant *C)
{
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
ConstantExpr *VCE = dyn_cast<ConstantExpr>(CE->stripPointerCasts());
if (!VCE)
VCE = CE;
GlobalVariable *GV =
dyn_cast<GlobalVariable>(VCE->getOperand(0)->stripPointerCasts());
if (VCE->getOpcode() == Instruction::GetElementPtr &&
VCE->getNumOperands() == 2 && GV) {
ConstantInt *C1 = dyn_cast<ConstantInt>(VCE->getOperand(1));
uint64_t v = C1->getValue().getZExtValue();
printNumber(Out, v, true);
printNumber(Out, pAnalyzer->getGlobalID(GV), true);
return;
}
if (VCE->getNumOperands() == 3 && GV) {
ConstantInt *C0 = dyn_cast<ConstantInt>(VCE->getOperand(1));
ConstantInt *C1 = dyn_cast<ConstantInt>(VCE->getOperand(2));
if (C0->isZero()) {
printNumber(Out, C1->getValue().getZExtValue(), true);
printNumber(Out, pAnalyzer->getGlobalID(GV), true);
return;
}
}
if (CE->getOpcode() == Instruction::BitCast && GV) {
printNumber(Out, 0, true);
printNumber(Out, pAnalyzer->getGlobalID(GV), true);
return;
}
}
if (C->isNullValue()) {
printNumber(Out, 0, true);
return;
}
if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
uint64_t v = CI->getValue().getZExtValue();
printNumber(Out, v, true);
return;
}
assert(!isa<ConstantAggregateZero>(C) && "ConstantAggregateZero with non-null value?");
assert(!isa<ConstantPointerNull>(C) && "ConstantPointerNull with non-null value?");
if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
assert(C->getNumOperands() && "[0xty] arrays are not supported!");
for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
printConstant(M, cast<Constant>(*I));
}
return;
}
// TODO: better diagnostics here
if (isa<ConstantFP>(C)) {
ClamBCStop("Floating point constants are not supported!", &M);
}
if (isa<ConstantExpr>(C)) {
C->dump();
ClamBCStop("Global variable has runtime-computable constant expression"
" initializer",
&M);
}
if (isa<ConstantDataSequential>(C)) {
ConstantDataSequential *cds = llvm::cast<ConstantDataSequential>(C);
size_t cnt = cds->getNumElements();
assert((0 < cnt) && "[0xty] arrays are not supported!");
for (size_t i = 0; i < cnt; i++) {
printConstant(M, cds->getElementAsConstant(i));
}
return;
}
ClamBCStop("Unsupported constant type", &M);
}
void printGlobals(llvm::Module *pMod, ClamBCAnalysis *pAnalyzer)
{
const std::string &ls = pAnalyzer->getLogicalSignature();
if (ls.empty()) {
Out << pAnalyzer->getVirusnames();
} else {
Out << ls;
}
printEOL();
Out << "T";
printFixedNumber(Out, pAnalyzer->getStartTID(), 2);
unsigned tid = pAnalyzer->getStartTID();
const std::vector<const Type *> &extraTypes = pAnalyzer->getExtraTypes();
for (auto I = extraTypes.begin(), E = extraTypes.end(); I != E; ++I) {
// assert(typeIDs[*I] == tid && "internal type ID mismatch");
assert(pAnalyzer->getTypeID(*I) == tid && "internal type ID mismatch");
describeType(Out, *I, pMod, pAnalyzer);
tid++;
}
// External function calls
printEOL();
Out << "E";
auto apiCalls = pAnalyzer->getApiCalls();
auto apis = pAnalyzer->getApis();
printNumber(Out, pAnalyzer->getMaxApi(), false);
printNumber(Out, apiCalls.size(), false);
/*This assert should probably be in the analyzer.*/
assert((apis.size() == apiCalls.size()) && "Number of apis don't match");
for (std::vector<const Function *>::iterator I = apis.begin(), E = apis.end();
I != E; ++I) {
const Function *F = *I;
// function api ID
printNumber(Out, apiCalls[F], false);
// function prototype
printNumber(Out, pAnalyzer->getTypeID(F->getFunctionType()), false);
// function name
std::string Name(F->getName());
printConstData(Out, (const unsigned char *)Name.c_str(), Name.size() + 1);
}
// Global constants
printEOL();
Out << "G";
unsigned maxGlobal = pAnalyzer->getMaxGlobal();
printNumber(Out, maxGlobal, false);
const std::vector<Constant *> &globalInits = pAnalyzer->getGlobalInits();
printNumber(Out, globalInits.size(), false);
for (auto I = globalInits.begin(), E = globalInits.end(); I != E; ++I) {
if (I == globalInits.begin()) {
assert(!*I);
printNumber(Out, 0, false);
printNumber(Out, 0, true);
printNumber(Out, 0, false);
continue;
}
Constant *pConst = llvm::cast<Constant>(*I);
// type of constant
uint16_t id = pAnalyzer->getTypeID((*I)->getType());
printNumber(Out, id, false);
// value of constant
printConstant(*pMod, pConst);
printNumber(Out, 0, false);
}
if (pAnalyzer->hasDbgIds()) {
/*Need to get debugging working.*/
assert(0 && "Just want to see if any of them have debug ids");
const std::vector<const MDNode *> &mds = pAnalyzer->getMDs();
printEOL();
Out << "D";
unsigned size = mds.size();
if (size > 32) {
printNumber(Out, 32, false);
size -= 32;
} else {
printNumber(Out, size, false);
}
unsigned cnt = 0, c = 0;
for (auto I = mds.begin(), E = mds.end();
I != E; ++I) {
if (const MDNode *N = dyn_cast<MDNode>(*I)) {
printNumber(Out, N->getNumOperands(), false);
errs() << c++ << ":";
for (unsigned i = 0; i < N->getNumOperands(); i++) {
Value *V = nullptr;
const MDOperand &op = N->getOperand(i);
if (llvm::isa<ValueAsMetadata>(op)) {
assert(0 && "See if thius happens");
V = llvm::cast<ValueAsMetadata>(op)->getValue();
}
if (!V) {
printNumber(Out, 0, false);
printNumber(Out, ~0u, false);
//} else if (MDNode *MB = dyn_cast<MDNode>(V)) {
} else if (const MDNode *MB = dyn_cast<MDNode>(op.get())) {
printNumber(Out, 0, false);
printNumber(Out, pAnalyzer->getDbgId(MB), false);
errs() << pAnalyzer->getDbgId(MB) << ", ";
//} else if (MDString *MS = dyn_cast<MDString>(V)) {
} else if (MDString *MS = dyn_cast<MDString>(op.get())) {
printConstData(Out, (const unsigned char *)MS->getString().data(), MS->getLength());
} else {
ConstantInt *CI = cast<ConstantInt>(V);
printNumber(Out, CI->getBitWidth(), false);
printNumber(Out, CI->getZExtValue(), false);
}
}
errs() << "\n";
}
if (++cnt >= 32) {
printEOL();
Out << "D";
if (size > 32) {
printNumber(Out, 32, false);
size -= 32;
} else
printNumber(Out, size, false);
cnt = 0;
}
}
}
}
void finished(llvm::Module *pMod, ClamBCAnalysis *pAnalyzer)
{
// maxline+1, 1 more for \0
printModuleHeader(*pMod, pAnalyzer, maxLineLength + 1);
OutReal << Out.str();
// MemoryBuffer *MB = nullptr;
const char *start = NULL;
std::string copyright = pAnalyzer->getCopyright();
if (copyright.length()) {
start = copyright.c_str();
} else {
std::string SrcFile = inputSourceFile;
if ("" == SrcFile) {
SrcFile = pMod->getSourceFileName();
}
if (!SrcFile.empty()) {
// std::string ErrStr;
// MB = MemoryBuffer::getFile(SrcFile, &ErrStr);
ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(SrcFile);
if (std::error_code ec = mbOrErr.getError()) {
ClamBCStop("Unable to (re)open input file: " + SrcFile, pMod);
}
// MB = mbOrErr.get();
LLVMMemoryBufferRef mbr = wrap(mbOrErr.get().release());
// mapped file is \0 terminated by getFile()
start = unwrap(mbr)->getBufferStart();
// start = MB->getBufferStart();
}
}
if (!start) {
ClamBCStop("Bytecode should either have source code or include copyright statement\n", pMod);
}
OutReal << "S";
char c;
unsigned linelength = 0;
do {
// skip whitespace at BOL
do {
c = *start++;
} while (c == ' ' || c == '\t');
while (c != '\n' && c) {
// char b[3] = {0x60 | (c & 0xf), 0x60 | ((c >> 4) & 0xf), '\0'};
char b[3];
b[0] = 0x60 | (c & 0xf);
b[1] = 0x60 | ((c >> 4) & 0xf);
b[2] = 0;
OutReal << b;
c = *start++;
linelength++;
}
if (c && linelength < 80) {
OutReal << "S";
} else if (linelength > 0) {
OutReal << "\n";
linelength = 0;
}
} while (c);
}
void dumpTypes(llvm::raw_ostream &OS)
{
// Print type IDs to debug.map
auto typeIDs = pAnalyzer->getTypeIDs();
const Type **revmap = new const Type *[typeIDs.size()];
for (auto I = typeIDs.begin(), E = typeIDs.end();
I != E; ++I) {
revmap[I->second] = I->first;
}
for (unsigned i = 65; i < typeIDs.size(); i++)
OS << "type " << i << ": " << *revmap[i] << "\n";
OS << "\n";
delete[] revmap;
}
protected:
llvm::raw_svector_ostream Out;
llvm::formatted_raw_ostream &OutReal;
llvm::SmallVector<char, 4096> lineBuffer;
int maxLineLength = 0;
int lastLinePos = 0;
llvm::Module *pMod = nullptr;
ClamBCAnalysis *pAnalyzer = nullptr;
void printFixedNumber(raw_ostream &Out, unsigned n, unsigned fixed)
{
char number[32];
unsigned i = 0;
while (fixed > 0) {
number[i++] = 0x60 | (n & 0xf);
n >>= 4;
fixed--;
}
assert((n == 0) && "Fixed-width number cannot exceed width");
number[i] = '\0';
Out << number;
}
static void printNumber(raw_ostream &Out, uint64_t n, bool constant)
{
// llvm::errs() << "printNumber" << "::" << n << "::" << constant << "::";
char number[32];
unsigned i = 0;
while (n > 0) {
number[++i] = 0x60 | (n & 0xf);
n >>= 4;
}
if (!constant) {
number[0] = 0x60 | i;
} else {
number[0] = 0x40 | i;
}
number[++i] = '\0';
// llvm::errs() << number << "<END>\n";
Out << number;
}
static void printString(raw_ostream &Out, const char *string,
unsigned maxlength)
{
std::string str;
if (string) {
StringRef truncatedStr;
truncatedStr = StringRef(string).substr(0, maxlength);
str = truncatedStr.str();
}
const char *cstr = str.c_str();
// null terminated cstring
printConstData(Out, (const unsigned char *)cstr, strlen(cstr) + 1);
}
static void printConstData(raw_ostream &Out, const unsigned char *s,
size_t len)
{
size_t i;
Out << "|";
printNumber(Out, len, false);
for (i = 0; i < len; i++) {
// char b[3] = {0x60 | (s[i] & 0xf), 0x60 | ((s[i] >> 4) & 0xf), '\0'};
char b[3];
b[0] = 0x60 | (s[i] & 0xf);
b[1] = 0x60 | ((s[i] >> 4) & 0xf);
b[2] = 0;
Out << b;
}
}
};
class ClamBCWriter : public PassInfoMixin<ClamBCWriter>, public InstVisitor<ClamBCWriter>
{
typedef DenseMap<const BasicBlock *, unsigned> BBIDMap;
BBIDMap BBMap;
const Module *TheModule = nullptr;
unsigned opcodecvt[Instruction::OtherOpsEnd];
raw_ostream *MapOut = nullptr;
FunctionPass *Dumper = nullptr;
ClamBCRegAllocAnalysis *RA = nullptr;
unsigned fid, minflvl;
MetadataContext *TheMetadata = nullptr;
unsigned MDDbgKind;
std::vector<unsigned> dbgInfo;
bool anyDbg;
llvm::Module *pMod = nullptr;
ClamBCOutputWriter *pOutputWriter = nullptr;
ClamBCAnalysis *pAnalyzer = nullptr;
ModuleAnalysisManager *pModuleAnalysisManager = nullptr;
public:
static char ID;
explicit ClamBCWriter()
: TheModule(0), MapOut(0), Dumper(0)
{
if (!MapFile.empty()) {
std::error_code ec;
std::error_condition ok;
MapOut = new raw_fd_ostream(MapFile.c_str(), ec);
if (ec != ok) {
errs() << "error opening mapfile" << MapFile << ": " << ec.message() << "\n";
MapOut = 0;
}
}
}
~ClamBCWriter()
{
if (MapOut) {
delete MapOut;
}
}
virtual llvm::StringRef getPassName() const
{
return "ClamAV Bytecode Backend Writer";
}
void getAnalysisUsage(AnalysisUsage &AU) const
{
AU.addRequired<ClamBCRegAlloc>();
AU.setPreservesAll();
}
virtual bool doInitialization(Module &M);
PreservedAnalyses run(Module &m, ModuleAnalysisManager &mam)
{
doInitialization(m);
pMod = &m;
pModuleAnalysisManager = &mam;
ClamBCAnalysis &analysis = mam.getResult<ClamBCAnalyzer>(m);
pAnalyzer = &analysis;
pOutputWriter = ClamBCOutputWriter::createClamBCOutputWriter(outFile, pMod, pAnalyzer);
for (auto i = pMod->begin(), e = pMod->end(); i != e; i++) {
if (llvm::isa<Function>(i)) {
Function *pFunc = llvm::cast<Function>(i);
if (not pFunc->isDeclaration()) {
runOnFunction(*pFunc);
}
}
}
doFinalization(m);
return PreservedAnalyses::all();
}
void gatherGEPs(BasicBlock *pBB, std::vector<GetElementPtrInst *> &geps)
{
for (auto i = pBB->begin(), e = pBB->end(); i != e; i++) {
if (llvm::isa<GetElementPtrInst>(i)) {
GetElementPtrInst *pGEP = llvm::cast<GetElementPtrInst>(i);
if (1 == pGEP->getNumIndices()) {
int iid = pAnalyzer->getTypeID(pGEP->getPointerOperand()->getType());
if (iid > 65) {
geps.push_back(pGEP);
}
}
}
}
}
void gatherGEPs(Function *pFunc, std::vector<GetElementPtrInst *> &geps)
{
for (auto i = pFunc->begin(), e = pFunc->end(); i != e; i++) {
BasicBlock *pBB = llvm::cast<BasicBlock>(i);
gatherGEPs(pBB, geps);
}
}
void fixGEPs(Function *pFunc)
{
std::vector<GetElementPtrInst *> geps;
gatherGEPs(pFunc, geps);
for (size_t i = 0; i < geps.size(); i++) {
GetElementPtrInst *pGep = geps[i];
assert(llvm::isa<PointerType>(pGep->getType()) && "ONLY POINTER TYPES ARE CURRENTLY SUPPORTED");
Value *operand = pGep->getPointerOperand();
PointerType *pDestType = Type::getInt8PtrTy(pMod->getContext());
CastInst *ci = CastInst::CreatePointerCast(operand, pDestType, "ClamBCWriter_fixGEPs", pGep);
Value *index = pGep->getOperand(1);
assert(operand->getType()->isPointerTy() && "HOW COULD THIS HAPPEN?");
Type *pType = operand->getType();
pType = pType->getPointerElementType();
if (not pType->isIntegerTy()) {
assert(0 && "ONLY INTEGER TYPES ARE CURRENTLY IMPLEMENTED");
}
unsigned multiplier = pType->getIntegerBitWidth() / 8;
assert(multiplier && "HOW DID THIS END UP ZERO");
Constant *cMultiplier = ConstantInt::get(index->getType(), multiplier);
Value *newIndex = BinaryOperator::Create(Instruction::Mul, cMultiplier, index, "ClamBCWriter_fixGEPs", pGep);
GetElementPtrInst *pNew = nullptr;
if (pGep->isInBounds()) {
Type *pt = ci->getType();
if (llvm::isa<PointerType>(pt)) {
pt = pt->getPointerElementType();
}
pNew = GetElementPtrInst::Create(pt, ci, newIndex, "ClamBCWriter_fixGEPs", pGep);
} else {
assert(0 && "DON'T THINK THIS CAN HAPPEN");
}
assert(pNew && "HOW DID HTIS HAPPEN");
ci = CastInst::CreatePointerCast(pNew, pGep->getType(), "ClamBCWriter_fixGEPs", pGep);
pGep->replaceAllUsesWith(ci);
pGep->eraseFromParent();
}
}
bool runOnFunction(Function &F)
{
fixGEPs(&F);
if ("" == F.getName()) {
assert(0 && "Function created by ClamBCRebuild is not being deleted");
}
pMod = F.getParent();
BBMap.clear();
dbgInfo.clear();
anyDbg = false;
if (F.hasAvailableExternallyLinkage()) {
return false;
}
fid++;
// Removed, see note about getFunctionID at the top of the file.
assert(pAnalyzer->getFunctionID(&F) == fid && "Function IDs don't match");
FunctionAnalysisManager &fam = pModuleAnalysisManager->getResult<FunctionAnalysisManagerModuleProxy>(*pMod).getManager();
RA = &fam.getResult<ClamBCRegAllocAnalyzer>(F);
printFunction(F);
if (Dumper) {
Dumper->runOnFunction(F);
}
return false;
}
virtual bool doFinalization(Module &M)
{
printEOL();
pOutputWriter->finished(pMod, pAnalyzer);
if (MapOut) {
pOutputWriter->dumpTypes(*MapOut);
MapOut->flush();
}
if (Dumper) {
delete Dumper;
}
delete (pOutputWriter);
return false;
}
private:
void printNumber(uint64_t c, bool constant)
{
pOutputWriter->printNumber(c, constant);
}
void printFixedNumber(unsigned c, unsigned fixed)
{
pOutputWriter->printFixedNumber(c, fixed);
}
void printEOL()
{
pOutputWriter->printEOL();
}
void stop(const std::string &Msg, const llvm::Function *F)
{
ClamBCStop(Msg, F);
}
void stop(const std::string &Msg, const llvm::Instruction *I)
{
ClamBCStop(Msg, I);
}
void printCount(Module &M, unsigned count, const std::string &What);
void printType(const Type *Ty, const Function *F = 0, const Instruction *I = 0);
void printFunction(Function &);
void printMapping(const Value *V, unsigned id, bool newline = false);
void printBasicBlock(BasicBlock *BB);
static const AllocaInst *isDirectAlloca(const Value *V)
{
const AllocaInst *AI = dyn_cast<AllocaInst>(V);
if (!AI) return 0;
if (AI->isArrayAllocation())
return 0;
if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
return 0;
return AI;
}
static bool isInlineAsm(const Instruction &I)
{
if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0))) {
return true;
}
return false;
}
friend class InstVisitor<ClamBCWriter>;
void visitGetElementPtrInst(GetElementPtrInst &GEP)
{
// Checking is done by the verifier!
unsigned ops = GEP.getNumIndices();
assert(ops && "GEP without indices?");
if (ops > 15) {
stop("Too many levels of pointer indexing, at most 15 is supported!",
&GEP);
}
switch (ops) {
case 1:
printFixedNumber(OP_BC_GEP1, 2);
assert(!isa<GlobalVariable>(GEP.getOperand(0)) &&
!isa<ConstantExpr>(GEP.getOperand(0)) &&
"would hit libclamav interpreter bug");
{
int iid = pAnalyzer->getTypeID(GEP.getPointerOperand()->getType());
if (iid > 65) {
DEBUGERR << GEP << "<END>\n";
DEBUGERR << *(GEP.getPointerOperand()) << "<END>\n";
DEBUGERR << *(GEP.getPointerOperand()->getType()) << "<END>\n";
DEBUGERR << iid << "<END>\n";
// stop("gep1 with type > 65 won't work on interpreter", &GEP);
assert(0 && "gep1 with type > 65 won't work on interpreter");
}
}
break;
case 2:
if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
if (CI->isZero()) {
assert(!isa<GlobalVariable>(GEP.getOperand(0)) &&
!isa<ConstantExpr>(GEP.getOperand(0)) &&
"would hit libclamav interpreter bug");
printFixedNumber(OP_BC_GEPZ, 2);
printType(GEP.getPointerOperand()->getType(), 0, &GEP);
printOperand(GEP, GEP.getOperand(0));
printOperand(GEP, GEP.getOperand(2));
if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
if (!CI->isZero()) {
const PointerType *Ty = cast<PointerType>(GEP.getPointerOperand()->getType());
const ArrayType *ATy = dyn_cast<ArrayType>(Ty->getPointerElementType());
if (ATy) {
ClamBCStop("ATy", &GEP);
}
}
}
return;
}
}
// fall through
default:
DEBUGERR << GEP << "<END>\n";
assert(0 && "GEPN");
ClamBCStop("GEPN", &GEP);