ObjectLinker.cpp revision 87f34658dec9097d987d254a990ea7f311bfc95f
1//===- ObjectLinker.cpp ---------------------------------------------------===//
2//
3//                     The MCLinker Project
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include <mcld/Object/ObjectLinker.h>
10
11#include <mcld/LinkerConfig.h>
12#include <mcld/LinkerScript.h>
13#include <mcld/Module.h>
14#include <mcld/InputTree.h>
15#include <mcld/IRBuilder.h>
16#include <mcld/LD/LDSection.h>
17#include <mcld/LD/LDContext.h>
18#include <mcld/LD/Archive.h>
19#include <mcld/LD/ArchiveReader.h>
20#include <mcld/LD/ObjectReader.h>
21#include <mcld/LD/DynObjReader.h>
22#include <mcld/LD/GroupReader.h>
23#include <mcld/LD/BinaryReader.h>
24#include <mcld/LD/GarbageCollection.h>
25#include <mcld/LD/ObjectWriter.h>
26#include <mcld/LD/ResolveInfo.h>
27#include <mcld/LD/RelocData.h>
28#include <mcld/LD/Relocator.h>
29#include <mcld/LD/SectionData.h>
30#include <mcld/LD/BranchIslandFactory.h>
31#include <mcld/Script/ScriptFile.h>
32#include <mcld/Script/ScriptReader.h>
33#include <mcld/Script/Assignment.h>
34#include <mcld/Script/Operand.h>
35#include <mcld/Script/RpnEvaluator.h>
36#include <mcld/Support/RealPath.h>
37#include <mcld/Support/FileOutputBuffer.h>
38#include <mcld/Support/MsgHandling.h>
39#include <mcld/Target/TargetLDBackend.h>
40#include <mcld/Fragment/Relocation.h>
41#include <mcld/Object/ObjectBuilder.h>
42
43#include <llvm/Support/Casting.h>
44#include <llvm/Support/Host.h>
45
46using namespace llvm;
47using namespace mcld;
48
49//===----------------------------------------------------------------------===//
50// ObjectLinker
51//===----------------------------------------------------------------------===//
52ObjectLinker::ObjectLinker(const LinkerConfig& pConfig,
53                           TargetLDBackend& pLDBackend)
54  : m_Config(pConfig),
55    m_pModule(NULL),
56    m_pBuilder(NULL),
57    m_LDBackend(pLDBackend),
58    m_pObjectReader(NULL),
59    m_pDynObjReader(NULL),
60    m_pArchiveReader(NULL),
61    m_pGroupReader(NULL),
62    m_pBinaryReader(NULL),
63    m_pScriptReader(NULL),
64    m_pWriter(NULL) {
65}
66
67ObjectLinker::~ObjectLinker()
68{
69  delete m_pObjectReader;
70  delete m_pDynObjReader;
71  delete m_pArchiveReader;
72  delete m_pGroupReader;
73  delete m_pBinaryReader;
74  delete m_pScriptReader;
75  delete m_pWriter;
76}
77
78bool ObjectLinker::initialize(Module& pModule, IRBuilder& pBuilder)
79{
80  m_pModule = &pModule;
81  m_pBuilder = &pBuilder;
82
83  // initialize the readers and writers
84  m_pObjectReader  = m_LDBackend.createObjectReader(*m_pBuilder);
85  m_pArchiveReader = m_LDBackend.createArchiveReader(*m_pModule);
86  m_pDynObjReader  = m_LDBackend.createDynObjReader(*m_pBuilder);
87  m_pBinaryReader  = m_LDBackend.createBinaryReader(*m_pBuilder);
88  m_pGroupReader   = new GroupReader(*m_pModule, *m_pObjectReader,
89                         *m_pDynObjReader, *m_pArchiveReader, *m_pBinaryReader);
90  m_pScriptReader  = new ScriptReader(*m_pGroupReader);
91  m_pWriter        = m_LDBackend.createWriter();
92
93  // initialize Relocator
94  m_LDBackend.initRelocator();
95
96  return true;
97}
98
99/// initStdSections - initialize standard sections
100bool ObjectLinker::initStdSections()
101{
102  ObjectBuilder builder(m_Config, *m_pModule);
103
104  // initialize standard sections
105  if (!m_LDBackend.initStdSections(builder))
106    return false;
107
108  // initialize target-dependent sections
109  m_LDBackend.initTargetSections(*m_pModule, builder);
110
111  return true;
112}
113
114void ObjectLinker::normalize()
115{
116  // -----  set up inputs  ----- //
117  Module::input_iterator input, inEnd = m_pModule->input_end();
118  for (input = m_pModule->input_begin(); input!=inEnd; ++input) {
119    // is a group node
120    if (isGroup(input)) {
121      getGroupReader()->readGroup(input, inEnd, m_pBuilder->getInputBuilder(),
122                                  m_Config);
123      continue;
124    }
125
126    // already got type - for example, bitcode or external OIR (object
127    // intermediate representation)
128    if ((*input)->type() == Input::Script ||
129        (*input)->type() == Input::Archive ||
130        (*input)->type() == Input::External)
131      continue;
132
133    if (Input::Object == (*input)->type()) {
134      m_pModule->getObjectList().push_back(*input);
135      continue;
136    }
137
138    if (Input::DynObj == (*input)->type()) {
139      m_pModule->getLibraryList().push_back(*input);
140      continue;
141    }
142
143    bool doContinue = false;
144    // read input as a binary file
145    if (getBinaryReader()->isMyFormat(**input, doContinue)) {
146      (*input)->setType(Input::Object);
147      getBinaryReader()->readBinary(**input);
148      m_pModule->getObjectList().push_back(*input);
149    }
150    // is a relocatable object file
151    else if (doContinue && getObjectReader()->isMyFormat(**input, doContinue)) {
152      (*input)->setType(Input::Object);
153      getObjectReader()->readHeader(**input);
154      getObjectReader()->readSections(**input);
155      getObjectReader()->readSymbols(**input);
156      m_pModule->getObjectList().push_back(*input);
157    }
158    // is a shared object file
159    else if (doContinue && getDynObjReader()->isMyFormat(**input, doContinue)) {
160      (*input)->setType(Input::DynObj);
161      getDynObjReader()->readHeader(**input);
162      getDynObjReader()->readSymbols(**input);
163      m_pModule->getLibraryList().push_back(*input);
164    }
165    // is an archive
166    else if (doContinue && getArchiveReader()->isMyFormat(**input, doContinue)) {
167      (*input)->setType(Input::Archive);
168      Archive archive(**input, m_pBuilder->getInputBuilder());
169      getArchiveReader()->readArchive(m_Config, archive);
170      if(archive.numOfObjectMember() > 0) {
171        m_pModule->getInputTree().merge<InputTree::Inclusive>(input,
172                                                              archive.inputs());
173      }
174    }
175    // try to parse input as a linker script
176    else if (doContinue && getScriptReader()->isMyFormat(**input, doContinue)) {
177      ScriptFile script(ScriptFile::LDScript, **input,
178                        m_pBuilder->getInputBuilder());
179      if (getScriptReader()->readScript(m_Config, script)) {
180        (*input)->setType(Input::Script);
181        script.activate(*m_pModule);
182        if (script.inputs().size() > 0) {
183          m_pModule->getInputTree().merge<InputTree::Inclusive>(input,
184            script.inputs());
185        }
186      }
187    }
188    else {
189      if (m_Config.options().warnMismatch())
190        warning(diag::warn_unrecognized_input_file) << (*input)->path()
191          << m_Config.targets().triple().str();
192    }
193  } // end of for
194}
195
196bool ObjectLinker::linkable() const
197{
198  // check we have input and output files
199  if (m_pModule->getInputTree().empty()) {
200    error(diag::err_no_inputs);
201    return false;
202  }
203
204  // can not mix -static with shared objects
205  Module::const_lib_iterator lib, libEnd = m_pModule->lib_end();
206  for (lib = m_pModule->lib_begin(); lib != libEnd; ++lib) {
207    if((*lib)->attribute()->isStatic()) {
208      error(diag::err_mixed_shared_static_objects)
209                                      << (*lib)->name() << (*lib)->path();
210      return false;
211    }
212  }
213
214  // --nmagic and --omagic options lead to static executable program.
215  // These options turn off page alignment of sections. Because the
216  // sections are not aligned to pages, these sections can not contain any
217  // exported functions. Also, because the two options disable linking
218  // against shared libraries, the output absolutely does not call outside
219  // functions.
220  if (m_Config.options().nmagic() && !m_Config.isCodeStatic()) {
221    error(diag::err_nmagic_not_static);
222    return false;
223  }
224  if (m_Config.options().omagic() && !m_Config.isCodeStatic()) {
225    error(diag::err_omagic_not_static);
226    return false;
227  }
228
229  return true;
230}
231
232void ObjectLinker::dataStrippingOpt()
233{
234  // Garbege collection
235  if (m_Config.options().GCSections()) {
236    GarbageCollection GC(m_Config, m_LDBackend, *m_pModule);
237    GC.run();
238  }
239  return;
240}
241
242/// readRelocations - read all relocation entries
243///
244/// All symbols should be read and resolved before this function.
245bool ObjectLinker::readRelocations()
246{
247  // Bitcode is read by the other path. This function reads relocation sections
248  // in object files.
249  mcld::InputTree::bfs_iterator input, inEnd = m_pModule->getInputTree().bfs_end();
250  for (input=m_pModule->getInputTree().bfs_begin(); input!=inEnd; ++input) {
251    if ((*input)->type() == Input::Object && (*input)->hasMemArea()) {
252      if (!getObjectReader()->readRelocations(**input))
253        return false;
254    }
255    // ignore the other kinds of files.
256  }
257  return true;
258}
259
260/// mergeSections - put allinput sections into output sections
261bool ObjectLinker::mergeSections()
262{
263  ObjectBuilder builder(m_Config, *m_pModule);
264  Module::obj_iterator obj, objEnd = m_pModule->obj_end();
265  for (obj = m_pModule->obj_begin(); obj != objEnd; ++obj) {
266    LDContext::sect_iterator sect, sectEnd = (*obj)->context()->sectEnd();
267    for (sect = (*obj)->context()->sectBegin(); sect != sectEnd; ++sect) {
268      switch ((*sect)->kind()) {
269        // Some *INPUT sections should not be merged.
270        case LDFileFormat::Ignore:
271        case LDFileFormat::Null:
272        case LDFileFormat::NamePool:
273        case LDFileFormat::Group:
274        case LDFileFormat::StackNote:
275          // skip
276          continue;
277        case LDFileFormat::Relocation: {
278          if (!(*sect)->hasRelocData())
279            continue; // skip
280
281          if ((*sect)->getLink()->kind() == LDFileFormat::Ignore)
282            (*sect)->setKind(LDFileFormat::Ignore);
283          break;
284        }
285        case LDFileFormat::Target:
286          if (!m_LDBackend.mergeSection(*m_pModule, **obj, **sect)) {
287            error(diag::err_cannot_merge_section) << (*sect)->name()
288                                                  << (*obj)->name();
289            return false;
290          }
291          break;
292        case LDFileFormat::EhFrame: {
293          if (!(*sect)->hasEhFrame())
294            continue; // skip
295
296          LDSection* out_sect = NULL;
297          if (NULL != (out_sect = builder.MergeSection(**obj, **sect))) {
298            if (!m_LDBackend.updateSectionFlags(*out_sect, **sect)) {
299              error(diag::err_cannot_merge_section) << (*sect)->name()
300                                                    << (*obj)->name();
301              return false;
302            }
303          }
304          break;
305        }
306        default: {
307          if (!(*sect)->hasSectionData())
308            continue; // skip
309
310          LDSection* out_sect = NULL;
311          if (NULL != (out_sect = builder.MergeSection(**obj, **sect))) {
312            if (!m_LDBackend.updateSectionFlags(*out_sect, **sect)) {
313              error(diag::err_cannot_merge_section) << (*sect)->name()
314                                                    << (*obj)->name();
315              return false;
316            }
317          }
318          break;
319        }
320      } // end of switch
321    } // for each section
322  } // for each obj
323
324  RpnEvaluator evaluator(*m_pModule, m_LDBackend);
325  SectionMap::iterator out, outBegin, outEnd;
326  outBegin = m_pModule->getScript().sectionMap().begin();
327  outEnd = m_pModule->getScript().sectionMap().end();
328  for (out = outBegin; out != outEnd; ++out) {
329    uint64_t out_align = 0x0, in_align = 0x0;
330    LDSection* out_sect = (*out)->getSection();
331    SectionMap::Output::iterator in, inBegin, inEnd;
332    inBegin = (*out)->begin();
333    inEnd = (*out)->end();
334
335    // force input alignment from ldscript if any
336    if ((*out)->prolog().hasSubAlign()) {
337      evaluator.eval((*out)->prolog().subAlign(), in_align);
338    }
339
340    for (in = inBegin; in != inEnd; ++in) {
341      LDSection* in_sect = (*in)->getSection();
342      if ((*out)->prolog().hasSubAlign())
343        in_sect->setAlign(in_align);
344
345      if (builder.MoveSectionData(*in_sect->getSectionData(),
346                                  *out_sect->getSectionData())) {
347        builder.UpdateSectionAlign(*out_sect, *in_sect);
348        m_LDBackend.updateSectionFlags(*out_sect, *in_sect);
349      }
350    } // for each input section description
351
352    // force output alignment from ldscript if any
353    if ((*out)->prolog().hasAlign()) {
354      evaluator.eval((*out)->prolog().align(), out_align);
355      out_sect->setAlign(out_align);
356    }
357
358    if ((*out)->hasContent()) {
359      LDSection* target = m_pModule->getSection((*out)->name());
360      assert(target != NULL && target->hasSectionData());
361      if (builder.MoveSectionData(*out_sect->getSectionData(),
362                                  *target->getSectionData())) {
363        builder.UpdateSectionAlign(*target, *out_sect);
364        m_LDBackend.updateSectionFlags(*target, *out_sect);
365      }
366    }
367  } // for each output section description
368
369  return true;
370}
371
372void ObjectLinker::addSymbolToOutput(ResolveInfo& pInfo, Module& pModule)
373{
374  // section symbols will be defined by linker later, we should not add section
375  // symbols to output here
376  if (ResolveInfo::Section == pInfo.type() || NULL == pInfo.outSymbol())
377    return;
378
379  // if the symbols defined in the Ignore sections (e.g. discared by GC), then
380  // not to put them to output
381  if (pInfo.outSymbol()->hasFragRef() && LDFileFormat::Ignore ==
382        pInfo.outSymbol()->fragRef()->frag()->getParent()->getSection().kind())
383    return;
384
385  if (pInfo.shouldForceLocal(m_Config))
386    pModule.getSymbolTable().forceLocal(*pInfo.outSymbol());
387  else
388    pModule.getSymbolTable().add(*pInfo.outSymbol());
389}
390
391void ObjectLinker::addSymbolsToOutput(Module& pModule)
392{
393  // Traverse all the free ResolveInfo and add the output symobols to output
394  NamePool::freeinfo_iterator free_it,
395                              free_end = pModule.getNamePool().freeinfo_end();
396  for (free_it = pModule.getNamePool().freeinfo_begin(); free_it != free_end;
397                                                                      ++free_it)
398    addSymbolToOutput(**free_it, pModule);
399
400
401  // Traverse all the resolveInfo and add the output symbol to output
402  NamePool::syminfo_iterator info_it,
403                             info_end = pModule.getNamePool().syminfo_end();
404  for (info_it = pModule.getNamePool().syminfo_begin(); info_it != info_end;
405                                                                      ++info_it)
406    addSymbolToOutput(*info_it.getEntry(), pModule);
407}
408
409
410/// addStandardSymbols - shared object and executable files need some
411/// standard symbols
412///   @return if there are some input symbols with the same name to the
413///   standard symbols, return false
414bool ObjectLinker::addStandardSymbols()
415{
416  // create and add section symbols for each output section
417  Module::iterator iter, iterEnd = m_pModule->end();
418  for (iter = m_pModule->begin(); iter != iterEnd; ++iter) {
419    m_pModule->getSectionSymbolSet().add(**iter, m_pModule->getNamePool());
420  }
421
422  return m_LDBackend.initStandardSymbols(*m_pBuilder, *m_pModule);
423}
424
425/// addTargetSymbols - some targets, such as MIPS and ARM, need some
426/// target-dependent symbols
427///   @return if there are some input symbols with the same name to the
428///   target symbols, return false
429bool ObjectLinker::addTargetSymbols()
430{
431  m_LDBackend.initTargetSymbols(*m_pBuilder, *m_pModule);
432  return true;
433}
434
435/// addScriptSymbols - define symbols from the command line option or linker
436/// scripts.
437bool ObjectLinker::addScriptSymbols()
438{
439  LinkerScript& script = m_pModule->getScript();
440  LinkerScript::Assignments::iterator it, ie = script.assignments().end();
441  // go through the entire symbol assignments
442  for (it = script.assignments().begin(); it != ie; ++it) {
443    LDSymbol* symbol = NULL;
444    assert((*it).second.symbol().type() == Operand::SYMBOL);
445    const llvm::StringRef symName =  (*it).second.symbol().name();
446    ResolveInfo::Type       type = ResolveInfo::NoType;
447    ResolveInfo::Visibility vis  = ResolveInfo::Default;
448    size_t size = 0;
449    ResolveInfo* old_info = m_pModule->getNamePool().findInfo(symName);
450    // if the symbol does not exist, we can set type to NOTYPE
451    // else we retain its type, same goes for size - 0 or retain old value
452    // and visibility - Default or retain
453    if (old_info != NULL) {
454      type = static_cast<ResolveInfo::Type>(old_info->type());
455      vis = old_info->visibility();
456      size = old_info->size();
457    }
458
459    // Add symbol and refine the visibility if needed
460    // FIXME: bfd linker would change the binding instead, but currently
461    //        ABS is also a kind of Binding in ResolveInfo.
462    switch ((*it).second.type()) {
463    case Assignment::HIDDEN:
464      vis = ResolveInfo::Hidden;
465      // Fall through
466    case Assignment::DEFAULT:
467      symbol =
468        m_pBuilder->AddSymbol<IRBuilder::Force,
469                              IRBuilder::Unresolve>(symName,
470                                                    type,
471                                                    ResolveInfo::Define,
472                                                    ResolveInfo::Absolute,
473                                                    size,
474                                                    0x0,
475                                                    FragmentRef::Null(),
476                                                    vis);
477      break;
478    case Assignment::PROVIDE_HIDDEN:
479      vis = ResolveInfo::Hidden;
480      // Fall through
481    case Assignment::PROVIDE:
482      symbol =
483        m_pBuilder->AddSymbol<IRBuilder::AsReferred,
484                              IRBuilder::Unresolve>(symName,
485                                                    type,
486                                                    ResolveInfo::Define,
487                                                    ResolveInfo::Absolute,
488                                                    size,
489                                                    0x0,
490                                                    FragmentRef::Null(),
491                                                    vis);
492      break;
493    }
494    // Set symbol of this assignment.
495    (*it).first = symbol;
496  }
497  return true;
498}
499
500bool ObjectLinker::scanRelocations()
501{
502  // apply all relocations of all inputs
503  Module::obj_iterator input, inEnd = m_pModule->obj_end();
504  for (input = m_pModule->obj_begin(); input != inEnd; ++input) {
505    m_LDBackend.getRelocator()->initializeScan(**input);
506    LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd();
507    for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) {
508      // bypass the reloc section if
509      // 1. its section kind is changed to Ignore. (The target section is a
510      // discarded group section.)
511      // 2. it has no reloc data. (All symbols in the input relocs are in the
512      // discarded group sections)
513      if (LDFileFormat::Ignore == (*rs)->kind() || !(*rs)->hasRelocData())
514        continue;
515      RelocData::iterator reloc, rEnd = (*rs)->getRelocData()->end();
516      for (reloc = (*rs)->getRelocData()->begin(); reloc != rEnd; ++reloc) {
517        Relocation* relocation = llvm::cast<Relocation>(reloc);
518
519        // bypass the reloc if the symbol is in the discarded input section
520        ResolveInfo* info = relocation->symInfo();
521        if (!info->outSymbol()->hasFragRef() &&
522            ResolveInfo::Section == info->type() &&
523            ResolveInfo::Undefined == info->desc())
524           continue;
525
526        // scan relocation
527        if (LinkerConfig::Object != m_Config.codeGenType())
528          m_LDBackend.getRelocator()->scanRelocation(
529                                    *relocation, *m_pBuilder, *m_pModule, **rs, **input);
530        else
531          m_LDBackend.getRelocator()->partialScanRelocation(
532                                                 *relocation, *m_pModule, **rs);
533      } // for all relocations
534    } // for all relocation section
535    m_LDBackend.getRelocator()->finalizeScan(**input);
536  } // for all inputs
537  return true;
538}
539
540/// initStubs - initialize stub-related stuff.
541bool ObjectLinker::initStubs()
542{
543  // initialize BranchIslandFactory
544  m_LDBackend.initBRIslandFactory();
545
546  // initialize StubFactory
547  m_LDBackend.initStubFactory();
548
549  // initialize target stubs
550  m_LDBackend.initTargetStubs();
551  return true;
552}
553
554/// allocateCommonSymobols - allocate fragments for common symbols to the
555/// corresponding sections
556bool ObjectLinker::allocateCommonSymbols()
557{
558  if (LinkerConfig::Object != m_Config.codeGenType() ||
559      m_Config.options().isDefineCommon())
560    return m_LDBackend.allocateCommonSymbols(*m_pModule);
561  return true;
562}
563
564/// prelayout - help backend to do some modification before layout
565bool ObjectLinker::prelayout()
566{
567  // finalize the section symbols, set their fragment reference and push them
568  // into output symbol table
569  Module::iterator sect, sEnd = m_pModule->end();
570  for (sect = m_pModule->begin(); sect != sEnd; ++sect) {
571    m_pModule->getSectionSymbolSet().finalize(**sect,
572        m_pModule->getSymbolTable(),
573        m_Config.codeGenType() == LinkerConfig::Object);
574  }
575
576  m_LDBackend.preLayout(*m_pModule, *m_pBuilder);
577
578  /// check program interpreter - computer the name size of the runtime dyld
579  if (!m_Config.isCodeStatic() &&
580      (LinkerConfig::Exec == m_Config.codeGenType() ||
581       m_Config.options().isPIE() ||
582       m_Config.options().hasDyld()))
583    m_LDBackend.sizeInterp();
584
585  /// measure NamePools - compute the size of name pool sections
586  /// In ELF, will compute  the size of.symtab, .strtab, .dynsym, .dynstr,
587  /// .hash and .shstrtab sections.
588  ///
589  /// dump all symbols and strings from ObjectLinker and build the format-dependent
590  /// hash table.
591  /// @note sizeNamePools replies on LinkerConfig::CodePosition. Must determine
592  /// code position model before calling GNULDBackend::sizeNamePools()
593  m_LDBackend.sizeNamePools(*m_pModule);
594
595  // Do this after backend prelayout since it may add eh_frame entries.
596  LDSection* eh_frame_sect = m_pModule->getSection(".eh_frame");
597  if (eh_frame_sect && eh_frame_sect->hasEhFrame())
598    eh_frame_sect->getEhFrame()->computeOffsetSize();
599  m_LDBackend.createAndSizeEhFrameHdr(*m_pModule);
600
601  return true;
602}
603
604/// layout - linearly layout all output sections and reserve some space
605/// for GOT/PLT
606///   Because we do not support instruction relaxing in this early version,
607///   if there is a branch can not jump to its target, we return false
608///   directly
609bool ObjectLinker::layout()
610{
611  m_LDBackend.layout(*m_pModule);
612  return true;
613}
614
615/// prelayout - help backend to do some modification after layout
616bool ObjectLinker::postlayout()
617{
618  m_LDBackend.postLayout(*m_pModule, *m_pBuilder);
619  return true;
620}
621
622/// finalizeSymbolValue - finalize the resolved symbol value.
623///   Before relocate(), after layout(), ObjectLinker should correct value of all
624///   symbol.
625bool ObjectLinker::finalizeSymbolValue()
626{
627  Module::sym_iterator symbol, symEnd = m_pModule->sym_end();
628  for (symbol = m_pModule->sym_begin(); symbol != symEnd; ++symbol) {
629
630    if ((*symbol)->resolveInfo()->isAbsolute() ||
631        (*symbol)->resolveInfo()->type() == ResolveInfo::File) {
632      // absolute symbols should just use its value directly (i.e., the result
633      // of symbol resolution)
634      continue;
635    }
636
637    if ((*symbol)->resolveInfo()->type() == ResolveInfo::ThreadLocal) {
638      m_LDBackend.finalizeTLSSymbol(**symbol);
639      continue;
640    }
641
642    if ((*symbol)->hasFragRef()) {
643      // set the virtual address of the symbol. If the output file is
644      // relocatable object file, the section's virtual address becomes zero.
645      // And the symbol's value become section relative offset.
646      uint64_t value = (*symbol)->fragRef()->getOutputOffset();
647      assert(NULL != (*symbol)->fragRef()->frag());
648      uint64_t addr =
649        (*symbol)->fragRef()->frag()->getParent()->getSection().addr();
650      (*symbol)->setValue(value + addr);
651      continue;
652    }
653  }
654
655  RpnEvaluator evaluator(*m_pModule, m_LDBackend);
656  bool finalized = m_LDBackend.finalizeSymbols();
657  bool scriptSymsFinalized = true;
658  LinkerScript& script = m_pModule->getScript();
659  LinkerScript::Assignments::iterator assign, assignEnd;
660  assignEnd = script.assignments().end();
661  for (assign = script.assignments().begin(); assign != assignEnd; ++assign) {
662    LDSymbol* symbol = (*assign).first;
663    Assignment& assignment = (*assign).second;
664
665    if (symbol == NULL)
666      continue;
667
668    scriptSymsFinalized &= assignment.assign(evaluator);
669    if (!scriptSymsFinalized)
670      break;
671
672    symbol->setValue(assignment.symbol().value());
673  } // for each script symbol assignment
674
675  bool assertionsPassed = true;
676  LinkerScript::Assertions::iterator assert, assertEnd;
677  assertEnd = script.assertions().end();
678  for (assert = script.assertions().begin(); assert != assertEnd; ++assert) {
679    uint64_t res = 0x0;
680    evaluator.eval((*assert).getRpnExpr(), res);
681    if (res == 0x0)
682      fatal(diag::err_assert_failed) << (*assert).message();
683  } // for each assertion in ldscript
684
685  return finalized && scriptSymsFinalized && assertionsPassed;
686}
687
688/// relocate - applying relocation entries and create relocation
689/// section in the output files
690/// Create relocation section, asking TargetLDBackend to
691/// read the relocation information into RelocationEntry
692/// and push_back into the relocation section
693bool ObjectLinker::relocation()
694{
695  // when producing relocatables, no need to apply relocation
696  if (LinkerConfig::Object == m_Config.codeGenType())
697    return true;
698
699  // apply all relocations of all inputs
700  Module::obj_iterator input, inEnd = m_pModule->obj_end();
701  for (input = m_pModule->obj_begin(); input != inEnd; ++input) {
702    m_LDBackend.getRelocator()->initializeApply(**input);
703    LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd();
704    for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) {
705      // bypass the reloc section if
706      // 1. its section kind is changed to Ignore. (The target section is a
707      // discarded group section.)
708      // 2. it has no reloc data. (All symbols in the input relocs are in the
709      // discarded group sections)
710      if (LDFileFormat::Ignore == (*rs)->kind() || !(*rs)->hasRelocData())
711        continue;
712      RelocData::iterator reloc, rEnd = (*rs)->getRelocData()->end();
713      for (reloc = (*rs)->getRelocData()->begin(); reloc != rEnd; ++reloc) {
714        Relocation* relocation = llvm::cast<Relocation>(reloc);
715
716        // bypass the reloc if the symbol is in the discarded input section
717        ResolveInfo* info = relocation->symInfo();
718        if (!info->outSymbol()->hasFragRef() &&
719            ResolveInfo::Section == info->type() &&
720            ResolveInfo::Undefined == info->desc())
721          continue;
722
723        relocation->apply(*m_LDBackend.getRelocator());
724      } // for all relocations
725    } // for all relocation section
726    m_LDBackend.getRelocator()->finalizeApply(**input);
727  } // for all inputs
728
729  // apply relocations created by relaxation
730  BranchIslandFactory* br_factory = m_LDBackend.getBRIslandFactory();
731  BranchIslandFactory::iterator facIter, facEnd = br_factory->end();
732  for (facIter = br_factory->begin(); facIter != facEnd; ++facIter) {
733    BranchIsland& island = *facIter;
734    BranchIsland::reloc_iterator iter, iterEnd = island.reloc_end();
735    for (iter = island.reloc_begin(); iter != iterEnd; ++iter)
736      (*iter)->apply(*m_LDBackend.getRelocator());
737  }
738  return true;
739}
740
741/// emitOutput - emit the output file.
742bool ObjectLinker::emitOutput(FileOutputBuffer& pOutput)
743{
744  return llvm::errc::success == getWriter()->writeObject(*m_pModule, pOutput);
745}
746
747
748/// postProcessing - do modification after all processes
749bool ObjectLinker::postProcessing(FileOutputBuffer& pOutput)
750{
751  if (LinkerConfig::Object != m_Config.codeGenType())
752    normalSyncRelocationResult(pOutput);
753  else
754    partialSyncRelocationResult(pOutput);
755
756  // emit .eh_frame_hdr
757  // eh_frame_hdr should be emitted after syncRelocation, because eh_frame_hdr
758  // needs FDE PC value, which will be corrected at syncRelocation
759  m_LDBackend.postProcessing(pOutput);
760  return true;
761}
762
763void ObjectLinker::normalSyncRelocationResult(FileOutputBuffer& pOutput)
764{
765  uint8_t* data = pOutput.getBufferStart();
766
767  // sync all relocations of all inputs
768  Module::obj_iterator input, inEnd = m_pModule->obj_end();
769  for (input = m_pModule->obj_begin(); input != inEnd; ++input) {
770    LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd();
771    for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) {
772      // bypass the reloc section if
773      // 1. its section kind is changed to Ignore. (The target section is a
774      // discarded group section.)
775      // 2. it has no reloc data. (All symbols in the input relocs are in the
776      // discarded group sections)
777      if (LDFileFormat::Ignore == (*rs)->kind() || !(*rs)->hasRelocData())
778        continue;
779      RelocData::iterator reloc, rEnd = (*rs)->getRelocData()->end();
780      for (reloc = (*rs)->getRelocData()->begin(); reloc != rEnd; ++reloc) {
781        Relocation* relocation = llvm::cast<Relocation>(reloc);
782
783        // bypass the reloc if the symbol is in the discarded input section
784        ResolveInfo* info = relocation->symInfo();
785        if (!info->outSymbol()->hasFragRef() &&
786            ResolveInfo::Section == info->type() &&
787            ResolveInfo::Undefined == info->desc())
788          continue;
789
790        // bypass the relocation with NONE type. This is to avoid overwrite the
791        // target result by NONE type relocation if there is a place which has
792        // two relocations to apply to, and one of it is NONE type. The result
793        // we want is the value of the other relocation result. For example,
794        // in .exidx, there are usually an R_ARM_NONE and R_ARM_PREL31 apply to
795        // the same place
796        if (0x0 == relocation->type())
797          continue;
798        writeRelocationResult(*relocation, data);
799      } // for all relocations
800    } // for all relocation section
801  } // for all inputs
802
803  // sync relocations created by relaxation
804  BranchIslandFactory* br_factory = m_LDBackend.getBRIslandFactory();
805  BranchIslandFactory::iterator facIter, facEnd = br_factory->end();
806  for (facIter = br_factory->begin(); facIter != facEnd; ++facIter) {
807    BranchIsland& island = *facIter;
808    BranchIsland::reloc_iterator iter, iterEnd = island.reloc_end();
809    for (iter = island.reloc_begin(); iter != iterEnd; ++iter) {
810      Relocation* reloc = *iter;
811      writeRelocationResult(*reloc, data);
812    }
813  }
814}
815
816void ObjectLinker::partialSyncRelocationResult(FileOutputBuffer& pOutput)
817{
818  uint8_t* data = pOutput.getBufferStart();
819
820  // traverse outputs' LDSection to get RelocData
821  Module::iterator sectIter, sectEnd = m_pModule->end();
822  for (sectIter = m_pModule->begin(); sectIter != sectEnd; ++sectIter) {
823    if (LDFileFormat::Relocation != (*sectIter)->kind())
824      continue;
825
826    RelocData* reloc_data = (*sectIter)->getRelocData();
827    RelocData::iterator relocIter, relocEnd = reloc_data->end();
828    for (relocIter = reloc_data->begin(); relocIter != relocEnd; ++relocIter) {
829      Relocation* reloc = llvm::cast<Relocation>(relocIter);
830
831      // bypass the relocation with NONE type. This is to avoid overwrite the
832      // target result by NONE type relocation if there is a place which has
833      // two relocations to apply to, and one of it is NONE type. The result
834      // we want is the value of the other relocation result. For example,
835      // in .exidx, there are usually an R_ARM_NONE and R_ARM_PREL31 apply to
836      // the same place
837      if (0x0 == reloc->type())
838        continue;
839      writeRelocationResult(*reloc, data);
840    }
841  }
842}
843
844void ObjectLinker::writeRelocationResult(Relocation& pReloc, uint8_t* pOutput)
845{
846  // get output file offset
847  size_t out_offset =
848                 pReloc.targetRef().frag()->getParent()->getSection().offset() +
849                 pReloc.targetRef().getOutputOffset();
850
851  uint8_t* target_addr = pOutput + out_offset;
852  // byte swapping if target and host has different endian, and then write back
853  if(llvm::sys::IsLittleEndianHost != m_Config.targets().isLittleEndian()) {
854     uint64_t tmp_data = 0;
855
856     switch(pReloc.size(*m_LDBackend.getRelocator())) {
857       case 8u:
858         std::memcpy(target_addr, &pReloc.target(), 1);
859         break;
860
861       case 16u:
862         tmp_data = mcld::bswap16(pReloc.target());
863         std::memcpy(target_addr, &tmp_data, 2);
864         break;
865
866       case 32u:
867         tmp_data = mcld::bswap32(pReloc.target());
868         std::memcpy(target_addr, &tmp_data, 4);
869         break;
870
871       case 64u:
872         tmp_data = mcld::bswap64(pReloc.target());
873         std::memcpy(target_addr, &tmp_data, 8);
874         break;
875
876       default:
877         break;
878    }
879  }
880  else
881    std::memcpy(target_addr, &pReloc.target(),
882                                      pReloc.size(*m_LDBackend.getRelocator())/8);
883}
884
885