OSDN Git Service

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