1 //===- SymbolizableObjectFile.cpp -----------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Implementation of SymbolizableObjectFile class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SymbolizableObjectFile.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/Triple.h" 16 #include "llvm/BinaryFormat/COFF.h" 17 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 18 #include "llvm/Object/COFF.h" 19 #include "llvm/Object/ObjectFile.h" 20 #include "llvm/Object/SymbolSize.h" 21 #include "llvm/Support/Casting.h" 22 #include "llvm/Support/DataExtractor.h" 23 #include <algorithm> 24 25 using namespace llvm; 26 using namespace object; 27 using namespace symbolize; 28 29 Expected<std::unique_ptr<SymbolizableObjectFile>> 30 SymbolizableObjectFile::create(const object::ObjectFile *Obj, 31 std::unique_ptr<DIContext> DICtx, 32 bool UntagAddresses) { 33 assert(DICtx); 34 std::unique_ptr<SymbolizableObjectFile> res( 35 new SymbolizableObjectFile(Obj, std::move(DICtx), UntagAddresses)); 36 std::unique_ptr<DataExtractor> OpdExtractor; 37 uint64_t OpdAddress = 0; 38 // Find the .opd (function descriptor) section if any, for big-endian 39 // PowerPC64 ELF. 40 if (Obj->getArch() == Triple::ppc64) { 41 for (section_iterator Section : Obj->sections()) { 42 Expected<StringRef> NameOrErr = Section->getName(); 43 if (!NameOrErr) 44 return NameOrErr.takeError(); 45 46 if (*NameOrErr == ".opd") { 47 Expected<StringRef> E = Section->getContents(); 48 if (!E) 49 return E.takeError(); 50 OpdExtractor.reset(new DataExtractor(*E, Obj->isLittleEndian(), 51 Obj->getBytesInAddress())); 52 OpdAddress = Section->getAddress(); 53 break; 54 } 55 } 56 } 57 std::vector<std::pair<SymbolRef, uint64_t>> Symbols = 58 computeSymbolSizes(*Obj); 59 for (auto &P : Symbols) 60 if (Error E = 61 res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress)) 62 return std::move(E); 63 64 // If this is a COFF object and we didn't find any symbols, try the export 65 // table. 66 if (Symbols.empty()) { 67 if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj)) 68 if (Error E = res->addCoffExportSymbols(CoffObj)) 69 return std::move(E); 70 } 71 72 std::vector<std::pair<SymbolDesc, StringRef>> &Fs = res->Functions, 73 &Os = res->Objects; 74 auto Uniquify = [](std::vector<std::pair<SymbolDesc, StringRef>> &S) { 75 // Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr, 76 // pick the one with the largest Size. This helps us avoid symbols with no 77 // size information (Size=0). 78 llvm::sort(S); 79 auto I = S.begin(), E = S.end(), J = S.begin(); 80 while (I != E) { 81 auto OI = I; 82 while (++I != E && OI->first.Addr == I->first.Addr) { 83 } 84 *J++ = I[-1]; 85 } 86 S.erase(J, S.end()); 87 }; 88 Uniquify(Fs); 89 Uniquify(Os); 90 91 return std::move(res); 92 } 93 94 SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj, 95 std::unique_ptr<DIContext> DICtx, 96 bool UntagAddresses) 97 : Module(Obj), DebugInfoContext(std::move(DICtx)), 98 UntagAddresses(UntagAddresses) {} 99 100 namespace { 101 102 struct OffsetNamePair { 103 uint32_t Offset; 104 StringRef Name; 105 106 bool operator<(const OffsetNamePair &R) const { 107 return Offset < R.Offset; 108 } 109 }; 110 111 } // end anonymous namespace 112 113 Error SymbolizableObjectFile::addCoffExportSymbols( 114 const COFFObjectFile *CoffObj) { 115 // Get all export names and offsets. 116 std::vector<OffsetNamePair> ExportSyms; 117 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) { 118 StringRef Name; 119 uint32_t Offset; 120 if (auto EC = Ref.getSymbolName(Name)) 121 return EC; 122 if (auto EC = Ref.getExportRVA(Offset)) 123 return EC; 124 ExportSyms.push_back(OffsetNamePair{Offset, Name}); 125 } 126 if (ExportSyms.empty()) 127 return Error::success(); 128 129 // Sort by ascending offset. 130 array_pod_sort(ExportSyms.begin(), ExportSyms.end()); 131 132 // Approximate the symbol sizes by assuming they run to the next symbol. 133 // FIXME: This assumes all exports are functions. 134 uint64_t ImageBase = CoffObj->getImageBase(); 135 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) { 136 OffsetNamePair &Export = *I; 137 // FIXME: The last export has a one byte size now. 138 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1; 139 uint64_t SymbolStart = ImageBase + Export.Offset; 140 uint64_t SymbolSize = NextOffset - Export.Offset; 141 SymbolDesc SD = {SymbolStart, SymbolSize}; 142 Functions.emplace_back(SD, Export.Name); 143 } 144 return Error::success(); 145 } 146 147 Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol, 148 uint64_t SymbolSize, 149 DataExtractor *OpdExtractor, 150 uint64_t OpdAddress) { 151 // Avoid adding symbols from an unknown/undefined section. 152 const ObjectFile *Obj = Symbol.getObject(); 153 Expected<section_iterator> Sec = Symbol.getSection(); 154 if (!Sec || (Obj && Obj->section_end() == *Sec)) 155 return Error::success(); 156 Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType(); 157 if (!SymbolTypeOrErr) 158 return SymbolTypeOrErr.takeError(); 159 SymbolRef::Type SymbolType = *SymbolTypeOrErr; 160 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data) 161 return Error::success(); 162 Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress(); 163 if (!SymbolAddressOrErr) 164 return SymbolAddressOrErr.takeError(); 165 uint64_t SymbolAddress = *SymbolAddressOrErr; 166 if (UntagAddresses) { 167 // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55 168 // into bits 56-63 instead of masking them out. 169 SymbolAddress &= (1ull << 56) - 1; 170 SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8; 171 } 172 if (OpdExtractor) { 173 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to 174 // function descriptors. The first word of the descriptor is a pointer to 175 // the function's code. 176 // For the purposes of symbolization, pretend the symbol's address is that 177 // of the function's code, not the descriptor. 178 uint64_t OpdOffset = SymbolAddress - OpdAddress; 179 if (OpdExtractor->isValidOffsetForAddress(OpdOffset)) 180 SymbolAddress = OpdExtractor->getAddress(&OpdOffset); 181 } 182 Expected<StringRef> SymbolNameOrErr = Symbol.getName(); 183 if (!SymbolNameOrErr) 184 return SymbolNameOrErr.takeError(); 185 StringRef SymbolName = *SymbolNameOrErr; 186 // Mach-O symbol table names have leading underscore, skip it. 187 if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_') 188 SymbolName = SymbolName.drop_front(); 189 // FIXME: If a function has alias, there are two entries in symbol table 190 // with same address size. Make sure we choose the correct one. 191 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects; 192 SymbolDesc SD = { SymbolAddress, SymbolSize }; 193 M.emplace_back(SD, SymbolName); 194 return Error::success(); 195 } 196 197 // Return true if this is a 32-bit x86 PE COFF module. 198 bool SymbolizableObjectFile::isWin32Module() const { 199 auto *CoffObject = dyn_cast<COFFObjectFile>(Module); 200 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386; 201 } 202 203 uint64_t SymbolizableObjectFile::getModulePreferredBase() const { 204 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module)) 205 return CoffObject->getImageBase(); 206 return 0; 207 } 208 209 bool SymbolizableObjectFile::getNameFromSymbolTable(SymbolRef::Type Type, 210 uint64_t Address, 211 std::string &Name, 212 uint64_t &Addr, 213 uint64_t &Size) const { 214 const auto &Symbols = Type == SymbolRef::ST_Function ? Functions : Objects; 215 std::pair<SymbolDesc, StringRef> SD{{Address, UINT64_C(-1)}, StringRef()}; 216 auto SymbolIterator = llvm::upper_bound(Symbols, SD); 217 if (SymbolIterator == Symbols.begin()) 218 return false; 219 --SymbolIterator; 220 if (SymbolIterator->first.Size != 0 && 221 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address) 222 return false; 223 Name = SymbolIterator->second.str(); 224 Addr = SymbolIterator->first.Addr; 225 Size = SymbolIterator->first.Size; 226 return true; 227 } 228 229 bool SymbolizableObjectFile::shouldOverrideWithSymbolTable( 230 FunctionNameKind FNKind, bool UseSymbolTable) const { 231 // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives 232 // better answers for linkage names than the DIContext. Otherwise, we are 233 // probably using PEs and PDBs, and we shouldn't do the override. PE files 234 // generally only contain the names of exported symbols. 235 return FNKind == FunctionNameKind::LinkageName && UseSymbolTable && 236 isa<DWARFContext>(DebugInfoContext.get()); 237 } 238 239 DILineInfo 240 SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset, 241 DILineInfoSpecifier LineInfoSpecifier, 242 bool UseSymbolTable) const { 243 if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection) 244 ModuleOffset.SectionIndex = 245 getModuleSectionIndexForAddress(ModuleOffset.Address); 246 DILineInfo LineInfo = 247 DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier); 248 249 // Override function name from symbol table if necessary. 250 if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) { 251 std::string FunctionName; 252 uint64_t Start, Size; 253 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address, 254 FunctionName, Start, Size)) { 255 LineInfo.FunctionName = FunctionName; 256 } 257 } 258 return LineInfo; 259 } 260 261 DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode( 262 object::SectionedAddress ModuleOffset, 263 DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const { 264 if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection) 265 ModuleOffset.SectionIndex = 266 getModuleSectionIndexForAddress(ModuleOffset.Address); 267 DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress( 268 ModuleOffset, LineInfoSpecifier); 269 270 // Make sure there is at least one frame in context. 271 if (InlinedContext.getNumberOfFrames() == 0) 272 InlinedContext.addFrame(DILineInfo()); 273 274 // Override the function name in lower frame with name from symbol table. 275 if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) { 276 std::string FunctionName; 277 uint64_t Start, Size; 278 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset.Address, 279 FunctionName, Start, Size)) { 280 InlinedContext.getMutableFrame(InlinedContext.getNumberOfFrames() - 1) 281 ->FunctionName = FunctionName; 282 } 283 } 284 285 return InlinedContext; 286 } 287 288 DIGlobal SymbolizableObjectFile::symbolizeData( 289 object::SectionedAddress ModuleOffset) const { 290 DIGlobal Res; 291 getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset.Address, Res.Name, 292 Res.Start, Res.Size); 293 return Res; 294 } 295 296 std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame( 297 object::SectionedAddress ModuleOffset) const { 298 if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection) 299 ModuleOffset.SectionIndex = 300 getModuleSectionIndexForAddress(ModuleOffset.Address); 301 return DebugInfoContext->getLocalsForAddress(ModuleOffset); 302 } 303 304 /// Search for the first occurence of specified Address in ObjectFile. 305 uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress( 306 uint64_t Address) const { 307 308 for (SectionRef Sec : Module->sections()) { 309 if (!Sec.isText() || Sec.isVirtual()) 310 continue; 311 312 if (Address >= Sec.getAddress() && 313 Address < Sec.getAddress() + Sec.getSize()) 314 return Sec.getIndex(); 315 } 316 317 return object::SectionedAddress::UndefSection; 318 } 319