fix typos; NFC
[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     return CoffObject->getImageBase();
132   return 0;
133 }
134
135 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
136                                         std::string &Name, uint64_t &Addr,
137                                         uint64_t &Size) const {
138   const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
139   if (SymbolMap.empty())
140     return false;
141   SymbolDesc SD = { Address, Address };
142   auto SymbolIterator = SymbolMap.upper_bound(SD);
143   if (SymbolIterator == SymbolMap.begin())
144     return false;
145   --SymbolIterator;
146   if (SymbolIterator->first.Size != 0 &&
147       SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
148     return false;
149   Name = SymbolIterator->second.str();
150   Addr = SymbolIterator->first.Addr;
151   Size = SymbolIterator->first.Size;
152   return true;
153 }
154
155 DILineInfo ModuleInfo::symbolizeCode(
156     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
157   DILineInfo LineInfo;
158   if (DebugInfoContext) {
159     LineInfo = DebugInfoContext->getLineInfoForAddress(
160         ModuleOffset, getDILineInfoSpecifier(Opts));
161   }
162   // Override function name from symbol table if necessary.
163   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
164     std::string FunctionName;
165     uint64_t Start, Size;
166     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
167                                FunctionName, Start, Size)) {
168       LineInfo.FunctionName = FunctionName;
169     }
170   }
171   return LineInfo;
172 }
173
174 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
175     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
176   DIInliningInfo InlinedContext;
177
178   if (DebugInfoContext) {
179     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
180         ModuleOffset, getDILineInfoSpecifier(Opts));
181   }
182   // Make sure there is at least one frame in context.
183   if (InlinedContext.getNumberOfFrames() == 0) {
184     InlinedContext.addFrame(DILineInfo());
185   }
186   // Override the function name in lower frame with name from symbol table.
187   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
188     DIInliningInfo PatchedInlinedContext;
189     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
190       DILineInfo LineInfo = InlinedContext.getFrame(i);
191       if (i == n - 1) {
192         std::string FunctionName;
193         uint64_t Start, Size;
194         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
195                                    FunctionName, Start, Size)) {
196           LineInfo.FunctionName = FunctionName;
197         }
198       }
199       PatchedInlinedContext.addFrame(LineInfo);
200     }
201     InlinedContext = PatchedInlinedContext;
202   }
203   return InlinedContext;
204 }
205
206 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
207                                uint64_t &Start, uint64_t &Size) const {
208   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
209                                 Size);
210 }
211
212 const char LLVMSymbolizer::kBadString[] = "??";
213
214 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
215                                           uint64_t ModuleOffset) {
216   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
217   if (!Info)
218     return printDILineInfo(DILineInfo(), Info);
219
220   // If the user is giving us relative addresses, add the preferred base of the
221   // object to the offset before we do the query. It's what DIContext expects.
222   if (Opts.RelativeAddresses)
223     ModuleOffset += Info->getModulePreferredBase();
224
225   if (Opts.PrintInlining) {
226     DIInliningInfo InlinedContext =
227         Info->symbolizeInlinedCode(ModuleOffset, Opts);
228     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
229     assert(FramesNum > 0);
230     std::string Result;
231     for (uint32_t i = 0; i < FramesNum; i++) {
232       DILineInfo LineInfo = InlinedContext.getFrame(i);
233       Result += printDILineInfo(LineInfo, Info);
234     }
235     return Result;
236   }
237   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
238   return printDILineInfo(LineInfo, Info);
239 }
240
241 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
242                                           uint64_t ModuleOffset) {
243   std::string Name = kBadString;
244   uint64_t Start = 0;
245   uint64_t Size = 0;
246   if (Opts.UseSymbolTable) {
247     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
248       // If the user is giving us relative addresses, add the preferred base of the
249       // object to the offset before we do the query. It's what DIContext expects.
250       if (Opts.RelativeAddresses)
251         ModuleOffset += Info->getModulePreferredBase();
252       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
253         Name = DemangleName(Name, Info);
254     }
255   }
256   std::stringstream ss;
257   ss << Name << "\n" << Start << " " << Size << "\n";
258   return ss.str();
259 }
260
261 void LLVMSymbolizer::flush() {
262   DeleteContainerSeconds(Modules);
263   ObjectPairForPathArch.clear();
264   ObjectFileForArch.clear();
265 }
266
267 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
268 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
269 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
270 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
271 static
272 std::string getDarwinDWARFResourceForPath(
273     const std::string &Path, const std::string &Basename) {
274   SmallString<16> ResourceName = StringRef(Path);
275   if (sys::path::extension(Path) != ".dSYM") {
276     ResourceName += ".dSYM";
277   }
278   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
279   sys::path::append(ResourceName, Basename);
280   return ResourceName.str();
281 }
282
283 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
284   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
285       MemoryBuffer::getFileOrSTDIN(Path);
286   if (!MB)
287     return false;
288   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
289 }
290
291 static bool findDebugBinary(const std::string &OrigPath,
292                             const std::string &DebuglinkName, uint32_t CRCHash,
293                             std::string &Result) {
294   std::string OrigRealPath = OrigPath;
295 #if defined(HAVE_REALPATH)
296   if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
297     OrigRealPath = RP;
298     free(RP);
299   }
300 #endif
301   SmallString<16> OrigDir(OrigRealPath);
302   llvm::sys::path::remove_filename(OrigDir);
303   SmallString<16> DebugPath = OrigDir;
304   // Try /path/to/original_binary/debuglink_name
305   llvm::sys::path::append(DebugPath, DebuglinkName);
306   if (checkFileCRC(DebugPath, CRCHash)) {
307     Result = DebugPath.str();
308     return true;
309   }
310   // Try /path/to/original_binary/.debug/debuglink_name
311   DebugPath = OrigRealPath;
312   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
313   if (checkFileCRC(DebugPath, CRCHash)) {
314     Result = DebugPath.str();
315     return true;
316   }
317   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
318   DebugPath = "/usr/lib/debug";
319   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
320                           DebuglinkName);
321   if (checkFileCRC(DebugPath, CRCHash)) {
322     Result = DebugPath.str();
323     return true;
324   }
325   return false;
326 }
327
328 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
329                                     uint32_t &CRCHash) {
330   if (!Obj)
331     return false;
332   for (const SectionRef &Section : Obj->sections()) {
333     StringRef Name;
334     Section.getName(Name);
335     Name = Name.substr(Name.find_first_not_of("._"));
336     if (Name == "gnu_debuglink") {
337       StringRef Data;
338       Section.getContents(Data);
339       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
340       uint32_t Offset = 0;
341       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
342         // 4-byte align the offset.
343         Offset = (Offset + 3) & ~0x3;
344         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
345           DebugName = DebugNameStr;
346           CRCHash = DE.getU32(&Offset);
347           return true;
348         }
349       }
350       break;
351     }
352   }
353   return false;
354 }
355
356 static
357 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
358                              const MachOObjectFile *Obj) {
359   ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
360   ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
361   if (dbg_uuid.empty() || bin_uuid.empty())
362     return false;
363   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
364 }
365
366 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
367     const MachOObjectFile *MachExeObj, const std::string &ArchName) {
368   // On Darwin we may find DWARF in separate object file in
369   // resource directory.
370   std::vector<std::string> DsymPaths;
371   StringRef Filename = sys::path::filename(ExePath);
372   DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
373   for (const auto &Path : Opts.DsymHints) {
374     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
375   }
376   for (const auto &path : DsymPaths) {
377     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
378     std::error_code EC = BinaryOrErr.getError();
379     if (EC != errc::no_such_file_or_directory && !error(EC)) {
380       OwningBinary<Binary> B = std::move(BinaryOrErr.get());
381       ObjectFile *DbgObj =
382           getObjectFileFromBinary(B.getBinary(), ArchName);
383       const MachOObjectFile *MachDbgObj =
384           dyn_cast<const MachOObjectFile>(DbgObj);
385       if (!MachDbgObj) continue;
386       if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
387         addOwningBinary(std::move(B));
388         return DbgObj; 
389       }
390     }
391   }
392   return nullptr;
393 }
394
395 LLVMSymbolizer::ObjectPair
396 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
397                                    const std::string &ArchName) {
398   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
399   if (I != ObjectPairForPathArch.end())
400     return I->second;
401   ObjectFile *Obj = nullptr;
402   ObjectFile *DbgObj = nullptr;
403   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
404   if (!error(BinaryOrErr.getError())) {
405     OwningBinary<Binary> &B = BinaryOrErr.get();
406     Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
407     if (!Obj) {
408       ObjectPair Res = std::make_pair(nullptr, nullptr);
409       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
410       return Res;
411     }
412     addOwningBinary(std::move(B));
413     if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
414       DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
415     // Try to locate the debug binary using .gnu_debuglink section.
416     if (!DbgObj) {
417       std::string DebuglinkName;
418       uint32_t CRCHash;
419       std::string DebugBinaryPath;
420       if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
421           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
422         BinaryOrErr = createBinary(DebugBinaryPath);
423         if (!error(BinaryOrErr.getError())) {
424           OwningBinary<Binary> B = std::move(BinaryOrErr.get());
425           DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
426           addOwningBinary(std::move(B));
427         }
428       }
429     }
430   }
431   if (!DbgObj)
432     DbgObj = Obj;
433   ObjectPair Res = std::make_pair(Obj, DbgObj);
434   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
435   return Res;
436 }
437
438 ObjectFile *
439 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
440                                         const std::string &ArchName) {
441   if (!Bin)
442     return nullptr;
443   ObjectFile *Res = nullptr;
444   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
445     const auto &I = ObjectFileForArch.find(
446         std::make_pair(UB, ArchName));
447     if (I != ObjectFileForArch.end())
448       return I->second;
449     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
450         UB->getObjectForArch(ArchName);
451     if (ParsedObj) {
452       Res = ParsedObj.get().get();
453       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
454     }
455     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
456   } else if (Bin->isObject()) {
457     Res = cast<ObjectFile>(Bin);
458   }
459   return Res;
460 }
461
462 ModuleInfo *
463 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
464   const auto &I = Modules.find(ModuleName);
465   if (I != Modules.end())
466     return I->second;
467   std::string BinaryName = ModuleName;
468   std::string ArchName = Opts.DefaultArch;
469   size_t ColonPos = ModuleName.find_last_of(':');
470   // Verify that substring after colon form a valid arch name.
471   if (ColonPos != std::string::npos) {
472     std::string ArchStr = ModuleName.substr(ColonPos + 1);
473     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
474       BinaryName = ModuleName.substr(0, ColonPos);
475       ArchName = ArchStr;
476     }
477   }
478   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
479
480   if (!Objects.first) {
481     // Failed to find valid object file.
482     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
483     return nullptr;
484   }
485   DIContext *Context = nullptr;
486   if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
487     // If this is a COFF object, assume it contains PDB debug information.  If
488     // we don't find any we will fall back to the DWARF case.
489     std::unique_ptr<IPDBSession> Session;
490     PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
491                                          Objects.first->getFileName(), Session);
492     if (Error == PDB_ErrorCode::Success) {
493       Context = new PDBContext(*CoffObject, std::move(Session));
494     }
495   }
496   if (!Context)
497     Context = new DWARFContextInMemory(*Objects.second);
498   assert(Context);
499   ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
500   Modules.insert(make_pair(ModuleName, Info));
501   return Info;
502 }
503
504 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
505                                             ModuleInfo *ModInfo) const {
506   // By default, DILineInfo contains "<invalid>" for function/filename it
507   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
508   static const std::string kDILineInfoBadString = "<invalid>";
509   std::stringstream Result;
510   if (Opts.PrintFunctions != FunctionNameKind::None) {
511     std::string FunctionName = LineInfo.FunctionName;
512     if (FunctionName == kDILineInfoBadString)
513       FunctionName = kBadString;
514     else if (Opts.Demangle)
515       FunctionName = DemangleName(FunctionName, ModInfo);
516     Result << FunctionName << "\n";
517   }
518   std::string Filename = LineInfo.FileName;
519   if (Filename == kDILineInfoBadString)
520     Filename = kBadString;
521   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
522   return Result.str();
523 }
524
525 // Undo these various manglings for Win32 extern "C" functions:
526 // cdecl       - _foo
527 // stdcall     - _foo@12
528 // fastcall    - @foo@12
529 // vectorcall  - foo@@12
530 // These are all different linkage names for 'foo'.
531 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
532   // Remove any '_' or '@' prefix.
533   char Front = SymbolName.empty() ? '\0' : SymbolName[0];
534   if (Front == '_' || Front == '@')
535     SymbolName = SymbolName.drop_front();
536
537   // Remove any '@[0-9]+' suffix.
538   if (Front != '?') {
539     size_t AtPos = SymbolName.rfind('@');
540     if (AtPos != StringRef::npos &&
541         std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
542                     [](char C) { return C >= '0' && C <= '9'; })) {
543       SymbolName = SymbolName.substr(0, AtPos);
544     }
545   }
546
547   // Remove any ending '@' for vectorcall.
548   if (SymbolName.endswith("@"))
549     SymbolName = SymbolName.drop_back();
550
551   return SymbolName;
552 }
553
554 #if !defined(_MSC_VER)
555 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
556 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
557                                 size_t *length, int *status);
558 #endif
559
560 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
561                                          ModuleInfo *ModInfo) {
562 #if !defined(_MSC_VER)
563   // We can spoil names of symbols with C linkage, so use an heuristic
564   // approach to check if the name should be demangled.
565   if (Name.substr(0, 2) == "_Z") {
566     int status = 0;
567     char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
568     if (status != 0)
569       return Name;
570     std::string Result = DemangledName;
571     free(DemangledName);
572     return Result;
573   }
574 #else
575   if (!Name.empty() && Name.front() == '?') {
576     // Only do MSVC C++ demangling on symbols starting with '?'.
577     char DemangledName[1024] = {0};
578     DWORD result = ::UnDecorateSymbolName(
579         Name.c_str(), DemangledName, 1023,
580         UNDNAME_NO_ACCESS_SPECIFIERS |       // Strip public, private, protected
581             UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
582             UNDNAME_NO_THROW_SIGNATURES |    // Strip throw() specifications
583             UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
584             UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
585             UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
586     return (result == 0) ? Name : std::string(DemangledName);
587   }
588 #endif
589   if (ModInfo->isWin32Module())
590     return std::string(demanglePE32ExternCFunc(Name));
591   return Name;
592 }
593
594 } // namespace symbolize
595 } // namespace llvm