Strings.cpp revision 360784
1//===- Strings.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 "lld/Common/Strings.h" 10#include "lld/Common/ErrorHandler.h" 11#include "lld/Common/LLVM.h" 12#include "llvm/Demangle/Demangle.h" 13#include "llvm/Support/GlobPattern.h" 14#include <algorithm> 15#include <mutex> 16#include <vector> 17 18using namespace llvm; 19using namespace lld; 20 21// Returns the demangled C++ symbol name for name. 22std::string lld::demangleItanium(StringRef name) { 23 // itaniumDemangle can be used to demangle strings other than symbol 24 // names which do not necessarily start with "_Z". Name can be 25 // either a C or C++ symbol. Don't call demangle if the name 26 // does not look like a C++ symbol name to avoid getting unexpected 27 // result for a C symbol that happens to match a mangled type name. 28 if (!name.startswith("_Z")) 29 return name; 30 31 return demangle(name); 32} 33 34StringMatcher::StringMatcher(ArrayRef<StringRef> pat) { 35 for (StringRef s : pat) { 36 Expected<GlobPattern> pat = GlobPattern::create(s); 37 if (!pat) 38 error(toString(pat.takeError())); 39 else 40 patterns.push_back(*pat); 41 } 42} 43 44bool StringMatcher::match(StringRef s) const { 45 for (const GlobPattern &pat : patterns) 46 if (pat.match(s)) 47 return true; 48 return false; 49} 50 51// Converts a hex string (e.g. "deadbeef") to a vector. 52std::vector<uint8_t> lld::parseHex(StringRef s) { 53 std::vector<uint8_t> hex; 54 while (!s.empty()) { 55 StringRef b = s.substr(0, 2); 56 s = s.substr(2); 57 uint8_t h; 58 if (!to_integer(b, h, 16)) { 59 error("not a hexadecimal value: " + b); 60 return {}; 61 } 62 hex.push_back(h); 63 } 64 return hex; 65} 66 67// Returns true if S is valid as a C language identifier. 68bool lld::isValidCIdentifier(StringRef s) { 69 return !s.empty() && (isAlpha(s[0]) || s[0] == '_') && 70 std::all_of(s.begin() + 1, s.end(), 71 [](char c) { return c == '_' || isAlnum(c); }); 72} 73 74// Write the contents of the a buffer to a file 75void lld::saveBuffer(StringRef buffer, const Twine &path) { 76 std::error_code ec; 77 raw_fd_ostream os(path.str(), ec, sys::fs::OpenFlags::OF_None); 78 if (ec) 79 error("cannot create " + path + ": " + ec.message()); 80 os << buffer; 81} 82