ObjectLinker.cpp revision 22add6ff3426df1a85089fe6a6e1597ee3b6f300
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/Module.h>
13#include <mcld/InputTree.h>
14#include <mcld/MC/InputBuilder.h>
15#include <mcld/LD/LDSection.h>
16#include <mcld/LD/LDContext.h>
17#include <mcld/LD/Archive.h>
18#include <mcld/LD/ArchiveReader.h>
19#include <mcld/LD/ObjectReader.h>
20#include <mcld/LD/DynObjReader.h>
21#include <mcld/LD/GroupReader.h>
22#include <mcld/LD/ObjectWriter.h>
23#include <mcld/LD/DynObjWriter.h>
24#include <mcld/LD/ExecWriter.h>
25#include <mcld/LD/ResolveInfo.h>
26#include <mcld/LD/Layout.h>
27#include <mcld/LD/RelocData.h>
28#include <mcld/Support/RealPath.h>
29#include <mcld/Support/MemoryArea.h>
30#include <mcld/Support/MsgHandling.h>
31#include <mcld/Target/TargetLDBackend.h>
32#include <mcld/Fragment/FragmentLinker.h>
33#include <mcld/Object/ObjectBuilder.h>
34
35#include <llvm/Support/Casting.h>
36
37using namespace llvm;
38using namespace mcld;
39
40ObjectLinker::ObjectLinker(const LinkerConfig& pConfig,
41                           Module& pModule,
42                           InputBuilder& pInputBuilder,
43                           TargetLDBackend& pLDBackend)
44  : m_Config(pConfig),
45    m_Module(pModule),
46    m_InputBuilder(pInputBuilder),
47    m_pLinker(NULL),
48    m_LDBackend(pLDBackend),
49    m_pObjectReader(NULL),
50    m_pDynObjReader(NULL),
51    m_pArchiveReader(NULL),
52    m_pObjectWriter(NULL),
53    m_pDynObjWriter(NULL),
54    m_pExecWriter(NULL),
55    m_pGroupReader(NULL)
56{
57  // set up soname
58  if (!m_Config.options().soname().empty()) {
59    m_Module.setName(m_Config.options().soname());
60  }
61}
62
63ObjectLinker::~ObjectLinker()
64{
65  delete m_pLinker;
66  delete m_pObjectReader;
67  delete m_pDynObjReader;
68  delete m_pArchiveReader;
69  delete m_pObjectWriter;
70  delete m_pDynObjWriter;
71  delete m_pExecWriter;
72  delete m_pGroupReader;
73}
74
75/// initFragmentLinker - initialize FragmentLinker
76///  Connect all components with FragmentLinker
77bool ObjectLinker::initFragmentLinker()
78{
79  if (NULL == m_pLinker) {
80    m_pLinker = new FragmentLinker(m_Config,
81                                   m_Module,
82                                   m_LDBackend);
83  }
84
85  // initialize the readers and writers
86  // Because constructor can not be failed, we initalize all readers and
87  // writers outside the FragmentLinker constructors.
88  m_pObjectReader  = m_LDBackend.createObjectReader(*m_pLinker);
89  m_pArchiveReader = m_LDBackend.createArchiveReader(m_Module);
90  m_pDynObjReader  = m_LDBackend.createDynObjReader(*m_pLinker);
91  m_pObjectWriter  = m_LDBackend.createObjectWriter(*m_pLinker);
92  m_pDynObjWriter  = m_LDBackend.createDynObjWriter(*m_pLinker);
93  m_pExecWriter    = m_LDBackend.createExecWriter(*m_pLinker);
94  m_pGroupReader   = new GroupReader(m_Module, *m_pObjectReader,
95                                     *m_pDynObjReader, *m_pArchiveReader);
96
97  // initialize RelocationFactory
98  m_LDBackend.initRelocFactory(*m_pLinker);
99
100  // initialize BranchIslandFactory
101  m_LDBackend.initBRIslandFactory();
102
103  // initialize StubFactory
104  m_LDBackend.initStubFactory();
105
106  // initialize target stubs
107  m_LDBackend.initTargetStubs(*m_pLinker);
108  return true;
109}
110
111/// initStdSections - initialize standard sections
112bool ObjectLinker::initStdSections()
113{
114  ObjectBuilder builder(m_Config, m_Module);
115
116  // initialize standard sections
117  if (!m_LDBackend.initStdSections(builder))
118    return false;
119
120  // initialize target-dependent sections
121  m_LDBackend.initTargetSections(m_Module, builder);
122
123  return true;
124}
125
126void ObjectLinker::normalize()
127{
128  // -----  set up inputs  ----- //
129  Module::input_iterator input, inEnd = m_Module.input_end();
130  for (input = m_Module.input_begin(); input!=inEnd; ++input) {
131    // is a group node
132    if (isGroup(input)) {
133      getGroupReader()->readGroup(input, m_InputBuilder, m_Config);
134      continue;
135    }
136
137    // already got type - for example, bitcode or external OIR (object
138    // intermediate representation)
139    if ((*input)->type() == Input::Script ||
140        (*input)->type() == Input::Archive ||
141        (*input)->type() == Input::External)
142      continue;
143
144    if (Input::Object == (*input)->type()) {
145      m_Module.getObjectList().push_back(*input);
146      continue;
147    }
148
149    if (Input::DynObj == (*input)->type()) {
150      m_Module.getLibraryList().push_back(*input);
151      continue;
152    }
153
154    // is a relocatable object file
155    if (getObjectReader()->isMyFormat(**input)) {
156      (*input)->setType(Input::Object);
157      getObjectReader()->readHeader(**input);
158      getObjectReader()->readSections(**input);
159      getObjectReader()->readSymbols(**input);
160      m_Module.getObjectList().push_back(*input);
161    }
162    // is a shared object file
163    else if (getDynObjReader()->isMyFormat(**input)) {
164      (*input)->setType(Input::DynObj);
165      getDynObjReader()->readHeader(**input);
166      getDynObjReader()->readSymbols(**input);
167      m_Module.getLibraryList().push_back(*input);
168    }
169    // is an archive
170    else if (getArchiveReader()->isMyFormat(**input)) {
171      (*input)->setType(Input::Archive);
172      Archive archive(**input, m_InputBuilder);
173      getArchiveReader()->readArchive(archive);
174      if(archive.numOfObjectMember() > 0) {
175        m_Module.getInputTree().merge<InputTree::Inclusive>(input,
176                                                            archive.inputs());
177      }
178    }
179    else {
180      fatal(diag::err_unrecognized_input_file) << (*input)->path()
181                                               << m_Config.triple().str();
182    }
183  } // end of for
184}
185
186bool ObjectLinker::linkable() const
187{
188  // check we have input and output files
189  if (m_Module.getInputTree().empty()) {
190    error(diag::err_no_inputs);
191    return false;
192  }
193
194  // can not mix -static with shared objects
195  Module::const_lib_iterator lib, libEnd = m_Module.lib_end();
196  for (lib = m_Module.lib_begin(); lib != libEnd; ++lib) {
197    if((*lib)->attribute()->isStatic()) {
198      error(diag::err_mixed_shared_static_objects)
199                                      << (*lib)->name() << (*lib)->path();
200      return false;
201    }
202  }
203
204  // can not mix -r with shared objects
205  return true;
206}
207
208/// readRelocations - read all relocation entries
209///
210/// All symbols should be read and resolved before this function.
211bool ObjectLinker::readRelocations()
212{
213  // Bitcode is read by the other path. This function reads relocation sections
214  // in object files.
215  mcld::InputTree::bfs_iterator input, inEnd = m_Module.getInputTree().bfs_end();
216  for (input=m_Module.getInputTree().bfs_begin(); input!=inEnd; ++input) {
217    if ((*input)->type() == Input::Object && (*input)->hasMemArea()) {
218      if (!getObjectReader()->readRelocations(**input))
219        return false;
220    }
221    // ignore the other kinds of files.
222  }
223  return true;
224}
225
226/// mergeSections - put allinput sections into output sections
227bool ObjectLinker::mergeSections()
228{
229  ObjectBuilder builder(m_Config, m_Module);
230  Module::obj_iterator obj, objEnd = m_Module.obj_end();
231  for (obj = m_Module.obj_begin(); obj != objEnd; ++obj) {
232    LDContext::sect_iterator sect, sectEnd = (*obj)->context()->sectEnd();
233    for (sect = (*obj)->context()->sectBegin(); sect != sectEnd; ++sect) {
234      switch ((*sect)->kind()) {
235        // Some *INPUT sections should not be merged.
236        case LDFileFormat::Ignore:
237        case LDFileFormat::Null:
238        case LDFileFormat::Relocation:
239        case LDFileFormat::NamePool:
240        case LDFileFormat::Group:
241        case LDFileFormat::StackNote:
242          // skip
243          continue;
244        case LDFileFormat::Target:
245          if (!m_LDBackend.mergeSection(m_Module, **sect)) {
246            error(diag::err_cannot_merge_section) << (*sect)->name()
247                                                  << (*obj)->name();
248            return false;
249          }
250          break;
251        case LDFileFormat::EhFrame: {
252          if (!(*sect)->hasEhFrame())
253            continue; // skip
254
255          if (!builder.MergeSection(**sect)) {
256            error(diag::err_cannot_merge_section) << (*sect)->name()
257                                                  << (*obj)->name();
258            return false;
259          }
260          break;
261        }
262        default: {
263          if (!(*sect)->hasSectionData())
264            continue; // skip
265
266          if (!builder.MergeSection(**sect)) {
267            error(diag::err_cannot_merge_section) << (*sect)->name()
268                                                  << (*obj)->name();
269            return false;
270          }
271          break;
272        }
273      } // end of switch
274    } // for each section
275  } // for each obj
276  return true;
277}
278
279/// addStandardSymbols - shared object and executable files need some
280/// standard symbols
281///   @return if there are some input symbols with the same name to the
282///   standard symbols, return false
283bool ObjectLinker::addStandardSymbols()
284{
285  // create and add section symbols for each output section
286  Module::iterator iter, iterEnd = m_Module.end();
287  for (iter = m_Module.begin(); iter != iterEnd; ++iter) {
288    m_Module.getSectionSymbolSet().add(**iter, m_Module.getNamePool());
289  }
290
291  return m_LDBackend.initStandardSymbols(*m_pLinker, m_Module);
292}
293
294/// addTargetSymbols - some targets, such as MIPS and ARM, need some
295/// target-dependent symbols
296///   @return if there are some input symbols with the same name to the
297///   target symbols, return false
298bool ObjectLinker::addTargetSymbols()
299{
300  m_LDBackend.initTargetSymbols(*m_pLinker);
301  return true;
302}
303
304bool ObjectLinker::scanRelocations()
305{
306  // apply all relocations of all inputs
307  Module::obj_iterator input, inEnd = m_Module.obj_end();
308  for (input = m_Module.obj_begin(); input != inEnd; ++input) {
309    LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd();
310    for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) {
311      // bypass the reloc section if
312      // 1. its section kind is changed to Ignore. (The target section is a
313      // discarded group section.)
314      // 2. it has no reloc data. (All symbols in the input relocs are in the
315      // discarded group sections)
316      if (LDFileFormat::Ignore == (*rs)->kind() || !(*rs)->hasRelocData())
317        continue;
318      RelocData::iterator reloc, rEnd = (*rs)->getRelocData()->end();
319      for (reloc = (*rs)->getRelocData()->begin(); reloc != rEnd; ++reloc) {
320        Relocation* relocation = llvm::cast<Relocation>(reloc);
321        // scan relocation
322        if (LinkerConfig::Object != m_Config.codeGenType()) {
323          m_LDBackend.scanRelocation(*relocation,
324                                     *m_pLinker,
325                                     m_Module,
326                                     *(*rs)->getLink());
327        }
328        else {
329          m_LDBackend.partialScanRelocation(*relocation,
330                                     *m_pLinker,
331                                     m_Module,
332                                     *(*rs)->getLink());
333        }
334      } // for all relocations
335    } // for all relocation section
336  } // for all inputs
337  return true;
338}
339
340/// prelayout - help backend to do some modification before layout
341bool ObjectLinker::prelayout()
342{
343  // finalize the section symbols, set their fragment reference and push them
344  // into output symbol table
345  Module::iterator iter, iterEnd = m_Module.end();
346  for (iter = m_Module.begin(); iter != iterEnd; ++iter) {
347    LDSection* section = *iter;
348    if (0x0 == section->size() || LDFileFormat::Relocation == section->kind())
349      continue;
350    m_Module.getSectionSymbolSet().finalize(
351                                           *section, m_Module.getSymbolTable());
352  }
353
354  m_LDBackend.preLayout(m_Module, *m_pLinker);
355
356  m_LDBackend.allocateCommonSymbols(m_Module);
357
358  /// check program interpreter - computer the name size of the runtime dyld
359  if (!m_pLinker->isStaticLink() &&
360      (LinkerConfig::Exec == m_Config.codeGenType() ||
361       m_Config.options().isPIE() ||
362       m_Config.options().hasDyld()))
363    m_LDBackend.sizeInterp();
364
365  /// measure NamePools - compute the size of name pool sections
366  /// In ELF, will compute  the size of.symtab, .strtab, .dynsym, .dynstr,
367  /// .hash and .shstrtab sections.
368  ///
369  /// dump all symbols and strings from FragmentLinker and build the format-dependent
370  /// hash table.
371  m_LDBackend.sizeNamePools(m_Module, m_pLinker->isStaticLink());
372
373  return true;
374}
375
376/// layout - linearly layout all output sections and reserve some space
377/// for GOT/PLT
378///   Because we do not support instruction relaxing in this early version,
379///   if there is a branch can not jump to its target, we return false
380///   directly
381bool ObjectLinker::layout()
382{
383  Layout layout;
384  return layout.layout(m_Module, m_LDBackend, m_Config);
385}
386
387/// prelayout - help backend to do some modification after layout
388bool ObjectLinker::postlayout()
389{
390  m_LDBackend.postLayout(m_Module, *m_pLinker);
391  return true;
392}
393
394/// finalizeSymbolValue - finalize the resolved symbol value.
395///   Before relocate(), after layout(), FragmentLinker should correct value of all
396///   symbol.
397bool ObjectLinker::finalizeSymbolValue()
398{
399  return m_pLinker->finalizeSymbols();
400}
401
402/// relocate - applying relocation entries and create relocation
403/// section in the output files
404/// Create relocation section, asking TargetLDBackend to
405/// read the relocation information into RelocationEntry
406/// and push_back into the relocation section
407bool ObjectLinker::relocation()
408{
409  return m_pLinker->applyRelocations();
410}
411
412/// emitOutput - emit the output file.
413bool ObjectLinker::emitOutput(MemoryArea& pOutput)
414{
415  switch(m_Config.codeGenType()) {
416    case LinkerConfig::Object:
417      getObjectWriter()->writeObject(m_Module, pOutput);
418      return true;
419    case LinkerConfig::DynObj:
420      getDynObjWriter()->writeDynObj(m_Module, pOutput);
421      return true;
422    case LinkerConfig::Exec:
423      getExecWriter()->writeExecutable(m_Module, pOutput);
424      return true;
425    default:
426      fatal(diag::unrecognized_output_file) << m_Config.codeGenType();
427  }
428  return false;
429}
430
431/// postProcessing - do modification after all processes
432bool ObjectLinker::postProcessing(MemoryArea& pOutput)
433{
434  m_pLinker->syncRelocationResult(pOutput);
435
436  // emit .eh_frame_hdr
437  // eh_frame_hdr should be emitted after syncRelocation, because eh_frame_hdr
438  // needs FDE PC value, which will be corrected at syncRelocation
439  m_LDBackend.postProcessing(*m_pLinker, pOutput);
440  return true;
441}
442
443