Switch all uses of LLVM_OVERRIDE to just use 'override' directly.
[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/ELFObjectFile.h"
18 #include "llvm/Object/MachO.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   const MachOObjectFile *MOOF;
30   // __TEXT;__stubs support.
31   uint64_t StubsStart;
32   uint64_t StubsCount;
33   uint64_t StubSize;
34   uint64_t StubsIndSymIndex;
35
36 public:
37   MCMachObjectSymbolizer(MCContext &Ctx, OwningPtr<MCRelocationInfo> &RelInfo,
38                          const MachOObjectFile *MOOF);
39
40   StringRef findExternalFunctionAt(uint64_t Addr) override;
41
42   void tryAddingPcLoadReferenceComment(raw_ostream &cStream, int64_t Value,
43                                        uint64_t Address) override;
44 };
45 } // End unnamed namespace
46
47
48 MCMachObjectSymbolizer::
49 MCMachObjectSymbolizer(MCContext &Ctx, OwningPtr<MCRelocationInfo> &RelInfo,
50                        const MachOObjectFile *MOOF)
51     : MCObjectSymbolizer(Ctx, RelInfo, MOOF), MOOF(MOOF),
52       StubsStart(0), StubsCount(0), StubSize(0), StubsIndSymIndex(0) {
53
54   for (section_iterator SI = MOOF->section_begin(), SE = MOOF->section_end();
55        SI != SE; ++SI) {
56     StringRef Name; SI->getName(Name);
57     if (Name == "__stubs") {
58       SectionRef StubsSec = *SI;
59       if (MOOF->is64Bit()) {
60         MachO::section_64 S = MOOF->getSection64(StubsSec.getRawDataRefImpl());
61         StubsIndSymIndex = S.reserved1;
62         StubSize = S.reserved2;
63       } else {
64         MachO::section S = MOOF->getSection(StubsSec.getRawDataRefImpl());
65         StubsIndSymIndex = S.reserved1;
66         StubSize = S.reserved2;
67       }
68       assert(StubSize && "Mach-O stub entry size can't be zero!");
69       StubsSec.getAddress(StubsStart);
70       StubsSec.getSize(StubsCount);
71       StubsCount /= StubSize;
72     }
73   }
74 }
75
76 StringRef MCMachObjectSymbolizer::findExternalFunctionAt(uint64_t Addr) {
77   // FIXME: also, this can all be done at the very beginning, by iterating over
78   // all stubs and creating the calls to outside functions. Is it worth it
79   // though?
80   if (!StubSize)
81     return StringRef();
82   uint64_t StubIdx = (Addr - StubsStart) / StubSize;
83   if (StubIdx >= StubsCount)
84     return StringRef();
85
86   uint32_t SymtabIdx =
87     MOOF->getIndirectSymbolTableEntry(MOOF->getDysymtabLoadCommand(), StubIdx);
88
89   StringRef SymName;
90   symbol_iterator SI = MOOF->symbol_begin();
91   for (uint32_t i = 0; i != SymtabIdx; ++i)
92     ++SI;
93   SI->getName(SymName);
94   assert(SI != MOOF->symbol_end() && "Stub wasn't found in the symbol table!");
95   assert(SymName.front() == '_' && "Mach-O symbol doesn't start with '_'!");
96   return SymName.substr(1);
97 }
98
99 void MCMachObjectSymbolizer::
100 tryAddingPcLoadReferenceComment(raw_ostream &cStream, int64_t Value,
101                                 uint64_t Address) {
102   if (const RelocationRef *R = findRelocationAt(Address)) {
103     const MCExpr *RelExpr = RelInfo->createExprForRelocation(*R);
104     if (!RelExpr || RelExpr->EvaluateAsAbsolute(Value) == false)
105       return;
106   }
107   uint64_t Addr = Value;
108   if (const SectionRef *S = findSectionContaining(Addr)) {
109     StringRef Name; S->getName(Name);
110     uint64_t SAddr; S->getAddress(SAddr);
111     if (Name == "__cstring") {
112       StringRef Contents;
113       S->getContents(Contents);
114       Contents = Contents.substr(Addr - SAddr);
115       cStream << " ## literal pool for: "
116               << Contents.substr(0, Contents.find_first_of(0));
117     }
118   }
119 }
120
121 //===- MCObjectSymbolizer -------------------------------------------------===//
122
123 MCObjectSymbolizer::MCObjectSymbolizer(MCContext &Ctx,
124                                        OwningPtr<MCRelocationInfo> &RelInfo,
125                                        const ObjectFile *Obj)
126     : MCSymbolizer(Ctx, RelInfo), Obj(Obj), SortedSections(), AddrToReloc() {
127 }
128
129 bool MCObjectSymbolizer::
130 tryAddingSymbolicOperand(MCInst &MI, raw_ostream &cStream,
131                          int64_t Value, uint64_t Address, bool IsBranch,
132                          uint64_t Offset, uint64_t InstSize) {
133   if (IsBranch) {
134     StringRef ExtFnName = findExternalFunctionAt((uint64_t)Value);
135     if (!ExtFnName.empty()) {
136       MCSymbol *Sym = Ctx.GetOrCreateSymbol(ExtFnName);
137       const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx);
138       MI.addOperand(MCOperand::CreateExpr(Expr));
139       return true;
140     }
141   }
142
143   if (const RelocationRef *R = findRelocationAt(Address + Offset)) {
144     if (const MCExpr *RelExpr = RelInfo->createExprForRelocation(*R)) {
145       MI.addOperand(MCOperand::CreateExpr(RelExpr));
146       return true;
147     }
148     // Only try to create a symbol+offset expression if there is no relocation.
149     return false;
150   }
151
152   // Interpret Value as a branch target.
153   if (IsBranch == false)
154     return false;
155   uint64_t UValue = Value;
156   // FIXME: map instead of looping each time?
157   for (symbol_iterator SI = Obj->symbol_begin(), SE = Obj->symbol_end();
158        SI != SE; ++SI) {
159     uint64_t SymAddr; SI->getAddress(SymAddr);
160     uint64_t SymSize; SI->getSize(SymSize);
161     StringRef SymName; SI->getName(SymName);
162     SymbolRef::Type SymType; SI->getType(SymType);
163     if (SymAddr == UnknownAddressOrSize || SymSize == UnknownAddressOrSize
164         || SymName.empty() || SymType != SymbolRef::ST_Function)
165       continue;
166
167     if ( SymAddr == UValue ||
168         (SymAddr <= UValue && SymAddr + SymSize > UValue)) {
169       MCSymbol *Sym = Ctx.GetOrCreateSymbol(SymName);
170       const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx);
171       if (SymAddr != UValue) {
172         const MCExpr *Off = MCConstantExpr::Create(UValue - SymAddr, Ctx);
173         Expr = MCBinaryExpr::CreateAdd(Expr, Off, Ctx);
174       }
175       MI.addOperand(MCOperand::CreateExpr(Expr));
176       return true;
177     }
178   }
179   return false;
180 }
181
182 void MCObjectSymbolizer::
183 tryAddingPcLoadReferenceComment(raw_ostream &cStream,
184                                 int64_t Value, uint64_t Address) {
185 }
186
187 StringRef MCObjectSymbolizer::findExternalFunctionAt(uint64_t Addr) {
188   return StringRef();
189 }
190
191 MCObjectSymbolizer *
192 MCObjectSymbolizer::createObjectSymbolizer(MCContext &Ctx,
193                                            OwningPtr<MCRelocationInfo> &RelInfo,
194                                            const ObjectFile *Obj) {
195   if (const MachOObjectFile *MOOF = dyn_cast<MachOObjectFile>(Obj))
196     return new MCMachObjectSymbolizer(Ctx, RelInfo, MOOF);
197   return new MCObjectSymbolizer(Ctx, RelInfo, Obj);
198 }
199
200 // SortedSections implementation.
201
202 static bool SectionStartsBefore(const SectionRef &S, uint64_t Addr) {
203   uint64_t SAddr; S.getAddress(SAddr);
204   return SAddr < Addr;
205 }
206
207 const SectionRef *MCObjectSymbolizer::findSectionContaining(uint64_t Addr) {
208   if (SortedSections.empty())
209     buildSectionList();
210
211   SortedSectionList::iterator
212     EndIt = SortedSections.end(),
213     It = std::lower_bound(SortedSections.begin(), EndIt,
214                           Addr, SectionStartsBefore);
215   if (It == EndIt)
216     return 0;
217   uint64_t SAddr; It->getAddress(SAddr);
218   uint64_t SSize; It->getSize(SSize);
219   if (Addr >= SAddr + SSize)
220     return 0;
221   return &*It;
222 }
223
224 const RelocationRef *MCObjectSymbolizer::findRelocationAt(uint64_t Addr) {
225   if (AddrToReloc.empty())
226     buildRelocationByAddrMap();
227
228   AddrToRelocMap::const_iterator RI = AddrToReloc.find(Addr);
229   if (RI == AddrToReloc.end())
230     return 0;
231   return &RI->second;
232 }
233
234 void MCObjectSymbolizer::buildSectionList() {
235   for (section_iterator SI = Obj->section_begin(), SE = Obj->section_end();
236        SI != SE; ++SI) {
237     bool RequiredForExec; SI->isRequiredForExecution(RequiredForExec);
238     if (RequiredForExec == false)
239       continue;
240     uint64_t SAddr; SI->getAddress(SAddr);
241     uint64_t SSize; SI->getSize(SSize);
242     SortedSectionList::iterator It = std::lower_bound(SortedSections.begin(),
243                                                       SortedSections.end(),
244                                                       SAddr,
245                                                       SectionStartsBefore);
246     if (It != SortedSections.end()) {
247       uint64_t FoundSAddr; It->getAddress(FoundSAddr);
248       if (FoundSAddr < SAddr + SSize)
249         llvm_unreachable("Inserting overlapping sections");
250     }
251     SortedSections.insert(It, *SI);
252   }
253 }
254
255 void MCObjectSymbolizer::buildRelocationByAddrMap() {
256   for (section_iterator SI = Obj->section_begin(), SE = Obj->section_end();
257        SI != SE; ++SI) {
258     section_iterator RelSecI = SI->getRelocatedSection();
259     if (RelSecI == Obj->section_end())
260       continue;
261
262     uint64_t StartAddr; RelSecI->getAddress(StartAddr);
263     uint64_t Size; RelSecI->getSize(Size);
264     bool RequiredForExec; RelSecI->isRequiredForExecution(RequiredForExec);
265     if (RequiredForExec == false || Size == 0)
266       continue;
267     for (relocation_iterator RI = SI->relocation_begin(),
268                              RE = SI->relocation_end();
269          RI != RE; ++RI) {
270       // FIXME: libObject is inconsistent regarding error handling. The
271       // overwhelming majority of methods always return object_error::success,
272       // and assert for simple errors.. Here, ELFObjectFile::getRelocationOffset
273       // asserts when the file type isn't ET_REL.
274       // This workaround handles x86-64 elf, the only one that has a relocinfo.
275       uint64_t Offset;
276       if (Obj->isELF()) {
277         const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj);
278         if (ELFObj == 0)
279           break;
280         if (ELFObj->getELFFile()->getHeader()->e_type == ELF::ET_REL) {
281           RI->getOffset(Offset);
282           Offset += StartAddr;
283         } else {
284           RI->getAddress(Offset);
285         }
286       } else {
287         RI->getOffset(Offset);
288         Offset += StartAddr;
289       }
290       // At a specific address, only keep the first relocation.
291       if (AddrToReloc.find(Offset) == AddrToReloc.end())
292         AddrToReloc[Offset] = *RI;
293     }
294   }
295 }