diff --git a/llvm/include/llvm/Demangle/Demangle.h b/llvm/include/llvm/Demangle/Demangle.h --- a/llvm/include/llvm/Demangle/Demangle.h +++ b/llvm/include/llvm/Demangle/Demangle.h @@ -57,6 +57,9 @@ char *buf, size_t *n_buf, int *status, MSDemangleFlags Flags = MSDF_None); +// Demangles a Rust v0 mangled symbol. The API follows that of __cxa_demangle. +char *rustDemangle(const char *MangledName, char *Buf, size_t *N, int *Status); + /// Attempt to demangle a string using different demangling schemes. /// The function uses heuristics to determine which demangling scheme to use. /// \param MangledName - reference to string to demangle. diff --git a/llvm/include/llvm/Demangle/RustDemangle.h b/llvm/include/llvm/Demangle/RustDemangle.h new file mode 100644 --- /dev/null +++ b/llvm/include/llvm/Demangle/RustDemangle.h @@ -0,0 +1,96 @@ +//===--- RustDemangle.h -----------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_DEMANGLE_RUSTDEMANGLE_H +#define LLVM_DEMANGLE_RUSTDEMANGLE_H + +#include "llvm/Demangle/DemangleConfig.h" +#include "llvm/Demangle/StringView.h" +#include "llvm/Demangle/Utility.h" + +namespace llvm { +namespace rust_demangle { + +using llvm::itanium_demangle::OutputStream; +using llvm::itanium_demangle::StringView; + +struct Identifier { + StringView Name; + bool Punycode; + + bool empty() const { return Name.empty(); } +}; + +class Demangler { + // Maximum recursion level. Used to avoid stack overflow. + const size_t MaxRecursionLevel; + // Current recursion level. + size_t RecursionLevel; + + // Input string that is being demangled (without "_R" prefix if any). + StringView Input; + // Position in the input string. + size_t Position; + + // True if an error occurred. + bool Error; + +public: + // Demangled output. + OutputStream Output; + + Demangler(size_t MaxRecursionLevel_ = 500); + + bool demangle(const char *Mangled, size_t MangledLen); + +private: + void demanglePath(); + + Identifier parseIdentifier(); + uint64_t parseOptionalBase62Number(char Tag); + uint64_t parseBase62Number(); + uint64_t parseDecimalNumber(); + + void printIdentifier(Identifier Ident); + + void print(StringView S) { + if (Error) + return; + + Output += S; + } + + char look() const { + if (Error || Position >= Input.size()) + return 0; + + return Input[Position]; + } + + char consume() { + if (Error || Position >= Input.size()) { + Error = true; + return 0; + } + + return Input[Position++]; + } + + bool consumeIf(char Prefix) { + if (Error || Position >= Input.size() || Input[Position] != Prefix) + return false; + + Position += 1; + return true; + } +}; + +} // namespace rust_demangle +} // namespace llvm + +#endif diff --git a/llvm/lib/Demangle/CMakeLists.txt b/llvm/lib/Demangle/CMakeLists.txt --- a/llvm/lib/Demangle/CMakeLists.txt +++ b/llvm/lib/Demangle/CMakeLists.txt @@ -3,6 +3,7 @@ ItaniumDemangle.cpp MicrosoftDemangle.cpp MicrosoftDemangleNodes.cpp + RustDemangle.cpp ADDITIONAL_HEADER_DIRS "${LLVM_MAIN_INCLUDE_DIR}/llvm/Demangle" diff --git a/llvm/lib/Demangle/RustDemangle.cpp b/llvm/lib/Demangle/RustDemangle.cpp new file mode 100644 --- /dev/null +++ b/llvm/lib/Demangle/RustDemangle.cpp @@ -0,0 +1,288 @@ +//===--- RustDemangle.cpp ---------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines a demangler for Rust v0 mangled symbols. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Demangle/RustDemangle.h" +#include "llvm/Demangle/Demangle.h" + +#include +#include +#include + +using namespace llvm; +using namespace rust_demangle; + +char *llvm::rustDemangle(const char *MangledName, char *Buf, size_t *N, + int *Status) { + if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) { + if (Status != nullptr) + *Status = demangle_invalid_args; + return nullptr; + } + + // Return early if mangled name doesn't look like a Rust symbol. + if (MangledName[0] != '_' || MangledName[1] != 'R') { + if (Status != nullptr) + *Status = demangle_invalid_mangled_name; + return nullptr; + } + + Demangler D; + if (!initializeOutputStream(nullptr, nullptr, D.Output, 1024)) { + if (Status != nullptr) + *Status = demangle_memory_alloc_failure; + return nullptr; + } + + if (!D.demangle(MangledName, strlen(MangledName))) { + if (Status != nullptr) + *Status = demangle_invalid_mangled_name; + std::free(D.Output.getBuffer()); + return nullptr; + } + + D.Output += '\0'; + char *Demangled = D.Output.getBuffer(); + const size_t DemangledLen = D.Output.getCurrentPosition(); + + if (Buf != nullptr) { + if (DemangledLen <= *N) { + std::memcpy(Buf, Demangled, DemangledLen); + std::free(Demangled); + Demangled = Buf; + } else { + std::free(Buf); + } + } + + if (N != nullptr) + *N = DemangledLen; + + if (Status != nullptr) + *Status = demangle_success; + + return Demangled; +} + +Demangler::Demangler(size_t MaxRecursionLevel_) + : MaxRecursionLevel(MaxRecursionLevel_) {} + +static inline bool isDigit(const char C) { return '0' <= C && C <= '9'; } + +static inline bool isLower(const char C) { return 'a' <= C && C <= 'z'; } + +static inline bool isUpper(const char C) { return 'A' <= C && C <= 'Z'; } + +/// Returns true if C is a valid mangled character: <0-9a-zA-Z_>. +static inline bool isValid(const char C) { + return isDigit(C) || isLower(C) || isUpper(C) || C == '_'; +} + +// Demangles Rust v0 mangled symbol. Returns true when successful, and false +// otherwise. The demangled symbol is stored in Output field. It is +// responsibility of the caller to free the memory behind the output stream. +// +// = "_R" [] [] +bool Demangler::demangle(const char *Mangled, size_t MangledLength) { + Input = StringView(Mangled, MangledLength); + Position = 0; + Error = false; + RecursionLevel = 0; + + if (!Input.consumeFront("_R")) { + Error = true; + return !Error; + } + + demanglePath(); + + if (Position != Input.size()) + Error = true; + + return !Error; +} + +// = "C" // crate root +// | "M" // (inherent impl) +// | "X" // (trait impl) +// | "Y" // (trait definition) +// | "N" // ...::ident (nested path) +// | "I" {} "E" // ... (generic args) +// | +// = [] +// = "C" // closure +// | "S" // shim +// | // other special namespaces +// | // internal namespaces +void Demangler::demanglePath() { + if (Error || RecursionLevel >= MaxRecursionLevel) { + Error = true; + return; + } + RecursionLevel += 1; + + switch (consume()) { + case 'C': { + parseOptionalBase62Number('s'); + Identifier Ident = parseIdentifier(); + printIdentifier(Ident); + break; + } + case 'N': { + const char NS = consume(); + if (!isLower(NS) && !isUpper(NS)) { + Error = true; + break; + } + demanglePath(); + + parseOptionalBase62Number('s'); + Identifier Ident = parseIdentifier(); + + if (!Ident.empty()) { + print("::"); + printIdentifier(Ident); + } + break; + } + default: + Error = true; + break; + } + + RecursionLevel -= 1; +} + +// = ["u"] ["_"] +Identifier Demangler::parseIdentifier() { + const bool Punycode = consumeIf('u'); + const uint64_t Bytes = parseDecimalNumber(); + consumeIf('_'); + + if (Error || Bytes > Input.size() - Position) { + Error = true; + return {}; + } + const StringView S = Input.substr(Position, Bytes); + Position += Bytes; + + for (const char C : S) { + if (!isValid(C)) { + Error = true; + return {}; + } + } + + return {S, Punycode}; +} + +// Parses optional base 62 number. The presence of a number is determined +// using Tag. Returns 0 when tag is absent and value + 1 otherwise. +uint64_t Demangler::parseOptionalBase62Number(char Tag) { + if (!consumeIf(Tag)) + return 0; + + const uint64_t N = parseBase62Number(); + if (Error || N == std::numeric_limits::max()) { + Error = true; + return 0; + } + return N + 1; +} + +// Parses base 62 number with <0-9a-zA-Z> as digits. Number is terminated by +// "_". All values are offset by 1, so that "_" encodes 0, "0_" encodes 1, +// "1_" encodes 2, etc. +// +// = {<0-9a-zA-Z>} "_" +uint64_t Demangler::parseBase62Number() { + uint64_t Value = 0; + if (consumeIf('_')) { + return Value; + } + + const uint64_t Max = std::numeric_limits::max(); + while (true) { + uint64_t Digit; + const char C = consume(); + + if (C == '_') { + break; + } else if (isDigit(C)) { + Digit = C - '0'; + } else if (isLower(C)) { + Digit = 10 + (C - 'a'); + } else if (isUpper(C)) { + Digit = 10 + 26 + (C - 'A'); + } else { + Error = true; + return 0; + } + + if (Value > (Max - Digit) / 62) { + Error = true; + return 0; + } + Value = Value * 62 + Digit; + } + + if (Value > Max - 1) { + Error = true; + return 0; + } + Value += 1; + + return Value; +} + +// Parses a decimal number that had been encoded without any leading zeros. +// +// = "0" +// | <1-9> {<0-9>} +uint64_t Demangler::parseDecimalNumber() { + const char C = look(); + if (!isDigit(C)) { + Error = true; + return 0; + } + + if (C == '0') { + consume(); + return 0; + } + + const uint64_t Max = std::numeric_limits::max(); + uint64_t Value = 0u; + + while (isDigit(look())) { + if (Value > Max / 10) { + Error = true; + return 0; + } + Value *= 10; + + const uint64_t D = consume() - '0'; + if (Value > Max - D) { + Error = true; + return 0; + } + Value += D; + } + + return Value; +} + +void Demangler::printIdentifier(Identifier Ident) { + if (Error) + return; + + print(Ident.Name); +} diff --git a/llvm/test/Demangle/rust.test b/llvm/test/Demangle/rust.test new file mode 100644 --- /dev/null +++ b/llvm/test/Demangle/rust.test @@ -0,0 +1,48 @@ +RUN: llvm-cxxfilt -n < %s | FileCheck --match-full-lines %s + +CHECK: a::main + _RNvC1a4main + +CHECK: hello::rust + _RNvCshGpAVYOtgW1_5hello4rust + +CHECK: a::b::c + _RNvNvC1a1b1c + +; Invalid mangled characters + +CHECK: _RNvC2a.1c + _RNvC2a.1c + +CHECK: _RNvC2a$1c + _RNvC2a$1c + +; Invalid identifier length (UINT64_MAX + 3, which happens to be ok after a wraparound). + +CHECK: _RNvC2ab18446744073709551618xy + _RNvC2ab18446744073709551618xy + +; Unsupported mangling version + +CHECK: _R0NvC1a4main + _R0NvC1a4main + +CHECK: _R1NvC1a4main + _R1NvC1a4main + +CHECK: _R199999999999999999999999999NvC1a4main + _R199999999999999999999999999NvC1a4main + +; Early EOF + +CHECK: _RNv + _RNv + +CHECK: _RNvC + _RNvC + +CHECK: _RNvC1a5main + _RNvC1a5main + +CHECK: _RNvC1a20abc + _RNvC1a20abc diff --git a/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp b/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp --- a/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp +++ b/llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp @@ -97,6 +97,11 @@ Undecorated = itaniumDemangle(DecoratedStr + 6, nullptr, nullptr, &Status); } + if (!Undecorated && + (DecoratedLength >= 2 && strncmp(DecoratedStr, "_R", 2) == 0)) { + Undecorated = rustDemangle(DecoratedStr, nullptr, nullptr, &Status); + } + std::string Result(Undecorated ? Prefix + Undecorated : Mangled); free(Undecorated); return Result; diff --git a/llvm/unittests/Demangle/CMakeLists.txt b/llvm/unittests/Demangle/CMakeLists.txt --- a/llvm/unittests/Demangle/CMakeLists.txt +++ b/llvm/unittests/Demangle/CMakeLists.txt @@ -7,5 +7,6 @@ DemangleTest.cpp ItaniumDemangleTest.cpp PartialDemangleTest.cpp + RustDemangleTest.cpp StringViewTest.cpp ) diff --git a/llvm/unittests/Demangle/RustDemangleTest.cpp b/llvm/unittests/Demangle/RustDemangleTest.cpp new file mode 100644 --- /dev/null +++ b/llvm/unittests/Demangle/RustDemangleTest.cpp @@ -0,0 +1,90 @@ +//===------------------ RustDemangleTest.cpp ------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "llvm/Demangle/Demangle.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include + +TEST(RustDemangle, Success) { + char *Demangled = + llvm::rustDemangle("_RNvC1a4main", nullptr, nullptr, nullptr); + EXPECT_STREQ(Demangled, "a::main"); + std::free(Demangled); + + // With status. + int Status = 0; + Demangled = llvm::rustDemangle("_RNvC1a4main", nullptr, nullptr, &Status); + EXPECT_EQ(Status, llvm::demangle_success); + EXPECT_STREQ(Demangled, "a::main"); + std::free(Demangled); + + // With status and length. + size_t N = 0; + Demangled = llvm::rustDemangle("_RNvC1a4main", nullptr, &N, &Status); + EXPECT_EQ(Status, llvm::demangle_success); + EXPECT_EQ(N, 8u); + EXPECT_STREQ(Demangled, "a::main"); + std::free(Demangled); +} + +TEST(RustDemangle, Invalid) { + int Status = 0; + char *Demangled = nullptr; + + // Invalid prefix. + Demangled = llvm::rustDemangle("_ABCDEF", nullptr, nullptr, &Status); + EXPECT_EQ(Status, llvm::demangle_invalid_mangled_name); + EXPECT_EQ(Demangled, nullptr); + + // Correct prefix but still invalid. + Demangled = llvm::rustDemangle("_RRR", nullptr, nullptr, &Status); + EXPECT_EQ(Status, llvm::demangle_invalid_mangled_name); + EXPECT_EQ(Demangled, nullptr); +} + +TEST(RustDemangle, OutputBufferWithoutLength) { + char *Buffer = static_cast(std::malloc(1024)); + ASSERT_NE(Buffer, nullptr); + + int Status = 0; + char *Demangled = + llvm::rustDemangle("_RNvC1a4main", Buffer, nullptr, &Status); + + EXPECT_EQ(Status, llvm::demangle_invalid_args); + EXPECT_EQ(Demangled, nullptr); + std::free(Buffer); +} + +TEST(RustDemangle, OutputBuffer) { + size_t N = 1024; + char *Buffer = static_cast(std::malloc(N)); + ASSERT_NE(Buffer, nullptr); + + int Status = 0; + char *Demangled = llvm::rustDemangle("_RNvC1a4main", Buffer, &N, &Status); + + EXPECT_EQ(Status, llvm::demangle_success); + EXPECT_EQ(Demangled, Buffer); + EXPECT_STREQ(Demangled, "a::main"); + std::free(Demangled); +} + +TEST(RustDemangle, SmallOutputBuffer) { + size_t N = 1; + char *Buffer = static_cast(std::malloc(N)); + ASSERT_NE(Buffer, nullptr); + + int Status = 0; + char *Demangled = llvm::rustDemangle("_RNvC1a4main", Buffer, &N, &Status); + + EXPECT_EQ(Status, llvm::demangle_success); + EXPECT_STREQ(Demangled, "a::main"); + std::free(Demangled); +}