[dsymutil] Implement the BinaryHolder object and gain archive support.
[oota-llvm.git] / tools / dsymutil / MachODebugMapParser.cpp
1 //===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===//
2 //
3 //                             The LLVM Linker
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 "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "dsymutil.h"
13 #include "llvm/Object/MachO.h"
14 #include "llvm/Support/Path.h"
15 #include "llvm/Support/raw_ostream.h"
16
17 namespace {
18 using namespace llvm;
19 using namespace llvm::dsymutil;
20 using namespace llvm::object;
21
22 class MachODebugMapParser {
23 public:
24   MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "",
25                       bool Verbose = false)
26       : BinaryPath(BinaryPath), PathPrefix(PathPrefix),
27         MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose) {}
28
29   /// \brief Parses and returns the DebugMap of the input binary.
30   /// \returns an error in case the provided BinaryPath doesn't exist
31   /// or isn't of a supported type.
32   ErrorOr<std::unique_ptr<DebugMap>> parse();
33
34 private:
35   std::string BinaryPath;
36   std::string PathPrefix;
37
38   /// Owns the MemoryBuffer for the main binary.
39   BinaryHolder MainBinaryHolder;
40   /// Map of the binary symbol addresses.
41   StringMap<uint64_t> MainBinarySymbolAddresses;
42   StringRef MainBinaryStrings;
43   /// The constructed DebugMap.
44   std::unique_ptr<DebugMap> Result;
45
46   /// Owns the MemoryBuffer for the currently handled object file.
47   BinaryHolder CurrentObjectHolder;
48   /// Map of the currently processed object file symbol addresses.
49   StringMap<uint64_t> CurrentObjectAddresses;
50   /// Element of the debug map corresponfing to the current object file.
51   DebugMapObject *CurrentDebugMapObject;
52
53   void switchToNewDebugMapObject(StringRef Filename);
54   void resetParserState();
55   uint64_t getMainBinarySymbolAddress(StringRef Name);
56   void loadMainBinarySymbols();
57   void loadCurrentObjectFileSymbols();
58   void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
59                                   uint8_t SectionIndex, uint16_t Flags,
60                                   uint64_t Value);
61
62   template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
63     handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
64                                STE.n_value);
65   }
66 };
67
68 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
69 }
70
71 /// Reset the parser state coresponding to the current object
72 /// file. This is to be called after an object file is finished
73 /// processing.
74 void MachODebugMapParser::resetParserState() {
75   CurrentObjectAddresses.clear();
76   CurrentDebugMapObject = nullptr;
77 }
78
79 /// Create a new DebugMapObject. This function resets the state of the
80 /// parser that was referring to the last object file and sets
81 /// everything up to add symbols to the new one.
82 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename) {
83   resetParserState();
84
85   SmallString<80> Path(PathPrefix);
86   sys::path::append(Path, Filename);
87
88   auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path);
89   if (auto Error = MachOOrError.getError()) {
90     Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
91             Error.message() + "\n");
92     return;
93   }
94
95   loadCurrentObjectFileSymbols();
96   CurrentDebugMapObject = &Result->addDebugMapObject(Path);
97 }
98
99 /// This main parsing routine tries to open the main binary and if
100 /// successful iterates over the STAB entries. The real parsing is
101 /// done in handleStabSymbolTableEntry.
102 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
103   auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath);
104   if (auto Error = MainBinOrError.getError())
105     return Error;
106
107   const MachOObjectFile &MainBinary = *MainBinOrError;
108   loadMainBinarySymbols();
109   Result = make_unique<DebugMap>();
110   MainBinaryStrings = MainBinary.getStringTableData();
111   for (const SymbolRef &Symbol : MainBinary.symbols()) {
112     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
113     if (MainBinary.is64Bit())
114       handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
115     else
116       handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
117   }
118
119   resetParserState();
120   return std::move(Result);
121 }
122
123 /// Interpret the STAB entries to fill the DebugMap.
124 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
125                                                      uint8_t Type,
126                                                      uint8_t SectionIndex,
127                                                      uint16_t Flags,
128                                                      uint64_t Value) {
129   if (!(Type & MachO::N_STAB))
130     return;
131
132   const char *Name = &MainBinaryStrings.data()[StringIndex];
133
134   // An N_OSO entry represents the start of a new object file description.
135   if (Type == MachO::N_OSO)
136     return switchToNewDebugMapObject(Name);
137
138   // If the last N_OSO object file wasn't found,
139   // CurrentDebugMapObject will be null. Do not update anything
140   // until we find the next valid N_OSO entry.
141   if (!CurrentDebugMapObject)
142     return;
143
144   switch (Type) {
145   case MachO::N_GSYM:
146     // This is a global variable. We need to query the main binary
147     // symbol table to find its address as it might not be in the
148     // debug map (for common symbols).
149     Value = getMainBinarySymbolAddress(Name);
150     if (Value == UnknownAddressOrSize)
151       return;
152     break;
153   case MachO::N_FUN:
154     // Functions are scopes in STABS. They have an end marker that we
155     // need to ignore.
156     if (Name[0] == '\0')
157       return;
158     break;
159   case MachO::N_STSYM:
160     break;
161   default:
162     return;
163   }
164
165   auto ObjectSymIt = CurrentObjectAddresses.find(Name);
166   if (ObjectSymIt == CurrentObjectAddresses.end())
167     return Warning("could not find object file symbol for symbol " +
168                    Twine(Name));
169   if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value))
170     return Warning(Twine("failed to insert symbol '") + Name +
171                    "' in the debug map.");
172 }
173
174 /// Load the current object file symbols into CurrentObjectAddresses.
175 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
176   CurrentObjectAddresses.clear();
177
178   for (auto Sym : CurrentObjectHolder.Get().symbols()) {
179     StringRef Name;
180     uint64_t Addr;
181     if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
182         Sym.getName(Name))
183       continue;
184     CurrentObjectAddresses[Name] = Addr;
185   }
186 }
187
188 /// Lookup a symbol address in the main binary symbol table. The
189 /// parser only needs to query common symbols, thus not every symbol's
190 /// address is available through this function.
191 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
192   auto Sym = MainBinarySymbolAddresses.find(Name);
193   if (Sym == MainBinarySymbolAddresses.end())
194     return UnknownAddressOrSize;
195   return Sym->second;
196 }
197
198 /// Load the interesting main binary symbols' addresses into
199 /// MainBinarySymbolAddresses.
200 void MachODebugMapParser::loadMainBinarySymbols() {
201   const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>();
202   section_iterator Section = MainBinary.section_end();
203   for (const auto &Sym : MainBinary.symbols()) {
204     SymbolRef::Type Type;
205     // Skip undefined and STAB entries.
206     if (Sym.getType(Type) || (Type & SymbolRef::ST_Debug) ||
207         (Type & SymbolRef::ST_Unknown))
208       continue;
209     StringRef Name;
210     uint64_t Addr;
211     // The only symbols of interest are the global variables. These
212     // are the only ones that need to be queried because the address
213     // of common data won't be described in the debug map. All other
214     // addresses should be fetched for the debug map.
215     if (Sym.getAddress(Addr) || Addr == UnknownAddressOrSize ||
216         !(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
217         Section->isText() || Sym.getName(Name) || Name.size() == 0 ||
218         Name[0] == '\0')
219       continue;
220     MainBinarySymbolAddresses[Name] = Addr;
221   }
222 }
223
224 namespace llvm {
225 namespace dsymutil {
226 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
227                                                        StringRef PrependPath,
228                                                        bool Verbose) {
229   MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
230   return Parser.parse();
231 }
232 }
233 }