Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-6108 - Port of rustc-demangle

Donough Liu8cd0d6f57d3c
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerLegacy.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerLegacy.java
index 946d8eb4a8..302717d0d7 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerLegacy.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerLegacy.java
@@ -42,24 +42,45 @@ public class RustDemanglerLegacy {
}
ArrayList<String> elements = new ArrayList<String>();
- char[] chars = symbol.toCharArray();
int i = 0;
+ int length = symbol.length();
- while (chars[i] != 'E') {
- if (chars[i] < '0' || chars[i] > '9') {
+ while (i < length && symbol.charAt(i) != 'E') {
+ char c = symbol.charAt(i);
+ if (c < '0' || c > '9') {
return null;
}
- int l = 0;
- while (chars[i + l] >= '0' && chars[i + l] <= '9') {
- l += 1;
+ int start = i;
+ while (i < length && symbol.charAt(i) >= '0' && symbol.charAt(i) <= '9') {
+ i++;
+ }
+ if (i >= length) {
+ return null; // missing element after length prefix
+ }
+
+ int elementLength;
+ try {
+ elementLength = Integer.parseInt(symbol.substring(start, i));
+ }
+ catch (NumberFormatException e) {
+ return null;
+ }
+
+ if (elementLength < 0 || i + elementLength > length) {
+ return null;
}
- String lengthString = symbol.substring(i, i + l);
- int length = Integer.parseInt(lengthString);
- String element = symbol.substring(i + l, i + l + length);
+ String element = symbol.substring(i, i + elementLength);
+ if (element.startsWith("_$")) {
+ element = element.substring(1);
+ }
elements.add(element);
- i = i + l + length;
+ i += elementLength;
+ }
+
+ if (i >= length || symbol.charAt(i) != 'E') {
+ return null;
}
for (int j = 0; j < elements.size(); j++) {
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerV0.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerV0.java
index 47a20d0fd4..cd5e2bc9bc 100644
--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerV0.java
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/rust/demangler/RustDemanglerV0.java
@@ -1,6 +1,11 @@
/* ###
* IP: GHIDRA
*
+ * Ported and adapted from rustc-demangle (https://github.com/rust-lang/rustc-demangle),
+ * which is dual-licensed under Apache-2.0 and MIT. This implementation is
+ * derived from commit c5688cfec32d2bd00701836f12beb3560ee015b8 and adjusted
+ * for Ghidra’s Java runtime.
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -15,8 +20,11 @@
*/
package ghidra.app.plugin.core.analysis.rust.demangler;
-import java.net.IDN;
-import java.util.*;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
/**
* A class that will demangle Rust symbols mangled according to the V0 format. This class
@@ -24,7 +32,15 @@ import java.util.*;
*
* @see <a href="https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html">2603-rust-symbol-name-mangling-v0.html</a>
*/
-public class RustDemanglerV0 {
+public final class RustDemanglerV0 {
+
+ public static final String RECURSION_LIMIT_MESSAGE = "{recursion limit reached}";
+
+ private static final int MAX_DEPTH = 500;
+
+ private RustDemanglerV0() {
+ // utility class
+ }
/**
* Demangles a symbol according to the format
@@ -32,91 +48,74 @@ public class RustDemanglerV0 {
* @return the demangled symbol name
*/
public static String demangle(String symbol) {
- if (symbol.startsWith("_R")) {
- symbol = symbol.substring(2);
- }
- else if (symbol.startsWith("R")) {
- symbol = symbol.substring(1);
- }
- else if (symbol.startsWith("__R")) {
- symbol = symbol.substring(3);
- }
-
- if (!symbol.matches("\\A\\p{ASCII}*\\z")) {
- return null;
- }
-
- Symbol cursor = new Symbol(symbol);
-
- return RustPath.parse(cursor).toString();
+ return demangleInternal(symbol, false);
}
-}
-
-/**
- * A class that represents a symbol in the demangling process. It keeps track of
- * the current state of the symbol and implements various methods to assist with
- * demangling it.
- */
-class Symbol {
- /** A list of backref objects */
- Map<Integer, SymbolNode> backrefs = new HashMap<Integer, SymbolNode>();
-
- /** The mangled symbol */
- String mangled;
-
- /** The current position in the mangled symbol */
- int pos = 0;
/**
- * Creates a symbol object
- * @param mangled the mangled symbol name
+ * Demangles a Rust V0 mangled symbol using an alternate format that omits
+ * hash/disambiguator suffixes.
+ *
+ * @param symbol the mangled symbol
+ * @return the demangled representation without hash suffixes, or {@code null} if the input is not
+ * a valid V0-mangled symbol
*/
- public Symbol(String mangled) {
- this.mangled = mangled;
+ public static String demangleAlternate(String symbol) {
+ return demangleInternal(symbol, true);
}
- /**
- * Adds a backref to the list
- * @param index the index of the backref
- * @param value the backref object to add
- */
- public void backrefAdd(int index, SymbolNode value) {
- backrefs.put(Integer.valueOf(index), value);
- index += 1;
- }
+ private static String demangleInternal(String symbol, boolean alternate) {
+ if (symbol == null || symbol.isEmpty()) {
+ return null;
+ }
- /**
- * Gets the backref at a certain index
- * @param index the index of he backref to return
- * @return the backref object
- */
- public String getBackref(int index) {
- SymbolNode backref = backrefs.get(index);
- if (backref != null) {
- return backref.toString();
+ String inner = stripPrefix(symbol);
+ if (inner == null || inner.isEmpty()) {
+ return null;
}
- return "{backref " + index + "}";
- }
+ if (!isAscii(inner)) {
+ return null;
+ }
- /**
- * Returns the number of the encoded backref
- * @return the number sting
- */
- public String parseBackref() {
- if (stripPrefix('B')) {
- return parseBase62Number();
+ if (!startsWithUpperPath(inner)) {
+ return null;
}
- return null;
- }
+ try {
+ Parser parser = new Parser(inner);
- /**
- * Returns the remaining string to be demangled
- * @return the mangled string
- */
- public String remaining() {
- return mangled.substring(pos);
+ try {
+ Parser afterFirst = Printer.dryRunParsePath(parser.copy(), false, alternate);
+ if (startsWithUpperPath(afterFirst)) {
+ Printer.dryRunParsePath(afterFirst, false, alternate);
+ }
+ }
+ catch (ParseException e) {
+ if (e.isRecursedTooDeep()) {
+ return null;
+ }
+ return null;
+ }
+
+ Printer printer = new Printer(parser.copy(), new StringBuilder(), alternate);
+ printer.printPath(true);
+ String result = printer.finish();
+ String suffix = printer.remaining();
+ if (!suffix.isEmpty()) {
+ boolean keepSuffix = suffix.startsWith(".") && !suffix.startsWith(".llvm") &&
+ !suffix.startsWith("@@");
+ if (!keepSuffix) {
+ suffix = "";
+ }
+ }
+ return suffix.isEmpty() ? result : result + suffix;
+ }
+ catch (ParseException e) {
+ if (e.isRecursedTooDeep()) {
+ return e.message();
+ }
+ return null;
+ }
}
/**
@@ -124,812 +123,1305 @@ class Symbol {
* @param c the char to strip
* @return if the strip succeeded
*/
- public boolean stripPrefix(char c) {
- if (c == nextChar()) {
- popChar();
- return true;
+ private static String stripPrefix(String symbol) {
+ if (symbol.length() > 2 && symbol.startsWith("_R")) {
+ return symbol.substring(2);
}
-
- return false;
- }
-
- /**
- * Gets the next char in the mangled string
- * @return the next char
- */
- public char nextChar() {
- return mangled.charAt(pos);
- }
-
- /**
- * Gets the next int in the mangled string
- * @return the next int
- */
- public int nextInt() {
- return mangled.charAt(pos);
- }
-
- /**
- * Pops the next char in the mangled string
- * @return the next char
- */
- public char popChar() {
- char c = mangled.charAt(pos);
- pos += 1;
- return c;
- }
-
- /**
- * Parses the following numerical digits in the mangled sting
- * @return the parsed integer
- */
- public int parseDigits() {
- String num = "";
-
- if (nextChar() == '0') {
- return 0;
+ if (symbol.length() > 1 && symbol.startsWith("R")) {
+ return symbol.substring(1);
}
-
- while (nextChar() >= '0' && nextChar() <= '9') {
- num += popChar();
+ if (symbol.length() > 3 && symbol.startsWith("__R")) {
+ return symbol.substring(3);
}
-
- return Integer.parseInt(num);
+ return null;
}
/**
- * Parses the string until the passed char is reached
- * @param c the char to parse until
- * @return the parsed string
+ * Returns true if every character in {@code text} is ASCII. Legacy demangler performed the
+ * same check up-front before attempting to walk the grammar.
*/
- public String parseUntil(char c) {
- String data = "";
-
- while (nextChar() != c) {
- data += popChar();
+ private static boolean isAscii(String text) {
+ for (int i = 0; i < text.length(); i++) {
+ if (text.charAt(i) >= 0x80) {
+ return false;
+ }
}
-
- return data;
- }
-
- /**
- * Subtracts one from the position in the mangled string
- */
- public void backChar() {
- pos -= 1;
+ return true;
}
/**
- * Parses the
- * @param n number of characters
- * @return the parsed string
+ * Rust v0 manglings always begin with a capital letter describing the top-level path kind.
*/
- public String parseString(int n) {
- String s = mangled.substring(pos, pos + n);
- pos += n;
- return s;
+ private static boolean startsWithUpperPath(String text) {
+ if (text == null || text.isEmpty()) {
+ return false;
+ }
+ char c = text.charAt(0);
+ return c >= 'A' && c <= 'Z';
}
- /**
- * Returns if the end of the mangled string has been reached
- * @return if the end has been reached
- */
- public boolean isEmpty() {
- return mangled.length() <= pos;
+ private static boolean startsWithUpperPath(Parser parser) {
+ int peek = parser.peek();
+ return peek >= 'A' && peek <= 'Z';
}
- /**
- * Parses the following base 62 number
- * @return the parsed num string
- */
- public String parseBase62Number() {
- String numString = parseUntil('_');
- popChar();
- return numString;
+ private enum ParseErrorKind {
+ INVALID,
+ RECURSED_TOO_DEEP
}
-}
-/**
- * A node to be used in symbol parsing
- */
-interface SymbolNode {
- // Parent class
-}
+ private static final class ParseException extends Exception {
+ private static final long serialVersionUID = 1L;
+ final ParseErrorKind kind;
-/**
- * A class to represent a nested path node
- */
-class RustPathNested implements SymbolNode {
- SymbolNode parent;
- RustIdentifier identifier;
+ ParseException(ParseErrorKind kind) {
+ this.kind = kind;
+ }
- public RustPathNested(SymbolNode parent, RustIdentifier identifier) {
- this.parent = parent;
- this.identifier = identifier;
+ boolean isRecursedTooDeep() {
+ return kind == ParseErrorKind.RECURSED_TOO_DEEP;
}
- @Override
- public String toString() {
- return parent.toString() + "::" + identifier.toString();
+ String message() {
+ return switch (kind) {
+ case RECURSED_TOO_DEEP -> RECURSION_LIMIT_MESSAGE;
+ case INVALID -> "{invalid syntax}";
+ };
+ }
}
-}
/**
- * A class to represent a string node
+ * Stateful cursor used while walking the v0 grammar. The parser owns the original
+ * mangled string, maintains the current offset, and keeps a recursion counter so we can
+ * mirror rustc's depth limits when following backrefs.
*/
-class RustString implements SymbolNode {
- String data;
+private static final class Parser {
+ private final String sym;
+ private int next;
+ private int depth;
- public RustString(String data) {
- this.data = data;
- }
+ Parser(String sym) {
+ this(sym, 0, 0);
+ }
- @Override
- public String toString() {
- return data;
- }
-}
+ Parser(String sym, int next, int depth) {
+ this.sym = sym;
+ this.next = next;
+ this.depth = depth;
+ }
-/**
- * A class that will represent and parse a backref node
- */
-class RustBackref implements SymbolNode {
- int backref;
- Symbol s;
+ Parser copy() {
+ return new Parser(sym, next, depth);
+ }
- public RustBackref(int backref, Symbol s) {
- this.backref = backref;
- this.s = s;
- }
+ /**
+ * Returns the remaining string to be demangled
+ * @return the mangled string
+ */
+ String remaining() {
+ return sym.substring(next);
+ }
- @Override
- public String toString() {
- return s.getBackref(backref);
- }
-}
+ /**
+ * @return the next character without consuming it, or {@code -1} if the cursor is exhausted.
+ */
+ int peek() {
+ if (next >= sym.length()) {
+ return -1;
+ }
+ return sym.charAt(next);
+ }
-/**
- * A class to represent and parse a rust symbol path node
- */
-class RustPath implements SymbolNode {
- SymbolNode child;
+ /**
+ * Advances the cursor when the next character matches {@code expected}.
+ */
+ boolean eat(char expected) {
+ if (peek() == expected) {
+ next++;
+ return true;
+ }
+ return false;
+ }
- public RustPath(SymbolNode child) {
- this.child = child;
- }
+ /**
+ * Consumes and returns the next character.
+ */
+ char next() throws ParseException {
+ if (next >= sym.length()) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ return sym.charAt(next++);
+ }
- public RustPath(String child) {
- this.child = new RustString(child);
- }
+ void pushDepth() throws ParseException {
+ depth++;
+ if (depth > MAX_DEPTH) {
+ throw new ParseException(ParseErrorKind.RECURSED_TOO_DEEP);
+ }
+ }
- /**
- * Parses a rust path from a mangled symbol
- * @param s parse the rust path
- * @return the rust path object
- */
- public static RustPath parse(Symbol s) {
- int pos = s.pos - 1;
-
- if (s.nextChar() == 'B') {
- String backref = s.parseBackref();
- int i = Integer.parseInt(backref, 16);
- RustBackref b = new RustBackref(i, s);
- RustPath path = new RustPath(b);
- return path;
- }
-
- char c = s.popChar();
- if (c == 'C') {
- // Crate root?
- RustIdentifier identifier = RustIdentifier.parse(s, new RustNamespace("crate"));
- s.backrefAdd(pos, identifier);
- return new RustPath(identifier.toString());
- }
- else if (c == 'M') {
- RustImplPath implPath = RustImplPath.parse(s);
- RustType type = RustType.parse(s);
- RustPath path = new RustPath("<" + implPath + "::" + type + ">");
-
- s.backrefAdd(pos, path);
- return path;
- // <impl-path> <type>
- // <T> (inherent impl)
- }
- else if (c == 'X') {
- RustImplPath.parse(s);
- RustType type = RustType.parse(s);
- RustPath parent = RustPath.parse(s);
- RustPath path = new RustPath("<" + type + " as " + parent + ">");
- s.backrefAdd(pos, path);
- return path;
- // <impl-path> <type> <data>
- // <T as Trait> (trait impl)
- }
- else if (c == 'Y') {
- RustType type = RustType.parse(s);
- RustPath parent = RustPath.parse(s);
-
- RustPath path = new RustPath("<" + type + " as " + parent + ">");
- s.backrefAdd(pos, path);
- return path;
- // <type> <data>
- // <T as Trait> (trait definition)
- }
- else if (c == 'N') {
- RustNamespace namespace = RustNamespace.parse(s);
- RustPath parent = RustPath.parse(s);
- RustIdentifier id = RustIdentifier.parse(s, namespace);
- RustPathNested nested = new RustPathNested(parent, id);
-
- RustPath path = new RustPath(nested.toString());
- s.backrefAdd(pos, path);
- return path;
- }
- else if (c == 'I') {
- RustPath parent = RustPath.parse(s);
- RustGenericArgs args = RustGenericArgs.parse(s);
-
- if (args == null) {
- RustPath path = new RustPath(parent);
- s.backrefAdd(pos, path);
- return path;
- }
-
- RustPath path = new RustPath("" + parent + args);
- s.backrefAdd(pos, path);
- return path;
- }
- else if (c == 'B') {
- s.backChar();
- String b = s.parseBackref();
- int i = Integer.parseInt(b, 16);
- RustBackref br = new RustBackref(i, s);
- return new RustPath(br);
+ void popDepth() {
+ depth--;
}
- return null;
- }
+ /**
+ * Reads a sequence of hexadecimal digits terminated by {@code '_'} and exposes them as a
+ * {@link HexNibbles} helper.
+ */
+ HexNibbles hexNibbles() throws ParseException {
+ int start = next;
+ while (true) {
+ char c = next();
+ if (isHexDigit(c)) {
+ continue;
+ }
+ if (c == '_') {
+ break;
+ }
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ return new HexNibbles(sym.substring(start, next - 1));
+ }
- @Override
- public String toString() {
- return child.toString();
- }
-}
+ /**
+ * Parses a decimal digit character.
+ */
+ int digit10() throws ParseException {
+ int p = peek();
+ if (p >= '0' && p <= '9') {
+ next++;
+ return p - '0';
+ }
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
-/**
- * Parses and represents a rust symbol namespace node
- */
-class RustNamespace {
- String data;
+ /**
+ * Parses the next base-62 digit.
+ */
+ int digit62() throws ParseException {
+ int p = peek();
+ if (p >= '0' && p <= '9') {
+ next++;
+ return p - '0';
+ }
+ if (p >= 'a' && p <= 'z') {
+ next++;
+ return 10 + (p - 'a');
+ }
+ if (p >= 'A' && p <= 'Z') {
+ next++;
+ return 36 + (p - 'A');
+ }
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
- public RustNamespace(String data) {
- this.data = data;
- }
+ /**
+ * Reads a base-62 integer terminated by {@code '_'} and returns the decoded value.
+ */
+ long integer62() throws ParseException {
+ if (eat('_')) {
+ return 0;
+ }
- /**
- * Parses a rust namespace from a mangled symbol
- * @param s symbol to parse
- * @return the rust path object
- */
- public static RustNamespace parse(Symbol s) {
- char c = s.popChar();
+ long value = 0;
+ while (!eat('_')) {
+ int digit = digit62();
+ value = multiplyAddBase62(value, digit);
+ }
+ return addExact(value, 1);
+ }
- if (c == 'C') {
- // closure
- return new RustNamespace("{closure}");
+ /**
+ * Optionally consumes a base-62 integer prefixed by {@code tag} and returns the decoded value.
+ */
+ long optInteger62(char tag) throws ParseException {
+ if (!eat(tag)) {
+ return 0;
+ }
+ return addExact(integer62(), 1);
}
- else if (c == 'S') {
- // shim
- return new RustNamespace("{shim}");
+
+ /**
+ * Parses the optional `s` disambiguator used to render hash-like suffixes.
+ */
+ long disambiguator() throws ParseException {
+ return optInteger62('s');
}
- else if (c >= 'A' && c <= 'Z') {
- // other special namespaces
- return new RustNamespace(String.valueOf(c));
+
+ /**
+ * Reads the namespace designator that precedes nested paths.
+ */
+ Character namespace() throws ParseException {
+ char c = next();
+ if (c >= 'A' && c <= 'Z') {
+ return Character.valueOf(c);
+ }
+ if (c >= 'a' && c <= 'z') {
+ return null;
+ }
+ throw new ParseException(ParseErrorKind.INVALID);
}
- else if (c >= 'a' && c <= 'z') {
- // internal namespaces
- return new RustNamespace(String.valueOf(c));
+
+ /**
+ * Resolves a backreference, returning a new parser positioned at the referenced start.
+ */
+ Parser backref() throws ParseException {
+ int start = next - 1;
+ long offset = integer62();
+ if (offset >= start) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ Parser p = new Parser(sym, (int) offset, depth);
+ p.pushDepth();
+ return p;
}
- return null;
- }
+ /**
+ * Parses an identifier, handling punycode (for non-ASCII) and optional disambiguator suffixes.
+ */
+ Ident ident() throws ParseException {
+ boolean isPunycode = eat('u');
+ int len = digit10();
+ if (len != 0) {
+ while (true) {
+ int peek = peek();
+ if (peek < '0' || peek > '9') {
+ break;
+ }
+ next++;
+ len = multiplyExact(len, 10);
+ len = addExact(len, peek - '0');
+ }
+ }
+
+ eat('_');
+
+ if (len < 0 || next + len > sym.length()) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ String raw = sym.substring(next, next + len);
+ next += len;
+
+ if (isPunycode) {
+ int sep = raw.lastIndexOf('_');
+ String ascii;
+ String punycode;
+ if (sep >= 0) {
+ ascii = raw.substring(0, sep);
+ punycode = raw.substring(sep + 1);
+ }
+ else {
+ ascii = "";
+ punycode = raw;
+ }
+ if (punycode.isEmpty()) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ return new Ident(ascii, punycode);
+ }
- @Override
- public String toString() {
- return data;
+ return new Ident(raw, "");
+ }
}
-}
/**
- * Parses and represents a rust symbol impl path node
+ * Pretty printer that mirrors the upstream rustc-demangle formatter. It consumes parsed
+ * tokens by delegating back into {@link Parser} and emits either the normal or the
+ * alternate (hash-stripped) textual form depending on the {@code alternate} flag.
*/
-class RustImplPath implements SymbolNode {
- RustPath path;
- RustString disambiguator;
-
- public RustImplPath(RustPath path, RustString disambiguator) {
- this.path = path;
- this.disambiguator = disambiguator;
- }
+private static final class Printer {
+ private Parser parser;
+ private StringBuilder out;
+ private int boundLifetimeDepth;
+ private final boolean alternate;
+
+ Printer(Parser parser, StringBuilder out, boolean alternate) {
+ this.parser = parser;
+ this.out = out;
+ this.boundLifetimeDepth = 0;
+ this.alternate = alternate;
+ }
- /**
- * Parses a impl rust path from a mangled symbol
- * @param s symbol to parse
- * @return the rust impl path object
- */
- public static RustImplPath parse(Symbol s) {
- RustString disambiguator = null;
- if (s.nextChar() == 's') {
- disambiguator = RustIdentifier.parseDisambiguator(s);
+ static Parser dryRunParsePath(Parser parser, boolean inValue, boolean alternate)
+ throws ParseException {
+ Printer printer = new Printer(parser, null, alternate);
+ printer.printPath(inValue);
+ return printer.parser.copy();
}
- RustPath path = RustPath.parse(s);
+ /**
+ * @return the accumulated demangled output.
+ */
+ String finish() {
+ return out == null ? "" : out.toString();
+ }
- return new RustImplPath(path, disambiguator);
- }
+ /**
+ * @return any suffix that was not consumed during the primary parse (e.g. ".llvm" decorations).
+ */
+ String remaining() {
+ return parser.remaining();
+ }
- @Override
- public String toString() {
- String s = path.toString();
+ /**
+ * Prints a v0 path grammar node. This mirrors the old implementation's {@code RustPath.parse}.
+ */
+ void printPath(boolean inValue) throws ParseException {
+ parser.pushDepth();
+
+ char tag = parser.next();
+ switch (tag) {
+ case 'C': { // crate root / plain identifier
+ long dis = parser.disambiguator();
+ Ident name = parser.ident();
+ print(name.render());
+ if (dis != 0 && !alternate) {
+ print('[');
+ printLowerHex(dis);
+ print(']');
+ }
+ break;
+ }
+ case 'N': { // nested path (module::item)
+ Character ns = parser.namespace();
+ printPath(inValue);
+ long dis = parser.disambiguator();
+ Ident name = parser.ident();
+
+ if (ns != null) {
+ print("::{");
+ switch (ns.charValue()) {
+ case 'C':
+ print("closure");
+ break;
+ case 'S':
+ print("shim");
+ break;
+ default:
+ print(ns.charValue());
+ break;
+ }
+ if (!name.isEmpty()) {
+ print(':');
+ print(name.render());
+ }
+ print('#');
+ print(dis);
+ print('}');
+ }
+ else if (!name.isEmpty()) {
+ print("::");
+ print(name.render());
+ }
+ break;
+ }
+ case 'M': // inherent impl path (<impl-path>::item)
+ case 'X': // trait impl path (<T as Trait>::item)
+ case 'Y': { // trait definition (<T as Trait>)
+ if (tag != 'Y') {
+ parser.disambiguator();
+ skippingPrinting(pr -> pr.printPath(false));
+ }
+ print('<');
+ printType();
+ if (tag != 'M') {
+ print(" as ");
+ printPath(false);
+ }
+ print('>');
+ break;
+ }
+ case 'I': { // path with generic arguments
+ printPath(inValue);
+ if (inValue) {
+ print("::");
+ }
+ print('<');
+ printSepList(pr -> pr.printGenericArg(), ", ");
+ print('>');
+ break;
+ }
+ case 'B': { // backreference into previously seen path
+ printBackref(pr -> pr.printPath(inValue));
+ break;
+ }
+ default:
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
- if (disambiguator != null && disambiguator.toString() != "") {
- s += "::" + "[" + disambiguator.toString() + "]";
+ parser.popDepth();
}
- return s;
- }
-}
+ /** Prints a single generic argument (lifetime, const, or type). */
+ private void printGenericArg() throws ParseException {
+ if (parser.eat('L')) {
+ long lt = parser.integer62();
+ printLifetimeFromIndex(lt);
+ }
+ else if (parser.eat('K')) {
+ printConst(false);
+ }
+ else {
+ printType();
+ }
+ }
-/**
- * Parses and represents an rust symbol identifier
- */
-class RustIdentifier implements SymbolNode {
- String id;
- RustNamespace namespace;
- RustString disambiguator;
-
- public RustIdentifier(RustNamespace namespace, String id, RustString disambiguator) {
- this.id = id;
- this.namespace = namespace;
- this.disambiguator = disambiguator;
- }
+ /** Prints a type node (the equivalent of legacy {@code RustType.parse}). */
+ private void printType() throws ParseException {
+ char tag = parser.next();
+ String basic = basicType(tag);
+ if (basic != null) {
+ print(basic);
+ return;
+ }
- /**
- * Parses a rust identifier from a mangled symbol
- * @param s symbol to parse
- * @param namespace namespace of symbol
- * @return the rust identifier object
- */
- public static RustIdentifier parse(Symbol s, RustNamespace namespace) {
- RustString disambiguator = null;
+ parser.pushDepth();
+
+ switch (tag) {
+ case 'R': // &T
+ case 'Q': { // &mut T
+ print('&');
+ if (parser.eat('L')) {
+ long lt = parser.integer62();
+ if (lt != 0) {
+ printLifetimeFromIndex(lt);
+ print(' ');
+ }
+ }
+ if (tag != 'R') {
+ print("mut ");
+ }
+ printType();
+ break;
+ }
+ case 'P': // *const T
+ case 'O': { // *mut T
+ print('*');
+ if (tag == 'P') {
+ print("const ");
+ }
+ else {
+ print("mut ");
+ }
+ printType();
+ break;
+ }
+ case 'A': // [T; N]
+ case 'S': { // [T]
+ print('[');
+ printType();
+ if (tag == 'A') {
+ print("; ");
+ printConst(true);
+ }
+ print(']');
+ break;
+ }
+ case 'T': { // tuple (T1, T2, ...)
+ print('(');
+ int count = printSepList(Printer::printType, ", ");
+ if (count == 1) {
+ print(',');
+ }
+ print(')');
+ break;
+ }
+ case 'F': { // fn(...) -> ...
+ inBinder(pr -> {
+ boolean isUnsafe = pr.parser.eat('U');
+ String abi = null;
+ if (pr.parser.eat('K')) {
+ if (pr.parser.eat('C')) {
+ abi = "C";
+ }
+ else {
+ Ident ident = pr.parser.ident();
+ if (!ident.punycode.isEmpty() || ident.ascii.isEmpty()) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ abi = ident.ascii;
+ }
+ }
- if (s.nextChar() == 's') {
- disambiguator = parseDisambiguator(s);
- }
+ if (isUnsafe) {
+ pr.print("unsafe ");
+ }
- String id = parseUndisambiguatedIdentifier(s);
- return new RustIdentifier(namespace, id, disambiguator);
- }
+ if (abi != null) {
+ pr.print("extern \"");
+ String[] parts = abi.split("_");
+ for (int i = 0; i < parts.length; i++) {
+ if (i != 0) {
+ pr.print('-');
+ }
+ pr.print(parts[i]);
+ }
+ pr.print("\" ");
+ }
- /**
- * Parses a rust disambiguator from a mangled symbol
- * @param s symbol to parse
- * @return a string representing the disambiguator
- */
- public static RustString parseDisambiguator(Symbol s) {
- char c = s.popChar();
- assert c == 's';
- return new RustString(s.parseBase62Number());
- }
+ pr.print("fn(");
+ pr.printSepList(Printer::printType, ", ");
+ pr.print(')');
- /**
- * Parses a rust undisambiguated identifier from a mangled symbol
- * @param s symbol to parse
- * @return the corresponding string object
- */
- public static String parseUndisambiguatedIdentifier(Symbol s) {
- boolean punycode = s.stripPrefix('u');
- int num = s.parseDigits();
+ if (!pr.parser.eat('u')) {
+ pr.print(" -> ");
+ pr.printType();
+ }
+ });
+ break;
+ }
+ case 'D': { // dyn Trait + bounds
+ print("dyn ");
+ inBinder(pr -> {
+ pr.printSepList(Printer::printDynTrait, " + ");
+ });
+ if (!parser.eat('L')) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ long lt = parser.integer62();
+ if (lt != 0) {
+ print(" + ");
+ printLifetimeFromIndex(lt);
+ }
+ break;
+ }
+ case 'B': { // backref to previously printed type
+ printBackref(Printer::printType);
+ break;
+ }
+ case 'W': { // type with pattern (unstable internal form)
+ printType();
+ print(" is ");
+ printPat();
+ break;
+ }
+ default: {
+ parser.next--; // rewind for path parsing
+ printPath(false);
+ break;
+ }
+ }
- if (s.nextChar() == '_') {
- s.popChar();
+ parser.popDepth();
}
- if (num == 0) {
- char c = s.popChar();
- return "{closure#" + c + "}";
+ /**
+ * Prints either a plain path or a path with `<...>` generics, returning whether the caller
+ * should emit the closing `>` (needed for dyn-trait associated bindings).
+ */
+ private boolean printPathMaybeOpenGenerics() throws ParseException {
+ if (parser.eat('B')) {
+ final boolean[] open = new boolean[] { false };
+ printBackref(pr -> open[0] = pr.printPathMaybeOpenGenerics());
+ return open[0];
+ }
+ if (parser.eat('I')) {
+ printPath(false);
+ print('<');
+ printSepList(Printer::printGenericArg, ", ");
+ return true;
+ }
+ printPath(false);
+ return false;
}
- String bytes = s.parseString(num);
-
- if (punycode) {
- return IDN.toASCII(bytes, IDN.ALLOW_UNASSIGNED);
+ /**
+ * Prints a single trait appearing inside a `dyn` object, including associated type bindings.
+ */
+ private void printDynTrait() throws ParseException {
+ boolean open = printPathMaybeOpenGenerics();
+ while (parser.eat('p')) {
+ if (!open) {
+ print('<');
+ open = true;
+ }
+ else {
+ print(", ");
+ }
+ Ident name = parser.ident();
+ print(name.render());
+ print(" = ");
+ printType();
+ }
+ if (open) {
+ print('>');
+ }
}
- return bytes;
- }
+ /** Prints pattern fragments used by the unstable `is` syntax (range unions, etc.). */
+ private void printPat() throws ParseException {
+ char tag = parser.next();
+ switch (tag) {
+ case 'R':
+ printConst(false);
+ print("..=");
+ printConst(false);
+ break;
+ case 'O':
+ parser.pushDepth();
+ printPat();
+ while (!parser.eat('E')) {
+ print(" | ");
+ printPat();
+ }
+ parser.popDepth();
+ break;
+ case 'N':
+ print("!null");
+ break;
+ default:
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ }
- @Override
- public String toString() {
- return id.toString();
- }
-}
+ /** Prints a constant expression appearing either as a value or inside generics. */
+ private void printConst(boolean inValue) throws ParseException {
+ char tag = parser.next();
+ parser.pushDepth();
+
+ boolean openedBrace = false;
+ final boolean requireWrap = !inValue;
+
+ switch (tag) {
+ case 'p': // `_` placeholder
+ print('_');
+ break;
+ case 'h':
+ case 't':
+ case 'm':
+ case 'y':
+ case 'o':
+ case 'j': // unsigned integers
+ printConstUint(tag);
+ break;
+ case 'a':
+ case 's':
+ case 'l':
+ case 'x':
+ case 'n':
+ case 'i': // signed integers
+ if (parser.eat('n')) {
+ print('-');
+ }
+ printConstUint(tag);
+ break;
+ case 'b': { // bool
+ Long v = parser.hexNibbles().tryParseUInt();
+ if (v == null) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ if (v == 0) {
+ print("false");
+ }
+ else if (v == 1) {
+ print("true");
+ }
+ else {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ break;
+ }
+ case 'c': { // char literal
+ Long value = parser.hexNibbles().tryParseUInt();
+ if (value == null || value < 0 || value > Character.MAX_CODE_POINT) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ String data = new String(Character.toChars(value.intValue()));
+ printQuotedEscapedChars('\'', data);
+ break;
+ }
+ case 'e': { // str literal (stored as *"...")
+ if (requireWrap) {
+ openedBrace = true;
+ print('{');
+ }
+ print('*');
+ printConstStrLiteral();
+ break;
+ }
+ case 'R':
+ case 'Q': { // references in const position
+ if (tag == 'R' && parser.eat('e')) {
+ printConstStrLiteral(true);
+ }
+ else {
+ if (requireWrap) {
+ openedBrace = true;
+ print('{');
+ }
+ print('&');
+ if (tag != 'R') {
+ print("mut ");
+ }
+ printConst(true);
+ }
+ break;
+ }
+ case 'A': { // array literal
+ if (requireWrap) {
+ openedBrace = true;
+ print('{');
+ }
+ print('[');
+ printSepList(pr -> pr.printConst(true), ", ");
+ print(']');
+ break;
+ }
+ case 'T': { // tuple literal
+ if (requireWrap) {
+ openedBrace = true;
+ print('{');
+ }
+ print('(');
+ int count = printSepList(pr -> pr.printConst(true), ", ");
+ if (count == 1) {
+ print(',');
+ }
+ print(')');
+ break;
+ }
+ case 'V': { // enum/struct literal
+ if (requireWrap) {
+ openedBrace = true;
+ print('{');
+ }
+ printPath(true);
+ char variant = parser.next();
+ switch (variant) {
+ case 'U':
+ break;
+ case 'T':
+ print('(');
+ printSepList(pr -> pr.printConst(true), ", ");
+ print(')');
+ break;
+ case 'S':
+ print(" { ");
+ printSepList(pr -> {
+ pr.parser.disambiguator();
+ Ident name = pr.parser.ident();
+ pr.print(name.render());
+ pr.print(": ");
+ pr.printConst(true);
+ }, ", ");
+ print(" }");
+ break;
+ default:
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ break;
+ }
+ case 'B': { // backref
+ printBackref(pr -> pr.printConst(inValue));
+ break;
+ }
+ default:
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
-/**
- * Parses and represents rust generic arguments
- */
-class RustGenericArgs implements SymbolNode {
- ArrayList<RustGenericArg> args;
+ if (openedBrace) {
+ print('}');
+ }
- public RustGenericArgs(ArrayList<RustGenericArg> args) {
- this.args = args;
- }
+ parser.popDepth();
+ }
- /**
- * Parses generics arguments from a mangled symbol
- * @param s symbol to parse
- * @return the rust generic arguments object
- */
- public static RustGenericArgs parse(Symbol s) {
- ArrayList<RustGenericArg> genericArgs = new ArrayList<RustGenericArg>();
+ /** Formats a hexadecimal string literal as either {@code "..."} or {@code *"..."}. */
+ private void printConstStrLiteral() throws ParseException {
+ printConstStrLiteral(false);
+ }
- while (s.nextChar() != 'E') {
- RustGenericArg arg = RustGenericArg.parse(s);
- if (arg == null) {
- return null;
+ private void printConstStrLiteral(boolean bare) throws ParseException {
+ String decoded = parser.hexNibbles().tryParseStr();
+ if (decoded == null) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ if (bare) {
+ printQuotedEscapedChars('"', decoded);
+ }
+ else {
+ printQuotedEscapedChars('"', decoded);
}
-
- genericArgs.add(arg);
}
- s.popChar();
+ /** Emits an integer literal, appending the suffix when alternate formatting is disabled. */
+ private void printConstUint(char tyTag) throws ParseException {
+ HexNibbles hex = parser.hexNibbles();
+ Long value = hex.tryParseUInt();
+ if (value != null) {
+ print(value);
+ }
+ else {
+ print("0x");
+ print(hex.nibbles);
+ }
+ String ty = basicType(tyTag);
+ if (ty != null && !alternate) {
+ print(ty);
+ }
+ }
- return new RustGenericArgs(genericArgs);
- }
+ /** Replays a previously printed node referenced by a `B` backref tag. */
+ private void printBackref(PrinterConsumer consumer) throws ParseException {
+ Parser backref = parser.backref();
+ if (out == null) {
+ return;
+ }
+ Parser saved = parser;
+ parser = backref;
+ consumer.accept(this);
+ parser = saved;
+ }
- @Override
- public String toString() {
- String s = "";
+ /** Handles the {@code for<...>} binder that introduces late-bound lifetimes. */
+ private void inBinder(PrinterConsumer consumer) throws ParseException {
+ long count = parser.optInteger62('G');
+ if (out == null) {
+ consumer.accept(this);
+ return;
+ }
+ if (count > 0) {
+ print("for<");
+ for (int i = 0; i < count; i++) {
+ if (i != 0) {
+ print(", ");
+ }
+ boundLifetimeDepth++;
+ printLifetimeFromIndex(1);
+ }
+ print("> ");
+ }
+ consumer.accept(this);
+ boundLifetimeDepth -= (int) count;
+ }
- for (RustGenericArg arg : args) {
- s += arg.toString() + ", ";
+ /** Utility for comma-separated lists terminated by {@code 'E'}. */
+ private int printSepList(PrinterConsumer consumer, String sep) throws ParseException {
+ int count = 0;
+ while (!parser.eat('E')) {
+ if (count != 0) {
+ print(sep);
+ }
+ consumer.accept(this);
+ count++;
+ }
+ return count;
}
- return "<" + s.substring(0, s.length() - 2) + ">";
- }
-}
+ /** Converts the encoded lifetime index into a textual representation (e.g. {@code 'a}). */
+ private void printLifetimeFromIndex(long lt) throws ParseException {
+ if (out == null) {
+ return;
+ }
+ print('\'');
+ if (lt == 0) {
+ print('_');
+ return;
+ }
+ long depth = (long) boundLifetimeDepth - lt;
+ if (depth < 0) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ if (depth < 26) {
+ print((char) ('a' + depth));
+ }
+ else {
+ print('_');
+ print(depth);
+ }
+ }
-/**
- * Parses and represents a generic argument node in a rust symbol
- */
-class RustGenericArg implements SymbolNode {
- SymbolNode child;
+ /** Temporarily disables output while still consuming the parse tree (used for impl paths). */
+ private void skippingPrinting(PrinterConsumer consumer) throws ParseException {
+ StringBuilder original = out;
+ out = null;
+ consumer.accept(this);
+ out = original;
+ }
- public RustGenericArg(SymbolNode child) {
- this.child = child;
- }
+ private void print(String text) {
+ if (out != null) {
+ out.append(text);
+ }
+ }
- /**
- * Parses a rust generic argument from a mangled symbol
- * @param s symbol to parse
- * @return the rust generic argument object
- */
- public static RustGenericArg parse(Symbol s) {
- SymbolNode lifetime = RustLifetime.parse(s);
- if (lifetime != null) {
- return new RustGenericArg(lifetime);
+ private void print(char c) {
+ if (out != null) {
+ out.append(c);
+ }
}
- if (s.nextChar() == 'K') {
- s.popChar();
- SymbolNode constant = RustConst.parse(s);
- if (constant != null) {
- return new RustGenericArg(constant);
+ private void print(long value) {
+ if (out != null) {
+ out.append(value);
}
}
- SymbolNode type = RustType.parse(s);
- if (type != null) {
- return new RustGenericArg(type);
+ private void printLowerHex(long value) {
+ if (out != null) {
+ out.append(Long.toHexString(value));
+ }
}
- return null;
+ private void printQuotedEscapedChars(char quote, String data) {
+ if (out == null) {
+ return;
+ }
+ out.append(quote);
+ data.codePoints().forEach(cp -> {
+ if ((quote == '\'' && cp == '"') || (quote == '"' && cp == '\'')) {
+ out.appendCodePoint(cp);
+ return;
+ }
+ switch (cp) {
+ case '\\':
+ out.append("\\\\");
+ break;
+ case '\n':
+ out.append("\\n");
+ break;
+ case '\r':
+ out.append("\\r");
+ break;
+ case '\t':
+ out.append("\\t");
+ break;
+ case '\0':
+ out.append("\\0");
+ break;
+ case '"':
+ if (quote == '"') {
+ out.append("\\\"");
+ }
+ else {
+ out.append('"');
+ }
+ break;
+ case '\'':
+ if (quote == '\'') {
+ out.append("\\'");
+ }
+ else {
+ out.append('\'');
+ }
+ break;
+ default:
+ if (cp < 0x20 || cp == 0x7f) {
+ out.append(String.format("\\x%02x", cp));
+ }
+ else {
+ out.appendCodePoint(cp);
+ }
+ }
+ });
+ out.append(quote);
+ }
}
- @Override
- public String toString() {
- return child.toString();
+ @FunctionalInterface
+ private interface PrinterConsumer {
+ void accept(Printer printer) throws ParseException;
}
-}
-/**
- * Parses a rust lifetime from a mangled symbol
- */
-class RustLifetime implements SymbolNode {
- String num;
+ private static final class Ident {
+ private final String ascii;
+ private final String punycode;
- public RustLifetime(String num) {
- this.num = num;
- }
+ Ident(String ascii, String punycode) {
+ this.ascii = ascii;
+ this.punycode = punycode;
+ }
- /**
- * Parses a rust lifetime node from a mangled symbol
- * @param s symbol to parse
- * @return the rust lifetime node
- */
- public static SymbolNode parse(Symbol s) {
- if (s.nextChar() != 'L') {
- return null;
+ boolean isEmpty() {
+ return ascii.isEmpty() && punycode.isEmpty();
}
- s.popChar();
+ String render() {
+ if (punycode.isEmpty()) {
+ return ascii;
+ }
+
+ List<Integer> decoded = decodePunycode();
+ if (decoded == null) {
+ StringBuilder builder = new StringBuilder("punycode{");
+ if (!ascii.isEmpty()) {
+ builder.append(ascii).append('-');
+ }
+ builder.append(punycode).append('}');
+ return builder.toString();
+ }
- String num = s.parseBase62Number();
- if (num != null) {
- return new RustLifetime(num);
+ StringBuilder out = new StringBuilder();
+ for (int cp : decoded) {
+ out.appendCodePoint(cp);
+ }
+ return out.toString();
}
- return null;
- }
+ /**
+ * Decodes the punycode payload used for non-ASCII identifiers. Returns {@code null} when the
+ * sequence is malformed so callers can fall back to the `{punycode{...}}` representation.
+ */
+ private List<Integer> decodePunycode() {
+ if (punycode.isEmpty()) {
+ return null;
+ }
- @Override
- public String toString() {
- return num;
- }
-}
+ List<Integer> output = new ArrayList<>();
+ ascii.codePoints().forEach(cp -> output.add(cp));
+
+ int base = 36;
+ int tMin = 1;
+ int tMax = 26;
+ int skew = 38;
+ int damp = 700;
+ int bias = 72;
+ long i = 0;
+ long n = 0x80;
+ int index = 0;
+
+ while (index < punycode.length()) {
+ long delta = 0;
+ long w = 1;
+ int k = base;
+ while (true) {
+ if (index >= punycode.length()) {
+ return null;
+ }
+ char c = punycode.charAt(index++);
+ int digit;
+ if (c >= 'a' && c <= 'z') {
+ digit = c - 'a';
+ }
+ else if (c >= '0' && c <= '9') {
+ digit = 26 + (c - '0');
+ }
+ else {
+ return null;
+ }
+
+ try {
+ delta = addExact(delta, multiplyExact(w, digit));
+ }
+ catch (ParseException e) {
+ return null;
+ }
+ int t = clamp(k - bias, tMin, tMax);
+ if (digit < t) {
+ break;
+ }
+ try {
+ w = multiplyExact(w, base - t);
+ }
+ catch (ParseException e) {
+ return null;
+ }
+ k += base;
+ }
-/**
- * Parses and represents a rust symbol type node
- */
-class RustType implements SymbolNode {
- String typeName;
- RustPath path;
+ int outLen = output.size() + 1;
+ try {
+ i = addExact(i, delta);
+ n = addExact(n, i / outLen);
+ }
+ catch (ParseException e) {
+ return null;
+ }
+ i %= outLen;
+
+ if (!Character.isValidCodePoint((int) n) || i > Integer.MAX_VALUE) {
+ return null;
+ }
+ output.add((int) i, (int) n);
+ i++;
+
+ delta /= damp;
+ damp = 2;
+ delta += delta / outLen;
+ int kAdjust = 0;
+ while (delta > ((base - tMin) * (long) tMax) / 2) {
+ delta /= (base - tMin);
+ kAdjust += base;
+ }
+ bias = kAdjust + (int) (((base - tMin + 1L) * delta) / (delta + skew));
+ }
- public RustType(String typeName) {
- this.typeName = typeName;
+ return output;
+ }
}
- public RustType(RustPath path) {
- this.path = path;
+ private static final class HexNibbles {
+ private final String nibbles;
+
+ HexNibbles(String nibbles) {
+ this.nibbles = nibbles;
+ }
+
+ Long tryParseUInt() {
+ String trimmed = stripLeadingZeros(nibbles);
+ if (trimmed.length() > 16) {
+ return null;
+ }
+ long value = 0;
+ for (int i = 0; i < trimmed.length(); i++) {
+ int digit = hexValue(trimmed.charAt(i));
+ value = (value << 4) | digit;
+ }
+ return Long.valueOf(value);
+ }
+
+ String tryParseStr() {
+ if ((nibbles.length() & 1) != 0) {
+ return null;
+ }
+ byte[] bytes = new byte[nibbles.length() / 2];
+ for (int i = 0; i < bytes.length; i++) {
+ int hi = hexValue(nibbles.charAt(2 * i));
+ int lo = hexValue(nibbles.charAt(2 * i + 1));
+ bytes[i] = (byte) ((hi << 4) | lo);
+ }
+ try {
+ return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
+ }
+ catch (CharacterCodingException e) {
+ return null;
+ }
+ }
}
/**
- * Parses a rust type from a mangled symbol
- * @param s symbol to parse
- * @return the rust type object
+ * Maps the single-character primitive tags to their textual forms (e.g. {@code 'a'} =&gt; {@code i8}).
+ * The ordering matches the original implementation to ease diffing against upstream rustc-demangle.
*/
- public static RustType parse(Symbol s) {
- char c = s.popChar();
-
- switch (c) {
+ private static String basicType(char tag) {
+ switch (tag) {
case 'a':
- return new RustType("i8");
+ return "i8";
case 'b':
- return new RustType("bool");
+ return "bool";
case 'c':
- return new RustType("char");
+ return "char";
case 'd':
- return new RustType("f64");
+ return "f64";
case 'e':
- return new RustType("str");
+ return "str";
case 'f':
- return new RustType("f32");
+ return "f32";
case 'h':
- return new RustType("u8");
+ return "u8";
case 'i':
- return new RustType("isize");
+ return "isize";
case 'j':
- return new RustType("usize");
+ return "usize";
case 'l':
- return new RustType("i32");
+ return "i32";
case 'm':
- return new RustType("u32");
+ return "u32";
case 'n':
- return new RustType("i128");
+ return "i128";
case 'o':
- return new RustType("u128");
+ return "u128";
+ case 'p':
+ return "_";
case 's':
- return new RustType("i16");
+ return "i16";
case 't':
- return new RustType("u16");
+ return "u16";
case 'u':
- return new RustType("()");
+ return "()";
case 'v':
- return new RustType("...");
+ return "...";
case 'x':
- return new RustType("i64");
+ return "i64";
case 'y':
- return new RustType("u64");
+ return "u64";
case 'z':
- return new RustType("!");
- case 'p':
- return new RustType("_");
+ return "!";
default:
- switch (c) {
- case 'A': // Array sized
- RustType rustType = RustType.parse(s);
- RustConst constant = RustConst.parse(s);
- return new RustType(
- "[" + rustType.toString() + "; " + constant.toString() + "]");
- case 'S': // Array unsized
- SymbolNode symbolType = RustType.parse(s);
- return new RustType("[" + symbolType.toString() + "]");
- case 'T': // Tuple
- ArrayList<String> types = new ArrayList<String>();
-
- while (s.nextChar() != 'E') {
- SymbolNode symbolNode = RustType.parse(s);
- if (symbolNode != null) {
- types.add(symbolNode.toString());
- }
- else {
- return null; // null type in parse
- }
- }
-
- s.popChar();
-
- String type = "(" + String.join(", ", types) + ")";
- return new RustType(type);
- case 'R': // &T
- RustLifetime.parse(s);
- SymbolNode type1 = RustType.parse(s);
- return new RustType("&" + type1);
- case 'Q': // &mut T
- RustLifetime.parse(s);
- SymbolNode type2 = RustType.parse(s);
- return new RustType("&mut " + type2);
- case 'P': // *const T
- SymbolNode type3 = RustType.parse(s);
- return new RustType("*const " + type3);
- case 'O': // *mut T
- SymbolNode type4 = RustType.parse(s);
- return new RustType("*mut " + type4);
- case 'F': // fn(...) -> ...
- // TODO: FnSig type
- case 'D': // dyn Trait<Assoc = X> + Send + 'a
- String bounds = parseDynBounds(s);
- RustLifetime.parse(s);
- String data = "dyn Trait<Assoc = X>";
-
- if (bounds != null) {
- data += bounds;
- }
-
- return new RustType(data);
- case 'B':
- s.backChar();
- String b1 = s.parseBackref();
- int b2 = Integer.parseInt(b1);
- RustBackref b3 = new RustBackref(b2, s);
- return new RustType(new RustPath(b3));
- default:
- s.backChar();
- RustPath path = RustPath.parse(s);
- return new RustType(path);
- }
+ return null;
}
}
/**
- * Parses a rust dyn bounds from a mangled symbol
- * @param s symbol to parse
- * @return a string representing the dyn bounds
+ * Utility used by the punycode decoder to mimic rustc's bias adjustment logic.
*/
- public static String parseDynBounds(Symbol s) {
- ArrayList<String> traits = new ArrayList<String>();
- @SuppressWarnings("unused")
- String binder = parseBinder(s);
-
- while (s.nextChar() != 'E') {
- String trait = parseDynTrait(s);
- traits.add(trait);
+ private static int clamp(int value, int min, int max) {
+ if (value < min) {
+ return min;
}
-
- s.popChar();
-
- return " + " + String.join(" + ", traits);
+ if (value > max) {
+ return max;
+ }
+ return value;
}
/**
- * Parses a rust dyn trait from a mangled symbol
- * @param s symbol to parse
- * @return a string representing the dyn trait
+ * Parses a single hexadecimal nibble character.
*/
- public static String parseDynTrait(Symbol s) {
- RustPath path = RustPath.parse(s);
- @SuppressWarnings("unused")
- String bindings = "";
- while (s.nextChar() == 'p') {
- String binding = parseDynTraitAssocBinding(s);
- bindings += binding;
+ private static int hexValue(char c) {
+ if (c >= '0' && c <= '9') {
+ return c - '0';
}
-
- if (path == null) {
- return "";
+ if (c >= 'a' && c <= 'f') {
+ return 10 + (c - 'a');
}
-
- return path.toString();
- }
-
- /**
- * Parses a rust dyn trait associated binding from a mangled symbol
- * @param s symbol to parse
- * @return a string representing the dyn trait associated binding
- */
- public static String parseDynTraitAssocBinding(Symbol s) {
- s.popChar();
-
- RustIdentifier.parseUndisambiguatedIdentifier(s);
- SymbolNode type = RustType.parse(s);
-
- return "dyn " + type.toString();
+ if (c >= 'A' && c <= 'F') {
+ return 10 + (c - 'A');
+ }
+ throw new IllegalArgumentException("invalid hex digit: " + c);
}
- /**
- * Parses a rust binding from a mangled symbol
- * @param s symbol to parse
- * @return a string representing the binding
- */
- public static String parseBinder(Symbol s) {
- if (s.nextChar() != 'G') {
- return null;
+ private static String stripLeadingZeros(String value) {
+ int i = 0;
+ while (i < value.length() && value.charAt(i) == '0') {
+ i++;
}
+ return value.substring(i);
+ }
- s.popChar();
- return s.parseBase62Number();
+ private static boolean isHexDigit(char c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
- @Override
- public String toString() {
- if (path != null) {
- return path.toString();
+ private static long multiplyExact(long a, long b) throws ParseException {
+ if (a == 0 || b == 0) {
+ return 0;
}
-
- return typeName;
+ long result = a * b;
+ if (Long.divideUnsigned(result, a) != b) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
+ return result;
}
-}
-
-/**
- * Parses and represents a rust symbol const node
- */
-class RustConst implements SymbolNode {
- String name;
- public RustConst(String name) {
- this.name = name;
+ private static long multiplyAddBase62(long value, int digit) throws ParseException {
+ long mult = multiplyExact(value, 62);
+ return addExact(mult, digit);
}
- /**
- * Parses a rust const from a mangled symbol
- * @param s symbol to parse
- * @return the rust const object
- */
- public static RustConst parse(Symbol s) {
- SymbolNode type = RustType.parse(s);
- String constData = RustConst.parseConstData(s);
-
- return new RustConst(constData + type.toString());
+ private static int multiplyExact(int a, int b) throws ParseException {
+ try {
+ return Math.multiplyExact(a, b);
+ }
+ catch (ArithmeticException e) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
}
- /**
- * Parses a rust const data from a mangled symbol
- * @param s symbol to parse
- * @return a string representing the const data
- */
- public static String parseConstData(Symbol s) {
- if (s.nextChar() == 'n') {
- s.popChar();
+ private static long addExact(long a, long b) throws ParseException {
+ long result = a + b;
+ if (Long.compareUnsigned(result, a) < 0) {
+ throw new ParseException(ParseErrorKind.INVALID);
}
-
- String name = s.parseUntil('_');
- s.popChar();
-
- return name;
+ return result;
}
- @Override
- public String toString() {
- return name;
+ private static int addExact(int a, int b) throws ParseException {
+ try {
+ return Math.addExact(a, b);
+ }
+ catch (ArithmeticException e) {
+ throw new ParseException(ParseErrorKind.INVALID);
+ }
}
}
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerLegacyTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerLegacyTest.java
index b401dc4202..a0a3dd465b 100644
--- a/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerLegacyTest.java
+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerLegacyTest.java
@@ -23,6 +23,7 @@ import ghidra.app.plugin.core.analysis.rust.demangler.RustDemangler;
import ghidra.app.util.demangler.DemangledException;
import ghidra.app.util.demangler.DemangledObject;
import ghidra.program.model.lang.CompilerSpec;
+import ghidra.app.plugin.core.analysis.rust.demangler.RustDemanglerLegacy;
public class RustDemanglerLegacyTest {
@@ -36,7 +37,7 @@ public class RustDemanglerLegacyTest {
"_ZN5alloc5alloc18handle_alloc_error8rt_error17h4b79f8a717741b7cE",
"_ZN3std6thread7current17h20e47a880e55afd5E", };
- private static String[] names = { RUSTCALL + " _<char_as_core::fmt::Display>::fmt(void)",
+ private static String[] names = { RUSTCALL + " <char_as_core::fmt::Display>::fmt(void)",
RUSTCALL + " core::option::expect_failed(void)",
RUSTCALL + " core::fmt::Formatter::debug_lower_hex(void)",
RUSTCALL + " std::path::Components::as_path(void)",
@@ -62,4 +63,31 @@ public class RustDemanglerLegacyTest {
}
}
}
+
+ @Test
+ public void legacy_handleAssocTypes() {
+ assertEquals(
+ "<alloc::boxed::Box<alloc::boxed::FnBox<A, Output=R> + 'a> as core::ops::function::FnOnce<A>>::call_once",
+ RustDemanglerLegacy.demangle(
+ "_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE"));
+ }
+
+ @Test
+ public void legacy_handleBang() {
+ assertEquals(
+ "<core::result::Result<!, E> as std::process::Termination>::report",
+ RustDemanglerLegacy.demangle(
+ "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E"));
+ }
+
+ @Test
+ public void legacy_preservesModuleSeparators() {
+ assertEquals("foo::bar::baz", RustDemanglerLegacy.demangle("_ZN3foo3bar3bazE"));
+ }
+
+ @Test
+ public void legacy_handlesUnicodeEscapes() {
+ assertEquals("unicode::∂value",
+ RustDemanglerLegacy.demangle("_ZN7unicode12$u2202$valueE"));
+ }
}
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerV0Test.java b/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerV0Test.java
index d5b6cd5f51..8f494c2bae 100644
--- a/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerV0Test.java
+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/analyzers/RustDemanglerV0Test.java
@@ -15,11 +15,19 @@
*/
package ghidra.app.analyzers;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
import org.junit.Test;
import ghidra.app.plugin.core.analysis.rust.demangler.RustDemangler;
+import ghidra.app.plugin.core.analysis.rust.demangler.RustDemanglerV0;
import ghidra.app.util.demangler.DemangledException;
import ghidra.app.util.demangler.DemangledObject;
@@ -93,4 +101,316 @@ public class RustDemanglerV0Test {
}
}
}
+
+ private static final int MAX_DEPTH = fetchMaxDepth();
+
+ @Test
+ public void upstream_demangleCrateWithLeadingDigit() {
+ assertDemangleAlternate("_RNvC6_123foo3bar", "123foo::bar");
+ }
+
+ @Test
+ public void upstream_demangleCrateWithZeroDisambiguator() {
+ assertDemangle("_RC4f128", "f128");
+ assertDemangleAlternate("_RC4f128", "f128");
+ }
+
+ @Test
+ public void upstream_demangleUtf8Idents() {
+ String expected = "utf8_idents::\u10e1\u10d0\u10ed\u10db\u10d4\u10da\u10d0\u10d3_\u10d2\u10d4\u10db\u10e0\u10d8\u10d4\u10da\u10d8_\u10e1\u10d0\u10d3\u10d8\u10da\u10d8";
+ assertDemangleAlternate("_RNqCs4fqI2P2rA04_11utf8_identsu30____7hkackfecea1cbdathfdh9hlq6y", expected);
+ }
+
+ @Test
+ public void upstream_demangleClosure() {
+ assertDemangleAlternate("_RNCNCNgCs6DXkGYLi8lr_2cc5spawn00B5_", "cc::spawn::{closure#0}::{closure#0}");
+ String expected = "<core::slice::Iter<u8> as core::iter::iterator::Iterator>::rposition::<core::slice::memchr::memrchr::{closure#1}>::{closure#0}";
+ assertDemangleAlternate(
+ "_RNCINkXs25_NgCsbmNqQUJIY6D_4core5sliceINyB9_4IterhENuNgNoBb_4iter8iterator8Iterator9rpositionNCNgNpB9_6memchr7memrchrs_0E0Bb_",
+ expected);
+ }
+
+ @Test
+ public void upstream_demangleDynTrait() {
+ assertDemangleAlternate(
+ "_RINbNbCskIICzLVDPPb_5alloc5alloc8box_freeDINbNiB4_5boxed5FnBoxuEp6OutputuEL_ECs1iopQbuBiw2_3std",
+ "alloc::alloc::box_free::<dyn alloc::boxed::FnBox<(), Output = ()>>");
+ }
+
+ @Test
+ public void upstream_demanglePatTy() {
+ assertDemangleAlternate("_RMC0WmRm1_m9_", "<u32 is 1..=9>");
+ assertDemangleAlternate("_RMC0WmORm1_m2_Rm5_m6_E", "<u32 is 1..=2 | 5..=6>");
+ assertNull(RustDemanglerV0.demangle("_RMC0WmORm1_m2_Rm5_m6_"));
+ }
+
+ @Test
+ public void upstream_demangleConstGenericsPreview() {
+ assertDemangleAlternate("_RMC0INtC8arrayvec8ArrayVechKj7b_E", "<arrayvec::ArrayVec<u8, 123>>");
+ assertConst("j7b_", "123", "123usize");
+ }
+
+ @Test
+ public void upstream_demangleMinConstGenerics() {
+ assertConst("p", "_", null);
+ assertConst("hb_", "11", "11u8");
+ assertConst("off00ff00ff00ff00ff_", "0xff00ff00ff00ff00ff", "0xff00ff00ff00ff00ffu128");
+ assertConst("s98_", "152", "152i16");
+ assertConst("anb_", "-11", "-11i8");
+ assertConst("b0_", "false", null);
+ assertConst("b1_", "true", null);
+ assertConst("c76_", "'v'", null);
+ assertConst("c22_", "'\"'", null);
+ assertConst("ca_", "'\\n'", null);
+ assertConst("c2202_", "'\u2202'", null);
+ }
+
+ @Test
+ public void upstream_demangleConstStr() {
+ assertConst("e616263_", "{*\"abc\"}", null);
+ assertConst("e27_", "{*\"'\"}", null);
+ assertConst("e090a_", "{*\"\\t\\n\"}", null);
+ assertConst("ee28882c3bc_", "{*\"\u2202\u00fc\"}", null);
+ assertConst(
+ "ee183a1e18390e183ade1839be18394e1839ae18390e183935fe18392e18394e1839be183a0e18398e18394e1839ae183985fe183a1e18390e18393e18398e1839ae18398_",
+ "{*\"\u10e1\u10d0\u10ed\u10db\u10d4\u10da\u10d0\u10d3_\u10d2\u10d4\u10db\u10e0\u10d8\u10d4\u10da\u10d8_\u10e1\u10d0\u10d3\u10d8\u10da\u10d8\"}",
+ null);
+ assertConst(
+ "ef09f908af09fa688f09fa686f09f90ae20c2a720f09f90b6f09f9192e29895f09f94a520c2a720f09fa7a1f09f929bf09f929af09f9299f09f929c_",
+ "{*\"\ud83d\udc0a\ud83e\udd88\ud83e\udd86\ud83d\udc2e \u00a7 \ud83d\udc36\ud83d\udc52\u2615\ud83d\udd25 \u00a7 \ud83e\udde1\ud83d\udc9b\ud83d\udc9a\ud83d\udc99\ud83d\udc9c\"}",
+ null);
+ }
+
+ @Test
+ public void upstream_demangleConstRefStr() {
+ assertConst("Re616263_", "\"abc\"", null);
+ assertConst("Re27_", "\"'\"", null);
+ assertConst("Re090a_", "\"\\t\\n\"", null);
+ assertConst("Ree28882c3bc_", "\"\u2202\u00fc\"", null);
+ assertConst(
+ "Ree183a1e18390e183ade1839be18394e1839ae18390e183935fe18392e18394e1839be183a0e18398e18394e1839ae183985fe183a1e18390e18393e18398e1839ae18398_",
+ "\"\u10e1\u10d0\u10ed\u10db\u10d4\u10da\u10d0\u10d3_\u10d2\u10d4\u10db\u10e0\u10d8\u10d4\u10da\u10d8_\u10e1\u10d0\u10d3\u10d8\u10da\u10d8\"",
+ null);
+ assertConst(
+ "Ref09f908af09fa688f09fa686f09f90ae20c2a720f09f90b6f09f9192e29895f09f94a520c2a720f09fa7a1f09f929bf09f929af09f9299f09f929c_",
+ "\"\ud83d\udc0a\ud83e\udd88\ud83e\udd86\ud83d\udc2e \u00a7 \ud83d\udc36\ud83d\udc52\u2615\ud83d\udd25 \u00a7 \ud83e\udde1\ud83d\udc9b\ud83d\udc9a\ud83d\udc99\ud83d\udc9c\"",
+ null);
+ }
+
+ @Test
+ public void upstream_demangleConstRef() {
+ assertConst("Rp", "{&_}", null);
+ assertConst("Rh7b_", "{&123}", null);
+ assertConst("Rb0_", "{&false}", null);
+ assertConst("Rc58_", "{&'X'}", null);
+ assertConst("RRRh0_", "{&&&0}", null);
+ assertConst("RRRe_", "{&&\"\"}", null);
+ assertConst("QAE", "{&mut []}", null);
+ }
+
+ @Test
+ public void upstream_demangleConstArray() {
+ assertConst("AE", "{[]}", null);
+ assertConst("Aj0_E", "{[0]}", null);
+ assertConst("Ah1_h2_h3_E", "{[1, 2, 3]}", null);
+ assertConst("ARe61_Re62_Re63_E", "{[\"a\", \"b\", \"c\"]}", null);
+ assertConst("AAh1_h2_EAh3_h4_EE", "{[[1, 2], [3, 4]]}", null);
+ }
+
+ @Test
+ public void upstream_demangleConstTuple() {
+ assertConst("TE", "{()}", null);
+ assertConst("Tj0_E", "{(0,)}", null);
+ assertConst("Th1_b0_E", "{(1, false)}", null);
+ assertConst("TRe616263_c78_RAh1_h2_h3_EE", "{(\"abc\", 'x', &[1, 2, 3])}", null);
+ }
+
+ @Test
+ public void upstream_demangleConstAdt() {
+ assertConst(
+ "VNvINtNtC4core6option6OptionjE4NoneU",
+ "{core::option::Option::<usize>::None}", null);
+ assertConst(
+ "VNvINtNtC4core6option6OptionjE4SomeTj0_E",
+ "{core::option::Option::<usize>::Some(0)}", null);
+ assertConst(
+ "VNtC3foo3BarS1sRe616263_2chc78_5sliceRAh1_h2_h3_EE",
+ "{foo::Bar { s: \"abc\", ch: 'x', slice: &[1, 2, 3] }}", null);
+ }
+
+ @Test
+ public void upstream_demangleExponentialExplosion() {
+ String symbol = "_RMC0" + "TTTTTT" + "p" + "B8_E" + "B7_E" + "B6_E" + "B5_E" + "B4_E" + "B3_E";
+ String expected = "<((((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _)))), ((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _))))), (((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _)))), ((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _))))))>";
+ assertDemangleAlternate(symbol, expected);
+ }
+
+ @Test
+ public void upstream_demangleThinlto() {
+ assertDemangleAlternate("_RC3foo.llvm.9D1C9369", "foo");
+ assertDemangleAlternate("_RC3foo.llvm.9D1C9369@@16", "foo");
+ assertDemangleAlternate("_RNvC9backtrace3foo.llvm.A5310EB9", "backtrace::foo");
+ }
+
+ @Test
+ public void upstream_demangleExtraSuffix() {
+ assertDemangleAlternate(
+ "_RNvNtNtNtNtCs92dm3009vxr_4rand4rngs7adapter9reseeding4fork23FORK_HANDLER_REGISTERED.0.0",
+ "rand::rngs::adapter::reseeding::fork::FORK_HANDLER_REGISTERED.0.0");
+ }
+
+ @Test
+ public void upstream_demanglingLimits() {
+ Path path = Paths.get("rustc-demangle", "src", "v0-large-test-symbols", "early-recursion-limit");
+ for (String line : readLines(path)) {
+ String symbol = line.trim();
+ if (symbol.isEmpty() || symbol.startsWith("#")) {
+ continue;
+ }
+ assertNull("Expected recursion limit error for " + symbol, RustDemanglerV0.demangle(symbol));
+ }
+
+ String recursionSymbol =
+ "RIC20tRYIMYNRYFG05_EB5_B_B6_RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR" +
+ "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRB_E";
+ String demangled = RustDemanglerV0.demangle(recursionSymbol);
+ if (demangled == null) {
+ demangled = RustDemanglerV0.RECURSION_LIMIT_MESSAGE;
+ }
+ assertTrue(demangled.contains(RustDemanglerV0.RECURSION_LIMIT_MESSAGE));
+ }
+
+ // Ported from Linux perf test: <https://github.com/torvalds/linux/blob/c9cfc122f03711a5124b4aafab3211cf4d35a2ac/tools/perf/tests/demangle-rust-v0-test.c#L9>
+ @Test
+ public void perfToolCases() {
+ assertDemangleAlternate(
+ "_RNvMsr_NtCs3ssYzQotkvD_3std4pathNtB5_7PathBuf3newCs15kBYyAo9fc_7mycrate",
+ "<std::path::PathBuf>::new");
+ assertDemangleAlternate("_RNvCs15kBYyAo9fc_7mycrate7example", "mycrate::example");
+ assertDemangleAlternate(
+ "_RNvMs_Cs4Cv8Wi1oAIB_7mycrateNtB4_7Example3foo",
+ "<mycrate::Example>::foo");
+ assertDemangleAlternate(
+ "_RNvXCs15kBYyAo9fc_7mycrateNtB2_7ExampleNtB2_5Trait3foo",
+ "<mycrate::Example as mycrate::Trait>::foo");
+ assertDemangleAlternate(
+ "_RNvMCs7qp2U7fqm6G_7mycrateNtB2_7Example3foo",
+ "<mycrate::Example>::foo");
+ assertDemangleAlternate(
+ "_RNvMs_Cs7qp2U7fqm6G_7mycrateNtB4_7Example3bar",
+ "<mycrate::Example>::bar");
+ assertDemangleAlternate(
+ "_RNvYNtCs15kBYyAo9fc_7mycrate7ExampleNtB4_5Trait7exampleB4_",
+ "<mycrate::Example as mycrate::Trait>::example");
+ assertDemangleAlternate(
+ "_RNCNvCsgStHSCytQ6I_7mycrate4main0B3_",
+ "mycrate::main::{closure#0}");
+ assertDemangleAlternate(
+ "_RNCNvCsgStHSCytQ6I_7mycrate4mains_0B3_",
+ "mycrate::main::{closure#1}");
+ assertDemangleAlternate(
+ "_RINvCsgStHSCytQ6I_7mycrate7examplelKj1_EB2_",
+ "mycrate::example::<i32, 1>");
+ assertDemangleAlternate(
+ "_RINvCs7qp2U7fqm6G_7mycrate7exampleFG0_RL1_hRL0_tEuEB2_",
+ "mycrate::example::<for<'a, 'b> fn(&'a u8, &'b u16)>");
+ assertDemangleAlternate(
+ "_RINvCs7qp2U7fqm6G_7mycrate7exampleKy12345678_EB2_",
+ "mycrate::example::<305419896>");
+ assertDemangleAlternate(
+ "_RNvNvMCsd9PVOYlP1UU_7mycrateINtB4_7ExamplepKpE3foo14EXAMPLE_STATIC",
+ "<mycrate::Example<_, _>>::foo::EXAMPLE_STATIC");
+ assertDemangleAlternate(
+ "_RINvCs7qp2U7fqm6G_7mycrate7exampleAtj8_EB2_",
+ "mycrate::example::<[u16; 8]>");
+ assertDemangleAlternate(
+ "_RINvCs7qp2U7fqm6G_7mycrate7exampleNtB2_7ExampleBw_EB2_",
+ "mycrate::example::<mycrate::Example, mycrate::Example>");
+ assertDemangleAlternate(
+ "_RINvMsY_NtCseXNvpPnDBDp_3std4pathNtB6_4Path3neweECs7qp2U7fqm6G_7mycrate",
+ "<std::path::Path>::new::<str>");
+ assertDemangleAlternate(
+ "_RNvNvNvCs7qp2U7fqm6G_7mycrate7EXAMPLE7___getit5___KEY",
+ "mycrate::EXAMPLE::__getit::__KEY");
+ }
+
+ @Test
+ public void upstream_recursionLimitLeaks() {
+ for (String[] pair : new String[][] { { "p", "_" }, { "Rp", "&_" }, { "C1x", "x" } }) {
+ String symLeaf = pair[0];
+ String expectedLeaf = pair[1];
+ StringBuilder sym = new StringBuilder("_RIC0p");
+ StringBuilder expected = new StringBuilder("::<_");
+ for (int i = 0; i < MAX_DEPTH * 2; i++) {
+ sym.append(symLeaf);
+ expected.append(", ").append(expectedLeaf);
+ }
+ sym.append('E');
+ expected.append('>');
+ assertDemangleAlternate(sym.toString(), expected.toString());
+ }
+ }
+
+ @Test
+ public void upstream_recursionLimitBackrefFreeBypass() {
+ int depth = 100_000;
+ StringBuilder sym = new StringBuilder("_RIC").append(depth);
+ int backrefStart = sym.length() - 2;
+ for (int i = 0; i < depth; i++) {
+ sym.append('R');
+ }
+ sym.append('B');
+ sym.append(Character.forDigit((backrefStart - 1) % 36, 36));
+ sym.append('_');
+ sym.append('E');
+
+ String demangled = RustDemanglerV0.demangle(sym.toString());
+ if (demangled == null) {
+ demangled = RustDemanglerV0.RECURSION_LIMIT_MESSAGE;
+ }
+ assertTrue(demangled.contains(RustDemanglerV0.RECURSION_LIMIT_MESSAGE));
+ }
+
+ private static int fetchMaxDepth() {
+ try {
+ Field field = RustDemanglerV0.class.getDeclaredField("MAX_DEPTH");
+ field.setAccessible(true);
+ return field.getInt(null);
+ }
+ catch (ReflectiveOperationException e) {
+ throw new AssertionError("Unable to access MAX_DEPTH", e);
+ }
+ }
+
+ private static void assertConst(String payload, String displayValue, String hashedValue) {
+ assertDemangleAlternate("_RIC0K" + payload + "E", "::<" + displayValue + ">");
+ if (hashedValue != null) {
+ assertDemangle("_RIC0K" + payload + "E", "::<" + hashedValue + ">");
+ }
+ }
+
+ private static void assertDemangle(String mangled, String expected) {
+ String demangled = RustDemanglerV0.demangle(mangled);
+ assertNotNull("Failed to demangle symbol " + mangled, demangled);
+ assertEquals("Unexpected demangle result for " + mangled, expected, demangled);
+ }
+
+ private static void assertDemangleAlternate(String mangled, String expected) {
+ String demangled = RustDemanglerV0.demangleAlternate(mangled);
+ assertNotNull("Failed to demangle symbol " + mangled, demangled);
+ assertEquals("Unexpected demangle result for " + mangled, expected, demangled);
+ }
+
+ private static List<String> readLines(Path path) {
+ Path candidate = path;
+ if (!Files.exists(candidate)) {
+ candidate = Paths.get("..", "..", "..").resolve(path).normalize();
+ }
+ try {
+ return Files.readAllLines(candidate);
+ }
+ catch (IOException e) {
+ throw new AssertionError("Unable to read test data from " + candidate, e);
+ }
+ }
}