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