Linker.cpp revision 87f34658dec9097d987d254a990ea7f311bfc95f
1//===- Linker.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/Linker.h>
10#include <mcld/LinkerConfig.h>
11#include <mcld/Module.h>
12#include <mcld/IRBuilder.h>
13
14#include <mcld/Support/MsgHandling.h>
15#include <mcld/Support/TargetRegistry.h>
16#include <mcld/Support/FileHandle.h>
17#include <mcld/Support/FileOutputBuffer.h>
18#include <mcld/Support/raw_ostream.h>
19
20#include <mcld/Object/ObjectLinker.h>
21#include <mcld/MC/InputBuilder.h>
22#include <mcld/Target/TargetLDBackend.h>
23#include <mcld/LD/LDSection.h>
24#include <mcld/LD/LDSymbol.h>
25#include <mcld/LD/SectionData.h>
26#include <mcld/LD/RelocData.h>
27#include <mcld/LD/ObjectWriter.h>
28#include <mcld/Fragment/Relocation.h>
29#include <mcld/Fragment/FragmentRef.h>
30
31#include <llvm/ADT/OwningPtr.h>
32
33#include <cassert>
34
35using namespace mcld;
36
37Linker::Linker()
38  : m_pConfig(NULL), m_pIRBuilder(NULL),
39    m_pTarget(NULL), m_pBackend(NULL), m_pObjLinker(NULL) {
40}
41
42Linker::~Linker()
43{
44  reset();
45}
46
47/// emulate - To set up target-dependent options and default linker script.
48/// Follow GNU ld quirks.
49bool Linker::emulate(LinkerScript& pScript, LinkerConfig& pConfig)
50{
51  m_pConfig = &pConfig;
52
53  if (!initTarget())
54    return false;
55
56  if (!initBackend())
57    return false;
58
59  if (!initOStream())
60    return false;
61
62  if (!initEmulator(pScript))
63    return false;
64
65  return true;
66}
67
68bool Linker::link(Module& pModule, IRBuilder& pBuilder)
69{
70  if (!normalize(pModule, pBuilder))
71    return false;
72
73  if (!resolve(pModule))
74    return false;
75
76  return layout();
77}
78
79/// normalize - to convert the command line language to the input tree.
80bool Linker::normalize(Module& pModule, IRBuilder& pBuilder)
81{
82  assert(NULL != m_pConfig);
83
84  m_pIRBuilder = &pBuilder;
85
86  m_pObjLinker = new ObjectLinker(*m_pConfig, *m_pBackend);
87
88  // 2. - initialize ObjectLinker
89  if (!m_pObjLinker->initialize(pModule, pBuilder))
90    return false;
91
92  // 3. - initialize output's standard sections
93  if (!m_pObjLinker->initStdSections())
94    return false;
95
96  if (!Diagnose())
97    return false;
98
99  // 4. - normalize the input tree
100  //   read out sections and symbol/string tables (from the files) and
101  //   set them in Module. When reading out the symbol, resolve their symbols
102  //   immediately and set their ResolveInfo (i.e., Symbol Resolution).
103  m_pObjLinker->normalize();
104
105  if (m_pConfig->options().trace()) {
106    static int counter = 0;
107    mcld::outs() << "** name\ttype\tpath\tsize (" << pModule.getInputTree().size() << ")\n";
108    InputTree::const_dfs_iterator input, inEnd = pModule.getInputTree().dfs_end();
109    for (input=pModule.getInputTree().dfs_begin(); input!=inEnd; ++input) {
110      mcld::outs() << counter++ << " *  " << (*input)->name();
111      switch((*input)->type()) {
112      case Input::Archive:
113        mcld::outs() << "\tarchive\t(";
114        break;
115      case Input::Object:
116        mcld::outs() << "\tobject\t(";
117        break;
118      case Input::DynObj:
119        mcld::outs() << "\tshared\t(";
120        break;
121      case Input::Script:
122        mcld::outs() << "\tscript\t(";
123        break;
124      case Input::External:
125        mcld::outs() << "\textern\t(";
126        break;
127      default:
128        unreachable(diag::err_cannot_trace_file) << (*input)->type()
129                                                 << (*input)->name()
130                                                 << (*input)->path();
131      }
132      mcld::outs() << (*input)->path() << ")\n";
133    }
134  }
135
136  // 5. - set up code position
137  if (LinkerConfig::DynObj == m_pConfig->codeGenType() ||
138      m_pConfig->options().isPIE()) {
139    m_pConfig->setCodePosition(LinkerConfig::Independent);
140  }
141  else if (pModule.getLibraryList().empty()) {
142    // If the output is dependent on its loaded address, and it does not need
143    // to call outside functions, then we can treat the output static dependent
144    // and perform better optimizations.
145    m_pConfig->setCodePosition(LinkerConfig::StaticDependent);
146
147    if (LinkerConfig::Exec == m_pConfig->codeGenType()) {
148      // Since the output is static dependent, there should not have any undefined
149      // references in the output module.
150      m_pConfig->options().setNoUndefined();
151    }
152  }
153  else {
154    m_pConfig->setCodePosition(LinkerConfig::DynamicDependent);
155  }
156
157  if (!m_pObjLinker->linkable())
158    return Diagnose();
159
160  return true;
161}
162
163bool Linker::resolve(Module& pModule)
164{
165  assert(NULL != m_pConfig);
166  assert(m_pObjLinker != NULL);
167
168  // 6. - read all relocation entries from input files
169  //   For all relocation sections of each input file (in the tree),
170  //   read out reloc entry info from the object file and accordingly
171  //   initiate their reloc entries in SectOrRelocData of LDSection.
172  //
173  //   To collect all edges in the reference graph.
174  m_pObjLinker->readRelocations();
175
176
177  // 7. - data stripping optimizations
178  m_pObjLinker->dataStrippingOpt();
179
180  // 8. - merge all sections
181  //   Push sections into Module's SectionTable.
182  //   Merge sections that have the same name.
183  //   Maintain them as fragments in the section.
184  //
185  //   To merge nodes of the reference graph.
186  if (!m_pObjLinker->mergeSections())
187    return false;
188
189  // 9.a - add symbols to output
190  //  After all input symbols have been resolved, add them to output symbol
191  //  table at once
192  m_pObjLinker->addSymbolsToOutput(pModule);
193
194  // 9.b - allocateCommonSymbols
195  //   Allocate fragments for common symbols to the corresponding sections.
196  if (!m_pObjLinker->allocateCommonSymbols())
197    return false;
198
199  return true;
200}
201
202bool Linker::layout()
203{
204  assert(NULL != m_pConfig && NULL != m_pObjLinker);
205
206  // 10. - add standard symbols, target-dependent symbols and script symbols
207  // m_pObjLinker->addUndefSymbols();
208  if (!m_pObjLinker->addStandardSymbols() ||
209      !m_pObjLinker->addTargetSymbols() ||
210      !m_pObjLinker->addScriptSymbols())
211    return false;
212
213  // 11. - scan all relocation entries by output symbols.
214  //   reserve GOT space for layout.
215  //   the space info is needed by pre-layout to compute the section size
216  m_pObjLinker->scanRelocations();
217
218  // 12.a - init relaxation stuff.
219  m_pObjLinker->initStubs();
220
221  // 12.b - pre-layout
222  m_pObjLinker->prelayout();
223
224  // 12.c - linear layout
225  //   Decide which sections will be left in. Sort the sections according to
226  //   a given order. Then, create program header accordingly.
227  //   Finally, set the offset for sections (@ref LDSection)
228  //   according to the new order.
229  m_pObjLinker->layout();
230
231  // 12.d - post-layout (create segment, instruction relaxing)
232  m_pObjLinker->postlayout();
233
234  // 13. - finalize symbol value
235  m_pObjLinker->finalizeSymbolValue();
236
237  // 14. - apply relocations
238  m_pObjLinker->relocation();
239
240  if (!Diagnose())
241    return false;
242  return true;
243}
244
245bool Linker::emit(FileOutputBuffer& pOutput)
246{
247  // 15. - write out output
248  m_pObjLinker->emitOutput(pOutput);
249
250  // 16. - post processing
251  m_pObjLinker->postProcessing(pOutput);
252
253  if (!Diagnose())
254    return false;
255
256  return true;
257}
258
259bool Linker::emit(const Module& pModule, const std::string& pPath)
260{
261  FileHandle file;
262  FileHandle::Permission perm;
263  switch (m_pConfig->codeGenType()) {
264    case mcld::LinkerConfig::Unknown:
265    case mcld::LinkerConfig::Object:
266      perm = mcld::FileHandle::Permission(0x644);
267      break;
268    case mcld::LinkerConfig::DynObj:
269    case mcld::LinkerConfig::Exec:
270    case mcld::LinkerConfig::Binary:
271      perm = mcld::FileHandle::Permission(0x755);
272      break;
273    default: assert(0 && "Unknown file type");
274  }
275
276  if (!file.open(pPath,
277            FileHandle::ReadWrite | FileHandle::Truncate | FileHandle::Create,
278            perm)) {
279    error(diag::err_cannot_open_output_file) << "Linker::emit()" << pPath;
280    return false;
281  }
282
283  llvm::OwningPtr<FileOutputBuffer> output;
284  FileOutputBuffer::create(file,
285                           m_pObjLinker->getWriter()->getOutputSize(pModule),
286                           output);
287
288  bool result = emit(*output.get());
289  file.close();
290  return result;
291}
292
293bool Linker::emit(const Module& pModule, int pFileDescriptor)
294{
295  FileHandle file;
296  file.delegate(pFileDescriptor);
297
298  llvm::OwningPtr<FileOutputBuffer> output;
299  FileOutputBuffer::create(file,
300                           m_pObjLinker->getWriter()->getOutputSize(pModule),
301                           output);
302
303  bool result = emit(*output.get());
304
305  return result;
306}
307
308bool Linker::reset()
309{
310  m_pConfig = NULL;
311  m_pIRBuilder = NULL;
312  m_pTarget = NULL;
313
314  // Because llvm::iplist will touch the removed node, we must clear
315  // RelocData before deleting target backend.
316  RelocData::Clear();
317  SectionData::Clear();
318  EhFrame::Clear();
319
320  delete m_pBackend;
321  m_pBackend = NULL;
322
323  delete m_pObjLinker;
324  m_pObjLinker = NULL;
325
326  LDSection::Clear();
327  LDSymbol::Clear();
328  FragmentRef::Clear();
329  Relocation::Clear();
330  return true;
331}
332
333bool Linker::initTarget()
334{
335  assert(NULL != m_pConfig);
336
337  std::string error;
338  llvm::Triple triple(m_pConfig->targets().triple());
339
340  m_pTarget = mcld::TargetRegistry::lookupTarget(m_pConfig->targets().getArch(),
341                                                 triple, error);
342  m_pConfig->targets().setTriple(triple);
343
344  if (NULL == m_pTarget) {
345    fatal(diag::fatal_cannot_init_target) << triple.str() << error;
346    return false;
347  }
348  return true;
349}
350
351bool Linker::initBackend()
352{
353  assert(NULL != m_pTarget);
354  m_pBackend = m_pTarget->createLDBackend(*m_pConfig);
355  if (NULL == m_pBackend) {
356    fatal(diag::fatal_cannot_init_backend) << m_pConfig->targets().triple().str();
357    return false;
358  }
359  return true;
360}
361
362bool Linker::initOStream()
363{
364  assert(NULL != m_pConfig);
365
366  mcld::outs().setColor(m_pConfig->options().color());
367  mcld::errs().setColor(m_pConfig->options().color());
368
369  return true;
370}
371
372bool Linker::initEmulator(LinkerScript& pScript)
373{
374  assert(NULL != m_pTarget && NULL != m_pConfig);
375  return m_pTarget->emulate(pScript, *m_pConfig);
376}
377
378