Home | History | Annotate | Download | only in LD
      1 //===- ELFObjectReader.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/LD/ELFObjectReader.h"
     10 
     11 #include "mcld/IRBuilder.h"
     12 #include "mcld/MC/Input.h"
     13 #include "mcld/LD/ELFReader.h"
     14 #include "mcld/LD/EhFrameReader.h"
     15 #include "mcld/LD/EhFrame.h"
     16 #include "mcld/LD/LDContext.h"
     17 #include "mcld/Target/GNULDBackend.h"
     18 #include "mcld/Support/MsgHandling.h"
     19 #include "mcld/Support/MemoryArea.h"
     20 #include "mcld/Object/ObjectBuilder.h"
     21 
     22 #include <llvm/Support/ELF.h>
     23 #include <llvm/ADT/Twine.h>
     24 #include <llvm/ADT/StringRef.h>
     25 
     26 #include <string>
     27 #include <cassert>
     28 
     29 namespace mcld {
     30 
     31 //===----------------------------------------------------------------------===//
     32 // ELFObjectReader
     33 //===----------------------------------------------------------------------===//
     34 /// constructor
     35 ELFObjectReader::ELFObjectReader(GNULDBackend& pBackend,
     36                                  IRBuilder& pBuilder,
     37                                  const LinkerConfig& pConfig)
     38     : ObjectReader(),
     39       m_pELFReader(NULL),
     40       m_pEhFrameReader(NULL),
     41       m_Builder(pBuilder),
     42       m_ReadFlag(ParseEhFrame),
     43       m_Backend(pBackend),
     44       m_Config(pConfig) {
     45   if (pConfig.targets().is32Bits() && pConfig.targets().isLittleEndian()) {
     46     m_pELFReader = new ELFReader<32, true>(pBackend);
     47   } else if (pConfig.targets().is64Bits() &&
     48              pConfig.targets().isLittleEndian()) {
     49     m_pELFReader = new ELFReader<64, true>(pBackend);
     50   }
     51 
     52   m_pEhFrameReader = new EhFrameReader();
     53 }
     54 
     55 /// destructor
     56 ELFObjectReader::~ELFObjectReader() {
     57   delete m_pELFReader;
     58   delete m_pEhFrameReader;
     59 }
     60 
     61 /// isMyFormat
     62 bool ELFObjectReader::isMyFormat(Input& pInput, bool& pContinue) const {
     63   assert(pInput.hasMemArea());
     64 
     65   // Don't warning about the frequently requests.
     66   // MemoryArea has a list of cache to handle this.
     67   size_t hdr_size = m_pELFReader->getELFHeaderSize();
     68   if (pInput.memArea()->size() < hdr_size)
     69     return false;
     70 
     71   llvm::StringRef region =
     72       pInput.memArea()->request(pInput.fileOffset(), hdr_size);
     73 
     74   const char* ELF_hdr = region.begin();
     75   bool result = true;
     76   if (!m_pELFReader->isELF(ELF_hdr)) {
     77     pContinue = true;
     78     result = false;
     79   } else if (Input::Object != m_pELFReader->fileType(ELF_hdr)) {
     80     pContinue = true;
     81     result = false;
     82   } else if (!m_pELFReader->isMyEndian(ELF_hdr)) {
     83     pContinue = false;
     84     result = false;
     85   } else if (!m_pELFReader->isMyMachine(ELF_hdr)) {
     86     pContinue = false;
     87     result = false;
     88   }
     89   return result;
     90 }
     91 
     92 /// readHeader - read section header and create LDSections.
     93 bool ELFObjectReader::readHeader(Input& pInput) {
     94   assert(pInput.hasMemArea());
     95 
     96   size_t hdr_size = m_pELFReader->getELFHeaderSize();
     97   if (pInput.memArea()->size() < hdr_size)
     98     return false;
     99 
    100   llvm::StringRef region =
    101       pInput.memArea()->request(pInput.fileOffset(), hdr_size);
    102   const char* ELF_hdr = region.begin();
    103   m_Backend.mergeFlags(pInput, ELF_hdr);
    104   bool result = m_pELFReader->readSectionHeaders(pInput, ELF_hdr);
    105   return result;
    106 }
    107 
    108 /// readSections - read all regular sections.
    109 bool ELFObjectReader::readSections(Input& pInput) {
    110   // handle sections
    111   LDContext::sect_iterator section, sectEnd = pInput.context()->sectEnd();
    112   for (section = pInput.context()->sectBegin(); section != sectEnd; ++section) {
    113     // ignore the section if the LDSection* in input context is NULL
    114     if (*section == NULL)
    115       continue;
    116 
    117     switch ((*section)->kind()) {
    118       /** group sections **/
    119       case LDFileFormat::Group: {
    120         assert((*section)->getLink() != NULL);
    121         ResolveInfo* signature = m_pELFReader->readSignature(
    122             pInput, *(*section)->getLink(), (*section)->getInfo());
    123 
    124         bool exist = false;
    125         if (signature->nameSize() == 0 &&
    126             ResolveInfo::Section == signature->type()) {
    127           // if the signature is a section symbol in input object, we use the
    128           // section name as group signature.
    129           signatures().insert((*section)->name(), exist);
    130         } else {
    131           signatures().insert(signature->name(), exist);
    132         }
    133 
    134         if (exist) {
    135           // if this is not the first time we see this group signature, then
    136           // ignore all the members in this group (set Ignore)
    137           llvm::StringRef region = pInput.memArea()->request(
    138               pInput.fileOffset() + (*section)->offset(), (*section)->size());
    139           const llvm::ELF::Elf32_Word* value =
    140               reinterpret_cast<const llvm::ELF::Elf32_Word*>(region.begin());
    141 
    142           size_t size = region.size() / sizeof(llvm::ELF::Elf32_Word);
    143           if (llvm::ELF::GRP_COMDAT == *value) {
    144             for (size_t index = 1; index < size; ++index) {
    145               pInput.context()->getSection(value[index])->setKind(
    146                   LDFileFormat::Ignore);
    147             }
    148           }
    149         }
    150         ResolveInfo::Destroy(signature);
    151         break;
    152       }
    153       /** linkonce sections **/
    154       case LDFileFormat::LinkOnce: {
    155         bool exist = false;
    156         // .gnu.linkonce + "." + type + "." + name
    157         llvm::StringRef name(
    158             llvm::StringRef((*section)->name()).drop_front(14));
    159         signatures().insert(name.split(".").second, exist);
    160         if (!exist) {
    161           if (name.startswith("wi")) {
    162             (*section)->setKind(LDFileFormat::Debug);
    163             if (m_Config.options().stripDebug())
    164               (*section)->setKind(LDFileFormat::Ignore);
    165             else {
    166               SectionData* sd = IRBuilder::CreateSectionData(**section);
    167               if (!m_pELFReader->readRegularSection(pInput, *sd))
    168                 fatal(diag::err_cannot_read_section) << (*section)->name();
    169             }
    170           } else {
    171             if (((*section)->flag() & llvm::ELF::SHF_EXECINSTR) != 0)
    172               (*section)->setKind(LDFileFormat::TEXT);
    173             else
    174               (*section)->setKind(LDFileFormat::DATA);
    175             SectionData* sd = IRBuilder::CreateSectionData(**section);
    176             if (!m_pELFReader->readRegularSection(pInput, *sd))
    177               fatal(diag::err_cannot_read_section) << (*section)->name();
    178           }
    179         } else {
    180           (*section)->setKind(LDFileFormat::Ignore);
    181         }
    182         break;
    183       }
    184       /** relocation sections **/
    185       case LDFileFormat::Relocation: {
    186         assert((*section)->getLink() != NULL);
    187         size_t link_index = (*section)->getLink()->index();
    188         LDSection* link_sect = pInput.context()->getSection(link_index);
    189         if (link_sect == NULL || link_sect->kind() == LDFileFormat::Ignore) {
    190           // Relocation sections of group members should also be part of the
    191           // group. Thus, if the associated member sections are ignored, the
    192           // related relocations should be also ignored.
    193           (*section)->setKind(LDFileFormat::Ignore);
    194         }
    195         break;
    196       }
    197       /** normal sections **/
    198       // FIXME: support Version Kind
    199       case LDFileFormat::Version:
    200       // FIXME: support GCCExceptTable Kind
    201       case LDFileFormat::GCCExceptTable:
    202       /** Fall through **/
    203       case LDFileFormat::TEXT:
    204       case LDFileFormat::DATA:
    205       case LDFileFormat::Note:
    206       case LDFileFormat::MetaData: {
    207         SectionData* sd = IRBuilder::CreateSectionData(**section);
    208         if (!m_pELFReader->readRegularSection(pInput, *sd))
    209           fatal(diag::err_cannot_read_section) << (*section)->name();
    210         break;
    211       }
    212       case LDFileFormat::Debug:
    213       case LDFileFormat::DebugString: {
    214         if (m_Config.options().stripDebug()) {
    215           (*section)->setKind(LDFileFormat::Ignore);
    216         } else {
    217           SectionData* sd = IRBuilder::CreateSectionData(**section);
    218           if (!m_pELFReader->readRegularSection(pInput, *sd)) {
    219             fatal(diag::err_cannot_read_section) << (*section)->name();
    220           }
    221         }
    222         break;
    223       }
    224       case LDFileFormat::EhFrame: {
    225         EhFrame* eh_frame = IRBuilder::CreateEhFrame(**section);
    226 
    227         // We don't really parse EhFrame if this is a partial linking
    228         if ((m_Config.codeGenType() != LinkerConfig::Object) &&
    229             (m_ReadFlag & ParseEhFrame)) {
    230           if (!m_pEhFrameReader->read<32, true>(pInput, *eh_frame)) {
    231             // if we failed to parse a .eh_frame, we should not parse the rest
    232             // .eh_frame.
    233             m_ReadFlag ^= ParseEhFrame;
    234           }
    235         } else {
    236           if (!m_pELFReader->readRegularSection(pInput,
    237                                                 *eh_frame->getSectionData())) {
    238             fatal(diag::err_cannot_read_section) << (*section)->name();
    239           }
    240         }
    241         break;
    242       }
    243       /** target dependent sections **/
    244       case LDFileFormat::Target: {
    245         SectionData* sd = IRBuilder::CreateSectionData(**section);
    246         if (!m_Backend.readSection(pInput, *sd)) {
    247           fatal(diag::err_cannot_read_target_section) << (*section)->name();
    248         }
    249         break;
    250       }
    251       /** BSS sections **/
    252       case LDFileFormat::BSS: {
    253         IRBuilder::CreateBSS(**section);
    254         break;
    255       }
    256       // ignore
    257       case LDFileFormat::Null:
    258       case LDFileFormat::NamePool:
    259       case LDFileFormat::Ignore:
    260       case LDFileFormat::StackNote:
    261         continue;
    262       // warning
    263       case LDFileFormat::EhFrameHdr:
    264       default: {
    265         warning(diag::warn_illegal_input_section)
    266             << (*section)->name() << pInput.name() << pInput.path();
    267         break;
    268       }
    269     }
    270   }  // end of for all sections
    271 
    272   return true;
    273 }
    274 
    275 /// readSymbols - read symbols from the input relocatable object.
    276 bool ELFObjectReader::readSymbols(Input& pInput) {
    277   assert(pInput.hasMemArea());
    278 
    279   LDSection* symtab_shdr = pInput.context()->getSection(".symtab");
    280   if (symtab_shdr == NULL) {
    281     note(diag::note_has_no_symtab) << pInput.name() << pInput.path()
    282                                    << ".symtab";
    283     return true;
    284   }
    285 
    286   LDSection* strtab_shdr = symtab_shdr->getLink();
    287   if (strtab_shdr == NULL) {
    288     fatal(diag::fatal_cannot_read_strtab) << pInput.name() << pInput.path()
    289                                           << ".symtab";
    290     return false;
    291   }
    292 
    293   llvm::StringRef symtab_region = pInput.memArea()->request(
    294       pInput.fileOffset() + symtab_shdr->offset(), symtab_shdr->size());
    295   llvm::StringRef strtab_region = pInput.memArea()->request(
    296       pInput.fileOffset() + strtab_shdr->offset(), strtab_shdr->size());
    297   const char* strtab = strtab_region.begin();
    298   bool result =
    299       m_pELFReader->readSymbols(pInput, m_Builder, symtab_region, strtab);
    300   return result;
    301 }
    302 
    303 bool ELFObjectReader::readRelocations(Input& pInput) {
    304   assert(pInput.hasMemArea());
    305 
    306   MemoryArea* mem = pInput.memArea();
    307   LDContext::sect_iterator rs, rsEnd = pInput.context()->relocSectEnd();
    308   for (rs = pInput.context()->relocSectBegin(); rs != rsEnd; ++rs) {
    309     if (LDFileFormat::Ignore == (*rs)->kind())
    310       continue;
    311 
    312     uint32_t offset = pInput.fileOffset() + (*rs)->offset();
    313     uint32_t size = (*rs)->size();
    314     llvm::StringRef region = mem->request(offset, size);
    315     IRBuilder::CreateRelocData(
    316         **rs);  ///< create relocation data for the header
    317     switch ((*rs)->type()) {
    318       case llvm::ELF::SHT_RELA: {
    319         if (!m_pELFReader->readRela(pInput, **rs, region)) {
    320           return false;
    321         }
    322         break;
    323       }
    324       case llvm::ELF::SHT_REL: {
    325         if (!m_pELFReader->readRel(pInput, **rs, region)) {
    326           return false;
    327         }
    328         break;
    329       }
    330       default: {  ///< should not enter
    331         return false;
    332       }
    333     }  // end of switch
    334   }  // end of for all relocation data
    335 
    336   return true;
    337 }
    338 
    339 }  // namespace mcld
    340