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