demangle.cc 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983
  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. #include "absl/debugging/internal/demangle.h"
  17. #include <cstddef>
  18. #include <cstdint>
  19. #include <cstdio>
  20. #include <cstdlib>
  21. #include <cstring>
  22. #include <limits>
  23. #include <string>
  24. #include "absl/base/config.h"
  25. #include "absl/debugging/internal/demangle_rust.h"
  26. #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
  27. #include <cxxabi.h>
  28. #endif
  29. namespace absl {
  30. ABSL_NAMESPACE_BEGIN
  31. namespace debugging_internal {
  32. typedef struct {
  33. const char *abbrev;
  34. const char *real_name;
  35. // Number of arguments in <expression> context, or 0 if disallowed.
  36. int arity;
  37. } AbbrevPair;
  38. // List of operators from Itanium C++ ABI.
  39. static const AbbrevPair kOperatorList[] = {
  40. // New has special syntax.
  41. {"nw", "new", 0},
  42. {"na", "new[]", 0},
  43. // Special-cased elsewhere to support the optional gs prefix.
  44. {"dl", "delete", 1},
  45. {"da", "delete[]", 1},
  46. {"aw", "co_await", 1},
  47. {"ps", "+", 1}, // "positive"
  48. {"ng", "-", 1}, // "negative"
  49. {"ad", "&", 1}, // "address-of"
  50. {"de", "*", 1}, // "dereference"
  51. {"co", "~", 1},
  52. {"pl", "+", 2},
  53. {"mi", "-", 2},
  54. {"ml", "*", 2},
  55. {"dv", "/", 2},
  56. {"rm", "%", 2},
  57. {"an", "&", 2},
  58. {"or", "|", 2},
  59. {"eo", "^", 2},
  60. {"aS", "=", 2},
  61. {"pL", "+=", 2},
  62. {"mI", "-=", 2},
  63. {"mL", "*=", 2},
  64. {"dV", "/=", 2},
  65. {"rM", "%=", 2},
  66. {"aN", "&=", 2},
  67. {"oR", "|=", 2},
  68. {"eO", "^=", 2},
  69. {"ls", "<<", 2},
  70. {"rs", ">>", 2},
  71. {"lS", "<<=", 2},
  72. {"rS", ">>=", 2},
  73. {"ss", "<=>", 2},
  74. {"eq", "==", 2},
  75. {"ne", "!=", 2},
  76. {"lt", "<", 2},
  77. {"gt", ">", 2},
  78. {"le", "<=", 2},
  79. {"ge", ">=", 2},
  80. {"nt", "!", 1},
  81. {"aa", "&&", 2},
  82. {"oo", "||", 2},
  83. {"pp", "++", 1},
  84. {"mm", "--", 1},
  85. {"cm", ",", 2},
  86. {"pm", "->*", 2},
  87. {"pt", "->", 0}, // Special syntax
  88. {"cl", "()", 0}, // Special syntax
  89. {"ix", "[]", 2},
  90. {"qu", "?", 3},
  91. {"st", "sizeof", 0}, // Special syntax
  92. {"sz", "sizeof", 1}, // Not a real operator name, but used in expressions.
  93. {"sZ", "sizeof...", 0}, // Special syntax
  94. {nullptr, nullptr, 0},
  95. };
  96. // List of builtin types from Itanium C++ ABI.
  97. //
  98. // Invariant: only one- or two-character type abbreviations here.
  99. static const AbbrevPair kBuiltinTypeList[] = {
  100. {"v", "void", 0},
  101. {"w", "wchar_t", 0},
  102. {"b", "bool", 0},
  103. {"c", "char", 0},
  104. {"a", "signed char", 0},
  105. {"h", "unsigned char", 0},
  106. {"s", "short", 0},
  107. {"t", "unsigned short", 0},
  108. {"i", "int", 0},
  109. {"j", "unsigned int", 0},
  110. {"l", "long", 0},
  111. {"m", "unsigned long", 0},
  112. {"x", "long long", 0},
  113. {"y", "unsigned long long", 0},
  114. {"n", "__int128", 0},
  115. {"o", "unsigned __int128", 0},
  116. {"f", "float", 0},
  117. {"d", "double", 0},
  118. {"e", "long double", 0},
  119. {"g", "__float128", 0},
  120. {"z", "ellipsis", 0},
  121. {"De", "decimal128", 0}, // IEEE 754r decimal floating point (128 bits)
  122. {"Dd", "decimal64", 0}, // IEEE 754r decimal floating point (64 bits)
  123. {"Dc", "decltype(auto)", 0},
  124. {"Da", "auto", 0},
  125. {"Dn", "std::nullptr_t", 0}, // i.e., decltype(nullptr)
  126. {"Df", "decimal32", 0}, // IEEE 754r decimal floating point (32 bits)
  127. {"Di", "char32_t", 0},
  128. {"Du", "char8_t", 0},
  129. {"Ds", "char16_t", 0},
  130. {"Dh", "float16", 0}, // IEEE 754r half-precision float (16 bits)
  131. {nullptr, nullptr, 0},
  132. };
  133. // List of substitutions Itanium C++ ABI.
  134. static const AbbrevPair kSubstitutionList[] = {
  135. {"St", "", 0},
  136. {"Sa", "allocator", 0},
  137. {"Sb", "basic_string", 0},
  138. // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
  139. {"Ss", "string", 0},
  140. // std::basic_istream<char, std::char_traits<char> >
  141. {"Si", "istream", 0},
  142. // std::basic_ostream<char, std::char_traits<char> >
  143. {"So", "ostream", 0},
  144. // std::basic_iostream<char, std::char_traits<char> >
  145. {"Sd", "iostream", 0},
  146. {nullptr, nullptr, 0},
  147. };
  148. // State needed for demangling. This struct is copied in almost every stack
  149. // frame, so every byte counts.
  150. typedef struct {
  151. int mangled_idx; // Cursor of mangled name.
  152. int out_cur_idx; // Cursor of output string.
  153. int prev_name_idx; // For constructors/destructors.
  154. unsigned int prev_name_length : 16; // For constructors/destructors.
  155. signed int nest_level : 15; // For nested names.
  156. unsigned int append : 1; // Append flag.
  157. // Note: for some reason MSVC can't pack "bool append : 1" into the same int
  158. // with the above two fields, so we use an int instead. Amusingly it can pack
  159. // "signed bool" as expected, but relying on that to continue to be a legal
  160. // type seems ill-advised (as it's illegal in at least clang).
  161. } ParseState;
  162. static_assert(sizeof(ParseState) == 4 * sizeof(int),
  163. "unexpected size of ParseState");
  164. // One-off state for demangling that's not subject to backtracking -- either
  165. // constant data, data that's intentionally immune to backtracking (steps), or
  166. // data that would never be changed by backtracking anyway (recursion_depth).
  167. //
  168. // Only one copy of this exists for each call to Demangle, so the size of this
  169. // struct is nearly inconsequential.
  170. typedef struct {
  171. const char *mangled_begin; // Beginning of input string.
  172. char *out; // Beginning of output string.
  173. int out_end_idx; // One past last allowed output character.
  174. int recursion_depth; // For stack exhaustion prevention.
  175. int steps; // Cap how much work we'll do, regardless of depth.
  176. ParseState parse_state; // Backtrackable state copied for most frames.
  177. // Conditionally compiled support for marking the position of the first
  178. // construct Demangle couldn't parse. This preprocessor symbol is intended
  179. // for use by Abseil demangler maintainers only; its behavior is not part of
  180. // Abseil's public interface.
  181. #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
  182. int high_water_mark; // Input position where parsing failed.
  183. bool too_complex; // True if any guard.IsTooComplex() call returned true.
  184. #endif
  185. } State;
  186. namespace {
  187. #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
  188. void UpdateHighWaterMark(State *state) {
  189. if (state->high_water_mark < state->parse_state.mangled_idx) {
  190. state->high_water_mark = state->parse_state.mangled_idx;
  191. }
  192. }
  193. void ReportHighWaterMark(State *state) {
  194. // Write out the mangled name with the trouble point marked, provided that the
  195. // output buffer is large enough and the mangled name did not hit a complexity
  196. // limit (in which case the high water mark wouldn't point out an unparsable
  197. // construct, only the point where a budget ran out).
  198. const size_t input_length = std::strlen(state->mangled_begin);
  199. if (input_length + 6 > static_cast<size_t>(state->out_end_idx) ||
  200. state->too_complex) {
  201. if (state->out_end_idx > 0) state->out[0] = '\0';
  202. return;
  203. }
  204. const size_t high_water_mark = static_cast<size_t>(state->high_water_mark);
  205. std::memcpy(state->out, state->mangled_begin, high_water_mark);
  206. std::memcpy(state->out + high_water_mark, "--!--", 5);
  207. std::memcpy(state->out + high_water_mark + 5,
  208. state->mangled_begin + high_water_mark,
  209. input_length - high_water_mark);
  210. state->out[input_length + 5] = '\0';
  211. }
  212. #else
  213. void UpdateHighWaterMark(State *) {}
  214. void ReportHighWaterMark(State *) {}
  215. #endif
  216. // Prevent deep recursion / stack exhaustion.
  217. // Also prevent unbounded handling of complex inputs.
  218. class ComplexityGuard {
  219. public:
  220. explicit ComplexityGuard(State *state) : state_(state) {
  221. ++state->recursion_depth;
  222. ++state->steps;
  223. }
  224. ~ComplexityGuard() { --state_->recursion_depth; }
  225. // 256 levels of recursion seems like a reasonable upper limit on depth.
  226. // 128 is not enough to demangle synthetic tests from demangle_unittest.txt:
  227. // "_ZaaZZZZ..." and "_ZaaZcvZcvZ..."
  228. static constexpr int kRecursionDepthLimit = 256;
  229. // We're trying to pick a charitable upper-limit on how many parse steps are
  230. // necessary to handle something that a human could actually make use of.
  231. // This is mostly in place as a bound on how much work we'll do if we are
  232. // asked to demangle an mangled name from an untrusted source, so it should be
  233. // much larger than the largest expected symbol, but much smaller than the
  234. // amount of work we can do in, e.g., a second.
  235. //
  236. // Some real-world symbols from an arbitrary binary started failing between
  237. // 2^12 and 2^13, so we multiply the latter by an extra factor of 16 to set
  238. // the limit.
  239. //
  240. // Spending one second on 2^17 parse steps would require each step to take
  241. // 7.6us, or ~30000 clock cycles, so it's safe to say this can be done in
  242. // under a second.
  243. static constexpr int kParseStepsLimit = 1 << 17;
  244. bool IsTooComplex() const {
  245. if (state_->recursion_depth > kRecursionDepthLimit ||
  246. state_->steps > kParseStepsLimit) {
  247. #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
  248. state_->too_complex = true;
  249. #endif
  250. return true;
  251. }
  252. return false;
  253. }
  254. private:
  255. State *state_;
  256. };
  257. } // namespace
  258. // We don't use strlen() in libc since it's not guaranteed to be async
  259. // signal safe.
  260. static size_t StrLen(const char *str) {
  261. size_t len = 0;
  262. while (*str != '\0') {
  263. ++str;
  264. ++len;
  265. }
  266. return len;
  267. }
  268. // Returns true if "str" has at least "n" characters remaining.
  269. static bool AtLeastNumCharsRemaining(const char *str, size_t n) {
  270. for (size_t i = 0; i < n; ++i) {
  271. if (str[i] == '\0') {
  272. return false;
  273. }
  274. }
  275. return true;
  276. }
  277. // Returns true if "str" has "prefix" as a prefix.
  278. static bool StrPrefix(const char *str, const char *prefix) {
  279. size_t i = 0;
  280. while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) {
  281. ++i;
  282. }
  283. return prefix[i] == '\0'; // Consumed everything in "prefix".
  284. }
  285. static void InitState(State* state,
  286. const char* mangled,
  287. char* out,
  288. size_t out_size) {
  289. state->mangled_begin = mangled;
  290. state->out = out;
  291. state->out_end_idx = static_cast<int>(out_size);
  292. state->recursion_depth = 0;
  293. state->steps = 0;
  294. #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
  295. state->high_water_mark = 0;
  296. state->too_complex = false;
  297. #endif
  298. state->parse_state.mangled_idx = 0;
  299. state->parse_state.out_cur_idx = 0;
  300. state->parse_state.prev_name_idx = 0;
  301. state->parse_state.prev_name_length = 0;
  302. state->parse_state.nest_level = -1;
  303. state->parse_state.append = true;
  304. }
  305. static inline const char *RemainingInput(State *state) {
  306. return &state->mangled_begin[state->parse_state.mangled_idx];
  307. }
  308. // Returns true and advances "mangled_idx" if we find "one_char_token"
  309. // at "mangled_idx" position. It is assumed that "one_char_token" does
  310. // not contain '\0'.
  311. static bool ParseOneCharToken(State *state, const char one_char_token) {
  312. ComplexityGuard guard(state);
  313. if (guard.IsTooComplex()) return false;
  314. if (RemainingInput(state)[0] == one_char_token) {
  315. ++state->parse_state.mangled_idx;
  316. UpdateHighWaterMark(state);
  317. return true;
  318. }
  319. return false;
  320. }
  321. // Returns true and advances "mangled_idx" if we find "two_char_token"
  322. // at "mangled_idx" position. It is assumed that "two_char_token" does
  323. // not contain '\0'.
  324. static bool ParseTwoCharToken(State *state, const char *two_char_token) {
  325. ComplexityGuard guard(state);
  326. if (guard.IsTooComplex()) return false;
  327. if (RemainingInput(state)[0] == two_char_token[0] &&
  328. RemainingInput(state)[1] == two_char_token[1]) {
  329. state->parse_state.mangled_idx += 2;
  330. UpdateHighWaterMark(state);
  331. return true;
  332. }
  333. return false;
  334. }
  335. // Returns true and advances "mangled_idx" if we find "three_char_token"
  336. // at "mangled_idx" position. It is assumed that "three_char_token" does
  337. // not contain '\0'.
  338. static bool ParseThreeCharToken(State *state, const char *three_char_token) {
  339. ComplexityGuard guard(state);
  340. if (guard.IsTooComplex()) return false;
  341. if (RemainingInput(state)[0] == three_char_token[0] &&
  342. RemainingInput(state)[1] == three_char_token[1] &&
  343. RemainingInput(state)[2] == three_char_token[2]) {
  344. state->parse_state.mangled_idx += 3;
  345. UpdateHighWaterMark(state);
  346. return true;
  347. }
  348. return false;
  349. }
  350. // Returns true and advances "mangled_idx" if we find a copy of the
  351. // NUL-terminated string "long_token" at "mangled_idx" position.
  352. static bool ParseLongToken(State *state, const char *long_token) {
  353. ComplexityGuard guard(state);
  354. if (guard.IsTooComplex()) return false;
  355. int i = 0;
  356. for (; long_token[i] != '\0'; ++i) {
  357. // Note that we cannot run off the end of the NUL-terminated input here.
  358. // Inside the loop body, long_token[i] is known to be different from NUL.
  359. // So if we read the NUL on the end of the input here, we return at once.
  360. if (RemainingInput(state)[i] != long_token[i]) return false;
  361. }
  362. state->parse_state.mangled_idx += i;
  363. UpdateHighWaterMark(state);
  364. return true;
  365. }
  366. // Returns true and advances "mangled_cur" if we find any character in
  367. // "char_class" at "mangled_cur" position.
  368. static bool ParseCharClass(State *state, const char *char_class) {
  369. ComplexityGuard guard(state);
  370. if (guard.IsTooComplex()) return false;
  371. if (RemainingInput(state)[0] == '\0') {
  372. return false;
  373. }
  374. const char *p = char_class;
  375. for (; *p != '\0'; ++p) {
  376. if (RemainingInput(state)[0] == *p) {
  377. ++state->parse_state.mangled_idx;
  378. UpdateHighWaterMark(state);
  379. return true;
  380. }
  381. }
  382. return false;
  383. }
  384. static bool ParseDigit(State *state, int *digit) {
  385. char c = RemainingInput(state)[0];
  386. if (ParseCharClass(state, "0123456789")) {
  387. if (digit != nullptr) {
  388. *digit = c - '0';
  389. }
  390. return true;
  391. }
  392. return false;
  393. }
  394. // This function is used for handling an optional non-terminal.
  395. static bool Optional(bool /*status*/) { return true; }
  396. // This function is used for handling <non-terminal>+ syntax.
  397. typedef bool (*ParseFunc)(State *);
  398. static bool OneOrMore(ParseFunc parse_func, State *state) {
  399. if (parse_func(state)) {
  400. while (parse_func(state)) {
  401. }
  402. return true;
  403. }
  404. return false;
  405. }
  406. // This function is used for handling <non-terminal>* syntax. The function
  407. // always returns true and must be followed by a termination token or a
  408. // terminating sequence not handled by parse_func (e.g.
  409. // ParseOneCharToken(state, 'E')).
  410. static bool ZeroOrMore(ParseFunc parse_func, State *state) {
  411. while (parse_func(state)) {
  412. }
  413. return true;
  414. }
  415. // Append "str" at "out_cur_idx". If there is an overflow, out_cur_idx is
  416. // set to out_end_idx+1. The output string is ensured to
  417. // always terminate with '\0' as long as there is no overflow.
  418. static void Append(State *state, const char *const str, const size_t length) {
  419. for (size_t i = 0; i < length; ++i) {
  420. if (state->parse_state.out_cur_idx + 1 <
  421. state->out_end_idx) { // +1 for '\0'
  422. state->out[state->parse_state.out_cur_idx++] = str[i];
  423. } else {
  424. // signal overflow
  425. state->parse_state.out_cur_idx = state->out_end_idx + 1;
  426. break;
  427. }
  428. }
  429. if (state->parse_state.out_cur_idx < state->out_end_idx) {
  430. state->out[state->parse_state.out_cur_idx] =
  431. '\0'; // Terminate it with '\0'
  432. }
  433. }
  434. // We don't use equivalents in libc to avoid locale issues.
  435. static bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
  436. static bool IsAlpha(char c) {
  437. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  438. }
  439. static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
  440. // Returns true if "str" is a function clone suffix. These suffixes are used
  441. // by GCC 4.5.x and later versions (and our locally-modified version of GCC
  442. // 4.4.x) to indicate functions which have been cloned during optimization.
  443. // We treat any sequence (.<alpha>+.<digit>+)+ as a function clone suffix.
  444. // Additionally, '_' is allowed along with the alphanumeric sequence.
  445. static bool IsFunctionCloneSuffix(const char *str) {
  446. size_t i = 0;
  447. while (str[i] != '\0') {
  448. bool parsed = false;
  449. // Consume a single [.<alpha> | _]*[.<digit>]* sequence.
  450. if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) {
  451. parsed = true;
  452. i += 2;
  453. while (IsAlpha(str[i]) || str[i] == '_') {
  454. ++i;
  455. }
  456. }
  457. if (str[i] == '.' && IsDigit(str[i + 1])) {
  458. parsed = true;
  459. i += 2;
  460. while (IsDigit(str[i])) {
  461. ++i;
  462. }
  463. }
  464. if (!parsed)
  465. return false;
  466. }
  467. return true; // Consumed everything in "str".
  468. }
  469. static bool EndsWith(State *state, const char chr) {
  470. return state->parse_state.out_cur_idx > 0 &&
  471. state->parse_state.out_cur_idx < state->out_end_idx &&
  472. chr == state->out[state->parse_state.out_cur_idx - 1];
  473. }
  474. // Append "str" with some tweaks, iff "append" state is true.
  475. static void MaybeAppendWithLength(State *state, const char *const str,
  476. const size_t length) {
  477. if (state->parse_state.append && length > 0) {
  478. // Append a space if the output buffer ends with '<' and "str"
  479. // starts with '<' to avoid <<<.
  480. if (str[0] == '<' && EndsWith(state, '<')) {
  481. Append(state, " ", 1);
  482. }
  483. // Remember the last identifier name for ctors/dtors,
  484. // but only if we haven't yet overflown the buffer.
  485. if (state->parse_state.out_cur_idx < state->out_end_idx &&
  486. (IsAlpha(str[0]) || str[0] == '_')) {
  487. state->parse_state.prev_name_idx = state->parse_state.out_cur_idx;
  488. state->parse_state.prev_name_length = static_cast<unsigned int>(length);
  489. }
  490. Append(state, str, length);
  491. }
  492. }
  493. // Appends a positive decimal number to the output if appending is enabled.
  494. static bool MaybeAppendDecimal(State *state, int val) {
  495. // Max {32-64}-bit unsigned int is 20 digits.
  496. constexpr size_t kMaxLength = 20;
  497. char buf[kMaxLength];
  498. // We can't use itoa or sprintf as neither is specified to be
  499. // async-signal-safe.
  500. if (state->parse_state.append) {
  501. // We can't have a one-before-the-beginning pointer, so instead start with
  502. // one-past-the-end and manipulate one character before the pointer.
  503. char *p = &buf[kMaxLength];
  504. do { // val=0 is the only input that should write a leading zero digit.
  505. *--p = static_cast<char>((val % 10) + '0');
  506. val /= 10;
  507. } while (p > buf && val != 0);
  508. // 'p' landed on the last character we set. How convenient.
  509. Append(state, p, kMaxLength - static_cast<size_t>(p - buf));
  510. }
  511. return true;
  512. }
  513. // A convenient wrapper around MaybeAppendWithLength().
  514. // Returns true so that it can be placed in "if" conditions.
  515. static bool MaybeAppend(State *state, const char *const str) {
  516. if (state->parse_state.append) {
  517. size_t length = StrLen(str);
  518. MaybeAppendWithLength(state, str, length);
  519. }
  520. return true;
  521. }
  522. // This function is used for handling nested names.
  523. static bool EnterNestedName(State *state) {
  524. state->parse_state.nest_level = 0;
  525. return true;
  526. }
  527. // This function is used for handling nested names.
  528. static bool LeaveNestedName(State *state, int16_t prev_value) {
  529. state->parse_state.nest_level = prev_value;
  530. return true;
  531. }
  532. // Disable the append mode not to print function parameters, etc.
  533. static bool DisableAppend(State *state) {
  534. state->parse_state.append = false;
  535. return true;
  536. }
  537. // Restore the append mode to the previous state.
  538. static bool RestoreAppend(State *state, bool prev_value) {
  539. state->parse_state.append = prev_value;
  540. return true;
  541. }
  542. // Increase the nest level for nested names.
  543. static void MaybeIncreaseNestLevel(State *state) {
  544. if (state->parse_state.nest_level > -1) {
  545. ++state->parse_state.nest_level;
  546. }
  547. }
  548. // Appends :: for nested names if necessary.
  549. static void MaybeAppendSeparator(State *state) {
  550. if (state->parse_state.nest_level >= 1) {
  551. MaybeAppend(state, "::");
  552. }
  553. }
  554. // Cancel the last separator if necessary.
  555. static void MaybeCancelLastSeparator(State *state) {
  556. if (state->parse_state.nest_level >= 1 && state->parse_state.append &&
  557. state->parse_state.out_cur_idx >= 2) {
  558. state->parse_state.out_cur_idx -= 2;
  559. state->out[state->parse_state.out_cur_idx] = '\0';
  560. }
  561. }
  562. // Returns true if the identifier of the given length pointed to by
  563. // "mangled_cur" is anonymous namespace.
  564. static bool IdentifierIsAnonymousNamespace(State *state, size_t length) {
  565. // Returns true if "anon_prefix" is a proper prefix of "mangled_cur".
  566. static const char anon_prefix[] = "_GLOBAL__N_";
  567. return (length > (sizeof(anon_prefix) - 1) &&
  568. StrPrefix(RemainingInput(state), anon_prefix));
  569. }
  570. // Forward declarations of our parsing functions.
  571. static bool ParseMangledName(State *state);
  572. static bool ParseEncoding(State *state);
  573. static bool ParseName(State *state);
  574. static bool ParseUnscopedName(State *state);
  575. static bool ParseNestedName(State *state);
  576. static bool ParsePrefix(State *state);
  577. static bool ParseUnqualifiedName(State *state);
  578. static bool ParseSourceName(State *state);
  579. static bool ParseLocalSourceName(State *state);
  580. static bool ParseUnnamedTypeName(State *state);
  581. static bool ParseNumber(State *state, int *number_out);
  582. static bool ParseFloatNumber(State *state);
  583. static bool ParseSeqId(State *state);
  584. static bool ParseIdentifier(State *state, size_t length);
  585. static bool ParseOperatorName(State *state, int *arity);
  586. static bool ParseConversionOperatorType(State *state);
  587. static bool ParseSpecialName(State *state);
  588. static bool ParseCallOffset(State *state);
  589. static bool ParseNVOffset(State *state);
  590. static bool ParseVOffset(State *state);
  591. static bool ParseAbiTags(State *state);
  592. static bool ParseCtorDtorName(State *state);
  593. static bool ParseDecltype(State *state);
  594. static bool ParseType(State *state);
  595. static bool ParseCVQualifiers(State *state);
  596. static bool ParseExtendedQualifier(State *state);
  597. static bool ParseBuiltinType(State *state);
  598. static bool ParseVendorExtendedType(State *state);
  599. static bool ParseFunctionType(State *state);
  600. static bool ParseBareFunctionType(State *state);
  601. static bool ParseOverloadAttribute(State *state);
  602. static bool ParseClassEnumType(State *state);
  603. static bool ParseArrayType(State *state);
  604. static bool ParsePointerToMemberType(State *state);
  605. static bool ParseTemplateParam(State *state);
  606. static bool ParseTemplateParamDecl(State *state);
  607. static bool ParseTemplateTemplateParam(State *state);
  608. static bool ParseTemplateArgs(State *state);
  609. static bool ParseTemplateArg(State *state);
  610. static bool ParseBaseUnresolvedName(State *state);
  611. static bool ParseUnresolvedName(State *state);
  612. static bool ParseUnresolvedQualifierLevel(State *state);
  613. static bool ParseUnionSelector(State* state);
  614. static bool ParseFunctionParam(State* state);
  615. static bool ParseBracedExpression(State *state);
  616. static bool ParseExpression(State *state);
  617. static bool ParseInitializer(State *state);
  618. static bool ParseExprPrimary(State *state);
  619. static bool ParseExprCastValueAndTrailingE(State *state);
  620. static bool ParseQRequiresClauseExpr(State *state);
  621. static bool ParseRequirement(State *state);
  622. static bool ParseTypeConstraint(State *state);
  623. static bool ParseLocalName(State *state);
  624. static bool ParseLocalNameSuffix(State *state);
  625. static bool ParseDiscriminator(State *state);
  626. static bool ParseSubstitution(State *state, bool accept_std);
  627. // Implementation note: the following code is a straightforward
  628. // translation of the Itanium C++ ABI defined in BNF with a couple of
  629. // exceptions.
  630. //
  631. // - Support GNU extensions not defined in the Itanium C++ ABI
  632. // - <prefix> and <template-prefix> are combined to avoid infinite loop
  633. // - Reorder patterns to shorten the code
  634. // - Reorder patterns to give greedier functions precedence
  635. // We'll mark "Less greedy than" for these cases in the code
  636. //
  637. // Each parsing function changes the parse state and returns true on
  638. // success, or returns false and doesn't change the parse state (note:
  639. // the parse-steps counter increases regardless of success or failure).
  640. // To ensure that the parse state isn't changed in the latter case, we
  641. // save the original state before we call multiple parsing functions
  642. // consecutively with &&, and restore it if unsuccessful. See
  643. // ParseEncoding() as an example of this convention. We follow the
  644. // convention throughout the code.
  645. //
  646. // Originally we tried to do demangling without following the full ABI
  647. // syntax but it turned out we needed to follow the full syntax to
  648. // parse complicated cases like nested template arguments. Note that
  649. // implementing a full-fledged demangler isn't trivial (libiberty's
  650. // cp-demangle.c has +4300 lines).
  651. //
  652. // Note that (foo) in <(foo) ...> is a modifier to be ignored.
  653. //
  654. // Reference:
  655. // - Itanium C++ ABI
  656. // <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>
  657. // <mangled-name> ::= _Z <encoding>
  658. static bool ParseMangledName(State *state) {
  659. ComplexityGuard guard(state);
  660. if (guard.IsTooComplex()) return false;
  661. return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
  662. }
  663. // <encoding> ::= <(function) name> <bare-function-type>
  664. // [`Q` <requires-clause expr>]
  665. // ::= <(data) name>
  666. // ::= <special-name>
  667. //
  668. // NOTE: Based on http://shortn/_Hoq9qG83rx
  669. static bool ParseEncoding(State *state) {
  670. ComplexityGuard guard(state);
  671. if (guard.IsTooComplex()) return false;
  672. // Since the first two productions both start with <name>, attempt
  673. // to parse it only once to avoid exponential blowup of backtracking.
  674. //
  675. // We're careful about exponential blowup because <encoding> recursively
  676. // appears in other productions downstream of its first two productions,
  677. // which means that every call to `ParseName` would possibly indirectly
  678. // result in two calls to `ParseName` etc.
  679. if (ParseName(state)) {
  680. if (!ParseBareFunctionType(state)) {
  681. return true; // <(data) name>
  682. }
  683. // Parsed: <(function) name> <bare-function-type>
  684. // Pending: [`Q` <requires-clause expr>]
  685. ParseQRequiresClauseExpr(state); // restores state on failure
  686. return true;
  687. }
  688. if (ParseSpecialName(state)) {
  689. return true; // <special-name>
  690. }
  691. return false;
  692. }
  693. // <name> ::= <nested-name>
  694. // ::= <unscoped-template-name> <template-args>
  695. // ::= <unscoped-name>
  696. // ::= <local-name>
  697. static bool ParseName(State *state) {
  698. ComplexityGuard guard(state);
  699. if (guard.IsTooComplex()) return false;
  700. if (ParseNestedName(state) || ParseLocalName(state)) {
  701. return true;
  702. }
  703. // We reorganize the productions to avoid re-parsing unscoped names.
  704. // - Inline <unscoped-template-name> productions:
  705. // <name> ::= <substitution> <template-args>
  706. // ::= <unscoped-name> <template-args>
  707. // ::= <unscoped-name>
  708. // - Merge the two productions that start with unscoped-name:
  709. // <name> ::= <unscoped-name> [<template-args>]
  710. ParseState copy = state->parse_state;
  711. // "std<...>" isn't a valid name.
  712. if (ParseSubstitution(state, /*accept_std=*/false) &&
  713. ParseTemplateArgs(state)) {
  714. return true;
  715. }
  716. state->parse_state = copy;
  717. // Note there's no need to restore state after this since only the first
  718. // subparser can fail.
  719. return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state));
  720. }
  721. // <unscoped-name> ::= <unqualified-name>
  722. // ::= St <unqualified-name>
  723. static bool ParseUnscopedName(State *state) {
  724. ComplexityGuard guard(state);
  725. if (guard.IsTooComplex()) return false;
  726. if (ParseUnqualifiedName(state)) {
  727. return true;
  728. }
  729. ParseState copy = state->parse_state;
  730. if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") &&
  731. ParseUnqualifiedName(state)) {
  732. return true;
  733. }
  734. state->parse_state = copy;
  735. return false;
  736. }
  737. // <ref-qualifer> ::= R // lvalue method reference qualifier
  738. // ::= O // rvalue method reference qualifier
  739. static inline bool ParseRefQualifier(State *state) {
  740. return ParseCharClass(state, "OR");
  741. }
  742. // <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix>
  743. // <unqualified-name> E
  744. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
  745. // <template-args> E
  746. static bool ParseNestedName(State *state) {
  747. ComplexityGuard guard(state);
  748. if (guard.IsTooComplex()) return false;
  749. ParseState copy = state->parse_state;
  750. if (ParseOneCharToken(state, 'N') && EnterNestedName(state) &&
  751. Optional(ParseCVQualifiers(state)) &&
  752. Optional(ParseRefQualifier(state)) && ParsePrefix(state) &&
  753. LeaveNestedName(state, copy.nest_level) &&
  754. ParseOneCharToken(state, 'E')) {
  755. return true;
  756. }
  757. state->parse_state = copy;
  758. return false;
  759. }
  760. // This part is tricky. If we literally translate them to code, we'll
  761. // end up infinite loop. Hence we merge them to avoid the case.
  762. //
  763. // <prefix> ::= <prefix> <unqualified-name>
  764. // ::= <template-prefix> <template-args>
  765. // ::= <template-param>
  766. // ::= <decltype>
  767. // ::= <substitution>
  768. // ::= # empty
  769. // <template-prefix> ::= <prefix> <(template) unqualified-name>
  770. // ::= <template-param>
  771. // ::= <substitution>
  772. // ::= <vendor-extended-type>
  773. static bool ParsePrefix(State *state) {
  774. ComplexityGuard guard(state);
  775. if (guard.IsTooComplex()) return false;
  776. bool has_something = false;
  777. while (true) {
  778. MaybeAppendSeparator(state);
  779. if (ParseTemplateParam(state) || ParseDecltype(state) ||
  780. ParseSubstitution(state, /*accept_std=*/true) ||
  781. // Although the official grammar does not mention it, nested-names
  782. // shaped like Nu14__some_builtinIiE6memberE occur in practice, and it
  783. // is not clear what else a compiler is supposed to do when a
  784. // vendor-extended type has named members.
  785. ParseVendorExtendedType(state) ||
  786. ParseUnscopedName(state) ||
  787. (ParseOneCharToken(state, 'M') && ParseUnnamedTypeName(state))) {
  788. has_something = true;
  789. MaybeIncreaseNestLevel(state);
  790. continue;
  791. }
  792. MaybeCancelLastSeparator(state);
  793. if (has_something && ParseTemplateArgs(state)) {
  794. return ParsePrefix(state);
  795. } else {
  796. break;
  797. }
  798. }
  799. return true;
  800. }
  801. // <unqualified-name> ::= <operator-name> [<abi-tags>]
  802. // ::= <ctor-dtor-name> [<abi-tags>]
  803. // ::= <source-name> [<abi-tags>]
  804. // ::= <local-source-name> [<abi-tags>]
  805. // ::= <unnamed-type-name> [<abi-tags>]
  806. // ::= DC <source-name>+ E # C++17 structured binding
  807. // ::= F <source-name> # C++20 constrained friend
  808. // ::= F <operator-name> # C++20 constrained friend
  809. //
  810. // <local-source-name> is a GCC extension; see below.
  811. //
  812. // For the F notation for constrained friends, see
  813. // https://github.com/itanium-cxx-abi/cxx-abi/issues/24#issuecomment-1491130332.
  814. static bool ParseUnqualifiedName(State *state) {
  815. ComplexityGuard guard(state);
  816. if (guard.IsTooComplex()) return false;
  817. if (ParseOperatorName(state, nullptr) || ParseCtorDtorName(state) ||
  818. ParseSourceName(state) || ParseLocalSourceName(state) ||
  819. ParseUnnamedTypeName(state)) {
  820. return ParseAbiTags(state);
  821. }
  822. // DC <source-name>+ E
  823. ParseState copy = state->parse_state;
  824. if (ParseTwoCharToken(state, "DC") && OneOrMore(ParseSourceName, state) &&
  825. ParseOneCharToken(state, 'E')) {
  826. return true;
  827. }
  828. state->parse_state = copy;
  829. // F <source-name>
  830. // F <operator-name>
  831. if (ParseOneCharToken(state, 'F') && MaybeAppend(state, "friend ") &&
  832. (ParseSourceName(state) || ParseOperatorName(state, nullptr))) {
  833. return true;
  834. }
  835. state->parse_state = copy;
  836. return false;
  837. }
  838. // <abi-tags> ::= <abi-tag> [<abi-tags>]
  839. // <abi-tag> ::= B <source-name>
  840. static bool ParseAbiTags(State *state) {
  841. ComplexityGuard guard(state);
  842. if (guard.IsTooComplex()) return false;
  843. while (ParseOneCharToken(state, 'B')) {
  844. ParseState copy = state->parse_state;
  845. MaybeAppend(state, "[abi:");
  846. if (!ParseSourceName(state)) {
  847. state->parse_state = copy;
  848. return false;
  849. }
  850. MaybeAppend(state, "]");
  851. }
  852. return true;
  853. }
  854. // <source-name> ::= <positive length number> <identifier>
  855. static bool ParseSourceName(State *state) {
  856. ComplexityGuard guard(state);
  857. if (guard.IsTooComplex()) return false;
  858. ParseState copy = state->parse_state;
  859. int length = -1;
  860. if (ParseNumber(state, &length) &&
  861. ParseIdentifier(state, static_cast<size_t>(length))) {
  862. return true;
  863. }
  864. state->parse_state = copy;
  865. return false;
  866. }
  867. // <local-source-name> ::= L <source-name> [<discriminator>]
  868. //
  869. // References:
  870. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
  871. // https://gcc.gnu.org/viewcvs?view=rev&revision=124467
  872. static bool ParseLocalSourceName(State *state) {
  873. ComplexityGuard guard(state);
  874. if (guard.IsTooComplex()) return false;
  875. ParseState copy = state->parse_state;
  876. if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
  877. Optional(ParseDiscriminator(state))) {
  878. return true;
  879. }
  880. state->parse_state = copy;
  881. return false;
  882. }
  883. // <unnamed-type-name> ::= Ut [<(nonnegative) number>] _
  884. // ::= <closure-type-name>
  885. // <closure-type-name> ::= Ul <lambda-sig> E [<(nonnegative) number>] _
  886. // <lambda-sig> ::= <template-param-decl>* <(parameter) type>+
  887. //
  888. // For <template-param-decl>* in <lambda-sig> see:
  889. //
  890. // https://github.com/itanium-cxx-abi/cxx-abi/issues/31
  891. static bool ParseUnnamedTypeName(State *state) {
  892. ComplexityGuard guard(state);
  893. if (guard.IsTooComplex()) return false;
  894. ParseState copy = state->parse_state;
  895. // Type's 1-based index n is encoded as { "", n == 1; itoa(n-2), otherwise }.
  896. // Optionally parse the encoded value into 'which' and add 2 to get the index.
  897. int which = -1;
  898. // Unnamed type local to function or class.
  899. if (ParseTwoCharToken(state, "Ut") && Optional(ParseNumber(state, &which)) &&
  900. which <= std::numeric_limits<int>::max() - 2 && // Don't overflow.
  901. ParseOneCharToken(state, '_')) {
  902. MaybeAppend(state, "{unnamed type#");
  903. MaybeAppendDecimal(state, 2 + which);
  904. MaybeAppend(state, "}");
  905. return true;
  906. }
  907. state->parse_state = copy;
  908. // Closure type.
  909. which = -1;
  910. if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) &&
  911. ZeroOrMore(ParseTemplateParamDecl, state) &&
  912. OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) &&
  913. ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) &&
  914. which <= std::numeric_limits<int>::max() - 2 && // Don't overflow.
  915. ParseOneCharToken(state, '_')) {
  916. MaybeAppend(state, "{lambda()#");
  917. MaybeAppendDecimal(state, 2 + which);
  918. MaybeAppend(state, "}");
  919. return true;
  920. }
  921. state->parse_state = copy;
  922. return false;
  923. }
  924. // <number> ::= [n] <non-negative decimal integer>
  925. // If "number_out" is non-null, then *number_out is set to the value of the
  926. // parsed number on success.
  927. static bool ParseNumber(State *state, int *number_out) {
  928. ComplexityGuard guard(state);
  929. if (guard.IsTooComplex()) return false;
  930. bool negative = false;
  931. if (ParseOneCharToken(state, 'n')) {
  932. negative = true;
  933. }
  934. const char *p = RemainingInput(state);
  935. uint64_t number = 0;
  936. for (; *p != '\0'; ++p) {
  937. if (IsDigit(*p)) {
  938. number = number * 10 + static_cast<uint64_t>(*p - '0');
  939. } else {
  940. break;
  941. }
  942. }
  943. // Apply the sign with uint64_t arithmetic so overflows aren't UB. Gives
  944. // "incorrect" results for out-of-range inputs, but negative values only
  945. // appear for literals, which aren't printed.
  946. if (negative) {
  947. number = ~number + 1;
  948. }
  949. if (p != RemainingInput(state)) { // Conversion succeeded.
  950. state->parse_state.mangled_idx += p - RemainingInput(state);
  951. UpdateHighWaterMark(state);
  952. if (number_out != nullptr) {
  953. // Note: possibly truncate "number".
  954. *number_out = static_cast<int>(number);
  955. }
  956. return true;
  957. }
  958. return false;
  959. }
  960. // Floating-point literals are encoded using a fixed-length lowercase
  961. // hexadecimal string.
  962. static bool ParseFloatNumber(State *state) {
  963. ComplexityGuard guard(state);
  964. if (guard.IsTooComplex()) return false;
  965. const char *p = RemainingInput(state);
  966. for (; *p != '\0'; ++p) {
  967. if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
  968. break;
  969. }
  970. }
  971. if (p != RemainingInput(state)) { // Conversion succeeded.
  972. state->parse_state.mangled_idx += p - RemainingInput(state);
  973. UpdateHighWaterMark(state);
  974. return true;
  975. }
  976. return false;
  977. }
  978. // The <seq-id> is a sequence number in base 36,
  979. // using digits and upper case letters
  980. static bool ParseSeqId(State *state) {
  981. ComplexityGuard guard(state);
  982. if (guard.IsTooComplex()) return false;
  983. const char *p = RemainingInput(state);
  984. for (; *p != '\0'; ++p) {
  985. if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
  986. break;
  987. }
  988. }
  989. if (p != RemainingInput(state)) { // Conversion succeeded.
  990. state->parse_state.mangled_idx += p - RemainingInput(state);
  991. UpdateHighWaterMark(state);
  992. return true;
  993. }
  994. return false;
  995. }
  996. // <identifier> ::= <unqualified source code identifier> (of given length)
  997. static bool ParseIdentifier(State *state, size_t length) {
  998. ComplexityGuard guard(state);
  999. if (guard.IsTooComplex()) return false;
  1000. if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) {
  1001. return false;
  1002. }
  1003. if (IdentifierIsAnonymousNamespace(state, length)) {
  1004. MaybeAppend(state, "(anonymous namespace)");
  1005. } else {
  1006. MaybeAppendWithLength(state, RemainingInput(state), length);
  1007. }
  1008. state->parse_state.mangled_idx += length;
  1009. UpdateHighWaterMark(state);
  1010. return true;
  1011. }
  1012. // <operator-name> ::= nw, and other two letters cases
  1013. // ::= cv <type> # (cast)
  1014. // ::= li <source-name> # C++11 user-defined literal
  1015. // ::= v <digit> <source-name> # vendor extended operator
  1016. static bool ParseOperatorName(State *state, int *arity) {
  1017. ComplexityGuard guard(state);
  1018. if (guard.IsTooComplex()) return false;
  1019. if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) {
  1020. return false;
  1021. }
  1022. // First check with "cv" (cast) case.
  1023. ParseState copy = state->parse_state;
  1024. if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") &&
  1025. EnterNestedName(state) && ParseConversionOperatorType(state) &&
  1026. LeaveNestedName(state, copy.nest_level)) {
  1027. if (arity != nullptr) {
  1028. *arity = 1;
  1029. }
  1030. return true;
  1031. }
  1032. state->parse_state = copy;
  1033. // Then user-defined literals.
  1034. if (ParseTwoCharToken(state, "li") && MaybeAppend(state, "operator\"\" ") &&
  1035. ParseSourceName(state)) {
  1036. return true;
  1037. }
  1038. state->parse_state = copy;
  1039. // Then vendor extended operators.
  1040. if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) &&
  1041. ParseSourceName(state)) {
  1042. return true;
  1043. }
  1044. state->parse_state = copy;
  1045. // Other operator names should start with a lower alphabet followed
  1046. // by a lower/upper alphabet.
  1047. if (!(IsLower(RemainingInput(state)[0]) &&
  1048. IsAlpha(RemainingInput(state)[1]))) {
  1049. return false;
  1050. }
  1051. // We may want to perform a binary search if we really need speed.
  1052. const AbbrevPair *p;
  1053. for (p = kOperatorList; p->abbrev != nullptr; ++p) {
  1054. if (RemainingInput(state)[0] == p->abbrev[0] &&
  1055. RemainingInput(state)[1] == p->abbrev[1]) {
  1056. if (arity != nullptr) {
  1057. *arity = p->arity;
  1058. }
  1059. MaybeAppend(state, "operator");
  1060. if (IsLower(*p->real_name)) { // new, delete, etc.
  1061. MaybeAppend(state, " ");
  1062. }
  1063. MaybeAppend(state, p->real_name);
  1064. state->parse_state.mangled_idx += 2;
  1065. UpdateHighWaterMark(state);
  1066. return true;
  1067. }
  1068. }
  1069. return false;
  1070. }
  1071. // <operator-name> ::= cv <type> # (cast)
  1072. //
  1073. // The name of a conversion operator is the one place where cv-qualifiers, *, &,
  1074. // and other simple type combinators are expected to appear in our stripped-down
  1075. // demangling (elsewhere they appear in function signatures or template
  1076. // arguments, which we omit from the output). We make reasonable efforts to
  1077. // render simple cases accurately.
  1078. static bool ParseConversionOperatorType(State *state) {
  1079. ComplexityGuard guard(state);
  1080. if (guard.IsTooComplex()) return false;
  1081. ParseState copy = state->parse_state;
  1082. // Scan pointers, const, and other easy mangling prefixes with postfix
  1083. // demanglings. Remember the range of input for later rescanning.
  1084. //
  1085. // See `ParseType` and the `switch` below for the meaning of each char.
  1086. const char* begin_simple_prefixes = RemainingInput(state);
  1087. while (ParseCharClass(state, "OPRCGrVK")) {}
  1088. const char* end_simple_prefixes = RemainingInput(state);
  1089. // Emit the base type first.
  1090. if (!ParseType(state)) {
  1091. state->parse_state = copy;
  1092. return false;
  1093. }
  1094. // Then rescan the easy type combinators in reverse order to emit their
  1095. // demanglings in the expected output order.
  1096. while (begin_simple_prefixes != end_simple_prefixes) {
  1097. switch (*--end_simple_prefixes) {
  1098. case 'P':
  1099. MaybeAppend(state, "*");
  1100. break;
  1101. case 'R':
  1102. MaybeAppend(state, "&");
  1103. break;
  1104. case 'O':
  1105. MaybeAppend(state, "&&");
  1106. break;
  1107. case 'C':
  1108. MaybeAppend(state, " _Complex");
  1109. break;
  1110. case 'G':
  1111. MaybeAppend(state, " _Imaginary");
  1112. break;
  1113. case 'r':
  1114. MaybeAppend(state, " restrict");
  1115. break;
  1116. case 'V':
  1117. MaybeAppend(state, " volatile");
  1118. break;
  1119. case 'K':
  1120. MaybeAppend(state, " const");
  1121. break;
  1122. }
  1123. }
  1124. return true;
  1125. }
  1126. // <special-name> ::= TV <type>
  1127. // ::= TT <type>
  1128. // ::= TI <type>
  1129. // ::= TS <type>
  1130. // ::= TW <name> # thread-local wrapper
  1131. // ::= TH <name> # thread-local initialization
  1132. // ::= Tc <call-offset> <call-offset> <(base) encoding>
  1133. // ::= GV <(object) name>
  1134. // ::= GR <(object) name> [<seq-id>] _
  1135. // ::= T <call-offset> <(base) encoding>
  1136. // ::= GTt <encoding> # transaction-safe entry point
  1137. // ::= TA <template-arg> # nontype template parameter object
  1138. // G++ extensions:
  1139. // ::= TC <type> <(offset) number> _ <(base) type>
  1140. // ::= TF <type>
  1141. // ::= TJ <type>
  1142. // ::= GR <name> # without final _, perhaps an earlier form?
  1143. // ::= GA <encoding>
  1144. // ::= Th <call-offset> <(base) encoding>
  1145. // ::= Tv <call-offset> <(base) encoding>
  1146. //
  1147. // Note: Most of these are special data, not functions that occur in stack
  1148. // traces. Exceptions are TW and TH, which denote functions supporting the
  1149. // thread_local feature. For these see:
  1150. //
  1151. // https://maskray.me/blog/2021-02-14-all-about-thread-local-storage
  1152. //
  1153. // For TA see https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
  1154. static bool ParseSpecialName(State *state) {
  1155. ComplexityGuard guard(state);
  1156. if (guard.IsTooComplex()) return false;
  1157. ParseState copy = state->parse_state;
  1158. if (ParseTwoCharToken(state, "TW")) {
  1159. MaybeAppend(state, "thread-local wrapper routine for ");
  1160. if (ParseName(state)) return true;
  1161. state->parse_state = copy;
  1162. return false;
  1163. }
  1164. if (ParseTwoCharToken(state, "TH")) {
  1165. MaybeAppend(state, "thread-local initialization routine for ");
  1166. if (ParseName(state)) return true;
  1167. state->parse_state = copy;
  1168. return false;
  1169. }
  1170. if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTIS") &&
  1171. ParseType(state)) {
  1172. return true;
  1173. }
  1174. state->parse_state = copy;
  1175. if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
  1176. ParseCallOffset(state) && ParseEncoding(state)) {
  1177. return true;
  1178. }
  1179. state->parse_state = copy;
  1180. if (ParseTwoCharToken(state, "GV") && ParseName(state)) {
  1181. return true;
  1182. }
  1183. state->parse_state = copy;
  1184. if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
  1185. ParseEncoding(state)) {
  1186. return true;
  1187. }
  1188. state->parse_state = copy;
  1189. // G++ extensions
  1190. if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
  1191. ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
  1192. DisableAppend(state) && ParseType(state)) {
  1193. RestoreAppend(state, copy.append);
  1194. return true;
  1195. }
  1196. state->parse_state = copy;
  1197. if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
  1198. ParseType(state)) {
  1199. return true;
  1200. }
  1201. state->parse_state = copy;
  1202. // <special-name> ::= GR <(object) name> [<seq-id>] _ # modern standard
  1203. // ::= GR <(object) name> # also recognized
  1204. if (ParseTwoCharToken(state, "GR")) {
  1205. MaybeAppend(state, "reference temporary for ");
  1206. if (!ParseName(state)) {
  1207. state->parse_state = copy;
  1208. return false;
  1209. }
  1210. const bool has_seq_id = ParseSeqId(state);
  1211. const bool has_underscore = ParseOneCharToken(state, '_');
  1212. if (has_seq_id && !has_underscore) {
  1213. state->parse_state = copy;
  1214. return false;
  1215. }
  1216. return true;
  1217. }
  1218. if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
  1219. return true;
  1220. }
  1221. state->parse_state = copy;
  1222. if (ParseThreeCharToken(state, "GTt") &&
  1223. MaybeAppend(state, "transaction clone for ") && ParseEncoding(state)) {
  1224. return true;
  1225. }
  1226. state->parse_state = copy;
  1227. if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
  1228. ParseCallOffset(state) && ParseEncoding(state)) {
  1229. return true;
  1230. }
  1231. state->parse_state = copy;
  1232. if (ParseTwoCharToken(state, "TA")) {
  1233. bool append = state->parse_state.append;
  1234. DisableAppend(state);
  1235. if (ParseTemplateArg(state)) {
  1236. RestoreAppend(state, append);
  1237. MaybeAppend(state, "template parameter object");
  1238. return true;
  1239. }
  1240. }
  1241. state->parse_state = copy;
  1242. return false;
  1243. }
  1244. // <call-offset> ::= h <nv-offset> _
  1245. // ::= v <v-offset> _
  1246. static bool ParseCallOffset(State *state) {
  1247. ComplexityGuard guard(state);
  1248. if (guard.IsTooComplex()) return false;
  1249. ParseState copy = state->parse_state;
  1250. if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) &&
  1251. ParseOneCharToken(state, '_')) {
  1252. return true;
  1253. }
  1254. state->parse_state = copy;
  1255. if (ParseOneCharToken(state, 'v') && ParseVOffset(state) &&
  1256. ParseOneCharToken(state, '_')) {
  1257. return true;
  1258. }
  1259. state->parse_state = copy;
  1260. return false;
  1261. }
  1262. // <nv-offset> ::= <(offset) number>
  1263. static bool ParseNVOffset(State *state) {
  1264. ComplexityGuard guard(state);
  1265. if (guard.IsTooComplex()) return false;
  1266. return ParseNumber(state, nullptr);
  1267. }
  1268. // <v-offset> ::= <(offset) number> _ <(virtual offset) number>
  1269. static bool ParseVOffset(State *state) {
  1270. ComplexityGuard guard(state);
  1271. if (guard.IsTooComplex()) return false;
  1272. ParseState copy = state->parse_state;
  1273. if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
  1274. ParseNumber(state, nullptr)) {
  1275. return true;
  1276. }
  1277. state->parse_state = copy;
  1278. return false;
  1279. }
  1280. // <ctor-dtor-name> ::= C1 | C2 | C3 | CI1 <base-class-type> | CI2
  1281. // <base-class-type>
  1282. // ::= D0 | D1 | D2
  1283. // # GCC extensions: "unified" constructor/destructor. See
  1284. // #
  1285. // https://github.com/gcc-mirror/gcc/blob/7ad17b583c3643bd4557f29b8391ca7ef08391f5/gcc/cp/mangle.c#L1847
  1286. // ::= C4 | D4
  1287. static bool ParseCtorDtorName(State *state) {
  1288. ComplexityGuard guard(state);
  1289. if (guard.IsTooComplex()) return false;
  1290. ParseState copy = state->parse_state;
  1291. if (ParseOneCharToken(state, 'C')) {
  1292. if (ParseCharClass(state, "1234")) {
  1293. const char *const prev_name =
  1294. state->out + state->parse_state.prev_name_idx;
  1295. MaybeAppendWithLength(state, prev_name,
  1296. state->parse_state.prev_name_length);
  1297. return true;
  1298. } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") &&
  1299. ParseClassEnumType(state)) {
  1300. return true;
  1301. }
  1302. }
  1303. state->parse_state = copy;
  1304. if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) {
  1305. const char *const prev_name = state->out + state->parse_state.prev_name_idx;
  1306. MaybeAppend(state, "~");
  1307. MaybeAppendWithLength(state, prev_name,
  1308. state->parse_state.prev_name_length);
  1309. return true;
  1310. }
  1311. state->parse_state = copy;
  1312. return false;
  1313. }
  1314. // <decltype> ::= Dt <expression> E # decltype of an id-expression or class
  1315. // # member access (C++0x)
  1316. // ::= DT <expression> E # decltype of an expression (C++0x)
  1317. static bool ParseDecltype(State *state) {
  1318. ComplexityGuard guard(state);
  1319. if (guard.IsTooComplex()) return false;
  1320. ParseState copy = state->parse_state;
  1321. if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
  1322. ParseExpression(state) && ParseOneCharToken(state, 'E')) {
  1323. return true;
  1324. }
  1325. state->parse_state = copy;
  1326. return false;
  1327. }
  1328. // <type> ::= <CV-qualifiers> <type>
  1329. // ::= P <type> # pointer-to
  1330. // ::= R <type> # reference-to
  1331. // ::= O <type> # rvalue reference-to (C++0x)
  1332. // ::= C <type> # complex pair (C 2000)
  1333. // ::= G <type> # imaginary (C 2000)
  1334. // ::= <builtin-type>
  1335. // ::= <function-type>
  1336. // ::= <class-enum-type> # note: just an alias for <name>
  1337. // ::= <array-type>
  1338. // ::= <pointer-to-member-type>
  1339. // ::= <template-template-param> <template-args>
  1340. // ::= <template-param>
  1341. // ::= <decltype>
  1342. // ::= <substitution>
  1343. // ::= Dp <type> # pack expansion of (C++0x)
  1344. // ::= Dv <(elements) number> _ <type> # GNU vector extension
  1345. // ::= Dv <(bytes) expression> _ <type>
  1346. // ::= Dk <type-constraint> # constrained auto
  1347. //
  1348. static bool ParseType(State *state) {
  1349. ComplexityGuard guard(state);
  1350. if (guard.IsTooComplex()) return false;
  1351. ParseState copy = state->parse_state;
  1352. // We should check CV-qualifers, and PRGC things first.
  1353. //
  1354. // CV-qualifiers overlap with some operator names, but an operator name is not
  1355. // valid as a type. To avoid an ambiguity that can lead to exponential time
  1356. // complexity, refuse to backtrack the CV-qualifiers.
  1357. //
  1358. // _Z4aoeuIrMvvE
  1359. // => _Z 4aoeuI rM v v E
  1360. // aoeu<operator%=, void, void>
  1361. // => _Z 4aoeuI r Mv v E
  1362. // aoeu<void void::* restrict>
  1363. //
  1364. // By consuming the CV-qualifiers first, the former parse is disabled.
  1365. if (ParseCVQualifiers(state)) {
  1366. const bool result = ParseType(state);
  1367. if (!result) state->parse_state = copy;
  1368. return result;
  1369. }
  1370. state->parse_state = copy;
  1371. // Similarly, these tag characters can overlap with other <name>s resulting in
  1372. // two different parse prefixes that land on <template-args> in the same
  1373. // place, such as "C3r1xI...". So, disable the "ctor-name = C3" parse by
  1374. // refusing to backtrack the tag characters.
  1375. if (ParseCharClass(state, "OPRCG")) {
  1376. const bool result = ParseType(state);
  1377. if (!result) state->parse_state = copy;
  1378. return result;
  1379. }
  1380. state->parse_state = copy;
  1381. if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
  1382. return true;
  1383. }
  1384. state->parse_state = copy;
  1385. if (ParseBuiltinType(state) || ParseFunctionType(state) ||
  1386. ParseClassEnumType(state) || ParseArrayType(state) ||
  1387. ParsePointerToMemberType(state) || ParseDecltype(state) ||
  1388. // "std" on its own isn't a type.
  1389. ParseSubstitution(state, /*accept_std=*/false)) {
  1390. return true;
  1391. }
  1392. if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) {
  1393. return true;
  1394. }
  1395. state->parse_state = copy;
  1396. // Less greedy than <template-template-param> <template-args>.
  1397. if (ParseTemplateParam(state)) {
  1398. return true;
  1399. }
  1400. // GNU vector extension Dv <number> _ <type>
  1401. if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) &&
  1402. ParseOneCharToken(state, '_') && ParseType(state)) {
  1403. return true;
  1404. }
  1405. state->parse_state = copy;
  1406. // GNU vector extension Dv <expression> _ <type>
  1407. if (ParseTwoCharToken(state, "Dv") && ParseExpression(state) &&
  1408. ParseOneCharToken(state, '_') && ParseType(state)) {
  1409. return true;
  1410. }
  1411. state->parse_state = copy;
  1412. if (ParseTwoCharToken(state, "Dk") && ParseTypeConstraint(state)) {
  1413. return true;
  1414. }
  1415. state->parse_state = copy;
  1416. // For this notation see CXXNameMangler::mangleType in Clang's source code.
  1417. // The relevant logic and its comment "not clear how to mangle this!" date
  1418. // from 2011, so it may be with us awhile.
  1419. return ParseLongToken(state, "_SUBSTPACK_");
  1420. }
  1421. // <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
  1422. // <CV-qualifiers> ::= [r] [V] [K]
  1423. //
  1424. // We don't allow empty <CV-qualifiers> to avoid infinite loop in
  1425. // ParseType().
  1426. static bool ParseCVQualifiers(State *state) {
  1427. ComplexityGuard guard(state);
  1428. if (guard.IsTooComplex()) return false;
  1429. int num_cv_qualifiers = 0;
  1430. while (ParseExtendedQualifier(state)) ++num_cv_qualifiers;
  1431. num_cv_qualifiers += ParseOneCharToken(state, 'r');
  1432. num_cv_qualifiers += ParseOneCharToken(state, 'V');
  1433. num_cv_qualifiers += ParseOneCharToken(state, 'K');
  1434. return num_cv_qualifiers > 0;
  1435. }
  1436. // <extended-qualifier> ::= U <source-name> [<template-args>]
  1437. static bool ParseExtendedQualifier(State *state) {
  1438. ComplexityGuard guard(state);
  1439. if (guard.IsTooComplex()) return false;
  1440. ParseState copy = state->parse_state;
  1441. if (!ParseOneCharToken(state, 'U')) return false;
  1442. bool append = state->parse_state.append;
  1443. DisableAppend(state);
  1444. if (!ParseSourceName(state)) {
  1445. state->parse_state = copy;
  1446. return false;
  1447. }
  1448. Optional(ParseTemplateArgs(state));
  1449. RestoreAppend(state, append);
  1450. return true;
  1451. }
  1452. // <builtin-type> ::= v, etc. # single-character builtin types
  1453. // ::= <vendor-extended-type>
  1454. // ::= Dd, etc. # two-character builtin types
  1455. // ::= DB (<number> | <expression>) _ # _BitInt(N)
  1456. // ::= DU (<number> | <expression>) _ # unsigned _BitInt(N)
  1457. // ::= DF <number> _ # _FloatN (N bits)
  1458. // ::= DF <number> x # _FloatNx
  1459. // ::= DF16b # std::bfloat16_t
  1460. //
  1461. // Not supported:
  1462. // ::= [DS] DA <fixed-point-size>
  1463. // ::= [DS] DR <fixed-point-size>
  1464. // because real implementations of N1169 fixed-point are scant.
  1465. static bool ParseBuiltinType(State *state) {
  1466. ComplexityGuard guard(state);
  1467. if (guard.IsTooComplex()) return false;
  1468. ParseState copy = state->parse_state;
  1469. // DB (<number> | <expression>) _ # _BitInt(N)
  1470. // DU (<number> | <expression>) _ # unsigned _BitInt(N)
  1471. if (ParseTwoCharToken(state, "DB") ||
  1472. (ParseTwoCharToken(state, "DU") && MaybeAppend(state, "unsigned "))) {
  1473. bool append = state->parse_state.append;
  1474. DisableAppend(state);
  1475. int number = -1;
  1476. if (!ParseNumber(state, &number) && !ParseExpression(state)) {
  1477. state->parse_state = copy;
  1478. return false;
  1479. }
  1480. RestoreAppend(state, append);
  1481. if (!ParseOneCharToken(state, '_')) {
  1482. state->parse_state = copy;
  1483. return false;
  1484. }
  1485. MaybeAppend(state, "_BitInt(");
  1486. if (number >= 0) {
  1487. MaybeAppendDecimal(state, number);
  1488. } else {
  1489. MaybeAppend(state, "?"); // the best we can do for dependent sizes
  1490. }
  1491. MaybeAppend(state, ")");
  1492. return true;
  1493. }
  1494. // DF <number> _ # _FloatN
  1495. // DF <number> x # _FloatNx
  1496. // DF16b # std::bfloat16_t
  1497. if (ParseTwoCharToken(state, "DF")) {
  1498. if (ParseThreeCharToken(state, "16b")) {
  1499. MaybeAppend(state, "std::bfloat16_t");
  1500. return true;
  1501. }
  1502. int number = 0;
  1503. if (!ParseNumber(state, &number)) {
  1504. state->parse_state = copy;
  1505. return false;
  1506. }
  1507. MaybeAppend(state, "_Float");
  1508. MaybeAppendDecimal(state, number);
  1509. if (ParseOneCharToken(state, 'x')) {
  1510. MaybeAppend(state, "x");
  1511. return true;
  1512. }
  1513. if (ParseOneCharToken(state, '_')) return true;
  1514. state->parse_state = copy;
  1515. return false;
  1516. }
  1517. for (const AbbrevPair *p = kBuiltinTypeList; p->abbrev != nullptr; ++p) {
  1518. // Guaranteed only 1- or 2-character strings in kBuiltinTypeList.
  1519. if (p->abbrev[1] == '\0') {
  1520. if (ParseOneCharToken(state, p->abbrev[0])) {
  1521. MaybeAppend(state, p->real_name);
  1522. return true; // ::= v, etc. # single-character builtin types
  1523. }
  1524. } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) {
  1525. MaybeAppend(state, p->real_name);
  1526. return true; // ::= Dd, etc. # two-character builtin types
  1527. }
  1528. }
  1529. return ParseVendorExtendedType(state);
  1530. }
  1531. // <vendor-extended-type> ::= u <source-name> [<template-args>]
  1532. static bool ParseVendorExtendedType(State *state) {
  1533. ComplexityGuard guard(state);
  1534. if (guard.IsTooComplex()) return false;
  1535. ParseState copy = state->parse_state;
  1536. if (ParseOneCharToken(state, 'u') && ParseSourceName(state) &&
  1537. Optional(ParseTemplateArgs(state))) {
  1538. return true;
  1539. }
  1540. state->parse_state = copy;
  1541. return false;
  1542. }
  1543. // <exception-spec> ::= Do # non-throwing
  1544. // exception-specification (e.g.,
  1545. // noexcept, throw())
  1546. // ::= DO <expression> E # computed (instantiation-dependent)
  1547. // noexcept
  1548. // ::= Dw <type>+ E # dynamic exception specification
  1549. // with instantiation-dependent types
  1550. static bool ParseExceptionSpec(State *state) {
  1551. ComplexityGuard guard(state);
  1552. if (guard.IsTooComplex()) return false;
  1553. if (ParseTwoCharToken(state, "Do")) return true;
  1554. ParseState copy = state->parse_state;
  1555. if (ParseTwoCharToken(state, "DO") && ParseExpression(state) &&
  1556. ParseOneCharToken(state, 'E')) {
  1557. return true;
  1558. }
  1559. state->parse_state = copy;
  1560. if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) &&
  1561. ParseOneCharToken(state, 'E')) {
  1562. return true;
  1563. }
  1564. state->parse_state = copy;
  1565. return false;
  1566. }
  1567. // <function-type> ::=
  1568. // [exception-spec] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
  1569. //
  1570. // <ref-qualifier> ::= R | O
  1571. static bool ParseFunctionType(State *state) {
  1572. ComplexityGuard guard(state);
  1573. if (guard.IsTooComplex()) return false;
  1574. ParseState copy = state->parse_state;
  1575. Optional(ParseExceptionSpec(state));
  1576. Optional(ParseTwoCharToken(state, "Dx"));
  1577. if (!ParseOneCharToken(state, 'F')) {
  1578. state->parse_state = copy;
  1579. return false;
  1580. }
  1581. Optional(ParseOneCharToken(state, 'Y'));
  1582. if (!ParseBareFunctionType(state)) {
  1583. state->parse_state = copy;
  1584. return false;
  1585. }
  1586. Optional(ParseCharClass(state, "RO"));
  1587. if (!ParseOneCharToken(state, 'E')) {
  1588. state->parse_state = copy;
  1589. return false;
  1590. }
  1591. return true;
  1592. }
  1593. // <bare-function-type> ::= <overload-attribute>* <(signature) type>+
  1594. //
  1595. // The <overload-attribute>* prefix is nonstandard; see the comment on
  1596. // ParseOverloadAttribute.
  1597. static bool ParseBareFunctionType(State *state) {
  1598. ComplexityGuard guard(state);
  1599. if (guard.IsTooComplex()) return false;
  1600. ParseState copy = state->parse_state;
  1601. DisableAppend(state);
  1602. if (ZeroOrMore(ParseOverloadAttribute, state) &&
  1603. OneOrMore(ParseType, state)) {
  1604. RestoreAppend(state, copy.append);
  1605. MaybeAppend(state, "()");
  1606. return true;
  1607. }
  1608. state->parse_state = copy;
  1609. return false;
  1610. }
  1611. // <overload-attribute> ::= Ua <name>
  1612. //
  1613. // The nonstandard <overload-attribute> production is sufficient to accept the
  1614. // current implementation of __attribute__((enable_if(condition, "message")))
  1615. // and future attributes of a similar shape. See
  1616. // https://clang.llvm.org/docs/AttributeReference.html#enable-if and the
  1617. // definition of CXXNameMangler::mangleFunctionEncodingBareType in Clang's
  1618. // source code.
  1619. static bool ParseOverloadAttribute(State *state) {
  1620. ComplexityGuard guard(state);
  1621. if (guard.IsTooComplex()) return false;
  1622. ParseState copy = state->parse_state;
  1623. if (ParseTwoCharToken(state, "Ua") && ParseName(state)) {
  1624. return true;
  1625. }
  1626. state->parse_state = copy;
  1627. return false;
  1628. }
  1629. // <class-enum-type> ::= <name>
  1630. // ::= Ts <name> # struct Name or class Name
  1631. // ::= Tu <name> # union Name
  1632. // ::= Te <name> # enum Name
  1633. //
  1634. // See http://shortn/_W3YrltiEd0.
  1635. static bool ParseClassEnumType(State *state) {
  1636. ComplexityGuard guard(state);
  1637. if (guard.IsTooComplex()) return false;
  1638. ParseState copy = state->parse_state;
  1639. if (Optional(ParseTwoCharToken(state, "Ts") ||
  1640. ParseTwoCharToken(state, "Tu") ||
  1641. ParseTwoCharToken(state, "Te")) &&
  1642. ParseName(state)) {
  1643. return true;
  1644. }
  1645. state->parse_state = copy;
  1646. return false;
  1647. }
  1648. // <array-type> ::= A <(positive dimension) number> _ <(element) type>
  1649. // ::= A [<(dimension) expression>] _ <(element) type>
  1650. static bool ParseArrayType(State *state) {
  1651. ComplexityGuard guard(state);
  1652. if (guard.IsTooComplex()) return false;
  1653. ParseState copy = state->parse_state;
  1654. if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) &&
  1655. ParseOneCharToken(state, '_') && ParseType(state)) {
  1656. return true;
  1657. }
  1658. state->parse_state = copy;
  1659. if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
  1660. ParseOneCharToken(state, '_') && ParseType(state)) {
  1661. return true;
  1662. }
  1663. state->parse_state = copy;
  1664. return false;
  1665. }
  1666. // <pointer-to-member-type> ::= M <(class) type> <(member) type>
  1667. static bool ParsePointerToMemberType(State *state) {
  1668. ComplexityGuard guard(state);
  1669. if (guard.IsTooComplex()) return false;
  1670. ParseState copy = state->parse_state;
  1671. if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) {
  1672. return true;
  1673. }
  1674. state->parse_state = copy;
  1675. return false;
  1676. }
  1677. // <template-param> ::= T_
  1678. // ::= T <parameter-2 non-negative number> _
  1679. // ::= TL <level-1> __
  1680. // ::= TL <level-1> _ <parameter-2 non-negative number> _
  1681. static bool ParseTemplateParam(State *state) {
  1682. ComplexityGuard guard(state);
  1683. if (guard.IsTooComplex()) return false;
  1684. if (ParseTwoCharToken(state, "T_")) {
  1685. MaybeAppend(state, "?"); // We don't support template substitutions.
  1686. return true; // ::= T_
  1687. }
  1688. ParseState copy = state->parse_state;
  1689. if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) &&
  1690. ParseOneCharToken(state, '_')) {
  1691. MaybeAppend(state, "?"); // We don't support template substitutions.
  1692. return true; // ::= T <parameter-2 non-negative number> _
  1693. }
  1694. state->parse_state = copy;
  1695. if (ParseTwoCharToken(state, "TL") && ParseNumber(state, nullptr)) {
  1696. if (ParseTwoCharToken(state, "__")) {
  1697. MaybeAppend(state, "?"); // We don't support template substitutions.
  1698. return true; // ::= TL <level-1> __
  1699. }
  1700. if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) &&
  1701. ParseOneCharToken(state, '_')) {
  1702. MaybeAppend(state, "?"); // We don't support template substitutions.
  1703. return true; // ::= TL <level-1> _ <parameter-2 non-negative number> _
  1704. }
  1705. }
  1706. state->parse_state = copy;
  1707. return false;
  1708. }
  1709. // <template-param-decl>
  1710. // ::= Ty # template type parameter
  1711. // ::= Tk <concept name> [<template-args>] # constrained type parameter
  1712. // ::= Tn <type> # template non-type parameter
  1713. // ::= Tt <template-param-decl>* E # template template parameter
  1714. // ::= Tp <template-param-decl> # template parameter pack
  1715. //
  1716. // NOTE: <concept name> is just a <name>: http://shortn/_MqJVyr0fc1
  1717. // TODO(b/324066279): Implement optional suffix for `Tt`:
  1718. // [Q <requires-clause expr>]
  1719. static bool ParseTemplateParamDecl(State *state) {
  1720. ComplexityGuard guard(state);
  1721. if (guard.IsTooComplex()) return false;
  1722. ParseState copy = state->parse_state;
  1723. if (ParseTwoCharToken(state, "Ty")) {
  1724. return true;
  1725. }
  1726. state->parse_state = copy;
  1727. if (ParseTwoCharToken(state, "Tk") && ParseName(state) &&
  1728. Optional(ParseTemplateArgs(state))) {
  1729. return true;
  1730. }
  1731. state->parse_state = copy;
  1732. if (ParseTwoCharToken(state, "Tn") && ParseType(state)) {
  1733. return true;
  1734. }
  1735. state->parse_state = copy;
  1736. if (ParseTwoCharToken(state, "Tt") &&
  1737. ZeroOrMore(ParseTemplateParamDecl, state) &&
  1738. ParseOneCharToken(state, 'E')) {
  1739. return true;
  1740. }
  1741. state->parse_state = copy;
  1742. if (ParseTwoCharToken(state, "Tp") && ParseTemplateParamDecl(state)) {
  1743. return true;
  1744. }
  1745. state->parse_state = copy;
  1746. return false;
  1747. }
  1748. // <template-template-param> ::= <template-param>
  1749. // ::= <substitution>
  1750. static bool ParseTemplateTemplateParam(State *state) {
  1751. ComplexityGuard guard(state);
  1752. if (guard.IsTooComplex()) return false;
  1753. return (ParseTemplateParam(state) ||
  1754. // "std" on its own isn't a template.
  1755. ParseSubstitution(state, /*accept_std=*/false));
  1756. }
  1757. // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
  1758. static bool ParseTemplateArgs(State *state) {
  1759. ComplexityGuard guard(state);
  1760. if (guard.IsTooComplex()) return false;
  1761. ParseState copy = state->parse_state;
  1762. DisableAppend(state);
  1763. if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) &&
  1764. Optional(ParseQRequiresClauseExpr(state)) &&
  1765. ParseOneCharToken(state, 'E')) {
  1766. RestoreAppend(state, copy.append);
  1767. MaybeAppend(state, "<>");
  1768. return true;
  1769. }
  1770. state->parse_state = copy;
  1771. return false;
  1772. }
  1773. // <template-arg> ::= <template-param-decl> <template-arg>
  1774. // ::= <type>
  1775. // ::= <expr-primary>
  1776. // ::= J <template-arg>* E # argument pack
  1777. // ::= X <expression> E
  1778. static bool ParseTemplateArg(State *state) {
  1779. ComplexityGuard guard(state);
  1780. if (guard.IsTooComplex()) return false;
  1781. ParseState copy = state->parse_state;
  1782. if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) &&
  1783. ParseOneCharToken(state, 'E')) {
  1784. return true;
  1785. }
  1786. state->parse_state = copy;
  1787. // There can be significant overlap between the following leading to
  1788. // exponential backtracking:
  1789. //
  1790. // <expr-primary> ::= L <type> <expr-cast-value> E
  1791. // e.g. L 2xxIvE 1 E
  1792. // <type> ==> <local-source-name> <template-args>
  1793. // e.g. L 2xx IvE
  1794. //
  1795. // This means parsing an entire <type> twice, and <type> can contain
  1796. // <template-arg>, so this can generate exponential backtracking. There is
  1797. // only overlap when the remaining input starts with "L <source-name>", so
  1798. // parse all cases that can start this way jointly to share the common prefix.
  1799. //
  1800. // We have:
  1801. //
  1802. // <template-arg> ::= <type>
  1803. // ::= <expr-primary>
  1804. //
  1805. // First, drop all the productions of <type> that must start with something
  1806. // other than 'L'. All that's left is <class-enum-type>; inline it.
  1807. //
  1808. // <type> ::= <nested-name> # starts with 'N'
  1809. // ::= <unscoped-name>
  1810. // ::= <unscoped-template-name> <template-args>
  1811. // ::= <local-name> # starts with 'Z'
  1812. //
  1813. // Drop and inline again:
  1814. //
  1815. // <type> ::= <unscoped-name>
  1816. // ::= <unscoped-name> <template-args>
  1817. // ::= <substitution> <template-args> # starts with 'S'
  1818. //
  1819. // Merge the first two, inline <unscoped-name>, drop last:
  1820. //
  1821. // <type> ::= <unqualified-name> [<template-args>]
  1822. // ::= St <unqualified-name> [<template-args>] # starts with 'S'
  1823. //
  1824. // Drop and inline:
  1825. //
  1826. // <type> ::= <operator-name> [<template-args>] # starts with lowercase
  1827. // ::= <ctor-dtor-name> [<template-args>] # starts with 'C' or 'D'
  1828. // ::= <source-name> [<template-args>] # starts with digit
  1829. // ::= <local-source-name> [<template-args>]
  1830. // ::= <unnamed-type-name> [<template-args>] # starts with 'U'
  1831. //
  1832. // One more time:
  1833. //
  1834. // <type> ::= L <source-name> [<template-args>]
  1835. //
  1836. // Likewise with <expr-primary>:
  1837. //
  1838. // <expr-primary> ::= L <type> <expr-cast-value> E
  1839. // ::= LZ <encoding> E # cannot overlap; drop
  1840. // ::= L <mangled_name> E # cannot overlap; drop
  1841. //
  1842. // By similar reasoning as shown above, the only <type>s starting with
  1843. // <source-name> are "<source-name> [<template-args>]". Inline this.
  1844. //
  1845. // <expr-primary> ::= L <source-name> [<template-args>] <expr-cast-value> E
  1846. //
  1847. // Now inline both of these into <template-arg>:
  1848. //
  1849. // <template-arg> ::= L <source-name> [<template-args>]
  1850. // ::= L <source-name> [<template-args>] <expr-cast-value> E
  1851. //
  1852. // Merge them and we're done:
  1853. // <template-arg>
  1854. // ::= L <source-name> [<template-args>] [<expr-cast-value> E]
  1855. if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) {
  1856. copy = state->parse_state;
  1857. if (ParseExprCastValueAndTrailingE(state)) {
  1858. return true;
  1859. }
  1860. state->parse_state = copy;
  1861. return true;
  1862. }
  1863. // Now that the overlapping cases can't reach this code, we can safely call
  1864. // both of these.
  1865. if (ParseType(state) || ParseExprPrimary(state)) {
  1866. return true;
  1867. }
  1868. state->parse_state = copy;
  1869. if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
  1870. ParseOneCharToken(state, 'E')) {
  1871. return true;
  1872. }
  1873. state->parse_state = copy;
  1874. if (ParseTemplateParamDecl(state) && ParseTemplateArg(state)) {
  1875. return true;
  1876. }
  1877. state->parse_state = copy;
  1878. return false;
  1879. }
  1880. // <unresolved-type> ::= <template-param> [<template-args>]
  1881. // ::= <decltype>
  1882. // ::= <substitution>
  1883. static inline bool ParseUnresolvedType(State *state) {
  1884. // No ComplexityGuard because we don't copy the state in this stack frame.
  1885. return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) ||
  1886. ParseDecltype(state) || ParseSubstitution(state, /*accept_std=*/false);
  1887. }
  1888. // <simple-id> ::= <source-name> [<template-args>]
  1889. static inline bool ParseSimpleId(State *state) {
  1890. // No ComplexityGuard because we don't copy the state in this stack frame.
  1891. // Note: <simple-id> cannot be followed by a parameter pack; see comment in
  1892. // ParseUnresolvedType.
  1893. return ParseSourceName(state) && Optional(ParseTemplateArgs(state));
  1894. }
  1895. // <base-unresolved-name> ::= <source-name> [<template-args>]
  1896. // ::= on <operator-name> [<template-args>]
  1897. // ::= dn <destructor-name>
  1898. static bool ParseBaseUnresolvedName(State *state) {
  1899. ComplexityGuard guard(state);
  1900. if (guard.IsTooComplex()) return false;
  1901. if (ParseSimpleId(state)) {
  1902. return true;
  1903. }
  1904. ParseState copy = state->parse_state;
  1905. if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) &&
  1906. Optional(ParseTemplateArgs(state))) {
  1907. return true;
  1908. }
  1909. state->parse_state = copy;
  1910. if (ParseTwoCharToken(state, "dn") &&
  1911. (ParseUnresolvedType(state) || ParseSimpleId(state))) {
  1912. return true;
  1913. }
  1914. state->parse_state = copy;
  1915. return false;
  1916. }
  1917. // <unresolved-name> ::= [gs] <base-unresolved-name>
  1918. // ::= sr <unresolved-type> <base-unresolved-name>
  1919. // ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
  1920. // <base-unresolved-name>
  1921. // ::= [gs] sr <unresolved-qualifier-level>+ E
  1922. // <base-unresolved-name>
  1923. // ::= sr St <simple-id> <simple-id> # nonstandard
  1924. //
  1925. // The last case is not part of the official grammar but has been observed in
  1926. // real-world examples that the GNU demangler (but not the LLVM demangler) is
  1927. // able to decode; see demangle_test.cc for one such symbol name. The shape
  1928. // sr St <simple-id> <simple-id> was inferred by closed-box testing of the GNU
  1929. // demangler.
  1930. static bool ParseUnresolvedName(State *state) {
  1931. ComplexityGuard guard(state);
  1932. if (guard.IsTooComplex()) return false;
  1933. ParseState copy = state->parse_state;
  1934. if (Optional(ParseTwoCharToken(state, "gs")) &&
  1935. ParseBaseUnresolvedName(state)) {
  1936. return true;
  1937. }
  1938. state->parse_state = copy;
  1939. if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) &&
  1940. ParseBaseUnresolvedName(state)) {
  1941. return true;
  1942. }
  1943. state->parse_state = copy;
  1944. if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') &&
  1945. ParseUnresolvedType(state) &&
  1946. OneOrMore(ParseUnresolvedQualifierLevel, state) &&
  1947. ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
  1948. return true;
  1949. }
  1950. state->parse_state = copy;
  1951. if (Optional(ParseTwoCharToken(state, "gs")) &&
  1952. ParseTwoCharToken(state, "sr") &&
  1953. OneOrMore(ParseUnresolvedQualifierLevel, state) &&
  1954. ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
  1955. return true;
  1956. }
  1957. state->parse_state = copy;
  1958. if (ParseTwoCharToken(state, "sr") && ParseTwoCharToken(state, "St") &&
  1959. ParseSimpleId(state) && ParseSimpleId(state)) {
  1960. return true;
  1961. }
  1962. state->parse_state = copy;
  1963. return false;
  1964. }
  1965. // <unresolved-qualifier-level> ::= <simple-id>
  1966. // ::= <substitution> <template-args>
  1967. //
  1968. // The production <substitution> <template-args> is nonstandard but is observed
  1969. // in practice. An upstream discussion on the best shape of <unresolved-name>
  1970. // has not converged:
  1971. //
  1972. // https://github.com/itanium-cxx-abi/cxx-abi/issues/38
  1973. static bool ParseUnresolvedQualifierLevel(State *state) {
  1974. ComplexityGuard guard(state);
  1975. if (guard.IsTooComplex()) return false;
  1976. if (ParseSimpleId(state)) return true;
  1977. ParseState copy = state->parse_state;
  1978. if (ParseSubstitution(state, /*accept_std=*/false) &&
  1979. ParseTemplateArgs(state)) {
  1980. return true;
  1981. }
  1982. state->parse_state = copy;
  1983. return false;
  1984. }
  1985. // <union-selector> ::= _ [<number>]
  1986. //
  1987. // https://github.com/itanium-cxx-abi/cxx-abi/issues/47
  1988. static bool ParseUnionSelector(State *state) {
  1989. return ParseOneCharToken(state, '_') && Optional(ParseNumber(state, nullptr));
  1990. }
  1991. // <function-param> ::= fp <(top-level) CV-qualifiers> _
  1992. // ::= fp <(top-level) CV-qualifiers> <number> _
  1993. // ::= fL <number> p <(top-level) CV-qualifiers> _
  1994. // ::= fL <number> p <(top-level) CV-qualifiers> <number> _
  1995. // ::= fpT # this
  1996. static bool ParseFunctionParam(State *state) {
  1997. ComplexityGuard guard(state);
  1998. if (guard.IsTooComplex()) return false;
  1999. ParseState copy = state->parse_state;
  2000. // Function-param expression (level 0).
  2001. if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) &&
  2002. Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
  2003. return true;
  2004. }
  2005. state->parse_state = copy;
  2006. // Function-param expression (level 1+).
  2007. if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) &&
  2008. ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) &&
  2009. Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
  2010. return true;
  2011. }
  2012. state->parse_state = copy;
  2013. return ParseThreeCharToken(state, "fpT");
  2014. }
  2015. // <braced-expression> ::= <expression>
  2016. // ::= di <field source-name> <braced-expression>
  2017. // ::= dx <index expression> <braced-expression>
  2018. // ::= dX <expression> <expression> <braced-expression>
  2019. static bool ParseBracedExpression(State *state) {
  2020. ComplexityGuard guard(state);
  2021. if (guard.IsTooComplex()) return false;
  2022. ParseState copy = state->parse_state;
  2023. if (ParseTwoCharToken(state, "di") && ParseSourceName(state) &&
  2024. ParseBracedExpression(state)) {
  2025. return true;
  2026. }
  2027. state->parse_state = copy;
  2028. if (ParseTwoCharToken(state, "dx") && ParseExpression(state) &&
  2029. ParseBracedExpression(state)) {
  2030. return true;
  2031. }
  2032. state->parse_state = copy;
  2033. if (ParseTwoCharToken(state, "dX") &&
  2034. ParseExpression(state) && ParseExpression(state) &&
  2035. ParseBracedExpression(state)) {
  2036. return true;
  2037. }
  2038. state->parse_state = copy;
  2039. return ParseExpression(state);
  2040. }
  2041. // <expression> ::= <1-ary operator-name> <expression>
  2042. // ::= <2-ary operator-name> <expression> <expression>
  2043. // ::= <3-ary operator-name> <expression> <expression> <expression>
  2044. // ::= pp_ <expression> # ++e; pp <expression> is e++
  2045. // ::= mm_ <expression> # --e; mm <expression> is e--
  2046. // ::= cl <expression>+ E
  2047. // ::= cp <simple-id> <expression>* E # Clang-specific.
  2048. // ::= so <type> <expression> [<number>] <union-selector>* [p] E
  2049. // ::= cv <type> <expression> # type (expression)
  2050. // ::= cv <type> _ <expression>* E # type (expr-list)
  2051. // ::= tl <type> <braced-expression>* E
  2052. // ::= il <braced-expression>* E
  2053. // ::= [gs] nw <expression>* _ <type> E
  2054. // ::= [gs] nw <expression>* _ <type> <initializer>
  2055. // ::= [gs] na <expression>* _ <type> E
  2056. // ::= [gs] na <expression>* _ <type> <initializer>
  2057. // ::= [gs] dl <expression>
  2058. // ::= [gs] da <expression>
  2059. // ::= dc <type> <expression>
  2060. // ::= sc <type> <expression>
  2061. // ::= cc <type> <expression>
  2062. // ::= rc <type> <expression>
  2063. // ::= ti <type>
  2064. // ::= te <expression>
  2065. // ::= st <type>
  2066. // ::= at <type>
  2067. // ::= az <expression>
  2068. // ::= nx <expression>
  2069. // ::= <template-param>
  2070. // ::= <function-param>
  2071. // ::= sZ <template-param>
  2072. // ::= sZ <function-param>
  2073. // ::= sP <template-arg>* E
  2074. // ::= <expr-primary>
  2075. // ::= dt <expression> <unresolved-name> # expr.name
  2076. // ::= pt <expression> <unresolved-name> # expr->name
  2077. // ::= sp <expression> # argument pack expansion
  2078. // ::= fl <binary operator-name> <expression>
  2079. // ::= fr <binary operator-name> <expression>
  2080. // ::= fL <binary operator-name> <expression> <expression>
  2081. // ::= fR <binary operator-name> <expression> <expression>
  2082. // ::= tw <expression>
  2083. // ::= tr
  2084. // ::= sr <type> <unqualified-name> <template-args>
  2085. // ::= sr <type> <unqualified-name>
  2086. // ::= u <source-name> <template-arg>* E # vendor extension
  2087. // ::= rq <requirement>+ E
  2088. // ::= rQ <bare-function-type> _ <requirement>+ E
  2089. static bool ParseExpression(State *state) {
  2090. ComplexityGuard guard(state);
  2091. if (guard.IsTooComplex()) return false;
  2092. if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
  2093. return true;
  2094. }
  2095. ParseState copy = state->parse_state;
  2096. // Object/function call expression.
  2097. if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) &&
  2098. ParseOneCharToken(state, 'E')) {
  2099. return true;
  2100. }
  2101. state->parse_state = copy;
  2102. // Preincrement and predecrement. Postincrement and postdecrement are handled
  2103. // by the operator-name logic later on.
  2104. if ((ParseThreeCharToken(state, "pp_") ||
  2105. ParseThreeCharToken(state, "mm_")) &&
  2106. ParseExpression(state)) {
  2107. return true;
  2108. }
  2109. state->parse_state = copy;
  2110. // Clang-specific "cp <simple-id> <expression>* E"
  2111. // https://clang.llvm.org/doxygen/ItaniumMangle_8cpp_source.html#l04338
  2112. if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) &&
  2113. ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) {
  2114. return true;
  2115. }
  2116. state->parse_state = copy;
  2117. // <expression> ::= so <type> <expression> [<number>] <union-selector>* [p] E
  2118. //
  2119. // https://github.com/itanium-cxx-abi/cxx-abi/issues/47
  2120. if (ParseTwoCharToken(state, "so") && ParseType(state) &&
  2121. ParseExpression(state) && Optional(ParseNumber(state, nullptr)) &&
  2122. ZeroOrMore(ParseUnionSelector, state) &&
  2123. Optional(ParseOneCharToken(state, 'p')) &&
  2124. ParseOneCharToken(state, 'E')) {
  2125. return true;
  2126. }
  2127. state->parse_state = copy;
  2128. // <expression> ::= <function-param>
  2129. if (ParseFunctionParam(state)) return true;
  2130. state->parse_state = copy;
  2131. // <expression> ::= tl <type> <braced-expression>* E
  2132. if (ParseTwoCharToken(state, "tl") && ParseType(state) &&
  2133. ZeroOrMore(ParseBracedExpression, state) &&
  2134. ParseOneCharToken(state, 'E')) {
  2135. return true;
  2136. }
  2137. state->parse_state = copy;
  2138. // <expression> ::= il <braced-expression>* E
  2139. if (ParseTwoCharToken(state, "il") &&
  2140. ZeroOrMore(ParseBracedExpression, state) &&
  2141. ParseOneCharToken(state, 'E')) {
  2142. return true;
  2143. }
  2144. state->parse_state = copy;
  2145. // <expression> ::= [gs] nw <expression>* _ <type> E
  2146. // ::= [gs] nw <expression>* _ <type> <initializer>
  2147. // ::= [gs] na <expression>* _ <type> E
  2148. // ::= [gs] na <expression>* _ <type> <initializer>
  2149. if (Optional(ParseTwoCharToken(state, "gs")) &&
  2150. (ParseTwoCharToken(state, "nw") || ParseTwoCharToken(state, "na")) &&
  2151. ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, '_') &&
  2152. ParseType(state) &&
  2153. (ParseOneCharToken(state, 'E') || ParseInitializer(state))) {
  2154. return true;
  2155. }
  2156. state->parse_state = copy;
  2157. // <expression> ::= [gs] dl <expression>
  2158. // ::= [gs] da <expression>
  2159. if (Optional(ParseTwoCharToken(state, "gs")) &&
  2160. (ParseTwoCharToken(state, "dl") || ParseTwoCharToken(state, "da")) &&
  2161. ParseExpression(state)) {
  2162. return true;
  2163. }
  2164. state->parse_state = copy;
  2165. // dynamic_cast, static_cast, const_cast, reinterpret_cast.
  2166. //
  2167. // <expression> ::= (dc | sc | cc | rc) <type> <expression>
  2168. if (ParseCharClass(state, "dscr") && ParseOneCharToken(state, 'c') &&
  2169. ParseType(state) && ParseExpression(state)) {
  2170. return true;
  2171. }
  2172. state->parse_state = copy;
  2173. // Parse the conversion expressions jointly to avoid re-parsing the <type> in
  2174. // their common prefix. Parsed as:
  2175. // <expression> ::= cv <type> <conversion-args>
  2176. // <conversion-args> ::= _ <expression>* E
  2177. // ::= <expression>
  2178. //
  2179. // Also don't try ParseOperatorName after seeing "cv", since ParseOperatorName
  2180. // also needs to accept "cv <type>" in other contexts.
  2181. if (ParseTwoCharToken(state, "cv")) {
  2182. if (ParseType(state)) {
  2183. ParseState copy2 = state->parse_state;
  2184. if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) &&
  2185. ParseOneCharToken(state, 'E')) {
  2186. return true;
  2187. }
  2188. state->parse_state = copy2;
  2189. if (ParseExpression(state)) {
  2190. return true;
  2191. }
  2192. }
  2193. } else {
  2194. // Parse unary, binary, and ternary operator expressions jointly, taking
  2195. // care not to re-parse subexpressions repeatedly. Parse like:
  2196. // <expression> ::= <operator-name> <expression>
  2197. // [<one-to-two-expressions>]
  2198. // <one-to-two-expressions> ::= <expression> [<expression>]
  2199. int arity = -1;
  2200. if (ParseOperatorName(state, &arity) &&
  2201. arity > 0 && // 0 arity => disabled.
  2202. (arity < 3 || ParseExpression(state)) &&
  2203. (arity < 2 || ParseExpression(state)) &&
  2204. (arity < 1 || ParseExpression(state))) {
  2205. return true;
  2206. }
  2207. }
  2208. state->parse_state = copy;
  2209. // typeid(type)
  2210. if (ParseTwoCharToken(state, "ti") && ParseType(state)) {
  2211. return true;
  2212. }
  2213. state->parse_state = copy;
  2214. // typeid(expression)
  2215. if (ParseTwoCharToken(state, "te") && ParseExpression(state)) {
  2216. return true;
  2217. }
  2218. state->parse_state = copy;
  2219. // sizeof type
  2220. if (ParseTwoCharToken(state, "st") && ParseType(state)) {
  2221. return true;
  2222. }
  2223. state->parse_state = copy;
  2224. // alignof(type)
  2225. if (ParseTwoCharToken(state, "at") && ParseType(state)) {
  2226. return true;
  2227. }
  2228. state->parse_state = copy;
  2229. // alignof(expression), a GNU extension
  2230. if (ParseTwoCharToken(state, "az") && ParseExpression(state)) {
  2231. return true;
  2232. }
  2233. state->parse_state = copy;
  2234. // noexcept(expression) appearing as an expression in a dependent signature
  2235. if (ParseTwoCharToken(state, "nx") && ParseExpression(state)) {
  2236. return true;
  2237. }
  2238. state->parse_state = copy;
  2239. // sizeof...(pack)
  2240. //
  2241. // <expression> ::= sZ <template-param>
  2242. // ::= sZ <function-param>
  2243. if (ParseTwoCharToken(state, "sZ") &&
  2244. (ParseFunctionParam(state) || ParseTemplateParam(state))) {
  2245. return true;
  2246. }
  2247. state->parse_state = copy;
  2248. // sizeof...(pack) captured from an alias template
  2249. //
  2250. // <expression> ::= sP <template-arg>* E
  2251. if (ParseTwoCharToken(state, "sP") && ZeroOrMore(ParseTemplateArg, state) &&
  2252. ParseOneCharToken(state, 'E')) {
  2253. return true;
  2254. }
  2255. state->parse_state = copy;
  2256. // Unary folds (... op pack) and (pack op ...).
  2257. //
  2258. // <expression> ::= fl <binary operator-name> <expression>
  2259. // ::= fr <binary operator-name> <expression>
  2260. if ((ParseTwoCharToken(state, "fl") || ParseTwoCharToken(state, "fr")) &&
  2261. ParseOperatorName(state, nullptr) && ParseExpression(state)) {
  2262. return true;
  2263. }
  2264. state->parse_state = copy;
  2265. // Binary folds (init op ... op pack) and (pack op ... op init).
  2266. //
  2267. // <expression> ::= fL <binary operator-name> <expression> <expression>
  2268. // ::= fR <binary operator-name> <expression> <expression>
  2269. if ((ParseTwoCharToken(state, "fL") || ParseTwoCharToken(state, "fR")) &&
  2270. ParseOperatorName(state, nullptr) && ParseExpression(state) &&
  2271. ParseExpression(state)) {
  2272. return true;
  2273. }
  2274. state->parse_state = copy;
  2275. // tw <expression>: throw e
  2276. if (ParseTwoCharToken(state, "tw") && ParseExpression(state)) {
  2277. return true;
  2278. }
  2279. state->parse_state = copy;
  2280. // tr: throw (rethrows an exception from the handler that caught it)
  2281. if (ParseTwoCharToken(state, "tr")) return true;
  2282. // Object and pointer member access expressions.
  2283. //
  2284. // <expression> ::= (dt | pt) <expression> <unresolved-name>
  2285. if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) &&
  2286. ParseExpression(state) && ParseUnresolvedName(state)) {
  2287. return true;
  2288. }
  2289. state->parse_state = copy;
  2290. // Pointer-to-member access expressions. This parses the same as a binary
  2291. // operator, but it's implemented separately because "ds" shouldn't be
  2292. // accepted in other contexts that parse an operator name.
  2293. if (ParseTwoCharToken(state, "ds") && ParseExpression(state) &&
  2294. ParseExpression(state)) {
  2295. return true;
  2296. }
  2297. state->parse_state = copy;
  2298. // Parameter pack expansion
  2299. if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) {
  2300. return true;
  2301. }
  2302. state->parse_state = copy;
  2303. // Vendor extended expressions
  2304. if (ParseOneCharToken(state, 'u') && ParseSourceName(state) &&
  2305. ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) {
  2306. return true;
  2307. }
  2308. state->parse_state = copy;
  2309. // <expression> ::= rq <requirement>+ E
  2310. //
  2311. // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
  2312. if (ParseTwoCharToken(state, "rq") && OneOrMore(ParseRequirement, state) &&
  2313. ParseOneCharToken(state, 'E')) {
  2314. return true;
  2315. }
  2316. state->parse_state = copy;
  2317. // <expression> ::= rQ <bare-function-type> _ <requirement>+ E
  2318. //
  2319. // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
  2320. if (ParseTwoCharToken(state, "rQ") && ParseBareFunctionType(state) &&
  2321. ParseOneCharToken(state, '_') && OneOrMore(ParseRequirement, state) &&
  2322. ParseOneCharToken(state, 'E')) {
  2323. return true;
  2324. }
  2325. state->parse_state = copy;
  2326. return ParseUnresolvedName(state);
  2327. }
  2328. // <initializer> ::= pi <expression>* E
  2329. // ::= il <braced-expression>* E
  2330. //
  2331. // The il ... E form is not in the ABI spec but is seen in practice for
  2332. // braced-init-lists in new-expressions, which are standard syntax from C++11
  2333. // on.
  2334. static bool ParseInitializer(State *state) {
  2335. ComplexityGuard guard(state);
  2336. if (guard.IsTooComplex()) return false;
  2337. ParseState copy = state->parse_state;
  2338. if (ParseTwoCharToken(state, "pi") && ZeroOrMore(ParseExpression, state) &&
  2339. ParseOneCharToken(state, 'E')) {
  2340. return true;
  2341. }
  2342. state->parse_state = copy;
  2343. if (ParseTwoCharToken(state, "il") &&
  2344. ZeroOrMore(ParseBracedExpression, state) &&
  2345. ParseOneCharToken(state, 'E')) {
  2346. return true;
  2347. }
  2348. state->parse_state = copy;
  2349. return false;
  2350. }
  2351. // <expr-primary> ::= L <type> <(value) number> E
  2352. // ::= L <type> <(value) float> E
  2353. // ::= L <mangled-name> E
  2354. // // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
  2355. // ::= LZ <encoding> E
  2356. //
  2357. // Warning, subtle: the "bug" LZ production above is ambiguous with the first
  2358. // production where <type> starts with <local-name>, which can lead to
  2359. // exponential backtracking in two scenarios:
  2360. //
  2361. // - When whatever follows the E in the <local-name> in the first production is
  2362. // not a name, we backtrack the whole <encoding> and re-parse the whole thing.
  2363. //
  2364. // - When whatever follows the <local-name> in the first production is not a
  2365. // number and this <expr-primary> may be followed by a name, we backtrack the
  2366. // <name> and re-parse it.
  2367. //
  2368. // Moreover this ambiguity isn't always resolved -- for example, the following
  2369. // has two different parses:
  2370. //
  2371. // _ZaaILZ4aoeuE1x1EvE
  2372. // => operator&&<aoeu, x, E, void>
  2373. // => operator&&<(aoeu::x)(1), void>
  2374. //
  2375. // To resolve this, we just do what GCC's demangler does, and refuse to parse
  2376. // casts to <local-name> types.
  2377. static bool ParseExprPrimary(State *state) {
  2378. ComplexityGuard guard(state);
  2379. if (guard.IsTooComplex()) return false;
  2380. ParseState copy = state->parse_state;
  2381. // The "LZ" special case: if we see LZ, we commit to accept "LZ <encoding> E"
  2382. // or fail, no backtracking.
  2383. if (ParseTwoCharToken(state, "LZ")) {
  2384. if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) {
  2385. return true;
  2386. }
  2387. state->parse_state = copy;
  2388. return false;
  2389. }
  2390. if (ParseOneCharToken(state, 'L')) {
  2391. // There are two special cases in which a literal may or must contain a type
  2392. // without a value. The first is that both LDnE and LDn0E are valid
  2393. // encodings of nullptr, used in different situations. Recognize LDnE here,
  2394. // leaving LDn0E to be recognized by the general logic afterward.
  2395. if (ParseThreeCharToken(state, "DnE")) return true;
  2396. // The second special case is a string literal, currently mangled in C++98
  2397. // style as LA<length + 1>_KcE. This is inadequate to support C++11 and
  2398. // later versions, and the discussion of this problem has not converged.
  2399. //
  2400. // https://github.com/itanium-cxx-abi/cxx-abi/issues/64
  2401. //
  2402. // For now the bare-type mangling is what's used in practice, so we
  2403. // recognize this form and only this form if an array type appears here.
  2404. // Someday we'll probably have to accept a new form of value mangling in
  2405. // LA...E constructs. (Note also that C++20 allows a wide range of
  2406. // class-type objects as template arguments, so someday their values will be
  2407. // mangled and we'll have to recognize them here too.)
  2408. if (RemainingInput(state)[0] == 'A' /* an array type follows */) {
  2409. if (ParseType(state) && ParseOneCharToken(state, 'E')) return true;
  2410. state->parse_state = copy;
  2411. return false;
  2412. }
  2413. // The merged cast production.
  2414. if (ParseType(state) && ParseExprCastValueAndTrailingE(state)) {
  2415. return true;
  2416. }
  2417. }
  2418. state->parse_state = copy;
  2419. if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
  2420. ParseOneCharToken(state, 'E')) {
  2421. return true;
  2422. }
  2423. state->parse_state = copy;
  2424. return false;
  2425. }
  2426. // <number> or <float>, followed by 'E', as described above ParseExprPrimary.
  2427. static bool ParseExprCastValueAndTrailingE(State *state) {
  2428. ComplexityGuard guard(state);
  2429. if (guard.IsTooComplex()) return false;
  2430. // We have to be able to backtrack after accepting a number because we could
  2431. // have e.g. "7fffE", which will accept "7" as a number but then fail to find
  2432. // the 'E'.
  2433. ParseState copy = state->parse_state;
  2434. if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) {
  2435. return true;
  2436. }
  2437. state->parse_state = copy;
  2438. if (ParseFloatNumber(state)) {
  2439. // <float> for ordinary floating-point types
  2440. if (ParseOneCharToken(state, 'E')) return true;
  2441. // <float> _ <float> for complex floating-point types
  2442. if (ParseOneCharToken(state, '_') && ParseFloatNumber(state) &&
  2443. ParseOneCharToken(state, 'E')) {
  2444. return true;
  2445. }
  2446. }
  2447. state->parse_state = copy;
  2448. return false;
  2449. }
  2450. // Parses `Q <requires-clause expr>`.
  2451. // If parsing fails, applies backtracking to `state`.
  2452. //
  2453. // This function covers two symbols instead of one for convenience,
  2454. // because in LLVM's Itanium ABI mangling grammar, <requires-clause expr>
  2455. // always appears after Q.
  2456. //
  2457. // Does not emit the parsed `requires` clause to simplify the implementation.
  2458. // In other words, these two functions' mangled names will demangle identically:
  2459. //
  2460. // template <typename T>
  2461. // int foo(T) requires IsIntegral<T>;
  2462. //
  2463. // vs.
  2464. //
  2465. // template <typename T>
  2466. // int foo(T);
  2467. static bool ParseQRequiresClauseExpr(State *state) {
  2468. ComplexityGuard guard(state);
  2469. if (guard.IsTooComplex()) return false;
  2470. ParseState copy = state->parse_state;
  2471. DisableAppend(state);
  2472. // <requires-clause expr> is just an <expression>: http://shortn/_9E1Ul0rIM8
  2473. if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) {
  2474. RestoreAppend(state, copy.append);
  2475. return true;
  2476. }
  2477. // also restores append
  2478. state->parse_state = copy;
  2479. return false;
  2480. }
  2481. // <requirement> ::= X <expression> [N] [R <type-constraint>]
  2482. // <requirement> ::= T <type>
  2483. // <requirement> ::= Q <constraint-expression>
  2484. //
  2485. // <constraint-expression> ::= <expression>
  2486. //
  2487. // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
  2488. static bool ParseRequirement(State *state) {
  2489. ComplexityGuard guard(state);
  2490. if (guard.IsTooComplex()) return false;
  2491. ParseState copy = state->parse_state;
  2492. if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
  2493. Optional(ParseOneCharToken(state, 'N')) &&
  2494. // This logic backtracks cleanly if we eat an R but a valid type doesn't
  2495. // follow it.
  2496. (!ParseOneCharToken(state, 'R') || ParseTypeConstraint(state))) {
  2497. return true;
  2498. }
  2499. state->parse_state = copy;
  2500. if (ParseOneCharToken(state, 'T') && ParseType(state)) return true;
  2501. state->parse_state = copy;
  2502. if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) return true;
  2503. state->parse_state = copy;
  2504. return false;
  2505. }
  2506. // <type-constraint> ::= <name>
  2507. static bool ParseTypeConstraint(State *state) {
  2508. return ParseName(state);
  2509. }
  2510. // <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
  2511. // ::= Z <(function) encoding> E s [<discriminator>]
  2512. // ::= Z <(function) encoding> E d [<(parameter) number>] _ <name>
  2513. //
  2514. // Parsing a common prefix of these two productions together avoids an
  2515. // exponential blowup of backtracking. Parse like:
  2516. // <local-name> := Z <encoding> E <local-name-suffix>
  2517. // <local-name-suffix> ::= s [<discriminator>]
  2518. // ::= d [<(parameter) number>] _ <name>
  2519. // ::= <name> [<discriminator>]
  2520. static bool ParseLocalNameSuffix(State *state) {
  2521. ComplexityGuard guard(state);
  2522. if (guard.IsTooComplex()) return false;
  2523. ParseState copy = state->parse_state;
  2524. // <local-name-suffix> ::= d [<(parameter) number>] _ <name>
  2525. if (ParseOneCharToken(state, 'd') &&
  2526. (IsDigit(RemainingInput(state)[0]) || RemainingInput(state)[0] == '_')) {
  2527. int number = -1;
  2528. Optional(ParseNumber(state, &number));
  2529. if (number < -1 || number > 2147483645) {
  2530. // Work around overflow cases. We do not expect these outside of a fuzzer
  2531. // or other source of adversarial input. If we do detect overflow here,
  2532. // we'll print {default arg#1}.
  2533. number = -1;
  2534. }
  2535. number += 2;
  2536. // The ::{default arg#1}:: infix must be rendered before the lambda itself,
  2537. // so print this before parsing the rest of the <local-name-suffix>.
  2538. MaybeAppend(state, "::{default arg#");
  2539. MaybeAppendDecimal(state, number);
  2540. MaybeAppend(state, "}::");
  2541. if (ParseOneCharToken(state, '_') && ParseName(state)) return true;
  2542. // On late parse failure, roll back not only the input but also the output,
  2543. // whose trailing NUL was overwritten.
  2544. state->parse_state = copy;
  2545. if (state->parse_state.append) {
  2546. state->out[state->parse_state.out_cur_idx] = '\0';
  2547. }
  2548. return false;
  2549. }
  2550. state->parse_state = copy;
  2551. // <local-name-suffix> ::= <name> [<discriminator>]
  2552. if (MaybeAppend(state, "::") && ParseName(state) &&
  2553. Optional(ParseDiscriminator(state))) {
  2554. return true;
  2555. }
  2556. state->parse_state = copy;
  2557. if (state->parse_state.append) {
  2558. state->out[state->parse_state.out_cur_idx] = '\0';
  2559. }
  2560. // <local-name-suffix> ::= s [<discriminator>]
  2561. return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state));
  2562. }
  2563. static bool ParseLocalName(State *state) {
  2564. ComplexityGuard guard(state);
  2565. if (guard.IsTooComplex()) return false;
  2566. ParseState copy = state->parse_state;
  2567. if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
  2568. ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) {
  2569. return true;
  2570. }
  2571. state->parse_state = copy;
  2572. return false;
  2573. }
  2574. // <discriminator> := _ <digit>
  2575. // := __ <number (>= 10)> _
  2576. static bool ParseDiscriminator(State *state) {
  2577. ComplexityGuard guard(state);
  2578. if (guard.IsTooComplex()) return false;
  2579. ParseState copy = state->parse_state;
  2580. // Both forms start with _ so parse that first.
  2581. if (!ParseOneCharToken(state, '_')) return false;
  2582. // <digit>
  2583. if (ParseDigit(state, nullptr)) return true;
  2584. // _ <number> _
  2585. if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) &&
  2586. ParseOneCharToken(state, '_')) {
  2587. return true;
  2588. }
  2589. state->parse_state = copy;
  2590. return false;
  2591. }
  2592. // <substitution> ::= S_
  2593. // ::= S <seq-id> _
  2594. // ::= St, etc.
  2595. //
  2596. // "St" is special in that it's not valid as a standalone name, and it *is*
  2597. // allowed to precede a name without being wrapped in "N...E". This means that
  2598. // if we accept it on its own, we can accept "St1a" and try to parse
  2599. // template-args, then fail and backtrack, accept "St" on its own, then "1a" as
  2600. // an unqualified name and re-parse the same template-args. To block this
  2601. // exponential backtracking, we disable it with 'accept_std=false' in
  2602. // problematic contexts.
  2603. static bool ParseSubstitution(State *state, bool accept_std) {
  2604. ComplexityGuard guard(state);
  2605. if (guard.IsTooComplex()) return false;
  2606. if (ParseTwoCharToken(state, "S_")) {
  2607. MaybeAppend(state, "?"); // We don't support substitutions.
  2608. return true;
  2609. }
  2610. ParseState copy = state->parse_state;
  2611. if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
  2612. ParseOneCharToken(state, '_')) {
  2613. MaybeAppend(state, "?"); // We don't support substitutions.
  2614. return true;
  2615. }
  2616. state->parse_state = copy;
  2617. // Expand abbreviations like "St" => "std".
  2618. if (ParseOneCharToken(state, 'S')) {
  2619. const AbbrevPair *p;
  2620. for (p = kSubstitutionList; p->abbrev != nullptr; ++p) {
  2621. if (RemainingInput(state)[0] == p->abbrev[1] &&
  2622. (accept_std || p->abbrev[1] != 't')) {
  2623. MaybeAppend(state, "std");
  2624. if (p->real_name[0] != '\0') {
  2625. MaybeAppend(state, "::");
  2626. MaybeAppend(state, p->real_name);
  2627. }
  2628. ++state->parse_state.mangled_idx;
  2629. UpdateHighWaterMark(state);
  2630. return true;
  2631. }
  2632. }
  2633. }
  2634. state->parse_state = copy;
  2635. return false;
  2636. }
  2637. // Parse <mangled-name>, optionally followed by either a function-clone suffix
  2638. // or version suffix. Returns true only if all of "mangled_cur" was consumed.
  2639. static bool ParseTopLevelMangledName(State *state) {
  2640. ComplexityGuard guard(state);
  2641. if (guard.IsTooComplex()) return false;
  2642. if (ParseMangledName(state)) {
  2643. if (RemainingInput(state)[0] != '\0') {
  2644. // Drop trailing function clone suffix, if any.
  2645. if (IsFunctionCloneSuffix(RemainingInput(state))) {
  2646. return true;
  2647. }
  2648. // Append trailing version suffix if any.
  2649. // ex. _Z3foo@@GLIBCXX_3.4
  2650. if (RemainingInput(state)[0] == '@') {
  2651. MaybeAppend(state, RemainingInput(state));
  2652. return true;
  2653. }
  2654. ReportHighWaterMark(state);
  2655. return false; // Unconsumed suffix.
  2656. }
  2657. return true;
  2658. }
  2659. ReportHighWaterMark(state);
  2660. return false;
  2661. }
  2662. static bool Overflowed(const State *state) {
  2663. return state->parse_state.out_cur_idx >= state->out_end_idx;
  2664. }
  2665. // The demangler entry point.
  2666. bool Demangle(const char* mangled, char* out, size_t out_size) {
  2667. if (mangled[0] == '_' && mangled[1] == 'R') {
  2668. return DemangleRustSymbolEncoding(mangled, out, out_size);
  2669. }
  2670. State state;
  2671. InitState(&state, mangled, out, out_size);
  2672. return ParseTopLevelMangledName(&state) && !Overflowed(&state) &&
  2673. state.parse_state.out_cur_idx > 0;
  2674. }
  2675. std::string DemangleString(const char* mangled) {
  2676. std::string out;
  2677. int status = 0;
  2678. char* demangled = nullptr;
  2679. #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
  2680. demangled = abi::__cxa_demangle(mangled, nullptr, nullptr, &status);
  2681. #endif
  2682. if (status == 0 && demangled != nullptr) {
  2683. out.append(demangled);
  2684. free(demangled);
  2685. } else {
  2686. out.append(mangled);
  2687. }
  2688. return out;
  2689. }
  2690. } // namespace debugging_internal
  2691. ABSL_NAMESPACE_END
  2692. } // namespace absl