1 //===- lib/ReaderWriter/MachO/File.h ----------------------------*- C++ -*-===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLD_READER_WRITER_MACHO_FILE_H
11 #define LLD_READER_WRITER_MACHO_FILE_H
14 #include "DebugInfo.h"
15 #include "MachONormalizedFile.h"
16 #include "lld/Core/SharedLibraryFile.h"
17 #include "lld/Core/Simple.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/Format.h"
21 #include <unordered_map>
26 using lld::mach_o::normalized::Section;
28 class MachOFile : public SimpleFile {
31 /// Real file constructor - for on-disk files.
32 MachOFile(std::unique_ptr<MemoryBuffer> mb, MachOLinkingContext *ctx)
33 : SimpleFile(mb->getBufferIdentifier(), File::kindMachObject),
34 _mb(std::move(mb)), _ctx(ctx) {}
36 /// Dummy file constructor - for virtual files.
37 MachOFile(StringRef path)
38 : SimpleFile(path, File::kindMachObject) {}
40 void addDefinedAtom(StringRef name, Atom::Scope scope,
41 DefinedAtom::ContentType type, DefinedAtom::Merge merge,
42 uint64_t sectionOffset, uint64_t contentSize, bool thumb,
43 bool noDeadStrip, bool copyRefs,
44 const Section *inSection) {
45 assert(sectionOffset+contentSize <= inSection->content.size());
46 ArrayRef<uint8_t> content = inSection->content.slice(sectionOffset,
49 // Make a copy of the atom's name and content that is owned by this file.
50 name = name.copy(allocator());
51 content = content.copy(allocator());
53 DefinedAtom::Alignment align(
55 sectionOffset % inSection->alignment);
57 new (allocator()) MachODefinedAtom(*this, name, scope, type, merge,
58 thumb, noDeadStrip, content, align);
59 addAtomForSection(inSection, atom, sectionOffset);
62 void addDefinedAtomInCustomSection(StringRef name, Atom::Scope scope,
63 DefinedAtom::ContentType type, DefinedAtom::Merge merge,
64 bool thumb, bool noDeadStrip, uint64_t sectionOffset,
65 uint64_t contentSize, StringRef sectionName,
66 bool copyRefs, const Section *inSection) {
67 assert(sectionOffset+contentSize <= inSection->content.size());
68 ArrayRef<uint8_t> content = inSection->content.slice(sectionOffset,
71 // Make a copy of the atom's name and content that is owned by this file.
72 name = name.copy(allocator());
73 content = content.copy(allocator());
74 sectionName = sectionName.copy(allocator());
76 DefinedAtom::Alignment align(
78 sectionOffset % inSection->alignment);
80 new (allocator()) MachODefinedCustomSectionAtom(*this, name, scope, type,
84 addAtomForSection(inSection, atom, sectionOffset);
87 void addZeroFillDefinedAtom(StringRef name, Atom::Scope scope,
88 uint64_t sectionOffset, uint64_t size,
89 bool noDeadStrip, bool copyRefs,
90 const Section *inSection) {
92 // Make a copy of the atom's name and content that is owned by this file.
93 name = name.copy(allocator());
95 DefinedAtom::Alignment align(
97 sectionOffset % inSection->alignment);
99 DefinedAtom::ContentType type = DefinedAtom::typeUnknown;
100 switch (inSection->type) {
101 case llvm::MachO::S_ZEROFILL:
102 type = DefinedAtom::typeZeroFill;
104 case llvm::MachO::S_THREAD_LOCAL_ZEROFILL:
105 type = DefinedAtom::typeTLVInitialZeroFill;
108 llvm_unreachable("Unrecognized zero-fill section");
112 new (allocator()) MachODefinedAtom(*this, name, scope, type, size,
114 addAtomForSection(inSection, atom, sectionOffset);
117 void addUndefinedAtom(StringRef name, bool copyRefs) {
119 // Make a copy of the atom's name that is owned by this file.
120 name = name.copy(allocator());
122 auto *atom = new (allocator()) SimpleUndefinedAtom(*this, name);
124 _undefAtoms[name] = atom;
127 void addTentativeDefAtom(StringRef name, Atom::Scope scope, uint64_t size,
128 DefinedAtom::Alignment align, bool copyRefs) {
130 // Make a copy of the atom's name that is owned by this file.
131 name = name.copy(allocator());
134 new (allocator()) MachOTentativeDefAtom(*this, name, scope, size, align);
136 _undefAtoms[name] = atom;
139 /// Search this file for an the atom from 'section' that covers
140 /// 'offsetInSect'. Returns nullptr is no atom found.
141 MachODefinedAtom *findAtomCoveringAddress(const Section §ion,
142 uint64_t offsetInSect,
143 uint32_t *foundOffsetAtom=nullptr) {
144 const auto &pos = _sectionAtoms.find(§ion);
145 if (pos == _sectionAtoms.end())
147 const auto &vec = pos->second;
148 assert(offsetInSect < section.content.size());
149 // Vector of atoms for section are already sorted, so do binary search.
150 const auto &atomPos = std::lower_bound(vec.begin(), vec.end(), offsetInSect,
151 [offsetInSect](const SectionOffsetAndAtom &ao,
152 uint64_t targetAddr) -> bool {
153 // Each atom has a start offset of its slice of the
154 // section's content. This compare function must return true
155 // iff the atom's range is before the offset being searched for.
156 uint64_t atomsEndOffset = ao.offset+ao.atom->rawContent().size();
157 return (atomsEndOffset <= offsetInSect);
159 if (atomPos == vec.end())
162 *foundOffsetAtom = offsetInSect - atomPos->offset;
163 return atomPos->atom;
166 /// Searches this file for an UndefinedAtom named 'name'. Returns
167 /// nullptr is no such atom found.
168 const lld::Atom *findUndefAtom(StringRef name) {
169 auto pos = _undefAtoms.find(name);
170 if (pos == _undefAtoms.end())
175 typedef std::function<void (MachODefinedAtom* atom)> DefinedAtomVisitor;
177 void eachDefinedAtom(DefinedAtomVisitor vistor) {
178 for (auto §AndAtoms : _sectionAtoms) {
179 for (auto &offAndAtom : sectAndAtoms.second) {
180 vistor(offAndAtom.atom);
185 typedef std::function<void(MachODefinedAtom *atom, uint64_t offset)>
188 void eachAtomInSection(const Section §ion, SectionAtomVisitor visitor) {
189 auto pos = _sectionAtoms.find(§ion);
190 if (pos == _sectionAtoms.end())
192 auto vec = pos->second;
194 for (auto &offAndAtom : vec)
195 visitor(offAndAtom.atom, offAndAtom.offset);
198 MachOLinkingContext::Arch arch() const { return _arch; }
199 void setArch(MachOLinkingContext::Arch arch) { _arch = arch; }
201 MachOLinkingContext::OS OS() const { return _os; }
202 void setOS(MachOLinkingContext::OS os) { _os = os; }
204 MachOLinkingContext::ObjCConstraint objcConstraint() const {
205 return _objcConstraint;
207 void setObjcConstraint(MachOLinkingContext::ObjCConstraint v) {
211 uint32_t minVersion() const { return _minVersion; }
212 void setMinVersion(uint32_t v) { _minVersion = v; }
214 LoadCommandType minVersionLoadCommandKind() const {
215 return _minVersionLoadCommandKind;
217 void setMinVersionLoadCommandKind(LoadCommandType v) {
218 _minVersionLoadCommandKind = v;
221 uint32_t swiftVersion() const { return _swiftVersion; }
222 void setSwiftVersion(uint32_t v) { _swiftVersion = v; }
224 bool subsectionsViaSymbols() const {
225 return _flags & llvm::MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
227 void setFlags(normalized::FileFlags v) { _flags = v; }
229 /// Methods for support type inquiry through isa, cast, and dyn_cast:
230 static inline bool classof(const File *F) {
231 return F->kind() == File::kindMachObject;
234 void setDebugInfo(std::unique_ptr<DebugInfo> debugInfo) {
235 _debugInfo = std::move(debugInfo);
238 DebugInfo* debugInfo() const { return _debugInfo.get(); }
239 std::unique_ptr<DebugInfo> takeDebugInfo() { return std::move(_debugInfo); }
242 std::error_code doParse() override {
243 // Convert binary file to normalized mach-o.
244 auto normFile = normalized::readBinary(_mb, _ctx->arch());
245 if (auto ec = normFile.takeError())
246 return llvm::errorToErrorCode(std::move(ec));
247 // Convert normalized mach-o to atoms.
248 if (auto ec = normalized::normalizedObjectToAtoms(this, **normFile, false))
249 return llvm::errorToErrorCode(std::move(ec));
250 return std::error_code();
254 struct SectionOffsetAndAtom { uint64_t offset; MachODefinedAtom *atom; };
256 void addAtomForSection(const Section *inSection, MachODefinedAtom* atom,
257 uint64_t sectionOffset) {
258 SectionOffsetAndAtom offAndAtom;
259 offAndAtom.offset = sectionOffset;
260 offAndAtom.atom = atom;
261 _sectionAtoms[inSection].push_back(offAndAtom);
265 typedef llvm::DenseMap<const normalized::Section *,
266 std::vector<SectionOffsetAndAtom>> SectionToAtoms;
267 typedef llvm::StringMap<const lld::Atom *> NameToAtom;
269 std::unique_ptr<MemoryBuffer> _mb;
270 MachOLinkingContext *_ctx;
271 SectionToAtoms _sectionAtoms;
272 NameToAtom _undefAtoms;
273 MachOLinkingContext::Arch _arch = MachOLinkingContext::arch_unknown;
274 MachOLinkingContext::OS _os = MachOLinkingContext::OS::unknown;
275 uint32_t _minVersion = 0;
276 LoadCommandType _minVersionLoadCommandKind = (LoadCommandType)0;
277 MachOLinkingContext::ObjCConstraint _objcConstraint =
278 MachOLinkingContext::objc_unknown;
279 uint32_t _swiftVersion = 0;
280 normalized::FileFlags _flags = llvm::MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
281 std::unique_ptr<DebugInfo> _debugInfo;
284 class MachODylibFile : public SharedLibraryFile {
286 MachODylibFile(std::unique_ptr<MemoryBuffer> mb, MachOLinkingContext *ctx)
287 : SharedLibraryFile(mb->getBufferIdentifier()),
288 _mb(std::move(mb)), _ctx(ctx) {}
290 MachODylibFile(StringRef path) : SharedLibraryFile(path) {}
292 OwningAtomPtr<SharedLibraryAtom> exports(StringRef name) const override {
293 // Pass down _installName so that if this requested symbol
294 // is re-exported through this dylib, the SharedLibraryAtom's loadName()
295 // is this dylib installName and not the implementation dylib's.
296 // NOTE: isData is not needed for dylibs (it matters for static libs).
297 return exports(name, _installName);
300 /// Adds symbol name that this dylib exports. The corresponding
301 /// SharedLibraryAtom is created lazily (since most symbols are not used).
302 void addExportedSymbol(StringRef name, bool weakDef, bool copyRefs) {
304 name = name.copy(allocator());
306 AtomAndFlags info(weakDef);
307 _nameToAtom[name] = info;
310 void addReExportedDylib(StringRef dylibPath) {
311 _reExportedDylibs.emplace_back(dylibPath);
314 StringRef installName() const { return _installName; }
315 uint32_t currentVersion() { return _currentVersion; }
316 uint32_t compatVersion() { return _compatVersion; }
318 void setInstallName(StringRef name) { _installName = name; }
319 void setCompatVersion(uint32_t version) { _compatVersion = version; }
320 void setCurrentVersion(uint32_t version) { _currentVersion = version; }
322 typedef std::function<MachODylibFile *(StringRef)> FindDylib;
324 void loadReExportedDylibs(FindDylib find) {
325 for (ReExportedDylib &entry : _reExportedDylibs) {
326 entry.file = find(entry.path);
330 StringRef getDSOName() const override { return _installName; }
332 std::error_code doParse() override {
333 // Convert binary file to normalized mach-o.
334 auto normFile = normalized::readBinary(_mb, _ctx->arch());
335 if (auto ec = normFile.takeError())
336 return llvm::errorToErrorCode(std::move(ec));
337 // Convert normalized mach-o to atoms.
338 if (auto ec = normalized::normalizedDylibToAtoms(this, **normFile, false))
339 return llvm::errorToErrorCode(std::move(ec));
340 return std::error_code();
344 OwningAtomPtr<SharedLibraryAtom> exports(StringRef name,
345 StringRef installName) const {
346 // First, check if requested symbol is directly implemented by this dylib.
347 auto entry = _nameToAtom.find(name);
348 if (entry != _nameToAtom.end()) {
349 // FIXME: Make this map a set and only used in assert builds.
350 // Note, its safe to assert here as the resolver is the only client of
351 // this API and it only requests exports for undefined symbols.
352 // If we return from here we are no longer undefined so we should never
354 assert(!entry->second.atom && "Duplicate shared library export");
355 bool weakDef = entry->second.weakDef;
356 auto *atom = new (allocator()) MachOSharedLibraryAtom(*this, name,
359 entry->second.atom = atom;
363 // Next, check if symbol is implemented in some re-exported dylib.
364 for (const ReExportedDylib &dylib : _reExportedDylibs) {
366 auto atom = dylib.file->exports(name, installName);
371 // Symbol not exported or re-exported by this dylib.
375 struct ReExportedDylib {
376 ReExportedDylib(StringRef p) : path(p), file(nullptr) { }
378 MachODylibFile *file;
381 struct AtomAndFlags {
382 AtomAndFlags() : atom(nullptr), weakDef(false) { }
383 AtomAndFlags(bool weak) : atom(nullptr), weakDef(weak) { }
384 const SharedLibraryAtom *atom;
388 std::unique_ptr<MemoryBuffer> _mb;
389 MachOLinkingContext *_ctx;
390 StringRef _installName;
391 uint32_t _currentVersion;
392 uint32_t _compatVersion;
393 std::vector<ReExportedDylib> _reExportedDylibs;
394 mutable std::unordered_map<StringRef, AtomAndFlags> _nameToAtom;
397 } // end namespace mach_o
398 } // end namespace lld
400 #endif // LLD_READER_WRITER_MACHO_FILE_H