blob: 44234a135e4714239c6a316594ca0e57d633a529 [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) {
369 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 }
376};
377
378template <>
379struct ScalarEnumerationTraits<lld::DefinedAtom::ContentType> {
380 static void enumeration(IO &io, lld::DefinedAtom::ContentType &value) {
381 io.enumCase(value, "unknown",
382 lld::DefinedAtom::typeUnknown);
383 io.enumCase(value, "code",
384 lld::DefinedAtom::typeCode);
385 io.enumCase(value, "stub",
386 lld::DefinedAtom::typeStub);
387 io.enumCase(value, "constant",
388 lld::DefinedAtom::typeConstant);
389 io.enumCase(value, "data",
390 lld::DefinedAtom::typeData);
391 io.enumCase(value, "zero-fill",
392 lld::DefinedAtom::typeZeroFill);
393 io.enumCase(value, "got",
394 lld::DefinedAtom::typeGOT);
395 io.enumCase(value, "resolver",
396 lld::DefinedAtom::typeResolver);
397 io.enumCase(value, "branch-island",
398 lld::DefinedAtom::typeBranchIsland);
399 io.enumCase(value, "branch-shim",
400 lld::DefinedAtom::typeBranchShim);
401 io.enumCase(value, "stub-helper",
402 lld::DefinedAtom::typeStubHelper);
403 io.enumCase(value, "c-string",
404 lld::DefinedAtom::typeCString);
405 io.enumCase(value, "utf16-string",
406 lld::DefinedAtom::typeUTF16String);
407 io.enumCase(value, "unwind-cfi",
408 lld::DefinedAtom::typeCFI);
409 io.enumCase(value, "unwind-lsda",
410 lld::DefinedAtom::typeLSDA);
411 io.enumCase(value, "const-4-byte",
412 lld::DefinedAtom::typeLiteral4);
413 io.enumCase(value, "const-8-byte",
414 lld::DefinedAtom::typeLiteral8);
415 io.enumCase(value, "const-16-byte",
416 lld::DefinedAtom::typeLiteral16);
417 io.enumCase(value, "lazy-pointer",
418 lld::DefinedAtom::typeLazyPointer);
419 io.enumCase(value, "lazy-dylib-pointer",
420 lld::DefinedAtom::typeLazyDylibPointer);
421 io.enumCase(value, "cfstring",
422 lld::DefinedAtom::typeCFString);
423 io.enumCase(value, "initializer-pointer",
424 lld::DefinedAtom::typeInitializerPtr);
425 io.enumCase(value, "terminator-pointer",
426 lld::DefinedAtom::typeTerminatorPtr);
427 io.enumCase(value, "c-string-pointer",
428 lld::DefinedAtom::typeCStringPtr);
429 io.enumCase(value, "objc-class-pointer",
430 lld::DefinedAtom::typeObjCClassPtr);
431 io.enumCase(value, "objc-category-list",
432 lld::DefinedAtom::typeObjC2CategoryList);
433 io.enumCase(value, "objc-class1",
434 lld::DefinedAtom::typeObjC1Class);
435 io.enumCase(value, "dtraceDOF",
436 lld::DefinedAtom::typeDTraceDOF);
437 io.enumCase(value, "lto-temp",
438 lld::DefinedAtom::typeTempLTO);
439 io.enumCase(value, "compact-unwind",
440 lld::DefinedAtom::typeCompactUnwindInfo);
441 io.enumCase(value, "tlv-thunk",
442 lld::DefinedAtom::typeThunkTLV);
443 io.enumCase(value, "tlv-data",
444 lld::DefinedAtom::typeTLVInitialData);
445 io.enumCase(value, "tlv-zero-fill",
446 lld::DefinedAtom::typeTLVInitialZeroFill);
447 io.enumCase(value, "tlv-initializer-ptr",
448 lld::DefinedAtom::typeTLVInitializerPtr);
449 io.enumCase(value, "first-in-section",
450 lld::DefinedAtom::typeFirstInSection);
451 io.enumCase(value, "last-in-section",
452 lld::DefinedAtom::typeLastInSection);
453 }
454};
455
456template <>
457struct ScalarEnumerationTraits<lld::UndefinedAtom::CanBeNull> {
458 static void enumeration(IO &io, lld::UndefinedAtom::CanBeNull &value) {
459 io.enumCase(value, "never", lld::UndefinedAtom::canBeNullNever);
460 io.enumCase(value, "at-runtime", lld::UndefinedAtom::canBeNullAtRuntime);
461 io.enumCase(value, "at-buildtime", lld::UndefinedAtom::canBeNullAtBuildtime);
462 }
463};
464
465
466template <>
467struct ScalarEnumerationTraits<ShlibCanBeNull> {
468 static void enumeration(IO &io, ShlibCanBeNull &value) {
469 io.enumCase(value, "never", false);
470 io.enumCase(value, "at-runtime", true);
471 }
472};
473
474
475
476/// This is a custom formatter for lld::DefinedAtom::Alignment. Values look
477/// like:
478/// 2^3 # 8-byte aligned
479/// 7 mod 2^4 # 16-byte aligned plus 7 bytes
480template<>
481struct ScalarTraits<lld::DefinedAtom::Alignment> {
482 static void output(const lld::DefinedAtom::Alignment &value, void *ctxt,
483 llvm::raw_ostream &out) {
484 if (value.modulus == 0) {
485 out << llvm::format("2^%d", value.powerOf2);
486 }
487 else {
488 out << llvm::format("%d mod 2^%d", value.modulus, value.powerOf2);
489 }
490 }
491
492 static StringRef input(StringRef scalar, void *ctxt,
493 lld::DefinedAtom::Alignment &value) {
494 value.modulus = 0;
495 size_t modStart = scalar.find("mod");
496 if (modStart != StringRef::npos) {
497 StringRef modStr = scalar.slice(0, modStart);
498 modStr = modStr.rtrim();
499 unsigned int modulus;
500 if (modStr.getAsInteger(0, modulus)) {
501 return "malformed alignment modulus";
502 }
503 value.modulus = modulus;
504 scalar = scalar.drop_front(modStart+3);
505 scalar = scalar.ltrim();
506 }
507 if (!scalar.startswith("2^")) {
508 return "malformed alignment";
509 }
510 StringRef powerStr = scalar.drop_front(2);
511 unsigned int power;
512 if (powerStr.getAsInteger(0, power)) {
513 return "malformed alignment power";
514 }
515 value.powerOf2 = power;
516 if (value.modulus > (1<<value.powerOf2)) {
517 return "malformed alignment, modulus too large for power";
518 }
519 return StringRef(); // returning empty string means success
520 }
521};
522
523
524
525
526template <>
527struct ScalarEnumerationTraits<FileKinds> {
528 static void enumeration(IO &io, FileKinds &value) {
529 io.enumCase(value, "object", fileKindObjectAtoms);
530 io.enumCase(value, "archive", fileKindArchive);
531 io.enumCase(value, "object-elf", fileKindObjectELF);
532 io.enumCase(value, "object-mach-o", fileKindObjectMachO);
533 }
534};
535
536template <>
537struct MappingTraits<ArchMember> {
538 static void mapping(IO &io, ArchMember &member) {
539 io.mapOptional("kind", member._kind, fileKindObjectAtoms);
540 io.mapOptional("name", member._name);
541 io.mapRequired("content", member._content);
542 }
543};
544
Nick Kledzik6b079f52013-01-05 02:22:35 +0000545
546
547// Declare that an AtomList is a yaml sequence.
548template<typename T>
549struct SequenceTraits<AtomList<T>> {
550 static size_t size(IO &io, AtomList<T> &seq) {
551 return seq._atoms.size();
552 }
553 static const T *&element(IO &io, AtomList<T> &seq, size_t index) {
554 if (index >= seq._atoms.size())
555 seq._atoms.resize(index+1);
556 return seq._atoms[index];
557 }
558};
559
560// Used to allow DefinedAtom content bytes to be a flow sequence of
561// two-digit hex numbers without the leading 0x (e.g. FF, 04, 0A)
562template<>
563struct ScalarTraits<ImplicitHex8> {
564 static void output(const ImplicitHex8 &val, void*, llvm::raw_ostream &out) {
565 uint8_t num = val;
566 out << llvm::format("%02X", num);
567 }
568
569 static llvm::StringRef input(llvm::StringRef str, void*, ImplicitHex8 &val) {
570 unsigned long long n;
571 if (getAsUnsignedInteger(str, 16, n))
572 return "invalid two-digit-hex number";
573 if (n > 0xFF)
574 return "out of range two-digit-hex number";
575 val = n;
576 return StringRef(); // returning empty string means success
577 }
578};
579
Nick Kledzik6b079f52013-01-05 02:22:35 +0000580
581// YAML conversion for std::vector<const lld::File*>
582template<>
583struct DocumentListTraits< std::vector<const lld::File*> > {
584 static size_t size(IO &io, std::vector<const lld::File*> &seq) {
585 return seq.size();
586 }
587 static const lld::File *&element(IO &io, std::vector<const lld::File*> &seq,
588 size_t index) {
589 if (index >= seq.size())
590 seq.resize(index+1);
591 return seq[index];
592 }
593};
594
595
596// YAML conversion for const lld::File*
597template <>
598struct MappingTraits<const lld::File*> {
599
600 class NormArchiveFile : public lld::ArchiveLibraryFile {
601 public:
602 NormArchiveFile(IO &io) : ArchiveLibraryFile(""), _path() {
603 }
604 NormArchiveFile(IO &io, const lld::File *file)
605 : ArchiveLibraryFile(file->path()),
606 _path(file->path()) {
607 // If we want to support writing archives, this constructor would
608 // need to populate _members.
609 }
610
611 const lld::File *denormalize(IO &io) {
612 return this;
613 }
614
615 virtual void addAtom(const lld::Atom&) {
616 llvm_unreachable("cannot add atoms to yaml .o files");
617 }
618 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);
672
673
674 virtual void addAtom(const lld::Atom&) {
675 llvm_unreachable("cannot add atoms to yaml .o files");
676 }
677 virtual const atom_collection<lld::DefinedAtom> &defined() const {
678 return _definedAtoms;
679 }
680 virtual const atom_collection<lld::UndefinedAtom> &undefined() const {
681 return _undefinedAtoms;
682 }
683 virtual const atom_collection<lld::SharedLibraryAtom> &sharedLibrary()const{
684 return _sharedLibraryAtoms;
685 }
686 virtual const atom_collection<lld::AbsoluteAtom> &absolute() const {
687 return _absoluteAtoms;
688 }
689
690 // Allocate a new copy of this string and keep track of allocations
691 // in _stringCopies, so they can be freed when File is destroyed.
692 StringRef copyString(StringRef str) {
693 // We want _stringCopies to own the string memory so it is deallocated
694 // when the File object is destroyed. But we need a StringRef that
695 // points into that memory.
696 std::unique_ptr<char> s = std::unique_ptr<char>(new char[str.size()]);
697 memcpy(s.get(), str.data(), str.size());
698 llvm::StringRef r = llvm::StringRef(s.get(), str.size());
699 _stringCopies.push_back(std::move(s));
700 return r;
701 }
702
703 RefNameBuilder *_rnb;
704 StringRef _path;
705 AtomList<lld::DefinedAtom> _definedAtoms;
706 AtomList<lld::UndefinedAtom> _undefinedAtoms;
707 AtomList<lld::SharedLibraryAtom> _sharedLibraryAtoms;
708 AtomList<lld::AbsoluteAtom> _absoluteAtoms;
709 std::vector<std::unique_ptr<char>> _stringCopies;
710 };
711
712
713 static void mapping(IO &io, const lld::File *&file) {
714 // We only support writing atom based YAML
715 FileKinds kind = fileKindObjectAtoms;
716 // If reading, peek ahead to see what kind of file this is.
717 io.mapOptional("kind", kind, fileKindObjectAtoms);
718 //
719 switch (kind) {
720 case fileKindObjectAtoms:
721 mappingAtoms(io, file);
722 break;
723 case fileKindArchive:
724 mappingArchive(io, file);
725 break;
726 case fileKindObjectELF:
727 case fileKindObjectMachO:
728 // Eventually we will have an external function to call, similar
729 // to mappingAtoms() and mappingArchive() but implememented
730 // with coresponding file format code.
Nick Kledzik6b079f52013-01-05 02:22:35 +0000731 llvm_unreachable("section based YAML not supported yet");
732 }
733 }
734
735 static void mappingAtoms(IO &io, const lld::File *&file) {
736 MappingNormalizationHeap<NormalizedFile, const lld::File*> keys(io, file);
737 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
738 assert(info != nullptr);
739 info->_currentFile = keys.operator->();
740
741 io.mapOptional("path", keys->_path);
742 io.mapOptional("defined-atoms", keys->_definedAtoms);
743 io.mapOptional("undefined-atoms", keys->_undefinedAtoms);
744 io.mapOptional("shared-library-atoms", keys->_sharedLibraryAtoms);
745 io.mapOptional("absolute-atoms", keys->_absoluteAtoms);
746 }
747
748 static void mappingArchive(IO &io, const lld::File *&file) {
749 MappingNormalizationHeap<NormArchiveFile, const lld::File*> keys(io, file);
750
751 io.mapOptional("path", keys->_path);
752 io.mapOptional("members", keys->_members);
753 }
754
755};
756
757
758
759// YAML conversion for const lld::Reference*
760template <>
761struct MappingTraits<const lld::Reference*> {
762
763 class NormalizedReference : public lld::Reference {
764 public:
765 NormalizedReference(IO &io)
766 : _target(nullptr), _targetName(), _offset(0), _addend(0) , _kind(0) {
767 }
768 NormalizedReference(IO &io, const lld::Reference *ref)
769 : _target(nullptr),
770 _targetName(targetName(io, ref)),
771 _offset(ref->offsetInAtom()),
772 _addend(ref->addend()),
773 _kind(ref->kind()) {
774 }
775 const lld::Reference *denormalize(IO &io) {
776 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
777 assert(info != nullptr);
778 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
779 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
780 if (!_targetName.empty())
781 _targetName = f->copyString(_targetName);
782 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
783 << "created Reference to name: '" << _targetName
784 << "' (" << (void*)_targetName.data() << ", "
785 << _targetName.size() << ")\n");
786 return this;
787 }
788 void bind(const RefNameResolver&);
789 static StringRef targetName(IO &io, const lld::Reference *ref);
790
791 virtual uint64_t offsetInAtom() const { return _offset; }
792 virtual Kind kind() const { return _kind; }
793 virtual const lld::Atom *target() const { return _target; }
794 virtual Addend addend() const { return _addend; }
795 virtual void setKind(Kind k) { _kind = k; }
796 virtual void setAddend(Addend a) { _addend = a; }
797 virtual void setTarget(const lld::Atom *a) { _target = a; }
798
799 const lld::Atom *_target;
800 StringRef _targetName;
801 uint32_t _offset;
802 Addend _addend;
803 RefKind _kind;
804 };
805
806
807 static void mapping(IO &io, const lld::Reference *&ref) {
808 MappingNormalizationHeap<NormalizedReference,
809 const lld::Reference*> keys(io, ref);
810
811 io.mapRequired("kind", keys->_kind);
812 io.mapOptional("offset", keys->_offset);
813 io.mapOptional("target", keys->_targetName);
814 io.mapOptional("addend", keys->_addend, (lld::Reference::Addend)0);
815 }
816};
817
Nick Kledzik6b079f52013-01-05 02:22:35 +0000818
819
820// YAML conversion for const lld::DefinedAtom*
821template <>
822struct MappingTraits<const lld::DefinedAtom*> {
823
824 class NormalizedAtom : public lld::DefinedAtom {
825 public:
826 NormalizedAtom(IO &io)
827 : _file(fileFromContext(io)), _name(), _refName(),
828 _alignment(0), _content(), _references() {
829 }
830 NormalizedAtom(IO &io, const lld::DefinedAtom *atom)
831 : _file(fileFromContext(io)),
832 _name(atom->name()),
833 _refName(),
834 _scope(atom->scope()),
835 _interpose(atom->interposable()),
836 _merge(atom->merge()),
837 _contentType(atom->contentType()),
838 _alignment(atom->alignment()),
839 _sectionChoice(atom->sectionChoice()),
840 _deadStrip(atom->deadStrip()),
841 _permissions(atom->permissions()),
842 _size(atom->size()),
843 _sectionName(atom->customSectionName()) {
844 for ( const lld::Reference *r : *atom )
845 _references.push_back(r);
846 ArrayRef<uint8_t> cont = atom->rawContent();
847 _content.reserve(cont.size());
848 for (uint8_t x : cont)
849 _content.push_back(x);
850 }
851 const lld::DefinedAtom *denormalize(IO &io) {
852 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
853 assert(info != nullptr);
854 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
855 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
856 if ( !_name.empty() )
857 _name = f->copyString(_name);
858 if ( !_refName.empty() )
859 _refName = f->copyString(_refName);
860 if ( !_sectionName.empty() )
861 _sectionName = f->copyString(_sectionName);
862 DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
863 << "created DefinedAtom named: '" << _name
864 << "' (" << (void*)_name.data() << ", "
865 << _name.size() << ")\n");
866 return this;
867 }
868 void bind(const RefNameResolver&);
869 // Extract current File object from YAML I/O parsing context
870 const lld::File &fileFromContext(IO &io) {
871 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
872 assert(info != nullptr);
873 assert(info->_currentFile != nullptr);
874 return *info->_currentFile;
875 }
876
877 virtual const lld::File &file() const { return _file; }
878 virtual StringRef name() const { return _name; }
879 virtual uint64_t size() const { return _size; }
880 virtual Scope scope() const { return _scope; }
881 virtual Interposable interposable() const { return _interpose; }
882 virtual Merge merge() const { return _merge; }
883 virtual ContentType contentType() const { return _contentType; }
884 virtual Alignment alignment() const { return _alignment; }
885 virtual SectionChoice sectionChoice() const { return _sectionChoice; }
886 virtual StringRef customSectionName() const { return _sectionName;}
887 virtual DeadStripKind deadStrip() const { return _deadStrip; }
888 virtual ContentPermissions permissions() const { return _permissions; }
889 virtual bool isThumb() const { return false; }
890 virtual bool isAlias() const { return false; }
891 ArrayRef<uint8_t> rawContent() const {
892 return ArrayRef<uint8_t>((uint8_t*)&_content.operator[](0),
893 _content.size()); }
894 virtual uint64_t ordinal() const { return 0; }
895
896 reference_iterator begin() const {
897 uintptr_t index = 0;
898 const void *it = reinterpret_cast<const void*>(index);
899 return reference_iterator(*this, it);
900 }
901 reference_iterator end() const {
902 uintptr_t index = _references.size();
903 const void *it = reinterpret_cast<const void*>(index);
904 return reference_iterator(*this, it);
905 }
906 const lld::Reference *derefIterator(const void *it) const {
907 uintptr_t index = reinterpret_cast<uintptr_t>(it);
908 assert(index < _references.size());
909 return _references[index];
910 }
911 void incrementIterator(const void *&it) const {
912 uintptr_t index = reinterpret_cast<uintptr_t>(it);
913 ++index;
914 it = reinterpret_cast<const void*>(index);
915 }
916
917 const lld::File &_file;
918 StringRef _name;
919 StringRef _refName;
920 Scope _scope;
921 Interposable _interpose;
922 Merge _merge;
923 ContentType _contentType;
924 Alignment _alignment;
925 SectionChoice _sectionChoice;
926 DeadStripKind _deadStrip;
927 ContentPermissions _permissions;
928 std::vector<ImplicitHex8> _content;
929 uint64_t _size;
930 StringRef _sectionName;
931 std::vector<const lld::Reference*> _references;
932 };
933
934 static void mapping(IO &io, const lld::DefinedAtom *&atom) {
935 MappingNormalizationHeap<NormalizedAtom,
936 const lld::DefinedAtom*> keys(io, atom);
937 if ( io.outputting() ) {
938 // If writing YAML, check if atom needs a ref-name.
939 typedef MappingTraits<const lld::File*>::NormalizedFile NormalizedFile;
940 ContextInfo *info = reinterpret_cast<ContextInfo*>(io.getContext());
941 assert(info != nullptr);
942 NormalizedFile *f = reinterpret_cast<NormalizedFile*>(info->_currentFile);
943 assert(f);
944 assert(f->_rnb);
945 if ( f->_rnb->hasRefName(atom) ) {
946 keys->_refName = f->_rnb->refName(atom);
947 }
948 }
949
950 io.mapOptional("name", keys->_name,
951 StringRef());
952 io.mapOptional("ref-name", keys->_refName,
953 StringRef());
954 io.mapOptional("scope", keys->_scope,
955 lld::DefinedAtom::scopeTranslationUnit);
956 io.mapOptional("type", keys->_contentType,
957 lld::DefinedAtom::typeCode);
958 io.mapOptional("content", keys->_content);
959 io.mapOptional("size", keys->_size,
960 (uint64_t)keys->_content.size());
961 io.mapOptional("interposable", keys->_interpose,
962 lld::DefinedAtom::interposeNo);
963 io.mapOptional("merge", keys->_merge,
964 lld::DefinedAtom::mergeNo);
965 io.mapOptional("alignment", keys->_alignment,
966 lld::DefinedAtom::Alignment(0));
967 io.mapOptional("section-choice", keys->_sectionChoice,
968 lld::DefinedAtom::sectionBasedOnContent);
969 io.mapOptional("section-name", keys->_sectionName,
970 StringRef());
971 io.mapOptional("dead-strip", keys->_deadStrip,
972 lld::DefinedAtom::deadStripNormal);
973 io.mapOptional("permissions", keys->_permissions,
974 lld::DefinedAtom::permR_X);
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