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
23#include "llvm/CodeGen/JMCInstrumenter.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/IR/DIBuilder.h"
28#include "llvm/IR/DebugInfoMetadata.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/Type.h"
35#include "llvm/InitializePasses.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/DJB.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Transforms/Utils/ModuleUtils.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) {}
50 bool runOnModule(Module &M) override { return runImpl(M); }
51};
52char JMCInstrumenter::ID = 0;
53} // namespace
54
55PreservedAnalyses JMCInstrumenterPass::run(Module &M, ModuleAnalysisManager &) {
56 bool Changed = runImpl(M);
57 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
58}
59
60INITIALIZE_PASS(
61 JMCInstrumenter, DEBUG_TYPE,
62 "Instrument function entry with call to __CheckForDebuggerJustMyCode",
63 false, false)
64
65ModulePass *llvm::createJMCInstrumenterPass() { return new JMCInstrumenter(); }
66
67namespace {
68const char CheckFunctionName[] = "__CheckForDebuggerJustMyCode";
69
70std::string getFlagName(DISubprogram &SP, bool UseX86FastCall) {
71 // absolute windows path: windows_backslash
72 // relative windows backslash path: windows_backslash
73 // relative windows slash path: posix
74 // absolute posix path: posix
75 // relative posix path: posix
76 sys::path::Style PathStyle =
77 has_root_name(path: SP.getDirectory(), style: sys::path::Style::windows_backslash) ||
78 SP.getDirectory().contains(Other: "\\") ||
79 SP.getFilename().contains(Other: "\\")
80 ? sys::path::Style::windows_backslash
81 : sys::path::Style::posix;
82 // Best effort path normalization. This is to guarantee an unique flag symbol
83 // is produced for the same directory. Some builds may want to use relative
84 // paths, or paths with a specific prefix (see the -fdebug-compilation-dir
85 // flag), so only hash paths in debuginfo. Don't expand them to absolute
86 // paths.
87 SmallString<256> FilePath(SP.getDirectory());
88 sys::path::append(path&: FilePath, style: PathStyle, a: SP.getFilename());
89 sys::path::native(path&: FilePath, style: PathStyle);
90 sys::path::remove_dots(path&: FilePath, /*remove_dot_dot=*/true, style: PathStyle);
91
92 // The naming convention for the flag name is __<hash>_<file name> with '.' in
93 // <file name> replaced with '@'. For example C:\file.any.c would have a flag
94 // __D032E919_file@any@c. The naming convention match MSVC's format however
95 // the match is not required to make JMC work. The hashing function used here
96 // is different from MSVC's.
97
98 std::string Suffix;
99 for (auto C : sys::path::filename(path: FilePath, style: PathStyle))
100 Suffix.push_back(c: C == '.' ? '@' : C);
101
102 sys::path::remove_filename(path&: FilePath, style: PathStyle);
103 return (UseX86FastCall ? "_" : "__") +
104 utohexstr(X: djbHash(Buffer: FilePath), /*LowerCase=*/false,
105 /*Width=*/8) +
106 "_" + Suffix;
107}
108
109void attachDebugInfo(GlobalVariable &GV, DISubprogram &SP) {
110 Module &M = *GV.getParent();
111 DICompileUnit *CU = SP.getUnit();
112 assert(CU);
113 DIBuilder DB(M, false, CU);
114
115 auto *DType =
116 DB.createBasicType(Name: "unsigned char", SizeInBits: 8, Encoding: dwarf::DW_ATE_unsigned_char,
117 Flags: llvm::DINode::FlagArtificial);
118
119 auto *DGVE = DB.createGlobalVariableExpression(
120 Context: CU, Name: GV.getName(), /*LinkageName=*/StringRef(), File: SP.getFile(),
121 /*LineNo=*/0, Ty: DType, /*IsLocalToUnit=*/true, /*IsDefined=*/isDefined: true);
122 GV.addMetadata(KindID: LLVMContext::MD_dbg, MD&: *DGVE);
123 DB.finalize();
124}
125
126FunctionType *getCheckFunctionType(LLVMContext &Ctx) {
127 Type *VoidTy = Type::getVoidTy(C&: Ctx);
128 PointerType *VoidPtrTy = PointerType::getUnqual(C&: Ctx);
129 return FunctionType::get(Result: VoidTy, Params: VoidPtrTy, isVarArg: false);
130}
131
132Function *createDefaultCheckFunction(Module &M, bool UseX86FastCall) {
133 LLVMContext &Ctx = M.getContext();
134 const char *DefaultCheckFunctionName =
135 UseX86FastCall ? "_JustMyCode_Default" : "__JustMyCode_Default";
136 // Create the function.
137 Function *DefaultCheckFunc =
138 Function::Create(Ty: getCheckFunctionType(Ctx), Linkage: GlobalValue::ExternalLinkage,
139 N: DefaultCheckFunctionName, M: &M);
140 DefaultCheckFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
141 DefaultCheckFunc->addParamAttr(ArgNo: 0, Kind: Attribute::NoUndef);
142 if (UseX86FastCall)
143 DefaultCheckFunc->addParamAttr(ArgNo: 0, Kind: Attribute::InReg);
144
145 BasicBlock *EntryBB = BasicBlock::Create(Context&: Ctx, Name: "", Parent: DefaultCheckFunc);
146 ReturnInst::Create(C&: Ctx, InsertAtEnd: EntryBB);
147 return DefaultCheckFunc;
148}
149} // namespace
150
151bool runImpl(Module &M) {
152 bool Changed = false;
153 LLVMContext &Ctx = M.getContext();
154 Triple ModuleTriple(M.getTargetTriple());
155 bool IsMSVC = ModuleTriple.isKnownWindowsMSVCEnvironment();
156 bool IsELF = ModuleTriple.isOSBinFormatELF();
157 assert((IsELF || IsMSVC) && "Unsupported triple for JMC");
158 bool UseX86FastCall = IsMSVC && ModuleTriple.getArch() == Triple::x86;
159 const char *const FlagSymbolSection = IsELF ? ".data.just.my.code" : ".msvcjmc";
160
161 GlobalValue *CheckFunction = nullptr;
162 DenseMap<DISubprogram *, Constant *> SavedFlags(8);
163 for (auto &F : M) {
164 if (F.isDeclaration())
165 continue;
166 auto *SP = F.getSubprogram();
167 if (!SP)
168 continue;
169
170 Constant *&Flag = SavedFlags[SP];
171 if (!Flag) {
172 std::string FlagName = getFlagName(SP&: *SP, UseX86FastCall);
173 IntegerType *FlagTy = Type::getInt8Ty(C&: Ctx);
174 Flag = M.getOrInsertGlobal(Name: FlagName, Ty: FlagTy, CreateGlobalCallback: [&] {
175 // FIXME: Put the GV in comdat and have linkonce_odr linkage to save
176 // .msvcjmc section space? maybe not worth it.
177 GlobalVariable *GV = new GlobalVariable(
178 M, FlagTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
179 ConstantInt::get(Ty: FlagTy, V: 1), FlagName);
180 GV->setSection(FlagSymbolSection);
181 GV->setAlignment(Align(1));
182 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
183 attachDebugInfo(GV&: *GV, SP&: *SP);
184 return GV;
185 });
186 }
187
188 if (!CheckFunction) {
189 Function *DefaultCheckFunc =
190 createDefaultCheckFunction(M, UseX86FastCall);
191 if (IsELF) {
192 DefaultCheckFunc->setName(CheckFunctionName);
193 DefaultCheckFunc->setLinkage(GlobalValue::WeakAnyLinkage);
194 CheckFunction = DefaultCheckFunc;
195 } else {
196 assert(!M.getFunction(CheckFunctionName) &&
197 "JMC instrument more than once?");
198 auto *CheckFunc = cast<Function>(
199 Val: M.getOrInsertFunction(Name: CheckFunctionName, T: getCheckFunctionType(Ctx))
200 .getCallee());
201 CheckFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
202 CheckFunc->addParamAttr(ArgNo: 0, Kind: Attribute::NoUndef);
203 if (UseX86FastCall) {
204 CheckFunc->setCallingConv(CallingConv::X86_FastCall);
205 CheckFunc->addParamAttr(ArgNo: 0, Kind: Attribute::InReg);
206 }
207 CheckFunction = CheckFunc;
208
209 StringRef DefaultCheckFunctionName = DefaultCheckFunc->getName();
210 appendToUsed(M, Values: {DefaultCheckFunc});
211 Comdat *C = M.getOrInsertComdat(Name: DefaultCheckFunctionName);
212 C->setSelectionKind(Comdat::Any);
213 DefaultCheckFunc->setComdat(C);
214 // Add a linker option /alternatename to set the default implementation
215 // for the check function.
216 // https://devblogs.microsoft.com/oldnewthing/20200731-00/?p=104024
217 std::string AltOption = std::string("/alternatename:") +
218 CheckFunctionName + "=" +
219 DefaultCheckFunctionName.str();
220 llvm::Metadata *Ops[] = {llvm::MDString::get(Context&: Ctx, Str: AltOption)};
221 MDTuple *N = MDNode::get(Context&: Ctx, MDs: Ops);
222 M.getOrInsertNamedMetadata(Name: "llvm.linker.options")->addOperand(M: N);
223 }
224 }
225 // FIXME: it would be nice to make CI scheduling boundary, although in
226 // practice it does not matter much.
227 auto *CI = CallInst::Create(Ty: getCheckFunctionType(Ctx), Func: CheckFunction,
228 Args: {Flag}, NameStr: "", InsertBefore: F.begin()->getFirstInsertionPt());
229 CI->addParamAttr(ArgNo: 0, Kind: Attribute::NoUndef);
230 if (UseX86FastCall) {
231 CI->setCallingConv(CallingConv::X86_FastCall);
232 CI->addParamAttr(ArgNo: 0, Kind: Attribute::InReg);
233 }
234
235 Changed = true;
236 }
237 return Changed;
238}
239