about summary refs log tree commit diff homepage
path: root/lib/Module/WorkaroundLLVMPR39177.cpp
blob: 92458847983966f3dc82e15a1bb827c5b37a3ec5 (plain) (blame)
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
//===-- WorkaroundLLVMPR39177.cpp -------------------------------*- C++ -*-===//
//
//                     The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This pass provides a workaround for LLVM bug PR39177 within the KLEE repo.
// For more information on this, please refer to the comments in
// cmake/workaround_llvm_pr39177.cmake

#include "Passes.h"
#include "klee/Support/ErrorHandling.h"

#include "llvm/Transforms/Utils/Cloning.h"

using namespace llvm;

namespace klee {

bool WorkaroundLLVMPR39177Pass::runOnModule(Module &M) {
  bool modified = false;

  const char *libfunctions[] = {
    "strlen",
    "strchr",
    "strncmp",
    "strcpy",
    "strncpy",
    "__memcpy_chk",
    "memchr",
    "memcmp",
    "putchar",
    "puts",
    "fputc",
    "fputc_unlocked",
    "fputs",
    "fputs_unlocked",
    "fwrite",
    "malloc",
    "calloc",
    "fwrite_unlocked",
    "fgetc_unlocked",
    "fgets_unlocked",
    "fread_unlocked",
    "memset_pattern16",
    "fopen"
  };

  for (auto *funcname : libfunctions) {
    if (M.getFunction(funcname) != nullptr)
      continue;

    GlobalValue *gv = M.getNamedValue(funcname);
    auto *alias = dyn_cast_or_null<GlobalAlias>(gv);
    if (alias == nullptr)
      continue;

    // get aliasee function if exists
    while (auto *ga = dyn_cast<GlobalAlias>(alias->getAliasee())) {
      assert(ga != alias && "alias pointing to itself");
      alias = ga;
    }
    Function *f = dyn_cast<Function>(alias->getAliasee());
    if (f == nullptr)
      continue;

    std::string aliasName = alias->getName().str();

    // clone function
    ValueToValueMapTy VMap;
    Function *g = CloneFunction(f, VMap);

    // replace alias with cloned function
    alias->replaceAllUsesWith(g);
    g->takeName(alias);
    alias->eraseFromParent();

    klee_message(
        "WorkaroundLLVMPR39177: replaced alias @%s with clone of function @%s",
        aliasName.c_str(), f->getName().str().c_str());
    modified = true;
  }

  return modified;
}

char WorkaroundLLVMPR39177Pass::ID = 0;

} // namespace klee