[Symbolize] Improve the ownership of parsed objects.
[oota-llvm.git] / lib / DebugInfo / Symbolize / Symbolize.cpp
index 2e6f60416a4e0881a5c2a3eefbd430bfd7bd2289..3da1963bb791da7424f85078215e871595e5d694 100644 (file)
@@ -22,6 +22,7 @@
 #include "llvm/DebugInfo/PDB/PDBContext.h"
 #include "llvm/Object/ELFObjectFile.h"
 #include "llvm/Object/MachO.h"
+#include "llvm/Object/MachOUniversal.h"
 #include "llvm/Support/COFF.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compression.h"
@@ -30,7 +31,6 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
-#include <sstream>
 #include <stdlib.h>
 
 #if defined(_MSC_VER)
 namespace llvm {
 namespace symbolize {
 
-// FIXME: Move this to llvm-symbolizer tool.
-static bool error(std::error_code ec) {
-  if (!ec)
-    return false;
-  errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
-  return true;
-}
-
-
-// By default, DILineInfo contains "<invalid>" for function/filename it
-// cannot fetch. We replace it to "??" to make our output closer to addr2line.
-static const char kDILineInfoBadString[] = "<invalid>";
-
-const char LLVMSymbolizer::kBadString[] = "??";
-
-std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
-                                          uint64_t ModuleOffset) {
-  SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
-  if (!Info)
-    return printDILineInfo(DILineInfo(), Info);
+ErrorOr<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
+                                                  uint64_t ModuleOffset) {
+  auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
+  if (auto EC = InfoOrErr.getError())
+    return EC;
+  SymbolizableModule *Info = InfoOrErr.get();
 
   // If the user is giving us relative addresses, add the preferred base of the
   // object to the offset before we do the query. It's what DIContext expects.
@@ -75,14 +61,18 @@ std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
 
   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
                                             Opts.UseSymbolTable);
-  return printDILineInfo(LineInfo, Info);
+  if (Opts.Demangle)
+    LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
+  return LineInfo;
 }
 
-std::string LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
-                                                 uint64_t ModuleOffset) {
-  SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
-  if (!Info)
-    return printDIInliningInfo(DIInliningInfo(), nullptr);
+ErrorOr<DIInliningInfo>
+LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
+                                     uint64_t ModuleOffset) {
+  auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
+  if (auto EC = InfoOrErr.getError())
+    return EC;
+  SymbolizableModule *Info = InfoOrErr.get();
 
   // If the user is giving us relative addresses, add the preferred base of the
   // object to the offset before we do the query. It's what DIContext expects.
@@ -91,29 +81,39 @@ std::string LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
 
   DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
       ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
-  return printDIInliningInfo(InlinedContext, Info);
-}
-
-std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
-                                          uint64_t ModuleOffset) {
-  if (Opts.UseSymbolTable) {
-    if (SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName)) {
-      // If the user is giving us relative addresses, add the preferred base of
-      // the object to the offset before we do the query. It's what DIContext
-      // expects.
-      if (Opts.RelativeAddresses)
-        ModuleOffset += Info->getModulePreferredBase();
-      DIGlobal Global = Info->symbolizeData(ModuleOffset);
-      return printDIGlobal(Global, Info);
+  if (Opts.Demangle) {
+    for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
+      auto *Frame = InlinedContext.getMutableFrame(i);
+      Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
     }
   }
-  return printDIGlobal(DIGlobal(), nullptr);
+  return InlinedContext;
+}
+
+ErrorOr<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
+                                                uint64_t ModuleOffset) {
+  auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
+  if (auto EC = InfoOrErr.getError())
+    return EC;
+  SymbolizableModule *Info = InfoOrErr.get();
+
+  // If the user is giving us relative addresses, add the preferred base of
+  // the object to the offset before we do the query. It's what DIContext
+  // expects.
+  if (Opts.RelativeAddresses)
+    ModuleOffset += Info->getModulePreferredBase();
+
+  DIGlobal Global = Info->symbolizeData(ModuleOffset);
+  if (Opts.Demangle)
+    Global.Name = DemangleName(Global.Name, Info);
+  return Global;
 }
 
 void LLVMSymbolizer::flush() {
-  Modules.clear();
+  ObjectForUBPathAndArch.clear();
+  BinaryForPath.clear();
   ObjectPairForPathArch.clear();
-  ObjectFileForArch.clear();
+  Modules.clear();
 }
 
 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
@@ -225,97 +225,121 @@ ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
   for (const auto &Path : Opts.DsymHints) {
     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
   }
-  for (const auto &path : DsymPaths) {
-    ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
-    std::error_code EC = BinaryOrErr.getError();
-    if (EC != errc::no_such_file_or_directory && !error(EC)) {
-      OwningBinary<Binary> B = std::move(BinaryOrErr.get());
-      ObjectFile *DbgObj =
-          getObjectFileFromBinary(B.getBinary(), ArchName);
-      const MachOObjectFile *MachDbgObj =
-          dyn_cast<const MachOObjectFile>(DbgObj);
-      if (!MachDbgObj) continue;
-      if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
-        addOwningBinary(std::move(B));
-        return DbgObj; 
-      }
-    }
+  for (const auto &Path : DsymPaths) {
+    auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
+    if (!DbgObjOrErr)
+      continue;
+    ObjectFile *DbgObj = DbgObjOrErr.get();
+    const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
+    if (!MachDbgObj)
+      continue;
+    if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
+      return DbgObj;
   }
   return nullptr;
 }
 
-LLVMSymbolizer::ObjectPair
-LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
-                                   const std::string &ArchName) {
+ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
+                                                  const ObjectFile *Obj,
+                                                  const std::string &ArchName) {
+  std::string DebuglinkName;
+  uint32_t CRCHash;
+  std::string DebugBinaryPath;
+  if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
+    return nullptr;
+  if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
+    return nullptr;
+  auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
+  if (!DbgObjOrErr)
+    return nullptr;
+  return DbgObjOrErr.get();
+}
+
+ErrorOr<LLVMSymbolizer::ObjectPair>
+LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
+                                      const std::string &ArchName) {
   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
   if (I != ObjectPairForPathArch.end())
     return I->second;
-  ObjectFile *Obj = nullptr;
-  ObjectFile *DbgObj = nullptr;
-  ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
-  if (!error(BinaryOrErr.getError())) {
-    OwningBinary<Binary> &B = BinaryOrErr.get();
-    Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
-    if (!Obj) {
-      ObjectPair Res = std::make_pair(nullptr, nullptr);
-      ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
-      return Res;
-    }
-    addOwningBinary(std::move(B));
-    if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
-      DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
-    // Try to locate the debug binary using .gnu_debuglink section.
-    if (!DbgObj) {
-      std::string DebuglinkName;
-      uint32_t CRCHash;
-      std::string DebugBinaryPath;
-      if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
-          findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
-        BinaryOrErr = createBinary(DebugBinaryPath);
-        if (!error(BinaryOrErr.getError())) {
-          OwningBinary<Binary> B = std::move(BinaryOrErr.get());
-          DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
-          addOwningBinary(std::move(B));
-        }
-      }
-    }
+
+  auto ObjOrErr = getOrCreateObject(Path, ArchName);
+  if (auto EC = ObjOrErr.getError()) {
+    ObjectPairForPathArch.insert(
+        std::make_pair(std::make_pair(Path, ArchName), EC));
+    return EC;
   }
+
+  ObjectFile *Obj = ObjOrErr.get();
+  assert(Obj != nullptr);
+  ObjectFile *DbgObj = nullptr;
+
+  if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
+    DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
+  if (!DbgObj)
+    DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
   if (!DbgObj)
     DbgObj = Obj;
   ObjectPair Res = std::make_pair(Obj, DbgObj);
-  ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
+  ObjectPairForPathArch.insert(
+      std::make_pair(std::make_pair(Path, ArchName), Res));
   return Res;
 }
 
-ObjectFile *
-LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
-                                        const std::string &ArchName) {
-  if (!Bin)
-    return nullptr;
-  ObjectFile *Res = nullptr;
+ErrorOr<ObjectFile *>
+LLVMSymbolizer::getOrCreateObject(const std::string &Path,
+                                  const std::string &ArchName) {
+  const auto &I = BinaryForPath.find(Path);
+  Binary *Bin = nullptr;
+  if (I == BinaryForPath.end()) {
+    ErrorOr<OwningBinary<Binary>> BinOrErr = createBinary(Path);
+    if (auto EC = BinOrErr.getError()) {
+      BinaryForPath.insert(std::make_pair(Path, EC));
+      return EC;
+    }
+    Bin = BinOrErr->getBinary();
+    BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
+  } else if (auto EC = I->second.getError()) {
+    return EC;
+  } else {
+    Bin = I->second->getBinary();
+  }
+
+  assert(Bin != nullptr);
+
   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
-    const auto &I = ObjectFileForArch.find(
-        std::make_pair(UB, ArchName));
-    if (I != ObjectFileForArch.end())
-      return I->second;
-    ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
+    const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
+    if (I != ObjectForUBPathAndArch.end()) {
+      if (auto EC = I->second.getError())
+        return EC;
+      return I->second->get();
+    }
+    ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
         UB->getObjectForArch(ArchName);
-    if (ParsedObj) {
-      Res = ParsedObj.get().get();
-      ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
+    if (auto EC = ObjOrErr.getError()) {
+      ObjectForUBPathAndArch.insert(
+          std::make_pair(std::make_pair(Path, ArchName), EC));
+      return EC;
     }
-    ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
-  } else if (Bin->isObject()) {
-    Res = cast<ObjectFile>(Bin);
+    ObjectFile *Res = ObjOrErr->get();
+    ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
+                                                 std::move(ObjOrErr.get())));
+    return Res;
   }
-  return Res;
+  if (Bin->isObject()) {
+    return cast<ObjectFile>(Bin);
+  }
+  return object_error::arch_not_found;
 }
 
-SymbolizableModule *
+ErrorOr<SymbolizableModule *>
 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
   const auto &I = Modules.find(ModuleName);
-  if (I != Modules.end())
-    return I->second.get();
+  if (I != Modules.end()) {
+    auto &InfoOrErr = I->second;
+    if (auto EC = InfoOrErr.getError())
+      return EC;
+    return InfoOrErr->get();
+  }
   std::string BinaryName = ModuleName;
   std::string ArchName = Opts.DefaultArch;
   size_t ColonPos = ModuleName.find_last_of(':');
@@ -327,13 +351,14 @@ LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
       ArchName = ArchStr;
     }
   }
-  ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
-
-  if (!Objects.first) {
+  auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
+  if (auto EC = ObjectsOrErr.getError()) {
     // Failed to find valid object file.
-    Modules.insert(std::make_pair(ModuleName, nullptr));
-    return nullptr;
+    Modules.insert(std::make_pair(ModuleName, EC));
+    return EC;
   }
+  ObjectPair Objects = ObjectsOrErr.get();
+
   std::unique_ptr<DIContext> Context;
   if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
     // If this is a COFF object, assume it contains PDB debug information.  If
@@ -348,62 +373,14 @@ LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
   if (!Context)
     Context.reset(new DWARFContextInMemory(*Objects.second));
   assert(Context);
-  auto ErrOrInfo =
+  auto InfoOrErr =
       SymbolizableObjectFile::create(Objects.first, std::move(Context));
-  if (error(ErrOrInfo.getError())) {
-    Modules.insert(std::make_pair(ModuleName, nullptr));
-    return nullptr;
-  }
-  SymbolizableModule *Res = ErrOrInfo.get().get();
-  Modules.insert(std::make_pair(ModuleName, std::move(ErrOrInfo.get())));
-  return Res;
-}
-
-std::string
-LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
-                                const SymbolizableModule *ModInfo) const {
-  std::stringstream Result;
-  if (Opts.PrintFunctions != FunctionNameKind::None) {
-    std::string FunctionName = LineInfo.FunctionName;
-    if (FunctionName == kDILineInfoBadString)
-      FunctionName = kBadString;
-    else if (Opts.Demangle)
-      FunctionName = DemangleName(FunctionName, ModInfo);
-    Result << FunctionName << "\n";
-  }
-  std::string Filename = LineInfo.FileName;
-  if (Filename == kDILineInfoBadString)
-    Filename = kBadString;
-  Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
-  return Result.str();
-}
-
-std::string
-LLVMSymbolizer::printDIInliningInfo(DIInliningInfo InlinedContext,
-                                   const SymbolizableModule *ModInfo) const {
-  uint32_t FramesNum = InlinedContext.getNumberOfFrames();
-  if (FramesNum == 0)
-    return printDILineInfo(DILineInfo(), ModInfo);
-  std::string Result;
-  for (uint32_t i = 0; i < FramesNum; i++) {
-    DILineInfo LineInfo = InlinedContext.getFrame(i);
-    Result += printDILineInfo(LineInfo, ModInfo);
-  }
-  return Result;
-}
-
-std::string
-LLVMSymbolizer::printDIGlobal(DIGlobal Global,
-                              const SymbolizableModule *ModInfo) const {
-  std::stringstream Result;
-  std::string Name = Global.Name;
-  if (Name == kDILineInfoBadString)
-    Name = kBadString;
-  else if (Opts.Demangle)
-    Name = DemangleName(Name, ModInfo);
-  Result << Name << "\n";
-  Result << Global.Start << " " << Global.Size << "\n";
-  return Result.str();
+  auto InsertResult =
+      Modules.insert(std::make_pair(ModuleName, std::move(InfoOrErr)));
+  assert(InsertResult.second);
+  if (auto EC = InsertResult.first->second.getError())
+    return EC;
+  return InsertResult.first->second->get();
 }
 
 // Undo these various manglings for Win32 extern "C" functions: