Delete an unused function.
[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         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);
59   void resetParserState();
60   uint64_t getMainBinarySymbolAddress(StringRef Name);
61   void loadMainBinarySymbols();
62   void loadCurrentObjectFileSymbols();
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   resetParserState();
89
90   SmallString<80> Path(PathPrefix);
91   sys::path::append(Path, Filename);
92
93   auto MachOOrError = CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path);
94   if (auto Error = MachOOrError.getError()) {
95     Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
96             Error.message() + "\n");
97     return;
98   }
99
100   loadCurrentObjectFileSymbols();
101   CurrentDebugMapObject = &Result->addDebugMapObject(Path);
102 }
103
104 static Triple getTriple(const object::MachOObjectFile &Obj) {
105   Triple TheTriple("unknown-unknown-unknown");
106   TheTriple.setArch(Triple::ArchType(Obj.getArch()));
107   TheTriple.setObjectFormat(Triple::MachO);
108   return TheTriple;
109 }
110
111 /// This main parsing routine tries to open the main binary and if
112 /// successful iterates over the STAB entries. The real parsing is
113 /// done in handleStabSymbolTableEntry.
114 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() {
115   auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath);
116   if (auto Error = MainBinOrError.getError())
117     return Error;
118
119   const MachOObjectFile &MainBinary = *MainBinOrError;
120   loadMainBinarySymbols();
121   Result = make_unique<DebugMap>(getTriple(MainBinary));
122   MainBinaryStrings = MainBinary.getStringTableData();
123   for (const SymbolRef &Symbol : MainBinary.symbols()) {
124     const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
125     if (MainBinary.is64Bit())
126       handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
127     else
128       handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
129   }
130
131   resetParserState();
132   return std::move(Result);
133 }
134
135 /// Interpret the STAB entries to fill the DebugMap.
136 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
137                                                      uint8_t Type,
138                                                      uint8_t SectionIndex,
139                                                      uint16_t Flags,
140                                                      uint64_t Value) {
141   if (!(Type & MachO::N_STAB))
142     return;
143
144   const char *Name = &MainBinaryStrings.data()[StringIndex];
145
146   // An N_OSO entry represents the start of a new object file description.
147   if (Type == MachO::N_OSO)
148     return switchToNewDebugMapObject(Name);
149
150   // If the last N_OSO object file wasn't found,
151   // CurrentDebugMapObject will be null. Do not update anything
152   // until we find the next valid N_OSO entry.
153   if (!CurrentDebugMapObject)
154     return;
155
156   uint32_t Size = 0;
157   switch (Type) {
158   case MachO::N_GSYM:
159     // This is a global variable. We need to query the main binary
160     // symbol table to find its address as it might not be in the
161     // debug map (for common symbols).
162     Value = getMainBinarySymbolAddress(Name);
163     break;
164   case MachO::N_FUN:
165     // Functions are scopes in STABS. They have an end marker that
166     // contains the function size.
167     if (Name[0] == '\0') {
168       Size = Value;
169       Value = CurrentFunctionAddress;
170       Name = CurrentFunctionName;
171       break;
172     } else {
173       CurrentFunctionName = Name;
174       CurrentFunctionAddress = Value;
175       return;
176     }
177   case MachO::N_STSYM:
178     break;
179   default:
180     return;
181   }
182
183   auto ObjectSymIt = CurrentObjectAddresses.find(Name);
184   if (ObjectSymIt == CurrentObjectAddresses.end())
185     return Warning("could not find object file symbol for symbol " +
186                    Twine(Name));
187   if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
188                                         Size))
189     return Warning(Twine("failed to insert symbol '") + Name +
190                    "' in the debug map.");
191 }
192
193 /// Load the current object file symbols into CurrentObjectAddresses.
194 void MachODebugMapParser::loadCurrentObjectFileSymbols() {
195   CurrentObjectAddresses.clear();
196
197   for (auto Sym : CurrentObjectHolder.Get().symbols()) {
198     uint64_t Addr = Sym.getValue();
199     ErrorOr<StringRef> Name = Sym.getName();
200     if (!Name)
201       continue;
202     CurrentObjectAddresses[*Name] = Addr;
203   }
204 }
205
206 /// Lookup a symbol address in the main binary symbol table. The
207 /// parser only needs to query common symbols, thus not every symbol's
208 /// address is available through this function.
209 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
210   auto Sym = MainBinarySymbolAddresses.find(Name);
211   if (Sym == MainBinarySymbolAddresses.end())
212     return 0;
213   return Sym->second;
214 }
215
216 /// Load the interesting main binary symbols' addresses into
217 /// MainBinarySymbolAddresses.
218 void MachODebugMapParser::loadMainBinarySymbols() {
219   const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>();
220   section_iterator Section = MainBinary.section_end();
221   for (const auto &Sym : MainBinary.symbols()) {
222     SymbolRef::Type Type = Sym.getType();
223     // Skip undefined and STAB entries.
224     if ((Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown))
225       continue;
226     // The only symbols of interest are the global variables. These
227     // are the only ones that need to be queried because the address
228     // of common data won't be described in the debug map. All other
229     // addresses should be fetched for the debug map.
230     if (!(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) ||
231         Section == MainBinary.section_end() || Section->isText())
232       continue;
233     uint64_t Addr = Sym.getValue();
234     ErrorOr<StringRef> NameOrErr = Sym.getName();
235     if (!NameOrErr)
236       continue;
237     StringRef Name = *NameOrErr;
238     if (Name.size() == 0 || Name[0] == '\0')
239       continue;
240     MainBinarySymbolAddresses[Name] = Addr;
241   }
242 }
243
244 namespace llvm {
245 namespace dsymutil {
246 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
247                                                        StringRef PrependPath,
248                                                        bool Verbose,
249                                                        bool InputIsYAML) {
250   if (!InputIsYAML) {
251     MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
252     return Parser.parse();
253   } else {
254     return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
255   }
256 }
257 }
258 }