blob: ef22f07813a59a5f57fb1e5655d240596a921a40 [file] [log] [blame]
Nick Kledzik6b079f52013-01-05 02:22:35 +00001//===- lib/ReaderWriter/YAML/ReaderWriterYAML.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
Michael J. Spencer64afcb42013-01-23 01:18:43 +000011#include "lld/ReaderWriter/Reader.h"
12#include "lld/ReaderWriter/Writer.h"
13
Nick Kledzik6b079f52013-01-05 02:22:35 +000014#include "lld/Core/ArchiveLibraryFile.h"
15#include "lld/Core/DefinedAtom.h"
16#include "lld/Core/Error.h"
17#include "lld/Core/File.h"
18#include "lld/Core/LLVM.h"
19#include "lld/Core/Reference.h"
Nick Kledzik6b079f52013-01-05 02:22:35 +000020
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/StringMap.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/Support/system_error.h"
31#include "llvm/Support/YAMLTraits.h"
32
33#include <string>
34
35using llvm::yaml::MappingTraits;
36using llvm::yaml::ScalarEnumerationTraits;
37using llvm::yaml::ScalarTraits;
38using llvm::yaml::IO;
39using llvm::yaml::SequenceTraits;
40using llvm::yaml::DocumentListTraits;
41
Michael J. Spencer64afcb42013-01-23 01:18:43 +000042using namespace lld;
Nick Kledzik6b079f52013-01-05 02:22:35 +000043
44/// The conversion of Atoms to and from YAML uses LLVM's YAML I/O. This
45/// file just defines template specializations on the lld types which control
46/// how the mapping is done to and from YAML.
47
48
49namespace {
50/// Most of the traits are context-free and always do the same transformation.
51/// But, there are some traits that need some contextual information to properly
52/// do their transform. This struct is available via io.getContext() and
53/// supplies contextual information.
54class ContextInfo {
55public:
Michael J. Spencer64afcb42013-01-23 01:18:43 +000056 ContextInfo(const TargetInfo &ti) : _currentFile(nullptr), _targetInfo(ti) {}
Nick Kledzik6b079f52013-01-05 02:22:35 +000057
Michael J. Spencer64afcb42013-01-23 01:18:43 +000058 lld::File *_currentFile;
59 const TargetInfo &_targetInfo;
Nick Kledzik6b079f52013-01-05 02:22:35 +000060};
61
Nick Kledzik6b079f52013-01-05 02:22:35 +000062/// Used when writing yaml files.
63/// In most cases, atoms names are unambiguous, so references can just
64/// use the atom name as the target (e.g. target: foo). But in a few
65/// cases that does not work, so ref-names are added. These are labels
66/// used only in yaml. The labels do not exist in the Atom model.
67///
68/// One need for ref-names are when atoms have no user supplied name
69/// (e.g. c-string literal). Another case is when two object files with
70/// identically named static functions are merged (ld -r) into one object file.
71/// In that case referencing the function by name is ambiguous, so a unique
72/// ref-name is added.
73class RefNameBuilder {
74public:
75 RefNameBuilder(const lld::File &file)
76 : _collisionCount(0), _unnamedCounter(0) {
77 if (&file == nullptr)
78 return;
79 // visit all atoms
80 for (const lld::DefinedAtom *atom : file.defined()) {
81 // Build map of atoms names to detect duplicates
82 if (!atom->name().empty())
83 buildDuplicateNameMap(*atom);
84
85 // Find references to unnamed atoms and create ref-names for them.
86 for (const lld::Reference *ref : *atom) {
87 // create refname for any unnamed reference target
88 const lld::Atom *target = ref->target();
89 if ((target != nullptr) && target->name().empty()) {
90 std::string storage;
91 llvm::raw_string_ostream buffer(storage);
92 buffer << llvm::format("L%03d", _unnamedCounter++);
93 llvm::StringRef newName = copyString(buffer.str());
94 _refNames[target] = newName;
95 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
96 << "unnamed atom: creating ref-name: '" << newName
97 << "' (" << (void*)newName.data() << ", "
98 << newName.size() << ")\n");
99 }
100 }
101 }
102 for (const lld::UndefinedAtom *undefAtom : file.undefined()) {
103 buildDuplicateNameMap(*undefAtom);
104 }
105 for (const lld::SharedLibraryAtom *shlibAtom : file.sharedLibrary()) {
106 buildDuplicateNameMap(*shlibAtom);
107 }
108 for (const lld::AbsoluteAtom *absAtom : file.absolute()) {
109 buildDuplicateNameMap(*absAtom);
110 }
111 }
112
113 void buildDuplicateNameMap(const lld::Atom &atom) {
114 assert(!atom.name().empty());
115 NameToAtom::iterator pos = _nameMap.find(atom.name());
116 if ( pos != _nameMap.end() ) {
117 // Found name collision, give each a unique ref-name.
118 std::string Storage;
119 llvm::raw_string_ostream buffer(Storage);
120 buffer << atom.name() << llvm::format(".%03d", ++_collisionCount);
121 llvm::StringRef newName = copyString(buffer.str());
122 _refNames[&atom] = newName;
123 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
124 << "name collsion: creating ref-name: '" << newName
125 << "' (" << (void*)newName.data() << ", "
126 << newName.size() << ")\n");
127 const lld::Atom *prevAtom = pos->second;
128 AtomToRefName::iterator pos2 = _refNames.find(prevAtom);
129 if ( pos2 == _refNames.end() ) {
130 // Only create ref-name for previous if none already created.
131 std::string Storage2;
132 llvm::raw_string_ostream buffer2(Storage2);
133 buffer2 << prevAtom->name() << llvm::format(".%03d", ++_collisionCount);
134 llvm::StringRef newName2 = copyString(buffer2.str());
135 _refNames[prevAtom] = newName2;
136 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
137 << "name collsion: creating ref-name: '" << newName2
138 << "' (" << (void*)newName2.data() << ", "
139 << newName2.size() << ")\n");
140 }
141 }
142 else {
143 // First time we've seen this name, just add it to map.
144 _nameMap[atom.name()] = &atom;
145 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
146 << "atom name seen for first time: '" << atom.name()
147 << "' (" << (void*)atom.name().data() << ", "
148 << atom.name().size() << ")\n");
149 }
150 }
151
152 bool hasRefName(const lld::Atom *atom) {
153 return _refNames.count(atom);
154 }
155
156 llvm::StringRef refName(const lld::Atom *atom) {
157 return _refNames.find(atom)->second;
158 }
159
160private:
161 typedef llvm::StringMap<const lld::Atom*> NameToAtom;
162 typedef llvm::DenseMap<const lld::Atom*, std::string> AtomToRefName;
163
164 // Allocate a new copy of this string and keep track of allocations
165 // in _stringCopies, so they can be freed when RefNameBuilder is destroyed.
166 llvm::StringRef copyString(llvm::StringRef str) {
167 // We want _stringCopies to own the string memory so it is deallocated
168 // when the File object is destroyed. But we need a StringRef that
169 // points into that memory.
170 std::unique_ptr<char> s = std::unique_ptr<char>(new char[str.size()]);
171 memcpy(s.get(), str.data(), str.size());
172 llvm::StringRef r = llvm::StringRef(s.get(), str.size());
173 _stringCopies.push_back(std::move(s));
174 return r;
175 }
176
177 unsigned int _collisionCount;
178 unsigned int _unnamedCounter;
179 NameToAtom _nameMap;
180 AtomToRefName _refNames;
181 std::vector<std::unique_ptr<char>> _stringCopies;
182};
183
184
185/// Used when reading yaml files to find the target of a reference
186/// that could be a name or ref-name.
187class RefNameResolver {
188public:
189 RefNameResolver(const lld::File *file, IO &io);
190
191 const lld::Atom *lookup(llvm::StringRef name) const {
192 NameToAtom::const_iterator pos = _nameMap.find(name);
193 if (pos != _nameMap.end()) {
194 return pos->second;
195 }
196 else {
197 _io.setError(llvm::Twine("no such atom name: ") + name);
198 return nullptr;
199 }
200 }
201
202private:
203 typedef llvm::StringMap<const lld::Atom*> NameToAtom;
204
205 void add(llvm::StringRef name, const lld::Atom *atom) {
206 if (_nameMap.count(name)) {
207 _io.setError(llvm::Twine("duplicate atom name: ") + name);
208 }
209 else {
210 _nameMap[name] = atom;
211 }
212 }
213
214 IO &_io;
215 NameToAtom _nameMap;
216};
217
218
219// Used in NormalizedFile to hold the atoms lists.
220template <typename T>
221class AtomList : public lld::File::atom_collection<T> {
222public:
223 virtual lld::File::atom_iterator<T> begin() const {
224 return lld::File::atom_iterator<T>(*this, reinterpret_cast<const void*>
225 (_atoms.data()));
226 }
227 virtual lld::File::atom_iterator<T> end() const{
228 return lld::File::atom_iterator<T>(*this, reinterpret_cast<const void*>
229 (_atoms.data() + _atoms.size()));
230 }
231 virtual const T *deref(const void *it) const {
232 return *reinterpret_cast<const T *const*>(it);
233 }
234 virtual void next(const void *&it) const {
235 const T *const *p = reinterpret_cast<const T *const *>(it);
236 ++p;
237 it = reinterpret_cast<const void*>(p);
238 }
239 virtual void push_back(const T *element) {
240 _atoms.push_back(element);
241 }
242 std::vector<const T*> _atoms;
243};
244
245/// Mapping of kind: field in yaml files.
246enum FileKinds {
247 fileKindObjectAtoms, // atom based object file encoded in yaml
248 fileKindArchive, // static archive library encoded in yaml
249 fileKindObjectELF, // ELF object files encoded in yaml
250 fileKindObjectMachO // mach-o object files encoded in yaml
251};
252
253struct ArchMember {
254 FileKinds _kind;
255 llvm::StringRef _name;
256 const lld::File *_content;
257};
258
Nick Kledzikbd491982013-01-08 23:51:03 +0000259
Nick Kledzik6b079f52013-01-05 02:22:35 +0000260// The content bytes in a DefinedAtom are just uint8_t but we want
261// special formatting, so define a strong type.
Nick Kledzikbd491982013-01-08 23:51:03 +0000262LLVM_YAML_STRONG_TYPEDEF(uint8_t, ImplicitHex8)
Nick Kledzik6b079f52013-01-05 02:22:35 +0000263
264// SharedLibraryAtoms have a bool canBeNull() method which we'd like to be
265// more readable than just true/false.
Nick Kledzikbd491982013-01-08 23:51:03 +0000266LLVM_YAML_STRONG_TYPEDEF(bool, ShlibCanBeNull)
Nick Kledzik6b079f52013-01-05 02:22:35 +0000267
268// lld::Reference::Kind is a typedef of int32. We need a stronger
269// type to make template matching work, so invent RefKind.
Nick Kledzikbd491982013-01-08 23:51:03 +0000270LLVM_YAML_STRONG_TYPEDEF(lld::Reference::Kind, RefKind)
Nick Kledzik6b079f52013-01-05 02:22:35 +0000271
Nick Kledzik6b079f52013-01-05 02:22:35 +0000272} // namespace anon
273
Shankar Easwaran3256d4f2013-01-25 07:39:18 +0000274LLVM_YAML_IS_SEQUENCE_VECTOR(ArchMember)
275 LLVM_YAML_IS_SEQUENCE_VECTOR(const lld::Reference *)
276 // Always write DefinedAtoms content bytes as a flow sequence.
277 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(ImplicitHex8)
278 // for compatibility with gcc-4.7 in C++11 mode, add extra namespace
279 namespace llvm {
280 namespace yaml {
Nick Kledzikbd491982013-01-08 23:51:03 +0000281
Nick Kledzik6b079f52013-01-05 02:22:35 +0000282// This is a custom formatter for RefKind
283template<>
284struct ScalarTraits<RefKind> {
285 static void output(const RefKind &value, void *ctxt,
286 llvm::raw_ostream &out) {
287 assert(ctxt != nullptr);
288 ContextInfo *info = reinterpret_cast<ContextInfo*>(ctxt);
Michael J. Spencer64afcb42013-01-23 01:18:43 +0000289 auto relocStr = info->_targetInfo.stringFromRelocKind(value);
290 out << (relocStr ? *relocStr : "<unknown>");
Nick Kledzik6b079f52013-01-05 02:22:35 +0000291 }
292
293 static StringRef input(StringRef scalar, void *ctxt, RefKind &value) {
294 assert(ctxt != nullptr);
295 ContextInfo *info = reinterpret_cast<ContextInfo*>(ctxt);
Michael J. Spencer64afcb42013-01-23 01:18:43 +0000296 auto relocKind = info->_targetInfo.relocKindFromString(scalar);
297 if (!relocKind)
298 return "Invalid relocation kind";
299 value = *relocKind;
Nick Kledzik6b079f52013-01-05 02:22:35 +0000300 return StringRef();
301 }
302};
303
304
305template <>
306struct ScalarEnumerationTraits<lld::File::Kind> {
307 static void enumeration(IO &io, lld::File::Kind &value) {
308 io.enumCase(value, "object", lld::File::kindObject);
309 io.enumCase(value, "shared-library", lld::File::kindSharedLibrary);
310 io.enumCase(value, "static-library", lld::File::kindArchiveLibrary);
311 }
312};
313
314template <>
315struct ScalarEnumerationTraits<lld::Atom::Scope> {
316 static void enumeration(IO &io, lld::Atom::Scope &value) {
317 io.enumCase(value, "global", lld::Atom::scopeGlobal);
318 io.enumCase(value, "hidden", lld::Atom::scopeLinkageUnit);
319 io.enumCase(value, "static", lld::Atom::scopeTranslationUnit);
320 }
321};
322
323template <>
324struct ScalarEnumerationTraits<lld::DefinedAtom::SectionChoice> {
325 static void enumeration(IO &io, lld::DefinedAtom::SectionChoice &value) {
326 io.enumCase(value, "content", lld::DefinedAtom::sectionBasedOnContent);
327 io.enumCase(value, "custom", lld::DefinedAtom::sectionCustomPreferred);
328 io.enumCase(value, "custom-required",
329 lld::DefinedAtom::sectionCustomRequired);
330 }
331};
332
333template <>
Nick Kledzik36293f62013-01-23 22:32:56 +0000334struct ScalarEnumerationTraits<lld::DefinedAtom::SectionPosition> {
335 static void enumeration(IO &io, lld::DefinedAtom::SectionPosition &value) {
336 io.enumCase(value, "start", lld::DefinedAtom::sectionPositionStart);
337 io.enumCase(value, "early", lld::DefinedAtom::sectionPositionEarly);
338 io.enumCase(value, "any", lld::DefinedAtom::sectionPositionAny);
339 io.enumCase(value, "end", lld::DefinedAtom::sectionPositionEnd);
340 }
341};
342
343template <>
Nick Kledzik6b079f52013-01-05 02:22:35 +0000344struct ScalarEnumerationTraits<lld::DefinedAtom::Interposable> {
345 static void enumeration(IO &io, lld::DefinedAtom::Interposable &value) {
346 io.enumCase(value, "no", lld::DefinedAtom::interposeNo);
347 io.enumCase(value, "yes", lld::DefinedAtom::interposeYes);
348 io.enumCase(value, "yes-and-weak",
349 lld::DefinedAtom::interposeYesAndRuntimeWeak);
350 }
351};
352
353template <>
354struct ScalarEnumerationTraits<lld::DefinedAtom::Merge> {
355 static void enumeration(IO &io, lld::DefinedAtom::Merge &value) {
356 io.enumCase(value, "no", lld::DefinedAtom::mergeNo);
357 io.enumCase(value, "as-tentative", lld::DefinedAtom::mergeAsTentative);
358 io.enumCase(value, "as-weak", lld::DefinedAtom::mergeAsWeak);
359 io.enumCase(value, "as-addressed-weak",
360 lld::DefinedAtom::mergeAsWeakAndAddressUsed);
Nick Kledzik233f5372013-01-15 00:17:57 +0000361 io.enumCase(value, "by-content", lld::DefinedAtom::mergeByContent);
Nick Kledzik6b079f52013-01-05 02:22:35 +0000362 }
363};
364
365template <>
366struct ScalarEnumerationTraits<lld::DefinedAtom::DeadStripKind> {
367 static void enumeration(IO &io, lld::DefinedAtom::DeadStripKind &value) {
368 io.enumCase(value, "normal", lld::DefinedAtom::deadStripNormal);
369 io.enumCase(value, "never", lld::DefinedAtom::deadStripNever);
370 io.enumCase(value, "always", lld::DefinedAtom::deadStripAlways);
371 }
372};
373
374template <>
375struct ScalarEnumerationTraits<lld::DefinedAtom::ContentPermissions> {
376 static void enumeration(IO &io, lld::DefinedAtom::ContentPermissions &value) {
Nick Kledzikcc3d2dc2013-01-09 01:17:12 +0000377 io.enumCase(value, "---", lld::DefinedAtom::perm___);
378 io.enumCase(value, "r--", lld::DefinedAtom::permR__);
379 io.enumCase(value, "r-x", lld::DefinedAtom::permR_X);
380 io.enumCase(value, "rw-", lld::DefinedAtom::permRW_);
381 io.enumCase(value, "rwx", lld::DefinedAtom::permRWX);
382 io.enumCase(value, "rw-l", lld::DefinedAtom::permRW_L);
383 io.enumCase(value, "unknown", lld::DefinedAtom::permUnknown);
Nick Kledzik6b079f52013-01-05 02:22:35 +0000384 }
385};
386
387template <>
388struct ScalarEnumerationTraits<lld::DefinedAtom::ContentType> {
389 static void enumeration(IO &io, lld::DefinedAtom::ContentType &value) {
390 io.enumCase(value, "unknown",
391 lld::DefinedAtom::typeUnknown);
392 io.enumCase(value, "code",
393 lld::DefinedAtom::typeCode);
394 io.enumCase(value, "stub",
395 lld::DefinedAtom::typeStub);
396 io.enumCase(value, "constant",
397 lld::DefinedAtom::typeConstant);
398 io.enumCase(value, "data",
399 lld::DefinedAtom::typeData);
400 io.enumCase(value, "zero-fill",
401 lld::DefinedAtom::typeZeroFill);
Nick Kledzikcc3d2dc2013-01-09 01:17:12 +0000402 io.enumCase(value, "const-data",
403 lld::DefinedAtom::typeConstData);
Nick Kledzik6b079f52013-01-05 02:22:35 +0000404 io.enumCase(value, "got",
405 lld::DefinedAtom::typeGOT);
406 io.enumCase(value, "resolver",
407 lld::DefinedAtom::typeResolver);
408 io.enumCase(value, "branch-island",
409 lld::DefinedAtom::typeBranchIsland);
410 io.enumCase(value, "branch-shim",
411 lld::DefinedAtom::typeBranchShim);
412 io.enumCase(value, "stub-helper",
413 lld::DefinedAtom::typeStubHelper);
414 io.enumCase(value, "c-string",
415 lld::DefinedAtom::typeCString);
416 io.enumCase(value, "utf16-string",
417 lld::DefinedAtom::typeUTF16String);
418 io.enumCase(value, "unwind-cfi",
419 lld::DefinedAtom::typeCFI);
420 io.enumCase(value, "unwind-lsda",
421 lld::DefinedAtom::typeLSDA);
422 io.enumCase(value, "const-4-byte",
423 lld::DefinedAtom::typeLiteral4);
424 io.enumCase(value, "const-8-byte",
425 lld::DefinedAtom::typeLiteral8);
426 io.enumCase(value, "const-16-byte",
427 lld::DefinedAtom::typeLiteral16);
428 io.enumCase(value, "lazy-pointer",
429 lld::DefinedAtom::typeLazyPointer);
430 io.enumCase(value, "lazy-dylib-pointer",
431 lld::DefinedAtom::typeLazyDylibPointer);
432 io.enumCase(value, "cfstring",
433 lld::DefinedAtom::typeCFString);
434 io.enumCase(value, "initializer-pointer",
435 lld::DefinedAtom::typeInitializerPtr);
436 io.enumCase(value, "terminator-pointer",
437 lld::DefinedAtom::typeTerminatorPtr);
438 io.enumCase(value, "c-string-pointer",
439 lld::DefinedAtom::typeCStringPtr);
440 io.enumCase(value, "objc-class-pointer",
441 lld::DefinedAtom::typeObjCClassPtr);
442 io.enumCase(value, "objc-category-list",
443 lld::DefinedAtom::typeObjC2CategoryList);
444 io.enumCase(value, "objc-class1",
445 lld::DefinedAtom::typeObjC1Class);
446 io.enumCase(value, "dtraceDOF",
447 lld::DefinedAtom::typeDTraceDOF);
448 io.enumCase(value, "lto-temp",
449 lld::DefinedAtom::typeTempLTO);
450 io.enumCase(value, "compact-unwind",
451 lld::DefinedAtom::typeCompactUnwindInfo);
452 io.enumCase(value, "tlv-thunk",
453 lld::DefinedAtom::typeThunkTLV);
454 io.enumCase(value, "tlv-data",
455 lld::DefinedAtom::typeTLVInitialData);
456 io.enumCase(value, "tlv-zero-fill",
457 lld::DefinedAtom::typeTLVInitialZeroFill);
458 io.enumCase(value, "tlv-initializer-ptr",
459 lld::DefinedAtom::typeTLVInitializerPtr);
Nick Kledzik6b079f52013-01-05 02:22:35 +0000460 }
461};
462
463template <>
464struct ScalarEnumerationTraits<lld::UndefinedAtom::CanBeNull> {
465 static void enumeration(IO &io, lld::UndefinedAtom::CanBeNull &value) {
466 io.enumCase(value, "never", lld::UndefinedAtom::canBeNullNever);
467 io.enumCase(value, "at-runtime", lld::UndefinedAtom::canBeNullAtRuntime);
468 io.enumCase(value, "at-buildtime", lld::UndefinedAtom::canBeNullAtBuildtime);
469 }
470};
471
472
473template <>
474struct ScalarEnumerationTraits<ShlibCanBeNull> {
475 static void enumeration(IO &io, ShlibCanBeNull &value) {
476 io.enumCase(value, "never", false);
477 io.enumCase(value, "at-runtime", true);
478 }
479};
480
481
482
483/// This is a custom formatter for lld::DefinedAtom::Alignment. Values look
484/// like:
485/// 2^3 # 8-byte aligned
486/// 7 mod 2^4 # 16-byte aligned plus 7 bytes
487template<>
488struct ScalarTraits<lld::DefinedAtom::Alignment> {
489 static void output(const lld::DefinedAtom::Alignment &value, void *ctxt,
490 llvm::raw_ostream &out) {
491 if (value.modulus == 0) {
492 out << llvm::format("2^%d", value.powerOf2);
493 }
494 else {
495 out << llvm::format("%d mod 2^%d", value.modulus, value.powerOf2);
496 }
497 }
498
499 static StringRef input(StringRef scalar, void *ctxt,
500 lld::DefinedAtom::Alignment &value) {
501 value.modulus = 0;
502 size_t modStart = scalar.find("mod");
503 if (modStart != StringRef::npos) {
504 StringRef modStr = scalar.slice(0, modStart);
505 modStr = modStr.rtrim();
506 unsigned int modulus;
507 if (modStr.getAsInteger(0, modulus)) {
508 return "malformed alignment modulus";
509 }
510 value.modulus = modulus;
511 scalar = scalar.drop_front(modStart+3);
512 scalar = scalar.ltrim();
513 }
514 if (!scalar.startswith("2^")) {
515 return "malformed alignment";
516 }
517 StringRef powerStr = scalar.drop_front(2);
518 unsigned int power;
519 if (powerStr.getAsInteger(0, power)) {
520 return "malformed alignment power";
521 }
522 value.powerOf2 = power;
523 if (value.modulus > (1<<value.powerOf2)) {
524 return "malformed alignment, modulus too large for power";
525 }
526 return StringRef(); // returning empty string means success
527 }
528};
529
530
531
532
533template <>
534struct ScalarEnumerationTraits<FileKinds> {
535 static void enumeration(IO &io, FileKinds &value) {
536 io.enumCase(value, "object", fileKindObjectAtoms);
537 io.enumCase(value, "archive", fileKindArchive);
538 io.enumCase(value, "object-elf", fileKindObjectELF);
539 io.enumCase(value, "object-mach-o", fileKindObjectMachO);
540 }
541};
542
543template <>
544struct MappingTraits<ArchMember> {
545 static void mapping(IO &io, ArchMember &member) {
546 io.mapOptional("kind", member._kind, fileKindObjectAtoms);
547 io.mapOptional("name", member._name);
548 io.mapRequired("content", member._content);
549 }
550};
551
Nick Kledzik6b079f52013-01-05 02:22:35 +0000552
553
554// Declare that an AtomList is a yaml sequence.
555template<typename T>
556struct SequenceTraits<AtomList<T>> {
557 static size_t size(IO &io, AtomList<T> &seq) {
558 return seq._atoms.size();
559 }
560 static const T *&element(IO &io, AtomList<T> &seq, size_t index) {
561 if (index >= seq._atoms.size())
562 seq._atoms.resize(index+1);
563 return seq._atoms[index];
564 }
565};
566
567// Used to allow DefinedAtom content bytes to be a flow sequence of
568// two-digit hex numbers without the leading 0x (e.g. FF, 04, 0A)
569template<>
570struct ScalarTraits<ImplicitHex8> {
571 static void output(const ImplicitHex8 &val, void*, llvm::raw_ostream &out) {
572 uint8_t num = val;
573 out << llvm::format("%02X", num);
574 }
575
576 static llvm::StringRef input(llvm::StringRef str, void*, ImplicitHex8 &val) {
577 unsigned long long n;
578 if (getAsUnsignedInteger(str, 16, n))
579 return "invalid two-digit-hex number";
580 if (n > 0xFF)
581 return "out of range two-digit-hex number";
582 val = n;
583 return StringRef(); // returning empty string means success
584 }
585};
586
Nick Kledzik6b079f52013-01-05 02:22:35 +0000587
588// YAML conversion for std::vector<const lld::File*>
589template<>
590struct DocumentListTraits< std::vector<const lld::File*> > {
591 static size_t size(IO &io, std::vector<const lld::File*> &seq) {
592 return seq.size();
593 }
594 static const lld::File *&element(IO &io, std::vector<const lld::File*> &seq,
595 size_t index) {
596 if (index >= seq.size())
597 seq.resize(index+1);
598 return seq[index];
599 }
600};
601
602
603// YAML conversion for const lld::File*
604template <>
605struct MappingTraits<const lld::File*> {
Shankar Easwaran3256d4f2013-01-25 07:39:18 +0000606
607 class NormArchiveFile : public lld::ArchiveLibraryFile {
608 public:
609 NormArchiveFile(IO &io)
610 : ArchiveLibraryFile(((ContextInfo *)io.getContext())->_targetInfo,
611 ""),
612 _path() {
613 }
614 NormArchiveFile(IO &io, const lld::File *file)
615 : ArchiveLibraryFile(((ContextInfo *)io.getContext())->_targetInfo,
616 file->path()),
617 _path(file->path()) {
Nick Kledzik6b079f52013-01-05 02:22:35 +0000618 // If we want to support writing archives, this constructor would
619 // need to populate _members.
Shankar Easwaran3256d4f2013-01-25 07:39:18 +0000620 }
Nick Kledzik6b079f52013-01-05 02:22:35 +0000621
622 const lld::File *denormalize(IO &io) {
623 return this;
624 }
Michael J. Spencer57752dc2013-01-12 02:45:54 +0000625
Nick Kledzik36293f62013-01-23 22:32:56 +0000626 virtual void setOrdinalAndIncrement(uint64_t &ordinal) const {
627 _ordinal = ordinal++;
628 // Assign sequential ordinals to member files
629 for (const ArchMember &member : _members) {
630 member._content->setOrdinalAndIncrement(ordinal);
631 }
632 }
633
Nick Kledzik6b079f52013-01-05 02:22:35 +0000634 virtual const atom_collection<lld::DefinedAtom> &defined() const {
635 return _noDefinedAtoms;
636 }
637 virtual const atom_collection<lld::UndefinedAtom> &undefined() const {
638 return _noUndefinedAtoms;
639 }
640 virtual const atom_collection<lld::SharedLibraryAtom> &sharedLibrary()const{
641 return _noSharedLibaryAtoms;
642 }
643 virtual const atom_collection<lld::AbsoluteAtom> &absolute() const {
644 return _noAbsoluteAtoms;
645 }
646 virtual const File *find(StringRef name, bool dataSymbolOnly) const {
647 for (const ArchMember &member : _members) {
648 for (const lld::DefinedAtom *atom : member._content->defined() ) {
649 if (name == atom->name()) {
650 if (!dataSymbolOnly)
651 return member._content;
652 switch (atom->contentType()) {
653 case lld::DefinedAtom::typeData:
654 case lld::DefinedAtom::typeZeroFill:
655 return member._content;
656 default:
657 break;
658 }
659 }
660 }
661 }
662 return nullptr;
663 }
664
665 StringRef _path;
666 std::vector<ArchMember> _members;
667 };
Shankar Easwaran3256d4f2013-01-25 07:39:18 +0000668
669 class NormalizedFile : public lld::File {
670 public:
671 NormalizedFile(IO &io) : File(""), _IO(io), _rnb(nullptr) {}
672 NormalizedFile(IO &io, const lld::File *file)
673 : File(file->path()), _IO(io), _rnb(new RefNameBuilder(*file)),
674 _path(file->path()) {
675 for (const lld::DefinedAtom *a : file->defined())
676 _definedAtoms.push_back(a);
677 for (const lld::UndefinedAtom *a : file->undefined())
Nick Kledzik6b079f52013-01-05 02:22:35 +0000678 _undefinedAtoms.push_back(a);
679 for (const lld::SharedLibraryAtom *a : file->sharedLibrary())
680 _sharedLibraryAtoms.push_back(a);
681 for (const lld::AbsoluteAtom *a : file->absolute())
682 _absoluteAtoms.push_back(a);
683 }
684 const lld::File *denormalize(IO &io);
Michael J. Spencer57752dc2013-01-12 02:45:54 +0000685
Nick Kledzik6b079f52013-01-05 02:22:35 +0000686 virtual const atom_collection<lld::DefinedAtom> &defined() const {
687 return _definedAtoms;
688 }
689 virtual const atom_collection<lld::UndefinedAtom> &undefined() const {
690 return _undefinedAtoms;
691 }
692 virtual const atom_collection<lld::SharedLibraryAtom> &sharedLibrary()const{
693 return _sharedLibraryAtoms;
694 }
Shankar Easwaran3256d4f2013-01-25 07:39:18 +0000695 virtual const atom_collection<lld::AbsoluteAtom> &absolute() const {
696 return _absoluteAtoms;
697 }
698
699 virtual const TargetInfo &getTargetInfo() const {
700 return ((ContextInfo *)_IO.getContext())->_targetInfo;
701 }
702
703 // Allocate a new copy of this string and keep track of allocations
704 // in _stringCopies, so they can be freed when File is destroyed.
Nick Kledzik6b079f52013-01-05 02:22:35 +0000705 StringRef copyString(StringRef str) {
706 // We want _stringCopies to own the string memory so it is deallocated
707 // when the File object is destroyed. But we need a StringRef that
708 // points into that memory.
709 std::unique_ptr<char> s = std::unique_ptr<char>(new char[str.size()]);
710 memcpy(s.get(), str.data(), str.size());
711 llvm::StringRef r = llvm::StringRef(s.get(), str.size());
712 _stringCopies.push_back(std::move(s));
Shankar Easwaran3256d4f2013-01-25 07:39:18 +0000713 return r;
714 }
715
716 IO &_IO;
717 RefNameBuilder *_rnb;
718 StringRef _path;
719 AtomList<lld::DefinedAtom> _definedAtoms;
Nick Kledzik6b079f52013-01-05 02:22:35 +0000720 AtomList<lld::UndefinedAtom> _undefinedAtoms;
721 AtomList<lld::SharedLibraryAtom> _sharedLibraryAtoms;
722 AtomList<lld::AbsoluteAtom> _absoluteAtoms;
723 std::vector<std::unique_ptr<char>> _stringCopies;
724 };
725
726
727 static void mapping(IO &io, const lld::File *&file) {
728 // We only support writing atom based YAML
729 FileKinds kind = fileKindObjectAtoms;
730 // If reading, peek ahead to see what kind of file this is.
731 io.mapOptional("kind", kind, fileKindObjectAtoms);
732 //
733 switch (kind) {
734 case fileKindObjectAtoms:
735 mappingAtoms(io, file);
736 break;
737 case fileKindArchive:
738 mappingArchive(io, file);
739 break;
740 case fileKindObjectELF:
741 case fileKindObjectMachO:
742 // Eventually we will have an external function to call, similar
743 // to mappingAtoms() and mappingArchive() but implememented
744 // with coresponding file format code.
Nick Kledzik6b079f52013-01-05 02:22:35 +0000745 llvm_unreachable("section based YAML not supported yet");
746 }
747 }
748
749 static void mappingAtoms(IO &io, const lld::File *&file) {
750 MappingNormalizationHeap<NormalizedFile, const lld::File*> keys(io, file);
751 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
752 assert(info != nullptr);
753 info->_currentFile = keys.operator->();
754
755 io.mapOptional("path", keys->_path);
756 io.mapOptional("defined-atoms", keys->_definedAtoms);
757 io.mapOptional("undefined-atoms", keys->_undefinedAtoms);
758 io.mapOptional("shared-library-atoms", keys->_sharedLibraryAtoms);
759 io.mapOptional("absolute-atoms", keys->_absoluteAtoms);
760 }
761
762 static void mappingArchive(IO &io, const lld::File *&file) {
763 MappingNormalizationHeap<NormArchiveFile, const lld::File*> keys(io, file);
764
765 io.mapOptional("path", keys->_path);
766 io.mapOptional("members", keys->_members);
767 }
768
769};
770
771
772
773// YAML conversion for const lld::Reference*
774template <>
775struct MappingTraits<const lld::Reference*> {
776
777 class NormalizedReference : public lld::Reference {
778 public:
779 NormalizedReference(IO &io)
780 : _target(nullptr), _targetName(), _offset(0), _addend(0) , _kind(0) {
781 }
782 NormalizedReference(IO &io, const lld::Reference *ref)
783 : _target(nullptr),
784 _targetName(targetName(io, ref)),
785 _offset(ref->offsetInAtom()),
786 _addend(ref->addend()),
787 _kind(ref->kind()) {
788 }
789 const lld::Reference *denormalize(IO &io) {
790 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
791 assert(info != nullptr);
792 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
793 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
794 if (!_targetName.empty())
795 _targetName = f->copyString(_targetName);
796 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
797 << "created Reference to name: '" << _targetName
798 << "' (" << (void*)_targetName.data() << ", "
799 << _targetName.size() << ")\n");
800 return this;
801 }
802 void bind(const RefNameResolver&);
803 static StringRef targetName(IO &io, const lld::Reference *ref);
804
805 virtual uint64_t offsetInAtom() const { return _offset; }
806 virtual Kind kind() const { return _kind; }
807 virtual const lld::Atom *target() const { return _target; }
808 virtual Addend addend() const { return _addend; }
809 virtual void setKind(Kind k) { _kind = k; }
810 virtual void setAddend(Addend a) { _addend = a; }
811 virtual void setTarget(const lld::Atom *a) { _target = a; }
812
813 const lld::Atom *_target;
814 StringRef _targetName;
815 uint32_t _offset;
816 Addend _addend;
817 RefKind _kind;
818 };
819
820
821 static void mapping(IO &io, const lld::Reference *&ref) {
822 MappingNormalizationHeap<NormalizedReference,
823 const lld::Reference*> keys(io, ref);
824
825 io.mapRequired("kind", keys->_kind);
826 io.mapOptional("offset", keys->_offset);
827 io.mapOptional("target", keys->_targetName);
828 io.mapOptional("addend", keys->_addend, (lld::Reference::Addend)0);
829 }
830};
831
Nick Kledzik6b079f52013-01-05 02:22:35 +0000832
833
834// YAML conversion for const lld::DefinedAtom*
835template <>
836struct MappingTraits<const lld::DefinedAtom*> {
837
838 class NormalizedAtom : public lld::DefinedAtom {
839 public:
840 NormalizedAtom(IO &io)
841 : _file(fileFromContext(io)), _name(), _refName(),
842 _alignment(0), _content(), _references() {
Nick Kledzik36293f62013-01-23 22:32:56 +0000843 static uint32_t ordinalCounter = 1;
844 _ordinal = ordinalCounter++;
Nick Kledzik6b079f52013-01-05 02:22:35 +0000845 }
846 NormalizedAtom(IO &io, const lld::DefinedAtom *atom)
847 : _file(fileFromContext(io)),
848 _name(atom->name()),
849 _refName(),
850 _scope(atom->scope()),
851 _interpose(atom->interposable()),
852 _merge(atom->merge()),
853 _contentType(atom->contentType()),
854 _alignment(atom->alignment()),
855 _sectionChoice(atom->sectionChoice()),
Nick Kledzik36293f62013-01-23 22:32:56 +0000856 _sectionPosition(atom->sectionPosition()),
Nick Kledzik6b079f52013-01-05 02:22:35 +0000857 _deadStrip(atom->deadStrip()),
858 _permissions(atom->permissions()),
859 _size(atom->size()),
860 _sectionName(atom->customSectionName()) {
861 for ( const lld::Reference *r : *atom )
862 _references.push_back(r);
863 ArrayRef<uint8_t> cont = atom->rawContent();
864 _content.reserve(cont.size());
865 for (uint8_t x : cont)
866 _content.push_back(x);
867 }
868 const lld::DefinedAtom *denormalize(IO &io) {
869 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
870 assert(info != nullptr);
871 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
872 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
873 if ( !_name.empty() )
874 _name = f->copyString(_name);
875 if ( !_refName.empty() )
876 _refName = f->copyString(_refName);
877 if ( !_sectionName.empty() )
878 _sectionName = f->copyString(_sectionName);
879 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
880 << "created DefinedAtom named: '" << _name
881 << "' (" << (void*)_name.data() << ", "
882 << _name.size() << ")\n");
883 return this;
884 }
885 void bind(const RefNameResolver&);
886 // Extract current File object from YAML I/O parsing context
887 const lld::File &fileFromContext(IO &io) {
888 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
889 assert(info != nullptr);
890 assert(info->_currentFile != nullptr);
891 return *info->_currentFile;
892 }
893
894 virtual const lld::File &file() const { return _file; }
895 virtual StringRef name() const { return _name; }
896 virtual uint64_t size() const { return _size; }
897 virtual Scope scope() const { return _scope; }
898 virtual Interposable interposable() const { return _interpose; }
899 virtual Merge merge() const { return _merge; }
900 virtual ContentType contentType() const { return _contentType; }
901 virtual Alignment alignment() const { return _alignment; }
902 virtual SectionChoice sectionChoice() const { return _sectionChoice; }
903 virtual StringRef customSectionName() const { return _sectionName;}
Nick Kledzik36293f62013-01-23 22:32:56 +0000904 virtual SectionPosition sectionPosition() const{return _sectionPosition;}
Nick Kledzik6b079f52013-01-05 02:22:35 +0000905 virtual DeadStripKind deadStrip() const { return _deadStrip; }
906 virtual ContentPermissions permissions() const { return _permissions; }
907 virtual bool isThumb() const { return false; }
908 virtual bool isAlias() const { return false; }
Michael J. Spencer74ba7222013-01-13 01:09:39 +0000909 ArrayRef<uint8_t> rawContent() const {
910 return ArrayRef<uint8_t>(
911 reinterpret_cast<const uint8_t *>(_content.data()), _content.size());
912 }
913
Nick Kledzik36293f62013-01-23 22:32:56 +0000914 virtual uint64_t ordinal() const { return _ordinal; }
Nick Kledzik6b079f52013-01-05 02:22:35 +0000915
916 reference_iterator begin() const {
917 uintptr_t index = 0;
918 const void *it = reinterpret_cast<const void*>(index);
919 return reference_iterator(*this, it);
920 }
921 reference_iterator end() const {
922 uintptr_t index = _references.size();
923 const void *it = reinterpret_cast<const void*>(index);
924 return reference_iterator(*this, it);
925 }
926 const lld::Reference *derefIterator(const void *it) const {
927 uintptr_t index = reinterpret_cast<uintptr_t>(it);
928 assert(index < _references.size());
929 return _references[index];
930 }
931 void incrementIterator(const void *&it) const {
932 uintptr_t index = reinterpret_cast<uintptr_t>(it);
933 ++index;
934 it = reinterpret_cast<const void*>(index);
935 }
936
937 const lld::File &_file;
938 StringRef _name;
939 StringRef _refName;
940 Scope _scope;
941 Interposable _interpose;
942 Merge _merge;
943 ContentType _contentType;
944 Alignment _alignment;
945 SectionChoice _sectionChoice;
Nick Kledzik36293f62013-01-23 22:32:56 +0000946 SectionPosition _sectionPosition;
Nick Kledzik6b079f52013-01-05 02:22:35 +0000947 DeadStripKind _deadStrip;
948 ContentPermissions _permissions;
Nick Kledzik36293f62013-01-23 22:32:56 +0000949 uint32_t _ordinal;
Nick Kledzik6b079f52013-01-05 02:22:35 +0000950 std::vector<ImplicitHex8> _content;
951 uint64_t _size;
952 StringRef _sectionName;
953 std::vector<const lld::Reference*> _references;
954 };
955
956 static void mapping(IO &io, const lld::DefinedAtom *&atom) {
957 MappingNormalizationHeap<NormalizedAtom,
958 const lld::DefinedAtom*> keys(io, atom);
959 if ( io.outputting() ) {
960 // If writing YAML, check if atom needs a ref-name.
961 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
962 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
963 assert(info != nullptr);
964 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
965 assert(f);
966 assert(f->_rnb);
967 if ( f->_rnb->hasRefName(atom) ) {
968 keys->_refName = f->_rnb->refName(atom);
969 }
970 }
971
972 io.mapOptional("name", keys->_name,
973 StringRef());
974 io.mapOptional("ref-name", keys->_refName,
975 StringRef());
976 io.mapOptional("scope", keys->_scope,
977 lld::DefinedAtom::scopeTranslationUnit);
978 io.mapOptional("type", keys->_contentType,
979 lld::DefinedAtom::typeCode);
980 io.mapOptional("content", keys->_content);
981 io.mapOptional("size", keys->_size,
982 (uint64_t)keys->_content.size());
983 io.mapOptional("interposable", keys->_interpose,
984 lld::DefinedAtom::interposeNo);
985 io.mapOptional("merge", keys->_merge,
986 lld::DefinedAtom::mergeNo);
987 io.mapOptional("alignment", keys->_alignment,
988 lld::DefinedAtom::Alignment(0));
989 io.mapOptional("section-choice", keys->_sectionChoice,
990 lld::DefinedAtom::sectionBasedOnContent);
991 io.mapOptional("section-name", keys->_sectionName,
992 StringRef());
Nick Kledzik36293f62013-01-23 22:32:56 +0000993 io.mapOptional("section-position",keys->_sectionPosition,
994 lld::DefinedAtom::sectionPositionAny);
Nick Kledzik6b079f52013-01-05 02:22:35 +0000995 io.mapOptional("dead-strip", keys->_deadStrip,
996 lld::DefinedAtom::deadStripNormal);
Nick Kledzikcc3d2dc2013-01-09 01:17:12 +0000997 // default permissions based on content type
998 io.mapOptional("permissions", keys->_permissions,
999 lld::DefinedAtom::permissions(
1000 keys->_contentType));
Nick Kledzik8a3052e2013-01-08 21:12:13 +00001001 io.mapOptional("references", keys->_references);
Nick Kledzik6b079f52013-01-05 02:22:35 +00001002 }
1003};
1004
1005
1006
1007
Nick Kledzik6b079f52013-01-05 02:22:35 +00001008// YAML conversion for const lld::UndefinedAtom*
1009template <>
1010struct MappingTraits<const lld::UndefinedAtom*> {
1011
1012 class NormalizedAtom : public lld::UndefinedAtom {
1013 public:
1014 NormalizedAtom(IO &io)
1015 : _file(fileFromContext(io)), _name(), _canBeNull(canBeNullNever) {
1016 }
1017 NormalizedAtom(IO &io, const lld::UndefinedAtom *atom)
1018 : _file(fileFromContext(io)),
1019 _name(atom->name()),
1020 _canBeNull(atom->canBeNull()) {
1021 }
1022 const lld::UndefinedAtom *denormalize(IO &io) {
1023 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1024 assert(info != nullptr);
1025 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
1026 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
1027 if ( !_name.empty() )
1028 _name = f->copyString(_name);
1029
1030 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
1031 << "created UndefinedAtom named: '" << _name
1032 << "' (" << (void*)_name.data() << ", "
1033 << _name.size() << ")\n");
1034 return this;
1035 }
1036 // Extract current File object from YAML I/O parsing context
1037 const lld::File &fileFromContext(IO &io) {
1038 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1039 assert(info != nullptr);
1040 assert(info->_currentFile != nullptr);
1041 return *info->_currentFile;
1042 }
1043
1044 virtual const lld::File &file() const { return _file; }
1045 virtual StringRef name() const { return _name; }
1046 virtual CanBeNull canBeNull() const { return _canBeNull; }
1047
1048 const lld::File &_file;
1049 StringRef _name;
1050 CanBeNull _canBeNull;
1051 };
1052
1053
1054 static void mapping(IO &io, const lld::UndefinedAtom* &atom) {
1055 MappingNormalizationHeap<NormalizedAtom,
1056 const lld::UndefinedAtom*> keys(io, atom);
1057
1058 io.mapRequired("name", keys->_name);
1059 io.mapOptional("can-be-null", keys->_canBeNull,
1060 lld::UndefinedAtom::canBeNullNever);
1061 }
1062};
1063
1064
Nick Kledzik36293f62013-01-23 22:32:56 +00001065
Nick Kledzik6b079f52013-01-05 02:22:35 +00001066// YAML conversion for const lld::SharedLibraryAtom*
1067template <>
1068struct MappingTraits<const lld::SharedLibraryAtom*> {
1069
1070 class NormalizedAtom : public lld::SharedLibraryAtom {
1071 public:
1072 NormalizedAtom(IO &io)
1073 : _file(fileFromContext(io)), _name(), _loadName(), _canBeNull(false) {
1074 }
1075 NormalizedAtom(IO &io, const lld::SharedLibraryAtom *atom)
1076 : _file(fileFromContext(io)),
1077 _name(atom->name()),
1078 _loadName(atom->loadName()),
1079 _canBeNull(atom->canBeNullAtRuntime()) {
1080 }
1081 const lld::SharedLibraryAtom *denormalize(IO &io) {
1082 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1083 assert(info != nullptr);
1084 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
1085 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
1086 if ( !_name.empty() )
1087 _name = f->copyString(_name);
1088 if ( !_loadName.empty() )
1089 _loadName = f->copyString(_loadName);
1090
1091 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
1092 << "created SharedLibraryAtom named: '" << _name
1093 << "' (" << (void*)_name.data() << ", "
1094 << _name.size() << ")\n");
1095 return this;
1096 }
1097 // Extract current File object from YAML I/O parsing context
1098 const lld::File &fileFromContext(IO &io) {
1099 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1100 assert(info != nullptr);
1101 assert(info->_currentFile != nullptr);
1102 return *info->_currentFile;
1103 }
1104
1105 virtual const lld::File &file() const { return _file; }
1106 virtual StringRef name() const { return _name; }
1107 virtual StringRef loadName() const { return _loadName;}
1108 virtual bool canBeNullAtRuntime() const { return _canBeNull; }
1109
1110 const lld::File &_file;
1111 StringRef _name;
1112 StringRef _loadName;
1113 ShlibCanBeNull _canBeNull;
1114 };
1115
1116
1117 static void mapping(IO &io, const lld::SharedLibraryAtom *&atom) {
1118
1119 MappingNormalizationHeap<NormalizedAtom,
1120 const lld::SharedLibraryAtom*> keys(io, atom);
1121
1122 io.mapRequired("name", keys->_name);
1123 io.mapOptional("load-name", keys->_loadName);
1124 io.mapOptional("can-be-null", keys->_canBeNull,
1125 (ShlibCanBeNull)false);
1126 }
1127};
1128
1129
1130// YAML conversion for const lld::AbsoluteAtom*
1131template <>
1132struct MappingTraits<const lld::AbsoluteAtom*> {
1133
1134 class NormalizedAtom : public lld::AbsoluteAtom {
1135 public:
1136 NormalizedAtom(IO &io)
1137 : _file(fileFromContext(io)), _name(), _scope(), _value(0) {
1138 }
1139 NormalizedAtom(IO &io, const lld::AbsoluteAtom *atom)
1140 : _file(fileFromContext(io)),
1141 _name(atom->name()),
1142 _scope(atom->scope()),
1143 _value(atom->value()) {
1144 }
1145 const lld::AbsoluteAtom *denormalize(IO &io) {
1146 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1147 assert(info != nullptr);
1148 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
1149 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
1150 if ( !_name.empty() )
1151 _name = f->copyString(_name);
1152
1153 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
1154 << "created AbsoluteAtom named: '" << _name
1155 << "' (" << (void*)_name.data() << ", "
1156 << _name.size() << ")\n");
1157 return this;
1158 }
1159 // Extract current File object from YAML I/O parsing context
1160 const lld::File &fileFromContext(IO &io) {
1161 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1162 assert(info != nullptr);
1163 assert(info->_currentFile != nullptr);
1164 return *info->_currentFile;
1165 }
1166
1167 virtual const lld::File &file() const { return _file; }
1168 virtual StringRef name() const { return _name; }
1169 virtual uint64_t value() const { return _value; }
1170 virtual Scope scope() const { return _scope; }
1171
1172 const lld::File &_file;
1173 StringRef _name;
1174 StringRef _refName;
1175 Scope _scope;
1176 Hex64 _value;
1177 };
1178
1179
1180 static void mapping(IO &io, const lld::AbsoluteAtom *&atom) {
1181 MappingNormalizationHeap<NormalizedAtom,
1182 const lld::AbsoluteAtom*> keys(io, atom);
1183
1184 if ( io.outputting() ) {
1185 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
1186 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1187 assert(info != nullptr);
1188 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
1189 assert(f);
1190 assert(f->_rnb);
1191 if ( f->_rnb->hasRefName(atom) ) {
1192 keys->_refName = f->_rnb->refName(atom);
1193 }
1194 }
1195
1196 io.mapRequired("name", keys->_name);
1197 io.mapOptional("ref-name", keys->_refName, StringRef());
1198 io.mapOptional("scope", keys->_scope);
1199 io.mapRequired("value", keys->_value);
1200 }
1201};
1202
Nick Kledzikbd491982013-01-08 23:51:03 +00001203} // namespace llvm
1204} // namespace yaml
1205
Nick Kledzik6b079f52013-01-05 02:22:35 +00001206
1207RefNameResolver::RefNameResolver(const lld::File *file, IO &io) : _io(io) {
1208 typedef MappingTraits<const lld::DefinedAtom*>::NormalizedAtom NormalizedAtom;
1209 for (const lld::DefinedAtom *a : file->defined() ) {
1210 NormalizedAtom *na = (NormalizedAtom*)a;
1211 if ( na->_refName.empty() )
1212 add(na->_name, a);
1213 else
1214 add(na->_refName, a);
1215 }
1216
1217 for (const lld::UndefinedAtom *a : file->undefined() )
1218 add(a->name(), a);
1219
1220 for (const lld::SharedLibraryAtom *a : file->sharedLibrary() )
1221 add(a->name(), a);
1222
1223 typedef MappingTraits<const lld::AbsoluteAtom*>::NormalizedAtom NormAbsAtom;
1224 for (const lld::AbsoluteAtom *a : file->absolute() ) {
1225 NormAbsAtom *na = (NormAbsAtom*)a;
1226 if ( na->_refName.empty() )
1227 add(na->_name, a);
1228 else
1229 add(na->_refName, a);
1230 }
1231}
1232
1233
Nick Kledzikbd491982013-01-08 23:51:03 +00001234
1235inline
1236const lld::File*
1237MappingTraits<const lld::File*>::NormalizedFile::denormalize(IO &io) {
1238 typedef MappingTraits<const lld::DefinedAtom*>::NormalizedAtom NormalizedAtom;
1239
1240 RefNameResolver nameResolver(this, io);
1241 // Now that all atoms are parsed, references can be bound.
1242 for (const lld::DefinedAtom *a : this->defined() ) {
1243 NormalizedAtom *normAtom = (NormalizedAtom*)a;
1244 normAtom->bind(nameResolver);
1245 }
1246 return this;
1247}
1248
1249inline
1250void MappingTraits<const lld::DefinedAtom*>::
1251 NormalizedAtom::bind(const RefNameResolver &resolver) {
1252 typedef MappingTraits<const lld::Reference*>::NormalizedReference
1253 NormalizedReference;
1254 for (const lld::Reference *ref : _references) {
1255 NormalizedReference *normRef = (NormalizedReference*)ref;
1256 normRef->bind(resolver);
1257 }
1258}
1259
1260inline
1261void MappingTraits<const lld::Reference*>::
1262 NormalizedReference::bind(const RefNameResolver &resolver) {
1263 _target = resolver.lookup(_targetName);
1264}
1265
1266
Nick Kledzik6b079f52013-01-05 02:22:35 +00001267inline
1268llvm::StringRef MappingTraits<const lld::Reference*>::NormalizedReference::
1269 targetName(IO &io, const lld::Reference *ref) {
1270 if ( ref->target() == nullptr )
1271 return llvm::StringRef();
1272 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
1273 assert(info != nullptr);
1274 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
1275 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
1276 RefNameBuilder *rnb = f->_rnb;
1277 if ( rnb->hasRefName(ref->target()) )
1278 return rnb->refName(ref->target());
1279 return ref->target()->name();
1280}
1281
1282
1283
1284namespace lld {
1285namespace yaml {
1286
1287class Writer : public lld::Writer {
1288public:
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001289 Writer(const TargetInfo &ti) : _targetInfo(ti) {}
Nick Kledzik6b079f52013-01-05 02:22:35 +00001290
1291 virtual error_code writeFile(const lld::File &file, StringRef outPath) {
1292 // Create stream to path.
1293 std::string errorInfo;
1294 llvm::raw_fd_ostream out(outPath.data(), errorInfo);
1295 if (!errorInfo.empty())
1296 return llvm::make_error_code(llvm::errc::no_such_file_or_directory);
1297
1298 // Create yaml Output writer, using yaml options for context.
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001299 ContextInfo context(_targetInfo);
Nick Kledzik6b079f52013-01-05 02:22:35 +00001300 llvm::yaml::Output yout(out, &context);
1301
1302 // Write yaml output.
1303 const lld::File *fileRef = &file;
1304 yout << fileRef;
1305
1306 return error_code::success();
1307 }
1308
Nick Kledzik6b079f52013-01-05 02:22:35 +00001309private:
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001310 const TargetInfo &_targetInfo;
Nick Kledzik6b079f52013-01-05 02:22:35 +00001311};
1312
Nick Kledzik6b079f52013-01-05 02:22:35 +00001313class ReaderYAML : public Reader {
1314public:
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001315 ReaderYAML(const TargetInfo &ti) : Reader(ti) {}
Nick Kledzik6b079f52013-01-05 02:22:35 +00001316
1317 error_code parseFile(std::unique_ptr<MemoryBuffer> mb,
1318 std::vector<std::unique_ptr<File>> &result) {
1319 // Note: we do not take ownership of the MemoryBuffer. That is
1320 // because yaml may produce multiple File objects, so there is no
1321 // *one* File to take ownership. Therefore, the yaml File objects
1322 // produced must make copies of all strings that come from YAML I/O.
1323 // Otherwise the strings will become invalid when this MemoryBuffer
1324 // is deallocated.
1325
1326 // Create YAML Input parser.
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001327 ContextInfo context(_targetInfo);
Nick Kledzik6b079f52013-01-05 02:22:35 +00001328 llvm::yaml::Input yin(mb->getBuffer(), &context);
1329
1330 // Fill vector with File objects created by parsing yaml.
1331 std::vector<const lld::File*> createdFiles;
1332 yin >> createdFiles;
1333
1334 // Quit now if there were parsing errors.
1335 if ( yin.error() )
1336 return make_error_code(lld::yaml_reader_error::illegal_value);
1337
1338 for (const File *file : createdFiles) {
1339 // Note: parseFile() should return vector of *const* File
1340 File *f = const_cast<File*>(file);
1341 result.emplace_back(f);
1342 }
1343 return make_error_code(lld::yaml_reader_error::success);
1344 }
Nick Kledzik6b079f52013-01-05 02:22:35 +00001345};
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001346} // end namespace yaml
Nick Kledzik6b079f52013-01-05 02:22:35 +00001347
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001348std::unique_ptr<Writer> createWriterYAML(const TargetInfo &ti) {
1349 return std::unique_ptr<Writer>(new lld::yaml::Writer(ti));
Nick Kledzik6b079f52013-01-05 02:22:35 +00001350}
1351
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001352std::unique_ptr<Reader> createReaderYAML(const TargetInfo &ti) {
1353 return std::unique_ptr<Reader>(new lld::yaml::ReaderYAML(ti));
Nick Kledzik6b079f52013-01-05 02:22:35 +00001354}
Michael J. Spencer64afcb42013-01-23 01:18:43 +00001355} // end namespace lld