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