File: PointerTracking.cpp

package info (click to toggle)
clamav 0.101.2+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 29,464 kB
  • sloc: ansic: 158,856; sh: 8,156; cpp: 5,173; makefile: 2,077; yacc: 1,351; lex: 714; python: 120; perl: 17
file content (455 lines) | stat: -rw-r--r-- 14,444 bytes parent folder | download | duplicates (2)
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
//===- PointerTracking.cpp - Pointer Bounds Tracking ------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements tracking of pointer bounds.
//
//===----------------------------------------------------------------------===//

/* this shouldn't be part of win32 proj at all, but its easier to exclude here
 * */
#ifndef _WIN32

#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/ValueTracking.h"
#include "PointerTracking.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#if LLVM_VERSION < 35
#include "llvm/Support/CallSite.h"
#include "llvm/Support/InstIterator.h"
#else
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#if LLVM_VERSION < 37
#include "llvm/Target/TargetLibraryInfo.h"
#else
#include <llvm/Analysis/TargetLibraryInfo.h>
#endif

#if LLVM_VERSION < 32
#include "llvm/Target/TargetData.h"
#elif LLVM_VERSION < 33
#include "llvm/DataLayout.h"
#else
#include "llvm/IR/DataLayout.h"
#endif

#if LLVM_VERSION < 33
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Value.h"
#else
#include "llvm/IR/Constants.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#endif

using namespace llvm;
#if LLVM_VERSION < 29
/* function is succeeded in later LLVM with LLVM corresponding standalone */
static Value *GetUnderlyingObject(Value *P, TargetData *TD)
{
    return P->getUnderlyingObject();
}
#endif

#if LLVM_VERSION >= 29
namespace llvm {
    void initializePointerTrackingPass(llvm::PassRegistry&);
};
INITIALIZE_PASS_BEGIN(PointerTracking, "pointertracking",
                "Track pointer bounds", false, true)
#if LLVM_VERSION < 35
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
#else
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
#endif
#if LLVM_VERSION < 37
INITIALIZE_PASS_DEPENDENCY(LoopInfo)
#else
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
#endif
#if LLVM_VERSION < 38
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
#else
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
#endif
#if LLVM_VERSION < 35
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
#else
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
#endif
INITIALIZE_PASS_END(PointerTracking, "pointertracking",
                "Track pointer bounds", false, true)
#endif

char PointerTracking::ID = 0;
PointerTracking::PointerTracking() : FunctionPass(ID) {
#if LLVM_VERSION >= 29
    initializePointerTrackingPass(*PassRegistry::getPassRegistry());
#endif
}

bool PointerTracking::runOnFunction(Function &F) {
  predCache.clear();
  assert(analyzing.empty());
  FF = &F;
#if LLVM_VERSION < 32
  TD = getAnalysisIfAvailable<TargetData>();
#elif LLVM_VERSION < 35
  TD = getAnalysisIfAvailable<DataLayout>();
#elif LLVM_VERSION < 37
  DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
  TD = DLP ? &DLP->getDataLayout() : 0;
#else
  TD = &F.getEntryBlock().getModule()->getDataLayout();
#endif
#if LLVM_VERSION < 38
  SE = &getAnalysis<ScalarEvolution>();
#else
  SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
#endif
#if LLVM_VERSION < 37
  LI = &getAnalysis<LoopInfo>();
#else
 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
#endif
#if LLVM_VERSION < 35
  DT = &getAnalysis<DominatorTree>();
#else
  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
#endif
  return false;
}

void PointerTracking::getAnalysisUsage(AnalysisUsage &AU) const {
#if LLVM_VERSION < 35
  AU.addRequiredTransitive<DominatorTree>();
#else
  AU.addRequiredTransitive<DominatorTreeWrapperPass>();
#endif
#if LLVM_VERSION < 37
  AU.addRequiredTransitive<LoopInfo>();
#else
  AU.addRequiredTransitive<LoopInfoWrapperPass>();
#endif
#if LLVM_VERSION < 38
  AU.addRequiredTransitive<ScalarEvolution>();
#else
  AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
#endif
  AU.setPreservesAll();
}

bool PointerTracking::doInitialization(Module &M) {
  constType *PTy = Type::getInt8PtrTy(M.getContext());

  // Find calloc(i64, i64) or calloc(i32, i32).
  callocFunc = M.getFunction("calloc");
  if (callocFunc) {
    constFunctionType *Ty = callocFunc->getFunctionType();

    std::vector<constType*> args, args2;
    args.push_back(Type::getInt64Ty(M.getContext()));
    args.push_back(Type::getInt64Ty(M.getContext()));
    args2.push_back(Type::getInt32Ty(M.getContext()));
    args2.push_back(Type::getInt32Ty(M.getContext()));
    constFunctionType *Calloc1Type =
      FunctionType::get(PTy, args, false);
    constFunctionType *Calloc2Type =
      FunctionType::get(PTy, args2, false);
    if (Ty != Calloc1Type && Ty != Calloc2Type)
      callocFunc = 0; // Give up
  }

  // Find realloc(i8*, i64) or realloc(i8*, i32).
  reallocFunc = M.getFunction("realloc");
  if (reallocFunc) {
    constFunctionType *Ty = reallocFunc->getFunctionType();
    std::vector<constType*> args, args2;
    args.push_back(PTy);
    args.push_back(Type::getInt64Ty(M.getContext()));
    args2.push_back(PTy);
    args2.push_back(Type::getInt32Ty(M.getContext()));

    constFunctionType *Realloc1Type =
      FunctionType::get(PTy, args, false);
    constFunctionType *Realloc2Type =
      FunctionType::get(PTy, args2, false);
    if (Ty != Realloc1Type && Ty != Realloc2Type)
      reallocFunc = 0; // Give up
  }
  return false;
}

// Calculates the number of elements allocated for pointer P,
// the type of the element is stored in Ty.
const SCEV *PointerTracking::computeAllocationCount(Value *P,
                                                    constType *&Ty) const {
  Value *V = P->stripPointerCasts();
  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
    Value *arraySize = AI->getArraySize();
    Ty = AI->getAllocatedType();
    // arraySize elements of type Ty.
    return SE->getSCEV(arraySize);
  }

#if LLVM_VERSION < 32
  if (CallInst *CI = extractMallocCall(V)) {
    Value *arraySize = getMallocArraySize(CI, TD);
    constType* AllocTy = getMallocAllocatedType(CI);
#elif LLVM_VERSION < 37
  TargetLibraryInfo* TLI = new TargetLibraryInfo();

  if (CallInst *CI = extractMallocCall(V, TLI)) {
    Value *arraySize = getMallocArraySize(CI, TD, TLI);
    constType* AllocTy = getMallocAllocatedType(CI, TLI);
#else
  TargetLibraryInfoImpl* TLII = new TargetLibraryInfoImpl();
  TargetLibraryInfo* TLI = new TargetLibraryInfo(*TLII);

  if (CallInst *CI = extractMallocCall(V, TLI)) {
    Value *arraySize = getMallocArraySize(CI, *TD, TLI);
    constType* AllocTy = getMallocAllocatedType(CI, TLI);
#endif
    if (!AllocTy || !arraySize) return SE->getCouldNotCompute();
    Ty = AllocTy;
    // arraySize elements of type Ty.
    return SE->getSCEV(arraySize);
  }

  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
    if (GV->hasDefinitiveInitializer()) {
      Constant *C = GV->getInitializer();
      if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
        Ty = ATy->getElementType();
        return SE->getConstant(Type::getInt32Ty(P->getContext()),
                               ATy->getNumElements());
      }
    }
    Ty = GV->getType();
    return SE->getConstant(Type::getInt32Ty(P->getContext()), 1);
    //TODO: implement more tracking for globals
  }

  if (CallInst *CI = dyn_cast<CallInst>(V)) {
    CallSite CS(CI);
    Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
    const Loop *L = LI->getLoopFor(CI->getParent());
    if (F == callocFunc) {
      Ty = Type::getInt8Ty(P->getContext());
      // calloc allocates arg0*arg1 bytes.
      return SE->getSCEVAtScope(SE->getMulExpr(SE->getSCEV(CS.getArgument(0)),
                                               SE->getSCEV(CS.getArgument(1))),
                                L);
    } else if (F == reallocFunc) {
      Ty = Type::getInt8Ty(P->getContext());
      // realloc allocates arg1 bytes.
      return SE->getSCEVAtScope(CS.getArgument(1), L);
    }
  }

  return SE->getCouldNotCompute();
}

Value *PointerTracking::computeAllocationCountValue(Value *P, constType *&Ty) const 
{
  Value *V = P->stripPointerCasts();
  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
    Ty = AI->getAllocatedType();
    // arraySize elements of type Ty.
    return AI->getArraySize();
  }

#if LLVM_VERSION < 32
  if (CallInst *CI = extractMallocCall(V)) {
    Ty = getMallocAllocatedType(CI);
    if (!Ty)
      return 0;
    Value *arraySize = getMallocArraySize(CI, TD);
#elif LLVM_VERSION < 37
  TargetLibraryInfo* TLI = new TargetLibraryInfo();

  if (CallInst *CI = extractMallocCall(V, TLI)) {
    Ty = getMallocAllocatedType(CI, TLI);
    if (!Ty)
      return 0;
    Value *arraySize = getMallocArraySize(CI, TD, TLI);
#else
  TargetLibraryInfoImpl* TLII = new TargetLibraryInfoImpl();
  TargetLibraryInfo* TLI = new TargetLibraryInfo(*TLII);

  if (CallInst *CI = extractMallocCall(V, TLI)) {
    Ty = getMallocAllocatedType(CI, TLI);
    if (!Ty)
      return 0;
    Value *arraySize = getMallocArraySize(CI, *TD, TLI);
#endif
    if (!arraySize) {
      Ty = Type::getInt8Ty(P->getContext());
      return CI->getArgOperand(0);
    }
    // arraySize elements of type Ty.
    return arraySize;
  }

  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
    if (GV->hasDefinitiveInitializer()) {
      Constant *C = GV->getInitializer();
      if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
        Ty = ATy->getElementType();
        return ConstantInt::get(Type::getInt32Ty(P->getContext()),
                               ATy->getNumElements());
      }
    }
    Ty = cast<PointerType>(GV->getType())->getElementType();
    return ConstantInt::get(Type::getInt32Ty(P->getContext()), 1);
    //TODO: implement more tracking for globals
  }

  if (CallInst *CI = dyn_cast<CallInst>(V)) {
    CallSite CS(CI);
    Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
    if (F == reallocFunc) {
      Ty = Type::getInt8Ty(P->getContext());
      // realloc allocates arg1 bytes.
      return CS.getArgument(1);
    }
  }

  return 0;
}

// Calculates the number of elements of type Ty allocated for P.
const SCEV *PointerTracking::computeAllocationCountForType(Value *P,
                                                           constType *Ty)
  const {
    constType *elementTy;
    const SCEV *Count = computeAllocationCount(P, elementTy);
    if (isa<SCEVCouldNotCompute>(Count))
      return Count;
    if (elementTy == Ty)
      return Count;

    if (!TD) // need TargetData from this point forward
      return SE->getCouldNotCompute();

    uint64_t elementSize = TD->getTypeAllocSize(elementTy);
    uint64_t wantSize = TD->getTypeAllocSize(Ty);
    if (elementSize == wantSize)
      return Count;
    if (elementSize % wantSize) //fractional counts not possible
      return SE->getCouldNotCompute();
    return SE->getMulExpr(Count, SE->getConstant(Count->getType(),
                                                 elementSize/wantSize));
}

const SCEV *PointerTracking::getAllocationElementCount(Value *V) const {
  // We only deal with pointers.
  const PointerType *PTy = cast<PointerType>(V->getType());
  return computeAllocationCountForType(V, PTy->getElementType());
}

const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
  return computeAllocationCountForType(V, Type::getInt8Ty(V->getContext()));
}

// Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
enum SolverResult PointerTracking::isLoopGuardedBy(const Loop *L,
                                                   Predicate Pred,
                                                   const SCEV *A,
                                                   const SCEV *B) const {
  if (SE->isLoopEntryGuardedByCond(L, Pred, A, B))
    return AlwaysTrue;
  Pred = ICmpInst::getSwappedPredicate(Pred);
  if (SE->isLoopEntryGuardedByCond(L, Pred, B, A))
    return AlwaysTrue;

  Pred = ICmpInst::getInversePredicate(Pred);
  if (SE->isLoopEntryGuardedByCond(L, Pred, B, A))
    return AlwaysFalse;
  Pred = ICmpInst::getSwappedPredicate(Pred);
  if (SE->isLoopEntryGuardedByCond(L, Pred, A, B))
    return AlwaysTrue;
  return Unknown;
}

enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
                                               const SCEV *Limit,
                                               BasicBlock *BB)
{
  //FIXME: merge implementation
  return Unknown;
}

void PointerTracking::getPointerOffset(Value *Pointer, Value *&Base,
                                       const SCEV *&Limit,
                                       const SCEV *&Offset) const
{
    Pointer = Pointer->stripPointerCasts();
#if LLVM_VERSION < 37
    Base = GetUnderlyingObject(Pointer, TD);
#else
    Base = GetUnderlyingObject(Pointer, *TD);
#endif
    Limit = getAllocationSizeInBytes(Base);
    if (isa<SCEVCouldNotCompute>(Limit)) {
      Base = 0;
      Offset = Limit;
      return;
    }

    Offset = SE->getMinusSCEV(SE->getSCEV(Pointer), SE->getSCEV(Base));
    if (isa<SCEVCouldNotCompute>(Offset)) {
      Base = 0;
      Limit = Offset;
    }
}

void PointerTracking::print(raw_ostream &OS, const Module* M) const {
  // Calling some PT methods may cause caches to be updated, however
  // this should be safe for the same reason its safe for SCEV.
  PointerTracking &PT = *const_cast<PointerTracking*>(this);
  for (inst_iterator I=inst_begin(*FF), E=inst_end(*FF); I != E; ++I) {
    if (!I->getType()->isPointerTy())
      continue;
    Value *Base;
    const SCEV *Limit, *Offset;
    getPointerOffset(&*I, Base, Limit, Offset);
    if (!Base)
      continue;

    if (Base == &*I) {
      const SCEV *S = getAllocationElementCount(Base);
      OS << *Base << " ==> " << *S << " elements, ";
      OS << *Limit << " bytes allocated\n";
      continue;
    }
    OS << &*I << " -- base: " << *Base;
    OS << " offset: " << *Offset;

    enum SolverResult res = PT.checkLimits(Offset, Limit, I->getParent());
    switch (res) {
    case AlwaysTrue:
      OS << " always safe\n";
      break;
    case AlwaysFalse:
      OS << " always unsafe\n";
      break;
    case Unknown:
      OS << " <<unknown>>\n";
      break;
    }
  }
}
#endif