MipsLDBackend.cpp revision d0fbbb227051be16931a1aa9b4a7722ac039c698
1//===- MipsLDBackend.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 "Mips.h"
10#include "MipsGNUInfo.h"
11#include "MipsELFDynamic.h"
12#include "MipsLDBackend.h"
13#include "MipsRelocator.h"
14
15#include <llvm/ADT/Triple.h>
16#include <llvm/Support/ELF.h>
17
18#include <mcld/Module.h>
19#include <mcld/LinkerConfig.h>
20#include <mcld/IRBuilder.h>
21#include <mcld/MC/Attribute.h>
22#include <mcld/Fragment/FillFragment.h>
23#include <mcld/Fragment/FragmentLinker.h>
24#include <mcld/Support/MemoryRegion.h>
25#include <mcld/Support/MemoryArea.h>
26#include <mcld/Support/MsgHandling.h>
27#include <mcld/Support/TargetRegistry.h>
28#include <mcld/Target/OutputRelocSection.h>
29#include <mcld/Object/ObjectBuilder.h>
30
31enum {
32  // The original o32 abi.
33  E_MIPS_ABI_O32    = 0x00001000,
34  // O32 extended to work on 64 bit architectures.
35  E_MIPS_ABI_O64    = 0x00002000,
36  // EABI in 32 bit mode.
37  E_MIPS_ABI_EABI32 = 0x00003000,
38  // EABI in 64 bit mode.
39  E_MIPS_ABI_EABI64 = 0x00004000
40};
41
42using namespace mcld;
43
44//===----------------------------------------------------------------------===//
45// MipsGNULDBackend
46//===----------------------------------------------------------------------===//
47MipsGNULDBackend::MipsGNULDBackend(const LinkerConfig& pConfig,
48                                   MipsGNUInfo* pInfo)
49  : GNULDBackend(pConfig, pInfo),
50    m_pRelocator(NULL),
51    m_pGOT(NULL),
52    m_pRelDyn(NULL),
53    m_pDynamic(NULL),
54    m_pGOTSymbol(NULL),
55    m_pGpDispSymbol(NULL)
56{
57}
58
59MipsGNULDBackend::~MipsGNULDBackend()
60{
61  delete m_pRelocator;
62  delete m_pGOT;
63  delete m_pRelDyn;
64  delete m_pDynamic;
65}
66
67void MipsGNULDBackend::initTargetSections(Module& pModule, ObjectBuilder& pBuilder)
68{
69  if (LinkerConfig::Object != config().codeGenType()) {
70    ELFFileFormat* file_format = getOutputFormat();
71
72    // initialize .got
73    LDSection& got = file_format->getGOT();
74    m_pGOT = new MipsGOT(got);
75
76    // initialize .rel.dyn
77    LDSection& reldyn = file_format->getRelDyn();
78    m_pRelDyn = new OutputRelocSection(pModule, reldyn);
79  }
80}
81
82void MipsGNULDBackend::initTargetSymbols(FragmentLinker& pLinker)
83{
84  // Define the symbol _GLOBAL_OFFSET_TABLE_ if there is a symbol with the
85  // same name in input
86  m_pGOTSymbol = pLinker.defineSymbol<FragmentLinker::AsRefered, FragmentLinker::Resolve>(
87                   "_GLOBAL_OFFSET_TABLE_",
88                   false,
89                   ResolveInfo::Object,
90                   ResolveInfo::Define,
91                   ResolveInfo::Local,
92                   0x0,  // size
93                   0x0,  // value
94                   FragmentRef::Null(), // FragRef
95                   ResolveInfo::Hidden);
96
97  m_pGpDispSymbol = pLinker.defineSymbol<FragmentLinker::AsRefered, FragmentLinker::Resolve>(
98                   "_gp_disp",
99                   false,
100                   ResolveInfo::Section,
101                   ResolveInfo::Define,
102                   ResolveInfo::Absolute,
103                   0x0,  // size
104                   0x0,  // value
105                   FragmentRef::Null(), // FragRef
106                   ResolveInfo::Default);
107
108  if (NULL != m_pGpDispSymbol) {
109    m_pGpDispSymbol->resolveInfo()->setReserved(ReserveGpDisp);
110  }
111}
112
113bool MipsGNULDBackend::initRelocator(const FragmentLinker& pLinker)
114{
115  if (NULL == m_pRelocator) {
116    m_pRelocator = new MipsRelocator(*this);
117    m_pRelocator->setFragmentLinker(pLinker);
118  }
119  return true;
120}
121
122Relocator* MipsGNULDBackend::getRelocator()
123{
124  assert(NULL != m_pRelocator);
125  return m_pRelocator;
126}
127
128void MipsGNULDBackend::scanRelocation(Relocation& pReloc,
129                                      FragmentLinker& pLinker,
130                                      Module& pModule,
131                                      const LDSection& pSection)
132{
133  // rsym - The relocation target symbol
134  ResolveInfo* rsym = pReloc.symInfo();
135  assert(NULL != rsym && "ResolveInfo of relocation not set while scanRelocation");
136
137  // Skip relocation against _gp_disp
138  if (NULL != m_pGpDispSymbol) {
139    if (pReloc.symInfo() == m_pGpDispSymbol->resolveInfo())
140      return;
141  }
142
143  pReloc.updateAddend();
144
145  if (0 == (pSection.flag() & llvm::ELF::SHF_ALLOC))
146    return;
147
148  // We test isLocal or if pInputSym is not a dynamic symbol
149  // We assume -Bsymbolic to bind all symbols internaly via !rsym->isDyn()
150  // Don't put undef symbols into local entries.
151  if ((rsym->isLocal() || !isDynamicSymbol(*rsym) ||
152      !rsym->isDyn()) && !rsym->isUndef())
153    scanLocalReloc(pReloc, pLinker);
154  else
155    scanGlobalReloc(pReloc, pLinker);
156
157  // check if we shoule issue undefined reference for the relocation target
158  // symbol
159  if (rsym->isUndef() && !rsym->isDyn() && !rsym->isWeak() && !rsym->isNull())
160    fatal(diag::undefined_reference) << rsym->name();
161
162  if ((rsym->reserved() & ReserveRel) != 0x0) {
163    // set hasTextRelSection if needed
164    checkAndSetHasTextRel(pSection);
165  }
166}
167
168uint64_t MipsGNULDBackend::flags() const
169{
170  // TODO: (simon) The correct flag's set depend on command line
171  // arguments and flags from input .o files.
172  return llvm::ELF::EF_MIPS_ARCH_32R2 |
173         llvm::ELF::EF_MIPS_NOREORDER |
174         llvm::ELF::EF_MIPS_PIC |
175         llvm::ELF::EF_MIPS_CPIC |
176         E_MIPS_ABI_O32;
177}
178
179uint64_t MipsGNULDBackend::defaultTextSegmentAddr() const
180{
181  return 0x80000;
182}
183
184uint64_t MipsGNULDBackend::abiPageSize() const
185{
186  if (config().options().maxPageSize() > 0)
187    return config().options().maxPageSize();
188  else
189    return static_cast<uint64_t>(0x10000);
190}
191
192void MipsGNULDBackend::doPreLayout(FragmentLinker& pLinker)
193{
194  // set .got size
195  // when building shared object, the .got section is must.
196  if (LinkerConfig::Object != config().codeGenType()) {
197    if (LinkerConfig::DynObj == config().codeGenType() ||
198        m_pGOT->hasGOT1() ||
199        NULL != m_pGOTSymbol) {
200      m_pGOT->finalizeSectionSize();
201      defineGOTSymbol(pLinker);
202    }
203
204    ELFFileFormat* file_format = getOutputFormat();
205    // set .rel.dyn size
206    if (!m_pRelDyn->empty())
207      file_format->getRelDyn().setSize(
208                                  m_pRelDyn->numOfRelocs() * getRelEntrySize());
209  }
210}
211void MipsGNULDBackend::doPostLayout(Module& pModule,
212                                    FragmentLinker& pLinker)
213{
214}
215
216/// dynamic - the dynamic section of the target machine.
217/// Use co-variant return type to return its own dynamic section.
218MipsELFDynamic& MipsGNULDBackend::dynamic()
219{
220  if (NULL == m_pDynamic)
221    m_pDynamic = new MipsELFDynamic(*this, config());
222
223  return *m_pDynamic;
224}
225
226/// dynamic - the dynamic section of the target machine.
227/// Use co-variant return type to return its own dynamic section.
228const MipsELFDynamic& MipsGNULDBackend::dynamic() const
229{
230  assert( NULL != m_pDynamic);
231  return *m_pDynamic;
232}
233
234uint64_t MipsGNULDBackend::emitSectionData(const LDSection& pSection,
235                                           MemoryRegion& pRegion) const
236{
237  assert(pRegion.size() && "Size of MemoryRegion is zero!");
238
239  const ELFFileFormat* file_format = getOutputFormat();
240
241  if (&pSection == &(file_format->getGOT())) {
242    assert(NULL != m_pGOT && "emitSectionData failed, m_pGOT is NULL!");
243    uint64_t result = m_pGOT->emit(pRegion);
244    return result;
245  }
246
247  fatal(diag::unrecognized_output_sectoin)
248          << pSection.name()
249          << "mclinker@googlegroups.com";
250  return 0;
251}
252/// isGlobalGOTSymbol - return true if the symbol is the global GOT entry.
253bool MipsGNULDBackend::isGlobalGOTSymbol(const LDSymbol& pSymbol) const
254{
255  return std::find(m_GlobalGOTSyms.begin(),
256                   m_GlobalGOTSyms.end(), &pSymbol) != m_GlobalGOTSyms.end();
257}
258
259/// sizeNamePools - compute the size of regular name pools
260/// In ELF executable files, regular name pools are .symtab, .strtab,
261/// .dynsym, .dynstr, .hash and .shstrtab.
262void
263MipsGNULDBackend::sizeNamePools(const Module& pModule, bool pIsStaticLink)
264{
265  // number of entries in symbol tables starts from 1 to hold the special entry
266  // at index 0 (STN_UNDEF). See ELF Spec Book I, p1-21.
267  size_t symtab = 1;
268  size_t dynsym = pIsStaticLink ? 0 : 1;
269
270  // size of string tables starts from 1 to hold the null character in their
271  // first byte
272  size_t strtab = 1;
273  size_t dynstr = pIsStaticLink ? 0 : 1;
274  size_t shstrtab = 1;
275  size_t hash   = 0;
276
277  // number of local symbol in the .dynsym
278  size_t dynsym_local_cnt = 0;
279
280  /// compute the size of .symtab, .dynsym and .strtab
281  /// @{
282  Module::const_sym_iterator symbol;
283  const Module::SymbolTable& symbols = pModule.getSymbolTable();
284  size_t str_size = 0;
285  // compute the size of symbols in Local and File category
286  Module::const_sym_iterator symEnd = symbols.localEnd();
287  for (symbol = symbols.localBegin(); symbol != symEnd; ++symbol) {
288    str_size = (*symbol)->nameSize() + 1;
289    if (!pIsStaticLink && isDynamicSymbol(**symbol)) {
290      ++dynsym;
291    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
292        dynstr += str_size;
293    }
294    ++symtab;
295    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
296      strtab += str_size;
297  }
298  // compute the size of symbols in TLS category
299  symEnd = symbols.tlsEnd();
300  for (symbol = symbols.tlsBegin(); symbol != symEnd; ++symbol) {
301    str_size = (*symbol)->nameSize() + 1;
302    if (!pIsStaticLink) {
303      ++dynsym;
304      if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
305        dynstr += str_size;
306    }
307    ++symtab;
308    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
309      strtab += str_size;
310  }
311  dynsym_local_cnt = dynsym;
312  // compute the size of the reset of symbols
313  symEnd = pModule.sym_end();
314  for (symbol = symbols.tlsEnd(); symbol != symEnd; ++symbol) {
315    str_size = (*symbol)->nameSize() + 1;
316    if (!pIsStaticLink && isDynamicSymbol(**symbol)) {
317      ++dynsym;
318    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
319        dynstr += str_size;
320    }
321    ++symtab;
322    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
323      strtab += str_size;
324  }
325
326  ELFFileFormat* file_format = getOutputFormat();
327
328  switch(config().codeGenType()) {
329    // compute size of .dynstr and .hash
330    case LinkerConfig::DynObj: {
331      // soname
332      if (!pIsStaticLink)
333        dynstr += pModule.name().size() + 1;
334    }
335    /** fall through **/
336    case LinkerConfig::Exec: {
337      // add DT_NEED strings into .dynstr and .dynamic
338      // Rules:
339      //   1. ignore --no-add-needed
340      //   2. force count in --no-as-needed
341      //   3. judge --as-needed
342      if (!pIsStaticLink) {
343        Module::const_lib_iterator lib, libEnd = pModule.lib_end();
344        for (lib = pModule.lib_begin(); lib != libEnd; ++lib) {
345          // --add-needed
346          if ((*lib)->attribute()->isAddNeeded()) {
347            // --no-as-needed
348            if (!(*lib)->attribute()->isAsNeeded()) {
349              dynstr += (*lib)->name().size() + 1;
350              dynamic().reserveNeedEntry();
351            }
352            // --as-needed
353            else if ((*lib)->isNeeded()) {
354              dynstr += (*lib)->name().size() + 1;
355              dynamic().reserveNeedEntry();
356            }
357          }
358        }
359
360        // compute .hash
361        // Both Elf32_Word and Elf64_Word are 4 bytes
362        hash = (2 + getHashBucketCount(dynsym, false) + dynsym) *
363               sizeof(llvm::ELF::Elf32_Word);
364      }
365
366      // set size
367      if (config().targets().is32Bits())
368        file_format->getDynSymTab().setSize(dynsym*sizeof(llvm::ELF::Elf32_Sym));
369      else
370        file_format->getDynSymTab().setSize(dynsym*sizeof(llvm::ELF::Elf64_Sym));
371      file_format->getDynStrTab().setSize(dynstr);
372      file_format->getHashTab().setSize(hash);
373
374      // set .dynsym sh_info to one greater than the symbol table
375      // index of the last local symbol
376      file_format->getDynSymTab().setInfo(dynsym_local_cnt);
377    }
378    /* fall through */
379    case LinkerConfig::Object: {
380      if (config().targets().is32Bits())
381        file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf32_Sym));
382      else
383        file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf64_Sym));
384      file_format->getStrTab().setSize(strtab);
385
386      // set .symtab sh_info to one greater than the symbol table
387      // index of the last local symbol
388      file_format->getSymTab().setInfo(symbols.numOfLocals() + 1);
389      break;
390    }
391    default: {
392      fatal(diag::fatal_illegal_codegen_type) << pModule.name();
393      break;
394    }
395  } // end of switch
396  /// @}
397
398  /// reserve fixed entries in the .dynamic section.
399  /// @{
400  if (LinkerConfig::DynObj == config().codeGenType() ||
401      LinkerConfig::Exec == config().codeGenType()) {
402    // Because some entries in .dynamic section need information of .dynsym,
403    // .dynstr, .symtab, .strtab and .hash, we can not reserve non-DT_NEEDED
404    // entries until we get the size of the sections mentioned above
405    dynamic().reserveEntries(*file_format);
406    file_format->getDynamic().setSize(dynamic().numOfBytes());
407  }
408  /// @}
409
410  /// compute the size of .shstrtab section.
411  /// @{
412  Module::const_iterator sect, sectEnd = pModule.end();
413  for (sect = pModule.begin(); sect != sectEnd; ++sect) {
414    // StackNote sections will always be in output!
415    if (0 != (*sect)->size() || LDFileFormat::StackNote == (*sect)->kind()) {
416      shstrtab += ((*sect)->name().size() + 1);
417    }
418  }
419  shstrtab += (strlen(".shstrtab") + 1);
420  file_format->getShStrTab().setSize(shstrtab);
421  /// @}
422}
423
424/// emitSymbol32 - emit an ELF32 symbol
425void MipsGNULDBackend::emitSymbol32(llvm::ELF::Elf32_Sym& pSym,
426                                    LDSymbol& pSymbol,
427                                    char* pStrtab,
428                                    size_t pStrtabsize,
429                                    size_t pSymtabIdx)
430{
431   // FIXME: check the endian between host and target
432   // write out symbol
433    if (ResolveInfo::Section != pSymbol.type() ||
434          &pSymbol == m_pGpDispSymbol) {
435     pSym.st_name  = pStrtabsize;
436     strcpy((pStrtab + pStrtabsize), pSymbol.name());
437   }
438   else {
439     pSym.st_name  = 0;
440   }
441   pSym.st_value = pSymbol.value();
442   pSym.st_size  = getSymbolSize(pSymbol);
443   pSym.st_info  = getSymbolInfo(pSymbol);
444   pSym.st_other = pSymbol.visibility();
445   pSym.st_shndx = getSymbolShndx(pSymbol);
446}
447
448/// emitNamePools - emit dynamic name pools - .dyntab, .dynstr, .hash
449///
450/// the size of these tables should be computed before layout
451/// layout should computes the start offset of these tables
452void MipsGNULDBackend::emitDynNamePools(const Module& pModule,
453                                        MemoryArea& pOutput)
454{
455  ELFFileFormat* file_format = getOutputFormat();
456  if (!file_format->hasDynSymTab() ||
457      !file_format->hasDynStrTab() ||
458      !file_format->hasHashTab()   ||
459      !file_format->hasDynamic())
460    return;
461
462  LDSection& symtab_sect = file_format->getDynSymTab();
463  LDSection& strtab_sect = file_format->getDynStrTab();
464  LDSection& hash_sect   = file_format->getHashTab();
465  LDSection& dyn_sect    = file_format->getDynamic();
466
467  MemoryRegion* symtab_region = pOutput.request(symtab_sect.offset(),
468                                                symtab_sect.size());
469  MemoryRegion* strtab_region = pOutput.request(strtab_sect.offset(),
470                                                strtab_sect.size());
471  MemoryRegion* hash_region   = pOutput.request(hash_sect.offset(),
472                                                hash_sect.size());
473  MemoryRegion* dyn_region    = pOutput.request(dyn_sect.offset(),
474                                                dyn_sect.size());
475
476  // set up symtab_region
477  llvm::ELF::Elf32_Sym* symtab32 = NULL;
478  symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region->start();
479
480  symtab32[0].st_name  = 0;
481  symtab32[0].st_value = 0;
482  symtab32[0].st_size  = 0;
483  symtab32[0].st_info  = 0;
484  symtab32[0].st_other = 0;
485  symtab32[0].st_shndx = 0;
486
487  // set up strtab_region
488  char* strtab = (char*)strtab_region->start();
489  strtab[0] = '\0';
490
491  bool sym_exist = false;
492  HashTableType::entry_type* entry = 0;
493
494  // add index 0 symbol into SymIndexMap
495  entry = m_pSymIndexMap->insert(NULL, sym_exist);
496  entry->setValue(0);
497
498  size_t symtabIdx = 1;
499  size_t strtabsize = 1;
500
501  // emit of .dynsym, and .dynstr except GOT entries
502  Module::const_sym_iterator symbol;
503  const Module::SymbolTable& symbols = pModule.getSymbolTable();
504  // emit symbol in File and Local category if it's dynamic symbol
505  Module::const_sym_iterator symEnd = symbols.localEnd();
506  for (symbol = symbols.localBegin(); symbol != symEnd; ++symbol) {
507    if (!isDynamicSymbol(**symbol))
508      continue;
509
510    if (isGlobalGOTSymbol(**symbol))
511      continue;
512
513    emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize,
514                   symtabIdx);
515
516    // maintain output's symbol and index map
517    entry = m_pSymIndexMap->insert(*symbol, sym_exist);
518    entry->setValue(symtabIdx);
519    // sum up counters
520    ++symtabIdx;
521    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
522      strtabsize += (*symbol)->nameSize() + 1;
523  }
524
525  // emit symbols in TLS category, all symbols in TLS category shold be emitited
526  // directly, except GOT entries
527  symEnd = symbols.tlsEnd();
528  for (symbol = symbols.tlsBegin(); symbol != symEnd; ++symbol) {
529    if (isGlobalGOTSymbol(**symbol))
530      continue;
531
532    emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize,
533                   symtabIdx);
534
535    // maintain output's symbol and index map
536    entry = m_pSymIndexMap->insert(*symbol, sym_exist);
537    entry->setValue(symtabIdx);
538    // sum up counters
539    ++symtabIdx;
540    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
541      strtabsize += (*symbol)->nameSize() + 1;
542  }
543
544  // emit the reset of the symbols if the symbol is dynamic symbol
545  symEnd = pModule.sym_end();
546  for (symbol = symbols.tlsEnd(); symbol != symEnd; ++symbol) {
547    if (!isDynamicSymbol(**symbol))
548      continue;
549
550    if (isGlobalGOTSymbol(**symbol))
551      continue;
552
553    emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize,
554                   symtabIdx);
555
556    // maintain output's symbol and index map
557    entry = m_pSymIndexMap->insert(*symbol, sym_exist);
558    entry->setValue(symtabIdx);
559    // sum up counters
560    ++symtabIdx;
561    if (ResolveInfo::Section != (*symbol)->type() || *symbol == m_pGpDispSymbol)
562      strtabsize += (*symbol)->nameSize() + 1;
563  }
564
565  // emit global GOT
566  for (std::vector<LDSymbol*>::const_iterator symbol = m_GlobalGOTSyms.begin(),
567       symbol_end = m_GlobalGOTSyms.end();
568       symbol != symbol_end; ++symbol) {
569
570    // Make sure this golbal GOT entry is a dynamic symbol.
571    // If not, something is wrong earlier when putting this symbol into
572    //  global GOT.
573    if (!isDynamicSymbol(**symbol))
574      fatal(diag::mips_got_symbol) << (*symbol)->name();
575
576    emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize,
577                   symtabIdx);
578    // maintain output's symbol and index map
579    entry = m_pSymIndexMap->insert(*symbol, sym_exist);
580    entry->setValue(symtabIdx);
581
582    // sum up counters
583    ++symtabIdx;
584    if (ResolveInfo::Section != (*symbol)->type())
585      strtabsize += (*symbol)->nameSize() + 1;
586  }
587
588  // emit DT_NEED
589  // add DT_NEED strings into .dynstr
590  // Rules:
591  //   1. ignore --no-add-needed
592  //   2. force count in --no-as-needed
593  //   3. judge --as-needed
594  ELFDynamic::iterator dt_need = dynamic().needBegin();
595  Module::const_lib_iterator lib, libEnd = pModule.lib_end();
596  for (lib = pModule.lib_begin(); lib != libEnd; ++lib) {
597    // --add-needed
598    if ((*lib)->attribute()->isAddNeeded()) {
599      // --no-as-needed
600      if (!(*lib)->attribute()->isAsNeeded()) {
601        strcpy((strtab + strtabsize), (*lib)->name().c_str());
602        (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize);
603        strtabsize += (*lib)->name().size() + 1;
604        ++dt_need;
605      }
606      // --as-needed
607      else if ((*lib)->isNeeded()) {
608        strcpy((strtab + strtabsize), (*lib)->name().c_str());
609        (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize);
610        strtabsize += (*lib)->name().size() + 1;
611        ++dt_need;
612      }
613    }
614  } // for
615
616  // emit soname
617  // initialize value of ELF .dynamic section
618  if (LinkerConfig::DynObj == config().codeGenType())
619    dynamic().applySoname(strtabsize);
620  dynamic().applyEntries(*file_format);
621  dynamic().emit(dyn_sect, *dyn_region);
622
623  strcpy((strtab + strtabsize), pModule.name().c_str());
624  strtabsize += pModule.name().size() + 1;
625
626  // emit hash table
627  // FIXME: this verion only emit SVR4 hash section.
628  //        Please add GNU new hash section
629
630  // both 32 and 64 bits hash table use 32-bit entry
631  // set up hash_region
632  uint32_t* word_array = (uint32_t*)hash_region->start();
633  uint32_t& nbucket = word_array[0];
634  uint32_t& nchain  = word_array[1];
635
636  nbucket = getHashBucketCount(symtabIdx, false);
637  nchain  = symtabIdx;
638
639  uint32_t* bucket = (word_array + 2);
640  uint32_t* chain  = (bucket + nbucket);
641
642  // initialize bucket
643  bzero((void*)bucket, nbucket);
644
645  StringHash<ELF> hash_func;
646
647  for (size_t sym_idx=0; sym_idx < symtabIdx; ++sym_idx) {
648    llvm::StringRef name(strtab + symtab32[sym_idx].st_name);
649    size_t bucket_pos = hash_func(name) % nbucket;
650    chain[sym_idx] = bucket[bucket_pos];
651    bucket[bucket_pos] = sym_idx;
652  }
653
654}
655
656MipsGOT& MipsGNULDBackend::getGOT()
657{
658  assert(NULL != m_pGOT);
659  return *m_pGOT;
660}
661
662const MipsGOT& MipsGNULDBackend::getGOT() const
663{
664  assert(NULL != m_pGOT);
665  return *m_pGOT;
666}
667
668OutputRelocSection& MipsGNULDBackend::getRelDyn()
669{
670  assert(NULL != m_pRelDyn);
671  return *m_pRelDyn;
672}
673
674const OutputRelocSection& MipsGNULDBackend::getRelDyn() const
675{
676  assert(NULL != m_pRelDyn);
677  return *m_pRelDyn;
678}
679
680unsigned int
681MipsGNULDBackend::getTargetSectionOrder(const LDSection& pSectHdr) const
682{
683  const ELFFileFormat* file_format = getOutputFormat();
684
685  if (&pSectHdr == &file_format->getGOT())
686    return SHO_DATA;
687
688  return SHO_UNDEFINED;
689}
690
691/// finalizeSymbol - finalize the symbol value
692bool MipsGNULDBackend::finalizeTargetSymbols(FragmentLinker& pLinker)
693{
694  if (NULL != m_pGpDispSymbol)
695    m_pGpDispSymbol->setValue(m_pGOT->addr() + 0x7FF0);
696  return true;
697}
698
699/// allocateCommonSymbols - allocate common symbols in the corresponding
700/// sections. This is called at pre-layout stage.
701/// @refer Google gold linker: common.cc: 214
702/// FIXME: Mips needs to allocate small common symbol
703bool MipsGNULDBackend::allocateCommonSymbols(Module& pModule)
704{
705  SymbolCategory& symbol_list = pModule.getSymbolTable();
706
707  if (symbol_list.emptyCommons() && symbol_list.emptyLocals())
708    return true;
709
710  SymbolCategory::iterator com_sym, com_end;
711
712  // FIXME: If the order of common symbols is defined, then sort common symbols
713  // std::sort(com_sym, com_end, some kind of order);
714
715  // get corresponding BSS LDSection
716  ELFFileFormat* file_format = getOutputFormat();
717  LDSection& bss_sect = file_format->getBSS();
718  LDSection& tbss_sect = file_format->getTBSS();
719
720  // get or create corresponding BSS SectionData
721  SectionData* bss_sect_data = NULL;
722  if (bss_sect.hasSectionData())
723    bss_sect_data = bss_sect.getSectionData();
724  else
725    bss_sect_data = IRBuilder::CreateSectionData(bss_sect);
726
727  SectionData* tbss_sect_data = NULL;
728  if (tbss_sect.hasSectionData())
729    tbss_sect_data = tbss_sect.getSectionData();
730  else
731    tbss_sect_data = IRBuilder::CreateSectionData(tbss_sect);
732
733  // remember original BSS size
734  uint64_t bss_offset  = bss_sect.size();
735  uint64_t tbss_offset = tbss_sect.size();
736
737  // allocate all local common symbols
738  com_end = symbol_list.localEnd();
739
740  for (com_sym = symbol_list.localBegin(); com_sym != com_end; ++com_sym) {
741    if (ResolveInfo::Common == (*com_sym)->desc()) {
742      // We have to reset the description of the symbol here. When doing
743      // incremental linking, the output relocatable object may have common
744      // symbols. Therefore, we can not treat common symbols as normal symbols
745      // when emitting the regular name pools. We must change the symbols'
746      // description here.
747      (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define);
748      Fragment* frag = new FillFragment(0x0, 1, (*com_sym)->size());
749      (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0));
750
751      if (ResolveInfo::ThreadLocal == (*com_sym)->type()) {
752        // allocate TLS common symbol in tbss section
753        tbss_offset += ObjectBuilder::AppendFragment(*frag,
754                                                     *tbss_sect_data,
755                                                     (*com_sym)->value());
756      }
757      // FIXME: how to identify small and large common symbols?
758      else {
759        bss_offset += ObjectBuilder::AppendFragment(*frag,
760                                                    *bss_sect_data,
761                                                    (*com_sym)->value());
762      }
763    }
764  }
765
766  // allocate all global common symbols
767  com_end = symbol_list.commonEnd();
768  for (com_sym = symbol_list.commonBegin(); com_sym != com_end; ++com_sym) {
769    // We have to reset the description of the symbol here. When doing
770    // incremental linking, the output relocatable object may have common
771    // symbols. Therefore, we can not treat common symbols as normal symbols
772    // when emitting the regular name pools. We must change the symbols'
773    // description here.
774    (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define);
775    Fragment* frag = new FillFragment(0x0, 1, (*com_sym)->size());
776    (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0));
777
778    if (ResolveInfo::ThreadLocal == (*com_sym)->type()) {
779      // allocate TLS common symbol in tbss section
780      tbss_offset += ObjectBuilder::AppendFragment(*frag,
781                                                   *tbss_sect_data,
782                                                   (*com_sym)->value());
783    }
784    // FIXME: how to identify small and large common symbols?
785    else {
786      bss_offset += ObjectBuilder::AppendFragment(*frag,
787                                                  *bss_sect_data,
788                                                  (*com_sym)->value());
789    }
790  }
791
792  bss_sect.setSize(bss_offset);
793  tbss_sect.setSize(tbss_offset);
794  symbol_list.changeCommonsToGlobal();
795  return true;
796}
797
798void MipsGNULDBackend::scanLocalReloc(Relocation& pReloc,
799                                      FragmentLinker& pLinker)
800{
801  ResolveInfo* rsym = pReloc.symInfo();
802
803  switch (pReloc.type()){
804    case llvm::ELF::R_MIPS_NONE:
805    case llvm::ELF::R_MIPS_16:
806      break;
807    case llvm::ELF::R_MIPS_32:
808      if (LinkerConfig::DynObj == config().codeGenType()) {
809        // TODO: (simon) The gold linker does not create an entry in .rel.dyn
810        // section if the symbol section flags contains SHF_EXECINSTR.
811        // 1. Find the reason of this condition.
812        // 2. Check this condition here.
813        m_pRelDyn->reserveEntry();
814        rsym->setReserved(rsym->reserved() | ReserveRel);
815
816        // Remeber this rsym is a local GOT entry (as if it needs an entry).
817        // Actually we don't allocate an GOT entry.
818        m_pGOT->setLocal(rsym);
819      }
820      break;
821    case llvm::ELF::R_MIPS_REL32:
822    case llvm::ELF::R_MIPS_26:
823    case llvm::ELF::R_MIPS_HI16:
824    case llvm::ELF::R_MIPS_LO16:
825    case llvm::ELF::R_MIPS_PC16:
826    case llvm::ELF::R_MIPS_SHIFT5:
827    case llvm::ELF::R_MIPS_SHIFT6:
828    case llvm::ELF::R_MIPS_64:
829    case llvm::ELF::R_MIPS_GOT_PAGE:
830    case llvm::ELF::R_MIPS_GOT_OFST:
831    case llvm::ELF::R_MIPS_SUB:
832    case llvm::ELF::R_MIPS_INSERT_A:
833    case llvm::ELF::R_MIPS_INSERT_B:
834    case llvm::ELF::R_MIPS_DELETE:
835    case llvm::ELF::R_MIPS_HIGHER:
836    case llvm::ELF::R_MIPS_HIGHEST:
837    case llvm::ELF::R_MIPS_SCN_DISP:
838    case llvm::ELF::R_MIPS_REL16:
839    case llvm::ELF::R_MIPS_ADD_IMMEDIATE:
840    case llvm::ELF::R_MIPS_PJUMP:
841    case llvm::ELF::R_MIPS_RELGOT:
842    case llvm::ELF::R_MIPS_JALR:
843    case llvm::ELF::R_MIPS_GLOB_DAT:
844    case llvm::ELF::R_MIPS_COPY:
845    case llvm::ELF::R_MIPS_JUMP_SLOT:
846      break;
847    case llvm::ELF::R_MIPS_GOT16:
848    case llvm::ELF::R_MIPS_CALL16:
849      // For got16 section based relocations, we need to reserve got entries.
850      if (rsym->type() == ResolveInfo::Section) {
851        m_pGOT->reserveLocalEntry();
852        // Remeber this rsym is a local GOT entry
853        m_pGOT->setLocal(rsym);
854        return;
855      }
856
857      if (!(rsym->reserved() & MipsGNULDBackend::ReserveGot)) {
858        m_pGOT->reserveLocalEntry();
859        rsym->setReserved(rsym->reserved() | ReserveGot);
860        // Remeber this rsym is a local GOT entry
861        m_pGOT->setLocal(rsym);
862      }
863      break;
864    case llvm::ELF::R_MIPS_GPREL32:
865    case llvm::ELF::R_MIPS_GPREL16:
866    case llvm::ELF::R_MIPS_LITERAL:
867      break;
868    case llvm::ELF::R_MIPS_GOT_DISP:
869    case llvm::ELF::R_MIPS_GOT_HI16:
870    case llvm::ELF::R_MIPS_CALL_HI16:
871    case llvm::ELF::R_MIPS_GOT_LO16:
872    case llvm::ELF::R_MIPS_CALL_LO16:
873      break;
874    case llvm::ELF::R_MIPS_TLS_DTPMOD32:
875    case llvm::ELF::R_MIPS_TLS_DTPREL32:
876    case llvm::ELF::R_MIPS_TLS_DTPMOD64:
877    case llvm::ELF::R_MIPS_TLS_DTPREL64:
878    case llvm::ELF::R_MIPS_TLS_GD:
879    case llvm::ELF::R_MIPS_TLS_LDM:
880    case llvm::ELF::R_MIPS_TLS_DTPREL_HI16:
881    case llvm::ELF::R_MIPS_TLS_DTPREL_LO16:
882    case llvm::ELF::R_MIPS_TLS_GOTTPREL:
883    case llvm::ELF::R_MIPS_TLS_TPREL32:
884    case llvm::ELF::R_MIPS_TLS_TPREL64:
885    case llvm::ELF::R_MIPS_TLS_TPREL_HI16:
886    case llvm::ELF::R_MIPS_TLS_TPREL_LO16:
887      break;
888    default:
889      fatal(diag::unknown_relocation) << (int)pReloc.type()
890                                      << pReloc.symInfo()->name();
891  }
892}
893
894void MipsGNULDBackend::scanGlobalReloc(Relocation& pReloc,
895                                       FragmentLinker& pLinker)
896{
897  ResolveInfo* rsym = pReloc.symInfo();
898
899  switch (pReloc.type()){
900    case llvm::ELF::R_MIPS_NONE:
901    case llvm::ELF::R_MIPS_INSERT_A:
902    case llvm::ELF::R_MIPS_INSERT_B:
903    case llvm::ELF::R_MIPS_DELETE:
904    case llvm::ELF::R_MIPS_TLS_DTPMOD64:
905    case llvm::ELF::R_MIPS_TLS_DTPREL64:
906    case llvm::ELF::R_MIPS_REL16:
907    case llvm::ELF::R_MIPS_ADD_IMMEDIATE:
908    case llvm::ELF::R_MIPS_PJUMP:
909    case llvm::ELF::R_MIPS_RELGOT:
910    case llvm::ELF::R_MIPS_TLS_TPREL64:
911      break;
912    case llvm::ELF::R_MIPS_32:
913    case llvm::ELF::R_MIPS_64:
914    case llvm::ELF::R_MIPS_HI16:
915    case llvm::ELF::R_MIPS_LO16:
916      if (symbolNeedsDynRel(pLinker, *rsym, false, true)) {
917        m_pRelDyn->reserveEntry();
918        rsym->setReserved(rsym->reserved() | ReserveRel);
919
920        // Remeber this rsym is a global GOT entry (as if it needs an entry).
921        // Actually we don't allocate an GOT entry.
922        m_pGOT->setGlobal(rsym);
923      }
924      break;
925    case llvm::ELF::R_MIPS_GOT16:
926    case llvm::ELF::R_MIPS_CALL16:
927    case llvm::ELF::R_MIPS_GOT_DISP:
928    case llvm::ELF::R_MIPS_GOT_HI16:
929    case llvm::ELF::R_MIPS_CALL_HI16:
930    case llvm::ELF::R_MIPS_GOT_LO16:
931    case llvm::ELF::R_MIPS_CALL_LO16:
932    case llvm::ELF::R_MIPS_GOT_PAGE:
933    case llvm::ELF::R_MIPS_GOT_OFST:
934      if (!(rsym->reserved() & MipsGNULDBackend::ReserveGot)) {
935        m_pGOT->reserveGlobalEntry();
936        rsym->setReserved(rsym->reserved() | ReserveGot);
937        m_GlobalGOTSyms.push_back(rsym->outSymbol());
938        // Remeber this rsym is a global GOT entry
939        m_pGOT->setGlobal(rsym);
940      }
941      break;
942    case llvm::ELF::R_MIPS_LITERAL:
943    case llvm::ELF::R_MIPS_GPREL32:
944      fatal(diag::invalid_global_relocation) << (int)pReloc.type()
945                                             << pReloc.symInfo()->name();
946      break;
947    case llvm::ELF::R_MIPS_GPREL16:
948      break;
949    case llvm::ELF::R_MIPS_26:
950    case llvm::ELF::R_MIPS_PC16:
951      break;
952    case llvm::ELF::R_MIPS_16:
953    case llvm::ELF::R_MIPS_SHIFT5:
954    case llvm::ELF::R_MIPS_SHIFT6:
955    case llvm::ELF::R_MIPS_SUB:
956    case llvm::ELF::R_MIPS_HIGHER:
957    case llvm::ELF::R_MIPS_HIGHEST:
958    case llvm::ELF::R_MIPS_SCN_DISP:
959      break;
960    case llvm::ELF::R_MIPS_TLS_DTPREL32:
961    case llvm::ELF::R_MIPS_TLS_GD:
962    case llvm::ELF::R_MIPS_TLS_LDM:
963    case llvm::ELF::R_MIPS_TLS_DTPREL_HI16:
964    case llvm::ELF::R_MIPS_TLS_DTPREL_LO16:
965    case llvm::ELF::R_MIPS_TLS_GOTTPREL:
966    case llvm::ELF::R_MIPS_TLS_TPREL32:
967    case llvm::ELF::R_MIPS_TLS_TPREL_HI16:
968    case llvm::ELF::R_MIPS_TLS_TPREL_LO16:
969      break;
970    case llvm::ELF::R_MIPS_REL32:
971      break;
972    case llvm::ELF::R_MIPS_JALR:
973      break;
974    case llvm::ELF::R_MIPS_COPY:
975    case llvm::ELF::R_MIPS_GLOB_DAT:
976    case llvm::ELF::R_MIPS_JUMP_SLOT:
977      fatal(diag::dynamic_relocation) << (int)pReloc.type();
978      break;
979    default:
980      fatal(diag::unknown_relocation) << (int)pReloc.type()
981                                      << pReloc.symInfo()->name();
982  }
983}
984
985void MipsGNULDBackend::defineGOTSymbol(FragmentLinker& pLinker)
986{
987  // define symbol _GLOBAL_OFFSET_TABLE_
988  if ( m_pGOTSymbol != NULL ) {
989    pLinker.defineSymbol<FragmentLinker::Force, FragmentLinker::Unresolve>(
990                     "_GLOBAL_OFFSET_TABLE_",
991                     false,
992                     ResolveInfo::Object,
993                     ResolveInfo::Define,
994                     ResolveInfo::Local,
995                     0x0, // size
996                     0x0, // value
997                     FragmentRef::Create(*(m_pGOT->begin()), 0x0),
998                     ResolveInfo::Hidden);
999  }
1000  else {
1001    m_pGOTSymbol = pLinker.defineSymbol<FragmentLinker::Force, FragmentLinker::Resolve>(
1002                     "_GLOBAL_OFFSET_TABLE_",
1003                     false,
1004                     ResolveInfo::Object,
1005                     ResolveInfo::Define,
1006                     ResolveInfo::Local,
1007                     0x0, // size
1008                     0x0, // value
1009                     FragmentRef::Create(*(m_pGOT->begin()), 0x0),
1010                     ResolveInfo::Hidden);
1011  }
1012}
1013
1014/// doCreateProgramHdrs - backend can implement this function to create the
1015/// target-dependent segments
1016void MipsGNULDBackend::doCreateProgramHdrs(Module& pModule,
1017                                           const FragmentLinker& pLinker)
1018{
1019  // TODO
1020}
1021
1022//===----------------------------------------------------------------------===//
1023/// createMipsLDBackend - the help funtion to create corresponding MipsLDBackend
1024///
1025static TargetLDBackend* createMipsLDBackend(const llvm::Target& pTarget,
1026                                            const LinkerConfig& pConfig)
1027{
1028  if (pConfig.targets().triple().isOSDarwin()) {
1029    assert(0 && "MachO linker is not supported yet");
1030  }
1031  if (pConfig.targets().triple().isOSWindows()) {
1032    assert(0 && "COFF linker is not supported yet");
1033  }
1034  return new MipsGNULDBackend(pConfig, new MipsGNUInfo(pConfig.targets().triple()));
1035}
1036
1037//===----------------------------------------------------------------------===//
1038// Force static initialization.
1039//===----------------------------------------------------------------------===//
1040extern "C" void MCLDInitializeMipsLDBackend() {
1041  // Register the linker backend
1042  mcld::TargetRegistry::RegisterTargetLDBackend(mcld::TheMipselTarget,
1043                                                createMipsLDBackend);
1044}
1045
1046