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