[x86] Update the order of instructions after I switched to a bitcast
[oota-llvm.git] / tools / dsymutil / MachODebugMapParser.cpp
index 49d4949f8bbfcfda556d7a6ba680f51de33e7e1c..bf64303b9eab2872ffcea0abffcbbc3837b98602 100644 (file)
@@ -7,36 +7,76 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "MachODebugMapParser.h"
+#include "BinaryHolder.h"
+#include "DebugMap.h"
+#include "dsymutil.h"
+#include "llvm/Object/MachO.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 
+namespace {
+using namespace llvm;
+using namespace llvm::dsymutil;
 using namespace llvm::object;
 
-namespace llvm {
+class MachODebugMapParser {
+public:
+  MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "",
+                      bool Verbose = false)
+      : BinaryPath(BinaryPath), PathPrefix(PathPrefix),
+        MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose),
+        CurrentDebugMapObject(nullptr) {}
+
+  /// \brief Parses and returns the DebugMap of the input binary.
+  /// \returns an error in case the provided BinaryPath doesn't exist
+  /// or isn't of a supported type.
+  ErrorOr<std::unique_ptr<DebugMap>> parse();
+
+private:
+  std::string BinaryPath;
+  std::string PathPrefix;
+
+  /// Owns the MemoryBuffer for the main binary.
+  BinaryHolder MainBinaryHolder;
+  /// Map of the binary symbol addresses.
+  StringMap<uint64_t> MainBinarySymbolAddresses;
+  StringRef MainBinaryStrings;
+  /// The constructed DebugMap.
+  std::unique_ptr<DebugMap> Result;
+
+  /// Owns the MemoryBuffer for the currently handled object file.
+  BinaryHolder CurrentObjectHolder;
+  /// Map of the currently processed object file symbol addresses.
+  StringMap<uint64_t> CurrentObjectAddresses;
+  /// Element of the debug map corresponfing to the current object file.
+  DebugMapObject *CurrentDebugMapObject;
+
+  /// Holds function info while function scope processing.
+  const char *CurrentFunctionName;
+  uint64_t CurrentFunctionAddress;
+
+  void switchToNewDebugMapObject(StringRef Filename);
+  void resetParserState();
+  uint64_t getMainBinarySymbolAddress(StringRef Name);
+  void loadMainBinarySymbols();
+  void loadCurrentObjectFileSymbols();
+  void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
+                                  uint8_t SectionIndex, uint16_t Flags,
+                                  uint64_t Value);
+
+  template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
+    handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
+                               STE.n_value);
+  }
+};
 
 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
-
-static ErrorOr<OwningBinary<MachOObjectFile>> createMachOBinary(StringRef file) {
-  ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
-  if (BinaryOrErr.getError())
-    return BinaryOrErr.getError();
-
-  std::unique_ptr<Binary> Bin;
-  std::unique_ptr<MemoryBuffer> Buf;
-  std::tie(Bin, Buf) = BinaryOrErr->takeBinary();
-  if (!isa<MachOObjectFile>(Bin.get()))
-    return make_error_code(object_error::invalid_file_type);
-
-  std::unique_ptr<MachOObjectFile> MachOFile(cast<MachOObjectFile>(Bin.release()));
-  return OwningBinary<MachOObjectFile>(std::move(MachOFile), std::move(Buf));
 }
 
 /// Reset the parser state coresponding to the current object
 /// file. This is to be called after an object file is finished
 /// processing.
 void MachODebugMapParser::resetParserState() {
-  CurrentObjectFile = OwningBinary<object::MachOObjectFile>();
   CurrentObjectAddresses.clear();
   CurrentDebugMapObject = nullptr;
 }
@@ -47,33 +87,39 @@ void MachODebugMapParser::resetParserState() {
 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
   resetParserState();
 
-  std::string Path = Filename;
-  if (!PathPrefix.empty())
-    Path = PathPrefix + sys::path::get_separator().data() + Path;
+  SmallString<80> Path(PathPrefix);
+  sys::path::append(Path, Filename);
 
-  auto MachOOrError = createMachOBinary(Path);
+  auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path);
   if (auto Error = MachOOrError.getError()) {
-    Warning(Twine("cannot open debug object \"") + Path + "\": "
-            Error.message() + "\n");
+    Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
+            Error.message() + "\n");
     return;
   }
 
-  CurrentObjectFile = std::move(*MachOOrError);
   loadCurrentObjectFileSymbols();
   CurrentDebugMapObject = &Result->addDebugMapObject(Path);
 }
 
+static Triple getTriple(const object::MachOObjectFile &Obj) {
+  Triple TheTriple("unknown-unknown-unknown");
+  TheTriple.setArch(Triple::ArchType(Obj.getArch()));
+  TheTriple.setObjectFormat(Triple::MachO);
+  return TheTriple;
+}
+
 /// This main parsing routine tries to open the main binary and if
 /// successful iterates over the STAB entries. The real parsing is
 /// done in handleStabSymbolTableEntry.
 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
-  auto MainBinaryOrError = createMachOBinary(BinaryPath);
-  if (MainBinaryOrError.getError())
-    return MainBinaryOrError.getError();
-
-  MainOwningBinary = std::move(*MainBinaryOrError);
-  Result = make_unique<DebugMap>();
-  const auto &MainBinary = *MainOwningBinary.getBinary();
+  auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath);
+  if (auto Error = MainBinOrError.getError())
+    return Error;
+
+  const MachOObjectFile &MainBinary = *MainBinOrError;
+  loadMainBinarySymbols();
+  Result = make_unique<DebugMap>(getTriple(MainBinary));
+  MainBinaryStrings = MainBinary.getStringTableData();
   for (const SymbolRef &Symbol : MainBinary.symbols()) {
     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
     if (MainBinary.is64Bit())
@@ -95,8 +141,7 @@ void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
   if (!(Type & MachO::N_STAB))
     return;
 
-  const MachOObjectFile &MachOBinary = *MainOwningBinary.getBinary();
-  const char *Name = &MachOBinary.getStringTableData().data()[StringIndex];
+  const char *Name = &MainBinaryStrings.data()[StringIndex];
 
   // An N_OSO entry represents the start of a new object file description.
   if (Type == MachO::N_OSO)
@@ -108,6 +153,7 @@ void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
   if (!CurrentDebugMapObject)
     return;
 
+  uint32_t Size = 0;
   switch (Type) {
   case MachO::N_GSYM:
     // This is a global variable. We need to query the main binary
@@ -118,11 +164,18 @@ void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
       return;
     break;
   case MachO::N_FUN:
-    // Functions are scopes in STABS. They have an end marker that we
-    // need to ignore.
-    if (Name[0] == '\0')
+    // Functions are scopes in STABS. They have an end marker that
+    // contains the function size.
+    if (Name[0] == '\0') {
+      Size = Value;
+      Value = CurrentFunctionAddress;
+      Name = CurrentFunctionName;
+      break;
+    } else {
+      CurrentFunctionName = Name;
+      CurrentFunctionAddress = Value;
       return;
-    break;
+    }
   case MachO::N_STSYM:
     break;
   default:
@@ -133,16 +186,17 @@ void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
   if (ObjectSymIt == CurrentObjectAddresses.end())
     return Warning("could not find object file symbol for symbol " +
                    Twine(Name));
-  if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value))
-    return Warning(Twine("failed to insert symbol '") + Name + "' in the debug map.");
+  if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
+                                        Size))
+    return Warning(Twine("failed to insert symbol '") + Name +
+                   "' in the debug map.");
 }
 
 /// Load the current object file symbols into CurrentObjectAddresses.
 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
   CurrentObjectAddresses.clear();
-  const auto &Binary = *CurrentObjectFile.getBinary();
 
-  for (auto Sym : Binary.symbols()) {
+  for (auto Sym : CurrentObjectHolder.Get().symbols()) {
     StringRef Name;
     uint64_t Addr;
     if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
@@ -156,9 +210,6 @@ void MachODebugMapParser::loadCurrentObjectFileSymbols() {
 /// parser only needs to query common symbols, thus not every symbol's
 /// address is available through this function.
 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
-  if (MainBinarySymbolAddresses.empty())
-    loadMainBinarySymbols();
-
   auto Sym = MainBinarySymbolAddresses.find(Name);
   if (Sym == MainBinarySymbolAddresses.end())
     return UnknownAddressOrSize;
@@ -168,9 +219,9 @@ uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
 /// Load the interesting main binary symbols' addresses into
 /// MainBinarySymbolAddresses.
 void MachODebugMapParser::loadMainBinarySymbols() {
-  const MachOObjectFile &Binary = *MainOwningBinary.getBinary();
-  section_iterator Section = Binary.section_end();
-  for (const auto &Sym : Binary.symbols()) {
+  const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>();
+  section_iterator Section = MainBinary.section_end();
+  for (const auto &Sym : MainBinary.symbols()) {
     SymbolRef::Type Type;
     // Skip undefined and STAB entries.
     if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) ||
@@ -183,12 +234,20 @@ void MachODebugMapParser::loadMainBinarySymbols() {
     // of common data won't be described in the debug map. All other
     // addresses should be fetched for the debug map.
     if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
-        !(Sym.getFlags() & SymbolRef::SF_Global) ||
-        Sym.getSection(Section) || Section->isText() || Sym.getName(Name) ||
-        Name.size() == 0 || Name[0] == '\0')
+        !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
+        Section->isText() || Sym.getName(Name) || Name.size() == 0 ||
+        Name[0] == '\0')
       continue;
     MainBinarySymbolAddresses[Name] = Addr;
   }
 }
 
+namespace llvm {
+namespace dsymutil {
+llvm::ErrorOr<std::unique_ptr<DebugMap>>
+parseDebugMap(StringRef InputFile, StringRef PrependPath, bool Verbose) {
+  MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
+  return Parser.parse();
+}
+}
 }