demangle.cc 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // For reference check out:
  15. // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
  16. //
  17. // Note that we only have partial C++11 support yet.
  18. #include "absl/debugging/internal/demangle.h"
  19. #include <cstdint>
  20. #include <cstdio>
  21. #include <cstdlib>
  22. #include <limits>
  23. #include <string>
  24. #include "absl/base/config.h"
  25. #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
  26. #include <cxxabi.h>
  27. #endif
  28. namespace absl {
  29. ABSL_NAMESPACE_BEGIN
  30. namespace debugging_internal {
  31. typedef struct {
  32. const char *abbrev;
  33. const char *real_name;
  34. // Number of arguments in <expression> context, or 0 if disallowed.
  35. int arity;
  36. } AbbrevPair;
  37. // List of operators from Itanium C++ ABI.
  38. static const AbbrevPair kOperatorList[] = {
  39. // New has special syntax (not currently supported).
  40. {"nw", "new", 0},
  41. {"na", "new[]", 0},
  42. // Works except that the 'gs' prefix is not supported.
  43. {"dl", "delete", 1},
  44. {"da", "delete[]", 1},
  45. {"ps", "+", 1}, // "positive"
  46. {"ng", "-", 1}, // "negative"
  47. {"ad", "&", 1}, // "address-of"
  48. {"de", "*", 1}, // "dereference"
  49. {"co", "~", 1},
  50. {"pl", "+", 2},
  51. {"mi", "-", 2},
  52. {"ml", "*", 2},
  53. {"dv", "/", 2},
  54. {"rm", "%", 2},
  55. {"an", "&", 2},
  56. {"or", "|", 2},
  57. {"eo", "^", 2},
  58. {"aS", "=", 2},
  59. {"pL", "+=", 2},
  60. {"mI", "-=", 2},
  61. {"mL", "*=", 2},
  62. {"dV", "/=", 2},
  63. {"rM", "%=", 2},
  64. {"aN", "&=", 2},
  65. {"oR", "|=", 2},
  66. {"eO", "^=", 2},
  67. {"ls", "<<", 2},
  68. {"rs", ">>", 2},
  69. {"lS", "<<=", 2},
  70. {"rS", ">>=", 2},
  71. {"eq", "==", 2},
  72. {"ne", "!=", 2},
  73. {"lt", "<", 2},
  74. {"gt", ">", 2},
  75. {"le", "<=", 2},
  76. {"ge", ">=", 2},
  77. {"nt", "!", 1},
  78. {"aa", "&&", 2},
  79. {"oo", "||", 2},
  80. {"pp", "++", 1},
  81. {"mm", "--", 1},
  82. {"cm", ",", 2},
  83. {"pm", "->*", 2},
  84. {"pt", "->", 0}, // Special syntax
  85. {"cl", "()", 0}, // Special syntax
  86. {"ix", "[]", 2},
  87. {"qu", "?", 3},
  88. {"st", "sizeof", 0}, // Special syntax
  89. {"sz", "sizeof", 1}, // Not a real operator name, but used in expressions.
  90. {nullptr, nullptr, 0},
  91. };
  92. // List of builtin types from Itanium C++ ABI.
  93. //
  94. // Invariant: only one- or two-character type abbreviations here.
  95. static const AbbrevPair kBuiltinTypeList[] = {
  96. {"v", "void", 0},
  97. {"w", "wchar_t", 0},
  98. {"b", "bool", 0},
  99. {"c", "char", 0},
  100. {"a", "signed char", 0},
  101. {"h", "unsigned char", 0},
  102. {"s", "short", 0},
  103. {"t", "unsigned short", 0},
  104. {"i", "int", 0},
  105. {"j", "unsigned int", 0},
  106. {"l", "long", 0},
  107. {"m", "unsigned long", 0},
  108. {"x", "long long", 0},
  109. {"y", "unsigned long long", 0},
  110. {"n", "__int128", 0},
  111. {"o", "unsigned __int128", 0},
  112. {"f", "float", 0},
  113. {"d", "double", 0},
  114. {"e", "long double", 0},
  115. {"g", "__float128", 0},
  116. {"z", "ellipsis", 0},
  117. {"De", "decimal128", 0}, // IEEE 754r decimal floating point (128 bits)
  118. {"Dd", "decimal64", 0}, // IEEE 754r decimal floating point (64 bits)
  119. {"Dc", "decltype(auto)", 0},
  120. {"Da", "auto", 0},
  121. {"Dn", "std::nullptr_t", 0}, // i.e., decltype(nullptr)
  122. {"Df", "decimal32", 0}, // IEEE 754r decimal floating point (32 bits)
  123. {"Di", "char32_t", 0},
  124. {"Du", "char8_t", 0},
  125. {"Ds", "char16_t", 0},
  126. {"Dh", "float16", 0}, // IEEE 754r half-precision float (16 bits)
  127. {nullptr, nullptr, 0},
  128. };
  129. // List of substitutions Itanium C++ ABI.
  130. static const AbbrevPair kSubstitutionList[] = {
  131. {"St", "", 0},
  132. {"Sa", "allocator", 0},
  133. {"Sb", "basic_string", 0},
  134. // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
  135. {"Ss", "string", 0},
  136. // std::basic_istream<char, std::char_traits<char> >
  137. {"Si", "istream", 0},
  138. // std::basic_ostream<char, std::char_traits<char> >
  139. {"So", "ostream", 0},
  140. // std::basic_iostream<char, std::char_traits<char> >
  141. {"Sd", "iostream", 0},
  142. {nullptr, nullptr, 0},
  143. };
  144. // State needed for demangling. This struct is copied in almost every stack
  145. // frame, so every byte counts.
  146. typedef struct {
  147. int mangled_idx; // Cursor of mangled name.
  148. int out_cur_idx; // Cursor of output string.
  149. int prev_name_idx; // For constructors/destructors.
  150. unsigned int prev_name_length : 16; // For constructors/destructors.
  151. signed int nest_level : 15; // For nested names.
  152. unsigned int append : 1; // Append flag.
  153. // Note: for some reason MSVC can't pack "bool append : 1" into the same int
  154. // with the above two fields, so we use an int instead. Amusingly it can pack
  155. // "signed bool" as expected, but relying on that to continue to be a legal
  156. // type seems ill-advised (as it's illegal in at least clang).
  157. } ParseState;
  158. static_assert(sizeof(ParseState) == 4 * sizeof(int),
  159. "unexpected size of ParseState");
  160. // One-off state for demangling that's not subject to backtracking -- either
  161. // constant data, data that's intentionally immune to backtracking (steps), or
  162. // data that would never be changed by backtracking anyway (recursion_depth).
  163. //
  164. // Only one copy of this exists for each call to Demangle, so the size of this
  165. // struct is nearly inconsequential.
  166. typedef struct {
  167. const char *mangled_begin; // Beginning of input string.
  168. char *out; // Beginning of output string.
  169. int out_end_idx; // One past last allowed output character.
  170. int recursion_depth; // For stack exhaustion prevention.
  171. int steps; // Cap how much work we'll do, regardless of depth.
  172. ParseState parse_state; // Backtrackable state copied for most frames.
  173. } State;
  174. namespace {
  175. // Prevent deep recursion / stack exhaustion.
  176. // Also prevent unbounded handling of complex inputs.
  177. class ComplexityGuard {
  178. public:
  179. explicit ComplexityGuard(State *state) : state_(state) {
  180. ++state->recursion_depth;
  181. ++state->steps;
  182. }
  183. ~ComplexityGuard() { --state_->recursion_depth; }
  184. // 256 levels of recursion seems like a reasonable upper limit on depth.
  185. // 128 is not enough to demagle synthetic tests from demangle_unittest.txt:
  186. // "_ZaaZZZZ..." and "_ZaaZcvZcvZ..."
  187. static constexpr int kRecursionDepthLimit = 256;
  188. // We're trying to pick a charitable upper-limit on how many parse steps are
  189. // necessary to handle something that a human could actually make use of.
  190. // This is mostly in place as a bound on how much work we'll do if we are
  191. // asked to demangle an mangled name from an untrusted source, so it should be
  192. // much larger than the largest expected symbol, but much smaller than the
  193. // amount of work we can do in, e.g., a second.
  194. //
  195. // Some real-world symbols from an arbitrary binary started failing between
  196. // 2^12 and 2^13, so we multiply the latter by an extra factor of 16 to set
  197. // the limit.
  198. //
  199. // Spending one second on 2^17 parse steps would require each step to take
  200. // 7.6us, or ~30000 clock cycles, so it's safe to say this can be done in
  201. // under a second.
  202. static constexpr int kParseStepsLimit = 1 << 17;
  203. bool IsTooComplex() const {
  204. return state_->recursion_depth > kRecursionDepthLimit ||
  205. state_->steps > kParseStepsLimit;
  206. }
  207. private:
  208. State *state_;
  209. };
  210. } // namespace
  211. // We don't use strlen() in libc since it's not guaranteed to be async
  212. // signal safe.
  213. static size_t StrLen(const char *str) {
  214. size_t len = 0;
  215. while (*str != '\0') {
  216. ++str;
  217. ++len;
  218. }
  219. return len;
  220. }
  221. // Returns true if "str" has at least "n" characters remaining.
  222. static bool AtLeastNumCharsRemaining(const char *str, size_t n) {
  223. for (size_t i = 0; i < n; ++i) {
  224. if (str[i] == '\0') {
  225. return false;
  226. }
  227. }
  228. return true;
  229. }
  230. // Returns true if "str" has "prefix" as a prefix.
  231. static bool StrPrefix(const char *str, const char *prefix) {
  232. size_t i = 0;
  233. while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) {
  234. ++i;
  235. }
  236. return prefix[i] == '\0'; // Consumed everything in "prefix".
  237. }
  238. static void InitState(State* state,
  239. const char* mangled,
  240. char* out,
  241. size_t out_size) {
  242. state->mangled_begin = mangled;
  243. state->out = out;
  244. state->out_end_idx = static_cast<int>(out_size);
  245. state->recursion_depth = 0;
  246. state->steps = 0;
  247. state->parse_state.mangled_idx = 0;
  248. state->parse_state.out_cur_idx = 0;
  249. state->parse_state.prev_name_idx = 0;
  250. state->parse_state.prev_name_length = 0;
  251. state->parse_state.nest_level = -1;
  252. state->parse_state.append = true;
  253. }
  254. static inline const char *RemainingInput(State *state) {
  255. return &state->mangled_begin[state->parse_state.mangled_idx];
  256. }
  257. // Returns true and advances "mangled_idx" if we find "one_char_token"
  258. // at "mangled_idx" position. It is assumed that "one_char_token" does
  259. // not contain '\0'.
  260. static bool ParseOneCharToken(State *state, const char one_char_token) {
  261. ComplexityGuard guard(state);
  262. if (guard.IsTooComplex()) return false;
  263. if (RemainingInput(state)[0] == one_char_token) {
  264. ++state->parse_state.mangled_idx;
  265. return true;
  266. }
  267. return false;
  268. }
  269. // Returns true and advances "mangled_cur" if we find "two_char_token"
  270. // at "mangled_cur" position. It is assumed that "two_char_token" does
  271. // not contain '\0'.
  272. static bool ParseTwoCharToken(State *state, const char *two_char_token) {
  273. ComplexityGuard guard(state);
  274. if (guard.IsTooComplex()) return false;
  275. if (RemainingInput(state)[0] == two_char_token[0] &&
  276. RemainingInput(state)[1] == two_char_token[1]) {
  277. state->parse_state.mangled_idx += 2;
  278. return true;
  279. }
  280. return false;
  281. }
  282. // Returns true and advances "mangled_cur" if we find any character in
  283. // "char_class" at "mangled_cur" position.
  284. static bool ParseCharClass(State *state, const char *char_class) {
  285. ComplexityGuard guard(state);
  286. if (guard.IsTooComplex()) return false;
  287. if (RemainingInput(state)[0] == '\0') {
  288. return false;
  289. }
  290. const char *p = char_class;
  291. for (; *p != '\0'; ++p) {
  292. if (RemainingInput(state)[0] == *p) {
  293. ++state->parse_state.mangled_idx;
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. static bool ParseDigit(State *state, int *digit) {
  300. char c = RemainingInput(state)[0];
  301. if (ParseCharClass(state, "0123456789")) {
  302. if (digit != nullptr) {
  303. *digit = c - '0';
  304. }
  305. return true;
  306. }
  307. return false;
  308. }
  309. // This function is used for handling an optional non-terminal.
  310. static bool Optional(bool /*status*/) { return true; }
  311. // This function is used for handling <non-terminal>+ syntax.
  312. typedef bool (*ParseFunc)(State *);
  313. static bool OneOrMore(ParseFunc parse_func, State *state) {
  314. if (parse_func(state)) {
  315. while (parse_func(state)) {
  316. }
  317. return true;
  318. }
  319. return false;
  320. }
  321. // This function is used for handling <non-terminal>* syntax. The function
  322. // always returns true and must be followed by a termination token or a
  323. // terminating sequence not handled by parse_func (e.g.
  324. // ParseOneCharToken(state, 'E')).
  325. static bool ZeroOrMore(ParseFunc parse_func, State *state) {
  326. while (parse_func(state)) {
  327. }
  328. return true;
  329. }
  330. // Append "str" at "out_cur_idx". If there is an overflow, out_cur_idx is
  331. // set to out_end_idx+1. The output string is ensured to
  332. // always terminate with '\0' as long as there is no overflow.
  333. static void Append(State *state, const char *const str, const size_t length) {
  334. for (size_t i = 0; i < length; ++i) {
  335. if (state->parse_state.out_cur_idx + 1 <
  336. state->out_end_idx) { // +1 for '\0'
  337. state->out[state->parse_state.out_cur_idx++] = str[i];
  338. } else {
  339. // signal overflow
  340. state->parse_state.out_cur_idx = state->out_end_idx + 1;
  341. break;
  342. }
  343. }
  344. if (state->parse_state.out_cur_idx < state->out_end_idx) {
  345. state->out[state->parse_state.out_cur_idx] =
  346. '\0'; // Terminate it with '\0'
  347. }
  348. }
  349. // We don't use equivalents in libc to avoid locale issues.
  350. static bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
  351. static bool IsAlpha(char c) {
  352. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  353. }
  354. static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
  355. // Returns true if "str" is a function clone suffix. These suffixes are used
  356. // by GCC 4.5.x and later versions (and our locally-modified version of GCC
  357. // 4.4.x) to indicate functions which have been cloned during optimization.
  358. // We treat any sequence (.<alpha>+.<digit>+)+ as a function clone suffix.
  359. // Additionally, '_' is allowed along with the alphanumeric sequence.
  360. static bool IsFunctionCloneSuffix(const char *str) {
  361. size_t i = 0;
  362. while (str[i] != '\0') {
  363. bool parsed = false;
  364. // Consume a single [.<alpha> | _]*[.<digit>]* sequence.
  365. if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) {
  366. parsed = true;
  367. i += 2;
  368. while (IsAlpha(str[i]) || str[i] == '_') {
  369. ++i;
  370. }
  371. }
  372. if (str[i] == '.' && IsDigit(str[i + 1])) {
  373. parsed = true;
  374. i += 2;
  375. while (IsDigit(str[i])) {
  376. ++i;
  377. }
  378. }
  379. if (!parsed)
  380. return false;
  381. }
  382. return true; // Consumed everything in "str".
  383. }
  384. static bool EndsWith(State *state, const char chr) {
  385. return state->parse_state.out_cur_idx > 0 &&
  386. state->parse_state.out_cur_idx < state->out_end_idx &&
  387. chr == state->out[state->parse_state.out_cur_idx - 1];
  388. }
  389. // Append "str" with some tweaks, iff "append" state is true.
  390. static void MaybeAppendWithLength(State *state, const char *const str,
  391. const size_t length) {
  392. if (state->parse_state.append && length > 0) {
  393. // Append a space if the output buffer ends with '<' and "str"
  394. // starts with '<' to avoid <<<.
  395. if (str[0] == '<' && EndsWith(state, '<')) {
  396. Append(state, " ", 1);
  397. }
  398. // Remember the last identifier name for ctors/dtors,
  399. // but only if we haven't yet overflown the buffer.
  400. if (state->parse_state.out_cur_idx < state->out_end_idx &&
  401. (IsAlpha(str[0]) || str[0] == '_')) {
  402. state->parse_state.prev_name_idx = state->parse_state.out_cur_idx;
  403. state->parse_state.prev_name_length = static_cast<unsigned int>(length);
  404. }
  405. Append(state, str, length);
  406. }
  407. }
  408. // Appends a positive decimal number to the output if appending is enabled.
  409. static bool MaybeAppendDecimal(State *state, int val) {
  410. // Max {32-64}-bit unsigned int is 20 digits.
  411. constexpr size_t kMaxLength = 20;
  412. char buf[kMaxLength];
  413. // We can't use itoa or sprintf as neither is specified to be
  414. // async-signal-safe.
  415. if (state->parse_state.append) {
  416. // We can't have a one-before-the-beginning pointer, so instead start with
  417. // one-past-the-end and manipulate one character before the pointer.
  418. char *p = &buf[kMaxLength];
  419. do { // val=0 is the only input that should write a leading zero digit.
  420. *--p = static_cast<char>((val % 10) + '0');
  421. val /= 10;
  422. } while (p > buf && val != 0);
  423. // 'p' landed on the last character we set. How convenient.
  424. Append(state, p, kMaxLength - static_cast<size_t>(p - buf));
  425. }
  426. return true;
  427. }
  428. // A convenient wrapper around MaybeAppendWithLength().
  429. // Returns true so that it can be placed in "if" conditions.
  430. static bool MaybeAppend(State *state, const char *const str) {
  431. if (state->parse_state.append) {
  432. size_t length = StrLen(str);
  433. MaybeAppendWithLength(state, str, length);
  434. }
  435. return true;
  436. }
  437. // This function is used for handling nested names.
  438. static bool EnterNestedName(State *state) {
  439. state->parse_state.nest_level = 0;
  440. return true;
  441. }
  442. // This function is used for handling nested names.
  443. static bool LeaveNestedName(State *state, int16_t prev_value) {
  444. state->parse_state.nest_level = prev_value;
  445. return true;
  446. }
  447. // Disable the append mode not to print function parameters, etc.
  448. static bool DisableAppend(State *state) {
  449. state->parse_state.append = false;
  450. return true;
  451. }
  452. // Restore the append mode to the previous state.
  453. static bool RestoreAppend(State *state, bool prev_value) {
  454. state->parse_state.append = prev_value;
  455. return true;
  456. }
  457. // Increase the nest level for nested names.
  458. static void MaybeIncreaseNestLevel(State *state) {
  459. if (state->parse_state.nest_level > -1) {
  460. ++state->parse_state.nest_level;
  461. }
  462. }
  463. // Appends :: for nested names if necessary.
  464. static void MaybeAppendSeparator(State *state) {
  465. if (state->parse_state.nest_level >= 1) {
  466. MaybeAppend(state, "::");
  467. }
  468. }
  469. // Cancel the last separator if necessary.
  470. static void MaybeCancelLastSeparator(State *state) {
  471. if (state->parse_state.nest_level >= 1 && state->parse_state.append &&
  472. state->parse_state.out_cur_idx >= 2) {
  473. state->parse_state.out_cur_idx -= 2;
  474. state->out[state->parse_state.out_cur_idx] = '\0';
  475. }
  476. }
  477. // Returns true if the identifier of the given length pointed to by
  478. // "mangled_cur" is anonymous namespace.
  479. static bool IdentifierIsAnonymousNamespace(State *state, size_t length) {
  480. // Returns true if "anon_prefix" is a proper prefix of "mangled_cur".
  481. static const char anon_prefix[] = "_GLOBAL__N_";
  482. return (length > (sizeof(anon_prefix) - 1) &&
  483. StrPrefix(RemainingInput(state), anon_prefix));
  484. }
  485. // Forward declarations of our parsing functions.
  486. static bool ParseMangledName(State *state);
  487. static bool ParseEncoding(State *state);
  488. static bool ParseName(State *state);
  489. static bool ParseUnscopedName(State *state);
  490. static bool ParseNestedName(State *state);
  491. static bool ParsePrefix(State *state);
  492. static bool ParseUnqualifiedName(State *state);
  493. static bool ParseSourceName(State *state);
  494. static bool ParseLocalSourceName(State *state);
  495. static bool ParseUnnamedTypeName(State *state);
  496. static bool ParseNumber(State *state, int *number_out);
  497. static bool ParseFloatNumber(State *state);
  498. static bool ParseSeqId(State *state);
  499. static bool ParseIdentifier(State *state, size_t length);
  500. static bool ParseOperatorName(State *state, int *arity);
  501. static bool ParseSpecialName(State *state);
  502. static bool ParseCallOffset(State *state);
  503. static bool ParseNVOffset(State *state);
  504. static bool ParseVOffset(State *state);
  505. static bool ParseAbiTags(State *state);
  506. static bool ParseCtorDtorName(State *state);
  507. static bool ParseDecltype(State *state);
  508. static bool ParseType(State *state);
  509. static bool ParseCVQualifiers(State *state);
  510. static bool ParseBuiltinType(State *state);
  511. static bool ParseFunctionType(State *state);
  512. static bool ParseBareFunctionType(State *state);
  513. static bool ParseClassEnumType(State *state);
  514. static bool ParseArrayType(State *state);
  515. static bool ParsePointerToMemberType(State *state);
  516. static bool ParseTemplateParam(State *state);
  517. static bool ParseTemplateTemplateParam(State *state);
  518. static bool ParseTemplateArgs(State *state);
  519. static bool ParseTemplateArg(State *state);
  520. static bool ParseBaseUnresolvedName(State *state);
  521. static bool ParseUnresolvedName(State *state);
  522. static bool ParseExpression(State *state);
  523. static bool ParseExprPrimary(State *state);
  524. static bool ParseExprCastValue(State *state);
  525. static bool ParseLocalName(State *state);
  526. static bool ParseLocalNameSuffix(State *state);
  527. static bool ParseDiscriminator(State *state);
  528. static bool ParseSubstitution(State *state, bool accept_std);
  529. // Implementation note: the following code is a straightforward
  530. // translation of the Itanium C++ ABI defined in BNF with a couple of
  531. // exceptions.
  532. //
  533. // - Support GNU extensions not defined in the Itanium C++ ABI
  534. // - <prefix> and <template-prefix> are combined to avoid infinite loop
  535. // - Reorder patterns to shorten the code
  536. // - Reorder patterns to give greedier functions precedence
  537. // We'll mark "Less greedy than" for these cases in the code
  538. //
  539. // Each parsing function changes the parse state and returns true on
  540. // success, or returns false and doesn't change the parse state (note:
  541. // the parse-steps counter increases regardless of success or failure).
  542. // To ensure that the parse state isn't changed in the latter case, we
  543. // save the original state before we call multiple parsing functions
  544. // consecutively with &&, and restore it if unsuccessful. See
  545. // ParseEncoding() as an example of this convention. We follow the
  546. // convention throughout the code.
  547. //
  548. // Originally we tried to do demangling without following the full ABI
  549. // syntax but it turned out we needed to follow the full syntax to
  550. // parse complicated cases like nested template arguments. Note that
  551. // implementing a full-fledged demangler isn't trivial (libiberty's
  552. // cp-demangle.c has +4300 lines).
  553. //
  554. // Note that (foo) in <(foo) ...> is a modifier to be ignored.
  555. //
  556. // Reference:
  557. // - Itanium C++ ABI
  558. // <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>
  559. // <mangled-name> ::= _Z <encoding>
  560. static bool ParseMangledName(State *state) {
  561. ComplexityGuard guard(state);
  562. if (guard.IsTooComplex()) return false;
  563. return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
  564. }
  565. // <encoding> ::= <(function) name> <bare-function-type>
  566. // ::= <(data) name>
  567. // ::= <special-name>
  568. static bool ParseEncoding(State *state) {
  569. ComplexityGuard guard(state);
  570. if (guard.IsTooComplex()) return false;
  571. // Implementing the first two productions together as <name>
  572. // [<bare-function-type>] avoids exponential blowup of backtracking.
  573. //
  574. // Since Optional(...) can't fail, there's no need to copy the state for
  575. // backtracking.
  576. if (ParseName(state) && Optional(ParseBareFunctionType(state))) {
  577. return true;
  578. }
  579. if (ParseSpecialName(state)) {
  580. return true;
  581. }
  582. return false;
  583. }
  584. // <name> ::= <nested-name>
  585. // ::= <unscoped-template-name> <template-args>
  586. // ::= <unscoped-name>
  587. // ::= <local-name>
  588. static bool ParseName(State *state) {
  589. ComplexityGuard guard(state);
  590. if (guard.IsTooComplex()) return false;
  591. if (ParseNestedName(state) || ParseLocalName(state)) {
  592. return true;
  593. }
  594. // We reorganize the productions to avoid re-parsing unscoped names.
  595. // - Inline <unscoped-template-name> productions:
  596. // <name> ::= <substitution> <template-args>
  597. // ::= <unscoped-name> <template-args>
  598. // ::= <unscoped-name>
  599. // - Merge the two productions that start with unscoped-name:
  600. // <name> ::= <unscoped-name> [<template-args>]
  601. ParseState copy = state->parse_state;
  602. // "std<...>" isn't a valid name.
  603. if (ParseSubstitution(state, /*accept_std=*/false) &&
  604. ParseTemplateArgs(state)) {
  605. return true;
  606. }
  607. state->parse_state = copy;
  608. // Note there's no need to restore state after this since only the first
  609. // subparser can fail.
  610. return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state));
  611. }
  612. // <unscoped-name> ::= <unqualified-name>
  613. // ::= St <unqualified-name>
  614. static bool ParseUnscopedName(State *state) {
  615. ComplexityGuard guard(state);
  616. if (guard.IsTooComplex()) return false;
  617. if (ParseUnqualifiedName(state)) {
  618. return true;
  619. }
  620. ParseState copy = state->parse_state;
  621. if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") &&
  622. ParseUnqualifiedName(state)) {
  623. return true;
  624. }
  625. state->parse_state = copy;
  626. return false;
  627. }
  628. // <ref-qualifer> ::= R // lvalue method reference qualifier
  629. // ::= O // rvalue method reference qualifier
  630. static inline bool ParseRefQualifier(State *state) {
  631. return ParseCharClass(state, "OR");
  632. }
  633. // <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix>
  634. // <unqualified-name> E
  635. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
  636. // <template-args> E
  637. static bool ParseNestedName(State *state) {
  638. ComplexityGuard guard(state);
  639. if (guard.IsTooComplex()) return false;
  640. ParseState copy = state->parse_state;
  641. if (ParseOneCharToken(state, 'N') && EnterNestedName(state) &&
  642. Optional(ParseCVQualifiers(state)) &&
  643. Optional(ParseRefQualifier(state)) && ParsePrefix(state) &&
  644. LeaveNestedName(state, copy.nest_level) &&
  645. ParseOneCharToken(state, 'E')) {
  646. return true;
  647. }
  648. state->parse_state = copy;
  649. return false;
  650. }
  651. // This part is tricky. If we literally translate them to code, we'll
  652. // end up infinite loop. Hence we merge them to avoid the case.
  653. //
  654. // <prefix> ::= <prefix> <unqualified-name>
  655. // ::= <template-prefix> <template-args>
  656. // ::= <template-param>
  657. // ::= <substitution>
  658. // ::= # empty
  659. // <template-prefix> ::= <prefix> <(template) unqualified-name>
  660. // ::= <template-param>
  661. // ::= <substitution>
  662. static bool ParsePrefix(State *state) {
  663. ComplexityGuard guard(state);
  664. if (guard.IsTooComplex()) return false;
  665. bool has_something = false;
  666. while (true) {
  667. MaybeAppendSeparator(state);
  668. if (ParseTemplateParam(state) ||
  669. ParseSubstitution(state, /*accept_std=*/true) ||
  670. ParseUnscopedName(state) ||
  671. (ParseOneCharToken(state, 'M') && ParseUnnamedTypeName(state))) {
  672. has_something = true;
  673. MaybeIncreaseNestLevel(state);
  674. continue;
  675. }
  676. MaybeCancelLastSeparator(state);
  677. if (has_something && ParseTemplateArgs(state)) {
  678. return ParsePrefix(state);
  679. } else {
  680. break;
  681. }
  682. }
  683. return true;
  684. }
  685. // <unqualified-name> ::= <operator-name> [<abi-tags>]
  686. // ::= <ctor-dtor-name> [<abi-tags>]
  687. // ::= <source-name> [<abi-tags>]
  688. // ::= <local-source-name> [<abi-tags>]
  689. // ::= <unnamed-type-name> [<abi-tags>]
  690. //
  691. // <local-source-name> is a GCC extension; see below.
  692. static bool ParseUnqualifiedName(State *state) {
  693. ComplexityGuard guard(state);
  694. if (guard.IsTooComplex()) return false;
  695. if (ParseOperatorName(state, nullptr) || ParseCtorDtorName(state) ||
  696. ParseSourceName(state) || ParseLocalSourceName(state) ||
  697. ParseUnnamedTypeName(state)) {
  698. return ParseAbiTags(state);
  699. }
  700. return false;
  701. }
  702. // <abi-tags> ::= <abi-tag> [<abi-tags>]
  703. // <abi-tag> ::= B <source-name>
  704. static bool ParseAbiTags(State *state) {
  705. ComplexityGuard guard(state);
  706. if (guard.IsTooComplex()) return false;
  707. while (ParseOneCharToken(state, 'B')) {
  708. ParseState copy = state->parse_state;
  709. MaybeAppend(state, "[abi:");
  710. if (!ParseSourceName(state)) {
  711. state->parse_state = copy;
  712. return false;
  713. }
  714. MaybeAppend(state, "]");
  715. }
  716. return true;
  717. }
  718. // <source-name> ::= <positive length number> <identifier>
  719. static bool ParseSourceName(State *state) {
  720. ComplexityGuard guard(state);
  721. if (guard.IsTooComplex()) return false;
  722. ParseState copy = state->parse_state;
  723. int length = -1;
  724. if (ParseNumber(state, &length) &&
  725. ParseIdentifier(state, static_cast<size_t>(length))) {
  726. return true;
  727. }
  728. state->parse_state = copy;
  729. return false;
  730. }
  731. // <local-source-name> ::= L <source-name> [<discriminator>]
  732. //
  733. // References:
  734. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
  735. // https://gcc.gnu.org/viewcvs?view=rev&revision=124467
  736. static bool ParseLocalSourceName(State *state) {
  737. ComplexityGuard guard(state);
  738. if (guard.IsTooComplex()) return false;
  739. ParseState copy = state->parse_state;
  740. if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
  741. Optional(ParseDiscriminator(state))) {
  742. return true;
  743. }
  744. state->parse_state = copy;
  745. return false;
  746. }
  747. // <unnamed-type-name> ::= Ut [<(nonnegative) number>] _
  748. // ::= <closure-type-name>
  749. // <closure-type-name> ::= Ul <lambda-sig> E [<(nonnegative) number>] _
  750. // <lambda-sig> ::= <(parameter) type>+
  751. static bool ParseUnnamedTypeName(State *state) {
  752. ComplexityGuard guard(state);
  753. if (guard.IsTooComplex()) return false;
  754. ParseState copy = state->parse_state;
  755. // Type's 1-based index n is encoded as { "", n == 1; itoa(n-2), otherwise }.
  756. // Optionally parse the encoded value into 'which' and add 2 to get the index.
  757. int which = -1;
  758. // Unnamed type local to function or class.
  759. if (ParseTwoCharToken(state, "Ut") && Optional(ParseNumber(state, &which)) &&
  760. which <= std::numeric_limits<int>::max() - 2 && // Don't overflow.
  761. ParseOneCharToken(state, '_')) {
  762. MaybeAppend(state, "{unnamed type#");
  763. MaybeAppendDecimal(state, 2 + which);
  764. MaybeAppend(state, "}");
  765. return true;
  766. }
  767. state->parse_state = copy;
  768. // Closure type.
  769. which = -1;
  770. if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) &&
  771. OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) &&
  772. ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) &&
  773. which <= std::numeric_limits<int>::max() - 2 && // Don't overflow.
  774. ParseOneCharToken(state, '_')) {
  775. MaybeAppend(state, "{lambda()#");
  776. MaybeAppendDecimal(state, 2 + which);
  777. MaybeAppend(state, "}");
  778. return true;
  779. }
  780. state->parse_state = copy;
  781. return false;
  782. }
  783. // <number> ::= [n] <non-negative decimal integer>
  784. // If "number_out" is non-null, then *number_out is set to the value of the
  785. // parsed number on success.
  786. static bool ParseNumber(State *state, int *number_out) {
  787. ComplexityGuard guard(state);
  788. if (guard.IsTooComplex()) return false;
  789. bool negative = false;
  790. if (ParseOneCharToken(state, 'n')) {
  791. negative = true;
  792. }
  793. const char *p = RemainingInput(state);
  794. uint64_t number = 0;
  795. for (; *p != '\0'; ++p) {
  796. if (IsDigit(*p)) {
  797. number = number * 10 + static_cast<uint64_t>(*p - '0');
  798. } else {
  799. break;
  800. }
  801. }
  802. // Apply the sign with uint64_t arithmetic so overflows aren't UB. Gives
  803. // "incorrect" results for out-of-range inputs, but negative values only
  804. // appear for literals, which aren't printed.
  805. if (negative) {
  806. number = ~number + 1;
  807. }
  808. if (p != RemainingInput(state)) { // Conversion succeeded.
  809. state->parse_state.mangled_idx += p - RemainingInput(state);
  810. if (number_out != nullptr) {
  811. // Note: possibly truncate "number".
  812. *number_out = static_cast<int>(number);
  813. }
  814. return true;
  815. }
  816. return false;
  817. }
  818. // Floating-point literals are encoded using a fixed-length lowercase
  819. // hexadecimal string.
  820. static bool ParseFloatNumber(State *state) {
  821. ComplexityGuard guard(state);
  822. if (guard.IsTooComplex()) return false;
  823. const char *p = RemainingInput(state);
  824. for (; *p != '\0'; ++p) {
  825. if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
  826. break;
  827. }
  828. }
  829. if (p != RemainingInput(state)) { // Conversion succeeded.
  830. state->parse_state.mangled_idx += p - RemainingInput(state);
  831. return true;
  832. }
  833. return false;
  834. }
  835. // The <seq-id> is a sequence number in base 36,
  836. // using digits and upper case letters
  837. static bool ParseSeqId(State *state) {
  838. ComplexityGuard guard(state);
  839. if (guard.IsTooComplex()) return false;
  840. const char *p = RemainingInput(state);
  841. for (; *p != '\0'; ++p) {
  842. if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
  843. break;
  844. }
  845. }
  846. if (p != RemainingInput(state)) { // Conversion succeeded.
  847. state->parse_state.mangled_idx += p - RemainingInput(state);
  848. return true;
  849. }
  850. return false;
  851. }
  852. // <identifier> ::= <unqualified source code identifier> (of given length)
  853. static bool ParseIdentifier(State *state, size_t length) {
  854. ComplexityGuard guard(state);
  855. if (guard.IsTooComplex()) return false;
  856. if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) {
  857. return false;
  858. }
  859. if (IdentifierIsAnonymousNamespace(state, length)) {
  860. MaybeAppend(state, "(anonymous namespace)");
  861. } else {
  862. MaybeAppendWithLength(state, RemainingInput(state), length);
  863. }
  864. state->parse_state.mangled_idx += length;
  865. return true;
  866. }
  867. // <operator-name> ::= nw, and other two letters cases
  868. // ::= cv <type> # (cast)
  869. // ::= v <digit> <source-name> # vendor extended operator
  870. static bool ParseOperatorName(State *state, int *arity) {
  871. ComplexityGuard guard(state);
  872. if (guard.IsTooComplex()) return false;
  873. if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) {
  874. return false;
  875. }
  876. // First check with "cv" (cast) case.
  877. ParseState copy = state->parse_state;
  878. if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") &&
  879. EnterNestedName(state) && ParseType(state) &&
  880. LeaveNestedName(state, copy.nest_level)) {
  881. if (arity != nullptr) {
  882. *arity = 1;
  883. }
  884. return true;
  885. }
  886. state->parse_state = copy;
  887. // Then vendor extended operators.
  888. if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) &&
  889. ParseSourceName(state)) {
  890. return true;
  891. }
  892. state->parse_state = copy;
  893. // Other operator names should start with a lower alphabet followed
  894. // by a lower/upper alphabet.
  895. if (!(IsLower(RemainingInput(state)[0]) &&
  896. IsAlpha(RemainingInput(state)[1]))) {
  897. return false;
  898. }
  899. // We may want to perform a binary search if we really need speed.
  900. const AbbrevPair *p;
  901. for (p = kOperatorList; p->abbrev != nullptr; ++p) {
  902. if (RemainingInput(state)[0] == p->abbrev[0] &&
  903. RemainingInput(state)[1] == p->abbrev[1]) {
  904. if (arity != nullptr) {
  905. *arity = p->arity;
  906. }
  907. MaybeAppend(state, "operator");
  908. if (IsLower(*p->real_name)) { // new, delete, etc.
  909. MaybeAppend(state, " ");
  910. }
  911. MaybeAppend(state, p->real_name);
  912. state->parse_state.mangled_idx += 2;
  913. return true;
  914. }
  915. }
  916. return false;
  917. }
  918. // <special-name> ::= TV <type>
  919. // ::= TT <type>
  920. // ::= TI <type>
  921. // ::= TS <type>
  922. // ::= TH <type> # thread-local
  923. // ::= Tc <call-offset> <call-offset> <(base) encoding>
  924. // ::= GV <(object) name>
  925. // ::= T <call-offset> <(base) encoding>
  926. // G++ extensions:
  927. // ::= TC <type> <(offset) number> _ <(base) type>
  928. // ::= TF <type>
  929. // ::= TJ <type>
  930. // ::= GR <name>
  931. // ::= GA <encoding>
  932. // ::= Th <call-offset> <(base) encoding>
  933. // ::= Tv <call-offset> <(base) encoding>
  934. //
  935. // Note: we don't care much about them since they don't appear in
  936. // stack traces. The are special data.
  937. static bool ParseSpecialName(State *state) {
  938. ComplexityGuard guard(state);
  939. if (guard.IsTooComplex()) return false;
  940. ParseState copy = state->parse_state;
  941. if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTISH") &&
  942. ParseType(state)) {
  943. return true;
  944. }
  945. state->parse_state = copy;
  946. if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
  947. ParseCallOffset(state) && ParseEncoding(state)) {
  948. return true;
  949. }
  950. state->parse_state = copy;
  951. if (ParseTwoCharToken(state, "GV") && ParseName(state)) {
  952. return true;
  953. }
  954. state->parse_state = copy;
  955. if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
  956. ParseEncoding(state)) {
  957. return true;
  958. }
  959. state->parse_state = copy;
  960. // G++ extensions
  961. if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
  962. ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
  963. DisableAppend(state) && ParseType(state)) {
  964. RestoreAppend(state, copy.append);
  965. return true;
  966. }
  967. state->parse_state = copy;
  968. if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
  969. ParseType(state)) {
  970. return true;
  971. }
  972. state->parse_state = copy;
  973. if (ParseTwoCharToken(state, "GR") && ParseName(state)) {
  974. return true;
  975. }
  976. state->parse_state = copy;
  977. if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
  978. return true;
  979. }
  980. state->parse_state = copy;
  981. if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
  982. ParseCallOffset(state) && ParseEncoding(state)) {
  983. return true;
  984. }
  985. state->parse_state = copy;
  986. return false;
  987. }
  988. // <call-offset> ::= h <nv-offset> _
  989. // ::= v <v-offset> _
  990. static bool ParseCallOffset(State *state) {
  991. ComplexityGuard guard(state);
  992. if (guard.IsTooComplex()) return false;
  993. ParseState copy = state->parse_state;
  994. if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) &&
  995. ParseOneCharToken(state, '_')) {
  996. return true;
  997. }
  998. state->parse_state = copy;
  999. if (ParseOneCharToken(state, 'v') && ParseVOffset(state) &&
  1000. ParseOneCharToken(state, '_')) {
  1001. return true;
  1002. }
  1003. state->parse_state = copy;
  1004. return false;
  1005. }
  1006. // <nv-offset> ::= <(offset) number>
  1007. static bool ParseNVOffset(State *state) {
  1008. ComplexityGuard guard(state);
  1009. if (guard.IsTooComplex()) return false;
  1010. return ParseNumber(state, nullptr);
  1011. }
  1012. // <v-offset> ::= <(offset) number> _ <(virtual offset) number>
  1013. static bool ParseVOffset(State *state) {
  1014. ComplexityGuard guard(state);
  1015. if (guard.IsTooComplex()) return false;
  1016. ParseState copy = state->parse_state;
  1017. if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
  1018. ParseNumber(state, nullptr)) {
  1019. return true;
  1020. }
  1021. state->parse_state = copy;
  1022. return false;
  1023. }
  1024. // <ctor-dtor-name> ::= C1 | C2 | C3 | CI1 <base-class-type> | CI2
  1025. // <base-class-type>
  1026. // ::= D0 | D1 | D2
  1027. // # GCC extensions: "unified" constructor/destructor. See
  1028. // #
  1029. // https://github.com/gcc-mirror/gcc/blob/7ad17b583c3643bd4557f29b8391ca7ef08391f5/gcc/cp/mangle.c#L1847
  1030. // ::= C4 | D4
  1031. static bool ParseCtorDtorName(State *state) {
  1032. ComplexityGuard guard(state);
  1033. if (guard.IsTooComplex()) return false;
  1034. ParseState copy = state->parse_state;
  1035. if (ParseOneCharToken(state, 'C')) {
  1036. if (ParseCharClass(state, "1234")) {
  1037. const char *const prev_name =
  1038. state->out + state->parse_state.prev_name_idx;
  1039. MaybeAppendWithLength(state, prev_name,
  1040. state->parse_state.prev_name_length);
  1041. return true;
  1042. } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") &&
  1043. ParseClassEnumType(state)) {
  1044. return true;
  1045. }
  1046. }
  1047. state->parse_state = copy;
  1048. if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) {
  1049. const char *const prev_name = state->out + state->parse_state.prev_name_idx;
  1050. MaybeAppend(state, "~");
  1051. MaybeAppendWithLength(state, prev_name,
  1052. state->parse_state.prev_name_length);
  1053. return true;
  1054. }
  1055. state->parse_state = copy;
  1056. return false;
  1057. }
  1058. // <decltype> ::= Dt <expression> E # decltype of an id-expression or class
  1059. // # member access (C++0x)
  1060. // ::= DT <expression> E # decltype of an expression (C++0x)
  1061. static bool ParseDecltype(State *state) {
  1062. ComplexityGuard guard(state);
  1063. if (guard.IsTooComplex()) return false;
  1064. ParseState copy = state->parse_state;
  1065. if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
  1066. ParseExpression(state) && ParseOneCharToken(state, 'E')) {
  1067. return true;
  1068. }
  1069. state->parse_state = copy;
  1070. return false;
  1071. }
  1072. // <type> ::= <CV-qualifiers> <type>
  1073. // ::= P <type> # pointer-to
  1074. // ::= R <type> # reference-to
  1075. // ::= O <type> # rvalue reference-to (C++0x)
  1076. // ::= C <type> # complex pair (C 2000)
  1077. // ::= G <type> # imaginary (C 2000)
  1078. // ::= U <source-name> <type> # vendor extended type qualifier
  1079. // ::= <builtin-type>
  1080. // ::= <function-type>
  1081. // ::= <class-enum-type> # note: just an alias for <name>
  1082. // ::= <array-type>
  1083. // ::= <pointer-to-member-type>
  1084. // ::= <template-template-param> <template-args>
  1085. // ::= <template-param>
  1086. // ::= <decltype>
  1087. // ::= <substitution>
  1088. // ::= Dp <type> # pack expansion of (C++0x)
  1089. // ::= Dv <num-elems> _ # GNU vector extension
  1090. //
  1091. static bool ParseType(State *state) {
  1092. ComplexityGuard guard(state);
  1093. if (guard.IsTooComplex()) return false;
  1094. ParseState copy = state->parse_state;
  1095. // We should check CV-qualifers, and PRGC things first.
  1096. //
  1097. // CV-qualifiers overlap with some operator names, but an operator name is not
  1098. // valid as a type. To avoid an ambiguity that can lead to exponential time
  1099. // complexity, refuse to backtrack the CV-qualifiers.
  1100. //
  1101. // _Z4aoeuIrMvvE
  1102. // => _Z 4aoeuI rM v v E
  1103. // aoeu<operator%=, void, void>
  1104. // => _Z 4aoeuI r Mv v E
  1105. // aoeu<void void::* restrict>
  1106. //
  1107. // By consuming the CV-qualifiers first, the former parse is disabled.
  1108. if (ParseCVQualifiers(state)) {
  1109. const bool result = ParseType(state);
  1110. if (!result) state->parse_state = copy;
  1111. return result;
  1112. }
  1113. state->parse_state = copy;
  1114. // Similarly, these tag characters can overlap with other <name>s resulting in
  1115. // two different parse prefixes that land on <template-args> in the same
  1116. // place, such as "C3r1xI...". So, disable the "ctor-name = C3" parse by
  1117. // refusing to backtrack the tag characters.
  1118. if (ParseCharClass(state, "OPRCG")) {
  1119. const bool result = ParseType(state);
  1120. if (!result) state->parse_state = copy;
  1121. return result;
  1122. }
  1123. state->parse_state = copy;
  1124. if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
  1125. return true;
  1126. }
  1127. state->parse_state = copy;
  1128. if (ParseOneCharToken(state, 'U') && ParseSourceName(state) &&
  1129. ParseType(state)) {
  1130. return true;
  1131. }
  1132. state->parse_state = copy;
  1133. if (ParseBuiltinType(state) || ParseFunctionType(state) ||
  1134. ParseClassEnumType(state) || ParseArrayType(state) ||
  1135. ParsePointerToMemberType(state) || ParseDecltype(state) ||
  1136. // "std" on its own isn't a type.
  1137. ParseSubstitution(state, /*accept_std=*/false)) {
  1138. return true;
  1139. }
  1140. if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) {
  1141. return true;
  1142. }
  1143. state->parse_state = copy;
  1144. // Less greedy than <template-template-param> <template-args>.
  1145. if (ParseTemplateParam(state)) {
  1146. return true;
  1147. }
  1148. if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) &&
  1149. ParseOneCharToken(state, '_')) {
  1150. return true;
  1151. }
  1152. state->parse_state = copy;
  1153. return false;
  1154. }
  1155. // <CV-qualifiers> ::= [r] [V] [K]
  1156. // We don't allow empty <CV-qualifiers> to avoid infinite loop in
  1157. // ParseType().
  1158. static bool ParseCVQualifiers(State *state) {
  1159. ComplexityGuard guard(state);
  1160. if (guard.IsTooComplex()) return false;
  1161. int num_cv_qualifiers = 0;
  1162. num_cv_qualifiers += ParseOneCharToken(state, 'r');
  1163. num_cv_qualifiers += ParseOneCharToken(state, 'V');
  1164. num_cv_qualifiers += ParseOneCharToken(state, 'K');
  1165. return num_cv_qualifiers > 0;
  1166. }
  1167. // <builtin-type> ::= v, etc. # single-character builtin types
  1168. // ::= u <source-name>
  1169. // ::= Dd, etc. # two-character builtin types
  1170. //
  1171. // Not supported:
  1172. // ::= DF <number> _ # _FloatN (N bits)
  1173. //
  1174. static bool ParseBuiltinType(State *state) {
  1175. ComplexityGuard guard(state);
  1176. if (guard.IsTooComplex()) return false;
  1177. const AbbrevPair *p;
  1178. for (p = kBuiltinTypeList; p->abbrev != nullptr; ++p) {
  1179. // Guaranteed only 1- or 2-character strings in kBuiltinTypeList.
  1180. if (p->abbrev[1] == '\0') {
  1181. if (ParseOneCharToken(state, p->abbrev[0])) {
  1182. MaybeAppend(state, p->real_name);
  1183. return true;
  1184. }
  1185. } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) {
  1186. MaybeAppend(state, p->real_name);
  1187. return true;
  1188. }
  1189. }
  1190. ParseState copy = state->parse_state;
  1191. if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) {
  1192. return true;
  1193. }
  1194. state->parse_state = copy;
  1195. return false;
  1196. }
  1197. // <exception-spec> ::= Do # non-throwing
  1198. // exception-specification (e.g.,
  1199. // noexcept, throw())
  1200. // ::= DO <expression> E # computed (instantiation-dependent)
  1201. // noexcept
  1202. // ::= Dw <type>+ E # dynamic exception specification
  1203. // with instantiation-dependent types
  1204. static bool ParseExceptionSpec(State *state) {
  1205. ComplexityGuard guard(state);
  1206. if (guard.IsTooComplex()) return false;
  1207. if (ParseTwoCharToken(state, "Do")) return true;
  1208. ParseState copy = state->parse_state;
  1209. if (ParseTwoCharToken(state, "DO") && ParseExpression(state) &&
  1210. ParseOneCharToken(state, 'E')) {
  1211. return true;
  1212. }
  1213. state->parse_state = copy;
  1214. if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) &&
  1215. ParseOneCharToken(state, 'E')) {
  1216. return true;
  1217. }
  1218. state->parse_state = copy;
  1219. return false;
  1220. }
  1221. // <function-type> ::= [exception-spec] F [Y] <bare-function-type> [O] E
  1222. static bool ParseFunctionType(State *state) {
  1223. ComplexityGuard guard(state);
  1224. if (guard.IsTooComplex()) return false;
  1225. ParseState copy = state->parse_state;
  1226. if (Optional(ParseExceptionSpec(state)) && ParseOneCharToken(state, 'F') &&
  1227. Optional(ParseOneCharToken(state, 'Y')) && ParseBareFunctionType(state) &&
  1228. Optional(ParseOneCharToken(state, 'O')) &&
  1229. ParseOneCharToken(state, 'E')) {
  1230. return true;
  1231. }
  1232. state->parse_state = copy;
  1233. return false;
  1234. }
  1235. // <bare-function-type> ::= <(signature) type>+
  1236. static bool ParseBareFunctionType(State *state) {
  1237. ComplexityGuard guard(state);
  1238. if (guard.IsTooComplex()) return false;
  1239. ParseState copy = state->parse_state;
  1240. DisableAppend(state);
  1241. if (OneOrMore(ParseType, state)) {
  1242. RestoreAppend(state, copy.append);
  1243. MaybeAppend(state, "()");
  1244. return true;
  1245. }
  1246. state->parse_state = copy;
  1247. return false;
  1248. }
  1249. // <class-enum-type> ::= <name>
  1250. static bool ParseClassEnumType(State *state) {
  1251. ComplexityGuard guard(state);
  1252. if (guard.IsTooComplex()) return false;
  1253. return ParseName(state);
  1254. }
  1255. // <array-type> ::= A <(positive dimension) number> _ <(element) type>
  1256. // ::= A [<(dimension) expression>] _ <(element) type>
  1257. static bool ParseArrayType(State *state) {
  1258. ComplexityGuard guard(state);
  1259. if (guard.IsTooComplex()) return false;
  1260. ParseState copy = state->parse_state;
  1261. if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) &&
  1262. ParseOneCharToken(state, '_') && ParseType(state)) {
  1263. return true;
  1264. }
  1265. state->parse_state = copy;
  1266. if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
  1267. ParseOneCharToken(state, '_') && ParseType(state)) {
  1268. return true;
  1269. }
  1270. state->parse_state = copy;
  1271. return false;
  1272. }
  1273. // <pointer-to-member-type> ::= M <(class) type> <(member) type>
  1274. static bool ParsePointerToMemberType(State *state) {
  1275. ComplexityGuard guard(state);
  1276. if (guard.IsTooComplex()) return false;
  1277. ParseState copy = state->parse_state;
  1278. if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) {
  1279. return true;
  1280. }
  1281. state->parse_state = copy;
  1282. return false;
  1283. }
  1284. // <template-param> ::= T_
  1285. // ::= T <parameter-2 non-negative number> _
  1286. static bool ParseTemplateParam(State *state) {
  1287. ComplexityGuard guard(state);
  1288. if (guard.IsTooComplex()) return false;
  1289. if (ParseTwoCharToken(state, "T_")) {
  1290. MaybeAppend(state, "?"); // We don't support template substitutions.
  1291. return true;
  1292. }
  1293. ParseState copy = state->parse_state;
  1294. if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) &&
  1295. ParseOneCharToken(state, '_')) {
  1296. MaybeAppend(state, "?"); // We don't support template substitutions.
  1297. return true;
  1298. }
  1299. state->parse_state = copy;
  1300. return false;
  1301. }
  1302. // <template-template-param> ::= <template-param>
  1303. // ::= <substitution>
  1304. static bool ParseTemplateTemplateParam(State *state) {
  1305. ComplexityGuard guard(state);
  1306. if (guard.IsTooComplex()) return false;
  1307. return (ParseTemplateParam(state) ||
  1308. // "std" on its own isn't a template.
  1309. ParseSubstitution(state, /*accept_std=*/false));
  1310. }
  1311. // <template-args> ::= I <template-arg>+ E
  1312. static bool ParseTemplateArgs(State *state) {
  1313. ComplexityGuard guard(state);
  1314. if (guard.IsTooComplex()) return false;
  1315. ParseState copy = state->parse_state;
  1316. DisableAppend(state);
  1317. if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) &&
  1318. ParseOneCharToken(state, 'E')) {
  1319. RestoreAppend(state, copy.append);
  1320. MaybeAppend(state, "<>");
  1321. return true;
  1322. }
  1323. state->parse_state = copy;
  1324. return false;
  1325. }
  1326. // <template-arg> ::= <type>
  1327. // ::= <expr-primary>
  1328. // ::= J <template-arg>* E # argument pack
  1329. // ::= X <expression> E
  1330. static bool ParseTemplateArg(State *state) {
  1331. ComplexityGuard guard(state);
  1332. if (guard.IsTooComplex()) return false;
  1333. ParseState copy = state->parse_state;
  1334. if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) &&
  1335. ParseOneCharToken(state, 'E')) {
  1336. return true;
  1337. }
  1338. state->parse_state = copy;
  1339. // There can be significant overlap between the following leading to
  1340. // exponential backtracking:
  1341. //
  1342. // <expr-primary> ::= L <type> <expr-cast-value> E
  1343. // e.g. L 2xxIvE 1 E
  1344. // <type> ==> <local-source-name> <template-args>
  1345. // e.g. L 2xx IvE
  1346. //
  1347. // This means parsing an entire <type> twice, and <type> can contain
  1348. // <template-arg>, so this can generate exponential backtracking. There is
  1349. // only overlap when the remaining input starts with "L <source-name>", so
  1350. // parse all cases that can start this way jointly to share the common prefix.
  1351. //
  1352. // We have:
  1353. //
  1354. // <template-arg> ::= <type>
  1355. // ::= <expr-primary>
  1356. //
  1357. // First, drop all the productions of <type> that must start with something
  1358. // other than 'L'. All that's left is <class-enum-type>; inline it.
  1359. //
  1360. // <type> ::= <nested-name> # starts with 'N'
  1361. // ::= <unscoped-name>
  1362. // ::= <unscoped-template-name> <template-args>
  1363. // ::= <local-name> # starts with 'Z'
  1364. //
  1365. // Drop and inline again:
  1366. //
  1367. // <type> ::= <unscoped-name>
  1368. // ::= <unscoped-name> <template-args>
  1369. // ::= <substitution> <template-args> # starts with 'S'
  1370. //
  1371. // Merge the first two, inline <unscoped-name>, drop last:
  1372. //
  1373. // <type> ::= <unqualified-name> [<template-args>]
  1374. // ::= St <unqualified-name> [<template-args>] # starts with 'S'
  1375. //
  1376. // Drop and inline:
  1377. //
  1378. // <type> ::= <operator-name> [<template-args>] # starts with lowercase
  1379. // ::= <ctor-dtor-name> [<template-args>] # starts with 'C' or 'D'
  1380. // ::= <source-name> [<template-args>] # starts with digit
  1381. // ::= <local-source-name> [<template-args>]
  1382. // ::= <unnamed-type-name> [<template-args>] # starts with 'U'
  1383. //
  1384. // One more time:
  1385. //
  1386. // <type> ::= L <source-name> [<template-args>]
  1387. //
  1388. // Likewise with <expr-primary>:
  1389. //
  1390. // <expr-primary> ::= L <type> <expr-cast-value> E
  1391. // ::= LZ <encoding> E # cannot overlap; drop
  1392. // ::= L <mangled_name> E # cannot overlap; drop
  1393. //
  1394. // By similar reasoning as shown above, the only <type>s starting with
  1395. // <source-name> are "<source-name> [<template-args>]". Inline this.
  1396. //
  1397. // <expr-primary> ::= L <source-name> [<template-args>] <expr-cast-value> E
  1398. //
  1399. // Now inline both of these into <template-arg>:
  1400. //
  1401. // <template-arg> ::= L <source-name> [<template-args>]
  1402. // ::= L <source-name> [<template-args>] <expr-cast-value> E
  1403. //
  1404. // Merge them and we're done:
  1405. // <template-arg>
  1406. // ::= L <source-name> [<template-args>] [<expr-cast-value> E]
  1407. if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) {
  1408. copy = state->parse_state;
  1409. if (ParseExprCastValue(state) && ParseOneCharToken(state, 'E')) {
  1410. return true;
  1411. }
  1412. state->parse_state = copy;
  1413. return true;
  1414. }
  1415. // Now that the overlapping cases can't reach this code, we can safely call
  1416. // both of these.
  1417. if (ParseType(state) || ParseExprPrimary(state)) {
  1418. return true;
  1419. }
  1420. state->parse_state = copy;
  1421. if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
  1422. ParseOneCharToken(state, 'E')) {
  1423. return true;
  1424. }
  1425. state->parse_state = copy;
  1426. return false;
  1427. }
  1428. // <unresolved-type> ::= <template-param> [<template-args>]
  1429. // ::= <decltype>
  1430. // ::= <substitution>
  1431. static inline bool ParseUnresolvedType(State *state) {
  1432. // No ComplexityGuard because we don't copy the state in this stack frame.
  1433. return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) ||
  1434. ParseDecltype(state) || ParseSubstitution(state, /*accept_std=*/false);
  1435. }
  1436. // <simple-id> ::= <source-name> [<template-args>]
  1437. static inline bool ParseSimpleId(State *state) {
  1438. // No ComplexityGuard because we don't copy the state in this stack frame.
  1439. // Note: <simple-id> cannot be followed by a parameter pack; see comment in
  1440. // ParseUnresolvedType.
  1441. return ParseSourceName(state) && Optional(ParseTemplateArgs(state));
  1442. }
  1443. // <base-unresolved-name> ::= <source-name> [<template-args>]
  1444. // ::= on <operator-name> [<template-args>]
  1445. // ::= dn <destructor-name>
  1446. static bool ParseBaseUnresolvedName(State *state) {
  1447. ComplexityGuard guard(state);
  1448. if (guard.IsTooComplex()) return false;
  1449. if (ParseSimpleId(state)) {
  1450. return true;
  1451. }
  1452. ParseState copy = state->parse_state;
  1453. if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) &&
  1454. Optional(ParseTemplateArgs(state))) {
  1455. return true;
  1456. }
  1457. state->parse_state = copy;
  1458. if (ParseTwoCharToken(state, "dn") &&
  1459. (ParseUnresolvedType(state) || ParseSimpleId(state))) {
  1460. return true;
  1461. }
  1462. state->parse_state = copy;
  1463. return false;
  1464. }
  1465. // <unresolved-name> ::= [gs] <base-unresolved-name>
  1466. // ::= sr <unresolved-type> <base-unresolved-name>
  1467. // ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
  1468. // <base-unresolved-name>
  1469. // ::= [gs] sr <unresolved-qualifier-level>+ E
  1470. // <base-unresolved-name>
  1471. static bool ParseUnresolvedName(State *state) {
  1472. ComplexityGuard guard(state);
  1473. if (guard.IsTooComplex()) return false;
  1474. ParseState copy = state->parse_state;
  1475. if (Optional(ParseTwoCharToken(state, "gs")) &&
  1476. ParseBaseUnresolvedName(state)) {
  1477. return true;
  1478. }
  1479. state->parse_state = copy;
  1480. if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) &&
  1481. ParseBaseUnresolvedName(state)) {
  1482. return true;
  1483. }
  1484. state->parse_state = copy;
  1485. if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') &&
  1486. ParseUnresolvedType(state) &&
  1487. OneOrMore(/* <unresolved-qualifier-level> ::= */ ParseSimpleId, state) &&
  1488. ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
  1489. return true;
  1490. }
  1491. state->parse_state = copy;
  1492. if (Optional(ParseTwoCharToken(state, "gs")) &&
  1493. ParseTwoCharToken(state, "sr") &&
  1494. OneOrMore(/* <unresolved-qualifier-level> ::= */ ParseSimpleId, state) &&
  1495. ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
  1496. return true;
  1497. }
  1498. state->parse_state = copy;
  1499. return false;
  1500. }
  1501. // <expression> ::= <1-ary operator-name> <expression>
  1502. // ::= <2-ary operator-name> <expression> <expression>
  1503. // ::= <3-ary operator-name> <expression> <expression> <expression>
  1504. // ::= cl <expression>+ E
  1505. // ::= cp <simple-id> <expression>* E # Clang-specific.
  1506. // ::= cv <type> <expression> # type (expression)
  1507. // ::= cv <type> _ <expression>* E # type (expr-list)
  1508. // ::= st <type>
  1509. // ::= <template-param>
  1510. // ::= <function-param>
  1511. // ::= <expr-primary>
  1512. // ::= dt <expression> <unresolved-name> # expr.name
  1513. // ::= pt <expression> <unresolved-name> # expr->name
  1514. // ::= sp <expression> # argument pack expansion
  1515. // ::= sr <type> <unqualified-name> <template-args>
  1516. // ::= sr <type> <unqualified-name>
  1517. // <function-param> ::= fp <(top-level) CV-qualifiers> _
  1518. // ::= fp <(top-level) CV-qualifiers> <number> _
  1519. // ::= fL <number> p <(top-level) CV-qualifiers> _
  1520. // ::= fL <number> p <(top-level) CV-qualifiers> <number> _
  1521. static bool ParseExpression(State *state) {
  1522. ComplexityGuard guard(state);
  1523. if (guard.IsTooComplex()) return false;
  1524. if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
  1525. return true;
  1526. }
  1527. ParseState copy = state->parse_state;
  1528. // Object/function call expression.
  1529. if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) &&
  1530. ParseOneCharToken(state, 'E')) {
  1531. return true;
  1532. }
  1533. state->parse_state = copy;
  1534. // Clang-specific "cp <simple-id> <expression>* E"
  1535. // https://clang.llvm.org/doxygen/ItaniumMangle_8cpp_source.html#l04338
  1536. if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) &&
  1537. ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) {
  1538. return true;
  1539. }
  1540. state->parse_state = copy;
  1541. // Function-param expression (level 0).
  1542. if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) &&
  1543. Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
  1544. return true;
  1545. }
  1546. state->parse_state = copy;
  1547. // Function-param expression (level 1+).
  1548. if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) &&
  1549. ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) &&
  1550. Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
  1551. return true;
  1552. }
  1553. state->parse_state = copy;
  1554. // Parse the conversion expressions jointly to avoid re-parsing the <type> in
  1555. // their common prefix. Parsed as:
  1556. // <expression> ::= cv <type> <conversion-args>
  1557. // <conversion-args> ::= _ <expression>* E
  1558. // ::= <expression>
  1559. //
  1560. // Also don't try ParseOperatorName after seeing "cv", since ParseOperatorName
  1561. // also needs to accept "cv <type>" in other contexts.
  1562. if (ParseTwoCharToken(state, "cv")) {
  1563. if (ParseType(state)) {
  1564. ParseState copy2 = state->parse_state;
  1565. if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) &&
  1566. ParseOneCharToken(state, 'E')) {
  1567. return true;
  1568. }
  1569. state->parse_state = copy2;
  1570. if (ParseExpression(state)) {
  1571. return true;
  1572. }
  1573. }
  1574. } else {
  1575. // Parse unary, binary, and ternary operator expressions jointly, taking
  1576. // care not to re-parse subexpressions repeatedly. Parse like:
  1577. // <expression> ::= <operator-name> <expression>
  1578. // [<one-to-two-expressions>]
  1579. // <one-to-two-expressions> ::= <expression> [<expression>]
  1580. int arity = -1;
  1581. if (ParseOperatorName(state, &arity) &&
  1582. arity > 0 && // 0 arity => disabled.
  1583. (arity < 3 || ParseExpression(state)) &&
  1584. (arity < 2 || ParseExpression(state)) &&
  1585. (arity < 1 || ParseExpression(state))) {
  1586. return true;
  1587. }
  1588. }
  1589. state->parse_state = copy;
  1590. // sizeof type
  1591. if (ParseTwoCharToken(state, "st") && ParseType(state)) {
  1592. return true;
  1593. }
  1594. state->parse_state = copy;
  1595. // Object and pointer member access expressions.
  1596. if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) &&
  1597. ParseExpression(state) && ParseType(state)) {
  1598. return true;
  1599. }
  1600. state->parse_state = copy;
  1601. // Pointer-to-member access expressions. This parses the same as a binary
  1602. // operator, but it's implemented separately because "ds" shouldn't be
  1603. // accepted in other contexts that parse an operator name.
  1604. if (ParseTwoCharToken(state, "ds") && ParseExpression(state) &&
  1605. ParseExpression(state)) {
  1606. return true;
  1607. }
  1608. state->parse_state = copy;
  1609. // Parameter pack expansion
  1610. if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) {
  1611. return true;
  1612. }
  1613. state->parse_state = copy;
  1614. return ParseUnresolvedName(state);
  1615. }
  1616. // <expr-primary> ::= L <type> <(value) number> E
  1617. // ::= L <type> <(value) float> E
  1618. // ::= L <mangled-name> E
  1619. // // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
  1620. // ::= LZ <encoding> E
  1621. //
  1622. // Warning, subtle: the "bug" LZ production above is ambiguous with the first
  1623. // production where <type> starts with <local-name>, which can lead to
  1624. // exponential backtracking in two scenarios:
  1625. //
  1626. // - When whatever follows the E in the <local-name> in the first production is
  1627. // not a name, we backtrack the whole <encoding> and re-parse the whole thing.
  1628. //
  1629. // - When whatever follows the <local-name> in the first production is not a
  1630. // number and this <expr-primary> may be followed by a name, we backtrack the
  1631. // <name> and re-parse it.
  1632. //
  1633. // Moreover this ambiguity isn't always resolved -- for example, the following
  1634. // has two different parses:
  1635. //
  1636. // _ZaaILZ4aoeuE1x1EvE
  1637. // => operator&&<aoeu, x, E, void>
  1638. // => operator&&<(aoeu::x)(1), void>
  1639. //
  1640. // To resolve this, we just do what GCC's demangler does, and refuse to parse
  1641. // casts to <local-name> types.
  1642. static bool ParseExprPrimary(State *state) {
  1643. ComplexityGuard guard(state);
  1644. if (guard.IsTooComplex()) return false;
  1645. ParseState copy = state->parse_state;
  1646. // The "LZ" special case: if we see LZ, we commit to accept "LZ <encoding> E"
  1647. // or fail, no backtracking.
  1648. if (ParseTwoCharToken(state, "LZ")) {
  1649. if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) {
  1650. return true;
  1651. }
  1652. state->parse_state = copy;
  1653. return false;
  1654. }
  1655. // The merged cast production.
  1656. if (ParseOneCharToken(state, 'L') && ParseType(state) &&
  1657. ParseExprCastValue(state)) {
  1658. return true;
  1659. }
  1660. state->parse_state = copy;
  1661. if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
  1662. ParseOneCharToken(state, 'E')) {
  1663. return true;
  1664. }
  1665. state->parse_state = copy;
  1666. return false;
  1667. }
  1668. // <number> or <float>, followed by 'E', as described above ParseExprPrimary.
  1669. static bool ParseExprCastValue(State *state) {
  1670. ComplexityGuard guard(state);
  1671. if (guard.IsTooComplex()) return false;
  1672. // We have to be able to backtrack after accepting a number because we could
  1673. // have e.g. "7fffE", which will accept "7" as a number but then fail to find
  1674. // the 'E'.
  1675. ParseState copy = state->parse_state;
  1676. if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) {
  1677. return true;
  1678. }
  1679. state->parse_state = copy;
  1680. if (ParseFloatNumber(state) && ParseOneCharToken(state, 'E')) {
  1681. return true;
  1682. }
  1683. state->parse_state = copy;
  1684. return false;
  1685. }
  1686. // <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
  1687. // ::= Z <(function) encoding> E s [<discriminator>]
  1688. //
  1689. // Parsing a common prefix of these two productions together avoids an
  1690. // exponential blowup of backtracking. Parse like:
  1691. // <local-name> := Z <encoding> E <local-name-suffix>
  1692. // <local-name-suffix> ::= s [<discriminator>]
  1693. // ::= <name> [<discriminator>]
  1694. static bool ParseLocalNameSuffix(State *state) {
  1695. ComplexityGuard guard(state);
  1696. if (guard.IsTooComplex()) return false;
  1697. if (MaybeAppend(state, "::") && ParseName(state) &&
  1698. Optional(ParseDiscriminator(state))) {
  1699. return true;
  1700. }
  1701. // Since we're not going to overwrite the above "::" by re-parsing the
  1702. // <encoding> (whose trailing '\0' byte was in the byte now holding the
  1703. // first ':'), we have to rollback the "::" if the <name> parse failed.
  1704. if (state->parse_state.append) {
  1705. state->out[state->parse_state.out_cur_idx - 2] = '\0';
  1706. }
  1707. return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state));
  1708. }
  1709. static bool ParseLocalName(State *state) {
  1710. ComplexityGuard guard(state);
  1711. if (guard.IsTooComplex()) return false;
  1712. ParseState copy = state->parse_state;
  1713. if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
  1714. ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) {
  1715. return true;
  1716. }
  1717. state->parse_state = copy;
  1718. return false;
  1719. }
  1720. // <discriminator> := _ <(non-negative) number>
  1721. static bool ParseDiscriminator(State *state) {
  1722. ComplexityGuard guard(state);
  1723. if (guard.IsTooComplex()) return false;
  1724. ParseState copy = state->parse_state;
  1725. if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr)) {
  1726. return true;
  1727. }
  1728. state->parse_state = copy;
  1729. return false;
  1730. }
  1731. // <substitution> ::= S_
  1732. // ::= S <seq-id> _
  1733. // ::= St, etc.
  1734. //
  1735. // "St" is special in that it's not valid as a standalone name, and it *is*
  1736. // allowed to precede a name without being wrapped in "N...E". This means that
  1737. // if we accept it on its own, we can accept "St1a" and try to parse
  1738. // template-args, then fail and backtrack, accept "St" on its own, then "1a" as
  1739. // an unqualified name and re-parse the same template-args. To block this
  1740. // exponential backtracking, we disable it with 'accept_std=false' in
  1741. // problematic contexts.
  1742. static bool ParseSubstitution(State *state, bool accept_std) {
  1743. ComplexityGuard guard(state);
  1744. if (guard.IsTooComplex()) return false;
  1745. if (ParseTwoCharToken(state, "S_")) {
  1746. MaybeAppend(state, "?"); // We don't support substitutions.
  1747. return true;
  1748. }
  1749. ParseState copy = state->parse_state;
  1750. if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
  1751. ParseOneCharToken(state, '_')) {
  1752. MaybeAppend(state, "?"); // We don't support substitutions.
  1753. return true;
  1754. }
  1755. state->parse_state = copy;
  1756. // Expand abbreviations like "St" => "std".
  1757. if (ParseOneCharToken(state, 'S')) {
  1758. const AbbrevPair *p;
  1759. for (p = kSubstitutionList; p->abbrev != nullptr; ++p) {
  1760. if (RemainingInput(state)[0] == p->abbrev[1] &&
  1761. (accept_std || p->abbrev[1] != 't')) {
  1762. MaybeAppend(state, "std");
  1763. if (p->real_name[0] != '\0') {
  1764. MaybeAppend(state, "::");
  1765. MaybeAppend(state, p->real_name);
  1766. }
  1767. ++state->parse_state.mangled_idx;
  1768. return true;
  1769. }
  1770. }
  1771. }
  1772. state->parse_state = copy;
  1773. return false;
  1774. }
  1775. // Parse <mangled-name>, optionally followed by either a function-clone suffix
  1776. // or version suffix. Returns true only if all of "mangled_cur" was consumed.
  1777. static bool ParseTopLevelMangledName(State *state) {
  1778. ComplexityGuard guard(state);
  1779. if (guard.IsTooComplex()) return false;
  1780. if (ParseMangledName(state)) {
  1781. if (RemainingInput(state)[0] != '\0') {
  1782. // Drop trailing function clone suffix, if any.
  1783. if (IsFunctionCloneSuffix(RemainingInput(state))) {
  1784. return true;
  1785. }
  1786. // Append trailing version suffix if any.
  1787. // ex. _Z3foo@@GLIBCXX_3.4
  1788. if (RemainingInput(state)[0] == '@') {
  1789. MaybeAppend(state, RemainingInput(state));
  1790. return true;
  1791. }
  1792. return false; // Unconsumed suffix.
  1793. }
  1794. return true;
  1795. }
  1796. return false;
  1797. }
  1798. static bool Overflowed(const State *state) {
  1799. return state->parse_state.out_cur_idx >= state->out_end_idx;
  1800. }
  1801. // The demangler entry point.
  1802. bool Demangle(const char* mangled, char* out, size_t out_size) {
  1803. State state;
  1804. InitState(&state, mangled, out, out_size);
  1805. return ParseTopLevelMangledName(&state) && !Overflowed(&state) &&
  1806. state.parse_state.out_cur_idx > 0;
  1807. }
  1808. std::string DemangleString(const char* mangled) {
  1809. std::string out;
  1810. int status = 0;
  1811. char* demangled = nullptr;
  1812. #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
  1813. demangled = abi::__cxa_demangle(mangled, nullptr, nullptr, &status);
  1814. #endif
  1815. if (status == 0 && demangled != nullptr) {
  1816. out.append(demangled);
  1817. free(demangled);
  1818. } else {
  1819. out.append(mangled);
  1820. }
  1821. return out;
  1822. }
  1823. } // namespace debugging_internal
  1824. ABSL_NAMESPACE_END
  1825. } // namespace absl