]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/ReaderWriter/MachO/StubsPass.cpp
Vendor import of lld trunk r233088:
[FreeBSD/FreeBSD.git] / lib / ReaderWriter / MachO / StubsPass.cpp
1 //===- lib/ReaderWriter/MachO/StubsPass.cpp -------------------------------===//
2 //
3 //                             The LLVM Linker
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 linker pass updates call-sites which have references to shared library
11 // atoms to instead have a reference to a stub (PLT entry) for the specified
12 // symbol.  Each file format defines a subclass of StubsPass which implements
13 // the abstract methods for creating the file format specific StubAtoms.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "ArchHandler.h"
18 #include "File.h"
19 #include "MachOPasses.h"
20 #include "lld/Core/DefinedAtom.h"
21 #include "lld/Core/File.h"
22 #include "lld/Core/LLVM.h"
23 #include "lld/Core/Reference.h"
24 #include "lld/Core/Simple.h"
25 #include "lld/ReaderWriter/MachOLinkingContext.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallVector.h"
28
29
30 namespace lld {
31 namespace mach_o {
32
33
34 //
35 //  Lazy Pointer Atom created by the stubs pass.
36 //
37 class LazyPointerAtom : public SimpleDefinedAtom {
38 public:
39   LazyPointerAtom(const File &file, bool is64)
40     : SimpleDefinedAtom(file), _is64(is64) { }
41
42   ContentType contentType() const override {
43     return DefinedAtom::typeLazyPointer;
44   }
45
46   Alignment alignment() const override {
47     return Alignment(_is64 ? 3 : 2);
48   }
49
50   uint64_t size() const override {
51     return _is64 ? 8 : 4;
52   }
53
54   ContentPermissions permissions() const override {
55     return DefinedAtom::permRW_;
56   }
57
58   ArrayRef<uint8_t> rawContent() const override {
59     static const uint8_t zeros[] =
60         { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
61     return llvm::makeArrayRef(zeros, size());
62   }
63
64 private:
65   const bool _is64;
66 };
67
68
69 //
70 //  NonLazyPointer (GOT) Atom created by the stubs pass.
71 //
72 class NonLazyPointerAtom : public SimpleDefinedAtom {
73 public:
74   NonLazyPointerAtom(const File &file, bool is64)
75     : SimpleDefinedAtom(file), _is64(is64) { }
76
77   ContentType contentType() const override {
78     return DefinedAtom::typeGOT;
79   }
80
81   Alignment alignment() const override {
82     return Alignment(_is64 ? 3 : 2);
83   }
84
85   uint64_t size() const override {
86     return _is64 ? 8 : 4;
87   }
88
89   ContentPermissions permissions() const override {
90     return DefinedAtom::permRW_;
91   }
92
93   ArrayRef<uint8_t> rawContent() const override {
94     static const uint8_t zeros[] =
95         { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
96     return llvm::makeArrayRef(zeros, size());
97   }
98
99 private:
100   const bool _is64;
101 };
102
103
104
105 //
106 // Stub Atom created by the stubs pass.
107 //
108 class StubAtom : public SimpleDefinedAtom {
109 public:
110   StubAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
111       : SimpleDefinedAtom(file), _stubInfo(stubInfo){ }
112
113   ContentType contentType() const override {
114     return DefinedAtom::typeStub;
115   }
116
117   Alignment alignment() const override {
118     return Alignment(_stubInfo.codeAlignment);
119   }
120
121   uint64_t size() const override {
122     return _stubInfo.stubSize;
123   }
124
125   ContentPermissions permissions() const override {
126     return DefinedAtom::permR_X;
127   }
128
129   ArrayRef<uint8_t> rawContent() const override {
130     return llvm::makeArrayRef(_stubInfo.stubBytes, _stubInfo.stubSize);
131   }
132
133 private:
134   const ArchHandler::StubInfo   &_stubInfo;
135 };
136
137
138 //
139 // Stub Helper Atom created by the stubs pass.
140 //
141 class StubHelperAtom : public SimpleDefinedAtom {
142 public:
143   StubHelperAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
144       : SimpleDefinedAtom(file), _stubInfo(stubInfo) { }
145
146   ContentType contentType() const override {
147     return DefinedAtom::typeStubHelper;
148   }
149
150   Alignment alignment() const override {
151     return Alignment(_stubInfo.codeAlignment);
152   }
153
154   uint64_t size() const override {
155     return _stubInfo.stubHelperSize;
156   }
157
158   ContentPermissions permissions() const override {
159     return DefinedAtom::permR_X;
160   }
161
162   ArrayRef<uint8_t> rawContent() const override {
163     return llvm::makeArrayRef(_stubInfo.stubHelperBytes,
164                               _stubInfo.stubHelperSize);
165   }
166
167 private:
168   const ArchHandler::StubInfo   &_stubInfo;
169 };
170
171
172 //
173 // Stub Helper Common Atom created by the stubs pass.
174 //
175 class StubHelperCommonAtom : public SimpleDefinedAtom {
176 public:
177   StubHelperCommonAtom(const File &file, const ArchHandler::StubInfo &stubInfo)
178       : SimpleDefinedAtom(file), _stubInfo(stubInfo) { }
179
180   ContentType contentType() const override {
181     return DefinedAtom::typeStubHelper;
182   }
183
184   Alignment alignment() const override {
185     return Alignment(_stubInfo.codeAlignment);
186   }
187
188   uint64_t size() const override {
189     return _stubInfo.stubHelperCommonSize;
190   }
191
192   ContentPermissions permissions() const override {
193     return DefinedAtom::permR_X;
194   }
195
196   ArrayRef<uint8_t> rawContent() const override {
197     return llvm::makeArrayRef(_stubInfo.stubHelperCommonBytes,
198                         _stubInfo.stubHelperCommonSize);
199   }
200
201 private:
202   const ArchHandler::StubInfo   &_stubInfo;
203 };
204
205
206 class StubsPass : public Pass {
207 public:
208   StubsPass(const MachOLinkingContext &context)
209     : _context(context), _archHandler(_context.archHandler()),
210     _stubInfo(_archHandler.stubInfo()), _file("<mach-o Stubs pass>") { }
211
212
213   void perform(std::unique_ptr<MutableFile> &mergedFile) override {
214     // Skip this pass if output format uses text relocations instead of stubs.
215     if (!this->noTextRelocs())
216       return;
217
218     // Scan all references in all atoms.
219     for (const DefinedAtom *atom : mergedFile->defined()) {
220       for (const Reference *ref : *atom) {
221         // Look at call-sites.
222         if (!this->isCallSite(*ref))
223           continue;
224         const Atom *target = ref->target();
225         assert(target != nullptr);
226         if (isa<SharedLibraryAtom>(target)) {
227           // Calls to shared libraries go through stubs.
228           _targetToUses[target].push_back(ref);
229           continue;
230         }
231         const DefinedAtom *defTarget = dyn_cast<DefinedAtom>(target);
232         if (defTarget && defTarget->interposable() != DefinedAtom::interposeNo){
233           // Calls to interposable functions in same linkage unit must also go
234           // through a stub.
235           assert(defTarget->scope() != DefinedAtom::scopeTranslationUnit);
236           _targetToUses[target].push_back(ref);
237         }
238       }
239     }
240
241     // Exit early if no stubs needed.
242     if (_targetToUses.empty())
243       return;
244
245     // First add help-common and GOT slots used by lazy binding.
246     SimpleDefinedAtom *helperCommonAtom =
247         new (_file.allocator()) StubHelperCommonAtom(_file, _stubInfo);
248     SimpleDefinedAtom *helperCacheNLPAtom =
249         new (_file.allocator()) NonLazyPointerAtom(_file, _context.is64Bit());
250     SimpleDefinedAtom *helperBinderNLPAtom =
251         new (_file.allocator()) NonLazyPointerAtom(_file, _context.is64Bit());
252     addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
253                  helperCacheNLPAtom);
254     addOptReference(
255         helperCommonAtom, _stubInfo.stubHelperCommonReferenceToCache,
256         _stubInfo.optStubHelperCommonReferenceToCache, helperCacheNLPAtom);
257     addReference(helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
258                  helperBinderNLPAtom);
259     addOptReference(
260         helperCommonAtom, _stubInfo.stubHelperCommonReferenceToBinder,
261         _stubInfo.optStubHelperCommonReferenceToBinder, helperBinderNLPAtom);
262     mergedFile->addAtom(*helperCommonAtom);
263     mergedFile->addAtom(*helperBinderNLPAtom);
264     mergedFile->addAtom(*helperCacheNLPAtom);
265
266     // Add reference to dyld_stub_binder in libSystem.dylib
267     auto I = std::find_if(
268         mergedFile->sharedLibrary().begin(), mergedFile->sharedLibrary().end(),
269         [&](const SharedLibraryAtom *atom) {
270           return atom->name().equals(_stubInfo.binderSymbolName);
271         });
272     assert(I != mergedFile->sharedLibrary().end() && "dyld_stub_binder not found");
273     addReference(helperBinderNLPAtom, _stubInfo.nonLazyPointerReferenceToBinder, *I);
274
275     // Sort targets by name, so stubs and lazy pointers are consistent
276     std::vector<const Atom *> targetsNeedingStubs;
277     for (auto it : _targetToUses)
278       targetsNeedingStubs.push_back(it.first);
279     std::sort(targetsNeedingStubs.begin(), targetsNeedingStubs.end(),
280               [](const Atom * left, const Atom * right) {
281       return (left->name().compare(right->name()) < 0);
282     });
283
284     // Make and append stubs, lazy pointers, and helpers in alphabetical order.
285     unsigned lazyOffset = 0;
286     for (const Atom *target : targetsNeedingStubs) {
287       StubAtom *stub = new (_file.allocator()) StubAtom(_file, _stubInfo);
288       LazyPointerAtom *lp =
289           new (_file.allocator()) LazyPointerAtom(_file, _context.is64Bit());
290       StubHelperAtom *helper =
291           new (_file.allocator()) StubHelperAtom(_file, _stubInfo);
292
293       addReference(stub, _stubInfo.stubReferenceToLP, lp);
294       addOptReference(stub, _stubInfo.stubReferenceToLP,
295                       _stubInfo.optStubReferenceToLP, lp);
296       addReference(lp, _stubInfo.lazyPointerReferenceToHelper, helper);
297       addReference(lp, _stubInfo.lazyPointerReferenceToFinal, target);
298       addReference(helper, _stubInfo.stubHelperReferenceToImm, helper);
299       addReferenceAddend(helper, _stubInfo.stubHelperReferenceToImm, helper,
300                          lazyOffset);
301       addReference(helper, _stubInfo.stubHelperReferenceToHelperCommon,
302                    helperCommonAtom);
303
304       mergedFile->addAtom(*stub);
305       mergedFile->addAtom(*lp);
306       mergedFile->addAtom(*helper);
307
308       // Update each reference to use stub.
309       for (const Reference *ref : _targetToUses[target]) {
310         assert(ref->target() == target);
311         // Switch call site to reference stub atom instead.
312         const_cast<Reference *>(ref)->setTarget(stub);
313       }
314
315       // Calculate new offset
316       lazyOffset += target->name().size() + 12;
317     }
318   }
319
320 private:
321
322   bool noTextRelocs() {
323     return true;
324   }
325
326   bool isCallSite(const Reference &ref) {
327     return _archHandler.isCallSite(ref);
328   }
329
330   void addReference(SimpleDefinedAtom* atom,
331                     const ArchHandler::ReferenceInfo &refInfo,
332                     const lld::Atom* target) {
333     atom->addReference(Reference::KindNamespace::mach_o,
334                       refInfo.arch, refInfo.kind, refInfo.offset,
335                       target, refInfo.addend);
336   }
337
338   void addReferenceAddend(SimpleDefinedAtom *atom,
339                           const ArchHandler::ReferenceInfo &refInfo,
340                           const lld::Atom *target, uint64_t addend) {
341     atom->addReference(Reference::KindNamespace::mach_o, refInfo.arch,
342                        refInfo.kind, refInfo.offset, target, addend);
343   }
344
345    void addOptReference(SimpleDefinedAtom* atom,
346                     const ArchHandler::ReferenceInfo &refInfo,
347                     const ArchHandler::OptionalRefInfo &optRef,
348                     const lld::Atom* target) {
349       if (!optRef.used)
350         return;
351     atom->addReference(Reference::KindNamespace::mach_o,
352                       refInfo.arch, optRef.kind, optRef.offset,
353                       target, optRef.addend);
354   }
355
356   typedef llvm::DenseMap<const Atom*,
357                          llvm::SmallVector<const Reference *, 8>> TargetToUses;
358
359   const MachOLinkingContext                      &_context;
360   mach_o::ArchHandler                            &_archHandler;
361   const ArchHandler::StubInfo                    &_stubInfo;
362   MachOFile                                       _file;
363   TargetToUses                                    _targetToUses;
364 };
365
366
367
368 void addStubsPass(PassManager &pm, const MachOLinkingContext &ctx) {
369   pm.add(std::unique_ptr<Pass>(new StubsPass(ctx)));
370 }
371
372 } // end namespace mach_o
373 } // end namespace lld