1//===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions perform manipulations on Modules.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/ModuleUtils.h"
15#include "llvm/IR/DerivedTypes.h"
16#include "llvm/IR/Function.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/Module.h"
19#include "llvm/Support/raw_ostream.h"
20
21using namespace llvm;
22
23static void appendToGlobalArray(const char *Array, Module &M, Function *F,
24                                int Priority, Constant *Data) {
25  IRBuilder<> IRB(M.getContext());
26  FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
27
28  // Get the current set of static global constructors and add the new ctor
29  // to the list.
30  SmallVector<Constant *, 16> CurrentCtors;
31  StructType *EltTy;
32  if (GlobalVariable *GVCtor = M.getNamedGlobal(Array)) {
33    ArrayType *ATy = cast<ArrayType>(GVCtor->getValueType());
34    StructType *OldEltTy = cast<StructType>(ATy->getElementType());
35    // Upgrade a 2-field global array type to the new 3-field format if needed.
36    if (Data && OldEltTy->getNumElements() < 3)
37      EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
38                              IRB.getInt8PtrTy(), nullptr);
39    else
40      EltTy = OldEltTy;
41    if (Constant *Init = GVCtor->getInitializer()) {
42      unsigned n = Init->getNumOperands();
43      CurrentCtors.reserve(n + 1);
44      for (unsigned i = 0; i != n; ++i) {
45        auto Ctor = cast<Constant>(Init->getOperand(i));
46        if (EltTy != OldEltTy)
47          Ctor = ConstantStruct::get(
48              EltTy, Ctor->getAggregateElement((unsigned)0),
49              Ctor->getAggregateElement(1),
50              Constant::getNullValue(IRB.getInt8PtrTy()), nullptr);
51        CurrentCtors.push_back(Ctor);
52      }
53    }
54    GVCtor->eraseFromParent();
55  } else {
56    // Use the new three-field struct if there isn't one already.
57    EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy),
58                            IRB.getInt8PtrTy(), nullptr);
59  }
60
61  // Build a 2 or 3 field global_ctor entry.  We don't take a comdat key.
62  Constant *CSVals[3];
63  CSVals[0] = IRB.getInt32(Priority);
64  CSVals[1] = F;
65  // FIXME: Drop support for the two element form in LLVM 4.0.
66  if (EltTy->getNumElements() >= 3)
67    CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getInt8PtrTy())
68                     : Constant::getNullValue(IRB.getInt8PtrTy());
69  Constant *RuntimeCtorInit =
70      ConstantStruct::get(EltTy, makeArrayRef(CSVals, EltTy->getNumElements()));
71
72  CurrentCtors.push_back(RuntimeCtorInit);
73
74  // Create a new initializer.
75  ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size());
76  Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
77
78  // Create the new global variable and replace all uses of
79  // the old global variable with the new one.
80  (void)new GlobalVariable(M, NewInit->getType(), false,
81                           GlobalValue::AppendingLinkage, NewInit, Array);
82}
83
84void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) {
85  appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data);
86}
87
88void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) {
89  appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data);
90}
91
92Function *llvm::checkSanitizerInterfaceFunction(Constant *FuncOrBitcast) {
93  if (isa<Function>(FuncOrBitcast))
94    return cast<Function>(FuncOrBitcast);
95  FuncOrBitcast->dump();
96  std::string Err;
97  raw_string_ostream Stream(Err);
98  Stream << "Sanitizer interface function redefined: " << *FuncOrBitcast;
99  report_fatal_error(Err);
100}
101
102std::pair<Function *, Function *> llvm::createSanitizerCtorAndInitFunctions(
103    Module &M, StringRef CtorName, StringRef InitName,
104    ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs,
105    StringRef VersionCheckName) {
106  assert(!InitName.empty() && "Expected init function name");
107  assert(InitArgTypes.size() == InitArgTypes.size() &&
108         "Sanitizer's init function expects different number of arguments");
109  Function *Ctor = Function::Create(
110      FunctionType::get(Type::getVoidTy(M.getContext()), false),
111      GlobalValue::InternalLinkage, CtorName, &M);
112  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
113  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
114  Function *InitFunction =
115      checkSanitizerInterfaceFunction(M.getOrInsertFunction(
116          InitName, FunctionType::get(IRB.getVoidTy(), InitArgTypes, false),
117          AttributeSet()));
118  InitFunction->setLinkage(Function::ExternalLinkage);
119  IRB.CreateCall(InitFunction, InitArgs);
120  if (!VersionCheckName.empty()) {
121    Function *VersionCheckFunction =
122        checkSanitizerInterfaceFunction(M.getOrInsertFunction(
123            VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false),
124            AttributeSet()));
125    IRB.CreateCall(VersionCheckFunction, {});
126  }
127  return std::make_pair(Ctor, InitFunction);
128}
129