GNULDBackend.cpp revision 87f34658dec9097d987d254a990ea7f311bfc95f
1//===- GNULDBackend.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/Target/GNULDBackend.h>
10
11#include <string>
12#include <cstring>
13#include <cassert>
14#include <vector>
15#include <algorithm>
16#include <map>
17
18#include <mcld/Module.h>
19#include <mcld/LinkerConfig.h>
20#include <mcld/LinkerScript.h>
21#include <mcld/IRBuilder.h>
22#include <mcld/InputTree.h>
23#include <mcld/Config/Config.h>
24#include <mcld/ADT/SizeTraits.h>
25#include <mcld/LD/LDSymbol.h>
26#include <mcld/LD/LDContext.h>
27#include <mcld/LD/EhFrame.h>
28#include <mcld/LD/EhFrameHdr.h>
29#include <mcld/LD/RelocData.h>
30#include <mcld/LD/RelocationFactory.h>
31#include <mcld/LD/BranchIslandFactory.h>
32#include <mcld/LD/ELFSegmentFactory.h>
33#include <mcld/LD/ELFSegment.h>
34#include <mcld/LD/StubFactory.h>
35#include <mcld/LD/ELFFileFormat.h>
36#include <mcld/LD/ELFObjectFileFormat.h>
37#include <mcld/LD/ELFDynObjFileFormat.h>
38#include <mcld/LD/ELFExecFileFormat.h>
39#include <mcld/Target/ELFAttribute.h>
40#include <mcld/Target/ELFDynamic.h>
41#include <mcld/Target/GNUInfo.h>
42#include <mcld/Support/FileOutputBuffer.h>
43#include <mcld/Support/MsgHandling.h>
44#include <mcld/Object/ObjectBuilder.h>
45#include <mcld/Object/SectionMap.h>
46#include <mcld/Script/RpnEvaluator.h>
47#include <mcld/Script/Operand.h>
48#include <mcld/Script/OutputSectDesc.h>
49#include <mcld/Fragment/FillFragment.h>
50#include <mcld/MC/Attribute.h>
51
52#include <llvm/Support/Host.h>
53
54namespace {
55
56//===--------------------------------------------------------------------===//
57// non-member functions
58//===----------------------------------------------------------------------===//
59static const std::string simple_c_identifier_allowed_chars =
60  "0123456789"
61  "ABCDEFGHIJKLMNOPWRSTUVWXYZ"
62  "abcdefghijklmnopqrstuvwxyz"
63  "_";
64
65/// isCIdentifier - return if the pName is a valid C identifier
66static bool isCIdentifier(const std::string& pName)
67{
68  return (pName.find_first_not_of(simple_c_identifier_allowed_chars)
69              == std::string::npos);
70}
71
72} // anonymous namespace
73
74using namespace mcld;
75
76//===----------------------------------------------------------------------===//
77// GNULDBackend
78//===----------------------------------------------------------------------===//
79GNULDBackend::GNULDBackend(const LinkerConfig& pConfig, GNUInfo* pInfo)
80  : TargetLDBackend(pConfig),
81    m_pObjectReader(NULL),
82    m_pDynObjFileFormat(NULL),
83    m_pExecFileFormat(NULL),
84    m_pObjectFileFormat(NULL),
85    m_pInfo(pInfo),
86    m_pELFSegmentTable(NULL),
87    m_pBRIslandFactory(NULL),
88    m_pStubFactory(NULL),
89    m_pEhFrameHdr(NULL),
90    m_pAttribute(NULL),
91    m_bHasTextRel(false),
92    m_bHasStaticTLS(false),
93    f_pPreInitArrayStart(NULL),
94    f_pPreInitArrayEnd(NULL),
95    f_pInitArrayStart(NULL),
96    f_pInitArrayEnd(NULL),
97    f_pFiniArrayStart(NULL),
98    f_pFiniArrayEnd(NULL),
99    f_pStack(NULL),
100    f_pDynamic(NULL),
101    f_pTDATA(NULL),
102    f_pTBSS(NULL),
103    f_pExecutableStart(NULL),
104    f_pEText(NULL),
105    f_p_EText(NULL),
106    f_p__EText(NULL),
107    f_pEData(NULL),
108    f_p_EData(NULL),
109    f_pBSSStart(NULL),
110    f_pEnd(NULL),
111    f_p_End(NULL) {
112  m_pELFSegmentTable = new ELFSegmentFactory();
113  m_pSymIndexMap = new HashTableType(1024);
114  m_pAttribute = new ELFAttribute(*this, pConfig);
115}
116
117GNULDBackend::~GNULDBackend()
118{
119  delete m_pELFSegmentTable;
120  delete m_pInfo;
121  delete m_pDynObjFileFormat;
122  delete m_pExecFileFormat;
123  delete m_pObjectFileFormat;
124  delete m_pSymIndexMap;
125  delete m_pEhFrameHdr;
126  delete m_pAttribute;
127  delete m_pBRIslandFactory;
128  delete m_pStubFactory;
129}
130
131size_t GNULDBackend::sectionStartOffset() const
132{
133  if (LinkerConfig::Binary == config().codeGenType())
134    return 0x0;
135
136  switch (config().targets().bitclass()) {
137    case 32u:
138      return sizeof(llvm::ELF::Elf32_Ehdr) +
139             elfSegmentTable().size() * sizeof(llvm::ELF::Elf32_Phdr);
140    case 64u:
141      return sizeof(llvm::ELF::Elf64_Ehdr) +
142             elfSegmentTable().size() * sizeof(llvm::ELF::Elf64_Phdr);
143    default:
144      fatal(diag::unsupported_bitclass) << config().targets().triple().str()
145                                        << config().targets().bitclass();
146      return 0;
147  }
148}
149
150uint64_t GNULDBackend::getSegmentStartAddr(const LinkerScript& pScript) const
151{
152  LinkerScript::AddressMap::const_iterator mapping =
153    pScript.addressMap().find(".text");
154  if (pScript.addressMap().end() != mapping)
155    return mapping.getEntry()->value();
156  else if (config().isCodeIndep())
157    return 0x0;
158  else
159    return m_pInfo->defaultTextSegmentAddr();
160}
161
162GNUArchiveReader*
163GNULDBackend::createArchiveReader(Module& pModule)
164{
165  assert(NULL != m_pObjectReader);
166  return new GNUArchiveReader(pModule, *m_pObjectReader);
167}
168
169ELFObjectReader* GNULDBackend::createObjectReader(IRBuilder& pBuilder)
170{
171  m_pObjectReader = new ELFObjectReader(*this, pBuilder, config());
172  return m_pObjectReader;
173}
174
175ELFDynObjReader* GNULDBackend::createDynObjReader(IRBuilder& pBuilder)
176{
177  return new ELFDynObjReader(*this, pBuilder, config());
178}
179
180ELFBinaryReader* GNULDBackend::createBinaryReader(IRBuilder& pBuilder)
181{
182  return new ELFBinaryReader(pBuilder, config());
183}
184
185ELFObjectWriter* GNULDBackend::createWriter()
186{
187  return new ELFObjectWriter(*this, config());
188}
189
190bool GNULDBackend::initStdSections(ObjectBuilder& pBuilder)
191{
192  switch (config().codeGenType()) {
193    case LinkerConfig::DynObj: {
194      if (NULL == m_pDynObjFileFormat)
195        m_pDynObjFileFormat = new ELFDynObjFileFormat();
196      m_pDynObjFileFormat->initStdSections(pBuilder,
197                                           config().targets().bitclass());
198      return true;
199    }
200    case LinkerConfig::Exec:
201    case LinkerConfig::Binary: {
202      if (NULL == m_pExecFileFormat)
203        m_pExecFileFormat = new ELFExecFileFormat();
204      m_pExecFileFormat->initStdSections(pBuilder,
205                                         config().targets().bitclass());
206      return true;
207    }
208    case LinkerConfig::Object: {
209      if (NULL == m_pObjectFileFormat)
210        m_pObjectFileFormat = new ELFObjectFileFormat();
211      m_pObjectFileFormat->initStdSections(pBuilder,
212                                           config().targets().bitclass());
213      return true;
214    }
215    default:
216      fatal(diag::unrecognized_output_file) << config().codeGenType();
217      return false;
218  }
219}
220
221/// initStandardSymbols - define and initialize standard symbols.
222/// This function is called after section merging but before read relocations.
223bool GNULDBackend::initStandardSymbols(IRBuilder& pBuilder,
224                                       Module& pModule)
225{
226  if (LinkerConfig::Object == config().codeGenType())
227    return true;
228
229  // GNU extension: define __start and __stop symbols for the sections whose
230  // name can be presented as C symbol
231  // ref: GNU gold, Layout::define_section_symbols
232  Module::iterator iter, iterEnd = pModule.end();
233  for (iter = pModule.begin(); iter != iterEnd; ++iter) {
234    LDSection* section = *iter;
235
236    switch (section->kind()) {
237      case LDFileFormat::Relocation:
238        continue;
239      case LDFileFormat::EhFrame:
240        if (!section->hasEhFrame())
241          continue;
242        break;
243      default:
244        if (!section->hasSectionData())
245          continue;
246        break;
247    } // end of switch
248
249    if (isCIdentifier(section->name())) {
250      std::string start_name = "__start_" + section->name();
251      FragmentRef* start_fragref = FragmentRef::Create(
252                                       section->getSectionData()->front(), 0x0);
253      pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
254                                                    start_name,
255                                                    ResolveInfo::NoType,
256                                                    ResolveInfo::Define,
257                                                    ResolveInfo::Global,
258                                                    0x0, // size
259                                                    0x0, // value
260                                                    start_fragref, // FragRef
261                                                    ResolveInfo::Default);
262
263      std::string stop_name = "__stop_" + section->name();
264      FragmentRef* stop_fragref = FragmentRef::Create(
265                           section->getSectionData()->front(), section->size());
266      pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
267                                                    stop_name,
268                                                    ResolveInfo::NoType,
269                                                    ResolveInfo::Define,
270                                                    ResolveInfo::Global,
271                                                    0x0, // size
272                                                    0x0, // value
273                                                    stop_fragref, // FragRef
274                                                    ResolveInfo::Default);
275    }
276  }
277
278  ELFFileFormat* file_format = getOutputFormat();
279
280  // -----  section symbols  ----- //
281  // .preinit_array
282  FragmentRef* preinit_array = NULL;
283  if (file_format->hasPreInitArray()) {
284    preinit_array = FragmentRef::Create(
285                   file_format->getPreInitArray().getSectionData()->front(),
286                   0x0);
287  }
288  else {
289    preinit_array = FragmentRef::Null();
290  }
291  f_pPreInitArrayStart =
292     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
293                                             "__preinit_array_start",
294                                             ResolveInfo::NoType,
295                                             ResolveInfo::Define,
296                                             ResolveInfo::Global,
297                                             0x0, // size
298                                             0x0, // value
299                                             preinit_array, // FragRef
300                                             ResolveInfo::Hidden);
301  f_pPreInitArrayEnd =
302     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
303                                             "__preinit_array_end",
304                                             ResolveInfo::NoType,
305                                             ResolveInfo::Define,
306                                             ResolveInfo::Global,
307                                             0x0, // size
308                                             0x0, // value
309                                             FragmentRef::Null(), // FragRef
310                                             ResolveInfo::Hidden);
311
312  // .init_array
313  FragmentRef* init_array = NULL;
314  if (file_format->hasInitArray()) {
315    init_array = FragmentRef::Create(
316                      file_format->getInitArray().getSectionData()->front(),
317                      0x0);
318  }
319  else {
320    init_array = FragmentRef::Null();
321  }
322
323  f_pInitArrayStart =
324     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
325                                             "__init_array_start",
326                                             ResolveInfo::NoType,
327                                             ResolveInfo::Define,
328                                             ResolveInfo::Global,
329                                             0x0, // size
330                                             0x0, // value
331                                             init_array, // FragRef
332                                             ResolveInfo::Hidden);
333  f_pInitArrayEnd =
334     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
335                                             "__init_array_end",
336                                             ResolveInfo::NoType,
337                                             ResolveInfo::Define,
338                                             ResolveInfo::Global,
339                                             0x0, // size
340                                             0x0, // value
341                                             init_array, // FragRef
342                                             ResolveInfo::Hidden);
343
344  // .fini_array
345  FragmentRef* fini_array = NULL;
346  if (file_format->hasFiniArray()) {
347    fini_array = FragmentRef::Create(
348                     file_format->getFiniArray().getSectionData()->front(),
349                     0x0);
350  }
351  else {
352    fini_array = FragmentRef::Null();
353  }
354
355  f_pFiniArrayStart =
356     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
357                                             "__fini_array_start",
358                                             ResolveInfo::NoType,
359                                             ResolveInfo::Define,
360                                             ResolveInfo::Global,
361                                             0x0, // size
362                                             0x0, // value
363                                             fini_array, // FragRef
364                                             ResolveInfo::Hidden);
365  f_pFiniArrayEnd =
366     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
367                                             "__fini_array_end",
368                                             ResolveInfo::NoType,
369                                             ResolveInfo::Define,
370                                             ResolveInfo::Global,
371                                             0x0, // size
372                                             0x0, // value
373                                             fini_array, // FragRef
374                                             ResolveInfo::Hidden);
375
376  // .stack
377  FragmentRef* stack = NULL;
378  if (file_format->hasStack()) {
379    stack = FragmentRef::Create(
380                          file_format->getStack().getSectionData()->front(),
381                          0x0);
382  }
383  else {
384    stack = FragmentRef::Null();
385  }
386
387  f_pStack =
388     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
389                                             "__stack",
390                                             ResolveInfo::NoType,
391                                             ResolveInfo::Define,
392                                             ResolveInfo::Global,
393                                             0x0, // size
394                                             0x0, // value
395                                             stack, // FragRef
396                                             ResolveInfo::Hidden);
397
398  // _DYNAMIC
399  // TODO: add SectionData for .dynamic section, and then we can get the correct
400  // symbol section index for _DYNAMIC. Now it will be ABS.
401  f_pDynamic =
402     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
403                                                   "_DYNAMIC",
404                                                   ResolveInfo::Object,
405                                                   ResolveInfo::Define,
406                                                   ResolveInfo::Local,
407                                                   0x0, // size
408                                                   0x0, // value
409                                                   FragmentRef::Null(), // FragRef
410                                                   ResolveInfo::Hidden);
411
412  // -----  segment symbols  ----- //
413  f_pExecutableStart =
414     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
415                                             "__executable_start",
416                                             ResolveInfo::NoType,
417                                             ResolveInfo::Define,
418                                             ResolveInfo::Absolute,
419                                             0x0, // size
420                                             0x0, // value
421                                             FragmentRef::Null(), // FragRef
422                                             ResolveInfo::Default);
423  f_pEText =
424     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
425                                             "etext",
426                                             ResolveInfo::NoType,
427                                             ResolveInfo::Define,
428                                             ResolveInfo::Absolute,
429                                             0x0, // size
430                                             0x0, // value
431                                             FragmentRef::Null(), // FragRef
432                                             ResolveInfo::Default);
433  f_p_EText =
434     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
435                                             "_etext",
436                                             ResolveInfo::NoType,
437                                             ResolveInfo::Define,
438                                             ResolveInfo::Absolute,
439                                             0x0, // size
440                                             0x0, // value
441                                             FragmentRef::Null(), // FragRef
442                                             ResolveInfo::Default);
443  f_p__EText =
444     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
445                                             "__etext",
446                                             ResolveInfo::NoType,
447                                             ResolveInfo::Define,
448                                             ResolveInfo::Absolute,
449                                             0x0, // size
450                                             0x0, // value
451                                             FragmentRef::Null(), // FragRef
452                                             ResolveInfo::Default);
453  f_pEData =
454     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
455                                             "edata",
456                                             ResolveInfo::NoType,
457                                             ResolveInfo::Define,
458                                             ResolveInfo::Absolute,
459                                             0x0, // size
460                                             0x0, // value
461                                             FragmentRef::Null(), // FragRef
462                                             ResolveInfo::Default);
463
464  f_pEnd =
465     pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>(
466                                             "end",
467                                             ResolveInfo::NoType,
468                                             ResolveInfo::Define,
469                                             ResolveInfo::Absolute,
470                                             0x0, // size
471                                             0x0, // value
472                                             FragmentRef::Null(), // FragRef
473                                             ResolveInfo::Default);
474
475  // _edata is defined forcefully.
476  // @ref Google gold linker: defstd.cc: 186
477  f_p_EData =
478     pBuilder.AddSymbol<IRBuilder::Force, IRBuilder::Resolve>(
479                                             "_edata",
480                                             ResolveInfo::NoType,
481                                             ResolveInfo::Define,
482                                             ResolveInfo::Absolute,
483                                             0x0, // size
484                                             0x0, // value
485                                             FragmentRef::Null(), // FragRef
486                                             ResolveInfo::Default);
487
488  // __bss_start is defined forcefully.
489  // @ref Google gold linker: defstd.cc: 214
490  f_pBSSStart =
491     pBuilder.AddSymbol<IRBuilder::Force, IRBuilder::Resolve>(
492                                             "__bss_start",
493                                             ResolveInfo::NoType,
494                                             ResolveInfo::Define,
495                                             ResolveInfo::Absolute,
496                                             0x0, // size
497                                             0x0, // value
498                                             FragmentRef::Null(), // FragRef
499                                             ResolveInfo::Default);
500
501  // _end is defined forcefully.
502  // @ref Google gold linker: defstd.cc: 228
503  f_p_End =
504     pBuilder.AddSymbol<IRBuilder::Force, IRBuilder::Resolve>(
505                                             "_end",
506                                             ResolveInfo::NoType,
507                                             ResolveInfo::Define,
508                                             ResolveInfo::Absolute,
509                                             0x0, // size
510                                             0x0, // value
511                                             FragmentRef::Null(), // FragRef
512                                             ResolveInfo::Default);
513
514  return true;
515}
516
517bool GNULDBackend::finalizeStandardSymbols()
518{
519  if (LinkerConfig::Object == config().codeGenType())
520    return true;
521
522  ELFFileFormat* file_format = getOutputFormat();
523
524  // -----  section symbols  ----- //
525  if (NULL != f_pPreInitArrayStart) {
526    if (!f_pPreInitArrayStart->hasFragRef()) {
527      f_pPreInitArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute);
528      f_pPreInitArrayStart->setValue(0x0);
529    }
530  }
531
532  if (NULL != f_pPreInitArrayEnd) {
533    if (f_pPreInitArrayEnd->hasFragRef()) {
534      f_pPreInitArrayEnd->setValue(f_pPreInitArrayEnd->value() +
535                                   file_format->getPreInitArray().size());
536    }
537    else {
538      f_pPreInitArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute);
539      f_pPreInitArrayEnd->setValue(0x0);
540    }
541  }
542
543  if (NULL != f_pInitArrayStart) {
544    if (!f_pInitArrayStart->hasFragRef()) {
545      f_pInitArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute);
546      f_pInitArrayStart->setValue(0x0);
547    }
548  }
549
550  if (NULL != f_pInitArrayEnd) {
551    if (f_pInitArrayEnd->hasFragRef()) {
552      f_pInitArrayEnd->setValue(f_pInitArrayEnd->value() +
553                                file_format->getInitArray().size());
554    }
555    else {
556      f_pInitArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute);
557      f_pInitArrayEnd->setValue(0x0);
558    }
559  }
560
561  if (NULL != f_pFiniArrayStart) {
562    if (!f_pFiniArrayStart->hasFragRef()) {
563      f_pFiniArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute);
564      f_pFiniArrayStart->setValue(0x0);
565    }
566  }
567
568  if (NULL != f_pFiniArrayEnd) {
569    if (f_pFiniArrayEnd->hasFragRef()) {
570      f_pFiniArrayEnd->setValue(f_pFiniArrayEnd->value() +
571                                file_format->getFiniArray().size());
572    }
573    else {
574      f_pFiniArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute);
575      f_pFiniArrayEnd->setValue(0x0);
576    }
577  }
578
579  if (NULL != f_pStack) {
580    if (!f_pStack->hasFragRef()) {
581      f_pStack->resolveInfo()->setBinding(ResolveInfo::Absolute);
582      f_pStack->setValue(0x0);
583    }
584  }
585
586  if (NULL != f_pDynamic) {
587    f_pDynamic->resolveInfo()->setBinding(ResolveInfo::Local);
588    f_pDynamic->setValue(file_format->getDynamic().addr());
589    f_pDynamic->setSize(file_format->getDynamic().size());
590  }
591
592  // -----  segment symbols  ----- //
593  if (NULL != f_pExecutableStart) {
594    ELFSegmentFactory::const_iterator exec_start =
595      elfSegmentTable().find(llvm::ELF::PT_LOAD, 0x0, 0x0);
596    if (elfSegmentTable().end() != exec_start) {
597      if (ResolveInfo::ThreadLocal != f_pExecutableStart->type()) {
598        f_pExecutableStart->setValue(f_pExecutableStart->value() +
599                                     (*exec_start)->vaddr());
600      }
601    }
602    else
603      f_pExecutableStart->setValue(0x0);
604  }
605
606  if (NULL != f_pEText || NULL != f_p_EText || NULL !=f_p__EText) {
607    ELFSegmentFactory::const_iterator etext =
608      elfSegmentTable().find(llvm::ELF::PT_LOAD,
609                             llvm::ELF::PF_X,
610                             llvm::ELF::PF_W);
611    if (elfSegmentTable().end() != etext) {
612      if (NULL != f_pEText && ResolveInfo::ThreadLocal != f_pEText->type()) {
613        f_pEText->setValue(f_pEText->value() +
614                           (*etext)->vaddr() +
615                           (*etext)->memsz());
616      }
617      if (NULL != f_p_EText && ResolveInfo::ThreadLocal != f_p_EText->type()) {
618        f_p_EText->setValue(f_p_EText->value() +
619                            (*etext)->vaddr() +
620                            (*etext)->memsz());
621      }
622      if (NULL != f_p__EText && ResolveInfo::ThreadLocal != f_p__EText->type()) {
623        f_p__EText->setValue(f_p__EText->value() +
624                            (*etext)->vaddr() +
625                            (*etext)->memsz());
626      }
627    }
628    else {
629      if (NULL != f_pEText)
630        f_pEText->setValue(0x0);
631      if (NULL != f_p_EText)
632        f_p_EText->setValue(0x0);
633      if (NULL != f_p__EText)
634        f_p__EText->setValue(0x0);
635    }
636  }
637
638  if (NULL != f_pEData || NULL != f_p_EData || NULL != f_pBSSStart ||
639      NULL != f_pEnd || NULL != f_p_End) {
640    ELFSegmentFactory::const_iterator edata =
641      elfSegmentTable().find(llvm::ELF::PT_LOAD, llvm::ELF::PF_W, 0x0);
642    if (elfSegmentTable().end() != edata) {
643      if (NULL != f_pEData && ResolveInfo::ThreadLocal != f_pEData->type()) {
644        f_pEData->setValue(f_pEData->value() +
645                           (*edata)->vaddr() +
646                           (*edata)->filesz());
647      }
648      if (NULL != f_p_EData && ResolveInfo::ThreadLocal != f_p_EData->type()) {
649        f_p_EData->setValue(f_p_EData->value() +
650                            (*edata)->vaddr() +
651                            (*edata)->filesz());
652      }
653      if (NULL != f_pBSSStart && ResolveInfo::ThreadLocal != f_pBSSStart->type()) {
654        f_pBSSStart->setValue(f_pBSSStart->value() +
655                              (*edata)->vaddr() +
656                              (*edata)->filesz());
657      }
658
659      if (NULL != f_pEnd && ResolveInfo::ThreadLocal != f_pEnd->type()) {
660        f_pEnd->setValue(f_pEnd->value() +
661                         (*edata)->vaddr() +
662                         (*edata)->memsz());
663      }
664      if (NULL != f_p_End && ResolveInfo::ThreadLocal != f_p_End->type()) {
665        f_p_End->setValue(f_p_End->value() +
666                          (*edata)->vaddr() +
667                          (*edata)->memsz());
668      }
669    }
670    else {
671      if (NULL != f_pEData)
672        f_pEData->setValue(0x0);
673      if (NULL != f_p_EData)
674        f_p_EData->setValue(0x0);
675      if (NULL != f_pBSSStart)
676        f_pBSSStart->setValue(0x0);
677
678      if (NULL != f_pEnd)
679        f_pEnd->setValue(0x0);
680      if (NULL != f_p_End)
681        f_p_End->setValue(0x0);
682    }
683  }
684
685  return true;
686}
687
688bool GNULDBackend::finalizeTLSSymbol(LDSymbol& pSymbol)
689{
690  // ignore if symbol has no fragRef
691  if (!pSymbol.hasFragRef())
692    return true;
693
694  // the value of a TLS symbol is the offset to the TLS segment
695  ELFSegmentFactory::iterator tls_seg =
696    elfSegmentTable().find(llvm::ELF::PT_TLS, llvm::ELF::PF_R, 0x0);
697  assert(tls_seg != elfSegmentTable().end());
698  uint64_t value = pSymbol.fragRef()->getOutputOffset();
699  uint64_t addr  = pSymbol.fragRef()->frag()->getParent()->getSection().addr();
700  pSymbol.setValue(value + addr - (*tls_seg)->vaddr());
701  return true;
702}
703
704ELFFileFormat* GNULDBackend::getOutputFormat()
705{
706  switch (config().codeGenType()) {
707    case LinkerConfig::DynObj:
708      assert(NULL != m_pDynObjFileFormat);
709      return m_pDynObjFileFormat;
710    case LinkerConfig::Exec:
711    case LinkerConfig::Binary:
712      assert(NULL != m_pExecFileFormat);
713      return m_pExecFileFormat;
714    case LinkerConfig::Object:
715      assert(NULL != m_pObjectFileFormat);
716      return m_pObjectFileFormat;
717    default:
718      fatal(diag::unrecognized_output_file) << config().codeGenType();
719      return NULL;
720  }
721}
722
723const ELFFileFormat* GNULDBackend::getOutputFormat() const
724{
725  switch (config().codeGenType()) {
726    case LinkerConfig::DynObj:
727      assert(NULL != m_pDynObjFileFormat);
728      return m_pDynObjFileFormat;
729    case LinkerConfig::Exec:
730    case LinkerConfig::Binary:
731      assert(NULL != m_pExecFileFormat);
732      return m_pExecFileFormat;
733    case LinkerConfig::Object:
734      assert(NULL != m_pObjectFileFormat);
735      return m_pObjectFileFormat;
736    default:
737      fatal(diag::unrecognized_output_file) << config().codeGenType();
738      return NULL;
739  }
740}
741
742/// sizeShstrtab - compute the size of .shstrtab
743void GNULDBackend::sizeShstrtab(Module& pModule)
744{
745  size_t shstrtab = 0;
746  // compute the size of .shstrtab section.
747  Module::const_iterator sect, sectEnd = pModule.end();
748  for (sect = pModule.begin(); sect != sectEnd; ++sect) {
749    shstrtab += (*sect)->name().size() + 1;
750  } // end of for
751  getOutputFormat()->getShStrTab().setSize(shstrtab);
752}
753
754/// sizeNamePools - compute the size of regular name pools
755/// In ELF executable files, regular name pools are .symtab, .strtab,
756/// .dynsym, .dynstr, .hash and .shstrtab.
757void GNULDBackend::sizeNamePools(Module& pModule)
758{
759  assert(LinkerConfig::Unset != config().codePosition());
760
761  // number of entries in symbol tables starts from 1 to hold the special entry
762  // at index 0 (STN_UNDEF). See ELF Spec Book I, p1-21.
763  size_t symtab = 1;
764  size_t dynsym = config().isCodeStatic()? 0 : 1;
765
766  // size of string tables starts from 1 to hold the null character in their
767  // first byte
768  size_t strtab   = 1;
769  size_t dynstr   = config().isCodeStatic()? 0 : 1;
770  size_t hash     = 0;
771  size_t gnuhash  = 0;
772
773  // number of local symbol in the .symtab and .dynsym
774  size_t symtab_local_cnt = 0;
775  size_t dynsym_local_cnt = 0;
776
777  Module::SymbolTable& symbols = pModule.getSymbolTable();
778  Module::const_sym_iterator symbol, symEnd;
779  /// Compute the size of .symtab, .strtab, and symtab_local_cnt
780  /// @{
781  /* TODO:
782       1. discard locals and temporary locals
783       2. check whether the symbol is used
784   */
785  switch (config().options().getStripSymbolMode()) {
786    case GeneralOptions::StripAllSymbols: {
787      symtab = strtab = 0;
788      break;
789    }
790    default: {
791      symEnd = symbols.end();
792      for (symbol = symbols.begin(); symbol != symEnd; ++symbol) {
793        ++symtab;
794        if (hasEntryInStrTab(**symbol))
795          strtab += (*symbol)->nameSize() + 1;
796      }
797      symtab_local_cnt = 1 + symbols.numOfFiles() + symbols.numOfLocals() +
798                         symbols.numOfLocalDyns();
799      break;
800    }
801  } // end of switch
802
803  ELFFileFormat* file_format = getOutputFormat();
804
805  switch(config().codeGenType()) {
806    case LinkerConfig::DynObj: {
807      // soname
808      dynstr += config().options().soname().size() + 1;
809    }
810    /** fall through **/
811    case LinkerConfig::Exec:
812    case LinkerConfig::Binary: {
813      if (!config().isCodeStatic()) {
814        /// Compute the size of .dynsym, .dynstr, and dynsym_local_cnt
815        symEnd = symbols.dynamicEnd();
816        for (symbol = symbols.localDynBegin(); symbol != symEnd; ++symbol) {
817          ++dynsym;
818          if (hasEntryInStrTab(**symbol))
819            dynstr += (*symbol)->nameSize() + 1;
820        }
821        dynsym_local_cnt = 1 + symbols.numOfLocalDyns();
822
823        // compute .gnu.hash
824        if (GeneralOptions::GNU  == config().options().getHashStyle() ||
825            GeneralOptions::Both == config().options().getHashStyle()) {
826          // count the number of dynsym to hash
827          size_t hashed_sym_cnt = 0;
828          symEnd = symbols.dynamicEnd();
829          for (symbol = symbols.dynamicBegin(); symbol != symEnd; ++symbol) {
830            if (DynsymCompare().needGNUHash(**symbol))
831              ++hashed_sym_cnt;
832          }
833          // Special case for empty .dynsym
834          if (hashed_sym_cnt == 0)
835            gnuhash = 5 * 4 + config().targets().bitclass() / 8;
836          else {
837            size_t nbucket = getHashBucketCount(hashed_sym_cnt, true);
838            gnuhash = (4 + nbucket + hashed_sym_cnt) * 4;
839            gnuhash += (1U << getGNUHashMaskbitslog2(hashed_sym_cnt)) / 8;
840          }
841        }
842
843        // compute .hash
844        if (GeneralOptions::SystemV == config().options().getHashStyle() ||
845            GeneralOptions::Both == config().options().getHashStyle()) {
846          // Both Elf32_Word and Elf64_Word are 4 bytes
847          hash = (2 + getHashBucketCount(dynsym, false) + dynsym) *
848                 sizeof(llvm::ELF::Elf32_Word);
849        }
850
851        // add DT_NEEDED
852        Module::const_lib_iterator lib, libEnd = pModule.lib_end();
853        for (lib = pModule.lib_begin(); lib != libEnd; ++lib) {
854          if (!(*lib)->attribute()->isAsNeeded() || (*lib)->isNeeded()) {
855            dynstr += (*lib)->name().size() + 1;
856            dynamic().reserveNeedEntry();
857          }
858        }
859
860        // add DT_RPATH
861        if (!config().options().getRpathList().empty()) {
862          dynamic().reserveNeedEntry();
863          GeneralOptions::const_rpath_iterator rpath,
864            rpathEnd = config().options().rpath_end();
865          for (rpath = config().options().rpath_begin();
866               rpath != rpathEnd; ++rpath)
867            dynstr += (*rpath).size() + 1;
868        }
869
870        // set size
871        if (config().targets().is32Bits()) {
872          file_format->getDynSymTab().setSize(dynsym *
873                                              sizeof(llvm::ELF::Elf32_Sym));
874        } else {
875          file_format->getDynSymTab().setSize(dynsym *
876                                              sizeof(llvm::ELF::Elf64_Sym));
877        }
878        file_format->getDynStrTab().setSize(dynstr);
879        file_format->getHashTab().setSize(hash);
880        file_format->getGNUHashTab().setSize(gnuhash);
881
882        // set .dynsym sh_info to one greater than the symbol table
883        // index of the last local symbol
884        file_format->getDynSymTab().setInfo(dynsym_local_cnt);
885
886        // Because some entries in .dynamic section need information of .dynsym,
887        // .dynstr, .symtab, .strtab and .hash, we can not reserve non-DT_NEEDED
888        // entries until we get the size of the sections mentioned above
889        dynamic().reserveEntries(*file_format);
890        file_format->getDynamic().setSize(dynamic().numOfBytes());
891      }
892    }
893    /* fall through */
894    case LinkerConfig::Object: {
895      if (config().targets().is32Bits())
896        file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf32_Sym));
897      else
898        file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf64_Sym));
899      file_format->getStrTab().setSize(strtab);
900
901      // set .symtab sh_info to one greater than the symbol table
902      // index of the last local symbol
903      file_format->getSymTab().setInfo(symtab_local_cnt);
904
905      // The size of .shstrtab should be decided after output sections are all
906      // set, so we just set it to 1 here.
907      file_format->getShStrTab().setSize(0x1);
908      break;
909    }
910    default:
911      fatal(diag::fatal_illegal_codegen_type) << pModule.name();
912      break;
913  } // end of switch
914}
915
916/// emitSymbol32 - emit an ELF32 symbol
917void GNULDBackend::emitSymbol32(llvm::ELF::Elf32_Sym& pSym,
918                                LDSymbol& pSymbol,
919                                char* pStrtab,
920                                size_t pStrtabsize,
921                                size_t pSymtabIdx)
922{
923   // FIXME: check the endian between host and target
924   // write out symbol
925   if (hasEntryInStrTab(pSymbol)) {
926     pSym.st_name  = pStrtabsize;
927     strcpy((pStrtab + pStrtabsize), pSymbol.name());
928   }
929   else {
930     pSym.st_name  = 0;
931   }
932   pSym.st_value = pSymbol.value();
933   pSym.st_size  = getSymbolSize(pSymbol);
934   pSym.st_info  = getSymbolInfo(pSymbol);
935   pSym.st_other = pSymbol.visibility();
936   pSym.st_shndx = getSymbolShndx(pSymbol);
937}
938
939/// emitSymbol64 - emit an ELF64 symbol
940void GNULDBackend::emitSymbol64(llvm::ELF::Elf64_Sym& pSym,
941                                LDSymbol& pSymbol,
942                                char* pStrtab,
943                                size_t pStrtabsize,
944                                size_t pSymtabIdx)
945{
946   // FIXME: check the endian between host and target
947   // write out symbol
948   if (hasEntryInStrTab(pSymbol)) {
949     pSym.st_name  = pStrtabsize;
950     strcpy((pStrtab + pStrtabsize), pSymbol.name());
951   }
952   else {
953     pSym.st_name  = 0;
954   }
955   pSym.st_value = pSymbol.value();
956   pSym.st_size  = getSymbolSize(pSymbol);
957   pSym.st_info  = getSymbolInfo(pSymbol);
958   pSym.st_other = pSymbol.visibility();
959   pSym.st_shndx = getSymbolShndx(pSymbol);
960}
961
962/// emitRegNamePools - emit regular name pools - .symtab, .strtab
963///
964/// the size of these tables should be computed before layout
965/// layout should computes the start offset of these tables
966void GNULDBackend::emitRegNamePools(const Module& pModule,
967                                    FileOutputBuffer& pOutput)
968{
969  ELFFileFormat* file_format = getOutputFormat();
970  if (!file_format->hasSymTab())
971    return;
972
973  LDSection& symtab_sect = file_format->getSymTab();
974  LDSection& strtab_sect = file_format->getStrTab();
975
976  MemoryRegion symtab_region = pOutput.request(symtab_sect.offset(),
977                                               symtab_sect.size());
978  MemoryRegion strtab_region = pOutput.request(strtab_sect.offset(),
979                                               strtab_sect.size());
980
981  // set up symtab_region
982  llvm::ELF::Elf32_Sym* symtab32 = NULL;
983  llvm::ELF::Elf64_Sym* symtab64 = NULL;
984  if (config().targets().is32Bits())
985    symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region.begin();
986  else if (config().targets().is64Bits())
987    symtab64 = (llvm::ELF::Elf64_Sym*)symtab_region.begin();
988  else {
989    fatal(diag::unsupported_bitclass) << config().targets().triple().str()
990                                      << config().targets().bitclass();
991  }
992
993  // set up strtab_region
994  char* strtab = (char*)strtab_region.begin();
995
996  // emit the first ELF symbol
997  if (config().targets().is32Bits())
998    emitSymbol32(symtab32[0], *LDSymbol::Null(), strtab, 0, 0);
999  else
1000    emitSymbol64(symtab64[0], *LDSymbol::Null(), strtab, 0, 0);
1001
1002  bool sym_exist = false;
1003  HashTableType::entry_type* entry = NULL;
1004  if (LinkerConfig::Object == config().codeGenType()) {
1005    entry = m_pSymIndexMap->insert(LDSymbol::Null(), sym_exist);
1006    entry->setValue(0);
1007  }
1008
1009  size_t symIdx = 1;
1010  size_t strtabsize = 1;
1011
1012  const Module::SymbolTable& symbols = pModule.getSymbolTable();
1013  Module::const_sym_iterator symbol, symEnd;
1014
1015  symEnd = symbols.end();
1016  for (symbol = symbols.begin(); symbol != symEnd; ++symbol) {
1017    if (LinkerConfig::Object == config().codeGenType()) {
1018      entry = m_pSymIndexMap->insert(*symbol, sym_exist);
1019      entry->setValue(symIdx);
1020    }
1021    if (config().targets().is32Bits())
1022      emitSymbol32(symtab32[symIdx], **symbol, strtab, strtabsize, symIdx);
1023    else
1024      emitSymbol64(symtab64[symIdx], **symbol, strtab, strtabsize, symIdx);
1025    ++symIdx;
1026    if (hasEntryInStrTab(**symbol))
1027      strtabsize += (*symbol)->nameSize() + 1;
1028  }
1029}
1030
1031/// emitDynNamePools - emit dynamic name pools - .dyntab, .dynstr, .hash
1032///
1033/// the size of these tables should be computed before layout
1034/// layout should computes the start offset of these tables
1035void GNULDBackend::emitDynNamePools(Module& pModule, FileOutputBuffer& pOutput)
1036{
1037  ELFFileFormat* file_format = getOutputFormat();
1038  if (!file_format->hasDynSymTab() ||
1039      !file_format->hasDynStrTab() ||
1040      !file_format->hasDynamic())
1041    return;
1042
1043  bool sym_exist = false;
1044  HashTableType::entry_type* entry = 0;
1045
1046  LDSection& symtab_sect = file_format->getDynSymTab();
1047  LDSection& strtab_sect = file_format->getDynStrTab();
1048  LDSection& dyn_sect    = file_format->getDynamic();
1049
1050  MemoryRegion symtab_region = pOutput.request(symtab_sect.offset(),
1051                                               symtab_sect.size());
1052  MemoryRegion strtab_region = pOutput.request(strtab_sect.offset(),
1053                                               strtab_sect.size());
1054  MemoryRegion dyn_region = pOutput.request(dyn_sect.offset(),
1055                                            dyn_sect.size());
1056  // set up symtab_region
1057  llvm::ELF::Elf32_Sym* symtab32 = NULL;
1058  llvm::ELF::Elf64_Sym* symtab64 = NULL;
1059  if (config().targets().is32Bits())
1060    symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region.begin();
1061  else if (config().targets().is64Bits())
1062    symtab64 = (llvm::ELF::Elf64_Sym*)symtab_region.begin();
1063  else {
1064    fatal(diag::unsupported_bitclass) << config().targets().triple().str()
1065                                      << config().targets().bitclass();
1066  }
1067
1068  // set up strtab_region
1069  char* strtab = (char*)strtab_region.begin();
1070
1071  // emit the first ELF symbol
1072  if (config().targets().is32Bits())
1073    emitSymbol32(symtab32[0], *LDSymbol::Null(), strtab, 0, 0);
1074  else
1075    emitSymbol64(symtab64[0], *LDSymbol::Null(), strtab, 0, 0);
1076
1077  size_t symIdx = 1;
1078  size_t strtabsize = 1;
1079
1080  Module::SymbolTable& symbols = pModule.getSymbolTable();
1081  // emit .gnu.hash
1082  if (GeneralOptions::GNU  == config().options().getHashStyle() ||
1083      GeneralOptions::Both == config().options().getHashStyle())
1084    emitGNUHashTab(symbols, pOutput);
1085
1086  // emit .hash
1087  if (GeneralOptions::SystemV == config().options().getHashStyle() ||
1088      GeneralOptions::Both == config().options().getHashStyle())
1089    emitELFHashTab(symbols, pOutput);
1090
1091  // emit .dynsym, and .dynstr (emit LocalDyn and Dynamic category)
1092  Module::const_sym_iterator symbol, symEnd = symbols.dynamicEnd();
1093  for (symbol = symbols.localDynBegin(); symbol != symEnd; ++symbol) {
1094    if (config().targets().is32Bits())
1095      emitSymbol32(symtab32[symIdx], **symbol, strtab, strtabsize, symIdx);
1096    else
1097      emitSymbol64(symtab64[symIdx], **symbol, strtab, strtabsize, symIdx);
1098    // maintain output's symbol and index map
1099    entry = m_pSymIndexMap->insert(*symbol, sym_exist);
1100    entry->setValue(symIdx);
1101    // sum up counters
1102    ++symIdx;
1103    if (hasEntryInStrTab(**symbol))
1104      strtabsize += (*symbol)->nameSize() + 1;
1105  }
1106
1107  // emit DT_NEED
1108  // add DT_NEED strings into .dynstr
1109  ELFDynamic::iterator dt_need = dynamic().needBegin();
1110  Module::const_lib_iterator lib, libEnd = pModule.lib_end();
1111  for (lib = pModule.lib_begin(); lib != libEnd; ++lib) {
1112    if (!(*lib)->attribute()->isAsNeeded() || (*lib)->isNeeded()) {
1113      strcpy((strtab + strtabsize), (*lib)->name().c_str());
1114      (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize);
1115      strtabsize += (*lib)->name().size() + 1;
1116      ++dt_need;
1117    }
1118  }
1119
1120  if (!config().options().getRpathList().empty()) {
1121    if (!config().options().hasNewDTags())
1122      (*dt_need)->setValue(llvm::ELF::DT_RPATH, strtabsize);
1123    else
1124      (*dt_need)->setValue(llvm::ELF::DT_RUNPATH, strtabsize);
1125    ++dt_need;
1126
1127    GeneralOptions::const_rpath_iterator rpath,
1128      rpathEnd = config().options().rpath_end();
1129    for (rpath = config().options().rpath_begin(); rpath != rpathEnd; ++rpath) {
1130      memcpy((strtab + strtabsize), (*rpath).data(), (*rpath).size());
1131      strtabsize += (*rpath).size();
1132      strtab[strtabsize++] = (rpath + 1 == rpathEnd ? '\0' : ':');
1133    }
1134  }
1135
1136  // initialize value of ELF .dynamic section
1137  if (LinkerConfig::DynObj == config().codeGenType()) {
1138    // set pointer to SONAME entry in dynamic string table.
1139    dynamic().applySoname(strtabsize);
1140  }
1141  dynamic().applyEntries(*file_format);
1142  dynamic().emit(dyn_sect, dyn_region);
1143
1144  // emit soname
1145  if (LinkerConfig::DynObj == config().codeGenType()) {
1146    strcpy((strtab + strtabsize), config().options().soname().c_str());
1147    strtabsize += config().options().soname().size() + 1;
1148  }
1149}
1150
1151/// emitELFHashTab - emit .hash
1152void GNULDBackend::emitELFHashTab(const Module::SymbolTable& pSymtab,
1153                                  FileOutputBuffer& pOutput)
1154{
1155  ELFFileFormat* file_format = getOutputFormat();
1156  if (!file_format->hasHashTab())
1157    return;
1158  LDSection& hash_sect = file_format->getHashTab();
1159  MemoryRegion hash_region = pOutput.request(hash_sect.offset(),
1160                                             hash_sect.size());
1161  // both 32 and 64 bits hash table use 32-bit entry
1162  // set up hash_region
1163  uint32_t* word_array = (uint32_t*)hash_region.begin();
1164  uint32_t& nbucket = word_array[0];
1165  uint32_t& nchain  = word_array[1];
1166
1167  size_t dynsymSize = 1 + pSymtab.numOfLocalDyns() + pSymtab.numOfDynamics();
1168  nbucket = getHashBucketCount(dynsymSize, false);
1169  nchain  = dynsymSize;
1170
1171  uint32_t* bucket = (word_array + 2);
1172  uint32_t* chain  = (bucket + nbucket);
1173
1174  // initialize bucket
1175  memset((void*)bucket, 0, nbucket);
1176
1177  hash::StringHash<hash::ELF> hash_func;
1178
1179  size_t idx = 1;
1180  Module::const_sym_iterator symbol, symEnd = pSymtab.dynamicEnd();
1181  for (symbol = pSymtab.localDynBegin(); symbol != symEnd; ++symbol) {
1182    llvm::StringRef name((*symbol)->name());
1183    size_t bucket_pos = hash_func(name) % nbucket;
1184    chain[idx] = bucket[bucket_pos];
1185    bucket[bucket_pos] = idx;
1186    ++idx;
1187  }
1188}
1189
1190/// emitGNUHashTab - emit .gnu.hash
1191void GNULDBackend::emitGNUHashTab(Module::SymbolTable& pSymtab,
1192                                  FileOutputBuffer& pOutput)
1193{
1194  ELFFileFormat* file_format = getOutputFormat();
1195  if (!file_format->hasGNUHashTab())
1196    return;
1197
1198  MemoryRegion gnuhash_region =
1199    pOutput.request(file_format->getGNUHashTab().offset(),
1200                    file_format->getGNUHashTab().size());
1201
1202  uint32_t* word_array = (uint32_t*)gnuhash_region.begin();
1203  // fixed-length fields
1204  uint32_t& nbucket   = word_array[0];
1205  uint32_t& symidx    = word_array[1];
1206  uint32_t& maskwords = word_array[2];
1207  uint32_t& shift2    = word_array[3];
1208  // variable-length fields
1209  uint8_t*  bitmask = (uint8_t*)(word_array + 4);
1210  uint32_t* bucket  = NULL;
1211  uint32_t* chain   = NULL;
1212
1213  // count the number of dynsym to hash
1214  size_t unhashed_sym_cnt = pSymtab.numOfLocalDyns();
1215  size_t hashed_sym_cnt   = pSymtab.numOfDynamics();
1216  Module::const_sym_iterator symbol, symEnd = pSymtab.dynamicEnd();
1217  for (symbol = pSymtab.dynamicBegin(); symbol != symEnd; ++symbol) {
1218    if (DynsymCompare().needGNUHash(**symbol))
1219      break;
1220      ++unhashed_sym_cnt;
1221      --hashed_sym_cnt;
1222  }
1223
1224  // special case for the empty hash table
1225  if (hashed_sym_cnt == 0) {
1226    nbucket   = 1; // one empty bucket
1227    symidx    = 1 + unhashed_sym_cnt; // symidx above unhashed symbols
1228    maskwords = 1; // bitmask length
1229    shift2    = 0; // bloom filter
1230
1231    if (config().targets().is32Bits()) {
1232      uint32_t* maskval = (uint32_t*)bitmask;
1233      *maskval = 0; // no valid hashes
1234    } else {
1235      // must be 64
1236      uint64_t* maskval = (uint64_t*)bitmask;
1237      *maskval = 0; // no valid hashes
1238    }
1239    bucket  = (uint32_t*)(bitmask + config().targets().bitclass() / 8);
1240    *bucket = 0; // no hash in the only bucket
1241    return;
1242  }
1243
1244  uint32_t maskbitslog2 = getGNUHashMaskbitslog2(hashed_sym_cnt);
1245  uint32_t maskbits = 1u << maskbitslog2;
1246  uint32_t shift1 = config().targets().is32Bits() ? 5 : 6;
1247  uint32_t mask = (1u << shift1) - 1;
1248
1249  nbucket   = getHashBucketCount(hashed_sym_cnt, true);
1250  symidx    = 1 + unhashed_sym_cnt;
1251  maskwords = 1 << (maskbitslog2 - shift1);
1252  shift2    = maskbitslog2;
1253
1254  // setup bucket and chain
1255  bucket = (uint32_t*)(bitmask + maskbits / 8);
1256  chain  = (bucket + nbucket);
1257
1258  // build the gnu style hash table
1259  typedef std::multimap<uint32_t,
1260                        std::pair<LDSymbol*, uint32_t> > SymMapType;
1261  SymMapType symmap;
1262  symEnd = pSymtab.dynamicEnd();
1263  for (symbol = pSymtab.localDynBegin() + symidx - 1; symbol != symEnd;
1264    ++symbol) {
1265    hash::StringHash<hash::DJB> hasher;
1266    uint32_t djbhash = hasher((*symbol)->name());
1267    uint32_t hash = djbhash % nbucket;
1268    symmap.insert(std::make_pair(hash, std::make_pair(*symbol, djbhash)));
1269  }
1270
1271  // compute bucket, chain, and bitmask
1272  std::vector<uint64_t> bitmasks(maskwords);
1273  size_t hashedidx = symidx;
1274  for (size_t idx = 0; idx < nbucket; ++idx) {
1275    size_t count = 0;
1276    std::pair<SymMapType::iterator, SymMapType::iterator> ret;
1277    ret = symmap.equal_range(idx);
1278    for (SymMapType::iterator it = ret.first; it != ret.second; ) {
1279      // rearrange the hashed symbol ordering
1280      *(pSymtab.localDynBegin() + hashedidx - 1) = it->second.first;
1281      uint32_t djbhash = it->second.second;
1282      uint32_t val = ((djbhash >> shift1) & ((maskbits >> shift1) - 1));
1283      bitmasks[val] |= 1u << (djbhash & mask);
1284      bitmasks[val] |= 1u << ((djbhash >> shift2) & mask);
1285      val = djbhash & ~1u;
1286      // advance the iterator and check if we're dealing w/ the last elment
1287      if (++it == ret.second) {
1288        // last element terminates the chain
1289        val |= 1;
1290      }
1291      chain[hashedidx - symidx] = val;
1292
1293      ++hashedidx;
1294      ++count;
1295    }
1296
1297    if (count == 0)
1298      bucket[idx] = 0;
1299    else
1300      bucket[idx] = hashedidx - count;
1301  }
1302
1303  // write the bitmasks
1304  if (config().targets().is32Bits()) {
1305    uint32_t* maskval = (uint32_t*)bitmask;
1306    for (size_t i = 0; i < maskwords; ++i)
1307      std::memcpy(maskval + i, &bitmasks[i], 4);
1308  } else {
1309    // must be 64
1310    uint64_t* maskval = (uint64_t*)bitmask;
1311    for (size_t i = 0; i < maskwords; ++i)
1312      std::memcpy(maskval + i, &bitmasks[i], 8);
1313  }
1314}
1315
1316/// sizeInterp - compute the size of the .interp section
1317void GNULDBackend::sizeInterp()
1318{
1319  const char* dyld_name;
1320  if (config().options().hasDyld())
1321    dyld_name = config().options().dyld().c_str();
1322  else
1323    dyld_name = m_pInfo->dyld();
1324
1325  LDSection& interp = getOutputFormat()->getInterp();
1326  interp.setSize(std::strlen(dyld_name) + 1);
1327}
1328
1329/// emitInterp - emit the .interp
1330void GNULDBackend::emitInterp(FileOutputBuffer& pOutput)
1331{
1332  if (getOutputFormat()->hasInterp()) {
1333    const LDSection& interp = getOutputFormat()->getInterp();
1334    MemoryRegion region = pOutput.request(interp.offset(), interp.size());
1335    const char* dyld_name;
1336    if (config().options().hasDyld())
1337      dyld_name = config().options().dyld().c_str();
1338    else
1339      dyld_name = m_pInfo->dyld();
1340
1341    std::memcpy(region.begin(), dyld_name, interp.size());
1342  }
1343}
1344
1345bool GNULDBackend::hasEntryInStrTab(const LDSymbol& pSym) const
1346{
1347  return ResolveInfo::Section != pSym.type();
1348}
1349
1350void GNULDBackend::orderSymbolTable(Module& pModule)
1351{
1352  Module::SymbolTable& symbols = pModule.getSymbolTable();
1353
1354  if (GeneralOptions::GNU  == config().options().getHashStyle() ||
1355      GeneralOptions::Both == config().options().getHashStyle())
1356    // Currently we may add output symbols after sizeNamePools(), and a
1357    // non-stable sort is used in SymbolCategory::arrange(), so we just
1358    // sort .dynsym right before emitting .gnu.hash
1359    std::stable_sort(symbols.dynamicBegin(), symbols.dynamicEnd(),
1360                     DynsymCompare());
1361}
1362
1363/// getSectionOrder
1364unsigned int GNULDBackend::getSectionOrder(const LDSection& pSectHdr) const
1365{
1366  const ELFFileFormat* file_format = getOutputFormat();
1367
1368  // NULL section should be the "1st" section
1369  if (LDFileFormat::Null == pSectHdr.kind())
1370    return SHO_NULL;
1371
1372  if (&pSectHdr == &file_format->getStrTab())
1373    return SHO_STRTAB;
1374
1375  // if the section is not ALLOC, lay it out until the last possible moment
1376  if (0 == (pSectHdr.flag() & llvm::ELF::SHF_ALLOC))
1377    return SHO_UNDEFINED;
1378
1379  bool is_write = (pSectHdr.flag() & llvm::ELF::SHF_WRITE) != 0;
1380  bool is_exec = (pSectHdr.flag() & llvm::ELF::SHF_EXECINSTR) != 0;
1381  // TODO: need to take care other possible output sections
1382  switch (pSectHdr.kind()) {
1383    case LDFileFormat::Regular:
1384      if (is_exec) {
1385        if (&pSectHdr == &file_format->getInit())
1386          return SHO_INIT;
1387        if (&pSectHdr == &file_format->getFini())
1388          return SHO_FINI;
1389        return SHO_TEXT;
1390      } else if (!is_write) {
1391        return SHO_RO;
1392      } else {
1393        if (config().options().hasRelro()) {
1394          if (&pSectHdr == &file_format->getPreInitArray() ||
1395              &pSectHdr == &file_format->getInitArray() ||
1396              &pSectHdr == &file_format->getFiniArray() ||
1397              &pSectHdr == &file_format->getCtors() ||
1398              &pSectHdr == &file_format->getDtors() ||
1399              &pSectHdr == &file_format->getJCR() ||
1400              &pSectHdr == &file_format->getDataRelRo())
1401            return SHO_RELRO;
1402          if (&pSectHdr == &file_format->getDataRelRoLocal())
1403            return SHO_RELRO_LOCAL;
1404        }
1405        if ((pSectHdr.flag() & llvm::ELF::SHF_TLS) != 0x0) {
1406          return SHO_TLS_DATA;
1407        }
1408        return SHO_DATA;
1409      }
1410
1411    case LDFileFormat::BSS:
1412      if ((pSectHdr.flag() & llvm::ELF::SHF_TLS) != 0x0)
1413        return SHO_TLS_BSS;
1414      return SHO_BSS;
1415
1416    case LDFileFormat::NamePool: {
1417      if (&pSectHdr == &file_format->getDynamic())
1418        return SHO_RELRO;
1419      return SHO_NAMEPOOL;
1420    }
1421    case LDFileFormat::Relocation:
1422      if (&pSectHdr == &file_format->getRelPlt() ||
1423          &pSectHdr == &file_format->getRelaPlt())
1424        return SHO_REL_PLT;
1425      return SHO_RELOCATION;
1426
1427    // get the order from target for target specific sections
1428    case LDFileFormat::Target:
1429      return getTargetSectionOrder(pSectHdr);
1430
1431    // handle .interp and .note.* sections
1432    case LDFileFormat::Note:
1433      if (file_format->hasInterp() && (&pSectHdr == &file_format->getInterp()))
1434        return SHO_INTERP;
1435      else if (is_write)
1436        return SHO_RW_NOTE;
1437      else
1438        return SHO_RO_NOTE;
1439
1440    case LDFileFormat::EhFrame:
1441      // set writable .eh_frame as relro
1442      if (is_write)
1443        return SHO_RELRO;
1444    case LDFileFormat::EhFrameHdr:
1445    case LDFileFormat::GCCExceptTable:
1446      return SHO_EXCEPTION;
1447
1448    case LDFileFormat::MetaData:
1449    case LDFileFormat::Debug:
1450    default:
1451      return SHO_UNDEFINED;
1452  }
1453}
1454
1455/// getSymbolSize
1456uint64_t GNULDBackend::getSymbolSize(const LDSymbol& pSymbol) const
1457{
1458  // @ref Google gold linker: symtab.cc: 2780
1459  // undefined and dynamic symbols should have zero size.
1460  if (pSymbol.isDyn() || pSymbol.desc() == ResolveInfo::Undefined)
1461    return 0x0;
1462  return pSymbol.resolveInfo()->size();
1463}
1464
1465/// getSymbolInfo
1466uint64_t GNULDBackend::getSymbolInfo(const LDSymbol& pSymbol) const
1467{
1468  // set binding
1469  uint8_t bind = 0x0;
1470  if (pSymbol.resolveInfo()->isLocal())
1471    bind = llvm::ELF::STB_LOCAL;
1472  else if (pSymbol.resolveInfo()->isGlobal())
1473    bind = llvm::ELF::STB_GLOBAL;
1474  else if (pSymbol.resolveInfo()->isWeak())
1475    bind = llvm::ELF::STB_WEAK;
1476  else if (pSymbol.resolveInfo()->isAbsolute()) {
1477    // (Luba) Is a absolute but not global (weak or local) symbol meaningful?
1478    bind = llvm::ELF::STB_GLOBAL;
1479  }
1480
1481  if (config().codeGenType() != LinkerConfig::Object &&
1482      (pSymbol.visibility() == llvm::ELF::STV_INTERNAL ||
1483      pSymbol.visibility() == llvm::ELF::STV_HIDDEN))
1484    bind = llvm::ELF::STB_LOCAL;
1485
1486  uint32_t type = pSymbol.resolveInfo()->type();
1487  // if the IndirectFunc symbol (i.e., STT_GNU_IFUNC) is from dynobj, change
1488  // its type to Function
1489  if (type == ResolveInfo::IndirectFunc && pSymbol.isDyn())
1490    type = ResolveInfo::Function;
1491  return (type | (bind << 4));
1492}
1493
1494/// getSymbolValue - this function is called after layout()
1495uint64_t GNULDBackend::getSymbolValue(const LDSymbol& pSymbol) const
1496{
1497  if (pSymbol.isDyn())
1498    return 0x0;
1499
1500  return pSymbol.value();
1501}
1502
1503/// getSymbolShndx - this function is called after layout()
1504uint64_t
1505GNULDBackend::getSymbolShndx(const LDSymbol& pSymbol) const
1506{
1507  if (pSymbol.resolveInfo()->isAbsolute())
1508    return llvm::ELF::SHN_ABS;
1509  if (pSymbol.resolveInfo()->isCommon())
1510    return llvm::ELF::SHN_COMMON;
1511  if (pSymbol.resolveInfo()->isUndef() || pSymbol.isDyn())
1512    return llvm::ELF::SHN_UNDEF;
1513
1514  if (pSymbol.resolveInfo()->isDefine() && !pSymbol.hasFragRef())
1515    return llvm::ELF::SHN_ABS;
1516
1517  assert(pSymbol.hasFragRef() && "symbols must have fragment reference to get its index");
1518  return pSymbol.fragRef()->frag()->getParent()->getSection().index();
1519}
1520
1521/// getSymbolIdx - called by emitRelocation to get the ouput symbol table index
1522size_t GNULDBackend::getSymbolIdx(const LDSymbol* pSymbol) const
1523{
1524   HashTableType::iterator entry = m_pSymIndexMap->find(const_cast<LDSymbol *>(pSymbol));
1525   assert(entry != m_pSymIndexMap->end() && "symbol not found in the symbol table");
1526   return entry.getEntry()->value();
1527}
1528
1529/// isTemporary - Whether pSymbol is a local label.
1530bool GNULDBackend::isTemporary(const LDSymbol& pSymbol) const
1531{
1532  if (ResolveInfo::Local != pSymbol.binding())
1533    return false;
1534
1535  if (pSymbol.nameSize() < 2)
1536    return false;
1537
1538  const char* name = pSymbol.name();
1539  if ('.' == name[0] && 'L' == name[1])
1540    return true;
1541
1542  // UnixWare 2.1 cc generate DWARF debugging symbols with `..' prefix.
1543  // @ref Google gold linker, target.cc:39 @@ Target::do_is_local_label_name()
1544  if (name[0] == '.' && name[1] == '.')
1545    return true;
1546
1547  // Work arround for gcc's bug
1548  // gcc sometimes generate symbols with '_.L_' prefix.
1549  // @ref Google gold linker, target.cc:39 @@ Target::do_is_local_label_name()
1550  if (pSymbol.nameSize() < 4)
1551    return false;
1552
1553  if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
1554    return true;
1555
1556  return false;
1557}
1558
1559/// allocateCommonSymbols - allocate common symbols in the corresponding
1560/// sections. This is executed at pre-layout stage.
1561/// @refer Google gold linker: common.cc: 214
1562bool
1563GNULDBackend::allocateCommonSymbols(Module& pModule)
1564{
1565  SymbolCategory& symbol_list = pModule.getSymbolTable();
1566
1567  if (symbol_list.emptyCommons() && symbol_list.emptyFiles() &&
1568      symbol_list.emptyLocals() && symbol_list.emptyLocalDyns())
1569    return true;
1570
1571  SymbolCategory::iterator com_sym, com_end;
1572
1573  // FIXME: If the order of common symbols is defined, then sort common symbols
1574  // std::sort(com_sym, com_end, some kind of order);
1575
1576  // get corresponding BSS LDSection
1577  ELFFileFormat* file_format = getOutputFormat();
1578  LDSection& bss_sect = file_format->getBSS();
1579  LDSection& tbss_sect = file_format->getTBSS();
1580
1581  // get or create corresponding BSS SectionData
1582  SectionData* bss_sect_data = NULL;
1583  if (bss_sect.hasSectionData())
1584    bss_sect_data = bss_sect.getSectionData();
1585  else
1586    bss_sect_data = IRBuilder::CreateSectionData(bss_sect);
1587
1588  SectionData* tbss_sect_data = NULL;
1589  if (tbss_sect.hasSectionData())
1590    tbss_sect_data = tbss_sect.getSectionData();
1591  else
1592    tbss_sect_data = IRBuilder::CreateSectionData(tbss_sect);
1593
1594  // remember original BSS size
1595  uint64_t bss_offset  = bss_sect.size();
1596  uint64_t tbss_offset = tbss_sect.size();
1597
1598  // allocate all local common symbols
1599  com_end = symbol_list.localEnd();
1600
1601  for (com_sym = symbol_list.localBegin(); com_sym != com_end; ++com_sym) {
1602    if (ResolveInfo::Common == (*com_sym)->desc()) {
1603      // We have to reset the description of the symbol here. When doing
1604      // incremental linking, the output relocatable object may have common
1605      // symbols. Therefore, we can not treat common symbols as normal symbols
1606      // when emitting the regular name pools. We must change the symbols'
1607      // description here.
1608      (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define);
1609      Fragment* frag = new FillFragment(0x0, 1, (*com_sym)->size());
1610
1611      if (ResolveInfo::ThreadLocal == (*com_sym)->type()) {
1612        // allocate TLS common symbol in tbss section
1613        tbss_offset += ObjectBuilder::AppendFragment(*frag,
1614                                                     *tbss_sect_data,
1615                                                     (*com_sym)->value());
1616        (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0));
1617      }
1618      else {
1619        bss_offset += ObjectBuilder::AppendFragment(*frag,
1620                                                    *bss_sect_data,
1621                                                    (*com_sym)->value());
1622        (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0));
1623      }
1624    }
1625  }
1626
1627  // allocate all global common symbols
1628  com_end = symbol_list.commonEnd();
1629  for (com_sym = symbol_list.commonBegin(); com_sym != com_end; ++com_sym) {
1630    // We have to reset the description of the symbol here. When doing
1631    // incremental linking, the output relocatable object may have common
1632    // symbols. Therefore, we can not treat common symbols as normal symbols
1633    // when emitting the regular name pools. We must change the symbols'
1634    // description here.
1635    (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define);
1636    Fragment* frag = new FillFragment(0x0, 1, (*com_sym)->size());
1637
1638    if (ResolveInfo::ThreadLocal == (*com_sym)->type()) {
1639      // allocate TLS common symbol in tbss section
1640      tbss_offset += ObjectBuilder::AppendFragment(*frag,
1641                                                   *tbss_sect_data,
1642                                                   (*com_sym)->value());
1643      (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0));
1644    }
1645    else {
1646      bss_offset += ObjectBuilder::AppendFragment(*frag,
1647                                                  *bss_sect_data,
1648                                                  (*com_sym)->value());
1649      (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0));
1650    }
1651  }
1652
1653  bss_sect.setSize(bss_offset);
1654  tbss_sect.setSize(tbss_offset);
1655  symbol_list.changeCommonsToGlobal();
1656  return true;
1657}
1658
1659/// updateSectionFlags - update pTo's flags when merging pFrom
1660/// update the output section flags based on input section flags.
1661/// @ref The Google gold linker:
1662///      output.cc: 2809: Output_section::update_flags_for_input_section
1663bool GNULDBackend::updateSectionFlags(LDSection& pTo, const LDSection& pFrom)
1664{
1665  // union the flags from input
1666  uint32_t flags = pTo.flag();
1667  flags |= (pFrom.flag() &
1668              (llvm::ELF::SHF_WRITE |
1669               llvm::ELF::SHF_ALLOC |
1670               llvm::ELF::SHF_EXECINSTR));
1671
1672  // if there is an input section is not SHF_MERGE, clean this flag
1673  if (0 == (pFrom.flag() & llvm::ELF::SHF_MERGE))
1674    flags &= ~llvm::ELF::SHF_MERGE;
1675
1676  // if there is an input section is not SHF_STRINGS, clean this flag
1677  if (0 == (pFrom.flag() & llvm::ELF::SHF_STRINGS))
1678    flags &= ~llvm::ELF::SHF_STRINGS;
1679
1680  pTo.setFlag(flags);
1681  return true;
1682}
1683
1684/// readRelocation - read ELF32_Rel entry
1685bool GNULDBackend::readRelocation(const llvm::ELF::Elf32_Rel& pRel,
1686                                  Relocation::Type& pType,
1687                                  uint32_t& pSymIdx,
1688                                  uint32_t& pOffset) const
1689{
1690  uint32_t r_info = 0x0;
1691  if (llvm::sys::IsLittleEndianHost) {
1692    pOffset = pRel.r_offset;
1693    r_info  = pRel.r_info;
1694  }
1695  else {
1696    pOffset = mcld::bswap32(pRel.r_offset);
1697    r_info  = mcld::bswap32(pRel.r_info);
1698  }
1699
1700  pType = static_cast<unsigned char>(r_info);
1701  pSymIdx = (r_info >> 8);
1702  return true;
1703}
1704
1705/// readRelocation - read ELF32_Rela entry
1706bool GNULDBackend::readRelocation(const llvm::ELF::Elf32_Rela& pRel,
1707                                  Relocation::Type& pType,
1708                                  uint32_t& pSymIdx,
1709                                  uint32_t& pOffset,
1710                                  int32_t& pAddend) const
1711{
1712  uint32_t r_info   = 0x0;
1713  if (llvm::sys::IsLittleEndianHost) {
1714    pOffset = pRel.r_offset;
1715    r_info  = pRel.r_info;
1716    pAddend = pRel.r_addend;
1717  }
1718  else {
1719    pOffset = mcld::bswap32(pRel.r_offset);
1720    r_info  = mcld::bswap32(pRel.r_info);
1721    pAddend = mcld::bswap32(pRel.r_addend);
1722  }
1723
1724  pType = static_cast<unsigned char>(r_info);
1725  pSymIdx = (r_info >> 8);
1726  return true;
1727}
1728
1729/// readRelocation - read ELF64_Rel entry
1730bool GNULDBackend::readRelocation(const llvm::ELF::Elf64_Rel& pRel,
1731                              Relocation::Type& pType,
1732                              uint32_t& pSymIdx,
1733                              uint64_t& pOffset) const
1734{
1735  uint64_t r_info = 0x0;
1736  if (llvm::sys::IsLittleEndianHost) {
1737    pOffset = pRel.r_offset;
1738    r_info  = pRel.r_info;
1739  }
1740  else {
1741    pOffset = mcld::bswap64(pRel.r_offset);
1742    r_info  = mcld::bswap64(pRel.r_info);
1743  }
1744
1745  pType = static_cast<uint32_t>(r_info);
1746  pSymIdx = (r_info >> 32);
1747  return true;
1748}
1749
1750/// readRel - read ELF64_Rela entry
1751bool GNULDBackend::readRelocation(const llvm::ELF::Elf64_Rela& pRel,
1752                              Relocation::Type& pType,
1753                              uint32_t& pSymIdx,
1754                              uint64_t& pOffset,
1755                              int64_t& pAddend) const
1756{
1757  uint64_t r_info = 0x0;
1758  if (llvm::sys::IsLittleEndianHost) {
1759    pOffset = pRel.r_offset;
1760    r_info  = pRel.r_info;
1761    pAddend = pRel.r_addend;
1762  }
1763  else {
1764    pOffset = mcld::bswap64(pRel.r_offset);
1765    r_info  = mcld::bswap64(pRel.r_info);
1766    pAddend = mcld::bswap64(pRel.r_addend);
1767  }
1768
1769  pType = static_cast<uint32_t>(r_info);
1770  pSymIdx = (r_info >> 32);
1771  return true;
1772}
1773
1774/// emitRelocation - write data to the ELF32_Rel entry
1775void GNULDBackend::emitRelocation(llvm::ELF::Elf32_Rel& pRel,
1776                                  Relocation::Type pType,
1777                                  uint32_t pSymIdx,
1778                                  uint32_t pOffset) const
1779{
1780  pRel.r_offset = pOffset;
1781  pRel.setSymbolAndType(pSymIdx, pType);
1782}
1783
1784/// emitRelocation - write data to the ELF32_Rela entry
1785void GNULDBackend::emitRelocation(llvm::ELF::Elf32_Rela& pRel,
1786                                  Relocation::Type pType,
1787                                  uint32_t pSymIdx,
1788                                  uint32_t pOffset,
1789                                  int32_t pAddend) const
1790{
1791  pRel.r_offset = pOffset;
1792  pRel.r_addend = pAddend;
1793  pRel.setSymbolAndType(pSymIdx, pType);
1794}
1795
1796/// emitRelocation - write data to the ELF64_Rel entry
1797void GNULDBackend::emitRelocation(llvm::ELF::Elf64_Rel& pRel,
1798                                  Relocation::Type pType,
1799                                  uint32_t pSymIdx,
1800                                  uint64_t pOffset) const
1801{
1802  pRel.r_offset = pOffset;
1803  pRel.setSymbolAndType(pSymIdx, pType);
1804}
1805
1806/// emitRelocation - write data to the ELF64_Rela entry
1807void GNULDBackend::emitRelocation(llvm::ELF::Elf64_Rela& pRel,
1808                                  Relocation::Type pType,
1809                                  uint32_t pSymIdx,
1810                                  uint64_t pOffset,
1811                                  int64_t pAddend) const
1812{
1813  pRel.r_offset = pOffset;
1814  pRel.r_addend = pAddend;
1815  pRel.setSymbolAndType(pSymIdx, pType);
1816}
1817
1818/// createProgramHdrs - base on output sections to create the program headers
1819void GNULDBackend::createProgramHdrs(Module& pModule)
1820{
1821  ELFFileFormat *file_format = getOutputFormat();
1822
1823  // make PT_INTERP
1824  if (file_format->hasInterp()) {
1825    // make PT_PHDR
1826    elfSegmentTable().produce(llvm::ELF::PT_PHDR);
1827
1828    ELFSegment* interp_seg = elfSegmentTable().produce(llvm::ELF::PT_INTERP);
1829    interp_seg->append(&file_format->getInterp());
1830  }
1831
1832  uint32_t cur_flag, prev_flag = 0x0;
1833  ELFSegment* load_seg = NULL;
1834  // make possible PT_LOAD segments
1835  LinkerScript& ldscript = pModule.getScript();
1836  LinkerScript::AddressMap::iterator addrEnd= ldscript.addressMap().end();
1837  SectionMap::iterator out, prev, outBegin, outEnd;
1838  outBegin = ldscript.sectionMap().begin();
1839  outEnd = ldscript.sectionMap().end();
1840  for (out = outBegin, prev = outEnd; out != outEnd; prev = out, ++out) {
1841    LDSection* sect = (*out)->getSection();
1842
1843    if (0 == (sect->flag() & llvm::ELF::SHF_ALLOC) &&
1844        LDFileFormat::Null != sect->kind())
1845      break;
1846
1847    // bypass empty sections
1848    if (!(*out)->hasContent() &&
1849        (*out)->getSection()->kind() != LDFileFormat::Null)
1850      continue;
1851
1852    cur_flag = getSegmentFlag(sect->flag());
1853    bool createPT_LOAD = false;
1854    if (LDFileFormat::Null == sect->kind()) {
1855      // 1. create text segment
1856      createPT_LOAD = true;
1857    }
1858    else if (!config().options().omagic() &&
1859             (prev_flag & llvm::ELF::PF_W) ^ (cur_flag & llvm::ELF::PF_W)) {
1860      // 2. create data segment if w/o omagic set
1861      createPT_LOAD = true;
1862    }
1863    else if (sect->kind() == LDFileFormat::BSS &&
1864             load_seg->isDataSegment() &&
1865             addrEnd != ldscript.addressMap().find(".bss")) {
1866      // 3. create bss segment if w/ -Tbss and there is a data segment
1867      createPT_LOAD = true;
1868    }
1869    else if ((sect != &(file_format->getText())) &&
1870             (sect != &(file_format->getData())) &&
1871             (sect != &(file_format->getBSS())) &&
1872             (addrEnd != ldscript.addressMap().find(sect->name()))) {
1873      // 4. create PT_LOAD for sections in address map except for text, data,
1874      // and bss
1875      createPT_LOAD = true;
1876    }
1877    else if (LDFileFormat::Null == (*prev)->getSection()->kind() &&
1878             !config().options().getScriptList().empty()) {
1879      // 5. create PT_LOAD to hold NULL section if there is a default ldscript
1880      createPT_LOAD = true;
1881    }
1882
1883    if (createPT_LOAD) {
1884      // create new PT_LOAD segment
1885      load_seg = elfSegmentTable().produce(llvm::ELF::PT_LOAD, cur_flag);
1886      if (!config().options().nmagic() && !config().options().omagic())
1887        load_seg->setAlign(abiPageSize());
1888    }
1889
1890    assert(NULL != load_seg);
1891    load_seg->append(sect);
1892    if (cur_flag != prev_flag)
1893      load_seg->updateFlag(cur_flag);
1894
1895    prev_flag = cur_flag;
1896  }
1897
1898  // make PT_DYNAMIC
1899  if (file_format->hasDynamic()) {
1900    ELFSegment* dyn_seg = elfSegmentTable().produce(llvm::ELF::PT_DYNAMIC,
1901                                                    llvm::ELF::PF_R |
1902                                                    llvm::ELF::PF_W);
1903    dyn_seg->append(&file_format->getDynamic());
1904  }
1905
1906  if (config().options().hasRelro()) {
1907    // make PT_GNU_RELRO
1908    ELFSegment* relro_seg = elfSegmentTable().produce(llvm::ELF::PT_GNU_RELRO);
1909    for (ELFSegmentFactory::iterator seg = elfSegmentTable().begin(),
1910      segEnd = elfSegmentTable().end(); seg != segEnd; ++seg) {
1911      if (llvm::ELF::PT_LOAD != (*seg)->type())
1912        continue;
1913
1914      for (ELFSegment::iterator sect = (*seg)->begin(),
1915        sectEnd = (*seg)->end(); sect != sectEnd; ++sect) {
1916        unsigned int order = getSectionOrder(**sect);
1917        if (SHO_RELRO_LOCAL == order ||
1918            SHO_RELRO == order ||
1919            SHO_RELRO_LAST == order) {
1920          relro_seg->append(*sect);
1921        }
1922      }
1923    }
1924  }
1925
1926  // make PT_GNU_EH_FRAME
1927  if (file_format->hasEhFrameHdr()) {
1928    ELFSegment* eh_seg = elfSegmentTable().produce(llvm::ELF::PT_GNU_EH_FRAME);
1929    eh_seg->append(&file_format->getEhFrameHdr());
1930  }
1931
1932  // make PT_TLS
1933  if (file_format->hasTData() || file_format->hasTBSS()) {
1934    ELFSegment* tls_seg = elfSegmentTable().produce(llvm::ELF::PT_TLS);
1935    if (file_format->hasTData())
1936      tls_seg->append(&file_format->getTData());
1937    if (file_format->hasTBSS())
1938      tls_seg->append(&file_format->getTBSS());
1939  }
1940
1941  // make PT_GNU_STACK
1942  if (file_format->hasStackNote()) {
1943    elfSegmentTable().produce(llvm::ELF::PT_GNU_STACK,
1944                              llvm::ELF::PF_R |
1945                              llvm::ELF::PF_W |
1946                              getSegmentFlag(file_format->getStackNote().flag()));
1947  }
1948
1949  // make PT_NOTE
1950  ELFSegment *note_seg = NULL;
1951  prev_flag = 0x0;
1952  Module::iterator sect, sectBegin, sectEnd;
1953  sectBegin = pModule.begin();
1954  sectEnd = pModule.end();
1955  for (sect = sectBegin; sect != sectEnd; ++sect) {
1956    if ((*sect)->type() != llvm::ELF::SHT_NOTE ||
1957        ((*sect)->flag() & llvm::ELF::SHF_ALLOC) == 0)
1958      continue;
1959
1960    cur_flag = getSegmentFlag((*sect)->flag());
1961    // we have different section orders for read-only and writable notes, so
1962    // create 2 segments if needed.
1963    if (note_seg == NULL ||
1964        (cur_flag & llvm::ELF::PF_W) != (prev_flag & llvm::ELF::PF_W))
1965      note_seg = elfSegmentTable().produce(llvm::ELF::PT_NOTE, cur_flag);
1966
1967    note_seg->append(*sect);
1968    prev_flag = cur_flag;
1969  }
1970
1971  // create target dependent segments
1972  doCreateProgramHdrs(pModule);
1973}
1974
1975/// setupProgramHdrs - set up the attributes of segments
1976void GNULDBackend::setupProgramHdrs(const LinkerScript& pScript)
1977{
1978  // update segment info
1979  for (ELFSegmentFactory::iterator seg = elfSegmentTable().begin(),
1980    segEnd = elfSegmentTable().end(); seg != segEnd; ++seg) {
1981
1982    // bypass if there is no section in this segment (e.g., PT_GNU_STACK)
1983    if ((*seg)->size() == 0)
1984      continue;
1985
1986    // bypass the PT_LOAD that only has NULL section now
1987    if ((*seg)->type() == llvm::ELF::PT_LOAD &&
1988        (*seg)->front()->kind() == LDFileFormat::Null &&
1989        (*seg)->size() == 1)
1990       continue;
1991
1992    (*seg)->setOffset((*seg)->front()->offset());
1993    if ((*seg)->type() == llvm::ELF::PT_LOAD &&
1994        (*seg)->front()->kind() == LDFileFormat::Null) {
1995      const LDSection* second = *((*seg)->begin() + 1);
1996      assert(second != NULL);
1997      (*seg)->setVaddr(second->addr() - second->offset());
1998    } else {
1999      (*seg)->setVaddr((*seg)->front()->addr());
2000    }
2001    (*seg)->setPaddr((*seg)->vaddr());
2002
2003    ELFSegment::reverse_iterator sect, sectREnd = (*seg)->rend();
2004    for (sect = (*seg)->rbegin(); sect != sectREnd; ++sect) {
2005      if ((*sect)->kind() != LDFileFormat::BSS)
2006        break;
2007    }
2008    if (sect != sectREnd) {
2009      (*seg)->setFilesz((*sect)->offset() +
2010                        (*sect)->size() -
2011                        (*seg)->offset());
2012    } else {
2013      (*seg)->setFilesz(0x0);
2014    }
2015
2016    (*seg)->setMemsz((*seg)->back()->addr() +
2017                     (*seg)->back()->size() -
2018                     (*seg)->vaddr());
2019  } // end of for
2020
2021  // handle the case if text segment only has NULL section
2022  LDSection* null_sect = &getOutputFormat()->getNULLSection();
2023  ELFSegmentFactory::iterator null_seg =
2024    elfSegmentTable().find(llvm::ELF::PT_LOAD, null_sect);
2025
2026  if ((*null_seg)->size() == 1) {
2027    // find 2nd PT_LOAD
2028    ELFSegmentFactory::iterator seg, segEnd = elfSegmentTable().end();
2029    for (seg = null_seg + 1; seg != segEnd; ++seg) {
2030      if ((*seg)->type() == llvm::ELF::PT_LOAD)
2031        break;
2032    }
2033    if (seg != segEnd) {
2034      uint64_t addr = (*seg)->front()->addr() - (*seg)->front()->offset();
2035      uint64_t size = sectionStartOffset();
2036      if (addr + size == (*seg)->front()->addr()) {
2037        // if there is no space between the 2 segments, we can merge them.
2038        (*seg)->setOffset(0x0);
2039        (*seg)->setVaddr(addr);
2040        (*seg)->setPaddr(addr);
2041
2042        ELFSegment::iterator sect, sectEnd = (*seg)->end();
2043        for (sect = (*seg)->begin(); sect != sectEnd; ++sect) {
2044          if ((*sect)->kind() == LDFileFormat::BSS) {
2045            --sect;
2046            break;
2047          }
2048        }
2049        if (sect == sectEnd) {
2050          (*seg)->setFilesz((*seg)->back()->offset() +
2051                            (*seg)->back()->size() -
2052                            (*seg)->offset());
2053        } else if (*sect != (*seg)->front()) {
2054          --sect;
2055          (*seg)->setFilesz((*sect)->offset() +
2056                            (*sect)->size() -
2057                            (*seg)->offset());
2058        } else {
2059          (*seg)->setFilesz(0x0);
2060        }
2061
2062        (*seg)->setMemsz((*seg)->back()->addr() +
2063                         (*seg)->back()->size() -
2064                         (*seg)->vaddr());
2065
2066        (*seg)->insert((*seg)->begin(), null_sect);
2067        elfSegmentTable().erase(null_seg);
2068
2069      } else if (addr + size < (*seg)->vaddr()) {
2070        (*null_seg)->setOffset(0x0);
2071        (*null_seg)->setVaddr(addr);
2072        (*null_seg)->setPaddr(addr);
2073        (*null_seg)->setFilesz(size);
2074        (*null_seg)->setMemsz(size);
2075      } else {
2076        // erase the non valid segment contains NULL.
2077        elfSegmentTable().erase(null_seg);
2078      }
2079    }
2080  }
2081
2082  // set up PT_PHDR
2083  ELFSegmentFactory::iterator phdr =
2084    elfSegmentTable().find(llvm::ELF::PT_PHDR, llvm::ELF::PF_R, 0x0);
2085
2086  if (phdr != elfSegmentTable().end()) {
2087    ELFSegmentFactory::iterator null_seg =
2088      elfSegmentTable().find(llvm::ELF::PT_LOAD, null_sect);
2089    if (null_seg != elfSegmentTable().end()) {
2090      uint64_t offset = 0x0, phdr_size = 0x0;
2091      if (config().targets().is32Bits()) {
2092        offset = sizeof(llvm::ELF::Elf32_Ehdr);
2093        phdr_size = sizeof(llvm::ELF::Elf32_Phdr);
2094      } else {
2095        offset = sizeof(llvm::ELF::Elf64_Ehdr);
2096        phdr_size = sizeof(llvm::ELF::Elf64_Phdr);
2097      }
2098      (*phdr)->setOffset(offset);
2099      (*phdr)->setVaddr((*null_seg)->vaddr() + offset);
2100      (*phdr)->setPaddr((*phdr)->vaddr());
2101      (*phdr)->setFilesz(elfSegmentTable().size() * phdr_size);
2102      (*phdr)->setMemsz(elfSegmentTable().size() * phdr_size);
2103      (*phdr)->setAlign(config().targets().bitclass() / 8);
2104    } else {
2105      elfSegmentTable().erase(phdr);
2106    }
2107  }
2108}
2109
2110/// getSegmentFlag - give a section flag and return the corresponding segment
2111/// flag
2112uint32_t GNULDBackend::getSegmentFlag(const uint32_t pSectionFlag)
2113{
2114  uint32_t flag = 0x0;
2115  if ((pSectionFlag & llvm::ELF::SHF_ALLOC) != 0x0)
2116    flag |= llvm::ELF::PF_R;
2117  if ((pSectionFlag & llvm::ELF::SHF_WRITE) != 0x0)
2118    flag |= llvm::ELF::PF_W;
2119  if ((pSectionFlag & llvm::ELF::SHF_EXECINSTR) != 0x0)
2120    flag |= llvm::ELF::PF_X;
2121  return flag;
2122}
2123
2124/// setupGNUStackInfo - setup the section flag of .note.GNU-stack in output
2125/// @ref gold linker: layout.cc:2608
2126void GNULDBackend::setupGNUStackInfo(Module& pModule)
2127{
2128  uint32_t flag = 0x0;
2129  if (config().options().hasStackSet()) {
2130    // 1. check the command line option (-z execstack or -z noexecstack)
2131    if (config().options().hasExecStack())
2132      flag = llvm::ELF::SHF_EXECINSTR;
2133  }
2134  else {
2135    // 2. check the stack info from the input objects
2136    // FIXME: since we alway emit .note.GNU-stack in output now, we may be able
2137    // to check this from the output .note.GNU-stack directly after section
2138    // merging is done
2139    size_t object_count = 0, stack_note_count = 0;
2140    Module::const_obj_iterator obj, objEnd = pModule.obj_end();
2141    for (obj = pModule.obj_begin(); obj != objEnd; ++obj) {
2142      ++object_count;
2143      const LDSection* sect = (*obj)->context()->getSection(".note.GNU-stack");
2144      if (NULL != sect) {
2145        ++stack_note_count;
2146        // 2.1 found a stack note that is set as executable
2147        if (0 != (llvm::ELF::SHF_EXECINSTR & sect->flag())) {
2148          flag = llvm::ELF::SHF_EXECINSTR;
2149          break;
2150        }
2151      }
2152    }
2153
2154    // 2.2 there are no stack note sections in all input objects
2155    if (0 == stack_note_count)
2156      return;
2157
2158    // 2.3 a special case. Use the target default to decide if the stack should
2159    //     be executable
2160    if (llvm::ELF::SHF_EXECINSTR != flag && object_count != stack_note_count)
2161      if (m_pInfo->isDefaultExecStack())
2162        flag = llvm::ELF::SHF_EXECINSTR;
2163  }
2164
2165  if (getOutputFormat()->hasStackNote()) {
2166    getOutputFormat()->getStackNote().setFlag(flag);
2167  }
2168}
2169
2170/// setOutputSectionOffset - helper function to set output sections' offset.
2171void GNULDBackend::setOutputSectionOffset(Module& pModule)
2172{
2173  LinkerScript& script = pModule.getScript();
2174  uint64_t offset = 0x0;
2175  LDSection* cur = NULL;
2176  LDSection* prev = NULL;
2177  SectionMap::iterator out, outBegin, outEnd;
2178  outBegin = script.sectionMap().begin();
2179  outEnd = script.sectionMap().end();
2180  for (out = outBegin; out != outEnd; ++out, prev = cur) {
2181    cur = (*out)->getSection();
2182    if (cur->kind() == LDFileFormat::Null) {
2183      cur->setOffset(0x0);
2184      continue;
2185    }
2186
2187    switch (prev->kind()) {
2188    case LDFileFormat::Null:
2189      offset = sectionStartOffset();
2190      break;
2191    case LDFileFormat::BSS:
2192      offset = prev->offset();
2193      break;
2194    default:
2195      offset = prev->offset() + prev->size();
2196      break;
2197    }
2198    alignAddress(offset, cur->align());
2199    cur->setOffset(offset);
2200  }
2201}
2202
2203/// setOutputSectionAddress - helper function to set output sections' address.
2204void GNULDBackend::setOutputSectionAddress(Module& pModule)
2205{
2206  RpnEvaluator evaluator(pModule, *this);
2207  LinkerScript& script = pModule.getScript();
2208  uint64_t vma = 0x0, offset = 0x0;
2209  LDSection* cur = NULL;
2210  LDSection* prev = NULL;
2211  LinkerScript::AddressMap::iterator addr, addrEnd = script.addressMap().end();
2212  ELFSegmentFactory::iterator seg, segEnd = elfSegmentTable().end();
2213  SectionMap::Output::dot_iterator dot;
2214  SectionMap::iterator out, outBegin, outEnd;
2215  outBegin = script.sectionMap().begin();
2216  outEnd = script.sectionMap().end();
2217  for (out = outBegin; out != outEnd; prev = cur, ++out) {
2218    cur = (*out)->getSection();
2219
2220    if (cur->kind() == LDFileFormat::Null) {
2221      cur->setOffset(0x0);
2222      continue;
2223    }
2224
2225    // process dot assignments between 2 output sections
2226    for (SectionMap::Output::dot_iterator it = (*out)->dot_begin(),
2227      ie = (*out)->dot_end(); it != ie; ++it) {
2228      (*it).assign(evaluator);
2229    }
2230
2231    seg = elfSegmentTable().find(llvm::ELF::PT_LOAD, cur);
2232    if (seg != segEnd && cur == (*seg)->front()) {
2233      if ((*seg)->isBssSegment())
2234        addr = script.addressMap().find(".bss");
2235      else if ((*seg)->isDataSegment())
2236        addr = script.addressMap().find(".data");
2237      else
2238        addr = script.addressMap().find(cur->name());
2239    } else
2240      addr = addrEnd;
2241
2242    if (addr != addrEnd) {
2243      // use address mapping in script options
2244      vma = addr.getEntry()->value();
2245    } else if ((*out)->prolog().hasVMA()) {
2246      // use address from output section description
2247      evaluator.eval((*out)->prolog().vma(), vma);
2248    } else if ((dot = (*out)->find_last_explicit_dot()) != (*out)->dot_end()) {
2249      // assign address based on `.' symbol in ldscript
2250      vma = (*dot).symbol().value();
2251      alignAddress(vma, cur->align());
2252    } else {
2253      if ((*out)->prolog().type() == OutputSectDesc::NOLOAD) {
2254        vma = prev->addr() + prev->size();
2255      } else if ((cur->flag() & llvm::ELF::SHF_ALLOC) != 0) {
2256        if (prev->kind() == LDFileFormat::Null) {
2257          // Let SECTIONS starts at 0 if we have a default ldscript but don't
2258          // have any initial value (VMA or `.').
2259          if (!config().options().getScriptList().empty())
2260            vma = 0x0;
2261          else
2262            vma = getSegmentStartAddr(script) + sectionStartOffset();
2263        } else {
2264          if ((prev->kind() == LDFileFormat::BSS))
2265            vma = prev->addr();
2266          else
2267            vma = prev->addr() + prev->size();
2268        }
2269        alignAddress(vma, cur->align());
2270        if (config().options().getScriptList().empty()) {
2271          if (seg != segEnd && cur == (*seg)->front()) {
2272            // Try to align p_vaddr at page boundary if not in script options.
2273            // To do so will add more padding in file, but can save one page
2274            // at runtime.
2275            alignAddress(vma, (*seg)->align());
2276          }
2277        }
2278      } else {
2279        vma = 0x0;
2280      }
2281    }
2282
2283    if (config().options().hasRelro()) {
2284      // if -z relro is given, we need to adjust sections' offset again, and
2285      // let PT_GNU_RELRO end on a abi page boundary
2286
2287      // check if current is the first non-relro section
2288      SectionMap::iterator relro_last = out - 1;
2289      if (relro_last != outEnd &&
2290          (*relro_last)->order() <= SHO_RELRO_LAST &&
2291          (*out)->order() > SHO_RELRO_LAST) {
2292        // align the first non-relro section to page boundary
2293        alignAddress(vma, abiPageSize());
2294
2295        // It seems that compiler think .got and .got.plt are continuous (w/o
2296        // any padding between). If .got is the last section in PT_RELRO and
2297        // it's not continuous to its next section (i.e. .got.plt), we need to
2298        // add padding in front of .got instead.
2299        // FIXME: Maybe we can handle this in a more general way.
2300        LDSection& got = getOutputFormat()->getGOT();
2301        if ((getSectionOrder(got) == SHO_RELRO_LAST) &&
2302            (got.addr() + got.size() < vma)) {
2303          uint64_t diff = vma - got.addr() - got.size();
2304          got.setAddr(vma - got.size());
2305          got.setOffset(got.offset() + diff);
2306        }
2307      }
2308    } // end of if - for relro processing
2309
2310    cur->setAddr(vma);
2311
2312    switch (prev->kind()) {
2313    case LDFileFormat::Null:
2314      offset = sectionStartOffset();
2315      break;
2316    case LDFileFormat::BSS:
2317      offset = prev->offset();
2318      break;
2319    default:
2320      offset = prev->offset() + prev->size();
2321      break;
2322    }
2323    alignAddress(offset, cur->align());
2324    // in p75, http://www.sco.com/developers/devspecs/gabi41.pdf
2325    // p_align: As "Program Loading" describes in this chapter of the
2326    // processor supplement, loadable process segments must have congruent
2327    // values for p_vaddr and p_offset, modulo the page size.
2328    // FIXME: Now make all sh_addr and sh_offset are congruent, modulo the page
2329    // size. Otherwise, old objcopy (e.g., binutils 2.17) may fail with our
2330    // output!
2331    if ((cur->flag() & llvm::ELF::SHF_ALLOC) != 0 &&
2332        (vma & (abiPageSize() - 1)) != (offset & (abiPageSize() - 1))) {
2333      uint64_t padding = abiPageSize() +
2334                         (vma & (abiPageSize() - 1)) -
2335                         (offset & (abiPageSize() - 1));
2336      offset += padding;
2337    }
2338
2339    cur->setOffset(offset);
2340
2341    // process dot assignments in the output section
2342    bool changed = false;
2343    Fragment* invalid = NULL;
2344    for (SectionMap::Output::iterator in = (*out)->begin(),
2345      inEnd = (*out)->end(); in != inEnd; ++in) {
2346
2347      if (invalid != NULL && !(*in)->dotAssignments().empty()) {
2348        while (invalid != (*in)->dotAssignments().front().first) {
2349          Fragment* prev = invalid->getPrevNode();
2350          invalid->setOffset(prev->getOffset() + prev->size());
2351          invalid = invalid->getNextNode();
2352        }
2353        invalid = NULL;
2354      }
2355
2356      for (SectionMap::Input::dot_iterator it = (*in)->dot_begin(),
2357        ie = (*in)->dot_end(); it != ie; ++it) {
2358        (*it).second.assign(evaluator);
2359        if ((*it).first != NULL) {
2360          uint64_t new_offset = (*it).second.symbol().value() - vma;
2361          if (new_offset != (*it).first->getOffset()) {
2362            (*it).first->setOffset(new_offset);
2363            invalid = (*it).first->getNextNode();
2364            changed = true;
2365          }
2366        }
2367      } // for each dot assignment
2368    } // for each input description
2369
2370    if (changed) {
2371      while (invalid != NULL) {
2372        Fragment* prev = invalid->getPrevNode();
2373        invalid->setOffset(prev->getOffset() + prev->size());
2374        invalid = invalid->getNextNode();
2375      }
2376
2377      cur->setSize(cur->getSectionData()->back().getOffset() +
2378                   cur->getSectionData()->back().size());
2379    }
2380
2381  } // for each output section description
2382}
2383
2384/// placeOutputSections - place output sections based on SectionMap
2385void GNULDBackend::placeOutputSections(Module& pModule)
2386{
2387  typedef std::vector<LDSection*> Orphans;
2388  Orphans orphans;
2389  SectionMap& sectionMap = pModule.getScript().sectionMap();
2390
2391  for (Module::iterator it = pModule.begin(), ie = pModule.end(); it != ie;
2392    ++it) {
2393    bool wanted = false;
2394
2395    switch ((*it)->kind()) {
2396    // take NULL and StackNote directly
2397    case LDFileFormat::Null:
2398    case LDFileFormat::StackNote:
2399      wanted = true;
2400      break;
2401    // ignore if section size is 0
2402    case LDFileFormat::EhFrame:
2403      if (((*it)->size() != 0) ||
2404          ((*it)->hasEhFrame() &&
2405           config().codeGenType() == LinkerConfig::Object))
2406        wanted = true;
2407      break;
2408    case LDFileFormat::Relocation:
2409      if (((*it)->size() != 0) ||
2410          ((*it)->hasRelocData() &&
2411           config().codeGenType() == LinkerConfig::Object))
2412        wanted = true;
2413      break;
2414    case LDFileFormat::Regular:
2415    case LDFileFormat::Target:
2416    case LDFileFormat::MetaData:
2417    case LDFileFormat::BSS:
2418    case LDFileFormat::Debug:
2419    case LDFileFormat::GCCExceptTable:
2420    case LDFileFormat::Note:
2421    case LDFileFormat::NamePool:
2422    case LDFileFormat::EhFrameHdr:
2423      if (((*it)->size() != 0) ||
2424          ((*it)->hasSectionData() &&
2425           config().codeGenType() == LinkerConfig::Object))
2426        wanted = true;
2427      break;
2428    case LDFileFormat::Group:
2429      if (LinkerConfig::Object == config().codeGenType()) {
2430        //TODO: support incremental linking
2431        ;
2432      }
2433      break;
2434    case LDFileFormat::Version:
2435      if ((*it)->size() != 0) {
2436        wanted = true;
2437        warning(diag::warn_unsupported_symbolic_versioning) << (*it)->name();
2438      }
2439      break;
2440    default:
2441      if ((*it)->size() != 0) {
2442        error(diag::err_unsupported_section) << (*it)->name() << (*it)->kind();
2443      }
2444      break;
2445    } // end of switch
2446
2447    if (wanted) {
2448      SectionMap::iterator out, outBegin, outEnd;
2449      outBegin = sectionMap.begin();
2450      outEnd = sectionMap.end();
2451      for (out = outBegin; out != outEnd; ++out) {
2452        bool matched = false;
2453        if ((*it)->name().compare((*out)->name()) == 0) {
2454          switch ((*out)->prolog().constraint()) {
2455          case OutputSectDesc::NO_CONSTRAINT:
2456            matched = true;
2457            break;
2458          case OutputSectDesc::ONLY_IF_RO:
2459            matched = ((*it)->flag() & llvm::ELF::SHF_WRITE) == 0;
2460            break;
2461          case OutputSectDesc::ONLY_IF_RW:
2462            matched = ((*it)->flag() & llvm::ELF::SHF_WRITE) != 0;
2463            break;
2464          } // end of switch
2465
2466          if (matched)
2467            break;
2468        }
2469      } // for each output section description
2470
2471      if (out != outEnd) {
2472        // set up the section
2473        (*out)->setSection(*it);
2474        (*out)->setOrder(getSectionOrder(**it));
2475      } else {
2476        orphans.push_back(*it);
2477      }
2478    }
2479  } // for each section in Module
2480
2481  // set up sections in SectionMap but do not exist at all.
2482  uint32_t flag = 0x0;
2483  unsigned int order = SHO_UNDEFINED;
2484  OutputSectDesc::Type type = OutputSectDesc::LOAD;
2485  for (SectionMap::reverse_iterator out = sectionMap.rbegin(),
2486    outEnd = sectionMap.rend(); out != outEnd; ++out) {
2487    if ((*out)->hasContent() ||
2488        (*out)->getSection()->kind() == LDFileFormat::Null ||
2489        (*out)->getSection()->kind() == LDFileFormat::StackNote) {
2490      flag = (*out)->getSection()->flag();
2491      order = (*out)->order();
2492      type = (*out)->prolog().type();
2493    } else {
2494      (*out)->getSection()->setFlag(flag);
2495      (*out)->setOrder(order);
2496      (*out)->prolog().setType(type);
2497    }
2498  } // for each output section description
2499
2500  // place orphan sections
2501  for (Orphans::iterator it = orphans.begin(), ie = orphans.end(); it != ie;
2502    ++it) {
2503    size_t order = getSectionOrder(**it);
2504    SectionMap::iterator out, outBegin, outEnd;
2505    outBegin = sectionMap.begin();
2506    outEnd = sectionMap.end();
2507
2508    if ((*it)->kind() == LDFileFormat::Null)
2509      out = sectionMap.insert(outBegin, *it);
2510    else {
2511      for (out = outBegin; out != outEnd; ++out) {
2512        if ((*out)->order() > order)
2513          break;
2514      }
2515      out = sectionMap.insert(out, *it);
2516    }
2517    (*out)->setOrder(order);
2518  } // for each orphan section
2519
2520  // sort output section orders if there is no default ldscript
2521  if (config().options().getScriptList().empty()) {
2522    std::stable_sort(sectionMap.begin(),
2523                     sectionMap.end(),
2524                     SectionMap::SHOCompare());
2525  }
2526
2527  // when section ordering is fixed, now we can make sure dot assignments are
2528  // all set appropriately
2529  sectionMap.fixupDotSymbols();
2530}
2531
2532/// layout - layout method
2533void GNULDBackend::layout(Module& pModule)
2534{
2535  // 1. place output sections based on SectionMap from SECTIONS command
2536  placeOutputSections(pModule);
2537
2538  // 2. update output sections in Module
2539  SectionMap& sectionMap = pModule.getScript().sectionMap();
2540  pModule.getSectionTable().clear();
2541  for (SectionMap::iterator out = sectionMap.begin(), outEnd = sectionMap.end();
2542    out != outEnd; ++out) {
2543    if ((*out)->hasContent() ||
2544        (*out)->getSection()->kind() == LDFileFormat::Null ||
2545        (*out)->getSection()->kind() == LDFileFormat::StackNote ||
2546        config().codeGenType() == LinkerConfig::Object) {
2547      (*out)->getSection()->setIndex(pModule.size());
2548      pModule.getSectionTable().push_back((*out)->getSection());
2549    }
2550  } // for each output section description
2551
2552  // 3. update the size of .shstrtab
2553  sizeShstrtab(pModule);
2554
2555  // 4. create program headers
2556  if (LinkerConfig::Object != config().codeGenType()) {
2557    createProgramHdrs(pModule);
2558  }
2559
2560  // 5. set output section address/offset
2561  if (LinkerConfig::Object != config().codeGenType())
2562    setOutputSectionAddress(pModule);
2563  else
2564    setOutputSectionOffset(pModule);
2565}
2566
2567void GNULDBackend::createAndSizeEhFrameHdr(Module& pModule)
2568{
2569  if (LinkerConfig::Object != config().codeGenType() &&
2570      config().options().hasEhFrameHdr() && getOutputFormat()->hasEhFrame()) {
2571    // init EhFrameHdr and size the output section
2572    ELFFileFormat* format = getOutputFormat();
2573    m_pEhFrameHdr = new EhFrameHdr(format->getEhFrameHdr(),
2574                                   format->getEhFrame());
2575    m_pEhFrameHdr->sizeOutput();
2576  }
2577}
2578
2579/// preLayout - Backend can do any needed modification before layout
2580void GNULDBackend::preLayout(Module& pModule, IRBuilder& pBuilder)
2581{
2582  // prelayout target first
2583  doPreLayout(pBuilder);
2584
2585  // change .tbss and .tdata section symbol from Local to LocalDyn category
2586  if (NULL != f_pTDATA)
2587    pModule.getSymbolTable().changeToDynamic(*f_pTDATA);
2588
2589  if (NULL != f_pTBSS)
2590    pModule.getSymbolTable().changeToDynamic(*f_pTBSS);
2591
2592  // To merge input's relocation sections into output's relocation sections.
2593  //
2594  // If we are generating relocatables (-r), move input relocation sections
2595  // to corresponding output relocation sections.
2596  if (LinkerConfig::Object == config().codeGenType()) {
2597    Module::obj_iterator input, inEnd = pModule.obj_end();
2598    for (input = pModule.obj_begin(); input != inEnd; ++input) {
2599      LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd();
2600      for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) {
2601
2602        // get the output relocation LDSection with identical name.
2603        LDSection* output_sect = pModule.getSection((*rs)->name());
2604        if (NULL == output_sect) {
2605          output_sect = LDSection::Create((*rs)->name(),
2606                                          (*rs)->kind(),
2607                                          (*rs)->type(),
2608                                          (*rs)->flag());
2609
2610          output_sect->setAlign((*rs)->align());
2611          pModule.getSectionTable().push_back(output_sect);
2612        }
2613
2614        // set output relocation section link
2615        const LDSection* input_link = (*rs)->getLink();
2616        assert(NULL != input_link && "Illegal input relocation section.");
2617
2618        // get the linked output section
2619        LDSection* output_link = pModule.getSection(input_link->name());
2620        assert(NULL != output_link);
2621
2622        output_sect->setLink(output_link);
2623
2624        // get output relcoationData, create one if not exist
2625        if (!output_sect->hasRelocData())
2626          IRBuilder::CreateRelocData(*output_sect);
2627
2628        RelocData* out_reloc_data = output_sect->getRelocData();
2629
2630        // move relocations from input's to output's RelcoationData
2631        RelocData::RelocationListType& out_list =
2632                                             out_reloc_data->getRelocationList();
2633        RelocData::RelocationListType& in_list =
2634                                      (*rs)->getRelocData()->getRelocationList();
2635        out_list.splice(out_list.end(), in_list);
2636
2637        // size output
2638        if (llvm::ELF::SHT_REL == output_sect->type())
2639          output_sect->setSize(out_reloc_data->size() * getRelEntrySize());
2640        else if (llvm::ELF::SHT_RELA == output_sect->type())
2641          output_sect->setSize(out_reloc_data->size() * getRelaEntrySize());
2642        else {
2643          fatal(diag::unknown_reloc_section_type) << output_sect->type()
2644                                                  << output_sect->name();
2645        }
2646      } // end of for each relocation section
2647    } // end of for each input
2648  } // end of if
2649
2650  // set up the section flag of .note.GNU-stack section
2651  setupGNUStackInfo(pModule);
2652}
2653
2654/// postLayout - Backend can do any needed modification after layout
2655void GNULDBackend::postLayout(Module& pModule, IRBuilder& pBuilder)
2656{
2657  if (LinkerConfig::Object != config().codeGenType()) {
2658    // do relaxation
2659    relax(pModule, pBuilder);
2660    // set up the attributes of program headers
2661    setupProgramHdrs(pModule.getScript());
2662  }
2663
2664  doPostLayout(pModule, pBuilder);
2665}
2666
2667void GNULDBackend::postProcessing(FileOutputBuffer& pOutput)
2668{
2669  if (LinkerConfig::Object != config().codeGenType() &&
2670      config().options().hasEhFrameHdr() && getOutputFormat()->hasEhFrame()) {
2671    // emit eh_frame_hdr
2672    m_pEhFrameHdr->emitOutput<32>(pOutput);
2673  }
2674}
2675
2676/// getHashBucketCount - calculate hash bucket count.
2677/// @ref Google gold linker, dynobj.cc:791
2678unsigned GNULDBackend::getHashBucketCount(unsigned pNumOfSymbols,
2679                                          bool pIsGNUStyle)
2680{
2681  // @ref Google gold, dynobj.cc:loc 791
2682  static const unsigned int buckets[] =
2683  {
2684    1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
2685    16411, 32771, 65537, 131101, 262147
2686  };
2687  const unsigned buckets_count = sizeof buckets / sizeof buckets[0];
2688
2689  unsigned int result = 1;
2690  for (unsigned i = 0; i < buckets_count; ++i) {
2691    if (pNumOfSymbols < buckets[i])
2692      break;
2693    result = buckets[i];
2694  }
2695
2696  if (pIsGNUStyle && result < 2)
2697    result = 2;
2698
2699  return result;
2700}
2701
2702/// getGNUHashMaskbitslog2 - calculate the number of mask bits in log2
2703/// @ref binutils gold, dynobj.cc:1165
2704unsigned GNULDBackend::getGNUHashMaskbitslog2(unsigned pNumOfSymbols) const
2705{
2706  uint32_t maskbitslog2 = 1;
2707  for (uint32_t x = pNumOfSymbols >> 1; x != 0; x >>=1)
2708    ++maskbitslog2;
2709
2710  if (maskbitslog2 < 3)
2711    maskbitslog2 = 5;
2712  else if (((1U << (maskbitslog2 - 2)) & pNumOfSymbols) != 0)
2713    maskbitslog2 += 3;
2714  else
2715    maskbitslog2 += 2;
2716
2717  if (config().targets().bitclass() == 64 && maskbitslog2 == 5)
2718    maskbitslog2 = 6;
2719
2720  return maskbitslog2;
2721}
2722
2723/// isDynamicSymbol
2724/// @ref Google gold linker: symtab.cc:311
2725bool GNULDBackend::isDynamicSymbol(const LDSymbol& pSymbol) const
2726{
2727  // If a local symbol is in the LDContext's symbol table, it's a real local
2728  // symbol. We should not add it
2729  if (pSymbol.binding() == ResolveInfo::Local)
2730    return false;
2731
2732  // If we are building shared object, and the visibility is external, we
2733  // need to add it.
2734  if (LinkerConfig::DynObj == config().codeGenType() ||
2735      LinkerConfig::Exec   == config().codeGenType() ||
2736      LinkerConfig::Binary == config().codeGenType()) {
2737    if (pSymbol.resolveInfo()->visibility() == ResolveInfo::Default ||
2738        pSymbol.resolveInfo()->visibility() == ResolveInfo::Protected)
2739      return true;
2740  }
2741  return false;
2742}
2743
2744/// isDynamicSymbol
2745/// @ref Google gold linker: symtab.cc:311
2746bool GNULDBackend::isDynamicSymbol(const ResolveInfo& pResolveInfo) const
2747{
2748  // If a local symbol is in the LDContext's symbol table, it's a real local
2749  // symbol. We should not add it
2750  if (pResolveInfo.binding() == ResolveInfo::Local)
2751    return false;
2752
2753  // If we are building shared object, and the visibility is external, we
2754  // need to add it.
2755  if (LinkerConfig::DynObj == config().codeGenType() ||
2756      LinkerConfig::Exec   == config().codeGenType() ||
2757      LinkerConfig::Binary == config().codeGenType()) {
2758    if (pResolveInfo.visibility() == ResolveInfo::Default ||
2759        pResolveInfo.visibility() == ResolveInfo::Protected)
2760      return true;
2761  }
2762  return false;
2763}
2764
2765/// elfSegmentTable - return the reference of the elf segment table
2766ELFSegmentFactory& GNULDBackend::elfSegmentTable()
2767{
2768  assert(m_pELFSegmentTable != NULL && "Do not create ELFSegmentTable!");
2769  return *m_pELFSegmentTable;
2770}
2771
2772/// elfSegmentTable - return the reference of the elf segment table
2773const ELFSegmentFactory& GNULDBackend::elfSegmentTable() const
2774{
2775  assert(m_pELFSegmentTable != NULL && "Do not create ELFSegmentTable!");
2776  return *m_pELFSegmentTable;
2777}
2778
2779/// commonPageSize - the common page size of the target machine.
2780/// @ref gold linker: target.h:135
2781uint64_t GNULDBackend::commonPageSize() const
2782{
2783  if (config().options().commPageSize() > 0)
2784    return std::min(config().options().commPageSize(), abiPageSize());
2785  else
2786    return std::min(m_pInfo->commonPageSize(), abiPageSize());
2787}
2788
2789/// abiPageSize - the abi page size of the target machine.
2790/// @ref gold linker: target.h:125
2791uint64_t GNULDBackend::abiPageSize() const
2792{
2793  if (config().options().maxPageSize() > 0)
2794    return config().options().maxPageSize();
2795  else
2796    return m_pInfo->abiPageSize();
2797}
2798
2799/// isSymbolPreemtible - whether the symbol can be preemted by other
2800/// link unit
2801/// @ref Google gold linker, symtab.h:551
2802bool GNULDBackend::isSymbolPreemptible(const ResolveInfo& pSym) const
2803{
2804  if (pSym.other() != ResolveInfo::Default)
2805    return false;
2806
2807  // This is because the codeGenType of pie is DynObj. And gold linker check
2808  // the "shared" option instead.
2809  if (config().options().isPIE())
2810    return false;
2811
2812  if (LinkerConfig::DynObj != config().codeGenType())
2813    return false;
2814
2815  if (config().options().Bsymbolic())
2816    return false;
2817
2818  // A local defined symbol should be non-preemptible.
2819  // This issue is found when linking libstdc++ on freebsd. A R_386_GOT32
2820  // relocation refers to a local defined symbol, and we should generate a
2821  // relative dynamic relocation when applying the relocation.
2822  if (pSym.isDefine() && pSym.binding() == ResolveInfo::Local)
2823    return false;
2824
2825  return true;
2826}
2827
2828/// symbolNeedsDynRel - return whether the symbol needs a dynamic relocation
2829/// @ref Google gold linker, symtab.h:645
2830bool GNULDBackend::symbolNeedsDynRel(const ResolveInfo& pSym,
2831                                     bool pSymHasPLT,
2832                                     bool isAbsReloc) const
2833{
2834  // an undefined reference in the executables should be statically
2835  // resolved to 0 and no need a dynamic relocation
2836  if (pSym.isUndef() &&
2837      !pSym.isDyn() &&
2838      (LinkerConfig::Exec   == config().codeGenType() ||
2839       LinkerConfig::Binary == config().codeGenType()))
2840    return false;
2841
2842  // An absolute symbol can be resolved directly if it is either local
2843  // or we are linking statically. Otherwise it can still be overridden
2844  // at runtime.
2845  if (pSym.isAbsolute() &&
2846      (pSym.binding() == ResolveInfo::Local || config().isCodeStatic()))
2847    return false;
2848  if (config().isCodeIndep() && isAbsReloc)
2849    return true;
2850  if (pSymHasPLT && ResolveInfo::Function == pSym.type())
2851    return false;
2852  if (!config().isCodeIndep() && pSymHasPLT)
2853    return false;
2854  if (pSym.isDyn() || pSym.isUndef() ||
2855      isSymbolPreemptible(pSym))
2856    return true;
2857
2858  return false;
2859}
2860
2861/// symbolNeedsPLT - return whether the symbol needs a PLT entry
2862/// @ref Google gold linker, symtab.h:596
2863bool GNULDBackend::symbolNeedsPLT(const ResolveInfo& pSym) const
2864{
2865  if (pSym.isUndef() &&
2866      !pSym.isDyn() &&
2867      LinkerConfig::DynObj != config().codeGenType())
2868    return false;
2869
2870  // An IndirectFunc symbol (i.e., STT_GNU_IFUNC) always needs a plt entry
2871  if (pSym.type() == ResolveInfo::IndirectFunc)
2872    return true;
2873
2874  if (pSym.type() != ResolveInfo::Function)
2875    return false;
2876
2877  if (config().isCodeStatic())
2878    return false;
2879
2880  if (config().options().isPIE())
2881    return false;
2882
2883  return (pSym.isDyn() ||
2884          pSym.isUndef() ||
2885          isSymbolPreemptible(pSym));
2886}
2887
2888/// symbolHasFinalValue - return true if the symbol's value can be decided at
2889/// link time
2890/// @ref Google gold linker, Symbol::final_value_is_known
2891bool GNULDBackend::symbolFinalValueIsKnown(const ResolveInfo& pSym) const
2892{
2893  // if the output is pic code or if not executables, symbols' value may change
2894  // at runtime
2895  // FIXME: CodeIndep() || LinkerConfig::Relocatable == CodeGenType
2896  if (config().isCodeIndep() ||
2897      (LinkerConfig::Exec != config().codeGenType() &&
2898       LinkerConfig::Binary != config().codeGenType()))
2899    return false;
2900
2901  // if the symbol is from dynamic object, then its value is unknown
2902  if (pSym.isDyn())
2903    return false;
2904
2905  // if the symbol is not in dynamic object and is not undefined, then its value
2906  // is known
2907  if (!pSym.isUndef())
2908    return true;
2909
2910  // if the symbol is undefined and not in dynamic objects, for example, a weak
2911  // undefined symbol, then whether the symbol's final value can be known
2912  // depends on whrther we're doing static link
2913  return config().isCodeStatic();
2914}
2915
2916/// symbolNeedsCopyReloc - return whether the symbol needs a copy relocation
2917bool GNULDBackend::symbolNeedsCopyReloc(const Relocation& pReloc,
2918                                        const ResolveInfo& pSym) const
2919{
2920  // only the reference from dynamic executable to non-function symbol in
2921  // the dynamic objects may need copy relocation
2922  if (config().isCodeIndep() ||
2923      !pSym.isDyn() ||
2924      pSym.type() == ResolveInfo::Function ||
2925      pSym.size() == 0)
2926    return false;
2927
2928  // check if the option -z nocopyreloc is given
2929  if (config().options().hasNoCopyReloc())
2930    return false;
2931
2932  // TODO: Is this check necessary?
2933  // if relocation target place is readonly, a copy relocation is needed
2934  uint32_t flag = pReloc.targetRef().frag()->getParent()->getSection().flag();
2935  if (0 == (flag & llvm::ELF::SHF_WRITE))
2936    return true;
2937
2938  return false;
2939}
2940
2941LDSymbol& GNULDBackend::getTDATASymbol()
2942{
2943  assert(NULL != f_pTDATA);
2944  return *f_pTDATA;
2945}
2946
2947const LDSymbol& GNULDBackend::getTDATASymbol() const
2948{
2949  assert(NULL != f_pTDATA);
2950  return *f_pTDATA;
2951}
2952
2953LDSymbol& GNULDBackend::getTBSSSymbol()
2954{
2955  assert(NULL != f_pTBSS);
2956  return *f_pTBSS;
2957}
2958
2959const LDSymbol& GNULDBackend::getTBSSSymbol() const
2960{
2961  assert(NULL != f_pTBSS);
2962  return *f_pTBSS;
2963}
2964
2965llvm::StringRef GNULDBackend::getEntry(const Module& pModule) const
2966{
2967  if (pModule.getScript().hasEntry())
2968    return pModule.getScript().entry();
2969  else
2970    return getInfo().entry();
2971}
2972
2973void GNULDBackend::checkAndSetHasTextRel(const LDSection& pSection)
2974{
2975  if (m_bHasTextRel)
2976    return;
2977
2978  // if the target section of the dynamic relocation is ALLOCATE but is not
2979  // writable, than we should set DF_TEXTREL
2980  const uint32_t flag = pSection.flag();
2981  if (0 == (flag & llvm::ELF::SHF_WRITE) && (flag & llvm::ELF::SHF_ALLOC))
2982    m_bHasTextRel = true;
2983
2984  return;
2985}
2986
2987/// sortRelocation - sort the dynamic relocations to let dynamic linker
2988/// process relocations more efficiently
2989void GNULDBackend::sortRelocation(LDSection& pSection)
2990{
2991  if (!config().options().hasCombReloc())
2992    return;
2993
2994  assert(pSection.kind() == LDFileFormat::Relocation);
2995
2996  switch (config().codeGenType()) {
2997  case LinkerConfig::DynObj:
2998  case LinkerConfig::Exec:
2999    if (&pSection == &getOutputFormat()->getRelDyn() ||
3000        &pSection == &getOutputFormat()->getRelaDyn()) {
3001      if (pSection.hasRelocData())
3002        pSection.getRelocData()->sort(RelocCompare(*this));
3003    }
3004  default:
3005    return;
3006  }
3007}
3008
3009/// initBRIslandFactory - initialize the branch island factory for relaxation
3010bool GNULDBackend::initBRIslandFactory()
3011{
3012  if (NULL == m_pBRIslandFactory) {
3013    m_pBRIslandFactory = new BranchIslandFactory(maxBranchOffset());
3014  }
3015  return true;
3016}
3017
3018/// initStubFactory - initialize the stub factory for relaxation
3019bool GNULDBackend::initStubFactory()
3020{
3021  if (NULL == m_pStubFactory) {
3022    m_pStubFactory = new StubFactory();
3023  }
3024  return true;
3025}
3026
3027bool GNULDBackend::relax(Module& pModule, IRBuilder& pBuilder)
3028{
3029  if (!mayRelax())
3030    return true;
3031
3032  getBRIslandFactory()->group(pModule);
3033
3034  bool finished = true;
3035  do {
3036    if (doRelax(pModule, pBuilder, finished)) {
3037      setOutputSectionAddress(pModule);
3038    }
3039  } while (!finished);
3040
3041  return true;
3042}
3043
3044bool GNULDBackend::DynsymCompare::needGNUHash(const LDSymbol& X) const
3045{
3046  // FIXME: in bfd and gold linker, an undefined symbol might be hashed
3047  // when the ouput is not PIC, if the symbol is referred by a non pc-relative
3048  // reloc, and its value is set to the addr of the plt entry.
3049  return !X.resolveInfo()->isUndef() && !X.isDyn();
3050}
3051
3052bool GNULDBackend::DynsymCompare::operator()(const LDSymbol* X,
3053                                             const LDSymbol* Y) const
3054{
3055  return !needGNUHash(*X) && needGNUHash(*Y);
3056}
3057
3058bool GNULDBackend::RelocCompare::operator()(const Relocation* X,
3059                                            const Relocation* Y) const
3060{
3061  // 1. compare if relocation is relative
3062  if (X->symInfo() == NULL) {
3063    if (Y->symInfo() != NULL)
3064      return true;
3065  } else if (Y->symInfo() == NULL) {
3066    return false;
3067  } else {
3068    // 2. compare the symbol index
3069    size_t symIdxX = m_Backend.getSymbolIdx(X->symInfo()->outSymbol());
3070    size_t symIdxY = m_Backend.getSymbolIdx(Y->symInfo()->outSymbol());
3071    if (symIdxX < symIdxY)
3072      return true;
3073    if (symIdxX > symIdxY)
3074      return false;
3075  }
3076
3077  // 3. compare the relocation address
3078  if (X->place() < Y->place())
3079    return true;
3080  if (X->place() > Y->place())
3081    return false;
3082
3083  // 4. compare the relocation type
3084  if (X->type() < Y->type())
3085    return true;
3086  if (X->type() > Y->type())
3087    return false;
3088
3089  // 5. compare the addend
3090  if (X->addend() < Y->addend())
3091    return true;
3092  if (X->addend() > Y->addend())
3093    return false;
3094
3095  return false;
3096}
3097