1 //===- Error.cpp - system_error extensions for lld --------------*- C++ -*-===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lld/Core/Error.h" 11 #include "llvm/ADT/Twine.h" 12 #include "llvm/Support/ErrorHandling.h" 13 #include <mutex> 14 #include <string> 15 #include <vector> 16 17 using namespace lld; 18 19 namespace { 20 class _YamlReaderErrorCategory : public std::error_category { 21 public: name() const22 const char* name() const noexcept override { 23 return "lld.yaml.reader"; 24 } 25 message(int ev) const26 std::string message(int ev) const override { 27 switch (static_cast<YamlReaderError>(ev)) { 28 case YamlReaderError::unknown_keyword: 29 return "Unknown keyword found in yaml file"; 30 case YamlReaderError::illegal_value: 31 return "Bad value found in yaml file"; 32 } 33 llvm_unreachable("An enumerator of YamlReaderError does not have a " 34 "message defined."); 35 } 36 }; 37 } // end anonymous namespace 38 YamlReaderCategory()39const std::error_category &lld::YamlReaderCategory() { 40 static _YamlReaderErrorCategory o; 41 return o; 42 } 43 44 namespace lld { 45 46 /// Temporary class to enable make_dynamic_error_code() until 47 /// llvm::ErrorOr<> is updated to work with error encapsulations 48 /// other than error_code. 49 class dynamic_error_category : public std::error_category { 50 public: 51 ~dynamic_error_category() override = default; 52 name() const53 const char *name() const noexcept override { 54 return "lld.dynamic_error"; 55 } 56 message(int ev) const57 std::string message(int ev) const override { 58 assert(ev >= 0); 59 assert(ev < (int)_messages.size()); 60 // The value is an index into the string vector. 61 return _messages[ev]; 62 } 63 add(std::string msg)64 int add(std::string msg) { 65 std::lock_guard<std::recursive_mutex> lock(_mutex); 66 // Value zero is always the successs value. 67 if (_messages.empty()) 68 _messages.push_back("Success"); 69 _messages.push_back(msg); 70 // Return the index of the string just appended. 71 return _messages.size() - 1; 72 } 73 74 private: 75 std::vector<std::string> _messages; 76 std::recursive_mutex _mutex; 77 }; 78 79 static dynamic_error_category categorySingleton; 80 make_dynamic_error_code(StringRef msg)81std::error_code make_dynamic_error_code(StringRef msg) { 82 return std::error_code(categorySingleton.add(msg), categorySingleton); 83 } 84 85 char GenericError::ID = 0; 86 GenericError(Twine Msg)87GenericError::GenericError(Twine Msg) : Msg(Msg.str()) { } 88 log(raw_ostream & OS) const89void GenericError::log(raw_ostream &OS) const { 90 OS << Msg; 91 } 92 93 } // namespace lld 94