xref: /llvm-project/llvm/lib/Demangle/RustDemangle.cpp (revision b42400ccf3be9c8a422f175e16109e358298973c)
1 //===--- RustDemangle.cpp ---------------------------------------*- 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 a demangler for Rust v0 mangled symbols as specified in
10 // https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Demangle/RustDemangle.h"
15 #include "llvm/Demangle/Demangle.h"
16 
17 #include <algorithm>
18 #include <cassert>
19 #include <cstring>
20 #include <limits>
21 
22 using namespace llvm;
23 using namespace rust_demangle;
24 
25 char *llvm::rustDemangle(const char *MangledName, char *Buf, size_t *N,
26                          int *Status) {
27   if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
28     if (Status != nullptr)
29       *Status = demangle_invalid_args;
30     return nullptr;
31   }
32 
33   // Return early if mangled name doesn't look like a Rust symbol.
34   StringView Mangled(MangledName);
35   if (!Mangled.startsWith("_R")) {
36     if (Status != nullptr)
37       *Status = demangle_invalid_mangled_name;
38     return nullptr;
39   }
40 
41   Demangler D;
42   if (!initializeOutputStream(nullptr, nullptr, D.Output, 1024)) {
43     if (Status != nullptr)
44       *Status = demangle_memory_alloc_failure;
45     return nullptr;
46   }
47 
48   if (!D.demangle(Mangled)) {
49     if (Status != nullptr)
50       *Status = demangle_invalid_mangled_name;
51     std::free(D.Output.getBuffer());
52     return nullptr;
53   }
54 
55   D.Output += '\0';
56   char *Demangled = D.Output.getBuffer();
57   size_t DemangledLen = D.Output.getCurrentPosition();
58 
59   if (Buf != nullptr) {
60     if (DemangledLen <= *N) {
61       std::memcpy(Buf, Demangled, DemangledLen);
62       std::free(Demangled);
63       Demangled = Buf;
64     } else {
65       std::free(Buf);
66     }
67   }
68 
69   if (N != nullptr)
70     *N = DemangledLen;
71 
72   if (Status != nullptr)
73     *Status = demangle_success;
74 
75   return Demangled;
76 }
77 
78 Demangler::Demangler(size_t MaxRecursionLevel)
79     : MaxRecursionLevel(MaxRecursionLevel) {}
80 
81 static inline bool isDigit(const char C) { return '0' <= C && C <= '9'; }
82 
83 static inline bool isHexDigit(const char C) {
84   return ('0' <= C && C <= '9') || ('a' <= C && C <= 'f');
85 }
86 
87 static inline bool isLower(const char C) { return 'a' <= C && C <= 'z'; }
88 
89 static inline bool isUpper(const char C) { return 'A' <= C && C <= 'Z'; }
90 
91 /// Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
92 static inline bool isValid(const char C) {
93   return isDigit(C) || isLower(C) || isUpper(C) || C == '_';
94 }
95 
96 // Demangles Rust v0 mangled symbol. Returns true when successful, and false
97 // otherwise. The demangled symbol is stored in Output field. It is
98 // responsibility of the caller to free the memory behind the output stream.
99 //
100 // <symbol-name> = "_R" <path> [<instantiating-crate>]
101 bool Demangler::demangle(StringView Mangled) {
102   Position = 0;
103   Error = false;
104   Print = true;
105   RecursionLevel = 0;
106 
107   if (!Mangled.consumeFront("_R")) {
108     Error = true;
109     return false;
110   }
111   Input = Mangled;
112 
113   demanglePath(InType::No);
114 
115   // FIXME parse optional <instantiating-crate>.
116 
117   if (Position != Input.size())
118     Error = true;
119 
120   return !Error;
121 }
122 
123 // Demangles a path. InType indicates whether a path is inside a type.
124 //
125 // <path> = "C" <identifier>               // crate root
126 //        | "M" <impl-path> <type>         // <T> (inherent impl)
127 //        | "X" <impl-path> <type> <path>  // <T as Trait> (trait impl)
128 //        | "Y" <type> <path>              // <T as Trait> (trait definition)
129 //        | "N" <ns> <path> <identifier>   // ...::ident (nested path)
130 //        | "I" <path> {<generic-arg>} "E" // ...<T, U> (generic args)
131 //        | <backref>
132 // <identifier> = [<disambiguator>] <undisambiguated-identifier>
133 // <ns> = "C"      // closure
134 //      | "S"      // shim
135 //      | <A-Z>    // other special namespaces
136 //      | <a-z>    // internal namespaces
137 void Demangler::demanglePath(InType InType) {
138   if (Error || RecursionLevel >= MaxRecursionLevel) {
139     Error = true;
140     return;
141   }
142   SwapAndRestore<size_t> SaveRecursionLevel(RecursionLevel, RecursionLevel + 1);
143 
144   switch (consume()) {
145   case 'C': {
146     parseOptionalBase62Number('s');
147     Identifier Ident = parseIdentifier();
148     print(Ident.Name);
149     break;
150   }
151   case 'M': {
152     demangleImplPath(InType);
153     print("<");
154     demangleType();
155     print(">");
156     break;
157   }
158   case 'X': {
159     demangleImplPath(InType);
160     print("<");
161     demangleType();
162     print(" as ");
163     demanglePath(InType::Yes);
164     print(">");
165     break;
166   }
167   case 'Y': {
168     print("<");
169     demangleType();
170     print(" as ");
171     demanglePath(InType::Yes);
172     print(">");
173     break;
174   }
175   case 'N': {
176     char NS = consume();
177     if (!isLower(NS) && !isUpper(NS)) {
178       Error = true;
179       break;
180     }
181     demanglePath(InType);
182 
183     uint64_t Disambiguator = parseOptionalBase62Number('s');
184     Identifier Ident = parseIdentifier();
185 
186     if (isUpper(NS)) {
187       // Special namespaces
188       print("::{");
189       if (NS == 'C')
190         print("closure");
191       else if (NS == 'S')
192         print("shim");
193       else
194         print(NS);
195       if (!Ident.empty()) {
196         print(":");
197         print(Ident.Name);
198       }
199       print('#');
200       printDecimalNumber(Disambiguator);
201       print('}');
202     } else {
203       // Implementation internal namespaces.
204       if (!Ident.empty()) {
205         print("::");
206         print(Ident.Name);
207       }
208     }
209     break;
210   }
211   case 'I': {
212     demanglePath(InType);
213     // Omit "::" when in a type, where it is optional.
214     if (InType == InType::No)
215       print("::");
216     print("<");
217     for (size_t I = 0; !Error && !consumeIf('E'); ++I) {
218       if (I > 0)
219         print(", ");
220       demangleGenericArg();
221     }
222     print(">");
223     break;
224   }
225   default:
226     // FIXME parse remaining productions.
227     Error = true;
228     break;
229   }
230 }
231 
232 // <impl-path> = [<disambiguator>] <path>
233 // <disambiguator> = "s" <base-62-number>
234 void Demangler::demangleImplPath(InType InType) {
235   SwapAndRestore<bool> SavePrint(Print, false);
236   parseOptionalBase62Number('s');
237   demanglePath(InType);
238 }
239 
240 // <generic-arg> = <lifetime>
241 //               | <type>
242 //               | "K" <const>
243 // <lifetime> = "L" <base-62-number>
244 void Demangler::demangleGenericArg() {
245   if (consumeIf('K'))
246     demangleConst();
247   else
248     demangleType();
249   // FIXME demangle lifetimes.
250 }
251 
252 // <basic-type> = "a"      // i8
253 //              | "b"      // bool
254 //              | "c"      // char
255 //              | "d"      // f64
256 //              | "e"      // str
257 //              | "f"      // f32
258 //              | "h"      // u8
259 //              | "i"      // isize
260 //              | "j"      // usize
261 //              | "l"      // i32
262 //              | "m"      // u32
263 //              | "n"      // i128
264 //              | "o"      // u128
265 //              | "s"      // i16
266 //              | "t"      // u16
267 //              | "u"      // ()
268 //              | "v"      // ...
269 //              | "x"      // i64
270 //              | "y"      // u64
271 //              | "z"      // !
272 //              | "p"      // placeholder (e.g. for generic params), shown as _
273 static bool parseBasicType(char C, BasicType &Type) {
274   switch (C) {
275   case 'a':
276     Type = BasicType::I8;
277     return true;
278   case 'b':
279     Type = BasicType::Bool;
280     return true;
281   case 'c':
282     Type = BasicType::Char;
283     return true;
284   case 'd':
285     Type = BasicType::F64;
286     return true;
287   case 'e':
288     Type = BasicType::Str;
289     return true;
290   case 'f':
291     Type = BasicType::F32;
292     return true;
293   case 'h':
294     Type = BasicType::U8;
295     return true;
296   case 'i':
297     Type = BasicType::ISize;
298     return true;
299   case 'j':
300     Type = BasicType::USize;
301     return true;
302   case 'l':
303     Type = BasicType::I32;
304     return true;
305   case 'm':
306     Type = BasicType::U32;
307     return true;
308   case 'n':
309     Type = BasicType::I128;
310     return true;
311   case 'o':
312     Type = BasicType::U128;
313     return true;
314   case 'p':
315     Type = BasicType::Placeholder;
316     return true;
317   case 's':
318     Type = BasicType::I16;
319     return true;
320   case 't':
321     Type = BasicType::U16;
322     return true;
323   case 'u':
324     Type = BasicType::Unit;
325     return true;
326   case 'v':
327     Type = BasicType::Variadic;
328     return true;
329   case 'x':
330     Type = BasicType::I64;
331     return true;
332   case 'y':
333     Type = BasicType::U64;
334     return true;
335   case 'z':
336     Type = BasicType::Never;
337     return true;
338   default:
339     return false;
340   }
341 }
342 
343 void Demangler::printBasicType(BasicType Type) {
344   switch (Type) {
345   case BasicType::Bool:
346     print("bool");
347     break;
348   case BasicType::Char:
349     print("char");
350     break;
351   case BasicType::I8:
352     print("i8");
353     break;
354   case BasicType::I16:
355     print("i16");
356     break;
357   case BasicType::I32:
358     print("i32");
359     break;
360   case BasicType::I64:
361     print("i64");
362     break;
363   case BasicType::I128:
364     print("i128");
365     break;
366   case BasicType::ISize:
367     print("isize");
368     break;
369   case BasicType::U8:
370     print("u8");
371     break;
372   case BasicType::U16:
373     print("u16");
374     break;
375   case BasicType::U32:
376     print("u32");
377     break;
378   case BasicType::U64:
379     print("u64");
380     break;
381   case BasicType::U128:
382     print("u128");
383     break;
384   case BasicType::USize:
385     print("usize");
386     break;
387   case BasicType::F32:
388     print("f32");
389     break;
390   case BasicType::F64:
391     print("f64");
392     break;
393   case BasicType::Str:
394     print("str");
395     break;
396   case BasicType::Placeholder:
397     print("_");
398     break;
399   case BasicType::Unit:
400     print("()");
401     break;
402   case BasicType::Variadic:
403     print("...");
404     break;
405   case BasicType::Never:
406     print("!");
407     break;
408   }
409 }
410 
411 // <type> = | <basic-type>
412 //          | <path>                      // named type
413 //          | "A" <type> <const>          // [T; N]
414 //          | "S" <type>                  // [T]
415 //          | "T" {<type>} "E"            // (T1, T2, T3, ...)
416 //          | "R" [<lifetime>] <type>     // &T
417 //          | "Q" [<lifetime>] <type>     // &mut T
418 //          | "P" <type>                  // *const T
419 //          | "O" <type>                  // *mut T
420 //          | "F" <fn-sig>                // fn(...) -> ...
421 //          | "D" <dyn-bounds> <lifetime> // dyn Trait<Assoc = X> + Send + 'a
422 //          | <backref>                   // backref
423 void Demangler::demangleType() {
424   size_t Start = Position;
425 
426   char C = consume();
427   BasicType Type;
428   if (parseBasicType(C, Type))
429     return printBasicType(Type);
430 
431   switch (C) {
432   case 'A':
433     print("[");
434     demangleType();
435     print("; ");
436     demangleConst();
437     print("]");
438     break;
439   default:
440     Position = Start;
441     demanglePath(InType::Yes);
442     break;
443   }
444 }
445 
446 // <const> = <basic-type> <const-data>
447 //         | "p"                          // placeholder
448 //         | <backref>
449 void Demangler::demangleConst() {
450   BasicType Type;
451   if (parseBasicType(consume(), Type)) {
452     switch (Type) {
453     case BasicType::I8:
454     case BasicType::I16:
455     case BasicType::I32:
456     case BasicType::I64:
457     case BasicType::I128:
458     case BasicType::ISize:
459     case BasicType::U8:
460     case BasicType::U16:
461     case BasicType::U32:
462     case BasicType::U64:
463     case BasicType::U128:
464     case BasicType::USize:
465       demangleConstInt();
466       break;
467     case BasicType::Bool:
468       demangleConstBool();
469       break;
470     case BasicType::Char:
471       demangleConstChar();
472       break;
473     case BasicType::Placeholder:
474       print('_');
475       break;
476     default:
477       // FIXME demangle backreferences.
478       Error = true;
479       break;
480     }
481   } else {
482     Error = true;
483   }
484 }
485 
486 // <const-data> = ["n"] <hex-number>
487 void Demangler::demangleConstInt() {
488   if (consumeIf('n'))
489     print('-');
490 
491   StringView HexDigits;
492   uint64_t Value = parseHexNumber(HexDigits);
493   if (HexDigits.size() <= 16) {
494     printDecimalNumber(Value);
495   } else {
496     print("0x");
497     print(HexDigits);
498   }
499 }
500 
501 // <const-data> = "0_" // false
502 //              | "1_" // true
503 void Demangler::demangleConstBool() {
504   StringView HexDigits;
505   parseHexNumber(HexDigits);
506   if (HexDigits == "0")
507     print("false");
508   else if (HexDigits == "1")
509     print("true");
510   else
511     Error = true;
512 }
513 
514 /// Returns true if CodePoint represents a printable ASCII character.
515 static bool isAsciiPrintable(uint64_t CodePoint) {
516   return 0x20 <= CodePoint && CodePoint <= 0x7e;
517 }
518 
519 // <const-data> = <hex-number>
520 void Demangler::demangleConstChar() {
521   StringView HexDigits;
522   uint64_t CodePoint = parseHexNumber(HexDigits);
523   if (Error || HexDigits.size() > 6) {
524     Error = true;
525     return;
526   }
527 
528   print("'");
529   switch (CodePoint) {
530   case '\t':
531     print(R"(\t)");
532     break;
533   case '\r':
534     print(R"(\r)");
535     break;
536   case '\n':
537     print(R"(\n)");
538     break;
539   case '\\':
540     print(R"(\\)");
541     break;
542   case '"':
543     print(R"(")");
544     break;
545   case '\'':
546     print(R"(\')");
547     break;
548   default:
549     if (isAsciiPrintable(CodePoint)) {
550       char C = CodePoint;
551       print(C);
552     } else {
553       print(R"(\u{)");
554       print(HexDigits);
555       print('}');
556     }
557     break;
558   }
559   print('\'');
560 }
561 
562 // <undisambiguated-identifier> = ["u"] <decimal-number> ["_"] <bytes>
563 Identifier Demangler::parseIdentifier() {
564   bool Punycode = consumeIf('u');
565   uint64_t Bytes = parseDecimalNumber();
566 
567   // Underscore resolves the ambiguity when identifier starts with a decimal
568   // digit or another underscore.
569   consumeIf('_');
570 
571   if (Error || Bytes > Input.size() - Position) {
572     Error = true;
573     return {};
574   }
575   StringView S = Input.substr(Position, Bytes);
576   Position += Bytes;
577 
578   if (!std::all_of(S.begin(), S.end(), isValid)) {
579     Error = true;
580     return {};
581   }
582 
583   return {S, Punycode};
584 }
585 
586 // Parses optional base 62 number. The presence of a number is determined using
587 // Tag. Returns 0 when tag is absent and parsed value + 1 otherwise.
588 uint64_t Demangler::parseOptionalBase62Number(char Tag) {
589   if (!consumeIf(Tag))
590     return 0;
591 
592   uint64_t N = parseBase62Number();
593   if (Error || !addAssign(N, 1))
594     return 0;
595 
596   return N;
597 }
598 
599 // Parses base 62 number with <0-9a-zA-Z> as digits. Number is terminated by
600 // "_". All values are offset by 1, so that "_" encodes 0, "0_" encodes 1,
601 // "1_" encodes 2, etc.
602 //
603 // <base-62-number> = {<0-9a-zA-Z>} "_"
604 uint64_t Demangler::parseBase62Number() {
605   if (consumeIf('_'))
606     return 0;
607 
608   uint64_t Value = 0;
609 
610   while (true) {
611     uint64_t Digit;
612     char C = consume();
613 
614     if (C == '_') {
615       break;
616     } else if (isDigit(C)) {
617       Digit = C - '0';
618     } else if (isLower(C)) {
619       Digit = 10 + (C - 'a');
620     } else if (isUpper(C)) {
621       Digit = 10 + 26 + (C - 'A');
622     } else {
623       Error = true;
624       return 0;
625     }
626 
627     if (!mulAssign(Value, 62))
628       return 0;
629 
630     if (!addAssign(Value, Digit))
631       return 0;
632   }
633 
634   if (!addAssign(Value, 1))
635     return 0;
636 
637   return Value;
638 }
639 
640 // Parses a decimal number that had been encoded without any leading zeros.
641 //
642 // <decimal-number> = "0"
643 //                  | <1-9> {<0-9>}
644 uint64_t Demangler::parseDecimalNumber() {
645   char C = look();
646   if (!isDigit(C)) {
647     Error = true;
648     return 0;
649   }
650 
651   if (C == '0') {
652     consume();
653     return 0;
654   }
655 
656   uint64_t Value = 0;
657 
658   while (isDigit(look())) {
659     if (!mulAssign(Value, 10)) {
660       Error = true;
661       return 0;
662     }
663 
664     uint64_t D = consume() - '0';
665     if (!addAssign(Value, D))
666       return 0;
667   }
668 
669   return Value;
670 }
671 
672 // Parses a hexadecimal number with <0-9a-f> as a digits. Returns the parsed
673 // value and stores hex digits in HexDigits. The return value is unspecified if
674 // HexDigits.size() > 16.
675 //
676 // <hex-number> = "0_"
677 //              | <1-9a-f> {<0-9a-f>} "_"
678 uint64_t Demangler::parseHexNumber(StringView &HexDigits) {
679   size_t Start = Position;
680   uint64_t Value = 0;
681 
682   if (!isHexDigit(look()))
683     Error = true;
684 
685   if (consumeIf('0')) {
686     if (!consumeIf('_'))
687       Error = true;
688   } else {
689     while (!Error && !consumeIf('_')) {
690       char C = consume();
691       Value *= 16;
692       if (isDigit(C))
693         Value += C - '0';
694       else if ('a' <= C && C <= 'f')
695         Value += 10 + (C - 'a');
696       else
697         Error = true;
698     }
699   }
700 
701   if (Error) {
702     HexDigits = StringView();
703     return 0;
704   }
705 
706   size_t End = Position - 1;
707   assert(Start < End);
708   HexDigits = Input.substr(Start, End - Start);
709   return Value;
710 }
711