MC: Refactor ObjectSymbolizer to make relocation/section info generation lazy.
[oota-llvm.git] / lib / MC / MCObjectSymbolizer.cpp
1 //===-- lib/MC/MCObjectSymbolizer.cpp -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCObjectSymbolizer.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRelocationInfo.h"
16 #include "llvm/MC/MCSymbol.h"
17 #include "llvm/Object/MachO.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <algorithm>
21
22 using namespace llvm;
23 using namespace object;
24
25 //===- MCMachObjectSymbolizer ---------------------------------------------===//
26
27 namespace {
28 class MCMachObjectSymbolizer : public MCObjectSymbolizer {
29 public:
30   MCMachObjectSymbolizer(MCContext &Ctx, OwningPtr<MCRelocationInfo> &RelInfo,
31                          const MachOObjectFile *MOOF) {}
32
33   void tryAddingPcLoadReferenceComment(raw_ostream &cStream,
34                                        int64_t Value,
35                                        uint64_t Address) LLVM_OVERRIDE;
36 };
37 } // End unnamed namespace
38
39
40 void MCMachObjectSymbolizer::
41 tryAddingPcLoadReferenceComment(raw_ostream &cStream, int64_t Value,
42                                 uint64_t Address) {
43   if (const RelocationRef *R = findRelocationAt(Address)) {
44     const MCExpr *RelExpr = RelInfo->createExprForRelocation(*R);
45     if (!RelExpr || RelExpr->EvaluateAsAbsolute(Value) == false)
46       return;
47   }
48   uint64_t Addr = Value;
49   if (const SectionRef *S = findSectionContaining(Addr)) {
50     StringRef Name; S->getName(Name);
51     uint64_t SAddr; S->getAddress(SAddr);
52     if (Name == "__cstring") {
53       StringRef Contents;
54       S->getContents(Contents);
55       Contents = Contents.substr(Addr - SAddr);
56       cStream << " ## literal pool for: "
57               << Contents.substr(0, Contents.find_first_of(0));
58     }
59   }
60 }
61
62 //===- MCObjectSymbolizer -------------------------------------------------===//
63
64 MCObjectSymbolizer::MCObjectSymbolizer(MCContext &Ctx,
65                                        OwningPtr<MCRelocationInfo> &RelInfo,
66                                        const ObjectFile *Obj)
67     : MCSymbolizer(Ctx, RelInfo), Obj(Obj), SortedSections(), AddrToReloc() {
68 }
69
70 bool MCObjectSymbolizer::
71 tryAddingSymbolicOperand(MCInst &MI, raw_ostream &cStream,
72                          int64_t Value, uint64_t Address, bool IsBranch,
73                          uint64_t Offset, uint64_t InstSize) {
74   if (const RelocationRef *R = findRelocationAt(Address + Offset)) {
75     if (const MCExpr *RelExpr = RelInfo->createExprForRelocation(*R)) {
76       MI.addOperand(MCOperand::CreateExpr(RelExpr));
77       return true;
78     }
79     // Only try to create a symbol+offset expression if there is no relocation.
80     return false;
81   }
82
83   // Interpret Value as a branch target.
84   if (IsBranch == false)
85     return false;
86   uint64_t UValue = Value;
87   // FIXME: map instead of looping each time?
88   error_code ec;
89   for (symbol_iterator SI = Obj->begin_symbols(), SE = Obj->end_symbols();
90        SI != SE; SI.increment(ec)) {
91     if (ec) break;
92     uint64_t SymAddr; SI->getAddress(SymAddr);
93     uint64_t SymSize; SI->getSize(SymSize);
94     StringRef SymName; SI->getName(SymName);
95     SymbolRef::Type SymType; SI->getType(SymType);
96     if (SymAddr == UnknownAddressOrSize || SymSize == UnknownAddressOrSize
97         || SymName.empty() || SymType != SymbolRef::ST_Function)
98       continue;
99
100     if ( SymAddr == UValue ||
101         (SymAddr <= UValue && SymAddr + SymSize > UValue)) {
102       MCSymbol *Sym = Ctx.GetOrCreateSymbol(SymName);
103       const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx);
104       if (SymAddr != UValue) {
105         const MCExpr *Off = MCConstantExpr::Create(UValue - SymAddr, Ctx);
106         Expr = MCBinaryExpr::CreateAdd(Expr, Off, Ctx);
107       }
108       MI.addOperand(MCOperand::CreateExpr(Expr));
109       return true;
110     }
111   }
112   return false;
113 }
114
115 void MCObjectSymbolizer::
116 tryAddingPcLoadReferenceComment(raw_ostream &cStream,
117                                 int64_t Value, uint64_t Address) {
118 }
119
120 StringRef MCObjectSymbolizer::findExternalFunctionAt(uint64_t Addr) {
121   return StringRef();
122 }
123
124 MCObjectSymbolizer *
125 MCObjectSymbolizer::createObjectSymbolizer(MCContext &Ctx,
126                                            OwningPtr<MCRelocationInfo> &RelInfo,
127                                            const ObjectFile *Obj) {
128   if (const MachOObjectFile *MOOF = dyn_cast<MachOObjectFile>(Obj))
129     return new MCMachObjectSymbolizer(Ctx, RelInfo, MOOF);
130   return new MCObjectSymbolizer(Ctx, RelInfo, Obj);
131 }
132
133 // SortedSections implementation.
134
135 static bool SectionStartsBefore(const SectionRef &S, uint64_t Addr) {
136   uint64_t SAddr; S.getAddress(SAddr);
137   return SAddr < Addr;
138 }
139
140 const SectionRef *MCObjectSymbolizer::findSectionContaining(uint64_t Addr) {
141   if (SortedSections.empty())
142     buildSectionList();
143
144   SortedSectionList::iterator
145     EndIt = SortedSections.end(),
146     It = std::lower_bound(SortedSections.begin(), EndIt,
147                           Addr, SectionStartsBefore);
148   if (It == EndIt)
149     return 0;
150   uint64_t SAddr; It->getAddress(SAddr);
151   uint64_t SSize; It->getSize(SSize);
152   if (Addr >= SAddr + SSize)
153     return 0;
154   return &*It;
155 }
156
157 const RelocationRef *MCObjectSymbolizer::findRelocationAt(uint64_t Addr) {
158   if (AddrToReloc.empty())
159     buildRelocationByAddrMap();
160
161   AddrToRelocMap::const_iterator RI = AddrToReloc.find(Addr);
162   if (RI == AddrToReloc.end())
163     return 0;
164   return &RI->second;
165 }
166
167 void MCObjectSymbolizer::buildSectionList() {
168   error_code ec;
169   for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
170                         SI != SE; SI.increment(ec)) {
171     if (ec) break;
172
173     bool RequiredForExec; SI->isRequiredForExecution(RequiredForExec);
174     if (RequiredForExec == false)
175       continue;
176     uint64_t SAddr; SI->getAddress(SAddr);
177     uint64_t SSize; SI->getSize(SSize);
178     SortedSectionList::iterator It = std::lower_bound(SortedSections.begin(),
179                                                       SortedSections.end(),
180                                                       SAddr,
181                                                       SectionStartsBefore);
182     if (It != SortedSections.end()) {
183       uint64_t FoundSAddr; It->getAddress(FoundSAddr);
184       if (FoundSAddr < SAddr + SSize)
185         llvm_unreachable("Inserting overlapping sections");
186     }
187     SortedSections.insert(It, *SI);
188   }
189 }
190
191 void MCObjectSymbolizer::buildRelocationByAddrMap() {
192   error_code ec;
193   for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
194                         SI != SE; SI.increment(ec)) {
195     if (ec) break;
196
197     section_iterator RelSecI = SI->getRelocatedSection();
198     if (RelSecI == Obj->end_sections())
199       continue;
200
201     uint64_t StartAddr; RelSecI->getAddress(StartAddr);
202     uint64_t Size; RelSecI->getSize(Size);
203     bool RequiredForExec; RelSecI->isRequiredForExecution(RequiredForExec);
204     if (RequiredForExec == false || Size == 0)
205       continue;
206     for (relocation_iterator RI = SI->begin_relocations(),
207                              RE = SI->end_relocations();
208                              RI != RE;
209                              RI.increment(ec)) {
210       if (ec) break;
211       // FIXME: libObject is inconsistent regarding error handling. The
212       // overwhelming majority of methods always return object_error::success,
213       // and assert for simple errors.. Here, ELFObjectFile::getRelocationOffset
214       // asserts when the file type isn't ET_REL.
215       // This workaround handles x86-64 elf, the only one that has a relocinfo.
216       uint64_t Offset;
217       if (Obj->isELF()) {
218         const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj);
219         if (ELFObj == 0)
220           break;
221         if (ELFObj->getELFFile()->getHeader()->e_type == ELF::ET_REL) {
222           RI->getOffset(Offset);
223           Offset += StartAddr;
224         } else {
225           RI->getAddress(Offset);
226         }
227       } else {
228         RI->getOffset(Offset);
229         Offset += StartAddr;
230       }
231       // At a specific address, only keep the first relocation.
232       if (AddrToReloc.find(Offset) == AddrToReloc.end())
233         AddrToReloc[Offset] = *RI;
234     }
235   }
236 }