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