forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidateInternalCalls.cpp
343 lines (300 loc) · 12 KB
/
ValidateInternalCalls.cpp
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
//===- bolt/Passes/ValidateInternalCalls.cpp ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the ValidateInternalCalls class.
//
//===----------------------------------------------------------------------===//
#include "bolt/Passes/ValidateInternalCalls.h"
#include "bolt/Passes/DataflowInfoManager.h"
#include "bolt/Passes/FrameAnalysis.h"
#include "llvm/MC/MCInstPrinter.h"
#define DEBUG_TYPE "bolt-internalcalls"
namespace llvm {
namespace bolt {
namespace {
// Helper used to extract the target basic block used in an internal call.
// Return nullptr if this is not an internal call target.
BinaryBasicBlock *getInternalCallTarget(BinaryFunction &Function,
const MCInst &Inst) {
const BinaryContext &BC = Function.getBinaryContext();
if (!BC.MIB->isCall(Inst) || MCPlus::getNumPrimeOperands(Inst) != 1 ||
!Inst.getOperand(0).isExpr())
return nullptr;
return Function.getBasicBlockForLabel(BC.MIB->getTargetSymbol(Inst));
}
// A special StackPointerTracking that considers internal calls
class StackPointerTrackingForInternalCalls
: public StackPointerTrackingBase<StackPointerTrackingForInternalCalls> {
friend class DataflowAnalysis<StackPointerTrackingForInternalCalls,
std::pair<int, int>>;
Optional<unsigned> AnnotationIndex;
protected:
// We change the starting state to only consider the first block as an
// entry point, otherwise the analysis won't converge (there will be two valid
// stack offsets, one for an external call and another for an internal call).
std::pair<int, int> getStartingStateAtBB(const BinaryBasicBlock &BB) {
if (&BB == &*Func.begin())
return std::make_pair(-8, getEmpty());
return std::make_pair(getEmpty(), getEmpty());
}
// Here we decrement SP for internal calls too, in addition to the regular
// StackPointerTracking processing.
std::pair<int, int> computeNext(const MCInst &Point,
const std::pair<int, int> &Cur) {
std::pair<int, int> Res = StackPointerTrackingBase<
StackPointerTrackingForInternalCalls>::computeNext(Point, Cur);
if (Res.first == StackPointerTracking::SUPERPOSITION ||
Res.first == StackPointerTracking::EMPTY)
return Res;
if (BC.MIB->isReturn(Point)) {
Res.first += 8;
return Res;
}
BinaryBasicBlock *Target = getInternalCallTarget(Func, Point);
if (!Target)
return Res;
Res.first -= 8;
return Res;
}
StringRef getAnnotationName() const {
return StringRef("StackPointerTrackingForInternalCalls");
}
public:
StackPointerTrackingForInternalCalls(BinaryFunction &BF)
: StackPointerTrackingBase<StackPointerTrackingForInternalCalls>(BF) {}
void run() {
StackPointerTrackingBase<StackPointerTrackingForInternalCalls>::run();
}
};
} // end anonymous namespace
bool ValidateInternalCalls::fixCFGForPIC(BinaryFunction &Function) const {
const BinaryContext &BC = Function.getBinaryContext();
for (BinaryBasicBlock &BB : Function) {
for (auto II = BB.begin(); II != BB.end(); ++II) {
MCInst &Inst = *II;
BinaryBasicBlock *Target = getInternalCallTarget(Function, Inst);
if (!Target || BC.MIB->hasAnnotation(Inst, getProcessedICTag()))
continue;
BC.MIB->addAnnotation(Inst, getProcessedICTag(), 0U);
InstructionListType MovedInsts = BB.splitInstructions(&Inst);
if (!MovedInsts.empty()) {
// Split this block at the call instruction. Create an unreachable
// block.
std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
NewBBs.emplace_back(Function.createBasicBlock(0));
NewBBs.back()->addInstructions(MovedInsts.begin(), MovedInsts.end());
BB.moveAllSuccessorsTo(NewBBs.back().get());
Function.insertBasicBlocks(&BB, std::move(NewBBs));
}
// Update successors
BB.removeAllSuccessors();
BB.addSuccessor(Target, BB.getExecutionCount(), 0ULL);
return true;
}
}
return false;
}
bool ValidateInternalCalls::fixCFGForIC(BinaryFunction &Function) const {
const BinaryContext &BC = Function.getBinaryContext();
// Track SP value
StackPointerTrackingForInternalCalls SPTIC(Function);
SPTIC.run();
// Track instructions reaching a given point of the CFG to answer
// "There is a path from entry to point A that contains instruction B"
ReachingInsns<false> RI(Function);
RI.run();
// We use the InsnToBB map that DataflowInfoManager provides us
DataflowInfoManager Info(Function, nullptr, nullptr);
bool Updated = false;
auto processReturns = [&](BinaryBasicBlock &BB, MCInst &Return) {
// Check all reaching internal calls
for (auto I = RI.expr_begin(Return), E = RI.expr_end(); I != E; ++I) {
MCInst &ReachingInst = **I;
if (!getInternalCallTarget(Function, ReachingInst) ||
BC.MIB->hasAnnotation(ReachingInst, getProcessedICTag()))
continue;
// Stack pointer matching
int SPAtCall = SPTIC.getStateAt(ReachingInst)->first;
int SPAtRet = SPTIC.getStateAt(Return)->first;
if (SPAtCall != StackPointerTracking::SUPERPOSITION &&
SPAtRet != StackPointerTracking::SUPERPOSITION &&
SPAtCall != SPAtRet - 8)
continue;
Updated = true;
// Mark this call as processed, so we don't try to analyze it as a
// PIC-computation internal call.
BC.MIB->addAnnotation(ReachingInst, getProcessedICTag(), 0U);
// Connect this block with the returning block of the caller
BinaryBasicBlock *CallerBlock = Info.getInsnToBBMap()[&ReachingInst];
BinaryBasicBlock *ReturnDestBlock =
Function.getBasicBlockAfter(CallerBlock);
BB.addSuccessor(ReturnDestBlock, BB.getExecutionCount(), 0);
}
};
// This will connect blocks terminated with RETs to their respective
// internal caller return block. A note here: this is overly conservative
// because in nested calls, or unrelated calls, it will create edges
// connecting RETs to potentially unrelated internal calls. This is safe
// and if this causes a problem to recover the stack offsets properly, we
// will fail later.
for (BinaryBasicBlock &BB : Function) {
for (MCInst &Inst : BB) {
if (!BC.MIB->isReturn(Inst))
continue;
processReturns(BB, Inst);
}
}
return Updated;
}
bool ValidateInternalCalls::hasTailCallsInRange(
BinaryFunction &Function) const {
const BinaryContext &BC = Function.getBinaryContext();
for (BinaryBasicBlock &BB : Function)
for (MCInst &Inst : BB)
if (BC.MIB->isTailCall(Inst))
return true;
return false;
}
bool ValidateInternalCalls::analyzeFunction(BinaryFunction &Function) const {
while (fixCFGForPIC(Function)) {
}
clearAnnotations(Function);
while (fixCFGForIC(Function)) {
}
BinaryContext &BC = Function.getBinaryContext();
RegAnalysis RA = RegAnalysis(BC, nullptr, nullptr);
RA.setConservativeStrategy(RegAnalysis::ConservativeStrategy::CLOBBERS_NONE);
bool HasTailCalls = hasTailCallsInRange(Function);
for (BinaryBasicBlock &BB : Function) {
for (MCInst &Inst : BB) {
BinaryBasicBlock *Target = getInternalCallTarget(Function, Inst);
if (!Target || BC.MIB->hasAnnotation(Inst, getProcessedICTag()))
continue;
if (HasTailCalls) {
LLVM_DEBUG(dbgs() << Function
<< " has tail calls and internal calls.\n");
return false;
}
FrameIndexEntry FIE;
int32_t SrcImm = 0;
MCPhysReg Reg = 0;
int64_t StackOffset = 0;
bool IsIndexed = false;
MCInst *TargetInst = ProgramPoint::getFirstPointAt(*Target).getInst();
if (!BC.MIB->isStackAccess(*TargetInst, FIE.IsLoad, FIE.IsStore,
FIE.IsStoreFromReg, Reg, SrcImm,
FIE.StackPtrReg, StackOffset, FIE.Size,
FIE.IsSimple, IsIndexed)) {
LLVM_DEBUG({
dbgs() << "Frame analysis failed - not simple: " << Function << "\n";
Function.dump();
});
return false;
}
if (!FIE.IsLoad || FIE.StackPtrReg != BC.MIB->getStackPointer() ||
StackOffset != 0) {
LLVM_DEBUG({
dbgs() << "Target instruction does not fetch return address - not "
"simple: "
<< Function << "\n";
Function.dump();
});
return false;
}
// Now track how the return address is used by tracking uses of Reg
ReachingDefOrUse</*Def=*/false> RU =
ReachingDefOrUse<false>(RA, Function, Reg);
RU.run();
int64_t Offset = static_cast<int64_t>(Target->getInputOffset());
bool UseDetected = false;
for (auto I = RU.expr_begin(*RU.getStateBefore(*TargetInst)),
E = RU.expr_end();
I != E; ++I) {
MCInst &Use = **I;
BitVector UsedRegs = BitVector(BC.MRI->getNumRegs(), false);
BC.MIB->getTouchedRegs(Use, UsedRegs);
if (!UsedRegs[Reg])
continue;
UseDetected = true;
int64_t Output;
std::pair<MCPhysReg, int64_t> Input1 = std::make_pair(Reg, 0);
std::pair<MCPhysReg, int64_t> Input2 = std::make_pair(0, 0);
if (!BC.MIB->evaluateSimple(Use, Output, Input1, Input2)) {
LLVM_DEBUG(dbgs() << "Evaluate simple failed.\n");
return false;
}
if (Offset + Output < 0 ||
Offset + Output > static_cast<int64_t>(Function.getSize())) {
LLVM_DEBUG({
dbgs() << "Detected out-of-range PIC reference in " << Function
<< "\nReturn address load: ";
BC.InstPrinter->printInst(TargetInst, 0, "", *BC.STI, dbgs());
dbgs() << "\nUse: ";
BC.InstPrinter->printInst(&Use, 0, "", *BC.STI, dbgs());
dbgs() << "\n";
Function.dump();
});
return false;
}
LLVM_DEBUG({
dbgs() << "Validated access: ";
BC.InstPrinter->printInst(&Use, 0, "", *BC.STI, dbgs());
dbgs() << "\n";
});
}
if (!UseDetected) {
LLVM_DEBUG(dbgs() << "No use detected.\n");
return false;
}
}
}
return true;
}
void ValidateInternalCalls::runOnFunctions(BinaryContext &BC) {
if (!BC.isX86())
return;
// Look for functions that need validation. This should be pretty rare.
std::set<BinaryFunction *> NeedsValidation;
for (auto &BFI : BC.getBinaryFunctions()) {
BinaryFunction &Function = BFI.second;
for (BinaryBasicBlock &BB : Function) {
for (MCInst &Inst : BB) {
if (getInternalCallTarget(Function, Inst)) {
NeedsValidation.insert(&Function);
Function.setSimple(false);
break;
}
}
}
}
// Skip validation for non-relocation mode
if (!BC.HasRelocations)
return;
// Since few functions need validation, we can work with our most expensive
// algorithms here. Fix the CFG treating internal calls as unconditional
// jumps. This optimistically assumes this call is a PIC trick to get the PC
// value, so it is not really a call, but a jump. If we find that it's not the
// case, we mark this function as non-simple and stop processing it.
std::set<BinaryFunction *> Invalid;
for (BinaryFunction *Function : NeedsValidation) {
LLVM_DEBUG(dbgs() << "Validating " << *Function << "\n");
if (!analyzeFunction(*Function))
Invalid.insert(Function);
clearAnnotations(*Function);
}
if (!Invalid.empty()) {
errs() << "BOLT-WARNING: will skip the following function(s) as unsupported"
" internal calls were detected:\n";
for (BinaryFunction *Function : Invalid) {
errs() << " " << *Function << "\n";
Function->setIgnored();
}
}
}
} // namespace bolt
} // namespace llvm