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 BoundLifetimes = 0; 107 108 if (!Mangled.consumeFront("_R")) { 109 Error = true; 110 return false; 111 } 112 Input = Mangled; 113 114 demanglePath(rust_demangle::InType::No); 115 116 // FIXME parse optional <instantiating-crate>. 117 118 if (Position != Input.size()) 119 Error = true; 120 121 return !Error; 122 } 123 124 // Demangles a path. InType indicates whether a path is inside a type. 125 // 126 // <path> = "C" <identifier> // crate root 127 // | "M" <impl-path> <type> // <T> (inherent impl) 128 // | "X" <impl-path> <type> <path> // <T as Trait> (trait impl) 129 // | "Y" <type> <path> // <T as Trait> (trait definition) 130 // | "N" <ns> <path> <identifier> // ...::ident (nested path) 131 // | "I" <path> {<generic-arg>} "E" // ...<T, U> (generic args) 132 // | <backref> 133 // <identifier> = [<disambiguator>] <undisambiguated-identifier> 134 // <ns> = "C" // closure 135 // | "S" // shim 136 // | <A-Z> // other special namespaces 137 // | <a-z> // internal namespaces 138 void Demangler::demanglePath(InType InType) { 139 if (Error || RecursionLevel >= MaxRecursionLevel) { 140 Error = true; 141 return; 142 } 143 SwapAndRestore<size_t> SaveRecursionLevel(RecursionLevel, RecursionLevel + 1); 144 145 switch (consume()) { 146 case 'C': { 147 parseOptionalBase62Number('s'); 148 Identifier Ident = parseIdentifier(); 149 print(Ident.Name); 150 break; 151 } 152 case 'M': { 153 demangleImplPath(InType); 154 print("<"); 155 demangleType(); 156 print(">"); 157 break; 158 } 159 case 'X': { 160 demangleImplPath(InType); 161 print("<"); 162 demangleType(); 163 print(" as "); 164 demanglePath(rust_demangle::InType::Yes); 165 print(">"); 166 break; 167 } 168 case 'Y': { 169 print("<"); 170 demangleType(); 171 print(" as "); 172 demanglePath(rust_demangle::InType::Yes); 173 print(">"); 174 break; 175 } 176 case 'N': { 177 char NS = consume(); 178 if (!isLower(NS) && !isUpper(NS)) { 179 Error = true; 180 break; 181 } 182 demanglePath(InType); 183 184 uint64_t Disambiguator = parseOptionalBase62Number('s'); 185 Identifier Ident = parseIdentifier(); 186 187 if (isUpper(NS)) { 188 // Special namespaces 189 print("::{"); 190 if (NS == 'C') 191 print("closure"); 192 else if (NS == 'S') 193 print("shim"); 194 else 195 print(NS); 196 if (!Ident.empty()) { 197 print(":"); 198 print(Ident.Name); 199 } 200 print('#'); 201 printDecimalNumber(Disambiguator); 202 print('}'); 203 } else { 204 // Implementation internal namespaces. 205 if (!Ident.empty()) { 206 print("::"); 207 print(Ident.Name); 208 } 209 } 210 break; 211 } 212 case 'I': { 213 demanglePath(InType); 214 // Omit "::" when in a type, where it is optional. 215 if (InType == rust_demangle::InType::No) 216 print("::"); 217 print("<"); 218 for (size_t I = 0; !Error && !consumeIf('E'); ++I) { 219 if (I > 0) 220 print(", "); 221 demangleGenericArg(); 222 } 223 print(">"); 224 break; 225 } 226 default: 227 // FIXME parse remaining productions. 228 Error = true; 229 break; 230 } 231 } 232 233 // <impl-path> = [<disambiguator>] <path> 234 // <disambiguator> = "s" <base-62-number> 235 void Demangler::demangleImplPath(InType InType) { 236 SwapAndRestore<bool> SavePrint(Print, false); 237 parseOptionalBase62Number('s'); 238 demanglePath(InType); 239 } 240 241 // <generic-arg> = <lifetime> 242 // | <type> 243 // | "K" <const> 244 // <lifetime> = "L" <base-62-number> 245 void Demangler::demangleGenericArg() { 246 if (consumeIf('L')) 247 printLifetime(parseBase62Number()); 248 else if (consumeIf('K')) 249 demangleConst(); 250 else 251 demangleType(); 252 } 253 254 // <basic-type> = "a" // i8 255 // | "b" // bool 256 // | "c" // char 257 // | "d" // f64 258 // | "e" // str 259 // | "f" // f32 260 // | "h" // u8 261 // | "i" // isize 262 // | "j" // usize 263 // | "l" // i32 264 // | "m" // u32 265 // | "n" // i128 266 // | "o" // u128 267 // | "s" // i16 268 // | "t" // u16 269 // | "u" // () 270 // | "v" // ... 271 // | "x" // i64 272 // | "y" // u64 273 // | "z" // ! 274 // | "p" // placeholder (e.g. for generic params), shown as _ 275 static bool parseBasicType(char C, BasicType &Type) { 276 switch (C) { 277 case 'a': 278 Type = BasicType::I8; 279 return true; 280 case 'b': 281 Type = BasicType::Bool; 282 return true; 283 case 'c': 284 Type = BasicType::Char; 285 return true; 286 case 'd': 287 Type = BasicType::F64; 288 return true; 289 case 'e': 290 Type = BasicType::Str; 291 return true; 292 case 'f': 293 Type = BasicType::F32; 294 return true; 295 case 'h': 296 Type = BasicType::U8; 297 return true; 298 case 'i': 299 Type = BasicType::ISize; 300 return true; 301 case 'j': 302 Type = BasicType::USize; 303 return true; 304 case 'l': 305 Type = BasicType::I32; 306 return true; 307 case 'm': 308 Type = BasicType::U32; 309 return true; 310 case 'n': 311 Type = BasicType::I128; 312 return true; 313 case 'o': 314 Type = BasicType::U128; 315 return true; 316 case 'p': 317 Type = BasicType::Placeholder; 318 return true; 319 case 's': 320 Type = BasicType::I16; 321 return true; 322 case 't': 323 Type = BasicType::U16; 324 return true; 325 case 'u': 326 Type = BasicType::Unit; 327 return true; 328 case 'v': 329 Type = BasicType::Variadic; 330 return true; 331 case 'x': 332 Type = BasicType::I64; 333 return true; 334 case 'y': 335 Type = BasicType::U64; 336 return true; 337 case 'z': 338 Type = BasicType::Never; 339 return true; 340 default: 341 return false; 342 } 343 } 344 345 void Demangler::printBasicType(BasicType Type) { 346 switch (Type) { 347 case BasicType::Bool: 348 print("bool"); 349 break; 350 case BasicType::Char: 351 print("char"); 352 break; 353 case BasicType::I8: 354 print("i8"); 355 break; 356 case BasicType::I16: 357 print("i16"); 358 break; 359 case BasicType::I32: 360 print("i32"); 361 break; 362 case BasicType::I64: 363 print("i64"); 364 break; 365 case BasicType::I128: 366 print("i128"); 367 break; 368 case BasicType::ISize: 369 print("isize"); 370 break; 371 case BasicType::U8: 372 print("u8"); 373 break; 374 case BasicType::U16: 375 print("u16"); 376 break; 377 case BasicType::U32: 378 print("u32"); 379 break; 380 case BasicType::U64: 381 print("u64"); 382 break; 383 case BasicType::U128: 384 print("u128"); 385 break; 386 case BasicType::USize: 387 print("usize"); 388 break; 389 case BasicType::F32: 390 print("f32"); 391 break; 392 case BasicType::F64: 393 print("f64"); 394 break; 395 case BasicType::Str: 396 print("str"); 397 break; 398 case BasicType::Placeholder: 399 print("_"); 400 break; 401 case BasicType::Unit: 402 print("()"); 403 break; 404 case BasicType::Variadic: 405 print("..."); 406 break; 407 case BasicType::Never: 408 print("!"); 409 break; 410 } 411 } 412 413 // <type> = | <basic-type> 414 // | <path> // named type 415 // | "A" <type> <const> // [T; N] 416 // | "S" <type> // [T] 417 // | "T" {<type>} "E" // (T1, T2, T3, ...) 418 // | "R" [<lifetime>] <type> // &T 419 // | "Q" [<lifetime>] <type> // &mut T 420 // | "P" <type> // *const T 421 // | "O" <type> // *mut T 422 // | "F" <fn-sig> // fn(...) -> ... 423 // | "D" <dyn-bounds> <lifetime> // dyn Trait<Assoc = X> + Send + 'a 424 // | <backref> // backref 425 void Demangler::demangleType() { 426 size_t Start = Position; 427 428 char C = consume(); 429 BasicType Type; 430 if (parseBasicType(C, Type)) 431 return printBasicType(Type); 432 433 switch (C) { 434 case 'A': 435 print("["); 436 demangleType(); 437 print("; "); 438 demangleConst(); 439 print("]"); 440 break; 441 case 'S': 442 print("["); 443 demangleType(); 444 print("]"); 445 break; 446 case 'T': { 447 print("("); 448 size_t I = 0; 449 for (; !Error && !consumeIf('E'); ++I) { 450 if (I > 0) 451 print(", "); 452 demangleType(); 453 } 454 if (I == 1) 455 print(","); 456 print(")"); 457 break; 458 } 459 case 'R': 460 case 'Q': 461 print('&'); 462 if (consumeIf('L')) { 463 if (auto Lifetime = parseBase62Number()) { 464 printLifetime(Lifetime); 465 print(' '); 466 } 467 } 468 if (C == 'Q') 469 print("mut "); 470 demangleType(); 471 break; 472 case 'P': 473 print("*const "); 474 demangleType(); 475 break; 476 case 'O': 477 print("*mut "); 478 demangleType(); 479 break; 480 case 'F': 481 demangleFnSig(); 482 break; 483 default: 484 Position = Start; 485 demanglePath(rust_demangle::InType::Yes); 486 break; 487 } 488 } 489 490 // <fn-sig> := [<binder>] ["U"] ["K" <abi>] {<type>} "E" <type> 491 // <abi> = "C" 492 // | <undisambiguated-identifier> 493 void Demangler::demangleFnSig() { 494 SwapAndRestore<size_t> SaveBoundLifetimes(BoundLifetimes, BoundLifetimes); 495 demangleOptionalBinder(); 496 497 if (consumeIf('U')) 498 print("unsafe "); 499 500 if (consumeIf('K')) { 501 print("extern \""); 502 if (consumeIf('C')) { 503 print("C"); 504 } else { 505 Identifier Ident = parseIdentifier(); 506 for (char C : Ident.Name) { 507 // When mangling ABI string, the "-" is replaced with "_". 508 if (C == '_') 509 C = '-'; 510 print(C); 511 } 512 } 513 print("\" "); 514 } 515 516 print("fn("); 517 for (size_t I = 0; !Error && !consumeIf('E'); ++I) { 518 if (I > 0) 519 print(", "); 520 demangleType(); 521 } 522 print(")"); 523 524 if (consumeIf('u')) { 525 // Skip the unit type from the output. 526 } else { 527 print(" -> "); 528 demangleType(); 529 } 530 } 531 532 // Demangles optional binder and updates the number of bound lifetimes. 533 // 534 // <binder> = "G" <base-62-number> 535 void Demangler::demangleOptionalBinder() { 536 uint64_t Binder = parseOptionalBase62Number('G'); 537 if (Error || Binder == 0) 538 return; 539 540 // In valid inputs each bound lifetime is referenced later. Referencing a 541 // lifetime requires at least one byte of input. Reject inputs that are too 542 // short to reference all bound lifetimes. Otherwise demangling of invalid 543 // binders could generate excessive amounts of output. 544 if (Binder >= Input.size() - BoundLifetimes) { 545 Error = true; 546 return; 547 } 548 549 print("for<"); 550 for (size_t I = 0; I != Binder; ++I) { 551 BoundLifetimes += 1; 552 if (I > 0) 553 print(", "); 554 printLifetime(1); 555 } 556 print("> "); 557 } 558 559 // <const> = <basic-type> <const-data> 560 // | "p" // placeholder 561 // | <backref> 562 void Demangler::demangleConst() { 563 BasicType Type; 564 if (parseBasicType(consume(), Type)) { 565 switch (Type) { 566 case BasicType::I8: 567 case BasicType::I16: 568 case BasicType::I32: 569 case BasicType::I64: 570 case BasicType::I128: 571 case BasicType::ISize: 572 case BasicType::U8: 573 case BasicType::U16: 574 case BasicType::U32: 575 case BasicType::U64: 576 case BasicType::U128: 577 case BasicType::USize: 578 demangleConstInt(); 579 break; 580 case BasicType::Bool: 581 demangleConstBool(); 582 break; 583 case BasicType::Char: 584 demangleConstChar(); 585 break; 586 case BasicType::Placeholder: 587 print('_'); 588 break; 589 default: 590 // FIXME demangle backreferences. 591 Error = true; 592 break; 593 } 594 } else { 595 Error = true; 596 } 597 } 598 599 // <const-data> = ["n"] <hex-number> 600 void Demangler::demangleConstInt() { 601 if (consumeIf('n')) 602 print('-'); 603 604 StringView HexDigits; 605 uint64_t Value = parseHexNumber(HexDigits); 606 if (HexDigits.size() <= 16) { 607 printDecimalNumber(Value); 608 } else { 609 print("0x"); 610 print(HexDigits); 611 } 612 } 613 614 // <const-data> = "0_" // false 615 // | "1_" // true 616 void Demangler::demangleConstBool() { 617 StringView HexDigits; 618 parseHexNumber(HexDigits); 619 if (HexDigits == "0") 620 print("false"); 621 else if (HexDigits == "1") 622 print("true"); 623 else 624 Error = true; 625 } 626 627 /// Returns true if CodePoint represents a printable ASCII character. 628 static bool isAsciiPrintable(uint64_t CodePoint) { 629 return 0x20 <= CodePoint && CodePoint <= 0x7e; 630 } 631 632 // <const-data> = <hex-number> 633 void Demangler::demangleConstChar() { 634 StringView HexDigits; 635 uint64_t CodePoint = parseHexNumber(HexDigits); 636 if (Error || HexDigits.size() > 6) { 637 Error = true; 638 return; 639 } 640 641 print("'"); 642 switch (CodePoint) { 643 case '\t': 644 print(R"(\t)"); 645 break; 646 case '\r': 647 print(R"(\r)"); 648 break; 649 case '\n': 650 print(R"(\n)"); 651 break; 652 case '\\': 653 print(R"(\\)"); 654 break; 655 case '"': 656 print(R"(")"); 657 break; 658 case '\'': 659 print(R"(\')"); 660 break; 661 default: 662 if (isAsciiPrintable(CodePoint)) { 663 char C = CodePoint; 664 print(C); 665 } else { 666 print(R"(\u{)"); 667 print(HexDigits); 668 print('}'); 669 } 670 break; 671 } 672 print('\''); 673 } 674 675 // <undisambiguated-identifier> = ["u"] <decimal-number> ["_"] <bytes> 676 Identifier Demangler::parseIdentifier() { 677 bool Punycode = consumeIf('u'); 678 uint64_t Bytes = parseDecimalNumber(); 679 680 // Underscore resolves the ambiguity when identifier starts with a decimal 681 // digit or another underscore. 682 consumeIf('_'); 683 684 if (Error || Bytes > Input.size() - Position) { 685 Error = true; 686 return {}; 687 } 688 StringView S = Input.substr(Position, Bytes); 689 Position += Bytes; 690 691 if (!std::all_of(S.begin(), S.end(), isValid)) { 692 Error = true; 693 return {}; 694 } 695 696 return {S, Punycode}; 697 } 698 699 // Parses optional base 62 number. The presence of a number is determined using 700 // Tag. Returns 0 when tag is absent and parsed value + 1 otherwise 701 // 702 // This function is indended for parsing disambiguators and binders which when 703 // not present have their value interpreted as 0, and otherwise as decoded 704 // value + 1. For example for binders, value for "G_" is 1, for "G0_" value is 705 // 2. When "G" is absent value is 0. 706 uint64_t Demangler::parseOptionalBase62Number(char Tag) { 707 if (!consumeIf(Tag)) 708 return 0; 709 710 uint64_t N = parseBase62Number(); 711 if (Error || !addAssign(N, 1)) 712 return 0; 713 714 return N; 715 } 716 717 // Parses base 62 number with <0-9a-zA-Z> as digits. Number is terminated by 718 // "_". All values are offset by 1, so that "_" encodes 0, "0_" encodes 1, 719 // "1_" encodes 2, etc. 720 // 721 // <base-62-number> = {<0-9a-zA-Z>} "_" 722 uint64_t Demangler::parseBase62Number() { 723 if (consumeIf('_')) 724 return 0; 725 726 uint64_t Value = 0; 727 728 while (true) { 729 uint64_t Digit; 730 char C = consume(); 731 732 if (C == '_') { 733 break; 734 } else if (isDigit(C)) { 735 Digit = C - '0'; 736 } else if (isLower(C)) { 737 Digit = 10 + (C - 'a'); 738 } else if (isUpper(C)) { 739 Digit = 10 + 26 + (C - 'A'); 740 } else { 741 Error = true; 742 return 0; 743 } 744 745 if (!mulAssign(Value, 62)) 746 return 0; 747 748 if (!addAssign(Value, Digit)) 749 return 0; 750 } 751 752 if (!addAssign(Value, 1)) 753 return 0; 754 755 return Value; 756 } 757 758 // Parses a decimal number that had been encoded without any leading zeros. 759 // 760 // <decimal-number> = "0" 761 // | <1-9> {<0-9>} 762 uint64_t Demangler::parseDecimalNumber() { 763 char C = look(); 764 if (!isDigit(C)) { 765 Error = true; 766 return 0; 767 } 768 769 if (C == '0') { 770 consume(); 771 return 0; 772 } 773 774 uint64_t Value = 0; 775 776 while (isDigit(look())) { 777 if (!mulAssign(Value, 10)) { 778 Error = true; 779 return 0; 780 } 781 782 uint64_t D = consume() - '0'; 783 if (!addAssign(Value, D)) 784 return 0; 785 } 786 787 return Value; 788 } 789 790 // Parses a hexadecimal number with <0-9a-f> as a digits. Returns the parsed 791 // value and stores hex digits in HexDigits. The return value is unspecified if 792 // HexDigits.size() > 16. 793 // 794 // <hex-number> = "0_" 795 // | <1-9a-f> {<0-9a-f>} "_" 796 uint64_t Demangler::parseHexNumber(StringView &HexDigits) { 797 size_t Start = Position; 798 uint64_t Value = 0; 799 800 if (!isHexDigit(look())) 801 Error = true; 802 803 if (consumeIf('0')) { 804 if (!consumeIf('_')) 805 Error = true; 806 } else { 807 while (!Error && !consumeIf('_')) { 808 char C = consume(); 809 Value *= 16; 810 if (isDigit(C)) 811 Value += C - '0'; 812 else if ('a' <= C && C <= 'f') 813 Value += 10 + (C - 'a'); 814 else 815 Error = true; 816 } 817 } 818 819 if (Error) { 820 HexDigits = StringView(); 821 return 0; 822 } 823 824 size_t End = Position - 1; 825 assert(Start < End); 826 HexDigits = Input.substr(Start, End - Start); 827 return Value; 828 } 829 830 // Prints a lifetime. An index 0 always represents an erased lifetime. Indices 831 // starting from 1, are De Bruijn indices, referring to higher-ranked lifetimes 832 // bound by one of the enclosing binders. 833 void Demangler::printLifetime(uint64_t Index) { 834 if (Index == 0) { 835 print("'_"); 836 return; 837 } 838 839 if (Index - 1 >= BoundLifetimes) { 840 Error = true; 841 return; 842 } 843 844 uint64_t Depth = BoundLifetimes - Index; 845 print('\''); 846 if (Depth < 26) { 847 char C = 'a' + Depth; 848 print(C); 849 } else { 850 print('z'); 851 printDecimalNumber(Depth - 26 + 1); 852 } 853 } 854