LLVM 19.0.0git
JMCInstrumenter.cpp
Go to the documentation of this file.
1//===- JMCInstrumenter.cpp - JMC Instrumentation --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// JMCInstrumenter pass:
10// - instrument each function with a call to __CheckForDebuggerJustMyCode. The
11// sole argument should be defined in .msvcjmc. Each flag is 1 byte initilized
12// to 1.
13// - create the dummy COMDAT function __JustMyCode_Default to prevent linking
14// error if __CheckForDebuggerJustMyCode is not available.
15// - For MSVC:
16// add "/alternatename:__CheckForDebuggerJustMyCode=__JustMyCode_Default" to
17// "llvm.linker.options"
18// For ELF:
19// Rename __JustMyCode_Default to __CheckForDebuggerJustMyCode and mark it as
20// weak symbol.
21//===----------------------------------------------------------------------===//
22
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/IR/DIBuilder.h"
30#include "llvm/IR/Function.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/Type.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/DJB.h"
38#include "llvm/Support/Path.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "jmc-instrumenter"
44
45static bool runImpl(Module &M);
46namespace {
47struct JMCInstrumenter : public ModulePass {
48 static char ID;
49 JMCInstrumenter() : ModulePass(ID) {
51 }
52 bool runOnModule(Module &M) override { return runImpl(M); }
53};
54char JMCInstrumenter::ID = 0;
55} // namespace
56
58 bool Changed = runImpl(M);
60}
61
63 JMCInstrumenter, DEBUG_TYPE,
64 "Instrument function entry with call to __CheckForDebuggerJustMyCode",
65 false, false)
66
67ModulePass *llvm::createJMCInstrumenterPass() { return new JMCInstrumenter(); }
68
69namespace {
70const char CheckFunctionName[] = "__CheckForDebuggerJustMyCode";
71
72std::string getFlagName(DISubprogram &SP, bool UseX86FastCall) {
73 // absolute windows path: windows_backslash
74 // relative windows backslash path: windows_backslash
75 // relative windows slash path: posix
76 // absolute posix path: posix
77 // relative posix path: posix
78 sys::path::Style PathStyle =
80 SP.getDirectory().contains("\\") ||
81 SP.getFilename().contains("\\")
84 // Best effort path normalization. This is to guarantee an unique flag symbol
85 // is produced for the same directory. Some builds may want to use relative
86 // paths, or paths with a specific prefix (see the -fdebug-compilation-dir
87 // flag), so only hash paths in debuginfo. Don't expand them to absolute
88 // paths.
89 SmallString<256> FilePath(SP.getDirectory());
90 sys::path::append(FilePath, PathStyle, SP.getFilename());
91 sys::path::native(FilePath, PathStyle);
92 sys::path::remove_dots(FilePath, /*remove_dot_dot=*/true, PathStyle);
93
94 // The naming convention for the flag name is __<hash>_<file name> with '.' in
95 // <file name> replaced with '@'. For example C:\file.any.c would have a flag
96 // __D032E919_file@any@c. The naming convention match MSVC's format however
97 // the match is not required to make JMC work. The hashing function used here
98 // is different from MSVC's.
99
100 std::string Suffix;
101 for (auto C : sys::path::filename(FilePath, PathStyle))
102 Suffix.push_back(C == '.' ? '@' : C);
103
104 sys::path::remove_filename(FilePath, PathStyle);
105 return (UseX86FastCall ? "_" : "__") +
106 utohexstr(djbHash(FilePath), /*LowerCase=*/false,
107 /*Width=*/8) +
108 "_" + Suffix;
109}
110
111void attachDebugInfo(GlobalVariable &GV, DISubprogram &SP) {
112 Module &M = *GV.getParent();
113 DICompileUnit *CU = SP.getUnit();
114 assert(CU);
115 DIBuilder DB(M, false, CU);
116
117 auto *DType =
118 DB.createBasicType("unsigned char", 8, dwarf::DW_ATE_unsigned_char,
119 llvm::DINode::FlagArtificial);
120
121 auto *DGVE = DB.createGlobalVariableExpression(
122 CU, GV.getName(), /*LinkageName=*/StringRef(), SP.getFile(),
123 /*LineNo=*/0, DType, /*IsLocalToUnit=*/true, /*IsDefined=*/true);
124 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
125 DB.finalize();
126}
127
128FunctionType *getCheckFunctionType(LLVMContext &Ctx) {
129 Type *VoidTy = Type::getVoidTy(Ctx);
130 PointerType *VoidPtrTy = PointerType::getUnqual(Ctx);
131 return FunctionType::get(VoidTy, VoidPtrTy, false);
132}
133
134Function *createDefaultCheckFunction(Module &M, bool UseX86FastCall) {
135 LLVMContext &Ctx = M.getContext();
136 const char *DefaultCheckFunctionName =
137 UseX86FastCall ? "_JustMyCode_Default" : "__JustMyCode_Default";
138 // Create the function.
139 Function *DefaultCheckFunc =
140 Function::Create(getCheckFunctionType(Ctx), GlobalValue::ExternalLinkage,
141 DefaultCheckFunctionName, &M);
143 DefaultCheckFunc->addParamAttr(0, Attribute::NoUndef);
144 if (UseX86FastCall)
145 DefaultCheckFunc->addParamAttr(0, Attribute::InReg);
146
147 BasicBlock *EntryBB = BasicBlock::Create(Ctx, "", DefaultCheckFunc);
148 ReturnInst::Create(Ctx, EntryBB);
149 return DefaultCheckFunc;
150}
151} // namespace
152
153bool runImpl(Module &M) {
154 bool Changed = false;
155 LLVMContext &Ctx = M.getContext();
156 Triple ModuleTriple(M.getTargetTriple());
157 bool IsMSVC = ModuleTriple.isKnownWindowsMSVCEnvironment();
158 bool IsELF = ModuleTriple.isOSBinFormatELF();
159 assert((IsELF || IsMSVC) && "Unsupported triple for JMC");
160 bool UseX86FastCall = IsMSVC && ModuleTriple.getArch() == Triple::x86;
161 const char *const FlagSymbolSection = IsELF ? ".data.just.my.code" : ".msvcjmc";
162
163 GlobalValue *CheckFunction = nullptr;
165 for (auto &F : M) {
166 if (F.isDeclaration())
167 continue;
168 auto *SP = F.getSubprogram();
169 if (!SP)
170 continue;
171
172 Constant *&Flag = SavedFlags[SP];
173 if (!Flag) {
174 std::string FlagName = getFlagName(*SP, UseX86FastCall);
175 IntegerType *FlagTy = Type::getInt8Ty(Ctx);
176 Flag = M.getOrInsertGlobal(FlagName, FlagTy, [&] {
177 // FIXME: Put the GV in comdat and have linkonce_odr linkage to save
178 // .msvcjmc section space? maybe not worth it.
180 M, FlagTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
181 ConstantInt::get(FlagTy, 1), FlagName);
182 GV->setSection(FlagSymbolSection);
183 GV->setAlignment(Align(1));
185 attachDebugInfo(*GV, *SP);
186 return GV;
187 });
188 }
189
190 if (!CheckFunction) {
191 Function *DefaultCheckFunc =
192 createDefaultCheckFunction(M, UseX86FastCall);
193 if (IsELF) {
194 DefaultCheckFunc->setName(CheckFunctionName);
195 DefaultCheckFunc->setLinkage(GlobalValue::WeakAnyLinkage);
196 CheckFunction = DefaultCheckFunc;
197 } else {
198 assert(!M.getFunction(CheckFunctionName) &&
199 "JMC instrument more than once?");
200 auto *CheckFunc = cast<Function>(
201 M.getOrInsertFunction(CheckFunctionName, getCheckFunctionType(Ctx))
202 .getCallee());
203 CheckFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
204 CheckFunc->addParamAttr(0, Attribute::NoUndef);
205 if (UseX86FastCall) {
206 CheckFunc->setCallingConv(CallingConv::X86_FastCall);
207 CheckFunc->addParamAttr(0, Attribute::InReg);
208 }
209 CheckFunction = CheckFunc;
210
211 StringRef DefaultCheckFunctionName = DefaultCheckFunc->getName();
212 appendToUsed(M, {DefaultCheckFunc});
213 Comdat *C = M.getOrInsertComdat(DefaultCheckFunctionName);
214 C->setSelectionKind(Comdat::Any);
215 DefaultCheckFunc->setComdat(C);
216 // Add a linker option /alternatename to set the default implementation
217 // for the check function.
218 // https://devblogs.microsoft.com/oldnewthing/20200731-00/?p=104024
219 std::string AltOption = std::string("/alternatename:") +
220 CheckFunctionName + "=" +
221 DefaultCheckFunctionName.str();
222 llvm::Metadata *Ops[] = {llvm::MDString::get(Ctx, AltOption)};
223 MDTuple *N = MDNode::get(Ctx, Ops);
224 M.getOrInsertNamedMetadata("llvm.linker.options")->addOperand(N);
225 }
226 }
227 // FIXME: it would be nice to make CI scheduling boundary, although in
228 // practice it does not matter much.
229 auto *CI = CallInst::Create(getCheckFunctionType(Ctx), CheckFunction,
230 {Flag}, "", F.begin()->getFirstInsertionPt());
231 CI->addParamAttr(0, Attribute::NoUndef);
232 if (UseX86FastCall) {
233 CI->setCallingConv(CallingConv::X86_FastCall);
234 CI->addParamAttr(0, Attribute::InReg);
235 }
236
237 Changed = true;
238 }
239 return Changed;
240}
static bool runImpl(Function &F, const TargetLowering &TLI)
#define DEBUG_TYPE
static bool runImpl(Module &M)
#define F(x, y, z)
Definition: MD5.cpp:55
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:199
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
This is an important base class in LLVM.
Definition: Constant.h:41
StringRef getFilename() const
DIFile * getFile() const
StringRef getDirectory() const
Subprogram description.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:164
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition: Function.cpp:616
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:133
void setComdat(Comdat *C)
Definition: Globals.cpp:202
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:263
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1521
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:230
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:536
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:51
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:55
Class to represent integer types.
Definition: DerivedTypes.h:40
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:600
Tuple of metadata.
Definition: Metadata.h:1470
Root of the metadata hierarchy.
Definition: Metadata.h:62
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
static ReturnInst * Create(LLVMContext &C, Value *retVal, BasicBlock::iterator InsertBefore)
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:223
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:417
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:373
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:719
bool isKnownWindowsMSVCEnvironment() const
Checks if the environment is MSVC.
Definition: Triple.h:629
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
Definition: CallingConv.h:103
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:475
bool has_root_name(const Twine &path, Style style=Style::native)
Has root name?
Definition: Path.cpp:616
bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
In-place remove any '.
Definition: Path.cpp:716
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeJMCInstrumenterPass(PassRegistry &)
ModulePass * createJMCInstrumenterPass()
JMC instrument pass.
uint32_t djbHash(StringRef Buffer, uint32_t H=5381)
The Bernstein hash function used by the DWARF accelerator tables.
Definition: DJB.h:21
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39