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