[llvm-symbolizer] Make --relative-address work with DWARF contexts
[oota-llvm.git] / tools / llvm-symbolizer / LLVMSymbolize.cpp
1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation for LLVM symbolization library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLVMSymbolize.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/PDB/PDB.h"
19 #include "llvm/DebugInfo/PDB/PDBContext.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/MachO.h"
22 #include "llvm/Object/SymbolSize.h"
23 #include "llvm/Support/COFF.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/DataExtractor.h"
27 #include "llvm/Support/Errc.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include <sstream>
32 #include <stdlib.h>
33
34 #if defined(_MSC_VER)
35 #include <Windows.h>
36 #include <DbgHelp.h>
37 #pragma comment(lib, "dbghelp.lib")
38
39 // Windows.h conflicts with our COFF header definitions.
40 #ifdef IMAGE_FILE_MACHINE_I386
41 #undef IMAGE_FILE_MACHINE_I386
42 #endif
43 #endif
44
45 namespace llvm {
46 namespace symbolize {
47
48 static bool error(std::error_code ec) {
49   if (!ec)
50     return false;
51   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
52   return true;
53 }
54
55 static DILineInfoSpecifier
56 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
57   return DILineInfoSpecifier(
58       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
59       Opts.PrintFunctions);
60 }
61
62 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
63     : Module(Obj), DebugInfoContext(DICtx) {
64   std::unique_ptr<DataExtractor> OpdExtractor;
65   uint64_t OpdAddress = 0;
66   // Find the .opd (function descriptor) section if any, for big-endian
67   // PowerPC64 ELF.
68   if (Module->getArch() == Triple::ppc64) {
69     for (section_iterator Section : Module->sections()) {
70       StringRef Name;
71       if (!error(Section->getName(Name)) && Name == ".opd") {
72         StringRef Data;
73         if (!error(Section->getContents(Data))) {
74           OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
75                                                Module->getBytesInAddress()));
76           OpdAddress = Section->getAddress();
77         }
78         break;
79       }
80     }
81   }
82   std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
83       computeSymbolSizes(*Module);
84   for (auto &P : Symbols)
85     addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
86 }
87
88 void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
89                            DataExtractor *OpdExtractor, uint64_t OpdAddress) {
90   SymbolRef::Type SymbolType = Symbol.getType();
91   if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
92     return;
93   ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
94   if (error(SymbolAddressOrErr.getError()))
95     return;
96   uint64_t SymbolAddress = *SymbolAddressOrErr;
97   if (OpdExtractor) {
98     // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
99     // function descriptors. The first word of the descriptor is a pointer to
100     // the function's code.
101     // For the purposes of symbolization, pretend the symbol's address is that
102     // of the function's code, not the descriptor.
103     uint64_t OpdOffset = SymbolAddress - OpdAddress;
104     uint32_t OpdOffset32 = OpdOffset;
105     if (OpdOffset == OpdOffset32 && 
106         OpdExtractor->isValidOffsetForAddress(OpdOffset32))
107       SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
108   }
109   ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
110   if (error(SymbolNameOrErr.getError()))
111     return;
112   StringRef SymbolName = *SymbolNameOrErr;
113   // Mach-O symbol table names have leading underscore, skip it.
114   if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
115     SymbolName = SymbolName.drop_front();
116   // FIXME: If a function has alias, there are two entries in symbol table
117   // with same address size. Make sure we choose the correct one.
118   auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
119   SymbolDesc SD = { SymbolAddress, SymbolSize };
120   M.insert(std::make_pair(SD, SymbolName));
121 }
122
123 // Return true if this is a 32-bit x86 PE COFF module.
124 bool ModuleInfo::isWin32Module() const {
125   auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
126   return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
127 }
128
129 uint64_t ModuleInfo::getModulePreferredBase() const {
130   if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
131     if (auto Base = CoffObject->getImageBase())
132       return Base.get();
133   return 0;
134 }
135
136 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
137                                         std::string &Name, uint64_t &Addr,
138                                         uint64_t &Size) const {
139   const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
140   if (SymbolMap.empty())
141     return false;
142   SymbolDesc SD = { Address, Address };
143   auto SymbolIterator = SymbolMap.upper_bound(SD);
144   if (SymbolIterator == SymbolMap.begin())
145     return false;
146   --SymbolIterator;
147   if (SymbolIterator->first.Size != 0 &&
148       SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
149     return false;
150   Name = SymbolIterator->second.str();
151   Addr = SymbolIterator->first.Addr;
152   Size = SymbolIterator->first.Size;
153   return true;
154 }
155
156 DILineInfo ModuleInfo::symbolizeCode(
157     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
158   DILineInfo LineInfo;
159   if (DebugInfoContext) {
160     LineInfo = DebugInfoContext->getLineInfoForAddress(
161         ModuleOffset, getDILineInfoSpecifier(Opts));
162   }
163   // Override function name from symbol table if necessary.
164   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
165     std::string FunctionName;
166     uint64_t Start, Size;
167     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
168                                FunctionName, Start, Size)) {
169       LineInfo.FunctionName = FunctionName;
170     }
171   }
172   return LineInfo;
173 }
174
175 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
176     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
177   DIInliningInfo InlinedContext;
178
179   if (DebugInfoContext) {
180     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
181         ModuleOffset, getDILineInfoSpecifier(Opts));
182   }
183   // Make sure there is at least one frame in context.
184   if (InlinedContext.getNumberOfFrames() == 0) {
185     InlinedContext.addFrame(DILineInfo());
186   }
187   // Override the function name in lower frame with name from symbol table.
188   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
189     DIInliningInfo PatchedInlinedContext;
190     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
191       DILineInfo LineInfo = InlinedContext.getFrame(i);
192       if (i == n - 1) {
193         std::string FunctionName;
194         uint64_t Start, Size;
195         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
196                                    FunctionName, Start, Size)) {
197           LineInfo.FunctionName = FunctionName;
198         }
199       }
200       PatchedInlinedContext.addFrame(LineInfo);
201     }
202     InlinedContext = PatchedInlinedContext;
203   }
204   return InlinedContext;
205 }
206
207 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
208                                uint64_t &Start, uint64_t &Size) const {
209   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
210                                 Size);
211 }
212
213 const char LLVMSymbolizer::kBadString[] = "??";
214
215 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
216                                           uint64_t ModuleOffset) {
217   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
218   if (!Info)
219     return printDILineInfo(DILineInfo(), Info);
220
221   // If the user is giving us relative addresses, add the preferred base of the
222   // object to the offset before we do the query. It's what DIContext expects.
223   if (Opts.RelativeAddresses)
224     ModuleOffset += Info->getModulePreferredBase();
225
226   if (Opts.PrintInlining) {
227     DIInliningInfo InlinedContext =
228         Info->symbolizeInlinedCode(ModuleOffset, Opts);
229     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
230     assert(FramesNum > 0);
231     std::string Result;
232     for (uint32_t i = 0; i < FramesNum; i++) {
233       DILineInfo LineInfo = InlinedContext.getFrame(i);
234       Result += printDILineInfo(LineInfo, Info);
235     }
236     return Result;
237   }
238   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
239   return printDILineInfo(LineInfo, Info);
240 }
241
242 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
243                                           uint64_t ModuleOffset) {
244   std::string Name = kBadString;
245   uint64_t Start = 0;
246   uint64_t Size = 0;
247   if (Opts.UseSymbolTable) {
248     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
249       // If the user is giving us relative addresses, add the preferred base of the
250       // object to the offset before we do the query. It's what DIContext expects.
251       if (Opts.RelativeAddresses)
252         ModuleOffset += Info->getModulePreferredBase();
253       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
254         Name = DemangleName(Name, Info);
255     }
256   }
257   std::stringstream ss;
258   ss << Name << "\n" << Start << " " << Size << "\n";
259   return ss.str();
260 }
261
262 void LLVMSymbolizer::flush() {
263   DeleteContainerSeconds(Modules);
264   ObjectPairForPathArch.clear();
265   ObjectFileForArch.clear();
266 }
267
268 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
269 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
270 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
271 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
272 static
273 std::string getDarwinDWARFResourceForPath(
274     const std::string &Path, const std::string &Basename) {
275   SmallString<16> ResourceName = StringRef(Path);
276   if (sys::path::extension(Path) != ".dSYM") {
277     ResourceName += ".dSYM";
278   }
279   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
280   sys::path::append(ResourceName, Basename);
281   return ResourceName.str();
282 }
283
284 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
285   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
286       MemoryBuffer::getFileOrSTDIN(Path);
287   if (!MB)
288     return false;
289   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
290 }
291
292 static bool findDebugBinary(const std::string &OrigPath,
293                             const std::string &DebuglinkName, uint32_t CRCHash,
294                             std::string &Result) {
295   std::string OrigRealPath = OrigPath;
296 #if defined(HAVE_REALPATH)
297   if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
298     OrigRealPath = RP;
299     free(RP);
300   }
301 #endif
302   SmallString<16> OrigDir(OrigRealPath);
303   llvm::sys::path::remove_filename(OrigDir);
304   SmallString<16> DebugPath = OrigDir;
305   // Try /path/to/original_binary/debuglink_name
306   llvm::sys::path::append(DebugPath, DebuglinkName);
307   if (checkFileCRC(DebugPath, CRCHash)) {
308     Result = DebugPath.str();
309     return true;
310   }
311   // Try /path/to/original_binary/.debug/debuglink_name
312   DebugPath = OrigRealPath;
313   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
314   if (checkFileCRC(DebugPath, CRCHash)) {
315     Result = DebugPath.str();
316     return true;
317   }
318   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
319   DebugPath = "/usr/lib/debug";
320   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
321                           DebuglinkName);
322   if (checkFileCRC(DebugPath, CRCHash)) {
323     Result = DebugPath.str();
324     return true;
325   }
326   return false;
327 }
328
329 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
330                                     uint32_t &CRCHash) {
331   if (!Obj)
332     return false;
333   for (const SectionRef &Section : Obj->sections()) {
334     StringRef Name;
335     Section.getName(Name);
336     Name = Name.substr(Name.find_first_not_of("._"));
337     if (Name == "gnu_debuglink") {
338       StringRef Data;
339       Section.getContents(Data);
340       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
341       uint32_t Offset = 0;
342       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
343         // 4-byte align the offset.
344         Offset = (Offset + 3) & ~0x3;
345         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
346           DebugName = DebugNameStr;
347           CRCHash = DE.getU32(&Offset);
348           return true;
349         }
350       }
351       break;
352     }
353   }
354   return false;
355 }
356
357 static
358 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
359                              const MachOObjectFile *Obj) {
360   ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
361   ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
362   if (dbg_uuid.empty() || bin_uuid.empty())
363     return false;
364   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
365 }
366
367 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
368     const MachOObjectFile *MachExeObj, const std::string &ArchName) {
369   // On Darwin we may find DWARF in separate object file in
370   // resource directory.
371   std::vector<std::string> DsymPaths;
372   StringRef Filename = sys::path::filename(ExePath);
373   DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
374   for (const auto &Path : Opts.DsymHints) {
375     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
376   }
377   for (const auto &path : DsymPaths) {
378     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
379     std::error_code EC = BinaryOrErr.getError();
380     if (EC != errc::no_such_file_or_directory && !error(EC)) {
381       OwningBinary<Binary> B = std::move(BinaryOrErr.get());
382       ObjectFile *DbgObj =
383           getObjectFileFromBinary(B.getBinary(), ArchName);
384       const MachOObjectFile *MachDbgObj =
385           dyn_cast<const MachOObjectFile>(DbgObj);
386       if (!MachDbgObj) continue;
387       if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
388         addOwningBinary(std::move(B));
389         return DbgObj; 
390       }
391     }
392   }
393   return nullptr;
394 }
395
396 LLVMSymbolizer::ObjectPair
397 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
398                                    const std::string &ArchName) {
399   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
400   if (I != ObjectPairForPathArch.end())
401     return I->second;
402   ObjectFile *Obj = nullptr;
403   ObjectFile *DbgObj = nullptr;
404   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
405   if (!error(BinaryOrErr.getError())) {
406     OwningBinary<Binary> &B = BinaryOrErr.get();
407     Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
408     if (!Obj) {
409       ObjectPair Res = std::make_pair(nullptr, nullptr);
410       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
411       return Res;
412     }
413     addOwningBinary(std::move(B));
414     if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
415       DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
416     // Try to locate the debug binary using .gnu_debuglink section.
417     if (!DbgObj) {
418       std::string DebuglinkName;
419       uint32_t CRCHash;
420       std::string DebugBinaryPath;
421       if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
422           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
423         BinaryOrErr = createBinary(DebugBinaryPath);
424         if (!error(BinaryOrErr.getError())) {
425           OwningBinary<Binary> B = std::move(BinaryOrErr.get());
426           DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
427           addOwningBinary(std::move(B));
428         }
429       }
430     }
431   }
432   if (!DbgObj)
433     DbgObj = Obj;
434   ObjectPair Res = std::make_pair(Obj, DbgObj);
435   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
436   return Res;
437 }
438
439 ObjectFile *
440 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
441                                         const std::string &ArchName) {
442   if (!Bin)
443     return nullptr;
444   ObjectFile *Res = nullptr;
445   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
446     const auto &I = ObjectFileForArch.find(
447         std::make_pair(UB, ArchName));
448     if (I != ObjectFileForArch.end())
449       return I->second;
450     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
451         UB->getObjectForArch(ArchName);
452     if (ParsedObj) {
453       Res = ParsedObj.get().get();
454       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
455     }
456     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
457   } else if (Bin->isObject()) {
458     Res = cast<ObjectFile>(Bin);
459   }
460   return Res;
461 }
462
463 ModuleInfo *
464 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
465   const auto &I = Modules.find(ModuleName);
466   if (I != Modules.end())
467     return I->second;
468   std::string BinaryName = ModuleName;
469   std::string ArchName = Opts.DefaultArch;
470   size_t ColonPos = ModuleName.find_last_of(':');
471   // Verify that substring after colon form a valid arch name.
472   if (ColonPos != std::string::npos) {
473     std::string ArchStr = ModuleName.substr(ColonPos + 1);
474     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
475       BinaryName = ModuleName.substr(0, ColonPos);
476       ArchName = ArchStr;
477     }
478   }
479   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
480
481   if (!Objects.first) {
482     // Failed to find valid object file.
483     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
484     return nullptr;
485   }
486   DIContext *Context = nullptr;
487   if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
488     // If this is a COFF object, assume it contains PDB debug information.  If
489     // we don't find any we will fall back to the DWARF case.
490     std::unique_ptr<IPDBSession> Session;
491     PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
492                                          Objects.first->getFileName(), Session);
493     if (Error == PDB_ErrorCode::Success) {
494       Context = new PDBContext(*CoffObject, std::move(Session));
495     }
496   }
497   if (!Context)
498     Context = new DWARFContextInMemory(*Objects.second);
499   assert(Context);
500   ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
501   Modules.insert(make_pair(ModuleName, Info));
502   return Info;
503 }
504
505 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
506                                             ModuleInfo *ModInfo) const {
507   // By default, DILineInfo contains "<invalid>" for function/filename it
508   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
509   static const std::string kDILineInfoBadString = "<invalid>";
510   std::stringstream Result;
511   if (Opts.PrintFunctions != FunctionNameKind::None) {
512     std::string FunctionName = LineInfo.FunctionName;
513     if (FunctionName == kDILineInfoBadString)
514       FunctionName = kBadString;
515     else if (Opts.Demangle)
516       FunctionName = DemangleName(FunctionName, ModInfo);
517     Result << FunctionName << "\n";
518   }
519   std::string Filename = LineInfo.FileName;
520   if (Filename == kDILineInfoBadString)
521     Filename = kBadString;
522   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
523   return Result.str();
524 }
525
526 // Undo these various manglings for Win32 extern "C" functions:
527 // cdecl       - _foo
528 // stdcall     - _foo@12
529 // fastcall    - @foo@12
530 // vectorcall  - foo@@12
531 // These are all different linkage names for 'foo'.
532 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
533   // Remove any '_' or '@' prefix.
534   char Front = SymbolName.empty() ? '\0' : SymbolName[0];
535   if (Front == '_' || Front == '@')
536     SymbolName = SymbolName.drop_front();
537
538   // Remove any '@[0-9]+' suffix.
539   if (Front != '?') {
540     size_t AtPos = SymbolName.rfind('@');
541     if (AtPos != StringRef::npos &&
542         std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
543                     [](char C) { return C >= '0' && C <= '9'; })) {
544       SymbolName = SymbolName.substr(0, AtPos);
545     }
546   }
547
548   // Remove any ending '@' for vectorcall.
549   if (SymbolName.endswith("@"))
550     SymbolName = SymbolName.drop_back();
551
552   return SymbolName;
553 }
554
555 #if !defined(_MSC_VER)
556 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
557 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
558                                 size_t *length, int *status);
559 #endif
560
561 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
562                                          ModuleInfo *ModInfo) {
563 #if !defined(_MSC_VER)
564   // We can spoil names of symbols with C linkage, so use an heuristic
565   // approach to check if the name should be demangled.
566   if (Name.substr(0, 2) == "_Z") {
567     int status = 0;
568     char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
569     if (status != 0)
570       return Name;
571     std::string Result = DemangledName;
572     free(DemangledName);
573     return Result;
574   }
575 #else
576   if (!Name.empty() && Name.front() == '?') {
577     // Only do MSVC C++ demangling on symbols starting with '?'.
578     char DemangledName[1024] = {0};
579     DWORD result = ::UnDecorateSymbolName(
580         Name.c_str(), DemangledName, 1023,
581         UNDNAME_NO_ACCESS_SPECIFIERS |       // Strip public, private, protected
582             UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
583             UNDNAME_NO_THROW_SIGNATURES |    // Strip throw() specifications
584             UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
585             UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
586             UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
587     return (result == 0) ? Name : std::string(DemangledName);
588   }
589 #endif
590   if (ModInfo->isWin32Module())
591     return std::string(demanglePE32ExternCFunc(Name));
592   return Name;
593 }
594
595 } // namespace symbolize
596 } // namespace llvm