| File: | src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp |
| Warning: | line 316, column 13 Forming reference to null pointer |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 1 | //===-- SymbolFileNativePDB.cpp -------------------------------------------===// | |||
| 2 | // | |||
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
| 4 | // See https://llvm.org/LICENSE.txt for license information. | |||
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
| 6 | // | |||
| 7 | //===----------------------------------------------------------------------===// | |||
| 8 | ||||
| 9 | #include "SymbolFileNativePDB.h" | |||
| 10 | ||||
| 11 | #include "clang/AST/Attr.h" | |||
| 12 | #include "clang/AST/CharUnits.h" | |||
| 13 | #include "clang/AST/Decl.h" | |||
| 14 | #include "clang/AST/DeclCXX.h" | |||
| 15 | #include "clang/AST/Type.h" | |||
| 16 | ||||
| 17 | #include "Plugins/ExpressionParser/Clang/ClangUtil.h" | |||
| 18 | #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" | |||
| 19 | #include "Plugins/ObjectFile/PDB/ObjectFilePDB.h" | |||
| 20 | #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" | |||
| 21 | #include "lldb/Core/Module.h" | |||
| 22 | #include "lldb/Core/PluginManager.h" | |||
| 23 | #include "lldb/Core/StreamBuffer.h" | |||
| 24 | #include "lldb/Core/StreamFile.h" | |||
| 25 | #include "lldb/Symbol/CompileUnit.h" | |||
| 26 | #include "lldb/Symbol/LineTable.h" | |||
| 27 | #include "lldb/Symbol/ObjectFile.h" | |||
| 28 | #include "lldb/Symbol/SymbolContext.h" | |||
| 29 | #include "lldb/Symbol/SymbolVendor.h" | |||
| 30 | #include "lldb/Symbol/Variable.h" | |||
| 31 | #include "lldb/Symbol/VariableList.h" | |||
| 32 | #include "lldb/Utility/Log.h" | |||
| 33 | ||||
| 34 | #include "llvm/DebugInfo/CodeView/CVRecord.h" | |||
| 35 | #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" | |||
| 36 | #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h" | |||
| 37 | #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h" | |||
| 38 | #include "llvm/DebugInfo/CodeView/RecordName.h" | |||
| 39 | #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" | |||
| 40 | #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h" | |||
| 41 | #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" | |||
| 42 | #include "llvm/DebugInfo/PDB/Native/DbiStream.h" | |||
| 43 | #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h" | |||
| 44 | #include "llvm/DebugInfo/PDB/Native/InfoStream.h" | |||
| 45 | #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h" | |||
| 46 | #include "llvm/DebugInfo/PDB/Native/NativeSession.h" | |||
| 47 | #include "llvm/DebugInfo/PDB/Native/PDBFile.h" | |||
| 48 | #include "llvm/DebugInfo/PDB/Native/SymbolStream.h" | |||
| 49 | #include "llvm/DebugInfo/PDB/Native/TpiStream.h" | |||
| 50 | #include "llvm/DebugInfo/PDB/PDB.h" | |||
| 51 | #include "llvm/DebugInfo/PDB/PDBTypes.h" | |||
| 52 | #include "llvm/Demangle/MicrosoftDemangle.h" | |||
| 53 | #include "llvm/Object/COFF.h" | |||
| 54 | #include "llvm/Support/Allocator.h" | |||
| 55 | #include "llvm/Support/BinaryStreamReader.h" | |||
| 56 | #include "llvm/Support/Error.h" | |||
| 57 | #include "llvm/Support/ErrorOr.h" | |||
| 58 | #include "llvm/Support/MemoryBuffer.h" | |||
| 59 | ||||
| 60 | #include "DWARFLocationExpression.h" | |||
| 61 | #include "PdbAstBuilder.h" | |||
| 62 | #include "PdbSymUid.h" | |||
| 63 | #include "PdbUtil.h" | |||
| 64 | #include "UdtRecordCompleter.h" | |||
| 65 | ||||
| 66 | using namespace lldb; | |||
| 67 | using namespace lldb_private; | |||
| 68 | using namespace npdb; | |||
| 69 | using namespace llvm::codeview; | |||
| 70 | using namespace llvm::pdb; | |||
| 71 | ||||
| 72 | char SymbolFileNativePDB::ID; | |||
| 73 | ||||
| 74 | static lldb::LanguageType TranslateLanguage(PDB_Lang lang) { | |||
| 75 | switch (lang) { | |||
| 76 | case PDB_Lang::Cpp: | |||
| 77 | return lldb::LanguageType::eLanguageTypeC_plus_plus; | |||
| 78 | case PDB_Lang::C: | |||
| 79 | return lldb::LanguageType::eLanguageTypeC; | |||
| 80 | case PDB_Lang::Swift: | |||
| 81 | return lldb::LanguageType::eLanguageTypeSwift; | |||
| 82 | default: | |||
| 83 | return lldb::LanguageType::eLanguageTypeUnknown; | |||
| 84 | } | |||
| 85 | } | |||
| 86 | ||||
| 87 | static std::unique_ptr<PDBFile> | |||
| 88 | loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) { | |||
| 89 | // Try to find a matching PDB for an EXE. | |||
| 90 | using namespace llvm::object; | |||
| 91 | auto expected_binary = createBinary(exe_path); | |||
| 92 | ||||
| 93 | // If the file isn't a PE/COFF executable, fail. | |||
| 94 | if (!expected_binary) { | |||
| 95 | llvm::consumeError(expected_binary.takeError()); | |||
| 96 | return nullptr; | |||
| 97 | } | |||
| 98 | OwningBinary<Binary> binary = std::move(*expected_binary); | |||
| 99 | ||||
| 100 | // TODO: Avoid opening the PE/COFF binary twice by reading this information | |||
| 101 | // directly from the lldb_private::ObjectFile. | |||
| 102 | auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary()); | |||
| 103 | if (!obj) | |||
| 104 | return nullptr; | |||
| 105 | const llvm::codeview::DebugInfo *pdb_info = nullptr; | |||
| 106 | ||||
| 107 | // If it doesn't have a debug directory, fail. | |||
| 108 | llvm::StringRef pdb_file; | |||
| 109 | if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) { | |||
| 110 | consumeError(std::move(e)); | |||
| 111 | return nullptr; | |||
| 112 | } | |||
| 113 | ||||
| 114 | // If the file doesn't exist, perhaps the path specified at build time | |||
| 115 | // doesn't match the PDB's current location, so check the location of the | |||
| 116 | // executable. | |||
| 117 | if (!FileSystem::Instance().Exists(pdb_file)) { | |||
| 118 | const auto exe_dir = FileSpec(exe_path).CopyByRemovingLastPathComponent(); | |||
| 119 | const auto pdb_name = FileSpec(pdb_file).GetFilename().GetCString(); | |||
| 120 | pdb_file = exe_dir.CopyByAppendingPathComponent(pdb_name).GetCString(); | |||
| 121 | } | |||
| 122 | ||||
| 123 | // If the file is not a PDB or if it doesn't have a matching GUID, fail. | |||
| 124 | auto pdb = ObjectFilePDB::loadPDBFile(std::string(pdb_file), allocator); | |||
| 125 | if (!pdb) | |||
| 126 | return nullptr; | |||
| 127 | ||||
| 128 | auto expected_info = pdb->getPDBInfoStream(); | |||
| 129 | if (!expected_info) { | |||
| 130 | llvm::consumeError(expected_info.takeError()); | |||
| 131 | return nullptr; | |||
| 132 | } | |||
| 133 | llvm::codeview::GUID guid; | |||
| 134 | memcpy(&guid, pdb_info->PDB70.Signature, 16); | |||
| 135 | ||||
| 136 | if (expected_info->getGuid() != guid) | |||
| 137 | return nullptr; | |||
| 138 | return pdb; | |||
| 139 | } | |||
| 140 | ||||
| 141 | static bool IsFunctionPrologue(const CompilandIndexItem &cci, | |||
| 142 | lldb::addr_t addr) { | |||
| 143 | // FIXME: Implement this. | |||
| 144 | return false; | |||
| 145 | } | |||
| 146 | ||||
| 147 | static bool IsFunctionEpilogue(const CompilandIndexItem &cci, | |||
| 148 | lldb::addr_t addr) { | |||
| 149 | // FIXME: Implement this. | |||
| 150 | return false; | |||
| 151 | } | |||
| 152 | ||||
| 153 | static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) { | |||
| 154 | switch (kind) { | |||
| 155 | case SimpleTypeKind::Boolean128: | |||
| 156 | case SimpleTypeKind::Boolean16: | |||
| 157 | case SimpleTypeKind::Boolean32: | |||
| 158 | case SimpleTypeKind::Boolean64: | |||
| 159 | case SimpleTypeKind::Boolean8: | |||
| 160 | return "bool"; | |||
| 161 | case SimpleTypeKind::Byte: | |||
| 162 | case SimpleTypeKind::UnsignedCharacter: | |||
| 163 | return "unsigned char"; | |||
| 164 | case SimpleTypeKind::NarrowCharacter: | |||
| 165 | return "char"; | |||
| 166 | case SimpleTypeKind::SignedCharacter: | |||
| 167 | case SimpleTypeKind::SByte: | |||
| 168 | return "signed char"; | |||
| 169 | case SimpleTypeKind::Character16: | |||
| 170 | return "char16_t"; | |||
| 171 | case SimpleTypeKind::Character32: | |||
| 172 | return "char32_t"; | |||
| 173 | case SimpleTypeKind::Complex80: | |||
| 174 | case SimpleTypeKind::Complex64: | |||
| 175 | case SimpleTypeKind::Complex32: | |||
| 176 | return "complex"; | |||
| 177 | case SimpleTypeKind::Float128: | |||
| 178 | case SimpleTypeKind::Float80: | |||
| 179 | return "long double"; | |||
| 180 | case SimpleTypeKind::Float64: | |||
| 181 | return "double"; | |||
| 182 | case SimpleTypeKind::Float32: | |||
| 183 | return "float"; | |||
| 184 | case SimpleTypeKind::Float16: | |||
| 185 | return "single"; | |||
| 186 | case SimpleTypeKind::Int128: | |||
| 187 | return "__int128"; | |||
| 188 | case SimpleTypeKind::Int64: | |||
| 189 | case SimpleTypeKind::Int64Quad: | |||
| 190 | return "int64_t"; | |||
| 191 | case SimpleTypeKind::Int32: | |||
| 192 | return "int"; | |||
| 193 | case SimpleTypeKind::Int16: | |||
| 194 | return "short"; | |||
| 195 | case SimpleTypeKind::UInt128: | |||
| 196 | return "unsigned __int128"; | |||
| 197 | case SimpleTypeKind::UInt64: | |||
| 198 | case SimpleTypeKind::UInt64Quad: | |||
| 199 | return "uint64_t"; | |||
| 200 | case SimpleTypeKind::HResult: | |||
| 201 | return "HRESULT"; | |||
| 202 | case SimpleTypeKind::UInt32: | |||
| 203 | return "unsigned"; | |||
| 204 | case SimpleTypeKind::UInt16: | |||
| 205 | case SimpleTypeKind::UInt16Short: | |||
| 206 | return "unsigned short"; | |||
| 207 | case SimpleTypeKind::Int32Long: | |||
| 208 | return "long"; | |||
| 209 | case SimpleTypeKind::UInt32Long: | |||
| 210 | return "unsigned long"; | |||
| 211 | case SimpleTypeKind::Void: | |||
| 212 | return "void"; | |||
| 213 | case SimpleTypeKind::WideCharacter: | |||
| 214 | return "wchar_t"; | |||
| 215 | default: | |||
| 216 | return ""; | |||
| 217 | } | |||
| 218 | } | |||
| 219 | ||||
| 220 | static bool IsClassRecord(TypeLeafKind kind) { | |||
| 221 | switch (kind) { | |||
| 222 | case LF_STRUCTURE: | |||
| 223 | case LF_CLASS: | |||
| 224 | case LF_INTERFACE: | |||
| 225 | return true; | |||
| 226 | default: | |||
| 227 | return false; | |||
| 228 | } | |||
| 229 | } | |||
| 230 | ||||
| 231 | void SymbolFileNativePDB::Initialize() { | |||
| 232 | PluginManager::RegisterPlugin(GetPluginNameStatic(), | |||
| 233 | GetPluginDescriptionStatic(), CreateInstance, | |||
| 234 | DebuggerInitialize); | |||
| 235 | } | |||
| 236 | ||||
| 237 | void SymbolFileNativePDB::Terminate() { | |||
| 238 | PluginManager::UnregisterPlugin(CreateInstance); | |||
| 239 | } | |||
| 240 | ||||
| 241 | void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {} | |||
| 242 | ||||
| 243 | ConstString SymbolFileNativePDB::GetPluginNameStatic() { | |||
| 244 | static ConstString g_name("native-pdb"); | |||
| 245 | return g_name; | |||
| 246 | } | |||
| 247 | ||||
| 248 | const char *SymbolFileNativePDB::GetPluginDescriptionStatic() { | |||
| 249 | return "Microsoft PDB debug symbol cross-platform file reader."; | |||
| 250 | } | |||
| 251 | ||||
| 252 | SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) { | |||
| 253 | return new SymbolFileNativePDB(std::move(objfile_sp)); | |||
| 254 | } | |||
| 255 | ||||
| 256 | SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp) | |||
| 257 | : SymbolFile(std::move(objfile_sp)) {} | |||
| 258 | ||||
| 259 | SymbolFileNativePDB::~SymbolFileNativePDB() = default; | |||
| 260 | ||||
| 261 | uint32_t SymbolFileNativePDB::CalculateAbilities() { | |||
| 262 | uint32_t abilities = 0; | |||
| 263 | if (!m_objfile_sp) | |||
| 264 | return 0; | |||
| 265 | ||||
| 266 | if (!m_index) { | |||
| 267 | // Lazily load and match the PDB file, but only do this once. | |||
| 268 | PDBFile *pdb_file; | |||
| 269 | if (auto *pdb = llvm::dyn_cast<ObjectFilePDB>(m_objfile_sp.get())) { | |||
| 270 | pdb_file = &pdb->GetPDBFile(); | |||
| 271 | } else { | |||
| 272 | m_file_up = loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(), | |||
| 273 | m_allocator); | |||
| 274 | pdb_file = m_file_up.get(); | |||
| 275 | } | |||
| 276 | ||||
| 277 | if (!pdb_file) | |||
| 278 | return 0; | |||
| 279 | ||||
| 280 | auto expected_index = PdbIndex::create(pdb_file); | |||
| 281 | if (!expected_index) { | |||
| 282 | llvm::consumeError(expected_index.takeError()); | |||
| 283 | return 0; | |||
| 284 | } | |||
| 285 | m_index = std::move(*expected_index); | |||
| 286 | } | |||
| 287 | if (!m_index) | |||
| 288 | return 0; | |||
| 289 | ||||
| 290 | // We don't especially have to be precise here. We only distinguish between | |||
| 291 | // stripped and not stripped. | |||
| 292 | abilities = kAllAbilities; | |||
| 293 | ||||
| 294 | if (m_index->dbi().isStripped()) | |||
| 295 | abilities &= ~(Blocks | LocalVariables); | |||
| 296 | return abilities; | |||
| 297 | } | |||
| 298 | ||||
| 299 | void SymbolFileNativePDB::InitializeObject() { | |||
| 300 | m_obj_load_address = m_objfile_sp->GetModule() | |||
| 301 | ->GetObjectFile() | |||
| 302 | ->GetBaseAddress() | |||
| 303 | .GetFileAddress(); | |||
| 304 | m_index->SetLoadAddress(m_obj_load_address); | |||
| 305 | m_index->ParseSectionContribs(); | |||
| 306 | ||||
| 307 | auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage( | |||
| 308 | lldb::eLanguageTypeC_plus_plus); | |||
| 309 | if (auto err = ts_or_err.takeError()) { | |||
| ||||
| 310 | LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),do { ::lldb_private::Log *log_private = (lldb_private::GetLogIfAnyCategoriesSet ((1u << 20))); ::llvm::Error error_private = (std::move (err)); if (log_private && error_private) { log_private ->FormatError(::std::move(error_private), "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , __func__, "Failed to initialize"); } else ::llvm::consumeError (::std::move(error_private)); } while (0) | |||
| 311 | std::move(err), "Failed to initialize")do { ::lldb_private::Log *log_private = (lldb_private::GetLogIfAnyCategoriesSet ((1u << 20))); ::llvm::Error error_private = (std::move (err)); if (log_private && error_private) { log_private ->FormatError(::std::move(error_private), "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , __func__, "Failed to initialize"); } else ::llvm::consumeError (::std::move(error_private)); } while (0); | |||
| 312 | } else { | |||
| 313 | ts_or_err->SetSymbolFile(this); | |||
| 314 | auto *clang = llvm::cast_or_null<TypeSystemClang>(&ts_or_err.get()); | |||
| 315 | lldbassert(clang)lldb_private::lldb_assert(static_cast<bool>(clang), "clang" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 315); | |||
| 316 | m_ast = std::make_unique<PdbAstBuilder>(*m_objfile_sp, *m_index, *clang); | |||
| ||||
| 317 | } | |||
| 318 | } | |||
| 319 | ||||
| 320 | uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() { | |||
| 321 | const DbiModuleList &modules = m_index->dbi().modules(); | |||
| 322 | uint32_t count = modules.getModuleCount(); | |||
| 323 | if (count == 0) | |||
| 324 | return count; | |||
| 325 | ||||
| 326 | // The linker can inject an additional "dummy" compilation unit into the | |||
| 327 | // PDB. Ignore this special compile unit for our purposes, if it is there. | |||
| 328 | // It is always the last one. | |||
| 329 | DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1); | |||
| 330 | if (last.getModuleName() == "* Linker *") | |||
| 331 | --count; | |||
| 332 | return count; | |||
| 333 | } | |||
| 334 | ||||
| 335 | Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) { | |||
| 336 | CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi); | |||
| 337 | CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset); | |||
| 338 | ||||
| 339 | if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) { | |||
| 340 | // This is a function. It must be global. Creating the Function entry for | |||
| 341 | // it automatically creates a block for it. | |||
| 342 | CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii); | |||
| 343 | return GetOrCreateFunction(block_id, *comp_unit)->GetBlock(false); | |||
| 344 | } | |||
| 345 | ||||
| 346 | lldbassert(sym.kind() == S_BLOCK32)lldb_private::lldb_assert(static_cast<bool>(sym.kind() == S_BLOCK32), "sym.kind() == S_BLOCK32", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 346); | |||
| 347 | ||||
| 348 | // This is a block. Its parent is either a function or another block. In | |||
| 349 | // either case, its parent can be viewed as a block (e.g. a function contains | |||
| 350 | // 1 big block. So just get the parent block and add this block to it. | |||
| 351 | BlockSym block(static_cast<SymbolRecordKind>(sym.kind())); | |||
| 352 | cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block)); | |||
| 353 | lldbassert(block.Parent != 0)lldb_private::lldb_assert(static_cast<bool>(block.Parent != 0), "block.Parent != 0", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 353); | |||
| 354 | PdbCompilandSymId parent_id(block_id.modi, block.Parent); | |||
| 355 | Block &parent_block = GetOrCreateBlock(parent_id); | |||
| 356 | lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id); | |||
| 357 | BlockSP child_block = std::make_shared<Block>(opaque_block_uid); | |||
| 358 | parent_block.AddChild(child_block); | |||
| 359 | ||||
| 360 | m_ast->GetOrCreateBlockDecl(block_id); | |||
| 361 | ||||
| 362 | m_blocks.insert({opaque_block_uid, child_block}); | |||
| 363 | return *child_block; | |||
| 364 | } | |||
| 365 | ||||
| 366 | lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id, | |||
| 367 | CompileUnit &comp_unit) { | |||
| 368 | const CompilandIndexItem *cci = | |||
| 369 | m_index->compilands().GetCompiland(func_id.modi); | |||
| 370 | lldbassert(cci)lldb_private::lldb_assert(static_cast<bool>(cci), "cci" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 370); | |||
| 371 | CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset); | |||
| 372 | ||||
| 373 | lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32)lldb_private::lldb_assert(static_cast<bool>(sym_record. kind() == S_LPROC32 || sym_record.kind() == S_GPROC32), "sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 373); | |||
| 374 | SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record); | |||
| 375 | ||||
| 376 | auto file_vm_addr = m_index->MakeVirtualAddress(sol.so); | |||
| 377 | if (file_vm_addr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL || file_vm_addr == 0) | |||
| 378 | return nullptr; | |||
| 379 | ||||
| 380 | AddressRange func_range(file_vm_addr, sol.length, | |||
| 381 | comp_unit.GetModule()->GetSectionList()); | |||
| 382 | if (!func_range.GetBaseAddress().IsValid()) | |||
| 383 | return nullptr; | |||
| 384 | ||||
| 385 | ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind())); | |||
| 386 | cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc)); | |||
| 387 | if (proc.FunctionType == TypeIndex::None()) | |||
| 388 | return nullptr; | |||
| 389 | TypeSP func_type = GetOrCreateType(proc.FunctionType); | |||
| 390 | if (!func_type) | |||
| 391 | return nullptr; | |||
| 392 | ||||
| 393 | PdbTypeSymId sig_id(proc.FunctionType, false); | |||
| 394 | Mangled mangled(proc.Name); | |||
| 395 | FunctionSP func_sp = std::make_shared<Function>( | |||
| 396 | &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled, | |||
| 397 | func_type.get(), func_range); | |||
| 398 | ||||
| 399 | comp_unit.AddFunction(func_sp); | |||
| 400 | ||||
| 401 | m_ast->GetOrCreateFunctionDecl(func_id); | |||
| 402 | ||||
| 403 | return func_sp; | |||
| 404 | } | |||
| 405 | ||||
| 406 | CompUnitSP | |||
| 407 | SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) { | |||
| 408 | lldb::LanguageType lang = | |||
| 409 | cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage()) | |||
| 410 | : lldb::eLanguageTypeUnknown; | |||
| 411 | ||||
| 412 | LazyBool optimized = eLazyBoolNo; | |||
| 413 | if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations()) | |||
| 414 | optimized = eLazyBoolYes; | |||
| 415 | ||||
| 416 | llvm::SmallString<64> source_file_name = | |||
| 417 | m_index->compilands().GetMainSourceFile(cci); | |||
| 418 | FileSpec fs(source_file_name); | |||
| 419 | ||||
| 420 | CompUnitSP cu_sp = | |||
| 421 | std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs, | |||
| 422 | toOpaqueUid(cci.m_id), lang, optimized); | |||
| 423 | ||||
| 424 | SetCompileUnitAtIndex(cci.m_id.modi, cu_sp); | |||
| 425 | return cu_sp; | |||
| 426 | } | |||
| 427 | ||||
| 428 | lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id, | |||
| 429 | const ModifierRecord &mr, | |||
| 430 | CompilerType ct) { | |||
| 431 | TpiStream &stream = m_index->tpi(); | |||
| 432 | ||||
| 433 | std::string name; | |||
| 434 | if (mr.ModifiedType.isSimple()) | |||
| 435 | name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind())); | |||
| 436 | else | |||
| 437 | name = computeTypeName(stream.typeCollection(), mr.ModifiedType); | |||
| 438 | Declaration decl; | |||
| 439 | lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType); | |||
| 440 | ||||
| 441 | return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(name), | |||
| 442 | modified_type->GetByteSize(nullptr), nullptr, | |||
| 443 | LLDB_INVALID_UID0xffffffffffffffffULL, Type::eEncodingIsUID, decl, | |||
| 444 | ct, Type::ResolveState::Full); | |||
| 445 | } | |||
| 446 | ||||
| 447 | lldb::TypeSP | |||
| 448 | SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id, | |||
| 449 | const llvm::codeview::PointerRecord &pr, | |||
| 450 | CompilerType ct) { | |||
| 451 | TypeSP pointee = GetOrCreateType(pr.ReferentType); | |||
| 452 | if (!pointee) | |||
| 453 | return nullptr; | |||
| 454 | ||||
| 455 | if (pr.isPointerToMember()) { | |||
| 456 | MemberPointerInfo mpi = pr.getMemberInfo(); | |||
| 457 | GetOrCreateType(mpi.ContainingType); | |||
| 458 | } | |||
| 459 | ||||
| 460 | Declaration decl; | |||
| 461 | return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(), | |||
| 462 | pr.getSize(), nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 463 | Type::eEncodingIsUID, decl, ct, | |||
| 464 | Type::ResolveState::Full); | |||
| 465 | } | |||
| 466 | ||||
| 467 | lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti, | |||
| 468 | CompilerType ct) { | |||
| 469 | uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false)); | |||
| 470 | if (ti == TypeIndex::NullptrT()) { | |||
| 471 | Declaration decl; | |||
| 472 | return std::make_shared<Type>( | |||
| 473 | uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 474 | Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full); | |||
| 475 | } | |||
| 476 | ||||
| 477 | if (ti.getSimpleMode() != SimpleTypeMode::Direct) { | |||
| 478 | TypeSP direct_sp = GetOrCreateType(ti.makeDirect()); | |||
| 479 | uint32_t pointer_size = 0; | |||
| 480 | switch (ti.getSimpleMode()) { | |||
| 481 | case SimpleTypeMode::FarPointer32: | |||
| 482 | case SimpleTypeMode::NearPointer32: | |||
| 483 | pointer_size = 4; | |||
| 484 | break; | |||
| 485 | case SimpleTypeMode::NearPointer64: | |||
| 486 | pointer_size = 8; | |||
| 487 | break; | |||
| 488 | default: | |||
| 489 | // 128-bit and 16-bit pointers unsupported. | |||
| 490 | return nullptr; | |||
| 491 | } | |||
| 492 | Declaration decl; | |||
| 493 | return std::make_shared<Type>( | |||
| 494 | uid, this, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 495 | Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full); | |||
| 496 | } | |||
| 497 | ||||
| 498 | if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) | |||
| 499 | return nullptr; | |||
| 500 | ||||
| 501 | size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind()); | |||
| 502 | llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind()); | |||
| 503 | ||||
| 504 | Declaration decl; | |||
| 505 | return std::make_shared<Type>(uid, this, ConstString(type_name), size, | |||
| 506 | nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, Type::eEncodingIsUID, | |||
| 507 | decl, ct, Type::ResolveState::Full); | |||
| 508 | } | |||
| 509 | ||||
| 510 | static std::string GetUnqualifiedTypeName(const TagRecord &record) { | |||
| 511 | if (!record.hasUniqueName()) { | |||
| 512 | MSVCUndecoratedNameParser parser(record.Name); | |||
| 513 | llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); | |||
| 514 | ||||
| 515 | return std::string(specs.back().GetBaseName()); | |||
| 516 | } | |||
| 517 | ||||
| 518 | llvm::ms_demangle::Demangler demangler; | |||
| 519 | StringView sv(record.UniqueName.begin(), record.UniqueName.size()); | |||
| 520 | llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv); | |||
| 521 | if (demangler.Error) | |||
| 522 | return std::string(record.Name); | |||
| 523 | ||||
| 524 | llvm::ms_demangle::IdentifierNode *idn = | |||
| 525 | ttn->QualifiedName->getUnqualifiedIdentifier(); | |||
| 526 | return idn->toString(); | |||
| 527 | } | |||
| 528 | ||||
| 529 | lldb::TypeSP | |||
| 530 | SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id, | |||
| 531 | const TagRecord &record, | |||
| 532 | size_t size, CompilerType ct) { | |||
| 533 | ||||
| 534 | std::string uname = GetUnqualifiedTypeName(record); | |||
| 535 | ||||
| 536 | // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE. | |||
| 537 | Declaration decl; | |||
| 538 | return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(uname), | |||
| 539 | size, nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 540 | Type::eEncodingIsUID, decl, ct, | |||
| 541 | Type::ResolveState::Forward); | |||
| 542 | } | |||
| 543 | ||||
| 544 | lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, | |||
| 545 | const ClassRecord &cr, | |||
| 546 | CompilerType ct) { | |||
| 547 | return CreateClassStructUnion(type_id, cr, cr.getSize(), ct); | |||
| 548 | } | |||
| 549 | ||||
| 550 | lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, | |||
| 551 | const UnionRecord &ur, | |||
| 552 | CompilerType ct) { | |||
| 553 | return CreateClassStructUnion(type_id, ur, ur.getSize(), ct); | |||
| 554 | } | |||
| 555 | ||||
| 556 | lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id, | |||
| 557 | const EnumRecord &er, | |||
| 558 | CompilerType ct) { | |||
| 559 | std::string uname = GetUnqualifiedTypeName(er); | |||
| 560 | ||||
| 561 | Declaration decl; | |||
| 562 | TypeSP underlying_type = GetOrCreateType(er.UnderlyingType); | |||
| 563 | ||||
| 564 | return std::make_shared<lldb_private::Type>( | |||
| 565 | toOpaqueUid(type_id), this, ConstString(uname), | |||
| 566 | underlying_type->GetByteSize(nullptr), nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 567 | lldb_private::Type::eEncodingIsUID, decl, ct, | |||
| 568 | lldb_private::Type::ResolveState::Forward); | |||
| 569 | } | |||
| 570 | ||||
| 571 | TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id, | |||
| 572 | const ArrayRecord &ar, | |||
| 573 | CompilerType ct) { | |||
| 574 | TypeSP element_type = GetOrCreateType(ar.ElementType); | |||
| 575 | ||||
| 576 | Declaration decl; | |||
| 577 | TypeSP array_sp = std::make_shared<lldb_private::Type>( | |||
| 578 | toOpaqueUid(type_id), this, ConstString(), ar.Size, nullptr, | |||
| 579 | LLDB_INVALID_UID0xffffffffffffffffULL, lldb_private::Type::eEncodingIsUID, decl, ct, | |||
| 580 | lldb_private::Type::ResolveState::Full); | |||
| 581 | array_sp->SetEncodingType(element_type.get()); | |||
| 582 | return array_sp; | |||
| 583 | } | |||
| 584 | ||||
| 585 | ||||
| 586 | TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id, | |||
| 587 | const MemberFunctionRecord &mfr, | |||
| 588 | CompilerType ct) { | |||
| 589 | Declaration decl; | |||
| 590 | return std::make_shared<lldb_private::Type>( | |||
| 591 | toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 592 | lldb_private::Type::eEncodingIsUID, decl, ct, | |||
| 593 | lldb_private::Type::ResolveState::Full); | |||
| 594 | } | |||
| 595 | ||||
| 596 | TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id, | |||
| 597 | const ProcedureRecord &pr, | |||
| 598 | CompilerType ct) { | |||
| 599 | Declaration decl; | |||
| 600 | return std::make_shared<lldb_private::Type>( | |||
| 601 | toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID0xffffffffffffffffULL, | |||
| 602 | lldb_private::Type::eEncodingIsUID, decl, ct, | |||
| 603 | lldb_private::Type::ResolveState::Full); | |||
| 604 | } | |||
| 605 | ||||
| 606 | TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) { | |||
| 607 | if (type_id.index.isSimple()) | |||
| 608 | return CreateSimpleType(type_id.index, ct); | |||
| 609 | ||||
| 610 | TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi(); | |||
| 611 | CVType cvt = stream.getType(type_id.index); | |||
| 612 | ||||
| 613 | if (cvt.kind() == LF_MODIFIER) { | |||
| 614 | ModifierRecord modifier; | |||
| 615 | llvm::cantFail( | |||
| 616 | TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); | |||
| 617 | return CreateModifierType(type_id, modifier, ct); | |||
| 618 | } | |||
| 619 | ||||
| 620 | if (cvt.kind() == LF_POINTER) { | |||
| 621 | PointerRecord pointer; | |||
| 622 | llvm::cantFail( | |||
| 623 | TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); | |||
| 624 | return CreatePointerType(type_id, pointer, ct); | |||
| 625 | } | |||
| 626 | ||||
| 627 | if (IsClassRecord(cvt.kind())) { | |||
| 628 | ClassRecord cr; | |||
| 629 | llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr)); | |||
| 630 | return CreateTagType(type_id, cr, ct); | |||
| 631 | } | |||
| 632 | ||||
| 633 | if (cvt.kind() == LF_ENUM) { | |||
| 634 | EnumRecord er; | |||
| 635 | llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er)); | |||
| 636 | return CreateTagType(type_id, er, ct); | |||
| 637 | } | |||
| 638 | ||||
| 639 | if (cvt.kind() == LF_UNION) { | |||
| 640 | UnionRecord ur; | |||
| 641 | llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur)); | |||
| 642 | return CreateTagType(type_id, ur, ct); | |||
| 643 | } | |||
| 644 | ||||
| 645 | if (cvt.kind() == LF_ARRAY) { | |||
| 646 | ArrayRecord ar; | |||
| 647 | llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); | |||
| 648 | return CreateArrayType(type_id, ar, ct); | |||
| 649 | } | |||
| 650 | ||||
| 651 | if (cvt.kind() == LF_PROCEDURE) { | |||
| 652 | ProcedureRecord pr; | |||
| 653 | llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); | |||
| 654 | return CreateProcedureType(type_id, pr, ct); | |||
| 655 | } | |||
| 656 | if (cvt.kind() == LF_MFUNCTION) { | |||
| 657 | MemberFunctionRecord mfr; | |||
| 658 | llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); | |||
| 659 | return CreateFunctionType(type_id, mfr, ct); | |||
| 660 | } | |||
| 661 | ||||
| 662 | return nullptr; | |||
| 663 | } | |||
| 664 | ||||
| 665 | TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) { | |||
| 666 | // If they search for a UDT which is a forward ref, try and resolve the full | |||
| 667 | // decl and just map the forward ref uid to the full decl record. | |||
| 668 | llvm::Optional<PdbTypeSymId> full_decl_uid; | |||
| 669 | if (IsForwardRefUdt(type_id, m_index->tpi())) { | |||
| 670 | auto expected_full_ti = | |||
| 671 | m_index->tpi().findFullDeclForForwardRef(type_id.index); | |||
| 672 | if (!expected_full_ti) | |||
| 673 | llvm::consumeError(expected_full_ti.takeError()); | |||
| 674 | else if (*expected_full_ti != type_id.index) { | |||
| 675 | full_decl_uid = PdbTypeSymId(*expected_full_ti, false); | |||
| 676 | ||||
| 677 | // It's possible that a lookup would occur for the full decl causing it | |||
| 678 | // to be cached, then a second lookup would occur for the forward decl. | |||
| 679 | // We don't want to create a second full decl, so make sure the full | |||
| 680 | // decl hasn't already been cached. | |||
| 681 | auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid)); | |||
| 682 | if (full_iter != m_types.end()) { | |||
| 683 | TypeSP result = full_iter->second; | |||
| 684 | // Map the forward decl to the TypeSP for the full decl so we can take | |||
| 685 | // the fast path next time. | |||
| 686 | m_types[toOpaqueUid(type_id)] = result; | |||
| 687 | return result; | |||
| 688 | } | |||
| 689 | } | |||
| 690 | } | |||
| 691 | ||||
| 692 | PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id; | |||
| 693 | ||||
| 694 | clang::QualType qt = m_ast->GetOrCreateType(best_decl_id); | |||
| 695 | ||||
| 696 | TypeSP result = CreateType(best_decl_id, m_ast->ToCompilerType(qt)); | |||
| 697 | if (!result) | |||
| 698 | return nullptr; | |||
| 699 | ||||
| 700 | uint64_t best_uid = toOpaqueUid(best_decl_id); | |||
| 701 | m_types[best_uid] = result; | |||
| 702 | // If we had both a forward decl and a full decl, make both point to the new | |||
| 703 | // type. | |||
| 704 | if (full_decl_uid) | |||
| 705 | m_types[toOpaqueUid(type_id)] = result; | |||
| 706 | ||||
| 707 | return result; | |||
| 708 | } | |||
| 709 | ||||
| 710 | TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) { | |||
| 711 | // We can't use try_emplace / overwrite here because the process of creating | |||
| 712 | // a type could create nested types, which could invalidate iterators. So | |||
| 713 | // we have to do a 2-phase lookup / insert. | |||
| 714 | auto iter = m_types.find(toOpaqueUid(type_id)); | |||
| 715 | if (iter != m_types.end()) | |||
| 716 | return iter->second; | |||
| 717 | ||||
| 718 | TypeSP type = CreateAndCacheType(type_id); | |||
| 719 | if (type) | |||
| 720 | GetTypeList().Insert(type); | |||
| 721 | return type; | |||
| 722 | } | |||
| 723 | ||||
| 724 | VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) { | |||
| 725 | CVSymbol sym = m_index->symrecords().readRecord(var_id.offset); | |||
| 726 | if (sym.kind() == S_CONSTANT) | |||
| 727 | return CreateConstantSymbol(var_id, sym); | |||
| 728 | ||||
| 729 | lldb::ValueType scope = eValueTypeInvalid; | |||
| 730 | TypeIndex ti; | |||
| 731 | llvm::StringRef name; | |||
| 732 | lldb::addr_t addr = 0; | |||
| 733 | uint16_t section = 0; | |||
| 734 | uint32_t offset = 0; | |||
| 735 | bool is_external = false; | |||
| 736 | switch (sym.kind()) { | |||
| 737 | case S_GDATA32: | |||
| 738 | is_external = true; | |||
| 739 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 740 | case S_LDATA32: { | |||
| 741 | DataSym ds(sym.kind()); | |||
| 742 | llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds)); | |||
| 743 | ti = ds.Type; | |||
| 744 | scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal | |||
| 745 | : eValueTypeVariableStatic; | |||
| 746 | name = ds.Name; | |||
| 747 | section = ds.Segment; | |||
| 748 | offset = ds.DataOffset; | |||
| 749 | addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset); | |||
| 750 | break; | |||
| 751 | } | |||
| 752 | case S_GTHREAD32: | |||
| 753 | is_external = true; | |||
| 754 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
| 755 | case S_LTHREAD32: { | |||
| 756 | ThreadLocalDataSym tlds(sym.kind()); | |||
| 757 | llvm::cantFail( | |||
| 758 | SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds)); | |||
| 759 | ti = tlds.Type; | |||
| 760 | name = tlds.Name; | |||
| 761 | section = tlds.Segment; | |||
| 762 | offset = tlds.DataOffset; | |||
| 763 | addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset); | |||
| 764 | scope = eValueTypeVariableThreadLocal; | |||
| 765 | break; | |||
| 766 | } | |||
| 767 | default: | |||
| 768 | llvm_unreachable("unreachable!")__builtin_unreachable(); | |||
| 769 | } | |||
| 770 | ||||
| 771 | CompUnitSP comp_unit; | |||
| 772 | llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr); | |||
| 773 | if (modi) { | |||
| 774 | CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi); | |||
| 775 | comp_unit = GetOrCreateCompileUnit(cci); | |||
| 776 | } | |||
| 777 | ||||
| 778 | Declaration decl; | |||
| 779 | PdbTypeSymId tid(ti, false); | |||
| 780 | SymbolFileTypeSP type_sp = | |||
| 781 | std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); | |||
| 782 | Variable::RangeList ranges; | |||
| 783 | ||||
| 784 | m_ast->GetOrCreateVariableDecl(var_id); | |||
| 785 | ||||
| 786 | DWARFExpression location = MakeGlobalLocationExpression( | |||
| 787 | section, offset, GetObjectFile()->GetModule()); | |||
| 788 | ||||
| 789 | std::string global_name("::"); | |||
| 790 | global_name += name; | |||
| 791 | bool artificial = false; | |||
| 792 | bool location_is_constant_data = false; | |||
| 793 | bool static_member = false; | |||
| 794 | VariableSP var_sp = std::make_shared<Variable>( | |||
| 795 | toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp, | |||
| 796 | scope, comp_unit.get(), ranges, &decl, location, is_external, artificial, | |||
| 797 | location_is_constant_data, static_member); | |||
| 798 | ||||
| 799 | return var_sp; | |||
| 800 | } | |||
| 801 | ||||
| 802 | lldb::VariableSP | |||
| 803 | SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id, | |||
| 804 | const CVSymbol &cvs) { | |||
| 805 | TpiStream &tpi = m_index->tpi(); | |||
| 806 | ConstantSym constant(cvs.kind()); | |||
| 807 | ||||
| 808 | llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant)); | |||
| 809 | std::string global_name("::"); | |||
| 810 | global_name += constant.Name; | |||
| 811 | PdbTypeSymId tid(constant.Type, false); | |||
| 812 | SymbolFileTypeSP type_sp = | |||
| 813 | std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid)); | |||
| 814 | ||||
| 815 | Declaration decl; | |||
| 816 | Variable::RangeList ranges; | |||
| 817 | ModuleSP module = GetObjectFile()->GetModule(); | |||
| 818 | DWARFExpression location = MakeConstantLocationExpression( | |||
| 819 | constant.Type, tpi, constant.Value, module); | |||
| 820 | ||||
| 821 | bool external = false; | |||
| 822 | bool artificial = false; | |||
| 823 | bool location_is_constant_data = true; | |||
| 824 | bool static_member = false; | |||
| 825 | VariableSP var_sp = std::make_shared<Variable>( | |||
| 826 | toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(), | |||
| 827 | type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location, | |||
| 828 | external, artificial, location_is_constant_data, static_member); | |||
| 829 | return var_sp; | |||
| 830 | } | |||
| 831 | ||||
| 832 | VariableSP | |||
| 833 | SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) { | |||
| 834 | auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr); | |||
| 835 | if (emplace_result.second) | |||
| 836 | emplace_result.first->second = CreateGlobalVariable(var_id); | |||
| 837 | ||||
| 838 | return emplace_result.first->second; | |||
| 839 | } | |||
| 840 | ||||
| 841 | lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) { | |||
| 842 | return GetOrCreateType(PdbTypeSymId(ti, false)); | |||
| 843 | } | |||
| 844 | ||||
| 845 | FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id, | |||
| 846 | CompileUnit &comp_unit) { | |||
| 847 | auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr); | |||
| 848 | if (emplace_result.second) | |||
| 849 | emplace_result.first->second = CreateFunction(func_id, comp_unit); | |||
| 850 | ||||
| 851 | return emplace_result.first->second; | |||
| 852 | } | |||
| 853 | ||||
| 854 | CompUnitSP | |||
| 855 | SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) { | |||
| 856 | ||||
| 857 | auto emplace_result = | |||
| 858 | m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr); | |||
| 859 | if (emplace_result.second) | |||
| 860 | emplace_result.first->second = CreateCompileUnit(cci); | |||
| 861 | ||||
| 862 | lldbassert(emplace_result.first->second)lldb_private::lldb_assert(static_cast<bool>(emplace_result .first->second), "emplace_result.first->second", __FUNCTION__ , "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 862); | |||
| 863 | return emplace_result.first->second; | |||
| 864 | } | |||
| 865 | ||||
| 866 | Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) { | |||
| 867 | auto iter = m_blocks.find(toOpaqueUid(block_id)); | |||
| 868 | if (iter != m_blocks.end()) | |||
| 869 | return *iter->second; | |||
| 870 | ||||
| 871 | return CreateBlock(block_id); | |||
| 872 | } | |||
| 873 | ||||
| 874 | void SymbolFileNativePDB::ParseDeclsForContext( | |||
| 875 | lldb_private::CompilerDeclContext decl_ctx) { | |||
| 876 | clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx); | |||
| 877 | if (!context) | |||
| 878 | return; | |||
| 879 | m_ast->ParseDeclsForContext(*context); | |||
| 880 | } | |||
| 881 | ||||
| 882 | lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) { | |||
| 883 | if (index >= GetNumCompileUnits()) | |||
| 884 | return CompUnitSP(); | |||
| 885 | lldbassert(index < UINT16_MAX)lldb_private::lldb_assert(static_cast<bool>(index < 0xffff ), "index < UINT16_MAX", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 885); | |||
| 886 | if (index >= UINT16_MAX0xffff) | |||
| 887 | return nullptr; | |||
| 888 | ||||
| 889 | CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index); | |||
| 890 | ||||
| 891 | return GetOrCreateCompileUnit(item); | |||
| 892 | } | |||
| 893 | ||||
| 894 | lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) { | |||
| 895 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 896 | PdbSymUid uid(comp_unit.GetID()); | |||
| 897 | lldbassert(uid.kind() == PdbSymUidKind::Compiland)lldb_private::lldb_assert(static_cast<bool>(uid.kind() == PdbSymUidKind::Compiland), "uid.kind() == PdbSymUidKind::Compiland" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 897); | |||
| 898 | ||||
| 899 | CompilandIndexItem *item = | |||
| 900 | m_index->compilands().GetCompiland(uid.asCompiland().modi); | |||
| 901 | lldbassert(item)lldb_private::lldb_assert(static_cast<bool>(item), "item" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 901); | |||
| 902 | if (!item->m_compile_opts) | |||
| 903 | return lldb::eLanguageTypeUnknown; | |||
| 904 | ||||
| 905 | return TranslateLanguage(item->m_compile_opts->getLanguage()); | |||
| 906 | } | |||
| 907 | ||||
| 908 | void SymbolFileNativePDB::AddSymbols(Symtab &symtab) { return; } | |||
| 909 | ||||
| 910 | size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) { | |||
| 911 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 912 | PdbSymUid uid{comp_unit.GetID()}; | |||
| 913 | lldbassert(uid.kind() == PdbSymUidKind::Compiland)lldb_private::lldb_assert(static_cast<bool>(uid.kind() == PdbSymUidKind::Compiland), "uid.kind() == PdbSymUidKind::Compiland" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 913); | |||
| 914 | uint16_t modi = uid.asCompiland().modi; | |||
| 915 | CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi); | |||
| 916 | ||||
| 917 | size_t count = comp_unit.GetNumFunctions(); | |||
| 918 | const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray(); | |||
| 919 | for (auto iter = syms.begin(); iter != syms.end(); ++iter) { | |||
| 920 | if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) | |||
| 921 | continue; | |||
| 922 | ||||
| 923 | PdbCompilandSymId sym_id{modi, iter.offset()}; | |||
| 924 | ||||
| 925 | FunctionSP func = GetOrCreateFunction(sym_id, comp_unit); | |||
| 926 | } | |||
| 927 | ||||
| 928 | size_t new_count = comp_unit.GetNumFunctions(); | |||
| 929 | lldbassert(new_count >= count)lldb_private::lldb_assert(static_cast<bool>(new_count >= count), "new_count >= count", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 929); | |||
| 930 | return new_count - count; | |||
| 931 | } | |||
| 932 | ||||
| 933 | static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) { | |||
| 934 | // If any of these flags are set, we need to resolve the compile unit. | |||
| 935 | uint32_t flags = eSymbolContextCompUnit; | |||
| 936 | flags |= eSymbolContextVariable; | |||
| 937 | flags |= eSymbolContextFunction; | |||
| 938 | flags |= eSymbolContextBlock; | |||
| 939 | flags |= eSymbolContextLineEntry; | |||
| 940 | return (resolve_scope & flags) != 0; | |||
| 941 | } | |||
| 942 | ||||
| 943 | uint32_t SymbolFileNativePDB::ResolveSymbolContext( | |||
| 944 | const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) { | |||
| 945 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 946 | uint32_t resolved_flags = 0; | |||
| 947 | lldb::addr_t file_addr = addr.GetFileAddress(); | |||
| 948 | ||||
| 949 | if (NeedsResolvedCompileUnit(resolve_scope)) { | |||
| 950 | llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr); | |||
| 951 | if (!modi) | |||
| 952 | return 0; | |||
| 953 | CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi); | |||
| 954 | if (!cci) | |||
| 955 | return 0; | |||
| 956 | ||||
| 957 | sc.comp_unit = GetOrCreateCompileUnit(*cci).get(); | |||
| 958 | resolved_flags |= eSymbolContextCompUnit; | |||
| 959 | } | |||
| 960 | ||||
| 961 | if (resolve_scope & eSymbolContextFunction || | |||
| 962 | resolve_scope & eSymbolContextBlock) { | |||
| 963 | lldbassert(sc.comp_unit)lldb_private::lldb_assert(static_cast<bool>(sc.comp_unit ), "sc.comp_unit", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 963); | |||
| 964 | std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr); | |||
| 965 | // Search the matches in reverse. This way if there are multiple matches | |||
| 966 | // (for example we are 3 levels deep in a nested scope) it will find the | |||
| 967 | // innermost one first. | |||
| 968 | for (const auto &match : llvm::reverse(matches)) { | |||
| 969 | if (match.uid.kind() != PdbSymUidKind::CompilandSym) | |||
| 970 | continue; | |||
| 971 | ||||
| 972 | PdbCompilandSymId csid = match.uid.asCompilandSym(); | |||
| 973 | CVSymbol cvs = m_index->ReadSymbolRecord(csid); | |||
| 974 | PDB_SymType type = CVSymToPDBSym(cvs.kind()); | |||
| 975 | if (type != PDB_SymType::Function && type != PDB_SymType::Block) | |||
| 976 | continue; | |||
| 977 | if (type == PDB_SymType::Function) { | |||
| 978 | sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get(); | |||
| 979 | sc.block = sc.GetFunctionBlock(); | |||
| 980 | } | |||
| 981 | ||||
| 982 | if (type == PDB_SymType::Block) { | |||
| 983 | sc.block = &GetOrCreateBlock(csid); | |||
| 984 | sc.function = sc.block->CalculateSymbolContextFunction(); | |||
| 985 | } | |||
| 986 | resolved_flags |= eSymbolContextFunction; | |||
| 987 | resolved_flags |= eSymbolContextBlock; | |||
| 988 | break; | |||
| 989 | } | |||
| 990 | } | |||
| 991 | ||||
| 992 | if (resolve_scope & eSymbolContextLineEntry) { | |||
| 993 | lldbassert(sc.comp_unit)lldb_private::lldb_assert(static_cast<bool>(sc.comp_unit ), "sc.comp_unit", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 993); | |||
| 994 | if (auto *line_table = sc.comp_unit->GetLineTable()) { | |||
| 995 | if (line_table->FindLineEntryByAddress(addr, sc.line_entry)) | |||
| 996 | resolved_flags |= eSymbolContextLineEntry; | |||
| 997 | } | |||
| 998 | } | |||
| 999 | ||||
| 1000 | return resolved_flags; | |||
| 1001 | } | |||
| 1002 | ||||
| 1003 | uint32_t SymbolFileNativePDB::ResolveSymbolContext( | |||
| 1004 | const SourceLocationSpec &src_location_spec, | |||
| 1005 | lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) { | |||
| 1006 | return 0; | |||
| 1007 | } | |||
| 1008 | ||||
| 1009 | static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence, | |||
| 1010 | const CompilandIndexItem &cci, | |||
| 1011 | lldb::addr_t base_addr, | |||
| 1012 | uint32_t file_number, | |||
| 1013 | const LineFragmentHeader &block, | |||
| 1014 | const LineNumberEntry &cur) { | |||
| 1015 | LineInfo cur_info(cur.Flags); | |||
| 1016 | ||||
| 1017 | if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto()) | |||
| 1018 | return; | |||
| 1019 | ||||
| 1020 | uint64_t addr = base_addr + cur.Offset; | |||
| 1021 | ||||
| 1022 | bool is_statement = cur_info.isStatement(); | |||
| 1023 | bool is_prologue = IsFunctionPrologue(cci, addr); | |||
| 1024 | bool is_epilogue = IsFunctionEpilogue(cci, addr); | |||
| 1025 | ||||
| 1026 | uint32_t lno = cur_info.getStartLine(); | |||
| 1027 | ||||
| 1028 | table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number, | |||
| 1029 | is_statement, false, is_prologue, is_epilogue, | |||
| 1030 | false); | |||
| 1031 | } | |||
| 1032 | ||||
| 1033 | static void TerminateLineSequence(LineTable &table, | |||
| 1034 | const LineFragmentHeader &block, | |||
| 1035 | lldb::addr_t base_addr, uint32_t file_number, | |||
| 1036 | uint32_t last_line, | |||
| 1037 | std::unique_ptr<LineSequence> seq) { | |||
| 1038 | // The end is always a terminal entry, so insert it regardless. | |||
| 1039 | table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize, | |||
| 1040 | last_line, 0, file_number, false, false, | |||
| 1041 | false, false, true); | |||
| 1042 | table.InsertSequence(seq.get()); | |||
| 1043 | } | |||
| 1044 | ||||
| 1045 | bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) { | |||
| 1046 | // Unfortunately LLDB is set up to parse the entire compile unit line table | |||
| 1047 | // all at once, even if all it really needs is line info for a specific | |||
| 1048 | // function. In the future it would be nice if it could set the sc.m_function | |||
| 1049 | // member, and we could only get the line info for the function in question. | |||
| 1050 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1051 | PdbSymUid cu_id(comp_unit.GetID()); | |||
| 1052 | lldbassert(cu_id.kind() == PdbSymUidKind::Compiland)lldb_private::lldb_assert(static_cast<bool>(cu_id.kind( ) == PdbSymUidKind::Compiland), "cu_id.kind() == PdbSymUidKind::Compiland" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1052); | |||
| 1053 | CompilandIndexItem *cci = | |||
| 1054 | m_index->compilands().GetCompiland(cu_id.asCompiland().modi); | |||
| 1055 | lldbassert(cci)lldb_private::lldb_assert(static_cast<bool>(cci), "cci" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1055); | |||
| 1056 | auto line_table = std::make_unique<LineTable>(&comp_unit); | |||
| 1057 | ||||
| 1058 | // This is basically a copy of the .debug$S subsections from all original COFF | |||
| 1059 | // object files merged together with address relocations applied. We are | |||
| 1060 | // looking for all DEBUG_S_LINES subsections. | |||
| 1061 | for (const DebugSubsectionRecord &dssr : | |||
| 1062 | cci->m_debug_stream.getSubsectionsArray()) { | |||
| 1063 | if (dssr.kind() != DebugSubsectionKind::Lines) | |||
| 1064 | continue; | |||
| 1065 | ||||
| 1066 | DebugLinesSubsectionRef lines; | |||
| 1067 | llvm::BinaryStreamReader reader(dssr.getRecordData()); | |||
| 1068 | if (auto EC = lines.initialize(reader)) { | |||
| 1069 | llvm::consumeError(std::move(EC)); | |||
| 1070 | return false; | |||
| 1071 | } | |||
| 1072 | ||||
| 1073 | const LineFragmentHeader *lfh = lines.header(); | |||
| 1074 | uint64_t virtual_addr = | |||
| 1075 | m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset); | |||
| 1076 | ||||
| 1077 | const auto &checksums = cci->m_strings.checksums().getArray(); | |||
| 1078 | const auto &strings = cci->m_strings.strings(); | |||
| 1079 | for (const LineColumnEntry &group : lines) { | |||
| 1080 | // Indices in this structure are actually offsets of records in the | |||
| 1081 | // DEBUG_S_FILECHECKSUMS subsection. Those entries then have an index | |||
| 1082 | // into the global PDB string table. | |||
| 1083 | auto iter = checksums.at(group.NameIndex); | |||
| 1084 | if (iter == checksums.end()) | |||
| 1085 | continue; | |||
| 1086 | ||||
| 1087 | llvm::Expected<llvm::StringRef> efn = | |||
| 1088 | strings.getString(iter->FileNameOffset); | |||
| 1089 | if (!efn) { | |||
| 1090 | llvm::consumeError(efn.takeError()); | |||
| 1091 | continue; | |||
| 1092 | } | |||
| 1093 | ||||
| 1094 | // LLDB wants the index of the file in the list of support files. | |||
| 1095 | auto fn_iter = llvm::find(cci->m_file_list, *efn); | |||
| 1096 | lldbassert(fn_iter != cci->m_file_list.end())lldb_private::lldb_assert(static_cast<bool>(fn_iter != cci ->m_file_list.end()), "fn_iter != cci->m_file_list.end()" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1096); | |||
| 1097 | uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter); | |||
| 1098 | ||||
| 1099 | std::unique_ptr<LineSequence> sequence( | |||
| 1100 | line_table->CreateLineSequenceContainer()); | |||
| 1101 | lldbassert(!group.LineNumbers.empty())lldb_private::lldb_assert(static_cast<bool>(!group.LineNumbers .empty()), "!group.LineNumbers.empty()", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1101); | |||
| 1102 | ||||
| 1103 | for (const LineNumberEntry &entry : group.LineNumbers) { | |||
| 1104 | AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr, | |||
| 1105 | file_index, *lfh, entry); | |||
| 1106 | } | |||
| 1107 | LineInfo last_line(group.LineNumbers.back().Flags); | |||
| 1108 | TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index, | |||
| 1109 | last_line.getEndLine(), std::move(sequence)); | |||
| 1110 | } | |||
| 1111 | } | |||
| 1112 | ||||
| 1113 | if (line_table->GetSize() == 0) | |||
| 1114 | return false; | |||
| 1115 | ||||
| 1116 | comp_unit.SetLineTable(line_table.release()); | |||
| 1117 | return true; | |||
| 1118 | } | |||
| 1119 | ||||
| 1120 | bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) { | |||
| 1121 | // PDB doesn't contain information about macros | |||
| 1122 | return false; | |||
| 1123 | } | |||
| 1124 | ||||
| 1125 | bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit, | |||
| 1126 | FileSpecList &support_files) { | |||
| 1127 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1128 | PdbSymUid cu_id(comp_unit.GetID()); | |||
| 1129 | lldbassert(cu_id.kind() == PdbSymUidKind::Compiland)lldb_private::lldb_assert(static_cast<bool>(cu_id.kind( ) == PdbSymUidKind::Compiland), "cu_id.kind() == PdbSymUidKind::Compiland" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1129); | |||
| 1130 | CompilandIndexItem *cci = | |||
| 1131 | m_index->compilands().GetCompiland(cu_id.asCompiland().modi); | |||
| 1132 | lldbassert(cci)lldb_private::lldb_assert(static_cast<bool>(cci), "cci" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1132); | |||
| 1133 | ||||
| 1134 | for (llvm::StringRef f : cci->m_file_list) { | |||
| 1135 | FileSpec::Style style = | |||
| 1136 | f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows; | |||
| 1137 | FileSpec spec(f, style); | |||
| 1138 | support_files.Append(spec); | |||
| 1139 | } | |||
| 1140 | return true; | |||
| 1141 | } | |||
| 1142 | ||||
| 1143 | bool SymbolFileNativePDB::ParseImportedModules( | |||
| 1144 | const SymbolContext &sc, std::vector<SourceModule> &imported_modules) { | |||
| 1145 | // PDB does not yet support module debug info | |||
| 1146 | return false; | |||
| 1147 | } | |||
| 1148 | ||||
| 1149 | size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) { | |||
| 1150 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1151 | GetOrCreateBlock(PdbSymUid(func.GetID()).asCompilandSym()); | |||
| 1152 | // FIXME: Parse child blocks | |||
| 1153 | return 1; | |||
| 1154 | } | |||
| 1155 | ||||
| 1156 | void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); } | |||
| 1157 | ||||
| 1158 | void SymbolFileNativePDB::FindGlobalVariables( | |||
| 1159 | ConstString name, const CompilerDeclContext &parent_decl_ctx, | |||
| 1160 | uint32_t max_matches, VariableList &variables) { | |||
| 1161 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1162 | using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; | |||
| 1163 | ||||
| 1164 | std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName( | |||
| 1165 | name.GetStringRef(), m_index->symrecords()); | |||
| 1166 | for (const SymbolAndOffset &result : results) { | |||
| 1167 | VariableSP var; | |||
| 1168 | switch (result.second.kind()) { | |||
| 1169 | case SymbolKind::S_GDATA32: | |||
| 1170 | case SymbolKind::S_LDATA32: | |||
| 1171 | case SymbolKind::S_GTHREAD32: | |||
| 1172 | case SymbolKind::S_LTHREAD32: | |||
| 1173 | case SymbolKind::S_CONSTANT: { | |||
| 1174 | PdbGlobalSymId global(result.first, false); | |||
| 1175 | var = GetOrCreateGlobalVariable(global); | |||
| 1176 | variables.AddVariable(var); | |||
| 1177 | break; | |||
| 1178 | } | |||
| 1179 | default: | |||
| 1180 | continue; | |||
| 1181 | } | |||
| 1182 | } | |||
| 1183 | } | |||
| 1184 | ||||
| 1185 | void SymbolFileNativePDB::FindFunctions( | |||
| 1186 | ConstString name, const CompilerDeclContext &parent_decl_ctx, | |||
| 1187 | FunctionNameType name_type_mask, bool include_inlines, | |||
| 1188 | SymbolContextList &sc_list) { | |||
| 1189 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1190 | // For now we only support lookup by method name. | |||
| 1191 | if (!(name_type_mask & eFunctionNameTypeMethod)) | |||
| 1192 | return; | |||
| 1193 | ||||
| 1194 | using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>; | |||
| 1195 | ||||
| 1196 | std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName( | |||
| 1197 | name.GetStringRef(), m_index->symrecords()); | |||
| 1198 | for (const SymbolAndOffset &match : matches) { | |||
| 1199 | if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF) | |||
| 1200 | continue; | |||
| 1201 | ProcRefSym proc(match.second.kind()); | |||
| 1202 | cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc)); | |||
| 1203 | ||||
| 1204 | if (!IsValidRecord(proc)) | |||
| 1205 | continue; | |||
| 1206 | ||||
| 1207 | CompilandIndexItem &cci = | |||
| 1208 | m_index->compilands().GetOrCreateCompiland(proc.modi()); | |||
| 1209 | SymbolContext sc; | |||
| 1210 | ||||
| 1211 | sc.comp_unit = GetOrCreateCompileUnit(cci).get(); | |||
| 1212 | PdbCompilandSymId func_id(proc.modi(), proc.SymOffset); | |||
| 1213 | sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get(); | |||
| 1214 | ||||
| 1215 | sc_list.Append(sc); | |||
| 1216 | } | |||
| 1217 | } | |||
| 1218 | ||||
| 1219 | void SymbolFileNativePDB::FindFunctions(const RegularExpression ®ex, | |||
| 1220 | bool include_inlines, | |||
| 1221 | SymbolContextList &sc_list) {} | |||
| 1222 | ||||
| 1223 | void SymbolFileNativePDB::FindTypes( | |||
| 1224 | ConstString name, const CompilerDeclContext &parent_decl_ctx, | |||
| 1225 | uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files, | |||
| 1226 | TypeMap &types) { | |||
| 1227 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1228 | if (!name) | |||
| 1229 | return; | |||
| 1230 | ||||
| 1231 | searched_symbol_files.clear(); | |||
| 1232 | searched_symbol_files.insert(this); | |||
| 1233 | ||||
| 1234 | // There is an assumption 'name' is not a regex | |||
| 1235 | FindTypesByName(name.GetStringRef(), max_matches, types); | |||
| 1236 | } | |||
| 1237 | ||||
| 1238 | void SymbolFileNativePDB::FindTypes( | |||
| 1239 | llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages, | |||
| 1240 | llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {} | |||
| 1241 | ||||
| 1242 | void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name, | |||
| 1243 | uint32_t max_matches, | |||
| 1244 | TypeMap &types) { | |||
| 1245 | ||||
| 1246 | std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name); | |||
| 1247 | if (max_matches > 0 && max_matches < matches.size()) | |||
| 1248 | matches.resize(max_matches); | |||
| 1249 | ||||
| 1250 | for (TypeIndex ti : matches) { | |||
| 1251 | TypeSP type = GetOrCreateType(ti); | |||
| 1252 | if (!type) | |||
| 1253 | continue; | |||
| 1254 | ||||
| 1255 | types.Insert(type); | |||
| 1256 | } | |||
| 1257 | } | |||
| 1258 | ||||
| 1259 | size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) { | |||
| 1260 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1261 | // Only do the full type scan the first time. | |||
| 1262 | if (m_done_full_type_scan) | |||
| 1263 | return 0; | |||
| 1264 | ||||
| 1265 | const size_t old_count = GetTypeList().GetSize(); | |||
| 1266 | LazyRandomTypeCollection &types = m_index->tpi().typeCollection(); | |||
| 1267 | ||||
| 1268 | // First process the entire TPI stream. | |||
| 1269 | for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) { | |||
| 1270 | TypeSP type = GetOrCreateType(*ti); | |||
| 1271 | if (type) | |||
| 1272 | (void)type->GetFullCompilerType(); | |||
| 1273 | } | |||
| 1274 | ||||
| 1275 | // Next look for S_UDT records in the globals stream. | |||
| 1276 | for (const uint32_t gid : m_index->globals().getGlobalsTable()) { | |||
| 1277 | PdbGlobalSymId global{gid, false}; | |||
| 1278 | CVSymbol sym = m_index->ReadSymbolRecord(global); | |||
| 1279 | if (sym.kind() != S_UDT) | |||
| 1280 | continue; | |||
| 1281 | ||||
| 1282 | UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); | |||
| 1283 | bool is_typedef = true; | |||
| 1284 | if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) { | |||
| 1285 | CVType cvt = m_index->tpi().getType(udt.Type); | |||
| 1286 | llvm::StringRef name = CVTagRecord::create(cvt).name(); | |||
| 1287 | if (name == udt.Name) | |||
| 1288 | is_typedef = false; | |||
| 1289 | } | |||
| 1290 | ||||
| 1291 | if (is_typedef) | |||
| 1292 | GetOrCreateTypedef(global); | |||
| 1293 | } | |||
| 1294 | ||||
| 1295 | const size_t new_count = GetTypeList().GetSize(); | |||
| 1296 | ||||
| 1297 | m_done_full_type_scan = true; | |||
| 1298 | ||||
| 1299 | return new_count - old_count; | |||
| 1300 | } | |||
| 1301 | ||||
| 1302 | size_t | |||
| 1303 | SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit, | |||
| 1304 | VariableList &variables) { | |||
| 1305 | PdbSymUid sym_uid(comp_unit.GetID()); | |||
| 1306 | lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland)lldb_private::lldb_assert(static_cast<bool>(sym_uid.kind () == PdbSymUidKind::Compiland), "sym_uid.kind() == PdbSymUidKind::Compiland" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1306); | |||
| 1307 | return 0; | |||
| 1308 | } | |||
| 1309 | ||||
| 1310 | VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id, | |||
| 1311 | PdbCompilandSymId var_id, | |||
| 1312 | bool is_param) { | |||
| 1313 | ModuleSP module = GetObjectFile()->GetModule(); | |||
| 1314 | Block &block = GetOrCreateBlock(scope_id); | |||
| 1315 | VariableInfo var_info = | |||
| 1316 | GetVariableLocationInfo(*m_index, var_id, block, module); | |||
| 1317 | if (!var_info.location || !var_info.ranges) | |||
| 1318 | return nullptr; | |||
| 1319 | ||||
| 1320 | CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi); | |||
| 1321 | CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii); | |||
| 1322 | TypeSP type_sp = GetOrCreateType(var_info.type); | |||
| 1323 | std::string name = var_info.name.str(); | |||
| 1324 | Declaration decl; | |||
| 1325 | SymbolFileTypeSP sftype = | |||
| 1326 | std::make_shared<SymbolFileType>(*this, type_sp->GetID()); | |||
| 1327 | ||||
| 1328 | ValueType var_scope = | |||
| 1329 | is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal; | |||
| 1330 | bool external = false; | |||
| 1331 | bool artificial = false; | |||
| 1332 | bool location_is_constant_data = false; | |||
| 1333 | bool static_member = false; | |||
| 1334 | VariableSP var_sp = std::make_shared<Variable>( | |||
| 1335 | toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope, | |||
| 1336 | comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, external, | |||
| 1337 | artificial, location_is_constant_data, static_member); | |||
| 1338 | ||||
| 1339 | if (!is_param) | |||
| 1340 | m_ast->GetOrCreateVariableDecl(scope_id, var_id); | |||
| 1341 | ||||
| 1342 | m_local_variables[toOpaqueUid(var_id)] = var_sp; | |||
| 1343 | return var_sp; | |||
| 1344 | } | |||
| 1345 | ||||
| 1346 | VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable( | |||
| 1347 | PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) { | |||
| 1348 | auto iter = m_local_variables.find(toOpaqueUid(var_id)); | |||
| 1349 | if (iter != m_local_variables.end()) | |||
| 1350 | return iter->second; | |||
| 1351 | ||||
| 1352 | return CreateLocalVariable(scope_id, var_id, is_param); | |||
| 1353 | } | |||
| 1354 | ||||
| 1355 | TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) { | |||
| 1356 | CVSymbol sym = m_index->ReadSymbolRecord(id); | |||
| 1357 | lldbassert(sym.kind() == SymbolKind::S_UDT)lldb_private::lldb_assert(static_cast<bool>(sym.kind() == SymbolKind::S_UDT), "sym.kind() == SymbolKind::S_UDT", __FUNCTION__ , "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1357); | |||
| 1358 | ||||
| 1359 | UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); | |||
| 1360 | ||||
| 1361 | TypeSP target_type = GetOrCreateType(udt.Type); | |||
| 1362 | ||||
| 1363 | (void)m_ast->GetOrCreateTypedefDecl(id); | |||
| 1364 | ||||
| 1365 | Declaration decl; | |||
| 1366 | return std::make_shared<lldb_private::Type>( | |||
| 1367 | toOpaqueUid(id), this, ConstString(udt.Name), | |||
| 1368 | target_type->GetByteSize(nullptr), nullptr, target_type->GetID(), | |||
| 1369 | lldb_private::Type::eEncodingIsTypedefUID, decl, | |||
| 1370 | target_type->GetForwardCompilerType(), | |||
| 1371 | lldb_private::Type::ResolveState::Forward); | |||
| 1372 | } | |||
| 1373 | ||||
| 1374 | TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) { | |||
| 1375 | auto iter = m_types.find(toOpaqueUid(id)); | |||
| 1376 | if (iter != m_types.end()) | |||
| 1377 | return iter->second; | |||
| 1378 | ||||
| 1379 | return CreateTypedef(id); | |||
| 1380 | } | |||
| 1381 | ||||
| 1382 | size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) { | |||
| 1383 | Block &block = GetOrCreateBlock(block_id); | |||
| 1384 | ||||
| 1385 | size_t count = 0; | |||
| 1386 | ||||
| 1387 | CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi); | |||
| 1388 | CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset); | |||
| 1389 | uint32_t params_remaining = 0; | |||
| 1390 | switch (sym.kind()) { | |||
| 1391 | case S_GPROC32: | |||
| 1392 | case S_LPROC32: { | |||
| 1393 | ProcSym proc(static_cast<SymbolRecordKind>(sym.kind())); | |||
| 1394 | cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc)); | |||
| 1395 | CVType signature = m_index->tpi().getType(proc.FunctionType); | |||
| 1396 | ProcedureRecord sig; | |||
| 1397 | cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig)); | |||
| 1398 | params_remaining = sig.getParameterCount(); | |||
| 1399 | break; | |||
| 1400 | } | |||
| 1401 | case S_BLOCK32: | |||
| 1402 | break; | |||
| 1403 | default: | |||
| 1404 | lldbassert(false && "Symbol is not a block!")lldb_private::lldb_assert(static_cast<bool>(false && "Symbol is not a block!"), "false && \"Symbol is not a block!\"" , __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1404); | |||
| 1405 | return 0; | |||
| 1406 | } | |||
| 1407 | ||||
| 1408 | VariableListSP variables = block.GetBlockVariableList(false); | |||
| 1409 | if (!variables) { | |||
| 1410 | variables = std::make_shared<VariableList>(); | |||
| 1411 | block.SetVariableList(variables); | |||
| 1412 | } | |||
| 1413 | ||||
| 1414 | CVSymbolArray syms = limitSymbolArrayToScope( | |||
| 1415 | cii->m_debug_stream.getSymbolArray(), block_id.offset); | |||
| 1416 | ||||
| 1417 | // Skip the first record since it's a PROC32 or BLOCK32, and there's | |||
| 1418 | // no point examining it since we know it's not a local variable. | |||
| 1419 | syms.drop_front(); | |||
| 1420 | auto iter = syms.begin(); | |||
| 1421 | auto end = syms.end(); | |||
| 1422 | ||||
| 1423 | while (iter != end) { | |||
| 1424 | uint32_t record_offset = iter.offset(); | |||
| 1425 | CVSymbol variable_cvs = *iter; | |||
| 1426 | PdbCompilandSymId child_sym_id(block_id.modi, record_offset); | |||
| 1427 | ++iter; | |||
| 1428 | ||||
| 1429 | // If this is a block, recurse into its children and then skip it. | |||
| 1430 | if (variable_cvs.kind() == S_BLOCK32) { | |||
| 1431 | uint32_t block_end = getScopeEndOffset(variable_cvs); | |||
| 1432 | count += ParseVariablesForBlock(child_sym_id); | |||
| 1433 | iter = syms.at(block_end); | |||
| 1434 | continue; | |||
| 1435 | } | |||
| 1436 | ||||
| 1437 | bool is_param = params_remaining > 0; | |||
| 1438 | VariableSP variable; | |||
| 1439 | switch (variable_cvs.kind()) { | |||
| 1440 | case S_REGREL32: | |||
| 1441 | case S_REGISTER: | |||
| 1442 | case S_LOCAL: | |||
| 1443 | variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param); | |||
| 1444 | if (is_param) | |||
| 1445 | --params_remaining; | |||
| 1446 | if (variable) | |||
| 1447 | variables->AddVariableIfUnique(variable); | |||
| 1448 | break; | |||
| 1449 | default: | |||
| 1450 | break; | |||
| 1451 | } | |||
| 1452 | } | |||
| 1453 | ||||
| 1454 | // Pass false for set_children, since we call this recursively so that the | |||
| 1455 | // children will call this for themselves. | |||
| 1456 | block.SetDidParseVariables(true, false); | |||
| 1457 | ||||
| 1458 | return count; | |||
| 1459 | } | |||
| 1460 | ||||
| 1461 | size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) { | |||
| 1462 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1463 | lldbassert(sc.function || sc.comp_unit)lldb_private::lldb_assert(static_cast<bool>(sc.function || sc.comp_unit), "sc.function || sc.comp_unit", __FUNCTION__ , "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1463); | |||
| 1464 | ||||
| 1465 | VariableListSP variables; | |||
| 1466 | if (sc.block) { | |||
| 1467 | PdbSymUid block_id(sc.block->GetID()); | |||
| 1468 | ||||
| 1469 | size_t count = ParseVariablesForBlock(block_id.asCompilandSym()); | |||
| 1470 | return count; | |||
| 1471 | } | |||
| 1472 | ||||
| 1473 | if (sc.function) { | |||
| 1474 | PdbSymUid block_id(sc.function->GetID()); | |||
| 1475 | ||||
| 1476 | size_t count = ParseVariablesForBlock(block_id.asCompilandSym()); | |||
| 1477 | return count; | |||
| 1478 | } | |||
| 1479 | ||||
| 1480 | if (sc.comp_unit) { | |||
| 1481 | variables = sc.comp_unit->GetVariableList(false); | |||
| 1482 | if (!variables) { | |||
| 1483 | variables = std::make_shared<VariableList>(); | |||
| 1484 | sc.comp_unit->SetVariableList(variables); | |||
| 1485 | } | |||
| 1486 | return ParseVariablesForCompileUnit(*sc.comp_unit, *variables); | |||
| 1487 | } | |||
| 1488 | ||||
| 1489 | llvm_unreachable("Unreachable!")__builtin_unreachable(); | |||
| 1490 | } | |||
| 1491 | ||||
| 1492 | CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) { | |||
| 1493 | if (auto decl = m_ast->GetOrCreateDeclForUid(uid)) | |||
| 1494 | return decl.getValue(); | |||
| 1495 | else | |||
| 1496 | return CompilerDecl(); | |||
| 1497 | } | |||
| 1498 | ||||
| 1499 | CompilerDeclContext | |||
| 1500 | SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) { | |||
| 1501 | clang::DeclContext *context = | |||
| 1502 | m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid)); | |||
| 1503 | if (!context) | |||
| 1504 | return {}; | |||
| 1505 | ||||
| 1506 | return m_ast->ToCompilerDeclContext(*context); | |||
| 1507 | } | |||
| 1508 | ||||
| 1509 | CompilerDeclContext | |||
| 1510 | SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) { | |||
| 1511 | clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid)); | |||
| 1512 | return m_ast->ToCompilerDeclContext(*context); | |||
| 1513 | } | |||
| 1514 | ||||
| 1515 | Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) { | |||
| 1516 | std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); | |||
| 1517 | auto iter = m_types.find(type_uid); | |||
| 1518 | // lldb should not be passing us non-sensical type uids. the only way it | |||
| 1519 | // could have a type uid in the first place is if we handed it out, in which | |||
| 1520 | // case we should know about the type. However, that doesn't mean we've | |||
| 1521 | // instantiated it yet. We can vend out a UID for a future type. So if the | |||
| 1522 | // type doesn't exist, let's instantiate it now. | |||
| 1523 | if (iter != m_types.end()) | |||
| 1524 | return &*iter->second; | |||
| 1525 | ||||
| 1526 | PdbSymUid uid(type_uid); | |||
| 1527 | lldbassert(uid.kind() == PdbSymUidKind::Type)lldb_private::lldb_assert(static_cast<bool>(uid.kind() == PdbSymUidKind::Type), "uid.kind() == PdbSymUidKind::Type", __FUNCTION__ , "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp" , 1527); | |||
| 1528 | PdbTypeSymId type_id = uid.asTypeSym(); | |||
| 1529 | if (type_id.index.isNoneType()) | |||
| 1530 | return nullptr; | |||
| 1531 | ||||
| 1532 | TypeSP type_sp = CreateAndCacheType(type_id); | |||
| 1533 | return &*type_sp; | |||
| 1534 | } | |||
| 1535 | ||||
| 1536 | llvm::Optional<SymbolFile::ArrayInfo> | |||
| 1537 | SymbolFileNativePDB::GetDynamicArrayInfoForUID( | |||
| 1538 | lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { | |||
| 1539 | return llvm::None; | |||
| 1540 | } | |||
| 1541 | ||||
| 1542 | ||||
| 1543 | bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) { | |||
| 1544 | clang::QualType qt = | |||
| 1545 | clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType()); | |||
| 1546 | ||||
| 1547 | return m_ast->CompleteType(qt); | |||
| 1548 | } | |||
| 1549 | ||||
| 1550 | void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope, | |||
| 1551 | TypeClass type_mask, | |||
| 1552 | lldb_private::TypeList &type_list) {} | |||
| 1553 | ||||
| 1554 | CompilerDeclContext | |||
| 1555 | SymbolFileNativePDB::FindNamespace(ConstString name, | |||
| 1556 | const CompilerDeclContext &parent_decl_ctx) { | |||
| 1557 | return {}; | |||
| 1558 | } | |||
| 1559 | ||||
| 1560 | llvm::Expected<TypeSystem &> | |||
| 1561 | SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) { | |||
| 1562 | auto type_system_or_err = | |||
| 1563 | m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language); | |||
| 1564 | if (type_system_or_err) { | |||
| 1565 | type_system_or_err->SetSymbolFile(this); | |||
| 1566 | } | |||
| 1567 | return type_system_or_err; | |||
| 1568 | } | |||
| 1569 | ||||
| 1570 | ConstString SymbolFileNativePDB::GetPluginName() { | |||
| 1571 | static ConstString g_name("pdb"); | |||
| 1572 | return g_name; | |||
| 1573 | } | |||
| 1574 | ||||
| 1575 | uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; } |
| 1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file defines an API used to report recoverable errors. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #ifndef LLVM_SUPPORT_ERROR_H |
| 14 | #define LLVM_SUPPORT_ERROR_H |
| 15 | |
| 16 | #include "llvm-c/Error.h" |
| 17 | #include "llvm/ADT/STLExtras.h" |
| 18 | #include "llvm/ADT/SmallVector.h" |
| 19 | #include "llvm/ADT/StringExtras.h" |
| 20 | #include "llvm/ADT/Twine.h" |
| 21 | #include "llvm/Config/abi-breaking.h" |
| 22 | #include "llvm/Support/AlignOf.h" |
| 23 | #include "llvm/Support/Compiler.h" |
| 24 | #include "llvm/Support/Debug.h" |
| 25 | #include "llvm/Support/ErrorHandling.h" |
| 26 | #include "llvm/Support/ErrorOr.h" |
| 27 | #include "llvm/Support/Format.h" |
| 28 | #include "llvm/Support/raw_ostream.h" |
| 29 | #include <algorithm> |
| 30 | #include <cassert> |
| 31 | #include <cstdint> |
| 32 | #include <cstdlib> |
| 33 | #include <functional> |
| 34 | #include <memory> |
| 35 | #include <new> |
| 36 | #include <string> |
| 37 | #include <system_error> |
| 38 | #include <type_traits> |
| 39 | #include <utility> |
| 40 | #include <vector> |
| 41 | |
| 42 | namespace llvm { |
| 43 | |
| 44 | class ErrorSuccess; |
| 45 | |
| 46 | /// Base class for error info classes. Do not extend this directly: Extend |
| 47 | /// the ErrorInfo template subclass instead. |
| 48 | class ErrorInfoBase { |
| 49 | public: |
| 50 | virtual ~ErrorInfoBase() = default; |
| 51 | |
| 52 | /// Print an error message to an output stream. |
| 53 | virtual void log(raw_ostream &OS) const = 0; |
| 54 | |
| 55 | /// Return the error message as a string. |
| 56 | virtual std::string message() const { |
| 57 | std::string Msg; |
| 58 | raw_string_ostream OS(Msg); |
| 59 | log(OS); |
| 60 | return OS.str(); |
| 61 | } |
| 62 | |
| 63 | /// Convert this error to a std::error_code. |
| 64 | /// |
| 65 | /// This is a temporary crutch to enable interaction with code still |
| 66 | /// using std::error_code. It will be removed in the future. |
| 67 | virtual std::error_code convertToErrorCode() const = 0; |
| 68 | |
| 69 | // Returns the class ID for this type. |
| 70 | static const void *classID() { return &ID; } |
| 71 | |
| 72 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
| 73 | virtual const void *dynamicClassID() const = 0; |
| 74 | |
| 75 | // Check whether this instance is a subclass of the class identified by |
| 76 | // ClassID. |
| 77 | virtual bool isA(const void *const ClassID) const { |
| 78 | return ClassID == classID(); |
| 79 | } |
| 80 | |
| 81 | // Check whether this instance is a subclass of ErrorInfoT. |
| 82 | template <typename ErrorInfoT> bool isA() const { |
| 83 | return isA(ErrorInfoT::classID()); |
| 84 | } |
| 85 | |
| 86 | private: |
| 87 | virtual void anchor(); |
| 88 | |
| 89 | static char ID; |
| 90 | }; |
| 91 | |
| 92 | /// Lightweight error class with error context and mandatory checking. |
| 93 | /// |
| 94 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
| 95 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
| 96 | /// instance containing information describing the failure. Success is |
| 97 | /// represented by a null pointer value. |
| 98 | /// |
| 99 | /// Instances of Error also contains a 'Checked' flag, which must be set |
| 100 | /// before the destructor is called, otherwise the destructor will trigger a |
| 101 | /// runtime error. This enforces at runtime the requirement that all Error |
| 102 | /// instances be checked or returned to the caller. |
| 103 | /// |
| 104 | /// There are two ways to set the checked flag, depending on what state the |
| 105 | /// Error instance is in. For Error instances indicating success, it |
| 106 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
| 107 | /// |
| 108 | /// @code{.cpp} |
| 109 | /// Error foo(<...>); |
| 110 | /// |
| 111 | /// if (auto E = foo(<...>)) |
| 112 | /// return E; // <- Return E if it is in the error state. |
| 113 | /// // We have verified that E was in the success state. It can now be safely |
| 114 | /// // destroyed. |
| 115 | /// @endcode |
| 116 | /// |
| 117 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
| 118 | /// without testing the return value will raise a runtime error, even if foo |
| 119 | /// returns success. |
| 120 | /// |
| 121 | /// For Error instances representing failure, you must use either the |
| 122 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
| 123 | /// |
| 124 | /// @code{.cpp} |
| 125 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
| 126 | /// // Custom error info. |
| 127 | /// }; |
| 128 | /// |
| 129 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
| 130 | /// |
| 131 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
| 132 | /// auto NewE = |
| 133 | /// handleErrors(E, |
| 134 | /// [](const MyErrorInfo &M) { |
| 135 | /// // Deal with the error. |
| 136 | /// }, |
| 137 | /// [](std::unique_ptr<OtherError> M) -> Error { |
| 138 | /// if (canHandle(*M)) { |
| 139 | /// // handle error. |
| 140 | /// return Error::success(); |
| 141 | /// } |
| 142 | /// // Couldn't handle this error instance. Pass it up the stack. |
| 143 | /// return Error(std::move(M)); |
| 144 | /// ); |
| 145 | /// // Note - we must check or return NewE in case any of the handlers |
| 146 | /// // returned a new error. |
| 147 | /// @endcode |
| 148 | /// |
| 149 | /// The handleAllErrors function is identical to handleErrors, except |
| 150 | /// that it has a void return type, and requires all errors to be handled and |
| 151 | /// no new errors be returned. It prevents errors (assuming they can all be |
| 152 | /// handled) from having to be bubbled all the way to the top-level. |
| 153 | /// |
| 154 | /// *All* Error instances must be checked before destruction, even if |
| 155 | /// they're moved-assigned or constructed from Success values that have already |
| 156 | /// been checked. This enforces checking through all levels of the call stack. |
| 157 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { |
| 158 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors |
| 159 | // to add to the error list. It can't rely on handleErrors for this, since |
| 160 | // handleErrors does not support ErrorList handlers. |
| 161 | friend class ErrorList; |
| 162 | |
| 163 | // handleErrors needs to be able to set the Checked flag. |
| 164 | template <typename... HandlerTs> |
| 165 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
| 166 | |
| 167 | // Expected<T> needs to be able to steal the payload when constructed from an |
| 168 | // error. |
| 169 | template <typename T> friend class Expected; |
| 170 | |
| 171 | // wrap needs to be able to steal the payload. |
| 172 | friend LLVMErrorRef wrap(Error); |
| 173 | |
| 174 | protected: |
| 175 | /// Create a success value. Prefer using 'Error::success()' for readability |
| 176 | Error() { |
| 177 | setPtr(nullptr); |
| 178 | setChecked(false); |
| 179 | } |
| 180 | |
| 181 | public: |
| 182 | /// Create a success value. |
| 183 | static ErrorSuccess success(); |
| 184 | |
| 185 | // Errors are not copy-constructable. |
| 186 | Error(const Error &Other) = delete; |
| 187 | |
| 188 | /// Move-construct an error value. The newly constructed error is considered |
| 189 | /// unchecked, even if the source error had been checked. The original error |
| 190 | /// becomes a checked Success value, regardless of its original state. |
| 191 | Error(Error &&Other) { |
| 192 | setChecked(true); |
| 193 | *this = std::move(Other); |
| 194 | } |
| 195 | |
| 196 | /// Create an error value. Prefer using the 'make_error' function, but |
| 197 | /// this constructor can be useful when "re-throwing" errors from handlers. |
| 198 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
| 199 | setPtr(Payload.release()); |
| 200 | setChecked(false); |
| 201 | } |
| 202 | |
| 203 | // Errors are not copy-assignable. |
| 204 | Error &operator=(const Error &Other) = delete; |
| 205 | |
| 206 | /// Move-assign an error value. The current error must represent success, you |
| 207 | /// you cannot overwrite an unhandled error. The current error is then |
| 208 | /// considered unchecked. The source error becomes a checked success value, |
| 209 | /// regardless of its original state. |
| 210 | Error &operator=(Error &&Other) { |
| 211 | // Don't allow overwriting of unchecked values. |
| 212 | assertIsChecked(); |
| 213 | setPtr(Other.getPtr()); |
| 214 | |
| 215 | // This Error is unchecked, even if the source error was checked. |
| 216 | setChecked(false); |
| 217 | |
| 218 | // Null out Other's payload and set its checked bit. |
| 219 | Other.setPtr(nullptr); |
| 220 | Other.setChecked(true); |
| 221 | |
| 222 | return *this; |
| 223 | } |
| 224 | |
| 225 | /// Destroy a Error. Fails with a call to abort() if the error is |
| 226 | /// unchecked. |
| 227 | ~Error() { |
| 228 | assertIsChecked(); |
| 229 | delete getPtr(); |
| 230 | } |
| 231 | |
| 232 | /// Bool conversion. Returns true if this Error is in a failure state, |
| 233 | /// and false if it is in an accept state. If the error is in a Success state |
| 234 | /// it will be considered checked. |
| 235 | explicit operator bool() { |
| 236 | setChecked(getPtr() == nullptr); |
| 237 | return getPtr() != nullptr; |
| 238 | } |
| 239 | |
| 240 | /// Check whether one error is a subclass of another. |
| 241 | template <typename ErrT> bool isA() const { |
| 242 | return getPtr() && getPtr()->isA(ErrT::classID()); |
| 243 | } |
| 244 | |
| 245 | /// Returns the dynamic class id of this error, or null if this is a success |
| 246 | /// value. |
| 247 | const void* dynamicClassID() const { |
| 248 | if (!getPtr()) |
| 249 | return nullptr; |
| 250 | return getPtr()->dynamicClassID(); |
| 251 | } |
| 252 | |
| 253 | private: |
| 254 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 255 | // assertIsChecked() happens very frequently, but under normal circumstances |
| 256 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
| 257 | // of debug prints can cause the function to be too large for inlining. So |
| 258 | // it's important that we define this function out of line so that it can't be |
| 259 | // inlined. |
| 260 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
| 261 | void fatalUncheckedError() const; |
| 262 | #endif |
| 263 | |
| 264 | void assertIsChecked() { |
| 265 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 266 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) |
| 267 | fatalUncheckedError(); |
| 268 | #endif |
| 269 | } |
| 270 | |
| 271 | ErrorInfoBase *getPtr() const { |
| 272 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 273 | return reinterpret_cast<ErrorInfoBase*>( |
| 274 | reinterpret_cast<uintptr_t>(Payload) & |
| 275 | ~static_cast<uintptr_t>(0x1)); |
| 276 | #else |
| 277 | return Payload; |
| 278 | #endif |
| 279 | } |
| 280 | |
| 281 | void setPtr(ErrorInfoBase *EI) { |
| 282 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 283 | Payload = reinterpret_cast<ErrorInfoBase*>( |
| 284 | (reinterpret_cast<uintptr_t>(EI) & |
| 285 | ~static_cast<uintptr_t>(0x1)) | |
| 286 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
| 287 | #else |
| 288 | Payload = EI; |
| 289 | #endif |
| 290 | } |
| 291 | |
| 292 | bool getChecked() const { |
| 293 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 294 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
| 295 | #else |
| 296 | return true; |
| 297 | #endif |
| 298 | } |
| 299 | |
| 300 | void setChecked(bool V) { |
| 301 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 302 | Payload = reinterpret_cast<ErrorInfoBase*>( |
| 303 | (reinterpret_cast<uintptr_t>(Payload) & |
| 304 | ~static_cast<uintptr_t>(0x1)) | |
| 305 | (V ? 0 : 1)); |
| 306 | #endif |
| 307 | } |
| 308 | |
| 309 | std::unique_ptr<ErrorInfoBase> takePayload() { |
| 310 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
| 311 | setPtr(nullptr); |
| 312 | setChecked(true); |
| 313 | return Tmp; |
| 314 | } |
| 315 | |
| 316 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { |
| 317 | if (auto P = E.getPtr()) |
| 318 | P->log(OS); |
| 319 | else |
| 320 | OS << "success"; |
| 321 | return OS; |
| 322 | } |
| 323 | |
| 324 | ErrorInfoBase *Payload = nullptr; |
| 325 | }; |
| 326 | |
| 327 | /// Subclass of Error for the sole purpose of identifying the success path in |
| 328 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
| 329 | /// compile time. |
| 330 | class ErrorSuccess final : public Error {}; |
| 331 | |
| 332 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
| 333 | |
| 334 | /// Make a Error instance representing failure using the given error info |
| 335 | /// type. |
| 336 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
| 337 | return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
| 338 | } |
| 339 | |
| 340 | /// Base class for user error types. Users should declare their error types |
| 341 | /// like: |
| 342 | /// |
| 343 | /// class MyError : public ErrorInfo<MyError> { |
| 344 | /// .... |
| 345 | /// }; |
| 346 | /// |
| 347 | /// This class provides an implementation of the ErrorInfoBase::kind |
| 348 | /// method, which is used by the Error RTTI system. |
| 349 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
| 350 | class ErrorInfo : public ParentErrT { |
| 351 | public: |
| 352 | using ParentErrT::ParentErrT; // inherit constructors |
| 353 | |
| 354 | static const void *classID() { return &ThisErrT::ID; } |
| 355 | |
| 356 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
| 357 | |
| 358 | bool isA(const void *const ClassID) const override { |
| 359 | return ClassID == classID() || ParentErrT::isA(ClassID); |
| 360 | } |
| 361 | }; |
| 362 | |
| 363 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
| 364 | /// Instances of this class are constructed by joinError. |
| 365 | class ErrorList final : public ErrorInfo<ErrorList> { |
| 366 | // handleErrors needs to be able to iterate the payload list of an |
| 367 | // ErrorList. |
| 368 | template <typename... HandlerTs> |
| 369 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
| 370 | |
| 371 | // joinErrors is implemented in terms of join. |
| 372 | friend Error joinErrors(Error, Error); |
| 373 | |
| 374 | public: |
| 375 | void log(raw_ostream &OS) const override { |
| 376 | OS << "Multiple errors:\n"; |
| 377 | for (auto &ErrPayload : Payloads) { |
| 378 | ErrPayload->log(OS); |
| 379 | OS << "\n"; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | std::error_code convertToErrorCode() const override; |
| 384 | |
| 385 | // Used by ErrorInfo::classID. |
| 386 | static char ID; |
| 387 | |
| 388 | private: |
| 389 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
| 390 | std::unique_ptr<ErrorInfoBase> Payload2) { |
| 391 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((void)0) |
| 392 | "ErrorList constructor payloads should be singleton errors")((void)0); |
| 393 | Payloads.push_back(std::move(Payload1)); |
| 394 | Payloads.push_back(std::move(Payload2)); |
| 395 | } |
| 396 | |
| 397 | static Error join(Error E1, Error E2) { |
| 398 | if (!E1) |
| 399 | return E2; |
| 400 | if (!E2) |
| 401 | return E1; |
| 402 | if (E1.isA<ErrorList>()) { |
| 403 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
| 404 | if (E2.isA<ErrorList>()) { |
| 405 | auto E2Payload = E2.takePayload(); |
| 406 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
| 407 | for (auto &Payload : E2List.Payloads) |
| 408 | E1List.Payloads.push_back(std::move(Payload)); |
| 409 | } else |
| 410 | E1List.Payloads.push_back(E2.takePayload()); |
| 411 | |
| 412 | return E1; |
| 413 | } |
| 414 | if (E2.isA<ErrorList>()) { |
| 415 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
| 416 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); |
| 417 | return E2; |
| 418 | } |
| 419 | return Error(std::unique_ptr<ErrorList>( |
| 420 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
| 421 | } |
| 422 | |
| 423 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
| 424 | }; |
| 425 | |
| 426 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
| 427 | /// ErrorInfo(s), if any, contained in E1, followed by the |
| 428 | /// ErrorInfo(s), if any, contained in E2. |
| 429 | inline Error joinErrors(Error E1, Error E2) { |
| 430 | return ErrorList::join(std::move(E1), std::move(E2)); |
| 431 | } |
| 432 | |
| 433 | /// Tagged union holding either a T or a Error. |
| 434 | /// |
| 435 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
| 436 | /// Error cannot be copied, this class replaces getError() with |
| 437 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
| 438 | /// error class type. |
| 439 | /// |
| 440 | /// Example usage of 'Expected<T>' as a function return type: |
| 441 | /// |
| 442 | /// @code{.cpp} |
| 443 | /// Expected<int> myDivide(int A, int B) { |
| 444 | /// if (B == 0) { |
| 445 | /// // return an Error |
| 446 | /// return createStringError(inconvertibleErrorCode(), |
| 447 | /// "B must not be zero!"); |
| 448 | /// } |
| 449 | /// // return an integer |
| 450 | /// return A / B; |
| 451 | /// } |
| 452 | /// @endcode |
| 453 | /// |
| 454 | /// Checking the results of to a function returning 'Expected<T>': |
| 455 | /// @code{.cpp} |
| 456 | /// if (auto E = Result.takeError()) { |
| 457 | /// // We must consume the error. Typically one of: |
| 458 | /// // - return the error to our caller |
| 459 | /// // - toString(), when logging |
| 460 | /// // - consumeError(), to silently swallow the error |
| 461 | /// // - handleErrors(), to distinguish error types |
| 462 | /// errs() << "Problem with division " << toString(std::move(E)) << "\n"; |
| 463 | /// return; |
| 464 | /// } |
| 465 | /// // use the result |
| 466 | /// outs() << "The answer is " << *Result << "\n"; |
| 467 | /// @endcode |
| 468 | /// |
| 469 | /// For unit-testing a function returning an 'Expceted<T>', see the |
| 470 | /// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h |
| 471 | |
| 472 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { |
| 473 | template <class T1> friend class ExpectedAsOutParameter; |
| 474 | template <class OtherT> friend class Expected; |
| 475 | |
| 476 | static constexpr bool isRef = std::is_reference<T>::value; |
| 477 | |
| 478 | using wrap = std::reference_wrapper<std::remove_reference_t<T>>; |
| 479 | |
| 480 | using error_type = std::unique_ptr<ErrorInfoBase>; |
| 481 | |
| 482 | public: |
| 483 | using storage_type = std::conditional_t<isRef, wrap, T>; |
| 484 | using value_type = T; |
| 485 | |
| 486 | private: |
| 487 | using reference = std::remove_reference_t<T> &; |
| 488 | using const_reference = const std::remove_reference_t<T> &; |
| 489 | using pointer = std::remove_reference_t<T> *; |
| 490 | using const_pointer = const std::remove_reference_t<T> *; |
| 491 | |
| 492 | public: |
| 493 | /// Create an Expected<T> error value from the given Error. |
| 494 | Expected(Error Err) |
| 495 | : HasError(true) |
| 496 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 497 | // Expected is unchecked upon construction in Debug builds. |
| 498 | , Unchecked(true) |
| 499 | #endif |
| 500 | { |
| 501 | assert(Err && "Cannot create Expected<T> from Error success value.")((void)0); |
| 502 | new (getErrorStorage()) error_type(Err.takePayload()); |
| 503 | } |
| 504 | |
| 505 | /// Forbid to convert from Error::success() implicitly, this avoids having |
| 506 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
| 507 | /// but triggers the assertion above. |
| 508 | Expected(ErrorSuccess) = delete; |
| 509 | |
| 510 | /// Create an Expected<T> success value from the given OtherT value, which |
| 511 | /// must be convertible to T. |
| 512 | template <typename OtherT> |
| 513 | Expected(OtherT &&Val, |
| 514 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) |
| 515 | : HasError(false) |
| 516 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 517 | // Expected is unchecked upon construction in Debug builds. |
| 518 | , |
| 519 | Unchecked(true) |
| 520 | #endif |
| 521 | { |
| 522 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
| 523 | } |
| 524 | |
| 525 | /// Move construct an Expected<T> value. |
| 526 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
| 527 | |
| 528 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
| 529 | /// must be convertible to T. |
| 530 | template <class OtherT> |
| 531 | Expected( |
| 532 | Expected<OtherT> &&Other, |
| 533 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) { |
| 534 | moveConstruct(std::move(Other)); |
| 535 | } |
| 536 | |
| 537 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
| 538 | /// isn't convertible to T. |
| 539 | template <class OtherT> |
| 540 | explicit Expected( |
| 541 | Expected<OtherT> &&Other, |
| 542 | std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) { |
| 543 | moveConstruct(std::move(Other)); |
| 544 | } |
| 545 | |
| 546 | /// Move-assign from another Expected<T>. |
| 547 | Expected &operator=(Expected &&Other) { |
| 548 | moveAssign(std::move(Other)); |
| 549 | return *this; |
| 550 | } |
| 551 | |
| 552 | /// Destroy an Expected<T>. |
| 553 | ~Expected() { |
| 554 | assertIsChecked(); |
| 555 | if (!HasError) |
| 556 | getStorage()->~storage_type(); |
| 557 | else |
| 558 | getErrorStorage()->~error_type(); |
| 559 | } |
| 560 | |
| 561 | /// Return false if there is an error. |
| 562 | explicit operator bool() { |
| 563 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 564 | Unchecked = HasError; |
| 565 | #endif |
| 566 | return !HasError; |
| 567 | } |
| 568 | |
| 569 | /// Returns a reference to the stored T value. |
| 570 | reference get() { |
| 571 | assertIsChecked(); |
| 572 | return *getStorage(); |
| 573 | } |
| 574 | |
| 575 | /// Returns a const reference to the stored T value. |
| 576 | const_reference get() const { |
| 577 | assertIsChecked(); |
| 578 | return const_cast<Expected<T> *>(this)->get(); |
| 579 | } |
| 580 | |
| 581 | /// Check that this Expected<T> is an error of type ErrT. |
| 582 | template <typename ErrT> bool errorIsA() const { |
| 583 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
| 584 | } |
| 585 | |
| 586 | /// Take ownership of the stored error. |
| 587 | /// After calling this the Expected<T> is in an indeterminate state that can |
| 588 | /// only be safely destructed. No further calls (beside the destructor) should |
| 589 | /// be made on the Expected<T> value. |
| 590 | Error takeError() { |
| 591 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 592 | Unchecked = false; |
| 593 | #endif |
| 594 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
| 595 | } |
| 596 | |
| 597 | /// Returns a pointer to the stored T value. |
| 598 | pointer operator->() { |
| 599 | assertIsChecked(); |
| 600 | return toPointer(getStorage()); |
| 601 | } |
| 602 | |
| 603 | /// Returns a const pointer to the stored T value. |
| 604 | const_pointer operator->() const { |
| 605 | assertIsChecked(); |
| 606 | return toPointer(getStorage()); |
| 607 | } |
| 608 | |
| 609 | /// Returns a reference to the stored T value. |
| 610 | reference operator*() { |
| 611 | assertIsChecked(); |
| 612 | return *getStorage(); |
| 613 | } |
| 614 | |
| 615 | /// Returns a const reference to the stored T value. |
| 616 | const_reference operator*() const { |
| 617 | assertIsChecked(); |
| 618 | return *getStorage(); |
| 619 | } |
| 620 | |
| 621 | private: |
| 622 | template <class T1> |
| 623 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
| 624 | return &a == &b; |
| 625 | } |
| 626 | |
| 627 | template <class T1, class T2> |
| 628 | static bool compareThisIfSameType(const T1 &, const T2 &) { |
| 629 | return false; |
| 630 | } |
| 631 | |
| 632 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
| 633 | HasError = Other.HasError; |
| 634 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 635 | Unchecked = true; |
| 636 | Other.Unchecked = false; |
| 637 | #endif |
| 638 | |
| 639 | if (!HasError) |
| 640 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
| 641 | else |
| 642 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
| 643 | } |
| 644 | |
| 645 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
| 646 | assertIsChecked(); |
| 647 | |
| 648 | if (compareThisIfSameType(*this, Other)) |
| 649 | return; |
| 650 | |
| 651 | this->~Expected(); |
| 652 | new (this) Expected(std::move(Other)); |
| 653 | } |
| 654 | |
| 655 | pointer toPointer(pointer Val) { return Val; } |
| 656 | |
| 657 | const_pointer toPointer(const_pointer Val) const { return Val; } |
| 658 | |
| 659 | pointer toPointer(wrap *Val) { return &Val->get(); } |
| 660 | |
| 661 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
| 662 | |
| 663 | storage_type *getStorage() { |
| 664 | assert(!HasError && "Cannot get value when an error exists!")((void)0); |
| 665 | return reinterpret_cast<storage_type *>(&TStorage); |
| 666 | } |
| 667 | |
| 668 | const storage_type *getStorage() const { |
| 669 | assert(!HasError && "Cannot get value when an error exists!")((void)0); |
| 670 | return reinterpret_cast<const storage_type *>(&TStorage); |
| 671 | } |
| 672 | |
| 673 | error_type *getErrorStorage() { |
| 674 | assert(HasError && "Cannot get error when a value exists!")((void)0); |
| 675 | return reinterpret_cast<error_type *>(&ErrorStorage); |
| 676 | } |
| 677 | |
| 678 | const error_type *getErrorStorage() const { |
| 679 | assert(HasError && "Cannot get error when a value exists!")((void)0); |
| 680 | return reinterpret_cast<const error_type *>(&ErrorStorage); |
| 681 | } |
| 682 | |
| 683 | // Used by ExpectedAsOutParameter to reset the checked flag. |
| 684 | void setUnchecked() { |
| 685 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 686 | Unchecked = true; |
| 687 | #endif |
| 688 | } |
| 689 | |
| 690 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 691 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
| 692 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) |
| 693 | void fatalUncheckedExpected() const { |
| 694 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; |
| 695 | if (HasError) { |
| 696 | dbgs() << "Unchecked Expected<T> contained error:\n"; |
| 697 | (*getErrorStorage())->log(dbgs()); |
| 698 | } else |
| 699 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
| 700 | "values in success mode must still be checked prior to being " |
| 701 | "destroyed).\n"; |
| 702 | abort(); |
| 703 | } |
| 704 | #endif |
| 705 | |
| 706 | void assertIsChecked() const { |
| 707 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 708 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) |
| 709 | fatalUncheckedExpected(); |
| 710 | #endif |
| 711 | } |
| 712 | |
| 713 | union { |
| 714 | AlignedCharArrayUnion<storage_type> TStorage; |
| 715 | AlignedCharArrayUnion<error_type> ErrorStorage; |
| 716 | }; |
| 717 | bool HasError : 1; |
| 718 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS0 |
| 719 | bool Unchecked : 1; |
| 720 | #endif |
| 721 | }; |
| 722 | |
| 723 | /// Report a serious error, calling any installed error handler. See |
| 724 | /// ErrorHandling.h. |
| 725 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, |
| 726 | bool gen_crash_diag = true); |
| 727 | |
| 728 | /// Report a fatal error if Err is a failure value. |
| 729 | /// |
| 730 | /// This function can be used to wrap calls to fallible functions ONLY when it |
| 731 | /// is known that the Error will always be a success value. E.g. |
| 732 | /// |
| 733 | /// @code{.cpp} |
| 734 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
| 735 | /// // true. If DoFallibleOperation is false then foo always returns |
| 736 | /// // Error::success(). |
| 737 | /// Error foo(bool DoFallibleOperation); |
| 738 | /// |
| 739 | /// cantFail(foo(false)); |
| 740 | /// @endcode |
| 741 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
| 742 | if (Err) { |
| 743 | if (!Msg) |
| 744 | Msg = "Failure value returned from cantFail wrapped call"; |
| 745 | #ifndef NDEBUG1 |
| 746 | std::string Str; |
| 747 | raw_string_ostream OS(Str); |
| 748 | OS << Msg << "\n" << Err; |
| 749 | Msg = OS.str().c_str(); |
| 750 | #endif |
| 751 | llvm_unreachable(Msg)__builtin_unreachable(); |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
| 756 | /// returns the contained value. |
| 757 | /// |
| 758 | /// This function can be used to wrap calls to fallible functions ONLY when it |
| 759 | /// is known that the Error will always be a success value. E.g. |
| 760 | /// |
| 761 | /// @code{.cpp} |
| 762 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
| 763 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
| 764 | /// Expected<int> foo(bool DoFallibleOperation); |
| 765 | /// |
| 766 | /// int X = cantFail(foo(false)); |
| 767 | /// @endcode |
| 768 | template <typename T> |
| 769 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
| 770 | if (ValOrErr) |
| 771 | return std::move(*ValOrErr); |
| 772 | else { |
| 773 | if (!Msg) |
| 774 | Msg = "Failure value returned from cantFail wrapped call"; |
| 775 | #ifndef NDEBUG1 |
| 776 | std::string Str; |
| 777 | raw_string_ostream OS(Str); |
| 778 | auto E = ValOrErr.takeError(); |
| 779 | OS << Msg << "\n" << E; |
| 780 | Msg = OS.str().c_str(); |
| 781 | #endif |
| 782 | llvm_unreachable(Msg)__builtin_unreachable(); |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
| 787 | /// returns the contained reference. |
| 788 | /// |
| 789 | /// This function can be used to wrap calls to fallible functions ONLY when it |
| 790 | /// is known that the Error will always be a success value. E.g. |
| 791 | /// |
| 792 | /// @code{.cpp} |
| 793 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
| 794 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
| 795 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
| 796 | /// |
| 797 | /// Bar &X = cantFail(foo(false)); |
| 798 | /// @endcode |
| 799 | template <typename T> |
| 800 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
| 801 | if (ValOrErr) |
| 802 | return *ValOrErr; |
| 803 | else { |
| 804 | if (!Msg) |
| 805 | Msg = "Failure value returned from cantFail wrapped call"; |
| 806 | #ifndef NDEBUG1 |
| 807 | std::string Str; |
| 808 | raw_string_ostream OS(Str); |
| 809 | auto E = ValOrErr.takeError(); |
| 810 | OS << Msg << "\n" << E; |
| 811 | Msg = OS.str().c_str(); |
| 812 | #endif |
| 813 | llvm_unreachable(Msg)__builtin_unreachable(); |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | /// Helper for testing applicability of, and applying, handlers for |
| 818 | /// ErrorInfo types. |
| 819 | template <typename HandlerT> |
| 820 | class ErrorHandlerTraits |
| 821 | : public ErrorHandlerTraits<decltype( |
| 822 | &std::remove_reference<HandlerT>::type::operator())> {}; |
| 823 | |
| 824 | // Specialization functions of the form 'Error (const ErrT&)'. |
| 825 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
| 826 | public: |
| 827 | static bool appliesTo(const ErrorInfoBase &E) { |
| 828 | return E.template isA<ErrT>(); |
| 829 | } |
| 830 | |
| 831 | template <typename HandlerT> |
| 832 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
| 833 | assert(appliesTo(*E) && "Applying incorrect handler")((void)0); |
| 834 | return H(static_cast<ErrT &>(*E)); |
| 835 | } |
| 836 | }; |
| 837 | |
| 838 | // Specialization functions of the form 'void (const ErrT&)'. |
| 839 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
| 840 | public: |
| 841 | static bool appliesTo(const ErrorInfoBase &E) { |
| 842 | return E.template isA<ErrT>(); |
| 843 | } |
| 844 | |
| 845 | template <typename HandlerT> |
| 846 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
| 847 | assert(appliesTo(*E) && "Applying incorrect handler")((void)0); |
| 848 | H(static_cast<ErrT &>(*E)); |
| 849 | return Error::success(); |
| 850 | } |
| 851 | }; |
| 852 | |
| 853 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
| 854 | template <typename ErrT> |
| 855 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
| 856 | public: |
| 857 | static bool appliesTo(const ErrorInfoBase &E) { |
| 858 | return E.template isA<ErrT>(); |
| 859 | } |
| 860 | |
| 861 | template <typename HandlerT> |
| 862 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
| 863 | assert(appliesTo(*E) && "Applying incorrect handler")((void)0); |
| 864 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
| 865 | return H(std::move(SubE)); |
| 866 | } |
| 867 | }; |
| 868 | |
| 869 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
| 870 | template <typename ErrT> |
| 871 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
| 872 | public: |
| 873 | static bool appliesTo(const ErrorInfoBase &E) { |
| 874 | return E.template isA<ErrT>(); |
| 875 | } |
| 876 | |
| 877 | template <typename HandlerT> |
| 878 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
| 879 | assert(appliesTo(*E) && "Applying incorrect handler")((void)0); |
| 880 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
| 881 | H(std::move(SubE)); |
| 882 | return Error::success(); |
| 883 | } |
| 884 | }; |
| 885 | |
| 886 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
| 887 | template <typename C, typename RetT, typename ErrT> |
| 888 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
| 889 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
| 890 | |
| 891 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
| 892 | template <typename C, typename RetT, typename ErrT> |
| 893 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
| 894 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
| 895 | |
| 896 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
| 897 | template <typename C, typename RetT, typename ErrT> |
| 898 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
| 899 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
| 900 | |
| 901 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
| 902 | template <typename C, typename RetT, typename ErrT> |
| 903 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
| 904 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
| 905 | |
| 906 | /// Specialization for member functions of the form |
| 907 | /// 'RetT (std::unique_ptr<ErrT>)'. |
| 908 | template <typename C, typename RetT, typename ErrT> |
| 909 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
| 910 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
| 911 | |
| 912 | /// Specialization for member functions of the form |
| 913 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
| 914 | template <typename C, typename RetT, typename ErrT> |
| 915 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
| 916 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
| 917 | |
| 918 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
| 919 | return Error(std::move(Payload)); |
| 920 | } |
| 921 | |
| 922 | template <typename HandlerT, typename... HandlerTs> |
| 923 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
| 924 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
| 925 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
| 926 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
| 927 | std::move(Payload)); |
| 928 | return handleErrorImpl(std::move(Payload), |
| 929 | std::forward<HandlerTs>(Handlers)...); |
| 930 | } |
| 931 | |
| 932 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
| 933 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
| 934 | /// returned. |
| 935 | /// Because this function returns an error, its result must also be checked |
| 936 | /// or returned. If you intend to handle all errors use handleAllErrors |
| 937 | /// (which returns void, and will abort() on unhandled errors) instead. |
| 938 | template <typename... HandlerTs> |
| 939 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
| 940 | if (!E) |
| 941 | return Error::success(); |
| 942 | |
| 943 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
| 944 | |
| 945 | if (Payload->isA<ErrorList>()) { |
| 946 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
| 947 | Error R; |
| 948 | for (auto &P : List.Payloads) |
| 949 | R = ErrorList::join( |
| 950 | std::move(R), |
| 951 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
| 952 | return R; |
| 953 | } |
| 954 | |
| 955 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
| 956 | } |
| 957 | |
| 958 | /// Behaves the same as handleErrors, except that by contract all errors |
| 959 | /// *must* be handled by the given handlers (i.e. there must be no remaining |
| 960 | /// errors after running the handlers, or llvm_unreachable is called). |
| 961 | template <typename... HandlerTs> |
| 962 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
| 963 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
| 964 | } |
| 965 | |
| 966 | /// Check that E is a non-error, then drop it. |
| 967 | /// If E is an error, llvm_unreachable will be called. |
| 968 | inline void handleAllErrors(Error E) { |
| 969 | cantFail(std::move(E)); |
| 970 | } |
| 971 | |
| 972 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
| 973 | /// |
| 974 | /// If the incoming value is a success value it is returned unmodified. If it |
| 975 | /// is a failure value then it the contained error is passed to handleErrors. |
| 976 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
| 977 | /// is called to supply the final result. If handleErrors is not able to |
| 978 | /// handle all errors then the unhandled errors are returned. |
| 979 | /// |
| 980 | /// This utility enables the follow pattern: |
| 981 | /// |
| 982 | /// @code{.cpp} |
| 983 | /// enum FooStrategy { Aggressive, Conservative }; |
| 984 | /// Expected<Foo> foo(FooStrategy S); |
| 985 | /// |
| 986 | /// auto ResultOrErr = |
| 987 | /// handleExpected( |
| 988 | /// foo(Aggressive), |
| 989 | /// []() { return foo(Conservative); }, |
| 990 | /// [](AggressiveStrategyError&) { |
| 991 | /// // Implicitly conusme this - we'll recover by using a conservative |
| 992 | /// // strategy. |
| 993 | /// }); |
| 994 | /// |
| 995 | /// @endcode |
| 996 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
| 997 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
| 998 | HandlerTs &&... Handlers) { |
| 999 | if (ValOrErr) |
| 1000 | return ValOrErr; |
| 1001 | |
| 1002 | if (auto Err = handleErrors(ValOrErr.takeError(), |
| 1003 | std::forward<HandlerTs>(Handlers)...)) |
| 1004 | return std::move(Err); |
| 1005 | |
| 1006 | return RecoveryPath(); |
| 1007 | } |
| 1008 | |
| 1009 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
| 1010 | /// will be printed before the first one is logged. A newline will be printed |
| 1011 | /// after each error. |
| 1012 | /// |
| 1013 | /// This function is compatible with the helpers from Support/WithColor.h. You |
| 1014 | /// can pass any of them as the OS. Please consider using them instead of |
| 1015 | /// including 'error: ' in the ErrorBanner. |
| 1016 | /// |
| 1017 | /// This is useful in the base level of your program to allow clean termination |
| 1018 | /// (allowing clean deallocation of resources, etc.), while reporting error |
| 1019 | /// information to the user. |
| 1020 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); |
| 1021 | |
| 1022 | /// Write all error messages (if any) in E to a string. The newline character |
| 1023 | /// is used to separate error messages. |
| 1024 | inline std::string toString(Error E) { |
| 1025 | SmallVector<std::string, 2> Errors; |
| 1026 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { |
| 1027 | Errors.push_back(EI.message()); |
| 1028 | }); |
| 1029 | return join(Errors.begin(), Errors.end(), "\n"); |
| 1030 | } |
| 1031 | |
| 1032 | /// Consume a Error without doing anything. This method should be used |
| 1033 | /// only where an error can be considered a reasonable and expected return |
| 1034 | /// value. |
| 1035 | /// |
| 1036 | /// Uses of this method are potentially indicative of design problems: If it's |
| 1037 | /// legitimate to do nothing while processing an "error", the error-producer |
| 1038 | /// might be more clearly refactored to return an Optional<T>. |
| 1039 | inline void consumeError(Error Err) { |
| 1040 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); |
| 1041 | } |
| 1042 | |
| 1043 | /// Convert an Expected to an Optional without doing anything. This method |
| 1044 | /// should be used only where an error can be considered a reasonable and |
| 1045 | /// expected return value. |
| 1046 | /// |
| 1047 | /// Uses of this method are potentially indicative of problems: perhaps the |
| 1048 | /// error should be propagated further, or the error-producer should just |
| 1049 | /// return an Optional in the first place. |
| 1050 | template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) { |
| 1051 | if (E) |
| 1052 | return std::move(*E); |
| 1053 | consumeError(E.takeError()); |
| 1054 | return None; |
| 1055 | } |
| 1056 | |
| 1057 | /// Helper for converting an Error to a bool. |
| 1058 | /// |
| 1059 | /// This method returns true if Err is in an error state, or false if it is |
| 1060 | /// in a success state. Puts Err in a checked state in both cases (unlike |
| 1061 | /// Error::operator bool(), which only does this for success states). |
| 1062 | inline bool errorToBool(Error Err) { |
| 1063 | bool IsError = static_cast<bool>(Err); |
| 1064 | if (IsError) |
| 1065 | consumeError(std::move(Err)); |
| 1066 | return IsError; |
| 1067 | } |
| 1068 | |
| 1069 | /// Helper for Errors used as out-parameters. |
| 1070 | /// |
| 1071 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
| 1072 | /// is passed to a function or method by reference, rather than being returned. |
| 1073 | /// In such cases it is helpful to set the checked bit on entry to the function |
| 1074 | /// so that the error can be written to (unchecked Errors abort on assignment) |
| 1075 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
| 1076 | /// to check the result. This helper performs these actions automatically using |
| 1077 | /// RAII: |
| 1078 | /// |
| 1079 | /// @code{.cpp} |
| 1080 | /// Result foo(Error &Err) { |
| 1081 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
| 1082 | /// // <body of foo> |
| 1083 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
| 1084 | /// } |
| 1085 | /// @endcode |
| 1086 | /// |
| 1087 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
| 1088 | /// used with optional Errors (Error pointers that are allowed to be null). If |
| 1089 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
| 1090 | /// created inside every condition that verified that Error was non-null. By |
| 1091 | /// taking an Error pointer we can just create one instance at the top of the |
| 1092 | /// function. |
| 1093 | class ErrorAsOutParameter { |
| 1094 | public: |
| 1095 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
| 1096 | // Raise the checked bit if Err is success. |
| 1097 | if (Err) |
| 1098 | (void)!!*Err; |
| 1099 | } |
| 1100 | |
| 1101 | ~ErrorAsOutParameter() { |
| 1102 | // Clear the checked bit. |
| 1103 | if (Err && !*Err) |
| 1104 | *Err = Error::success(); |
| 1105 | } |
| 1106 | |
| 1107 | private: |
| 1108 | Error *Err; |
| 1109 | }; |
| 1110 | |
| 1111 | /// Helper for Expected<T>s used as out-parameters. |
| 1112 | /// |
| 1113 | /// See ErrorAsOutParameter. |
| 1114 | template <typename T> |
| 1115 | class ExpectedAsOutParameter { |
| 1116 | public: |
| 1117 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
| 1118 | : ValOrErr(ValOrErr) { |
| 1119 | if (ValOrErr) |
| 1120 | (void)!!*ValOrErr; |
| 1121 | } |
| 1122 | |
| 1123 | ~ExpectedAsOutParameter() { |
| 1124 | if (ValOrErr) |
| 1125 | ValOrErr->setUnchecked(); |
| 1126 | } |
| 1127 | |
| 1128 | private: |
| 1129 | Expected<T> *ValOrErr; |
| 1130 | }; |
| 1131 | |
| 1132 | /// This class wraps a std::error_code in a Error. |
| 1133 | /// |
| 1134 | /// This is useful if you're writing an interface that returns a Error |
| 1135 | /// (or Expected) and you want to call code that still returns |
| 1136 | /// std::error_codes. |
| 1137 | class ECError : public ErrorInfo<ECError> { |
| 1138 | friend Error errorCodeToError(std::error_code); |
| 1139 | |
| 1140 | virtual void anchor() override; |
| 1141 | |
| 1142 | public: |
| 1143 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
| 1144 | std::error_code convertToErrorCode() const override { return EC; } |
| 1145 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
| 1146 | |
| 1147 | // Used by ErrorInfo::classID. |
| 1148 | static char ID; |
| 1149 | |
| 1150 | protected: |
| 1151 | ECError() = default; |
| 1152 | ECError(std::error_code EC) : EC(EC) {} |
| 1153 | |
| 1154 | std::error_code EC; |
| 1155 | }; |
| 1156 | |
| 1157 | /// The value returned by this function can be returned from convertToErrorCode |
| 1158 | /// for Error values where no sensible translation to std::error_code exists. |
| 1159 | /// It should only be used in this situation, and should never be used where a |
| 1160 | /// sensible conversion to std::error_code is available, as attempts to convert |
| 1161 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
| 1162 | ///error to try to convert such a value). |
| 1163 | std::error_code inconvertibleErrorCode(); |
| 1164 | |
| 1165 | /// Helper for converting an std::error_code to a Error. |
| 1166 | Error errorCodeToError(std::error_code EC); |
| 1167 | |
| 1168 | /// Helper for converting an ECError to a std::error_code. |
| 1169 | /// |
| 1170 | /// This method requires that Err be Error() or an ECError, otherwise it |
| 1171 | /// will trigger a call to abort(). |
| 1172 | std::error_code errorToErrorCode(Error Err); |
| 1173 | |
| 1174 | /// Convert an ErrorOr<T> to an Expected<T>. |
| 1175 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
| 1176 | if (auto EC = EO.getError()) |
| 1177 | return errorCodeToError(EC); |
| 1178 | return std::move(*EO); |
| 1179 | } |
| 1180 | |
| 1181 | /// Convert an Expected<T> to an ErrorOr<T>. |
| 1182 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
| 1183 | if (auto Err = E.takeError()) |
| 1184 | return errorToErrorCode(std::move(Err)); |
| 1185 | return std::move(*E); |
| 1186 | } |
| 1187 | |
| 1188 | /// This class wraps a string in an Error. |
| 1189 | /// |
| 1190 | /// StringError is useful in cases where the client is not expected to be able |
| 1191 | /// to consume the specific error message programmatically (for example, if the |
| 1192 | /// error message is to be presented to the user). |
| 1193 | /// |
| 1194 | /// StringError can also be used when additional information is to be printed |
| 1195 | /// along with a error_code message. Depending on the constructor called, this |
| 1196 | /// class can either display: |
| 1197 | /// 1. the error_code message (ECError behavior) |
| 1198 | /// 2. a string |
| 1199 | /// 3. the error_code message and a string |
| 1200 | /// |
| 1201 | /// These behaviors are useful when subtyping is required; for example, when a |
| 1202 | /// specific library needs an explicit error type. In the example below, |
| 1203 | /// PDBError is derived from StringError: |
| 1204 | /// |
| 1205 | /// @code{.cpp} |
| 1206 | /// Expected<int> foo() { |
| 1207 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, |
| 1208 | /// "Additional information"); |
| 1209 | /// } |
| 1210 | /// @endcode |
| 1211 | /// |
| 1212 | class StringError : public ErrorInfo<StringError> { |
| 1213 | public: |
| 1214 | static char ID; |
| 1215 | |
| 1216 | // Prints EC + S and converts to EC |
| 1217 | StringError(std::error_code EC, const Twine &S = Twine()); |
| 1218 | |
| 1219 | // Prints S and converts to EC |
| 1220 | StringError(const Twine &S, std::error_code EC); |
| 1221 | |
| 1222 | void log(raw_ostream &OS) const override; |
| 1223 | std::error_code convertToErrorCode() const override; |
| 1224 | |
| 1225 | const std::string &getMessage() const { return Msg; } |
| 1226 | |
| 1227 | private: |
| 1228 | std::string Msg; |
| 1229 | std::error_code EC; |
| 1230 | const bool PrintMsgOnly = false; |
| 1231 | }; |
| 1232 | |
| 1233 | /// Create formatted StringError object. |
| 1234 | template <typename... Ts> |
| 1235 | inline Error createStringError(std::error_code EC, char const *Fmt, |
| 1236 | const Ts &... Vals) { |
| 1237 | std::string Buffer; |
| 1238 | raw_string_ostream Stream(Buffer); |
| 1239 | Stream << format(Fmt, Vals...); |
| 1240 | return make_error<StringError>(Stream.str(), EC); |
| 1241 | } |
| 1242 | |
| 1243 | Error createStringError(std::error_code EC, char const *Msg); |
| 1244 | |
| 1245 | inline Error createStringError(std::error_code EC, const Twine &S) { |
| 1246 | return createStringError(EC, S.str().c_str()); |
| 1247 | } |
| 1248 | |
| 1249 | template <typename... Ts> |
| 1250 | inline Error createStringError(std::errc EC, char const *Fmt, |
| 1251 | const Ts &... Vals) { |
| 1252 | return createStringError(std::make_error_code(EC), Fmt, Vals...); |
| 1253 | } |
| 1254 | |
| 1255 | /// This class wraps a filename and another Error. |
| 1256 | /// |
| 1257 | /// In some cases, an error needs to live along a 'source' name, in order to |
| 1258 | /// show more detailed information to the user. |
| 1259 | class FileError final : public ErrorInfo<FileError> { |
| 1260 | |
| 1261 | friend Error createFileError(const Twine &, Error); |
| 1262 | friend Error createFileError(const Twine &, size_t, Error); |
| 1263 | |
| 1264 | public: |
| 1265 | void log(raw_ostream &OS) const override { |
| 1266 | assert(Err && !FileName.empty() && "Trying to log after takeError().")((void)0); |
| 1267 | OS << "'" << FileName << "': "; |
| 1268 | if (Line.hasValue()) |
| 1269 | OS << "line " << Line.getValue() << ": "; |
| 1270 | Err->log(OS); |
| 1271 | } |
| 1272 | |
| 1273 | StringRef getFileName() { return FileName; } |
| 1274 | |
| 1275 | Error takeError() { return Error(std::move(Err)); } |
| 1276 | |
| 1277 | std::error_code convertToErrorCode() const override; |
| 1278 | |
| 1279 | // Used by ErrorInfo::classID. |
| 1280 | static char ID; |
| 1281 | |
| 1282 | private: |
| 1283 | FileError(const Twine &F, Optional<size_t> LineNum, |
| 1284 | std::unique_ptr<ErrorInfoBase> E) { |
| 1285 | assert(E && "Cannot create FileError from Error success value.")((void)0); |
| 1286 | assert(!F.isTriviallyEmpty() &&((void)0) |
| 1287 | "The file name provided to FileError must not be empty.")((void)0); |
| 1288 | FileName = F.str(); |
| 1289 | Err = std::move(E); |
| 1290 | Line = std::move(LineNum); |
| 1291 | } |
| 1292 | |
| 1293 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { |
| 1294 | std::unique_ptr<ErrorInfoBase> Payload; |
| 1295 | handleAllErrors(std::move(E), |
| 1296 | [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error { |
| 1297 | Payload = std::move(EIB); |
| 1298 | return Error::success(); |
| 1299 | }); |
| 1300 | return Error( |
| 1301 | std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload)))); |
| 1302 | } |
| 1303 | |
| 1304 | std::string FileName; |
| 1305 | Optional<size_t> Line; |
| 1306 | std::unique_ptr<ErrorInfoBase> Err; |
| 1307 | }; |
| 1308 | |
| 1309 | /// Concatenate a source file path and/or name with an Error. The resulting |
| 1310 | /// Error is unchecked. |
| 1311 | inline Error createFileError(const Twine &F, Error E) { |
| 1312 | return FileError::build(F, Optional<size_t>(), std::move(E)); |
| 1313 | } |
| 1314 | |
| 1315 | /// Concatenate a source file path and/or name with line number and an Error. |
| 1316 | /// The resulting Error is unchecked. |
| 1317 | inline Error createFileError(const Twine &F, size_t Line, Error E) { |
| 1318 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); |
| 1319 | } |
| 1320 | |
| 1321 | /// Concatenate a source file path and/or name with a std::error_code |
| 1322 | /// to form an Error object. |
| 1323 | inline Error createFileError(const Twine &F, std::error_code EC) { |
| 1324 | return createFileError(F, errorCodeToError(EC)); |
| 1325 | } |
| 1326 | |
| 1327 | /// Concatenate a source file path and/or name with line number and |
| 1328 | /// std::error_code to form an Error object. |
| 1329 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { |
| 1330 | return createFileError(F, Line, errorCodeToError(EC)); |
| 1331 | } |
| 1332 | |
| 1333 | Error createFileError(const Twine &F, ErrorSuccess) = delete; |
| 1334 | |
| 1335 | /// Helper for check-and-exit error handling. |
| 1336 | /// |
| 1337 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
| 1338 | /// |
| 1339 | class ExitOnError { |
| 1340 | public: |
| 1341 | /// Create an error on exit helper. |
| 1342 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) |
| 1343 | : Banner(std::move(Banner)), |
| 1344 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
| 1345 | |
| 1346 | /// Set the banner string for any errors caught by operator(). |
| 1347 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
| 1348 | |
| 1349 | /// Set the exit-code mapper function. |
| 1350 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
| 1351 | this->GetExitCode = std::move(GetExitCode); |
| 1352 | } |
| 1353 | |
| 1354 | /// Check Err. If it's in a failure state log the error(s) and exit. |
| 1355 | void operator()(Error Err) const { checkError(std::move(Err)); } |
| 1356 | |
| 1357 | /// Check E. If it's in a success state then return the contained value. If |
| 1358 | /// it's in a failure state log the error(s) and exit. |
| 1359 | template <typename T> T operator()(Expected<T> &&E) const { |
| 1360 | checkError(E.takeError()); |
| 1361 | return std::move(*E); |
| 1362 | } |
| 1363 | |
| 1364 | /// Check E. If it's in a success state then return the contained reference. If |
| 1365 | /// it's in a failure state log the error(s) and exit. |
| 1366 | template <typename T> T& operator()(Expected<T&> &&E) const { |
| 1367 | checkError(E.takeError()); |
| 1368 | return *E; |
| 1369 | } |
| 1370 | |
| 1371 | private: |
| 1372 | void checkError(Error Err) const { |
| 1373 | if (Err) { |
| 1374 | int ExitCode = GetExitCode(Err); |
| 1375 | logAllUnhandledErrors(std::move(Err), errs(), Banner); |
| 1376 | exit(ExitCode); |
| 1377 | } |
| 1378 | } |
| 1379 | |
| 1380 | std::string Banner; |
| 1381 | std::function<int(const Error &)> GetExitCode; |
| 1382 | }; |
| 1383 | |
| 1384 | /// Conversion from Error to LLVMErrorRef for C error bindings. |
| 1385 | inline LLVMErrorRef wrap(Error Err) { |
| 1386 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); |
| 1387 | } |
| 1388 | |
| 1389 | /// Conversion from LLVMErrorRef to Error for C error bindings. |
| 1390 | inline Error unwrap(LLVMErrorRef ErrRef) { |
| 1391 | return Error(std::unique_ptr<ErrorInfoBase>( |
| 1392 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); |
| 1393 | } |
| 1394 | |
| 1395 | } // end namespace llvm |
| 1396 | |
| 1397 | #endif // LLVM_SUPPORT_ERROR_H |