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