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