regcomp.c 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789
  1. /* Extended regular expression matching and search library.
  2. Copyright (C) 2002-2023 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <https://www.gnu.org/licenses/>. */
  16. #ifdef _LIBC
  17. # include <locale/weight.h>
  18. #endif
  19. static reg_errcode_t re_compile_internal (regex_t *preg, const char * pattern,
  20. size_t length, reg_syntax_t syntax);
  21. static void re_compile_fastmap_iter (regex_t *bufp,
  22. const re_dfastate_t *init_state,
  23. char *fastmap);
  24. static reg_errcode_t init_dfa (re_dfa_t *dfa, size_t pat_len);
  25. static void free_charset (re_charset_t *cset);
  26. static void free_workarea_compile (regex_t *preg);
  27. static reg_errcode_t create_initial_state (re_dfa_t *dfa);
  28. static void optimize_utf8 (re_dfa_t *dfa);
  29. static reg_errcode_t analyze (regex_t *preg);
  30. static reg_errcode_t preorder (bin_tree_t *root,
  31. reg_errcode_t (fn (void *, bin_tree_t *)),
  32. void *extra);
  33. static reg_errcode_t postorder (bin_tree_t *root,
  34. reg_errcode_t (fn (void *, bin_tree_t *)),
  35. void *extra);
  36. static reg_errcode_t optimize_subexps (void *extra, bin_tree_t *node);
  37. static reg_errcode_t lower_subexps (void *extra, bin_tree_t *node);
  38. static bin_tree_t *lower_subexp (reg_errcode_t *err, regex_t *preg,
  39. bin_tree_t *node);
  40. static reg_errcode_t calc_first (void *extra, bin_tree_t *node);
  41. static reg_errcode_t calc_next (void *extra, bin_tree_t *node);
  42. static reg_errcode_t link_nfa_nodes (void *extra, bin_tree_t *node);
  43. static Idx duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint);
  44. static Idx search_duplicated_node (const re_dfa_t *dfa, Idx org_node,
  45. unsigned int constraint);
  46. static reg_errcode_t calc_eclosure (re_dfa_t *dfa);
  47. static reg_errcode_t calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa,
  48. Idx node, bool root);
  49. static reg_errcode_t calc_inveclosure (re_dfa_t *dfa);
  50. static Idx fetch_number (re_string_t *input, re_token_t *token,
  51. reg_syntax_t syntax);
  52. static int peek_token (re_token_t *token, re_string_t *input,
  53. reg_syntax_t syntax);
  54. static bin_tree_t *parse (re_string_t *regexp, regex_t *preg,
  55. reg_syntax_t syntax, reg_errcode_t *err);
  56. static bin_tree_t *parse_reg_exp (re_string_t *regexp, regex_t *preg,
  57. re_token_t *token, reg_syntax_t syntax,
  58. Idx nest, reg_errcode_t *err);
  59. static bin_tree_t *parse_branch (re_string_t *regexp, regex_t *preg,
  60. re_token_t *token, reg_syntax_t syntax,
  61. Idx nest, reg_errcode_t *err);
  62. static bin_tree_t *parse_expression (re_string_t *regexp, regex_t *preg,
  63. re_token_t *token, reg_syntax_t syntax,
  64. Idx nest, reg_errcode_t *err);
  65. static bin_tree_t *parse_sub_exp (re_string_t *regexp, regex_t *preg,
  66. re_token_t *token, reg_syntax_t syntax,
  67. Idx nest, reg_errcode_t *err);
  68. static bin_tree_t *parse_dup_op (bin_tree_t *dup_elem, re_string_t *regexp,
  69. re_dfa_t *dfa, re_token_t *token,
  70. reg_syntax_t syntax, reg_errcode_t *err);
  71. static bin_tree_t *parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa,
  72. re_token_t *token, reg_syntax_t syntax,
  73. reg_errcode_t *err);
  74. static reg_errcode_t parse_bracket_element (bracket_elem_t *elem,
  75. re_string_t *regexp,
  76. re_token_t *token, int token_len,
  77. re_dfa_t *dfa,
  78. reg_syntax_t syntax,
  79. bool accept_hyphen);
  80. static reg_errcode_t parse_bracket_symbol (bracket_elem_t *elem,
  81. re_string_t *regexp,
  82. re_token_t *token);
  83. static reg_errcode_t build_equiv_class (bitset_t sbcset,
  84. re_charset_t *mbcset,
  85. Idx *equiv_class_alloc,
  86. const unsigned char *name);
  87. static reg_errcode_t build_charclass (RE_TRANSLATE_TYPE trans,
  88. bitset_t sbcset,
  89. re_charset_t *mbcset,
  90. Idx *char_class_alloc,
  91. const char *class_name,
  92. reg_syntax_t syntax);
  93. static bin_tree_t *build_charclass_op (re_dfa_t *dfa,
  94. RE_TRANSLATE_TYPE trans,
  95. const char *class_name,
  96. const char *extra,
  97. bool non_match, reg_errcode_t *err);
  98. static bin_tree_t *create_tree (re_dfa_t *dfa,
  99. bin_tree_t *left, bin_tree_t *right,
  100. re_token_type_t type);
  101. static bin_tree_t *create_token_tree (re_dfa_t *dfa,
  102. bin_tree_t *left, bin_tree_t *right,
  103. const re_token_t *token);
  104. static bin_tree_t *duplicate_tree (const bin_tree_t *src, re_dfa_t *dfa);
  105. static void free_token (re_token_t *node);
  106. static reg_errcode_t free_tree (void *extra, bin_tree_t *node);
  107. static reg_errcode_t mark_opt_subexp (void *extra, bin_tree_t *node);
  108. /* This table gives an error message for each of the error codes listed
  109. in regex.h. Obviously the order here has to be same as there.
  110. POSIX doesn't require that we do anything for REG_NOERROR,
  111. but why not be nice? */
  112. static const char __re_error_msgid[] =
  113. {
  114. #define REG_NOERROR_IDX 0
  115. gettext_noop ("Success") /* REG_NOERROR */
  116. "\0"
  117. #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
  118. gettext_noop ("No match") /* REG_NOMATCH */
  119. "\0"
  120. #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
  121. gettext_noop ("Invalid regular expression") /* REG_BADPAT */
  122. "\0"
  123. #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
  124. gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
  125. "\0"
  126. #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
  127. gettext_noop ("Invalid character class name") /* REG_ECTYPE */
  128. "\0"
  129. #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
  130. gettext_noop ("Trailing backslash") /* REG_EESCAPE */
  131. "\0"
  132. #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
  133. gettext_noop ("Invalid back reference") /* REG_ESUBREG */
  134. "\0"
  135. #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
  136. gettext_noop ("Unmatched [, [^, [:, [., or [=") /* REG_EBRACK */
  137. "\0"
  138. #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [, [^, [:, [., or [=")
  139. gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
  140. "\0"
  141. #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
  142. gettext_noop ("Unmatched \\{") /* REG_EBRACE */
  143. "\0"
  144. #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
  145. gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
  146. "\0"
  147. #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
  148. gettext_noop ("Invalid range end") /* REG_ERANGE */
  149. "\0"
  150. #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
  151. gettext_noop ("Memory exhausted") /* REG_ESPACE */
  152. "\0"
  153. #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
  154. gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
  155. "\0"
  156. #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
  157. gettext_noop ("Premature end of regular expression") /* REG_EEND */
  158. "\0"
  159. #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
  160. gettext_noop ("Regular expression too big") /* REG_ESIZE */
  161. "\0"
  162. #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
  163. gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
  164. };
  165. static const size_t __re_error_msgid_idx[] =
  166. {
  167. REG_NOERROR_IDX,
  168. REG_NOMATCH_IDX,
  169. REG_BADPAT_IDX,
  170. REG_ECOLLATE_IDX,
  171. REG_ECTYPE_IDX,
  172. REG_EESCAPE_IDX,
  173. REG_ESUBREG_IDX,
  174. REG_EBRACK_IDX,
  175. REG_EPAREN_IDX,
  176. REG_EBRACE_IDX,
  177. REG_BADBR_IDX,
  178. REG_ERANGE_IDX,
  179. REG_ESPACE_IDX,
  180. REG_BADRPT_IDX,
  181. REG_EEND_IDX,
  182. REG_ESIZE_IDX,
  183. REG_ERPAREN_IDX
  184. };
  185. /* Entry points for GNU code. */
  186. /* re_compile_pattern is the GNU regular expression compiler: it
  187. compiles PATTERN (of length LENGTH) and puts the result in BUFP.
  188. Returns 0 if the pattern was valid, otherwise an error string.
  189. Assumes the 'allocated' (and perhaps 'buffer') and 'translate' fields
  190. are set in BUFP on entry. */
  191. const char *
  192. re_compile_pattern (const char *pattern, size_t length,
  193. struct re_pattern_buffer *bufp)
  194. {
  195. reg_errcode_t ret;
  196. /* And GNU code determines whether or not to get register information
  197. by passing null for the REGS argument to re_match, etc., not by
  198. setting no_sub, unless RE_NO_SUB is set. */
  199. bufp->no_sub = !!(re_syntax_options & RE_NO_SUB);
  200. /* Match anchors at newline. */
  201. bufp->newline_anchor = 1;
  202. ret = re_compile_internal (bufp, pattern, length, re_syntax_options);
  203. if (!ret)
  204. return NULL;
  205. return gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  206. }
  207. weak_alias (__re_compile_pattern, re_compile_pattern)
  208. /* Set by 're_set_syntax' to the current regexp syntax to recognize. Can
  209. also be assigned to arbitrarily: each pattern buffer stores its own
  210. syntax, so it can be changed between regex compilations. */
  211. /* This has no initializer because initialized variables in Emacs
  212. become read-only after dumping. */
  213. reg_syntax_t re_syntax_options;
  214. /* Specify the precise syntax of regexps for compilation. This provides
  215. for compatibility for various utilities which historically have
  216. different, incompatible syntaxes.
  217. The argument SYNTAX is a bit mask comprised of the various bits
  218. defined in regex.h. We return the old syntax. */
  219. reg_syntax_t
  220. re_set_syntax (reg_syntax_t syntax)
  221. {
  222. reg_syntax_t ret = re_syntax_options;
  223. re_syntax_options = syntax;
  224. return ret;
  225. }
  226. weak_alias (__re_set_syntax, re_set_syntax)
  227. int
  228. re_compile_fastmap (struct re_pattern_buffer *bufp)
  229. {
  230. re_dfa_t *dfa = bufp->buffer;
  231. char *fastmap = bufp->fastmap;
  232. memset (fastmap, '\0', sizeof (char) * SBC_MAX);
  233. re_compile_fastmap_iter (bufp, dfa->init_state, fastmap);
  234. if (dfa->init_state != dfa->init_state_word)
  235. re_compile_fastmap_iter (bufp, dfa->init_state_word, fastmap);
  236. if (dfa->init_state != dfa->init_state_nl)
  237. re_compile_fastmap_iter (bufp, dfa->init_state_nl, fastmap);
  238. if (dfa->init_state != dfa->init_state_begbuf)
  239. re_compile_fastmap_iter (bufp, dfa->init_state_begbuf, fastmap);
  240. bufp->fastmap_accurate = 1;
  241. return 0;
  242. }
  243. weak_alias (__re_compile_fastmap, re_compile_fastmap)
  244. static __always_inline void
  245. re_set_fastmap (char *fastmap, bool icase, int ch)
  246. {
  247. fastmap[ch] = 1;
  248. if (icase)
  249. fastmap[tolower (ch)] = 1;
  250. }
  251. /* Helper function for re_compile_fastmap.
  252. Compile fastmap for the initial_state INIT_STATE. */
  253. static void
  254. re_compile_fastmap_iter (regex_t *bufp, const re_dfastate_t *init_state,
  255. char *fastmap)
  256. {
  257. re_dfa_t *dfa = bufp->buffer;
  258. Idx node_cnt;
  259. bool icase = (dfa->mb_cur_max == 1 && (bufp->syntax & RE_ICASE));
  260. for (node_cnt = 0; node_cnt < init_state->nodes.nelem; ++node_cnt)
  261. {
  262. Idx node = init_state->nodes.elems[node_cnt];
  263. re_token_type_t type = dfa->nodes[node].type;
  264. if (type == CHARACTER)
  265. {
  266. re_set_fastmap (fastmap, icase, dfa->nodes[node].opr.c);
  267. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  268. {
  269. unsigned char buf[MB_LEN_MAX];
  270. unsigned char *p;
  271. wchar_t wc;
  272. mbstate_t state;
  273. p = buf;
  274. *p++ = dfa->nodes[node].opr.c;
  275. while (++node < dfa->nodes_len
  276. && dfa->nodes[node].type == CHARACTER
  277. && dfa->nodes[node].mb_partial)
  278. *p++ = dfa->nodes[node].opr.c;
  279. memset (&state, '\0', sizeof (state));
  280. if (__mbrtowc (&wc, (const char *) buf, p - buf,
  281. &state) == p - buf
  282. && (__wcrtomb ((char *) buf, __towlower (wc), &state)
  283. != (size_t) -1))
  284. re_set_fastmap (fastmap, false, buf[0]);
  285. }
  286. }
  287. else if (type == SIMPLE_BRACKET)
  288. {
  289. int i, ch;
  290. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  291. {
  292. int j;
  293. bitset_word_t w = dfa->nodes[node].opr.sbcset[i];
  294. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  295. if (w & ((bitset_word_t) 1 << j))
  296. re_set_fastmap (fastmap, icase, ch);
  297. }
  298. }
  299. else if (type == COMPLEX_BRACKET)
  300. {
  301. re_charset_t *cset = dfa->nodes[node].opr.mbcset;
  302. Idx i;
  303. #ifdef _LIBC
  304. /* See if we have to try all bytes which start multiple collation
  305. elements.
  306. e.g. In da_DK, we want to catch 'a' since "aa" is a valid
  307. collation element, and don't catch 'b' since 'b' is
  308. the only collation element which starts from 'b' (and
  309. it is caught by SIMPLE_BRACKET). */
  310. if (_NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES) != 0
  311. && (cset->ncoll_syms || cset->nranges))
  312. {
  313. const int32_t *table = (const int32_t *)
  314. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  315. for (i = 0; i < SBC_MAX; ++i)
  316. if (table[i] < 0)
  317. re_set_fastmap (fastmap, icase, i);
  318. }
  319. #endif /* _LIBC */
  320. /* See if we have to start the match at all multibyte characters,
  321. i.e. where we would not find an invalid sequence. This only
  322. applies to multibyte character sets; for single byte character
  323. sets, the SIMPLE_BRACKET again suffices. */
  324. if (dfa->mb_cur_max > 1
  325. && (cset->nchar_classes || cset->non_match || cset->nranges
  326. #ifdef _LIBC
  327. || cset->nequiv_classes
  328. #endif /* _LIBC */
  329. ))
  330. {
  331. unsigned char c = 0;
  332. do
  333. {
  334. mbstate_t mbs;
  335. memset (&mbs, 0, sizeof (mbs));
  336. if (__mbrtowc (NULL, (char *) &c, 1, &mbs) == (size_t) -2)
  337. re_set_fastmap (fastmap, false, (int) c);
  338. }
  339. while (++c != 0);
  340. }
  341. else
  342. {
  343. /* ... Else catch all bytes which can start the mbchars. */
  344. for (i = 0; i < cset->nmbchars; ++i)
  345. {
  346. char buf[256];
  347. mbstate_t state;
  348. memset (&state, '\0', sizeof (state));
  349. if (__wcrtomb (buf, cset->mbchars[i], &state) != (size_t) -1)
  350. re_set_fastmap (fastmap, icase, *(unsigned char *) buf);
  351. if ((bufp->syntax & RE_ICASE) && dfa->mb_cur_max > 1)
  352. {
  353. if (__wcrtomb (buf, __towlower (cset->mbchars[i]), &state)
  354. != (size_t) -1)
  355. re_set_fastmap (fastmap, false, *(unsigned char *) buf);
  356. }
  357. }
  358. }
  359. }
  360. else if (type == OP_PERIOD || type == OP_UTF8_PERIOD || type == END_OF_RE)
  361. {
  362. memset (fastmap, '\1', sizeof (char) * SBC_MAX);
  363. if (type == END_OF_RE)
  364. bufp->can_be_null = 1;
  365. return;
  366. }
  367. }
  368. }
  369. /* Entry point for POSIX code. */
  370. /* regcomp takes a regular expression as a string and compiles it.
  371. PREG is a regex_t *. We do not expect any fields to be initialized,
  372. since POSIX says we shouldn't. Thus, we set
  373. 'buffer' to the compiled pattern;
  374. 'used' to the length of the compiled pattern;
  375. 'syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  376. REG_EXTENDED bit in CFLAGS is set; otherwise, to
  377. RE_SYNTAX_POSIX_BASIC;
  378. 'newline_anchor' to REG_NEWLINE being set in CFLAGS;
  379. 'fastmap' to an allocated space for the fastmap;
  380. 'fastmap_accurate' to zero;
  381. 're_nsub' to the number of subexpressions in PATTERN.
  382. PATTERN is the address of the pattern string.
  383. CFLAGS is a series of bits which affect compilation.
  384. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  385. use POSIX basic syntax.
  386. If REG_NEWLINE is set, then . and [^...] don't match newline.
  387. Also, regexec will try a match beginning after every newline.
  388. If REG_ICASE is set, then we considers upper- and lowercase
  389. versions of letters to be equivalent when matching.
  390. If REG_NOSUB is set, then when PREG is passed to regexec, that
  391. routine will report only success or failure, and nothing about the
  392. registers.
  393. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
  394. the return codes and their meanings.) */
  395. int
  396. regcomp (regex_t *__restrict preg, const char *__restrict pattern, int cflags)
  397. {
  398. reg_errcode_t ret;
  399. reg_syntax_t syntax = ((cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED
  400. : RE_SYNTAX_POSIX_BASIC);
  401. preg->buffer = NULL;
  402. preg->allocated = 0;
  403. preg->used = 0;
  404. /* Try to allocate space for the fastmap. */
  405. preg->fastmap = re_malloc (char, SBC_MAX);
  406. if (__glibc_unlikely (preg->fastmap == NULL))
  407. return REG_ESPACE;
  408. syntax |= (cflags & REG_ICASE) ? RE_ICASE : 0;
  409. /* If REG_NEWLINE is set, newlines are treated differently. */
  410. if (cflags & REG_NEWLINE)
  411. { /* REG_NEWLINE implies neither . nor [^...] match newline. */
  412. syntax &= ~RE_DOT_NEWLINE;
  413. syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  414. /* It also changes the matching behavior. */
  415. preg->newline_anchor = 1;
  416. }
  417. else
  418. preg->newline_anchor = 0;
  419. preg->no_sub = !!(cflags & REG_NOSUB);
  420. preg->translate = NULL;
  421. ret = re_compile_internal (preg, pattern, strlen (pattern), syntax);
  422. /* POSIX doesn't distinguish between an unmatched open-group and an
  423. unmatched close-group: both are REG_EPAREN. */
  424. if (ret == REG_ERPAREN)
  425. ret = REG_EPAREN;
  426. /* We have already checked preg->fastmap != NULL. */
  427. if (__glibc_likely (ret == REG_NOERROR))
  428. /* Compute the fastmap now, since regexec cannot modify the pattern
  429. buffer. This function never fails in this implementation. */
  430. (void) re_compile_fastmap (preg);
  431. else
  432. {
  433. /* Some error occurred while compiling the expression. */
  434. re_free (preg->fastmap);
  435. preg->fastmap = NULL;
  436. }
  437. return (int) ret;
  438. }
  439. libc_hidden_def (__regcomp)
  440. weak_alias (__regcomp, regcomp)
  441. /* Returns a message corresponding to an error code, ERRCODE, returned
  442. from either regcomp or regexec. We don't use PREG here. */
  443. size_t
  444. regerror (int errcode, const regex_t *__restrict preg, char *__restrict errbuf,
  445. size_t errbuf_size)
  446. {
  447. const char *msg;
  448. size_t msg_size;
  449. int nerrcodes = sizeof __re_error_msgid_idx / sizeof __re_error_msgid_idx[0];
  450. if (__glibc_unlikely (errcode < 0 || errcode >= nerrcodes))
  451. /* Only error codes returned by the rest of the code should be passed
  452. to this routine. If we are given anything else, or if other regex
  453. code generates an invalid error code, then the program has a bug.
  454. Dump core so we can fix it. */
  455. abort ();
  456. msg = gettext (__re_error_msgid + __re_error_msgid_idx[errcode]);
  457. msg_size = strlen (msg) + 1; /* Includes the null. */
  458. if (__glibc_likely (errbuf_size != 0))
  459. {
  460. size_t cpy_size = msg_size;
  461. if (__glibc_unlikely (msg_size > errbuf_size))
  462. {
  463. cpy_size = errbuf_size - 1;
  464. errbuf[cpy_size] = '\0';
  465. }
  466. memcpy (errbuf, msg, cpy_size);
  467. }
  468. return msg_size;
  469. }
  470. weak_alias (__regerror, regerror)
  471. /* This static array is used for the map to single-byte characters when
  472. UTF-8 is used. Otherwise we would allocate memory just to initialize
  473. it the same all the time. UTF-8 is the preferred encoding so this is
  474. a worthwhile optimization. */
  475. static const bitset_t utf8_sb_map =
  476. {
  477. /* Set the first 128 bits. */
  478. #if (defined __GNUC__ || __clang_major__ >= 4) && !defined __STRICT_ANSI__
  479. [0 ... 0x80 / BITSET_WORD_BITS - 1] = BITSET_WORD_MAX
  480. #else
  481. # if 4 * BITSET_WORD_BITS < ASCII_CHARS
  482. # error "bitset_word_t is narrower than 32 bits"
  483. # elif 3 * BITSET_WORD_BITS < ASCII_CHARS
  484. BITSET_WORD_MAX, BITSET_WORD_MAX, BITSET_WORD_MAX,
  485. # elif 2 * BITSET_WORD_BITS < ASCII_CHARS
  486. BITSET_WORD_MAX, BITSET_WORD_MAX,
  487. # elif 1 * BITSET_WORD_BITS < ASCII_CHARS
  488. BITSET_WORD_MAX,
  489. # endif
  490. (BITSET_WORD_MAX
  491. >> (SBC_MAX % BITSET_WORD_BITS == 0
  492. ? 0
  493. : BITSET_WORD_BITS - SBC_MAX % BITSET_WORD_BITS))
  494. #endif
  495. };
  496. static void
  497. free_dfa_content (re_dfa_t *dfa)
  498. {
  499. Idx i, j;
  500. if (dfa->nodes)
  501. for (i = 0; i < dfa->nodes_len; ++i)
  502. free_token (dfa->nodes + i);
  503. re_free (dfa->nexts);
  504. for (i = 0; i < dfa->nodes_len; ++i)
  505. {
  506. if (dfa->eclosures != NULL)
  507. re_node_set_free (dfa->eclosures + i);
  508. if (dfa->inveclosures != NULL)
  509. re_node_set_free (dfa->inveclosures + i);
  510. if (dfa->edests != NULL)
  511. re_node_set_free (dfa->edests + i);
  512. }
  513. re_free (dfa->edests);
  514. re_free (dfa->eclosures);
  515. re_free (dfa->inveclosures);
  516. re_free (dfa->nodes);
  517. if (dfa->state_table)
  518. for (i = 0; i <= dfa->state_hash_mask; ++i)
  519. {
  520. struct re_state_table_entry *entry = dfa->state_table + i;
  521. for (j = 0; j < entry->num; ++j)
  522. {
  523. re_dfastate_t *state = entry->array[j];
  524. free_state (state);
  525. }
  526. re_free (entry->array);
  527. }
  528. re_free (dfa->state_table);
  529. if (dfa->sb_char != utf8_sb_map)
  530. re_free (dfa->sb_char);
  531. re_free (dfa->subexp_map);
  532. #ifdef DEBUG
  533. re_free (dfa->re_str);
  534. #endif
  535. re_free (dfa);
  536. }
  537. /* Free dynamically allocated space used by PREG. */
  538. void
  539. regfree (regex_t *preg)
  540. {
  541. re_dfa_t *dfa = preg->buffer;
  542. if (__glibc_likely (dfa != NULL))
  543. {
  544. lock_fini (dfa->lock);
  545. free_dfa_content (dfa);
  546. }
  547. preg->buffer = NULL;
  548. preg->allocated = 0;
  549. re_free (preg->fastmap);
  550. preg->fastmap = NULL;
  551. re_free (preg->translate);
  552. preg->translate = NULL;
  553. }
  554. libc_hidden_def (__regfree)
  555. weak_alias (__regfree, regfree)
  556. /* Entry points compatible with 4.2 BSD regex library. We don't define
  557. them unless specifically requested. */
  558. #if defined _REGEX_RE_COMP || defined _LIBC
  559. /* BSD has one and only one pattern buffer. */
  560. static struct re_pattern_buffer re_comp_buf;
  561. char *
  562. # ifdef _LIBC
  563. /* Make these definitions weak in libc, so POSIX programs can redefine
  564. these names if they don't use our functions, and still use
  565. regcomp/regexec above without link errors. */
  566. weak_function
  567. # endif
  568. re_comp (const char *s)
  569. {
  570. reg_errcode_t ret;
  571. char *fastmap;
  572. if (!s)
  573. {
  574. if (!re_comp_buf.buffer)
  575. return gettext ("No previous regular expression");
  576. return 0;
  577. }
  578. if (re_comp_buf.buffer)
  579. {
  580. fastmap = re_comp_buf.fastmap;
  581. re_comp_buf.fastmap = NULL;
  582. __regfree (&re_comp_buf);
  583. memset (&re_comp_buf, '\0', sizeof (re_comp_buf));
  584. re_comp_buf.fastmap = fastmap;
  585. }
  586. if (re_comp_buf.fastmap == NULL)
  587. {
  588. re_comp_buf.fastmap = re_malloc (char, SBC_MAX);
  589. if (re_comp_buf.fastmap == NULL)
  590. return (char *) gettext (__re_error_msgid
  591. + __re_error_msgid_idx[(int) REG_ESPACE]);
  592. }
  593. /* Since 're_exec' always passes NULL for the 'regs' argument, we
  594. don't need to initialize the pattern buffer fields which affect it. */
  595. /* Match anchors at newlines. */
  596. re_comp_buf.newline_anchor = 1;
  597. ret = re_compile_internal (&re_comp_buf, s, strlen (s), re_syntax_options);
  598. if (!ret)
  599. return NULL;
  600. /* Yes, we're discarding 'const' here if !HAVE_LIBINTL. */
  601. return (char *) gettext (__re_error_msgid + __re_error_msgid_idx[(int) ret]);
  602. }
  603. #ifdef _LIBC
  604. libc_freeres_fn (free_mem)
  605. {
  606. __regfree (&re_comp_buf);
  607. }
  608. #endif
  609. #endif /* _REGEX_RE_COMP */
  610. /* Internal entry point.
  611. Compile the regular expression PATTERN, whose length is LENGTH.
  612. SYNTAX indicate regular expression's syntax. */
  613. static reg_errcode_t
  614. re_compile_internal (regex_t *preg, const char * pattern, size_t length,
  615. reg_syntax_t syntax)
  616. {
  617. reg_errcode_t err = REG_NOERROR;
  618. re_dfa_t *dfa;
  619. re_string_t regexp;
  620. /* Initialize the pattern buffer. */
  621. preg->fastmap_accurate = 0;
  622. preg->syntax = syntax;
  623. preg->not_bol = preg->not_eol = 0;
  624. preg->used = 0;
  625. preg->re_nsub = 0;
  626. preg->can_be_null = 0;
  627. preg->regs_allocated = REGS_UNALLOCATED;
  628. /* Initialize the dfa. */
  629. dfa = preg->buffer;
  630. if (__glibc_unlikely (preg->allocated < sizeof (re_dfa_t)))
  631. {
  632. /* If zero allocated, but buffer is non-null, try to realloc
  633. enough space. This loses if buffer's address is bogus, but
  634. that is the user's responsibility. If ->buffer is NULL this
  635. is a simple allocation. */
  636. dfa = re_realloc (preg->buffer, re_dfa_t, 1);
  637. if (dfa == NULL)
  638. return REG_ESPACE;
  639. preg->allocated = sizeof (re_dfa_t);
  640. preg->buffer = dfa;
  641. }
  642. preg->used = sizeof (re_dfa_t);
  643. err = init_dfa (dfa, length);
  644. if (__glibc_unlikely (err == REG_NOERROR && lock_init (dfa->lock) != 0))
  645. err = REG_ESPACE;
  646. if (__glibc_unlikely (err != REG_NOERROR))
  647. {
  648. free_dfa_content (dfa);
  649. preg->buffer = NULL;
  650. preg->allocated = 0;
  651. return err;
  652. }
  653. #ifdef DEBUG
  654. /* Note: length+1 will not overflow since it is checked in init_dfa. */
  655. dfa->re_str = re_malloc (char, length + 1);
  656. strncpy (dfa->re_str, pattern, length + 1);
  657. #endif
  658. err = re_string_construct (&regexp, pattern, length, preg->translate,
  659. (syntax & RE_ICASE) != 0, dfa);
  660. if (__glibc_unlikely (err != REG_NOERROR))
  661. {
  662. re_compile_internal_free_return:
  663. free_workarea_compile (preg);
  664. re_string_destruct (&regexp);
  665. lock_fini (dfa->lock);
  666. free_dfa_content (dfa);
  667. preg->buffer = NULL;
  668. preg->allocated = 0;
  669. return err;
  670. }
  671. /* Parse the regular expression, and build a structure tree. */
  672. preg->re_nsub = 0;
  673. dfa->str_tree = parse (&regexp, preg, syntax, &err);
  674. if (__glibc_unlikely (dfa->str_tree == NULL))
  675. goto re_compile_internal_free_return;
  676. /* Analyze the tree and create the nfa. */
  677. err = analyze (preg);
  678. if (__glibc_unlikely (err != REG_NOERROR))
  679. goto re_compile_internal_free_return;
  680. /* If possible, do searching in single byte encoding to speed things up. */
  681. if (dfa->is_utf8 && !(syntax & RE_ICASE) && preg->translate == NULL)
  682. optimize_utf8 (dfa);
  683. /* Then create the initial state of the dfa. */
  684. err = create_initial_state (dfa);
  685. /* Release work areas. */
  686. free_workarea_compile (preg);
  687. re_string_destruct (&regexp);
  688. if (__glibc_unlikely (err != REG_NOERROR))
  689. {
  690. lock_fini (dfa->lock);
  691. free_dfa_content (dfa);
  692. preg->buffer = NULL;
  693. preg->allocated = 0;
  694. }
  695. return err;
  696. }
  697. /* Initialize DFA. We use the length of the regular expression PAT_LEN
  698. as the initial length of some arrays. */
  699. static reg_errcode_t
  700. init_dfa (re_dfa_t *dfa, size_t pat_len)
  701. {
  702. __re_size_t table_size;
  703. #ifndef _LIBC
  704. const char *codeset_name;
  705. #endif
  706. size_t max_i18n_object_size = MAX (sizeof (wchar_t), sizeof (wctype_t));
  707. size_t max_object_size =
  708. MAX (sizeof (struct re_state_table_entry),
  709. MAX (sizeof (re_token_t),
  710. MAX (sizeof (re_node_set),
  711. MAX (sizeof (regmatch_t),
  712. max_i18n_object_size))));
  713. memset (dfa, '\0', sizeof (re_dfa_t));
  714. /* Force allocation of str_tree_storage the first time. */
  715. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  716. /* Avoid overflows. The extra "/ 2" is for the table_size doubling
  717. calculation below, and for similar doubling calculations
  718. elsewhere. And it's <= rather than <, because some of the
  719. doubling calculations add 1 afterwards. */
  720. if (__glibc_unlikely (MIN (IDX_MAX, SIZE_MAX / max_object_size) / 2
  721. <= pat_len))
  722. return REG_ESPACE;
  723. dfa->nodes_alloc = pat_len + 1;
  724. dfa->nodes = re_malloc (re_token_t, dfa->nodes_alloc);
  725. /* table_size = 2 ^ ceil(log pat_len) */
  726. for (table_size = 1; ; table_size <<= 1)
  727. if (table_size > pat_len)
  728. break;
  729. dfa->state_table = calloc (sizeof (struct re_state_table_entry), table_size);
  730. dfa->state_hash_mask = table_size - 1;
  731. dfa->mb_cur_max = MB_CUR_MAX;
  732. #ifdef _LIBC
  733. if (dfa->mb_cur_max == 6
  734. && strcmp (_NL_CURRENT (LC_CTYPE, _NL_CTYPE_CODESET_NAME), "UTF-8") == 0)
  735. dfa->is_utf8 = 1;
  736. dfa->map_notascii = (_NL_CURRENT_WORD (LC_CTYPE, _NL_CTYPE_MAP_TO_NONASCII)
  737. != 0);
  738. #else
  739. codeset_name = nl_langinfo (CODESET);
  740. if ((codeset_name[0] == 'U' || codeset_name[0] == 'u')
  741. && (codeset_name[1] == 'T' || codeset_name[1] == 't')
  742. && (codeset_name[2] == 'F' || codeset_name[2] == 'f')
  743. && strcmp (codeset_name + 3 + (codeset_name[3] == '-'), "8") == 0)
  744. dfa->is_utf8 = 1;
  745. /* We check exhaustively in the loop below if this charset is a
  746. superset of ASCII. */
  747. dfa->map_notascii = 0;
  748. #endif
  749. if (dfa->mb_cur_max > 1)
  750. {
  751. if (dfa->is_utf8)
  752. dfa->sb_char = (re_bitset_ptr_t) utf8_sb_map;
  753. else
  754. {
  755. int i, j, ch;
  756. dfa->sb_char = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  757. if (__glibc_unlikely (dfa->sb_char == NULL))
  758. return REG_ESPACE;
  759. /* Set the bits corresponding to single byte chars. */
  760. for (i = 0, ch = 0; i < BITSET_WORDS; ++i)
  761. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  762. {
  763. wint_t wch = __btowc (ch);
  764. if (wch != WEOF)
  765. dfa->sb_char[i] |= (bitset_word_t) 1 << j;
  766. #ifndef _LIBC
  767. if (isascii (ch) && wch != ch)
  768. dfa->map_notascii = 1;
  769. #endif
  770. }
  771. }
  772. }
  773. if (__glibc_unlikely (dfa->nodes == NULL || dfa->state_table == NULL))
  774. return REG_ESPACE;
  775. return REG_NOERROR;
  776. }
  777. /* Initialize WORD_CHAR table, which indicate which character is
  778. "word". In this case "word" means that it is the word construction
  779. character used by some operators like "\<", "\>", etc. */
  780. static void
  781. init_word_char (re_dfa_t *dfa)
  782. {
  783. int i = 0;
  784. int j;
  785. int ch = 0;
  786. dfa->word_ops_used = 1;
  787. if (__glibc_likely (dfa->map_notascii == 0))
  788. {
  789. bitset_word_t bits0 = 0x00000000;
  790. bitset_word_t bits1 = 0x03ff0000;
  791. bitset_word_t bits2 = 0x87fffffe;
  792. bitset_word_t bits3 = 0x07fffffe;
  793. if (BITSET_WORD_BITS == 64)
  794. {
  795. /* Pacify gcc -Woverflow on 32-bit platformns. */
  796. dfa->word_char[0] = bits1 << 31 << 1 | bits0;
  797. dfa->word_char[1] = bits3 << 31 << 1 | bits2;
  798. i = 2;
  799. }
  800. else if (BITSET_WORD_BITS == 32)
  801. {
  802. dfa->word_char[0] = bits0;
  803. dfa->word_char[1] = bits1;
  804. dfa->word_char[2] = bits2;
  805. dfa->word_char[3] = bits3;
  806. i = 4;
  807. }
  808. else
  809. goto general_case;
  810. ch = 128;
  811. if (__glibc_likely (dfa->is_utf8))
  812. {
  813. memset (&dfa->word_char[i], '\0', (SBC_MAX - ch) / 8);
  814. return;
  815. }
  816. }
  817. general_case:
  818. for (; i < BITSET_WORDS; ++i)
  819. for (j = 0; j < BITSET_WORD_BITS; ++j, ++ch)
  820. if (isalnum (ch) || ch == '_')
  821. dfa->word_char[i] |= (bitset_word_t) 1 << j;
  822. }
  823. /* Free the work area which are only used while compiling. */
  824. static void
  825. free_workarea_compile (regex_t *preg)
  826. {
  827. re_dfa_t *dfa = preg->buffer;
  828. bin_tree_storage_t *storage, *next;
  829. for (storage = dfa->str_tree_storage; storage; storage = next)
  830. {
  831. next = storage->next;
  832. re_free (storage);
  833. }
  834. dfa->str_tree_storage = NULL;
  835. dfa->str_tree_storage_idx = BIN_TREE_STORAGE_SIZE;
  836. dfa->str_tree = NULL;
  837. re_free (dfa->org_indices);
  838. dfa->org_indices = NULL;
  839. }
  840. /* Create initial states for all contexts. */
  841. static reg_errcode_t
  842. create_initial_state (re_dfa_t *dfa)
  843. {
  844. Idx first, i;
  845. reg_errcode_t err;
  846. re_node_set init_nodes;
  847. /* Initial states have the epsilon closure of the node which is
  848. the first node of the regular expression. */
  849. first = dfa->str_tree->first->node_idx;
  850. dfa->init_node = first;
  851. err = re_node_set_init_copy (&init_nodes, dfa->eclosures + first);
  852. if (__glibc_unlikely (err != REG_NOERROR))
  853. return err;
  854. /* The back-references which are in initial states can epsilon transit,
  855. since in this case all of the subexpressions can be null.
  856. Then we add epsilon closures of the nodes which are the next nodes of
  857. the back-references. */
  858. if (dfa->nbackref > 0)
  859. for (i = 0; i < init_nodes.nelem; ++i)
  860. {
  861. Idx node_idx = init_nodes.elems[i];
  862. re_token_type_t type = dfa->nodes[node_idx].type;
  863. Idx clexp_idx;
  864. if (type != OP_BACK_REF)
  865. continue;
  866. for (clexp_idx = 0; clexp_idx < init_nodes.nelem; ++clexp_idx)
  867. {
  868. re_token_t *clexp_node;
  869. clexp_node = dfa->nodes + init_nodes.elems[clexp_idx];
  870. if (clexp_node->type == OP_CLOSE_SUBEXP
  871. && clexp_node->opr.idx == dfa->nodes[node_idx].opr.idx)
  872. break;
  873. }
  874. if (clexp_idx == init_nodes.nelem)
  875. continue;
  876. if (type == OP_BACK_REF)
  877. {
  878. Idx dest_idx = dfa->edests[node_idx].elems[0];
  879. if (!re_node_set_contains (&init_nodes, dest_idx))
  880. {
  881. reg_errcode_t merge_err
  882. = re_node_set_merge (&init_nodes, dfa->eclosures + dest_idx);
  883. if (merge_err != REG_NOERROR)
  884. return merge_err;
  885. i = 0;
  886. }
  887. }
  888. }
  889. /* It must be the first time to invoke acquire_state. */
  890. dfa->init_state = re_acquire_state_context (&err, dfa, &init_nodes, 0);
  891. /* We don't check ERR here, since the initial state must not be NULL. */
  892. if (__glibc_unlikely (dfa->init_state == NULL))
  893. return err;
  894. if (dfa->init_state->has_constraint)
  895. {
  896. dfa->init_state_word = re_acquire_state_context (&err, dfa, &init_nodes,
  897. CONTEXT_WORD);
  898. dfa->init_state_nl = re_acquire_state_context (&err, dfa, &init_nodes,
  899. CONTEXT_NEWLINE);
  900. dfa->init_state_begbuf = re_acquire_state_context (&err, dfa,
  901. &init_nodes,
  902. CONTEXT_NEWLINE
  903. | CONTEXT_BEGBUF);
  904. if (__glibc_unlikely (dfa->init_state_word == NULL
  905. || dfa->init_state_nl == NULL
  906. || dfa->init_state_begbuf == NULL))
  907. return err;
  908. }
  909. else
  910. dfa->init_state_word = dfa->init_state_nl
  911. = dfa->init_state_begbuf = dfa->init_state;
  912. re_node_set_free (&init_nodes);
  913. return REG_NOERROR;
  914. }
  915. /* If it is possible to do searching in single byte encoding instead of UTF-8
  916. to speed things up, set dfa->mb_cur_max to 1, clear is_utf8 and change
  917. DFA nodes where needed. */
  918. static void
  919. optimize_utf8 (re_dfa_t *dfa)
  920. {
  921. Idx node;
  922. int i;
  923. bool mb_chars = false;
  924. bool has_period = false;
  925. for (node = 0; node < dfa->nodes_len; ++node)
  926. switch (dfa->nodes[node].type)
  927. {
  928. case CHARACTER:
  929. if (dfa->nodes[node].opr.c >= ASCII_CHARS)
  930. mb_chars = true;
  931. break;
  932. case ANCHOR:
  933. switch (dfa->nodes[node].opr.ctx_type)
  934. {
  935. case LINE_FIRST:
  936. case LINE_LAST:
  937. case BUF_FIRST:
  938. case BUF_LAST:
  939. break;
  940. default:
  941. /* Word anchors etc. cannot be handled. It's okay to test
  942. opr.ctx_type since constraints (for all DFA nodes) are
  943. created by ORing one or more opr.ctx_type values. */
  944. return;
  945. }
  946. break;
  947. case OP_PERIOD:
  948. has_period = true;
  949. break;
  950. case OP_BACK_REF:
  951. case OP_ALT:
  952. case END_OF_RE:
  953. case OP_DUP_ASTERISK:
  954. case OP_OPEN_SUBEXP:
  955. case OP_CLOSE_SUBEXP:
  956. break;
  957. case COMPLEX_BRACKET:
  958. return;
  959. case SIMPLE_BRACKET:
  960. /* Just double check. */
  961. {
  962. int rshift = (ASCII_CHARS % BITSET_WORD_BITS == 0
  963. ? 0
  964. : BITSET_WORD_BITS - ASCII_CHARS % BITSET_WORD_BITS);
  965. for (i = ASCII_CHARS / BITSET_WORD_BITS; i < BITSET_WORDS; ++i)
  966. {
  967. if (dfa->nodes[node].opr.sbcset[i] >> rshift != 0)
  968. return;
  969. rshift = 0;
  970. }
  971. }
  972. break;
  973. default:
  974. abort ();
  975. }
  976. if (mb_chars || has_period)
  977. for (node = 0; node < dfa->nodes_len; ++node)
  978. {
  979. if (dfa->nodes[node].type == CHARACTER
  980. && dfa->nodes[node].opr.c >= ASCII_CHARS)
  981. dfa->nodes[node].mb_partial = 0;
  982. else if (dfa->nodes[node].type == OP_PERIOD)
  983. dfa->nodes[node].type = OP_UTF8_PERIOD;
  984. }
  985. /* The search can be in single byte locale. */
  986. dfa->mb_cur_max = 1;
  987. dfa->is_utf8 = 0;
  988. dfa->has_mb_node = dfa->nbackref > 0 || has_period;
  989. }
  990. /* Analyze the structure tree, and calculate "first", "next", "edest",
  991. "eclosure", and "inveclosure". */
  992. static reg_errcode_t
  993. analyze (regex_t *preg)
  994. {
  995. re_dfa_t *dfa = preg->buffer;
  996. reg_errcode_t ret;
  997. /* Allocate arrays. */
  998. dfa->nexts = re_malloc (Idx, dfa->nodes_alloc);
  999. dfa->org_indices = re_malloc (Idx, dfa->nodes_alloc);
  1000. dfa->edests = re_malloc (re_node_set, dfa->nodes_alloc);
  1001. dfa->eclosures = re_malloc (re_node_set, dfa->nodes_alloc);
  1002. if (__glibc_unlikely (dfa->nexts == NULL || dfa->org_indices == NULL
  1003. || dfa->edests == NULL || dfa->eclosures == NULL))
  1004. return REG_ESPACE;
  1005. dfa->subexp_map = re_malloc (Idx, preg->re_nsub);
  1006. if (dfa->subexp_map != NULL)
  1007. {
  1008. Idx i;
  1009. for (i = 0; i < preg->re_nsub; i++)
  1010. dfa->subexp_map[i] = i;
  1011. preorder (dfa->str_tree, optimize_subexps, dfa);
  1012. for (i = 0; i < preg->re_nsub; i++)
  1013. if (dfa->subexp_map[i] != i)
  1014. break;
  1015. if (i == preg->re_nsub)
  1016. {
  1017. re_free (dfa->subexp_map);
  1018. dfa->subexp_map = NULL;
  1019. }
  1020. }
  1021. ret = postorder (dfa->str_tree, lower_subexps, preg);
  1022. if (__glibc_unlikely (ret != REG_NOERROR))
  1023. return ret;
  1024. ret = postorder (dfa->str_tree, calc_first, dfa);
  1025. if (__glibc_unlikely (ret != REG_NOERROR))
  1026. return ret;
  1027. preorder (dfa->str_tree, calc_next, dfa);
  1028. ret = preorder (dfa->str_tree, link_nfa_nodes, dfa);
  1029. if (__glibc_unlikely (ret != REG_NOERROR))
  1030. return ret;
  1031. ret = calc_eclosure (dfa);
  1032. if (__glibc_unlikely (ret != REG_NOERROR))
  1033. return ret;
  1034. /* We only need this during the prune_impossible_nodes pass in regexec.c;
  1035. skip it if p_i_n will not run, as calc_inveclosure can be quadratic. */
  1036. if ((!preg->no_sub && preg->re_nsub > 0 && dfa->has_plural_match)
  1037. || dfa->nbackref)
  1038. {
  1039. dfa->inveclosures = re_malloc (re_node_set, dfa->nodes_len);
  1040. if (__glibc_unlikely (dfa->inveclosures == NULL))
  1041. return REG_ESPACE;
  1042. ret = calc_inveclosure (dfa);
  1043. }
  1044. return ret;
  1045. }
  1046. /* Our parse trees are very unbalanced, so we cannot use a stack to
  1047. implement parse tree visits. Instead, we use parent pointers and
  1048. some hairy code in these two functions. */
  1049. static reg_errcode_t
  1050. postorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  1051. void *extra)
  1052. {
  1053. bin_tree_t *node, *prev;
  1054. for (node = root; ; )
  1055. {
  1056. /* Descend down the tree, preferably to the left (or to the right
  1057. if that's the only child). */
  1058. while (node->left || node->right)
  1059. if (node->left)
  1060. node = node->left;
  1061. else
  1062. node = node->right;
  1063. do
  1064. {
  1065. reg_errcode_t err = fn (extra, node);
  1066. if (__glibc_unlikely (err != REG_NOERROR))
  1067. return err;
  1068. if (node->parent == NULL)
  1069. return REG_NOERROR;
  1070. prev = node;
  1071. node = node->parent;
  1072. }
  1073. /* Go up while we have a node that is reached from the right. */
  1074. while (node->right == prev || node->right == NULL);
  1075. node = node->right;
  1076. }
  1077. }
  1078. static reg_errcode_t
  1079. preorder (bin_tree_t *root, reg_errcode_t (fn (void *, bin_tree_t *)),
  1080. void *extra)
  1081. {
  1082. bin_tree_t *node;
  1083. for (node = root; ; )
  1084. {
  1085. reg_errcode_t err = fn (extra, node);
  1086. if (__glibc_unlikely (err != REG_NOERROR))
  1087. return err;
  1088. /* Go to the left node, or up and to the right. */
  1089. if (node->left)
  1090. node = node->left;
  1091. else
  1092. {
  1093. bin_tree_t *prev = NULL;
  1094. while (node->right == prev || node->right == NULL)
  1095. {
  1096. prev = node;
  1097. node = node->parent;
  1098. if (!node)
  1099. return REG_NOERROR;
  1100. }
  1101. node = node->right;
  1102. }
  1103. }
  1104. }
  1105. /* Optimization pass: if a SUBEXP is entirely contained, strip it and tell
  1106. re_search_internal to map the inner one's opr.idx to this one's. Adjust
  1107. backreferences as well. Requires a preorder visit. */
  1108. static reg_errcode_t
  1109. optimize_subexps (void *extra, bin_tree_t *node)
  1110. {
  1111. re_dfa_t *dfa = (re_dfa_t *) extra;
  1112. if (node->token.type == OP_BACK_REF && dfa->subexp_map)
  1113. {
  1114. int idx = node->token.opr.idx;
  1115. node->token.opr.idx = dfa->subexp_map[idx];
  1116. dfa->used_bkref_map |= 1 << node->token.opr.idx;
  1117. }
  1118. else if (node->token.type == SUBEXP
  1119. && node->left && node->left->token.type == SUBEXP)
  1120. {
  1121. Idx other_idx = node->left->token.opr.idx;
  1122. node->left = node->left->left;
  1123. if (node->left)
  1124. node->left->parent = node;
  1125. dfa->subexp_map[other_idx] = dfa->subexp_map[node->token.opr.idx];
  1126. if (other_idx < BITSET_WORD_BITS)
  1127. dfa->used_bkref_map &= ~((bitset_word_t) 1 << other_idx);
  1128. }
  1129. return REG_NOERROR;
  1130. }
  1131. /* Lowering pass: Turn each SUBEXP node into the appropriate concatenation
  1132. of OP_OPEN_SUBEXP, the body of the SUBEXP (if any) and OP_CLOSE_SUBEXP. */
  1133. static reg_errcode_t
  1134. lower_subexps (void *extra, bin_tree_t *node)
  1135. {
  1136. regex_t *preg = (regex_t *) extra;
  1137. reg_errcode_t err = REG_NOERROR;
  1138. if (node->left && node->left->token.type == SUBEXP)
  1139. {
  1140. node->left = lower_subexp (&err, preg, node->left);
  1141. if (node->left)
  1142. node->left->parent = node;
  1143. }
  1144. if (node->right && node->right->token.type == SUBEXP)
  1145. {
  1146. node->right = lower_subexp (&err, preg, node->right);
  1147. if (node->right)
  1148. node->right->parent = node;
  1149. }
  1150. return err;
  1151. }
  1152. static bin_tree_t *
  1153. lower_subexp (reg_errcode_t *err, regex_t *preg, bin_tree_t *node)
  1154. {
  1155. re_dfa_t *dfa = preg->buffer;
  1156. bin_tree_t *body = node->left;
  1157. bin_tree_t *op, *cls, *tree1, *tree;
  1158. if (preg->no_sub
  1159. /* We do not optimize empty subexpressions, because otherwise we may
  1160. have bad CONCAT nodes with NULL children. This is obviously not
  1161. very common, so we do not lose much. An example that triggers
  1162. this case is the sed "script" /\(\)/x. */
  1163. && node->left != NULL
  1164. && (node->token.opr.idx >= BITSET_WORD_BITS
  1165. || !(dfa->used_bkref_map
  1166. & ((bitset_word_t) 1 << node->token.opr.idx))))
  1167. return node->left;
  1168. /* Convert the SUBEXP node to the concatenation of an
  1169. OP_OPEN_SUBEXP, the contents, and an OP_CLOSE_SUBEXP. */
  1170. op = create_tree (dfa, NULL, NULL, OP_OPEN_SUBEXP);
  1171. cls = create_tree (dfa, NULL, NULL, OP_CLOSE_SUBEXP);
  1172. tree1 = body ? create_tree (dfa, body, cls, CONCAT) : cls;
  1173. tree = create_tree (dfa, op, tree1, CONCAT);
  1174. if (__glibc_unlikely (tree == NULL || tree1 == NULL
  1175. || op == NULL || cls == NULL))
  1176. {
  1177. *err = REG_ESPACE;
  1178. return NULL;
  1179. }
  1180. op->token.opr.idx = cls->token.opr.idx = node->token.opr.idx;
  1181. op->token.opt_subexp = cls->token.opt_subexp = node->token.opt_subexp;
  1182. return tree;
  1183. }
  1184. /* Pass 1 in building the NFA: compute FIRST and create unlinked automaton
  1185. nodes. Requires a postorder visit. */
  1186. static reg_errcode_t
  1187. calc_first (void *extra, bin_tree_t *node)
  1188. {
  1189. re_dfa_t *dfa = (re_dfa_t *) extra;
  1190. if (node->token.type == CONCAT)
  1191. {
  1192. node->first = node->left->first;
  1193. node->node_idx = node->left->node_idx;
  1194. }
  1195. else
  1196. {
  1197. node->first = node;
  1198. node->node_idx = re_dfa_add_node (dfa, node->token);
  1199. if (__glibc_unlikely (node->node_idx == -1))
  1200. return REG_ESPACE;
  1201. if (node->token.type == ANCHOR)
  1202. dfa->nodes[node->node_idx].constraint = node->token.opr.ctx_type;
  1203. }
  1204. return REG_NOERROR;
  1205. }
  1206. /* Pass 2: compute NEXT on the tree. Preorder visit. */
  1207. static reg_errcode_t
  1208. calc_next (void *extra, bin_tree_t *node)
  1209. {
  1210. switch (node->token.type)
  1211. {
  1212. case OP_DUP_ASTERISK:
  1213. node->left->next = node;
  1214. break;
  1215. case CONCAT:
  1216. node->left->next = node->right->first;
  1217. node->right->next = node->next;
  1218. break;
  1219. default:
  1220. if (node->left)
  1221. node->left->next = node->next;
  1222. if (node->right)
  1223. node->right->next = node->next;
  1224. break;
  1225. }
  1226. return REG_NOERROR;
  1227. }
  1228. /* Pass 3: link all DFA nodes to their NEXT node (any order will do). */
  1229. static reg_errcode_t
  1230. link_nfa_nodes (void *extra, bin_tree_t *node)
  1231. {
  1232. re_dfa_t *dfa = (re_dfa_t *) extra;
  1233. Idx idx = node->node_idx;
  1234. reg_errcode_t err = REG_NOERROR;
  1235. switch (node->token.type)
  1236. {
  1237. case CONCAT:
  1238. break;
  1239. case END_OF_RE:
  1240. DEBUG_ASSERT (node->next == NULL);
  1241. break;
  1242. case OP_DUP_ASTERISK:
  1243. case OP_ALT:
  1244. {
  1245. Idx left, right;
  1246. dfa->has_plural_match = 1;
  1247. if (node->left != NULL)
  1248. left = node->left->first->node_idx;
  1249. else
  1250. left = node->next->node_idx;
  1251. if (node->right != NULL)
  1252. right = node->right->first->node_idx;
  1253. else
  1254. right = node->next->node_idx;
  1255. DEBUG_ASSERT (left > -1);
  1256. DEBUG_ASSERT (right > -1);
  1257. err = re_node_set_init_2 (dfa->edests + idx, left, right);
  1258. }
  1259. break;
  1260. case ANCHOR:
  1261. case OP_OPEN_SUBEXP:
  1262. case OP_CLOSE_SUBEXP:
  1263. err = re_node_set_init_1 (dfa->edests + idx, node->next->node_idx);
  1264. break;
  1265. case OP_BACK_REF:
  1266. dfa->nexts[idx] = node->next->node_idx;
  1267. if (node->token.type == OP_BACK_REF)
  1268. err = re_node_set_init_1 (dfa->edests + idx, dfa->nexts[idx]);
  1269. break;
  1270. default:
  1271. DEBUG_ASSERT (!IS_EPSILON_NODE (node->token.type));
  1272. dfa->nexts[idx] = node->next->node_idx;
  1273. break;
  1274. }
  1275. return err;
  1276. }
  1277. /* Duplicate the epsilon closure of the node ROOT_NODE.
  1278. Note that duplicated nodes have constraint INIT_CONSTRAINT in addition
  1279. to their own constraint. */
  1280. static reg_errcode_t
  1281. duplicate_node_closure (re_dfa_t *dfa, Idx top_org_node, Idx top_clone_node,
  1282. Idx root_node, unsigned int init_constraint)
  1283. {
  1284. Idx org_node, clone_node;
  1285. bool ok;
  1286. unsigned int constraint = init_constraint;
  1287. for (org_node = top_org_node, clone_node = top_clone_node;;)
  1288. {
  1289. Idx org_dest, clone_dest;
  1290. if (dfa->nodes[org_node].type == OP_BACK_REF)
  1291. {
  1292. /* If the back reference epsilon-transit, its destination must
  1293. also have the constraint. Then duplicate the epsilon closure
  1294. of the destination of the back reference, and store it in
  1295. edests of the back reference. */
  1296. org_dest = dfa->nexts[org_node];
  1297. re_node_set_empty (dfa->edests + clone_node);
  1298. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1299. if (__glibc_unlikely (clone_dest == -1))
  1300. return REG_ESPACE;
  1301. dfa->nexts[clone_node] = dfa->nexts[org_node];
  1302. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1303. if (__glibc_unlikely (! ok))
  1304. return REG_ESPACE;
  1305. }
  1306. else if (dfa->edests[org_node].nelem == 0)
  1307. {
  1308. /* In case of the node can't epsilon-transit, don't duplicate the
  1309. destination and store the original destination as the
  1310. destination of the node. */
  1311. dfa->nexts[clone_node] = dfa->nexts[org_node];
  1312. break;
  1313. }
  1314. else if (dfa->edests[org_node].nelem == 1)
  1315. {
  1316. /* In case of the node can epsilon-transit, and it has only one
  1317. destination. */
  1318. org_dest = dfa->edests[org_node].elems[0];
  1319. re_node_set_empty (dfa->edests + clone_node);
  1320. /* If the node is root_node itself, it means the epsilon closure
  1321. has a loop. Then tie it to the destination of the root_node. */
  1322. if (org_node == root_node && clone_node != org_node)
  1323. {
  1324. ok = re_node_set_insert (dfa->edests + clone_node, org_dest);
  1325. if (__glibc_unlikely (! ok))
  1326. return REG_ESPACE;
  1327. break;
  1328. }
  1329. /* In case the node has another constraint, append it. */
  1330. constraint |= dfa->nodes[org_node].constraint;
  1331. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1332. if (__glibc_unlikely (clone_dest == -1))
  1333. return REG_ESPACE;
  1334. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1335. if (__glibc_unlikely (! ok))
  1336. return REG_ESPACE;
  1337. }
  1338. else /* dfa->edests[org_node].nelem == 2 */
  1339. {
  1340. /* In case of the node can epsilon-transit, and it has two
  1341. destinations. In the bin_tree_t and DFA, that's '|' and '*'. */
  1342. org_dest = dfa->edests[org_node].elems[0];
  1343. re_node_set_empty (dfa->edests + clone_node);
  1344. /* Search for a duplicated node which satisfies the constraint. */
  1345. clone_dest = search_duplicated_node (dfa, org_dest, constraint);
  1346. if (clone_dest == -1)
  1347. {
  1348. /* There is no such duplicated node, create a new one. */
  1349. reg_errcode_t err;
  1350. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1351. if (__glibc_unlikely (clone_dest == -1))
  1352. return REG_ESPACE;
  1353. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1354. if (__glibc_unlikely (! ok))
  1355. return REG_ESPACE;
  1356. err = duplicate_node_closure (dfa, org_dest, clone_dest,
  1357. root_node, constraint);
  1358. if (__glibc_unlikely (err != REG_NOERROR))
  1359. return err;
  1360. }
  1361. else
  1362. {
  1363. /* There is a duplicated node which satisfies the constraint,
  1364. use it to avoid infinite loop. */
  1365. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1366. if (__glibc_unlikely (! ok))
  1367. return REG_ESPACE;
  1368. }
  1369. org_dest = dfa->edests[org_node].elems[1];
  1370. clone_dest = duplicate_node (dfa, org_dest, constraint);
  1371. if (__glibc_unlikely (clone_dest == -1))
  1372. return REG_ESPACE;
  1373. ok = re_node_set_insert (dfa->edests + clone_node, clone_dest);
  1374. if (__glibc_unlikely (! ok))
  1375. return REG_ESPACE;
  1376. }
  1377. org_node = org_dest;
  1378. clone_node = clone_dest;
  1379. }
  1380. return REG_NOERROR;
  1381. }
  1382. /* Search for a node which is duplicated from the node ORG_NODE, and
  1383. satisfies the constraint CONSTRAINT. */
  1384. static Idx
  1385. search_duplicated_node (const re_dfa_t *dfa, Idx org_node,
  1386. unsigned int constraint)
  1387. {
  1388. Idx idx;
  1389. for (idx = dfa->nodes_len - 1; dfa->nodes[idx].duplicated && idx > 0; --idx)
  1390. {
  1391. if (org_node == dfa->org_indices[idx]
  1392. && constraint == dfa->nodes[idx].constraint)
  1393. return idx; /* Found. */
  1394. }
  1395. return -1; /* Not found. */
  1396. }
  1397. /* Duplicate the node whose index is ORG_IDX and set the constraint CONSTRAINT.
  1398. Return the index of the new node, or -1 if insufficient storage is
  1399. available. */
  1400. static Idx
  1401. duplicate_node (re_dfa_t *dfa, Idx org_idx, unsigned int constraint)
  1402. {
  1403. Idx dup_idx = re_dfa_add_node (dfa, dfa->nodes[org_idx]);
  1404. if (__glibc_likely (dup_idx != -1))
  1405. {
  1406. dfa->nodes[dup_idx].constraint = constraint;
  1407. dfa->nodes[dup_idx].constraint |= dfa->nodes[org_idx].constraint;
  1408. dfa->nodes[dup_idx].duplicated = 1;
  1409. /* Store the index of the original node. */
  1410. dfa->org_indices[dup_idx] = org_idx;
  1411. }
  1412. return dup_idx;
  1413. }
  1414. static reg_errcode_t
  1415. calc_inveclosure (re_dfa_t *dfa)
  1416. {
  1417. Idx src, idx;
  1418. bool ok;
  1419. for (idx = 0; idx < dfa->nodes_len; ++idx)
  1420. re_node_set_init_empty (dfa->inveclosures + idx);
  1421. for (src = 0; src < dfa->nodes_len; ++src)
  1422. {
  1423. Idx *elems = dfa->eclosures[src].elems;
  1424. for (idx = 0; idx < dfa->eclosures[src].nelem; ++idx)
  1425. {
  1426. ok = re_node_set_insert_last (dfa->inveclosures + elems[idx], src);
  1427. if (__glibc_unlikely (! ok))
  1428. return REG_ESPACE;
  1429. }
  1430. }
  1431. return REG_NOERROR;
  1432. }
  1433. /* Calculate "eclosure" for all the node in DFA. */
  1434. static reg_errcode_t
  1435. calc_eclosure (re_dfa_t *dfa)
  1436. {
  1437. Idx node_idx;
  1438. bool incomplete;
  1439. DEBUG_ASSERT (dfa->nodes_len > 0);
  1440. incomplete = false;
  1441. /* For each nodes, calculate epsilon closure. */
  1442. for (node_idx = 0; ; ++node_idx)
  1443. {
  1444. reg_errcode_t err;
  1445. re_node_set eclosure_elem;
  1446. if (node_idx == dfa->nodes_len)
  1447. {
  1448. if (!incomplete)
  1449. break;
  1450. incomplete = false;
  1451. node_idx = 0;
  1452. }
  1453. DEBUG_ASSERT (dfa->eclosures[node_idx].nelem != -1);
  1454. /* If we have already calculated, skip it. */
  1455. if (dfa->eclosures[node_idx].nelem != 0)
  1456. continue;
  1457. /* Calculate epsilon closure of 'node_idx'. */
  1458. err = calc_eclosure_iter (&eclosure_elem, dfa, node_idx, true);
  1459. if (__glibc_unlikely (err != REG_NOERROR))
  1460. return err;
  1461. if (dfa->eclosures[node_idx].nelem == 0)
  1462. {
  1463. incomplete = true;
  1464. re_node_set_free (&eclosure_elem);
  1465. }
  1466. }
  1467. return REG_NOERROR;
  1468. }
  1469. /* Calculate epsilon closure of NODE. */
  1470. static reg_errcode_t
  1471. calc_eclosure_iter (re_node_set *new_set, re_dfa_t *dfa, Idx node, bool root)
  1472. {
  1473. reg_errcode_t err;
  1474. Idx i;
  1475. re_node_set eclosure;
  1476. bool incomplete = false;
  1477. err = re_node_set_alloc (&eclosure, dfa->edests[node].nelem + 1);
  1478. if (__glibc_unlikely (err != REG_NOERROR))
  1479. return err;
  1480. /* An epsilon closure includes itself. */
  1481. eclosure.elems[eclosure.nelem++] = node;
  1482. /* This indicates that we are calculating this node now.
  1483. We reference this value to avoid infinite loop. */
  1484. dfa->eclosures[node].nelem = -1;
  1485. /* If the current node has constraints, duplicate all nodes
  1486. since they must inherit the constraints. */
  1487. if (dfa->nodes[node].constraint
  1488. && dfa->edests[node].nelem
  1489. && !dfa->nodes[dfa->edests[node].elems[0]].duplicated)
  1490. {
  1491. err = duplicate_node_closure (dfa, node, node, node,
  1492. dfa->nodes[node].constraint);
  1493. if (__glibc_unlikely (err != REG_NOERROR))
  1494. return err;
  1495. }
  1496. /* Expand each epsilon destination nodes. */
  1497. if (IS_EPSILON_NODE(dfa->nodes[node].type))
  1498. for (i = 0; i < dfa->edests[node].nelem; ++i)
  1499. {
  1500. re_node_set eclosure_elem;
  1501. Idx edest = dfa->edests[node].elems[i];
  1502. /* If calculating the epsilon closure of 'edest' is in progress,
  1503. return intermediate result. */
  1504. if (dfa->eclosures[edest].nelem == -1)
  1505. {
  1506. incomplete = true;
  1507. continue;
  1508. }
  1509. /* If we haven't calculated the epsilon closure of 'edest' yet,
  1510. calculate now. Otherwise use calculated epsilon closure. */
  1511. if (dfa->eclosures[edest].nelem == 0)
  1512. {
  1513. err = calc_eclosure_iter (&eclosure_elem, dfa, edest, false);
  1514. if (__glibc_unlikely (err != REG_NOERROR))
  1515. return err;
  1516. }
  1517. else
  1518. eclosure_elem = dfa->eclosures[edest];
  1519. /* Merge the epsilon closure of 'edest'. */
  1520. err = re_node_set_merge (&eclosure, &eclosure_elem);
  1521. if (__glibc_unlikely (err != REG_NOERROR))
  1522. return err;
  1523. /* If the epsilon closure of 'edest' is incomplete,
  1524. the epsilon closure of this node is also incomplete. */
  1525. if (dfa->eclosures[edest].nelem == 0)
  1526. {
  1527. incomplete = true;
  1528. re_node_set_free (&eclosure_elem);
  1529. }
  1530. }
  1531. if (incomplete && !root)
  1532. dfa->eclosures[node].nelem = 0;
  1533. else
  1534. dfa->eclosures[node] = eclosure;
  1535. *new_set = eclosure;
  1536. return REG_NOERROR;
  1537. }
  1538. /* Functions for token which are used in the parser. */
  1539. /* Fetch a token from INPUT.
  1540. We must not use this function inside bracket expressions. */
  1541. static void
  1542. fetch_token (re_token_t *result, re_string_t *input, reg_syntax_t syntax)
  1543. {
  1544. re_string_skip_bytes (input, peek_token (result, input, syntax));
  1545. }
  1546. /* Peek a token from INPUT, and return the length of the token.
  1547. We must not use this function inside bracket expressions. */
  1548. static int
  1549. peek_token (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
  1550. {
  1551. unsigned char c;
  1552. if (re_string_eoi (input))
  1553. {
  1554. token->type = END_OF_RE;
  1555. return 0;
  1556. }
  1557. c = re_string_peek_byte (input, 0);
  1558. token->opr.c = c;
  1559. token->word_char = 0;
  1560. token->mb_partial = 0;
  1561. if (input->mb_cur_max > 1
  1562. && !re_string_first_byte (input, re_string_cur_idx (input)))
  1563. {
  1564. token->type = CHARACTER;
  1565. token->mb_partial = 1;
  1566. return 1;
  1567. }
  1568. if (c == '\\')
  1569. {
  1570. unsigned char c2;
  1571. if (re_string_cur_idx (input) + 1 >= re_string_length (input))
  1572. {
  1573. token->type = BACK_SLASH;
  1574. return 1;
  1575. }
  1576. c2 = re_string_peek_byte_case (input, 1);
  1577. token->opr.c = c2;
  1578. token->type = CHARACTER;
  1579. if (input->mb_cur_max > 1)
  1580. {
  1581. wint_t wc = re_string_wchar_at (input,
  1582. re_string_cur_idx (input) + 1);
  1583. token->word_char = IS_WIDE_WORD_CHAR (wc) != 0;
  1584. }
  1585. else
  1586. token->word_char = IS_WORD_CHAR (c2) != 0;
  1587. switch (c2)
  1588. {
  1589. case '|':
  1590. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_NO_BK_VBAR))
  1591. token->type = OP_ALT;
  1592. break;
  1593. case '1': case '2': case '3': case '4': case '5':
  1594. case '6': case '7': case '8': case '9':
  1595. if (!(syntax & RE_NO_BK_REFS))
  1596. {
  1597. token->type = OP_BACK_REF;
  1598. token->opr.idx = c2 - '1';
  1599. }
  1600. break;
  1601. case '<':
  1602. if (!(syntax & RE_NO_GNU_OPS))
  1603. {
  1604. token->type = ANCHOR;
  1605. token->opr.ctx_type = WORD_FIRST;
  1606. }
  1607. break;
  1608. case '>':
  1609. if (!(syntax & RE_NO_GNU_OPS))
  1610. {
  1611. token->type = ANCHOR;
  1612. token->opr.ctx_type = WORD_LAST;
  1613. }
  1614. break;
  1615. case 'b':
  1616. if (!(syntax & RE_NO_GNU_OPS))
  1617. {
  1618. token->type = ANCHOR;
  1619. token->opr.ctx_type = WORD_DELIM;
  1620. }
  1621. break;
  1622. case 'B':
  1623. if (!(syntax & RE_NO_GNU_OPS))
  1624. {
  1625. token->type = ANCHOR;
  1626. token->opr.ctx_type = NOT_WORD_DELIM;
  1627. }
  1628. break;
  1629. case 'w':
  1630. if (!(syntax & RE_NO_GNU_OPS))
  1631. token->type = OP_WORD;
  1632. break;
  1633. case 'W':
  1634. if (!(syntax & RE_NO_GNU_OPS))
  1635. token->type = OP_NOTWORD;
  1636. break;
  1637. case 's':
  1638. if (!(syntax & RE_NO_GNU_OPS))
  1639. token->type = OP_SPACE;
  1640. break;
  1641. case 'S':
  1642. if (!(syntax & RE_NO_GNU_OPS))
  1643. token->type = OP_NOTSPACE;
  1644. break;
  1645. case '`':
  1646. if (!(syntax & RE_NO_GNU_OPS))
  1647. {
  1648. token->type = ANCHOR;
  1649. token->opr.ctx_type = BUF_FIRST;
  1650. }
  1651. break;
  1652. case '\'':
  1653. if (!(syntax & RE_NO_GNU_OPS))
  1654. {
  1655. token->type = ANCHOR;
  1656. token->opr.ctx_type = BUF_LAST;
  1657. }
  1658. break;
  1659. case '(':
  1660. if (!(syntax & RE_NO_BK_PARENS))
  1661. token->type = OP_OPEN_SUBEXP;
  1662. break;
  1663. case ')':
  1664. if (!(syntax & RE_NO_BK_PARENS))
  1665. token->type = OP_CLOSE_SUBEXP;
  1666. break;
  1667. case '+':
  1668. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM))
  1669. token->type = OP_DUP_PLUS;
  1670. break;
  1671. case '?':
  1672. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_BK_PLUS_QM))
  1673. token->type = OP_DUP_QUESTION;
  1674. break;
  1675. case '{':
  1676. if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES)))
  1677. token->type = OP_OPEN_DUP_NUM;
  1678. break;
  1679. case '}':
  1680. if ((syntax & RE_INTERVALS) && (!(syntax & RE_NO_BK_BRACES)))
  1681. token->type = OP_CLOSE_DUP_NUM;
  1682. break;
  1683. default:
  1684. break;
  1685. }
  1686. return 2;
  1687. }
  1688. token->type = CHARACTER;
  1689. if (input->mb_cur_max > 1)
  1690. {
  1691. wint_t wc = re_string_wchar_at (input, re_string_cur_idx (input));
  1692. token->word_char = IS_WIDE_WORD_CHAR (wc) != 0;
  1693. }
  1694. else
  1695. token->word_char = IS_WORD_CHAR (token->opr.c);
  1696. switch (c)
  1697. {
  1698. case '\n':
  1699. if (syntax & RE_NEWLINE_ALT)
  1700. token->type = OP_ALT;
  1701. break;
  1702. case '|':
  1703. if (!(syntax & RE_LIMITED_OPS) && (syntax & RE_NO_BK_VBAR))
  1704. token->type = OP_ALT;
  1705. break;
  1706. case '*':
  1707. token->type = OP_DUP_ASTERISK;
  1708. break;
  1709. case '+':
  1710. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM))
  1711. token->type = OP_DUP_PLUS;
  1712. break;
  1713. case '?':
  1714. if (!(syntax & RE_LIMITED_OPS) && !(syntax & RE_BK_PLUS_QM))
  1715. token->type = OP_DUP_QUESTION;
  1716. break;
  1717. case '{':
  1718. if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1719. token->type = OP_OPEN_DUP_NUM;
  1720. break;
  1721. case '}':
  1722. if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1723. token->type = OP_CLOSE_DUP_NUM;
  1724. break;
  1725. case '(':
  1726. if (syntax & RE_NO_BK_PARENS)
  1727. token->type = OP_OPEN_SUBEXP;
  1728. break;
  1729. case ')':
  1730. if (syntax & RE_NO_BK_PARENS)
  1731. token->type = OP_CLOSE_SUBEXP;
  1732. break;
  1733. case '[':
  1734. token->type = OP_OPEN_BRACKET;
  1735. break;
  1736. case '.':
  1737. token->type = OP_PERIOD;
  1738. break;
  1739. case '^':
  1740. if (!(syntax & (RE_CONTEXT_INDEP_ANCHORS | RE_CARET_ANCHORS_HERE))
  1741. && re_string_cur_idx (input) != 0)
  1742. {
  1743. char prev = re_string_peek_byte (input, -1);
  1744. if (!(syntax & RE_NEWLINE_ALT) || prev != '\n')
  1745. break;
  1746. }
  1747. token->type = ANCHOR;
  1748. token->opr.ctx_type = LINE_FIRST;
  1749. break;
  1750. case '$':
  1751. if (!(syntax & RE_CONTEXT_INDEP_ANCHORS)
  1752. && re_string_cur_idx (input) + 1 != re_string_length (input))
  1753. {
  1754. re_token_t next;
  1755. re_string_skip_bytes (input, 1);
  1756. peek_token (&next, input, syntax);
  1757. re_string_skip_bytes (input, -1);
  1758. if (next.type != OP_ALT && next.type != OP_CLOSE_SUBEXP)
  1759. break;
  1760. }
  1761. token->type = ANCHOR;
  1762. token->opr.ctx_type = LINE_LAST;
  1763. break;
  1764. default:
  1765. break;
  1766. }
  1767. return 1;
  1768. }
  1769. /* Peek a token from INPUT, and return the length of the token.
  1770. We must not use this function out of bracket expressions. */
  1771. static int
  1772. peek_token_bracket (re_token_t *token, re_string_t *input, reg_syntax_t syntax)
  1773. {
  1774. unsigned char c;
  1775. if (re_string_eoi (input))
  1776. {
  1777. token->type = END_OF_RE;
  1778. return 0;
  1779. }
  1780. c = re_string_peek_byte (input, 0);
  1781. token->opr.c = c;
  1782. if (input->mb_cur_max > 1
  1783. && !re_string_first_byte (input, re_string_cur_idx (input)))
  1784. {
  1785. token->type = CHARACTER;
  1786. return 1;
  1787. }
  1788. if (c == '\\' && (syntax & RE_BACKSLASH_ESCAPE_IN_LISTS)
  1789. && re_string_cur_idx (input) + 1 < re_string_length (input))
  1790. {
  1791. /* In this case, '\' escape a character. */
  1792. unsigned char c2;
  1793. re_string_skip_bytes (input, 1);
  1794. c2 = re_string_peek_byte (input, 0);
  1795. token->opr.c = c2;
  1796. token->type = CHARACTER;
  1797. return 1;
  1798. }
  1799. if (c == '[') /* '[' is a special char in a bracket exps. */
  1800. {
  1801. unsigned char c2;
  1802. int token_len;
  1803. if (re_string_cur_idx (input) + 1 < re_string_length (input))
  1804. c2 = re_string_peek_byte (input, 1);
  1805. else
  1806. c2 = 0;
  1807. token->opr.c = c2;
  1808. token_len = 2;
  1809. switch (c2)
  1810. {
  1811. case '.':
  1812. token->type = OP_OPEN_COLL_ELEM;
  1813. break;
  1814. case '=':
  1815. token->type = OP_OPEN_EQUIV_CLASS;
  1816. break;
  1817. case ':':
  1818. if (syntax & RE_CHAR_CLASSES)
  1819. {
  1820. token->type = OP_OPEN_CHAR_CLASS;
  1821. break;
  1822. }
  1823. FALLTHROUGH;
  1824. default:
  1825. token->type = CHARACTER;
  1826. token->opr.c = c;
  1827. token_len = 1;
  1828. break;
  1829. }
  1830. return token_len;
  1831. }
  1832. switch (c)
  1833. {
  1834. case ']':
  1835. token->type = OP_CLOSE_BRACKET;
  1836. break;
  1837. case '^':
  1838. token->type = OP_NON_MATCH_LIST;
  1839. break;
  1840. case '-':
  1841. /* In V7 Unix grep and Unix awk and mawk, [...---...]
  1842. (3 adjacent minus signs) stands for a single minus sign.
  1843. Support that without breaking anything else. */
  1844. if (! (re_string_cur_idx (input) + 2 < re_string_length (input)
  1845. && re_string_peek_byte (input, 1) == '-'
  1846. && re_string_peek_byte (input, 2) == '-'))
  1847. {
  1848. token->type = OP_CHARSET_RANGE;
  1849. break;
  1850. }
  1851. re_string_skip_bytes (input, 2);
  1852. FALLTHROUGH;
  1853. default:
  1854. token->type = CHARACTER;
  1855. }
  1856. return 1;
  1857. }
  1858. /* Functions for parser. */
  1859. /* Entry point of the parser.
  1860. Parse the regular expression REGEXP and return the structure tree.
  1861. If an error occurs, ERR is set by error code, and return NULL.
  1862. This function build the following tree, from regular expression <reg_exp>:
  1863. CAT
  1864. / \
  1865. / \
  1866. <reg_exp> EOR
  1867. CAT means concatenation.
  1868. EOR means end of regular expression. */
  1869. static bin_tree_t *
  1870. parse (re_string_t *regexp, regex_t *preg, reg_syntax_t syntax,
  1871. reg_errcode_t *err)
  1872. {
  1873. re_dfa_t *dfa = preg->buffer;
  1874. bin_tree_t *tree, *eor, *root;
  1875. re_token_t current_token;
  1876. dfa->syntax = syntax;
  1877. fetch_token (&current_token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  1878. tree = parse_reg_exp (regexp, preg, &current_token, syntax, 0, err);
  1879. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  1880. return NULL;
  1881. eor = create_tree (dfa, NULL, NULL, END_OF_RE);
  1882. if (tree != NULL)
  1883. root = create_tree (dfa, tree, eor, CONCAT);
  1884. else
  1885. root = eor;
  1886. if (__glibc_unlikely (eor == NULL || root == NULL))
  1887. {
  1888. *err = REG_ESPACE;
  1889. return NULL;
  1890. }
  1891. return root;
  1892. }
  1893. /* This function build the following tree, from regular expression
  1894. <branch1>|<branch2>:
  1895. ALT
  1896. / \
  1897. / \
  1898. <branch1> <branch2>
  1899. ALT means alternative, which represents the operator '|'. */
  1900. static bin_tree_t *
  1901. parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
  1902. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  1903. {
  1904. re_dfa_t *dfa = preg->buffer;
  1905. bin_tree_t *tree, *branch = NULL;
  1906. bitset_word_t initial_bkref_map = dfa->completed_bkref_map;
  1907. tree = parse_branch (regexp, preg, token, syntax, nest, err);
  1908. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  1909. return NULL;
  1910. while (token->type == OP_ALT)
  1911. {
  1912. fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  1913. if (token->type != OP_ALT && token->type != END_OF_RE
  1914. && (nest == 0 || token->type != OP_CLOSE_SUBEXP))
  1915. {
  1916. bitset_word_t accumulated_bkref_map = dfa->completed_bkref_map;
  1917. dfa->completed_bkref_map = initial_bkref_map;
  1918. branch = parse_branch (regexp, preg, token, syntax, nest, err);
  1919. if (__glibc_unlikely (*err != REG_NOERROR && branch == NULL))
  1920. {
  1921. if (tree != NULL)
  1922. postorder (tree, free_tree, NULL);
  1923. return NULL;
  1924. }
  1925. dfa->completed_bkref_map |= accumulated_bkref_map;
  1926. }
  1927. else
  1928. branch = NULL;
  1929. tree = create_tree (dfa, tree, branch, OP_ALT);
  1930. if (__glibc_unlikely (tree == NULL))
  1931. {
  1932. *err = REG_ESPACE;
  1933. return NULL;
  1934. }
  1935. }
  1936. return tree;
  1937. }
  1938. /* This function build the following tree, from regular expression
  1939. <exp1><exp2>:
  1940. CAT
  1941. / \
  1942. / \
  1943. <exp1> <exp2>
  1944. CAT means concatenation. */
  1945. static bin_tree_t *
  1946. parse_branch (re_string_t *regexp, regex_t *preg, re_token_t *token,
  1947. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  1948. {
  1949. bin_tree_t *tree, *expr;
  1950. re_dfa_t *dfa = preg->buffer;
  1951. tree = parse_expression (regexp, preg, token, syntax, nest, err);
  1952. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  1953. return NULL;
  1954. while (token->type != OP_ALT && token->type != END_OF_RE
  1955. && (nest == 0 || token->type != OP_CLOSE_SUBEXP))
  1956. {
  1957. expr = parse_expression (regexp, preg, token, syntax, nest, err);
  1958. if (__glibc_unlikely (*err != REG_NOERROR && expr == NULL))
  1959. {
  1960. if (tree != NULL)
  1961. postorder (tree, free_tree, NULL);
  1962. return NULL;
  1963. }
  1964. if (tree != NULL && expr != NULL)
  1965. {
  1966. bin_tree_t *newtree = create_tree (dfa, tree, expr, CONCAT);
  1967. if (newtree == NULL)
  1968. {
  1969. postorder (expr, free_tree, NULL);
  1970. postorder (tree, free_tree, NULL);
  1971. *err = REG_ESPACE;
  1972. return NULL;
  1973. }
  1974. tree = newtree;
  1975. }
  1976. else if (tree == NULL)
  1977. tree = expr;
  1978. /* Otherwise expr == NULL, we don't need to create new tree. */
  1979. }
  1980. return tree;
  1981. }
  1982. /* This function build the following tree, from regular expression a*:
  1983. *
  1984. |
  1985. a
  1986. */
  1987. static bin_tree_t *
  1988. parse_expression (re_string_t *regexp, regex_t *preg, re_token_t *token,
  1989. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  1990. {
  1991. re_dfa_t *dfa = preg->buffer;
  1992. bin_tree_t *tree;
  1993. switch (token->type)
  1994. {
  1995. case CHARACTER:
  1996. tree = create_token_tree (dfa, NULL, NULL, token);
  1997. if (__glibc_unlikely (tree == NULL))
  1998. {
  1999. *err = REG_ESPACE;
  2000. return NULL;
  2001. }
  2002. if (dfa->mb_cur_max > 1)
  2003. {
  2004. while (!re_string_eoi (regexp)
  2005. && !re_string_first_byte (regexp, re_string_cur_idx (regexp)))
  2006. {
  2007. bin_tree_t *mbc_remain;
  2008. fetch_token (token, regexp, syntax);
  2009. mbc_remain = create_token_tree (dfa, NULL, NULL, token);
  2010. tree = create_tree (dfa, tree, mbc_remain, CONCAT);
  2011. if (__glibc_unlikely (mbc_remain == NULL || tree == NULL))
  2012. {
  2013. *err = REG_ESPACE;
  2014. return NULL;
  2015. }
  2016. }
  2017. }
  2018. break;
  2019. case OP_OPEN_SUBEXP:
  2020. tree = parse_sub_exp (regexp, preg, token, syntax, nest + 1, err);
  2021. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  2022. return NULL;
  2023. break;
  2024. case OP_OPEN_BRACKET:
  2025. tree = parse_bracket_exp (regexp, dfa, token, syntax, err);
  2026. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  2027. return NULL;
  2028. break;
  2029. case OP_BACK_REF:
  2030. if (!__glibc_likely (dfa->completed_bkref_map & (1 << token->opr.idx)))
  2031. {
  2032. *err = REG_ESUBREG;
  2033. return NULL;
  2034. }
  2035. dfa->used_bkref_map |= 1 << token->opr.idx;
  2036. tree = create_token_tree (dfa, NULL, NULL, token);
  2037. if (__glibc_unlikely (tree == NULL))
  2038. {
  2039. *err = REG_ESPACE;
  2040. return NULL;
  2041. }
  2042. ++dfa->nbackref;
  2043. dfa->has_mb_node = 1;
  2044. break;
  2045. case OP_OPEN_DUP_NUM:
  2046. if (syntax & RE_CONTEXT_INVALID_DUP)
  2047. {
  2048. *err = REG_BADRPT;
  2049. return NULL;
  2050. }
  2051. FALLTHROUGH;
  2052. case OP_DUP_ASTERISK:
  2053. case OP_DUP_PLUS:
  2054. case OP_DUP_QUESTION:
  2055. if (syntax & RE_CONTEXT_INVALID_OPS)
  2056. {
  2057. *err = REG_BADRPT;
  2058. return NULL;
  2059. }
  2060. else if (syntax & RE_CONTEXT_INDEP_OPS)
  2061. {
  2062. fetch_token (token, regexp, syntax);
  2063. return parse_expression (regexp, preg, token, syntax, nest, err);
  2064. }
  2065. FALLTHROUGH;
  2066. case OP_CLOSE_SUBEXP:
  2067. if ((token->type == OP_CLOSE_SUBEXP)
  2068. && !(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD))
  2069. {
  2070. *err = REG_ERPAREN;
  2071. return NULL;
  2072. }
  2073. FALLTHROUGH;
  2074. case OP_CLOSE_DUP_NUM:
  2075. /* We treat it as a normal character. */
  2076. /* Then we can these characters as normal characters. */
  2077. token->type = CHARACTER;
  2078. /* mb_partial and word_char bits should be initialized already
  2079. by peek_token. */
  2080. tree = create_token_tree (dfa, NULL, NULL, token);
  2081. if (__glibc_unlikely (tree == NULL))
  2082. {
  2083. *err = REG_ESPACE;
  2084. return NULL;
  2085. }
  2086. break;
  2087. case ANCHOR:
  2088. if ((token->opr.ctx_type
  2089. & (WORD_DELIM | NOT_WORD_DELIM | WORD_FIRST | WORD_LAST))
  2090. && dfa->word_ops_used == 0)
  2091. init_word_char (dfa);
  2092. if (token->opr.ctx_type == WORD_DELIM
  2093. || token->opr.ctx_type == NOT_WORD_DELIM)
  2094. {
  2095. bin_tree_t *tree_first, *tree_last;
  2096. if (token->opr.ctx_type == WORD_DELIM)
  2097. {
  2098. token->opr.ctx_type = WORD_FIRST;
  2099. tree_first = create_token_tree (dfa, NULL, NULL, token);
  2100. token->opr.ctx_type = WORD_LAST;
  2101. }
  2102. else
  2103. {
  2104. token->opr.ctx_type = INSIDE_WORD;
  2105. tree_first = create_token_tree (dfa, NULL, NULL, token);
  2106. token->opr.ctx_type = INSIDE_NOTWORD;
  2107. }
  2108. tree_last = create_token_tree (dfa, NULL, NULL, token);
  2109. tree = create_tree (dfa, tree_first, tree_last, OP_ALT);
  2110. if (__glibc_unlikely (tree_first == NULL || tree_last == NULL
  2111. || tree == NULL))
  2112. {
  2113. *err = REG_ESPACE;
  2114. return NULL;
  2115. }
  2116. }
  2117. else
  2118. {
  2119. tree = create_token_tree (dfa, NULL, NULL, token);
  2120. if (__glibc_unlikely (tree == NULL))
  2121. {
  2122. *err = REG_ESPACE;
  2123. return NULL;
  2124. }
  2125. }
  2126. /* We must return here, since ANCHORs can't be followed
  2127. by repetition operators.
  2128. eg. RE"^*" is invalid or "<ANCHOR(^)><CHAR(*)>",
  2129. it must not be "<ANCHOR(^)><REPEAT(*)>". */
  2130. fetch_token (token, regexp, syntax);
  2131. return tree;
  2132. case OP_PERIOD:
  2133. tree = create_token_tree (dfa, NULL, NULL, token);
  2134. if (__glibc_unlikely (tree == NULL))
  2135. {
  2136. *err = REG_ESPACE;
  2137. return NULL;
  2138. }
  2139. if (dfa->mb_cur_max > 1)
  2140. dfa->has_mb_node = 1;
  2141. break;
  2142. case OP_WORD:
  2143. case OP_NOTWORD:
  2144. tree = build_charclass_op (dfa, regexp->trans,
  2145. "alnum",
  2146. "_",
  2147. token->type == OP_NOTWORD, err);
  2148. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  2149. return NULL;
  2150. break;
  2151. case OP_SPACE:
  2152. case OP_NOTSPACE:
  2153. tree = build_charclass_op (dfa, regexp->trans,
  2154. "space",
  2155. "",
  2156. token->type == OP_NOTSPACE, err);
  2157. if (__glibc_unlikely (*err != REG_NOERROR && tree == NULL))
  2158. return NULL;
  2159. break;
  2160. case OP_ALT:
  2161. case END_OF_RE:
  2162. return NULL;
  2163. case BACK_SLASH:
  2164. *err = REG_EESCAPE;
  2165. return NULL;
  2166. default:
  2167. /* Must not happen? */
  2168. DEBUG_ASSERT (false);
  2169. return NULL;
  2170. }
  2171. fetch_token (token, regexp, syntax);
  2172. while (token->type == OP_DUP_ASTERISK || token->type == OP_DUP_PLUS
  2173. || token->type == OP_DUP_QUESTION || token->type == OP_OPEN_DUP_NUM)
  2174. {
  2175. bin_tree_t *dup_tree = parse_dup_op (tree, regexp, dfa, token,
  2176. syntax, err);
  2177. if (__glibc_unlikely (*err != REG_NOERROR && dup_tree == NULL))
  2178. {
  2179. if (tree != NULL)
  2180. postorder (tree, free_tree, NULL);
  2181. return NULL;
  2182. }
  2183. tree = dup_tree;
  2184. /* In BRE consecutive duplications are not allowed. */
  2185. if ((syntax & RE_CONTEXT_INVALID_DUP)
  2186. && (token->type == OP_DUP_ASTERISK
  2187. || token->type == OP_OPEN_DUP_NUM))
  2188. {
  2189. if (tree != NULL)
  2190. postorder (tree, free_tree, NULL);
  2191. *err = REG_BADRPT;
  2192. return NULL;
  2193. }
  2194. }
  2195. return tree;
  2196. }
  2197. /* This function build the following tree, from regular expression
  2198. (<reg_exp>):
  2199. SUBEXP
  2200. |
  2201. <reg_exp>
  2202. */
  2203. static bin_tree_t *
  2204. parse_sub_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,
  2205. reg_syntax_t syntax, Idx nest, reg_errcode_t *err)
  2206. {
  2207. re_dfa_t *dfa = preg->buffer;
  2208. bin_tree_t *tree;
  2209. size_t cur_nsub;
  2210. cur_nsub = preg->re_nsub++;
  2211. fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);
  2212. /* The subexpression may be a null string. */
  2213. if (token->type == OP_CLOSE_SUBEXP)
  2214. tree = NULL;
  2215. else
  2216. {
  2217. tree = parse_reg_exp (regexp, preg, token, syntax, nest, err);
  2218. if (__glibc_unlikely (*err == REG_NOERROR
  2219. && token->type != OP_CLOSE_SUBEXP))
  2220. {
  2221. if (tree != NULL)
  2222. postorder (tree, free_tree, NULL);
  2223. *err = REG_EPAREN;
  2224. }
  2225. if (__glibc_unlikely (*err != REG_NOERROR))
  2226. return NULL;
  2227. }
  2228. if (cur_nsub <= '9' - '1')
  2229. dfa->completed_bkref_map |= 1 << cur_nsub;
  2230. tree = create_tree (dfa, tree, NULL, SUBEXP);
  2231. if (__glibc_unlikely (tree == NULL))
  2232. {
  2233. *err = REG_ESPACE;
  2234. return NULL;
  2235. }
  2236. tree->token.opr.idx = cur_nsub;
  2237. return tree;
  2238. }
  2239. /* This function parse repetition operators like "*", "+", "{1,3}" etc. */
  2240. static bin_tree_t *
  2241. parse_dup_op (bin_tree_t *elem, re_string_t *regexp, re_dfa_t *dfa,
  2242. re_token_t *token, reg_syntax_t syntax, reg_errcode_t *err)
  2243. {
  2244. bin_tree_t *tree = NULL, *old_tree = NULL;
  2245. Idx i, start, end, start_idx = re_string_cur_idx (regexp);
  2246. re_token_t start_token = *token;
  2247. if (token->type == OP_OPEN_DUP_NUM)
  2248. {
  2249. end = 0;
  2250. start = fetch_number (regexp, token, syntax);
  2251. if (start == -1)
  2252. {
  2253. if (token->type == CHARACTER && token->opr.c == ',')
  2254. start = 0; /* We treat "{,m}" as "{0,m}". */
  2255. else
  2256. {
  2257. *err = REG_BADBR; /* <re>{} is invalid. */
  2258. return NULL;
  2259. }
  2260. }
  2261. if (__glibc_likely (start != -2))
  2262. {
  2263. /* We treat "{n}" as "{n,n}". */
  2264. end = ((token->type == OP_CLOSE_DUP_NUM) ? start
  2265. : ((token->type == CHARACTER && token->opr.c == ',')
  2266. ? fetch_number (regexp, token, syntax) : -2));
  2267. }
  2268. if (__glibc_unlikely (start == -2 || end == -2))
  2269. {
  2270. /* Invalid sequence. */
  2271. if (__glibc_unlikely (!(syntax & RE_INVALID_INTERVAL_ORD)))
  2272. {
  2273. if (token->type == END_OF_RE)
  2274. *err = REG_EBRACE;
  2275. else
  2276. *err = REG_BADBR;
  2277. return NULL;
  2278. }
  2279. /* If the syntax bit is set, rollback. */
  2280. re_string_set_index (regexp, start_idx);
  2281. *token = start_token;
  2282. token->type = CHARACTER;
  2283. /* mb_partial and word_char bits should be already initialized by
  2284. peek_token. */
  2285. return elem;
  2286. }
  2287. if (__glibc_unlikely ((end != -1 && start > end)
  2288. || token->type != OP_CLOSE_DUP_NUM))
  2289. {
  2290. /* First number greater than second. */
  2291. *err = REG_BADBR;
  2292. return NULL;
  2293. }
  2294. if (__glibc_unlikely (RE_DUP_MAX < (end == -1 ? start : end)))
  2295. {
  2296. *err = REG_ESIZE;
  2297. return NULL;
  2298. }
  2299. }
  2300. else
  2301. {
  2302. start = (token->type == OP_DUP_PLUS) ? 1 : 0;
  2303. end = (token->type == OP_DUP_QUESTION) ? 1 : -1;
  2304. }
  2305. fetch_token (token, regexp, syntax);
  2306. if (__glibc_unlikely (elem == NULL))
  2307. return NULL;
  2308. if (__glibc_unlikely (start == 0 && end == 0))
  2309. {
  2310. postorder (elem, free_tree, NULL);
  2311. return NULL;
  2312. }
  2313. /* Extract "<re>{n,m}" to "<re><re>...<re><re>{0,<m-n>}". */
  2314. if (__glibc_unlikely (start > 0))
  2315. {
  2316. tree = elem;
  2317. for (i = 2; i <= start; ++i)
  2318. {
  2319. elem = duplicate_tree (elem, dfa);
  2320. tree = create_tree (dfa, tree, elem, CONCAT);
  2321. if (__glibc_unlikely (elem == NULL || tree == NULL))
  2322. goto parse_dup_op_espace;
  2323. }
  2324. if (start == end)
  2325. return tree;
  2326. /* Duplicate ELEM before it is marked optional. */
  2327. elem = duplicate_tree (elem, dfa);
  2328. if (__glibc_unlikely (elem == NULL))
  2329. goto parse_dup_op_espace;
  2330. old_tree = tree;
  2331. }
  2332. else
  2333. old_tree = NULL;
  2334. if (elem->token.type == SUBEXP)
  2335. {
  2336. uintptr_t subidx = elem->token.opr.idx;
  2337. postorder (elem, mark_opt_subexp, (void *) subidx);
  2338. }
  2339. tree = create_tree (dfa, elem, NULL,
  2340. (end == -1 ? OP_DUP_ASTERISK : OP_ALT));
  2341. if (__glibc_unlikely (tree == NULL))
  2342. goto parse_dup_op_espace;
  2343. /* This loop is actually executed only when end != -1,
  2344. to rewrite <re>{0,n} as (<re>(<re>...<re>?)?)?... We have
  2345. already created the start+1-th copy. */
  2346. if (TYPE_SIGNED (Idx) || end != -1)
  2347. for (i = start + 2; i <= end; ++i)
  2348. {
  2349. elem = duplicate_tree (elem, dfa);
  2350. tree = create_tree (dfa, tree, elem, CONCAT);
  2351. if (__glibc_unlikely (elem == NULL || tree == NULL))
  2352. goto parse_dup_op_espace;
  2353. tree = create_tree (dfa, tree, NULL, OP_ALT);
  2354. if (__glibc_unlikely (tree == NULL))
  2355. goto parse_dup_op_espace;
  2356. }
  2357. if (old_tree)
  2358. tree = create_tree (dfa, old_tree, tree, CONCAT);
  2359. return tree;
  2360. parse_dup_op_espace:
  2361. *err = REG_ESPACE;
  2362. return NULL;
  2363. }
  2364. /* Size of the names for collating symbol/equivalence_class/character_class.
  2365. I'm not sure, but maybe enough. */
  2366. #define BRACKET_NAME_BUF_SIZE 32
  2367. #ifndef _LIBC
  2368. /* Convert the byte B to the corresponding wide character. In a
  2369. unibyte locale, treat B as itself. In a multibyte locale, return
  2370. WEOF if B is an encoding error. */
  2371. static wint_t
  2372. parse_byte (unsigned char b, re_dfa_t const *dfa)
  2373. {
  2374. return dfa->mb_cur_max > 1 ? __btowc (b) : b;
  2375. }
  2376. /* Local function for parse_bracket_exp used in _LIBC environment.
  2377. Build the range expression which starts from START_ELEM, and ends
  2378. at END_ELEM. The result are written to MBCSET and SBCSET.
  2379. RANGE_ALLOC is the allocated size of mbcset->range_starts, and
  2380. mbcset->range_ends, is a pointer argument since we may
  2381. update it. */
  2382. static reg_errcode_t
  2383. build_range_exp (bitset_t sbcset, re_charset_t *mbcset, Idx *range_alloc,
  2384. bracket_elem_t *start_elem, bracket_elem_t *end_elem,
  2385. re_dfa_t *dfa, reg_syntax_t syntax, uint_fast32_t nrules,
  2386. const unsigned char *collseqmb, const char *collseqwc,
  2387. int_fast32_t table_size, const void *symb_table,
  2388. const unsigned char *extra)
  2389. {
  2390. /* Equivalence Classes and Character Classes can't be a range start/end. */
  2391. if (__glibc_unlikely (start_elem->type == EQUIV_CLASS
  2392. || start_elem->type == CHAR_CLASS
  2393. || end_elem->type == EQUIV_CLASS
  2394. || end_elem->type == CHAR_CLASS))
  2395. return REG_ERANGE;
  2396. /* We can handle no multi character collating elements without libc
  2397. support. */
  2398. if (__glibc_unlikely ((start_elem->type == COLL_SYM
  2399. && strlen ((char *) start_elem->opr.name) > 1)
  2400. || (end_elem->type == COLL_SYM
  2401. && strlen ((char *) end_elem->opr.name) > 1)))
  2402. return REG_ECOLLATE;
  2403. unsigned int
  2404. start_ch = ((start_elem->type == SB_CHAR) ? start_elem->opr.ch
  2405. : ((start_elem->type == COLL_SYM) ? start_elem->opr.name[0]
  2406. : 0)),
  2407. end_ch = ((end_elem->type == SB_CHAR) ? end_elem->opr.ch
  2408. : ((end_elem->type == COLL_SYM) ? end_elem->opr.name[0]
  2409. : 0));
  2410. wint_t
  2411. start_wc = ((start_elem->type == SB_CHAR || start_elem->type == COLL_SYM)
  2412. ? parse_byte (start_ch, dfa) : start_elem->opr.wch),
  2413. end_wc = ((end_elem->type == SB_CHAR || end_elem->type == COLL_SYM)
  2414. ? parse_byte (end_ch, dfa) : end_elem->opr.wch);
  2415. if (start_wc == WEOF || end_wc == WEOF)
  2416. return REG_ECOLLATE;
  2417. else if (__glibc_unlikely ((syntax & RE_NO_EMPTY_RANGES)
  2418. && start_wc > end_wc))
  2419. return REG_ERANGE;
  2420. /* Got valid collation sequence values, add them as a new entry.
  2421. However, for !_LIBC we have no collation elements: if the
  2422. character set is single byte, the single byte character set
  2423. that we build below suffices. parse_bracket_exp passes
  2424. no MBCSET if dfa->mb_cur_max == 1. */
  2425. if (dfa->mb_cur_max > 1)
  2426. {
  2427. /* Check the space of the arrays. */
  2428. if (__glibc_unlikely (*range_alloc == mbcset->nranges))
  2429. {
  2430. /* There is not enough space, need realloc. */
  2431. wchar_t *new_array_start, *new_array_end;
  2432. Idx new_nranges;
  2433. /* +1 in case of mbcset->nranges is 0. */
  2434. new_nranges = 2 * mbcset->nranges + 1;
  2435. /* Use realloc since mbcset->range_starts and mbcset->range_ends
  2436. are NULL if *range_alloc == 0. */
  2437. new_array_start = re_realloc (mbcset->range_starts, wchar_t,
  2438. new_nranges);
  2439. new_array_end = re_realloc (mbcset->range_ends, wchar_t,
  2440. new_nranges);
  2441. if (__glibc_unlikely (new_array_start == NULL
  2442. || new_array_end == NULL))
  2443. {
  2444. re_free (new_array_start);
  2445. re_free (new_array_end);
  2446. return REG_ESPACE;
  2447. }
  2448. mbcset->range_starts = new_array_start;
  2449. mbcset->range_ends = new_array_end;
  2450. *range_alloc = new_nranges;
  2451. }
  2452. mbcset->range_starts[mbcset->nranges] = start_wc;
  2453. mbcset->range_ends[mbcset->nranges++] = end_wc;
  2454. }
  2455. /* Build the table for single byte characters. */
  2456. for (wchar_t wc = 0; wc < SBC_MAX; ++wc)
  2457. {
  2458. if (start_wc <= wc && wc <= end_wc)
  2459. bitset_set (sbcset, wc);
  2460. }
  2461. return REG_NOERROR;
  2462. }
  2463. #endif /* not _LIBC */
  2464. #ifndef _LIBC
  2465. /* Helper function for parse_bracket_exp only used in case of NOT _LIBC.
  2466. Build the collating element which is represented by NAME.
  2467. The result are written to MBCSET and SBCSET.
  2468. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
  2469. pointer argument since we may update it. */
  2470. static reg_errcode_t
  2471. build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
  2472. Idx *coll_sym_alloc, const unsigned char *name,
  2473. uint_fast32_t nrules, int_fast32_t table_size,
  2474. const void *symb_table, const unsigned char *extra)
  2475. {
  2476. size_t name_len = strlen ((const char *) name);
  2477. if (__glibc_unlikely (name_len != 1))
  2478. return REG_ECOLLATE;
  2479. else
  2480. {
  2481. bitset_set (sbcset, name[0]);
  2482. return REG_NOERROR;
  2483. }
  2484. }
  2485. #endif /* not _LIBC */
  2486. #ifdef _LIBC
  2487. /* Local function for parse_bracket_exp used in _LIBC environment.
  2488. Seek the collating symbol entry corresponding to NAME.
  2489. Return the index of the symbol in the SYMB_TABLE,
  2490. or -1 if not found. */
  2491. static __always_inline int32_t
  2492. seek_collating_symbol_entry (const unsigned char *name, size_t name_len,
  2493. const int32_t *symb_table,
  2494. int_fast32_t table_size,
  2495. const unsigned char *extra)
  2496. {
  2497. int_fast32_t elem;
  2498. for (elem = 0; elem < table_size; elem++)
  2499. if (symb_table[2 * elem] != 0)
  2500. {
  2501. int32_t idx = symb_table[2 * elem + 1];
  2502. /* Skip the name of collating element name. */
  2503. idx += 1 + extra[idx];
  2504. if (/* Compare the length of the name. */
  2505. name_len == extra[idx]
  2506. /* Compare the name. */
  2507. && memcmp (name, &extra[idx + 1], name_len) == 0)
  2508. /* Yep, this is the entry. */
  2509. return elem;
  2510. }
  2511. return -1;
  2512. }
  2513. /* Local function for parse_bracket_exp used in _LIBC environment.
  2514. Look up the collation sequence value of BR_ELEM.
  2515. Return the value if succeeded, UINT_MAX otherwise. */
  2516. static __always_inline unsigned int
  2517. lookup_collation_sequence_value (bracket_elem_t *br_elem, uint32_t nrules,
  2518. const unsigned char *collseqmb,
  2519. const char *collseqwc,
  2520. int_fast32_t table_size,
  2521. const int32_t *symb_table,
  2522. const unsigned char *extra)
  2523. {
  2524. if (br_elem->type == SB_CHAR)
  2525. {
  2526. /* if (MB_CUR_MAX == 1) */
  2527. if (nrules == 0)
  2528. return collseqmb[br_elem->opr.ch];
  2529. else
  2530. {
  2531. wint_t wc = __btowc (br_elem->opr.ch);
  2532. return __collseq_table_lookup (collseqwc, wc);
  2533. }
  2534. }
  2535. else if (br_elem->type == MB_CHAR)
  2536. {
  2537. if (nrules != 0)
  2538. return __collseq_table_lookup (collseqwc, br_elem->opr.wch);
  2539. }
  2540. else if (br_elem->type == COLL_SYM)
  2541. {
  2542. size_t sym_name_len = strlen ((char *) br_elem->opr.name);
  2543. if (nrules != 0)
  2544. {
  2545. int32_t elem, idx;
  2546. elem = seek_collating_symbol_entry (br_elem->opr.name,
  2547. sym_name_len,
  2548. symb_table, table_size,
  2549. extra);
  2550. if (elem != -1)
  2551. {
  2552. /* We found the entry. */
  2553. idx = symb_table[2 * elem + 1];
  2554. /* Skip the name of collating element name. */
  2555. idx += 1 + extra[idx];
  2556. /* Skip the byte sequence of the collating element. */
  2557. idx += 1 + extra[idx];
  2558. /* Adjust for the alignment. */
  2559. idx = (idx + 3) & ~3;
  2560. /* Skip the multibyte collation sequence value. */
  2561. idx += sizeof (unsigned int);
  2562. /* Skip the wide char sequence of the collating element. */
  2563. idx += sizeof (unsigned int) *
  2564. (1 + *(unsigned int *) (extra + idx));
  2565. /* Return the collation sequence value. */
  2566. return *(unsigned int *) (extra + idx);
  2567. }
  2568. else if (sym_name_len == 1)
  2569. {
  2570. /* No valid character. Match it as a single byte
  2571. character. */
  2572. return collseqmb[br_elem->opr.name[0]];
  2573. }
  2574. }
  2575. else if (sym_name_len == 1)
  2576. return collseqmb[br_elem->opr.name[0]];
  2577. }
  2578. return UINT_MAX;
  2579. }
  2580. /* Local function for parse_bracket_exp used in _LIBC environment.
  2581. Build the range expression which starts from START_ELEM, and ends
  2582. at END_ELEM. The result are written to MBCSET and SBCSET.
  2583. RANGE_ALLOC is the allocated size of mbcset->range_starts, and
  2584. mbcset->range_ends, is a pointer argument since we may
  2585. update it. */
  2586. static __always_inline reg_errcode_t
  2587. build_range_exp (bitset_t sbcset, re_charset_t *mbcset, Idx *range_alloc,
  2588. bracket_elem_t *start_elem, bracket_elem_t *end_elem,
  2589. re_dfa_t *dfa, reg_syntax_t syntax, uint32_t nrules,
  2590. const unsigned char *collseqmb, const char *collseqwc,
  2591. int_fast32_t table_size, const int32_t *symb_table,
  2592. const unsigned char *extra)
  2593. {
  2594. unsigned int ch;
  2595. uint32_t start_collseq;
  2596. uint32_t end_collseq;
  2597. /* Equivalence Classes and Character Classes can't be a range
  2598. start/end. */
  2599. if (__glibc_unlikely (start_elem->type == EQUIV_CLASS
  2600. || start_elem->type == CHAR_CLASS
  2601. || end_elem->type == EQUIV_CLASS
  2602. || end_elem->type == CHAR_CLASS))
  2603. return REG_ERANGE;
  2604. /* FIXME: Implement rational ranges here, too. */
  2605. start_collseq = lookup_collation_sequence_value (start_elem, nrules, collseqmb, collseqwc,
  2606. table_size, symb_table, extra);
  2607. end_collseq = lookup_collation_sequence_value (end_elem, nrules, collseqmb, collseqwc,
  2608. table_size, symb_table, extra);
  2609. /* Check start/end collation sequence values. */
  2610. if (__glibc_unlikely (start_collseq == UINT_MAX
  2611. || end_collseq == UINT_MAX))
  2612. return REG_ECOLLATE;
  2613. if (__glibc_unlikely ((syntax & RE_NO_EMPTY_RANGES)
  2614. && start_collseq > end_collseq))
  2615. return REG_ERANGE;
  2616. /* Got valid collation sequence values, add them as a new entry.
  2617. However, if we have no collation elements, and the character set
  2618. is single byte, the single byte character set that we
  2619. build below suffices. */
  2620. if (nrules > 0 || dfa->mb_cur_max > 1)
  2621. {
  2622. /* Check the space of the arrays. */
  2623. if (__glibc_unlikely (*range_alloc == mbcset->nranges))
  2624. {
  2625. /* There is not enough space, need realloc. */
  2626. uint32_t *new_array_start;
  2627. uint32_t *new_array_end;
  2628. int new_nranges;
  2629. /* +1 in case of mbcset->nranges is 0. */
  2630. new_nranges = 2 * mbcset->nranges + 1;
  2631. new_array_start = re_realloc (mbcset->range_starts, uint32_t,
  2632. new_nranges);
  2633. new_array_end = re_realloc (mbcset->range_ends, uint32_t,
  2634. new_nranges);
  2635. if (__glibc_unlikely (new_array_start == NULL
  2636. || new_array_end == NULL))
  2637. return REG_ESPACE;
  2638. mbcset->range_starts = new_array_start;
  2639. mbcset->range_ends = new_array_end;
  2640. *range_alloc = new_nranges;
  2641. }
  2642. mbcset->range_starts[mbcset->nranges] = start_collseq;
  2643. mbcset->range_ends[mbcset->nranges++] = end_collseq;
  2644. }
  2645. /* Build the table for single byte characters. */
  2646. for (ch = 0; ch < SBC_MAX; ch++)
  2647. {
  2648. uint32_t ch_collseq;
  2649. /* if (MB_CUR_MAX == 1) */
  2650. if (nrules == 0)
  2651. ch_collseq = collseqmb[ch];
  2652. else
  2653. ch_collseq = __collseq_table_lookup (collseqwc, __btowc (ch));
  2654. if (start_collseq <= ch_collseq && ch_collseq <= end_collseq)
  2655. bitset_set (sbcset, ch);
  2656. }
  2657. return REG_NOERROR;
  2658. }
  2659. /* Local function for parse_bracket_exp used in _LIBC environment.
  2660. Build the collating element which is represented by NAME.
  2661. The result are written to MBCSET and SBCSET.
  2662. COLL_SYM_ALLOC is the allocated size of mbcset->coll_sym, is a
  2663. pointer argument since we may update it. */
  2664. static __always_inline reg_errcode_t
  2665. build_collating_symbol (bitset_t sbcset, re_charset_t *mbcset,
  2666. Idx *coll_sym_alloc, const unsigned char *name,
  2667. uint_fast32_t nrules, int_fast32_t table_size,
  2668. const int32_t *symb_table, const unsigned char *extra)
  2669. {
  2670. int32_t elem, idx;
  2671. size_t name_len = strlen ((const char *) name);
  2672. if (nrules != 0)
  2673. {
  2674. elem = seek_collating_symbol_entry (name, name_len, symb_table,
  2675. table_size, extra);
  2676. if (elem != -1)
  2677. {
  2678. /* We found the entry. */
  2679. idx = symb_table[2 * elem + 1];
  2680. /* Skip the name of collating element name. */
  2681. idx += 1 + extra[idx];
  2682. }
  2683. else if (name_len == 1)
  2684. {
  2685. /* No valid character, treat it as a normal
  2686. character. */
  2687. bitset_set (sbcset, name[0]);
  2688. return REG_NOERROR;
  2689. }
  2690. else
  2691. return REG_ECOLLATE;
  2692. /* Got valid collation sequence, add it as a new entry. */
  2693. /* Check the space of the arrays. */
  2694. if (__glibc_unlikely (*coll_sym_alloc == mbcset->ncoll_syms))
  2695. {
  2696. /* Not enough, realloc it. */
  2697. /* +1 in case of mbcset->ncoll_syms is 0. */
  2698. int new_coll_sym_alloc = 2 * mbcset->ncoll_syms + 1;
  2699. /* Use realloc since mbcset->coll_syms is NULL
  2700. if *alloc == 0. */
  2701. int32_t *new_coll_syms = re_realloc (mbcset->coll_syms, int32_t,
  2702. new_coll_sym_alloc);
  2703. if (__glibc_unlikely (new_coll_syms == NULL))
  2704. return REG_ESPACE;
  2705. mbcset->coll_syms = new_coll_syms;
  2706. *coll_sym_alloc = new_coll_sym_alloc;
  2707. }
  2708. mbcset->coll_syms[mbcset->ncoll_syms++] = idx;
  2709. return REG_NOERROR;
  2710. }
  2711. else
  2712. {
  2713. if (__glibc_unlikely (name_len != 1))
  2714. return REG_ECOLLATE;
  2715. else
  2716. {
  2717. bitset_set (sbcset, name[0]);
  2718. return REG_NOERROR;
  2719. }
  2720. }
  2721. }
  2722. #endif /* _LIBC */
  2723. /* This function parse bracket expression like "[abc]", "[a-c]",
  2724. "[[.a-a.]]" etc. */
  2725. static bin_tree_t *
  2726. parse_bracket_exp (re_string_t *regexp, re_dfa_t *dfa, re_token_t *token,
  2727. reg_syntax_t syntax, reg_errcode_t *err)
  2728. {
  2729. const unsigned char *collseqmb = NULL;
  2730. const char *collseqwc = NULL;
  2731. uint_fast32_t nrules = 0;
  2732. int_fast32_t table_size = 0;
  2733. const void *symb_table = NULL;
  2734. const unsigned char *extra = NULL;
  2735. re_token_t br_token;
  2736. re_bitset_ptr_t sbcset;
  2737. re_charset_t *mbcset;
  2738. Idx coll_sym_alloc = 0, range_alloc = 0, mbchar_alloc = 0;
  2739. Idx equiv_class_alloc = 0, char_class_alloc = 0;
  2740. bool non_match = false;
  2741. bin_tree_t *work_tree;
  2742. int token_len;
  2743. bool first_round = true;
  2744. #ifdef _LIBC
  2745. collseqmb = (const unsigned char *)
  2746. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
  2747. nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  2748. if (nrules)
  2749. {
  2750. /*
  2751. if (MB_CUR_MAX > 1)
  2752. */
  2753. collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
  2754. table_size = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_SYMB_HASH_SIZEMB);
  2755. symb_table = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_TABLEMB);
  2756. extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  2757. _NL_COLLATE_SYMB_EXTRAMB);
  2758. }
  2759. #endif
  2760. sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  2761. mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
  2762. if (__glibc_unlikely (sbcset == NULL || mbcset == NULL))
  2763. {
  2764. re_free (sbcset);
  2765. re_free (mbcset);
  2766. *err = REG_ESPACE;
  2767. return NULL;
  2768. }
  2769. token_len = peek_token_bracket (token, regexp, syntax);
  2770. if (__glibc_unlikely (token->type == END_OF_RE))
  2771. {
  2772. *err = REG_BADPAT;
  2773. goto parse_bracket_exp_free_return;
  2774. }
  2775. if (token->type == OP_NON_MATCH_LIST)
  2776. {
  2777. mbcset->non_match = 1;
  2778. non_match = true;
  2779. if (syntax & RE_HAT_LISTS_NOT_NEWLINE)
  2780. bitset_set (sbcset, '\n');
  2781. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  2782. token_len = peek_token_bracket (token, regexp, syntax);
  2783. if (__glibc_unlikely (token->type == END_OF_RE))
  2784. {
  2785. *err = REG_BADPAT;
  2786. goto parse_bracket_exp_free_return;
  2787. }
  2788. }
  2789. /* We treat the first ']' as a normal character. */
  2790. if (token->type == OP_CLOSE_BRACKET)
  2791. token->type = CHARACTER;
  2792. while (1)
  2793. {
  2794. bracket_elem_t start_elem, end_elem;
  2795. unsigned char start_name_buf[BRACKET_NAME_BUF_SIZE];
  2796. unsigned char end_name_buf[BRACKET_NAME_BUF_SIZE];
  2797. reg_errcode_t ret;
  2798. int token_len2 = 0;
  2799. bool is_range_exp = false;
  2800. re_token_t token2;
  2801. start_elem.opr.name = start_name_buf;
  2802. start_elem.type = COLL_SYM;
  2803. ret = parse_bracket_element (&start_elem, regexp, token, token_len, dfa,
  2804. syntax, first_round);
  2805. if (__glibc_unlikely (ret != REG_NOERROR))
  2806. {
  2807. *err = ret;
  2808. goto parse_bracket_exp_free_return;
  2809. }
  2810. first_round = false;
  2811. /* Get information about the next token. We need it in any case. */
  2812. token_len = peek_token_bracket (token, regexp, syntax);
  2813. /* Do not check for ranges if we know they are not allowed. */
  2814. if (start_elem.type != CHAR_CLASS && start_elem.type != EQUIV_CLASS)
  2815. {
  2816. if (__glibc_unlikely (token->type == END_OF_RE))
  2817. {
  2818. *err = REG_EBRACK;
  2819. goto parse_bracket_exp_free_return;
  2820. }
  2821. if (token->type == OP_CHARSET_RANGE)
  2822. {
  2823. re_string_skip_bytes (regexp, token_len); /* Skip '-'. */
  2824. token_len2 = peek_token_bracket (&token2, regexp, syntax);
  2825. if (__glibc_unlikely (token2.type == END_OF_RE))
  2826. {
  2827. *err = REG_EBRACK;
  2828. goto parse_bracket_exp_free_return;
  2829. }
  2830. if (token2.type == OP_CLOSE_BRACKET)
  2831. {
  2832. /* We treat the last '-' as a normal character. */
  2833. re_string_skip_bytes (regexp, -token_len);
  2834. token->type = CHARACTER;
  2835. }
  2836. else
  2837. is_range_exp = true;
  2838. }
  2839. }
  2840. if (is_range_exp == true)
  2841. {
  2842. end_elem.opr.name = end_name_buf;
  2843. end_elem.type = COLL_SYM;
  2844. ret = parse_bracket_element (&end_elem, regexp, &token2, token_len2,
  2845. dfa, syntax, true);
  2846. if (__glibc_unlikely (ret != REG_NOERROR))
  2847. {
  2848. *err = ret;
  2849. goto parse_bracket_exp_free_return;
  2850. }
  2851. token_len = peek_token_bracket (token, regexp, syntax);
  2852. *err = build_range_exp (sbcset, mbcset, &range_alloc,
  2853. &start_elem, &end_elem,
  2854. dfa, syntax, nrules, collseqmb, collseqwc,
  2855. table_size, symb_table, extra);
  2856. if (__glibc_unlikely (*err != REG_NOERROR))
  2857. goto parse_bracket_exp_free_return;
  2858. }
  2859. else
  2860. {
  2861. switch (start_elem.type)
  2862. {
  2863. case SB_CHAR:
  2864. bitset_set (sbcset, start_elem.opr.ch);
  2865. break;
  2866. case MB_CHAR:
  2867. /* Check whether the array has enough space. */
  2868. if (__glibc_unlikely (mbchar_alloc == mbcset->nmbchars))
  2869. {
  2870. wchar_t *new_mbchars;
  2871. /* Not enough, realloc it. */
  2872. /* +1 in case of mbcset->nmbchars is 0. */
  2873. mbchar_alloc = 2 * mbcset->nmbchars + 1;
  2874. /* Use realloc since array is NULL if *alloc == 0. */
  2875. new_mbchars = re_realloc (mbcset->mbchars, wchar_t,
  2876. mbchar_alloc);
  2877. if (__glibc_unlikely (new_mbchars == NULL))
  2878. goto parse_bracket_exp_espace;
  2879. mbcset->mbchars = new_mbchars;
  2880. }
  2881. mbcset->mbchars[mbcset->nmbchars++] = start_elem.opr.wch;
  2882. break;
  2883. case EQUIV_CLASS:
  2884. *err = build_equiv_class (sbcset,
  2885. mbcset, &equiv_class_alloc,
  2886. start_elem.opr.name);
  2887. if (__glibc_unlikely (*err != REG_NOERROR))
  2888. goto parse_bracket_exp_free_return;
  2889. break;
  2890. case COLL_SYM:
  2891. *err = build_collating_symbol (sbcset,
  2892. mbcset, &coll_sym_alloc,
  2893. start_elem.opr.name,
  2894. nrules, table_size, symb_table, extra);
  2895. if (__glibc_unlikely (*err != REG_NOERROR))
  2896. goto parse_bracket_exp_free_return;
  2897. break;
  2898. case CHAR_CLASS:
  2899. *err = build_charclass (regexp->trans, sbcset,
  2900. mbcset, &char_class_alloc,
  2901. (const char *) start_elem.opr.name,
  2902. syntax);
  2903. if (__glibc_unlikely (*err != REG_NOERROR))
  2904. goto parse_bracket_exp_free_return;
  2905. break;
  2906. default:
  2907. DEBUG_ASSERT (false);
  2908. break;
  2909. }
  2910. }
  2911. if (__glibc_unlikely (token->type == END_OF_RE))
  2912. {
  2913. *err = REG_EBRACK;
  2914. goto parse_bracket_exp_free_return;
  2915. }
  2916. if (token->type == OP_CLOSE_BRACKET)
  2917. break;
  2918. }
  2919. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  2920. /* If it is non-matching list. */
  2921. if (non_match)
  2922. bitset_not (sbcset);
  2923. /* Ensure only single byte characters are set. */
  2924. if (dfa->mb_cur_max > 1)
  2925. bitset_mask (sbcset, dfa->sb_char);
  2926. if (mbcset->nmbchars || mbcset->ncoll_syms || mbcset->nequiv_classes
  2927. || mbcset->nranges || (dfa->mb_cur_max > 1 && (mbcset->nchar_classes
  2928. || mbcset->non_match)))
  2929. {
  2930. bin_tree_t *mbc_tree;
  2931. int sbc_idx;
  2932. /* Build a tree for complex bracket. */
  2933. dfa->has_mb_node = 1;
  2934. br_token.type = COMPLEX_BRACKET;
  2935. br_token.opr.mbcset = mbcset;
  2936. mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  2937. if (__glibc_unlikely (mbc_tree == NULL))
  2938. goto parse_bracket_exp_espace;
  2939. for (sbc_idx = 0; sbc_idx < BITSET_WORDS; ++sbc_idx)
  2940. if (sbcset[sbc_idx])
  2941. break;
  2942. /* If there are no bits set in sbcset, there is no point
  2943. of having both SIMPLE_BRACKET and COMPLEX_BRACKET. */
  2944. if (sbc_idx < BITSET_WORDS)
  2945. {
  2946. /* Build a tree for simple bracket. */
  2947. br_token.type = SIMPLE_BRACKET;
  2948. br_token.opr.sbcset = sbcset;
  2949. work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  2950. if (__glibc_unlikely (work_tree == NULL))
  2951. goto parse_bracket_exp_espace;
  2952. /* Then join them by ALT node. */
  2953. work_tree = create_tree (dfa, work_tree, mbc_tree, OP_ALT);
  2954. if (__glibc_unlikely (work_tree == NULL))
  2955. goto parse_bracket_exp_espace;
  2956. }
  2957. else
  2958. {
  2959. re_free (sbcset);
  2960. work_tree = mbc_tree;
  2961. }
  2962. }
  2963. else
  2964. {
  2965. free_charset (mbcset);
  2966. /* Build a tree for simple bracket. */
  2967. br_token.type = SIMPLE_BRACKET;
  2968. br_token.opr.sbcset = sbcset;
  2969. work_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  2970. if (__glibc_unlikely (work_tree == NULL))
  2971. goto parse_bracket_exp_espace;
  2972. }
  2973. return work_tree;
  2974. parse_bracket_exp_espace:
  2975. *err = REG_ESPACE;
  2976. parse_bracket_exp_free_return:
  2977. re_free (sbcset);
  2978. free_charset (mbcset);
  2979. return NULL;
  2980. }
  2981. /* Parse an element in the bracket expression. */
  2982. static reg_errcode_t
  2983. parse_bracket_element (bracket_elem_t *elem, re_string_t *regexp,
  2984. re_token_t *token, int token_len, re_dfa_t *dfa,
  2985. reg_syntax_t syntax, bool accept_hyphen)
  2986. {
  2987. int cur_char_size;
  2988. cur_char_size = re_string_char_size_at (regexp, re_string_cur_idx (regexp));
  2989. if (cur_char_size > 1)
  2990. {
  2991. elem->type = MB_CHAR;
  2992. elem->opr.wch = re_string_wchar_at (regexp, re_string_cur_idx (regexp));
  2993. re_string_skip_bytes (regexp, cur_char_size);
  2994. return REG_NOERROR;
  2995. }
  2996. re_string_skip_bytes (regexp, token_len); /* Skip a token. */
  2997. if (token->type == OP_OPEN_COLL_ELEM || token->type == OP_OPEN_CHAR_CLASS
  2998. || token->type == OP_OPEN_EQUIV_CLASS)
  2999. return parse_bracket_symbol (elem, regexp, token);
  3000. if (__glibc_unlikely (token->type == OP_CHARSET_RANGE) && !accept_hyphen)
  3001. {
  3002. /* A '-' must only appear as anything but a range indicator before
  3003. the closing bracket. Everything else is an error. */
  3004. re_token_t token2;
  3005. (void) peek_token_bracket (&token2, regexp, syntax);
  3006. if (token2.type != OP_CLOSE_BRACKET)
  3007. /* The actual error value is not standardized since this whole
  3008. case is undefined. But ERANGE makes good sense. */
  3009. return REG_ERANGE;
  3010. }
  3011. elem->type = SB_CHAR;
  3012. elem->opr.ch = token->opr.c;
  3013. return REG_NOERROR;
  3014. }
  3015. /* Parse a bracket symbol in the bracket expression. Bracket symbols are
  3016. such as [:<character_class>:], [.<collating_element>.], and
  3017. [=<equivalent_class>=]. */
  3018. static reg_errcode_t
  3019. parse_bracket_symbol (bracket_elem_t *elem, re_string_t *regexp,
  3020. re_token_t *token)
  3021. {
  3022. unsigned char ch, delim = token->opr.c;
  3023. int i = 0;
  3024. if (re_string_eoi(regexp))
  3025. return REG_EBRACK;
  3026. for (;; ++i)
  3027. {
  3028. if (i >= BRACKET_NAME_BUF_SIZE)
  3029. return REG_EBRACK;
  3030. if (token->type == OP_OPEN_CHAR_CLASS)
  3031. ch = re_string_fetch_byte_case (regexp);
  3032. else
  3033. ch = re_string_fetch_byte (regexp);
  3034. if (re_string_eoi(regexp))
  3035. return REG_EBRACK;
  3036. if (ch == delim && re_string_peek_byte (regexp, 0) == ']')
  3037. break;
  3038. elem->opr.name[i] = ch;
  3039. }
  3040. re_string_skip_bytes (regexp, 1);
  3041. elem->opr.name[i] = '\0';
  3042. switch (token->type)
  3043. {
  3044. case OP_OPEN_COLL_ELEM:
  3045. elem->type = COLL_SYM;
  3046. break;
  3047. case OP_OPEN_EQUIV_CLASS:
  3048. elem->type = EQUIV_CLASS;
  3049. break;
  3050. case OP_OPEN_CHAR_CLASS:
  3051. elem->type = CHAR_CLASS;
  3052. break;
  3053. default:
  3054. break;
  3055. }
  3056. return REG_NOERROR;
  3057. }
  3058. /* Helper function for parse_bracket_exp.
  3059. Build the equivalence class which is represented by NAME.
  3060. The result are written to MBCSET and SBCSET.
  3061. EQUIV_CLASS_ALLOC is the allocated size of mbcset->equiv_classes,
  3062. is a pointer argument since we may update it. */
  3063. static reg_errcode_t
  3064. build_equiv_class (bitset_t sbcset, re_charset_t *mbcset,
  3065. Idx *equiv_class_alloc, const unsigned char *name)
  3066. {
  3067. #ifdef _LIBC
  3068. uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  3069. if (nrules != 0)
  3070. {
  3071. const int32_t *table, *indirect;
  3072. const unsigned char *weights, *extra, *cp;
  3073. unsigned char char_buf[2];
  3074. int32_t idx1, idx2;
  3075. unsigned int ch;
  3076. size_t len;
  3077. /* Calculate the index for equivalence class. */
  3078. cp = name;
  3079. table = (const int32_t *) _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  3080. weights = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  3081. _NL_COLLATE_WEIGHTMB);
  3082. extra = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  3083. _NL_COLLATE_EXTRAMB);
  3084. indirect = (const int32_t *) _NL_CURRENT (LC_COLLATE,
  3085. _NL_COLLATE_INDIRECTMB);
  3086. idx1 = findidx (table, indirect, extra, &cp, -1);
  3087. if (__glibc_unlikely (idx1 == 0 || *cp != '\0'))
  3088. /* This isn't a valid character. */
  3089. return REG_ECOLLATE;
  3090. /* Build single byte matching table for this equivalence class. */
  3091. len = weights[idx1 & 0xffffff];
  3092. for (ch = 0; ch < SBC_MAX; ++ch)
  3093. {
  3094. char_buf[0] = ch;
  3095. cp = char_buf;
  3096. idx2 = findidx (table, indirect, extra, &cp, 1);
  3097. /*
  3098. idx2 = table[ch];
  3099. */
  3100. if (idx2 == 0)
  3101. /* This isn't a valid character. */
  3102. continue;
  3103. /* Compare only if the length matches and the collation rule
  3104. index is the same. */
  3105. if (len == weights[idx2 & 0xffffff] && (idx1 >> 24) == (idx2 >> 24)
  3106. && memcmp (weights + (idx1 & 0xffffff) + 1,
  3107. weights + (idx2 & 0xffffff) + 1, len) == 0)
  3108. bitset_set (sbcset, ch);
  3109. }
  3110. /* Check whether the array has enough space. */
  3111. if (__glibc_unlikely (*equiv_class_alloc == mbcset->nequiv_classes))
  3112. {
  3113. /* Not enough, realloc it. */
  3114. /* +1 in case of mbcset->nequiv_classes is 0. */
  3115. Idx new_equiv_class_alloc = 2 * mbcset->nequiv_classes + 1;
  3116. /* Use realloc since the array is NULL if *alloc == 0. */
  3117. int32_t *new_equiv_classes = re_realloc (mbcset->equiv_classes,
  3118. int32_t,
  3119. new_equiv_class_alloc);
  3120. if (__glibc_unlikely (new_equiv_classes == NULL))
  3121. return REG_ESPACE;
  3122. mbcset->equiv_classes = new_equiv_classes;
  3123. *equiv_class_alloc = new_equiv_class_alloc;
  3124. }
  3125. mbcset->equiv_classes[mbcset->nequiv_classes++] = idx1;
  3126. }
  3127. else
  3128. #endif /* _LIBC */
  3129. {
  3130. if (__glibc_unlikely (strlen ((const char *) name) != 1))
  3131. return REG_ECOLLATE;
  3132. bitset_set (sbcset, *name);
  3133. }
  3134. return REG_NOERROR;
  3135. }
  3136. /* Helper function for parse_bracket_exp.
  3137. Build the character class which is represented by NAME.
  3138. The result are written to MBCSET and SBCSET.
  3139. CHAR_CLASS_ALLOC is the allocated size of mbcset->char_classes,
  3140. is a pointer argument since we may update it. */
  3141. static reg_errcode_t
  3142. build_charclass (RE_TRANSLATE_TYPE trans, bitset_t sbcset,
  3143. re_charset_t *mbcset, Idx *char_class_alloc,
  3144. const char *class_name, reg_syntax_t syntax)
  3145. {
  3146. int i;
  3147. const char *name = class_name;
  3148. /* In case of REG_ICASE "upper" and "lower" match the both of
  3149. upper and lower cases. */
  3150. if ((syntax & RE_ICASE)
  3151. && (strcmp (name, "upper") == 0 || strcmp (name, "lower") == 0))
  3152. name = "alpha";
  3153. /* Check the space of the arrays. */
  3154. if (__glibc_unlikely (*char_class_alloc == mbcset->nchar_classes))
  3155. {
  3156. /* Not enough, realloc it. */
  3157. /* +1 in case of mbcset->nchar_classes is 0. */
  3158. Idx new_char_class_alloc = 2 * mbcset->nchar_classes + 1;
  3159. /* Use realloc since array is NULL if *alloc == 0. */
  3160. wctype_t *new_char_classes = re_realloc (mbcset->char_classes, wctype_t,
  3161. new_char_class_alloc);
  3162. if (__glibc_unlikely (new_char_classes == NULL))
  3163. return REG_ESPACE;
  3164. mbcset->char_classes = new_char_classes;
  3165. *char_class_alloc = new_char_class_alloc;
  3166. }
  3167. mbcset->char_classes[mbcset->nchar_classes++] = __wctype (name);
  3168. #define BUILD_CHARCLASS_LOOP(ctype_func) \
  3169. do { \
  3170. if (__glibc_unlikely (trans != NULL)) \
  3171. { \
  3172. for (i = 0; i < SBC_MAX; ++i) \
  3173. if (ctype_func (i)) \
  3174. bitset_set (sbcset, trans[i]); \
  3175. } \
  3176. else \
  3177. { \
  3178. for (i = 0; i < SBC_MAX; ++i) \
  3179. if (ctype_func (i)) \
  3180. bitset_set (sbcset, i); \
  3181. } \
  3182. } while (0)
  3183. if (strcmp (name, "alnum") == 0)
  3184. BUILD_CHARCLASS_LOOP (isalnum);
  3185. else if (strcmp (name, "cntrl") == 0)
  3186. BUILD_CHARCLASS_LOOP (iscntrl);
  3187. else if (strcmp (name, "lower") == 0)
  3188. BUILD_CHARCLASS_LOOP (islower);
  3189. else if (strcmp (name, "space") == 0)
  3190. BUILD_CHARCLASS_LOOP (isspace);
  3191. else if (strcmp (name, "alpha") == 0)
  3192. BUILD_CHARCLASS_LOOP (isalpha);
  3193. else if (strcmp (name, "digit") == 0)
  3194. BUILD_CHARCLASS_LOOP (isdigit);
  3195. else if (strcmp (name, "print") == 0)
  3196. BUILD_CHARCLASS_LOOP (isprint);
  3197. else if (strcmp (name, "upper") == 0)
  3198. BUILD_CHARCLASS_LOOP (isupper);
  3199. else if (strcmp (name, "blank") == 0)
  3200. BUILD_CHARCLASS_LOOP (isblank);
  3201. else if (strcmp (name, "graph") == 0)
  3202. BUILD_CHARCLASS_LOOP (isgraph);
  3203. else if (strcmp (name, "punct") == 0)
  3204. BUILD_CHARCLASS_LOOP (ispunct);
  3205. else if (strcmp (name, "xdigit") == 0)
  3206. BUILD_CHARCLASS_LOOP (isxdigit);
  3207. else
  3208. return REG_ECTYPE;
  3209. return REG_NOERROR;
  3210. }
  3211. static bin_tree_t *
  3212. build_charclass_op (re_dfa_t *dfa, RE_TRANSLATE_TYPE trans,
  3213. const char *class_name,
  3214. const char *extra, bool non_match,
  3215. reg_errcode_t *err)
  3216. {
  3217. re_bitset_ptr_t sbcset;
  3218. re_charset_t *mbcset;
  3219. Idx alloc = 0;
  3220. reg_errcode_t ret;
  3221. bin_tree_t *tree;
  3222. sbcset = (re_bitset_ptr_t) calloc (sizeof (bitset_t), 1);
  3223. if (__glibc_unlikely (sbcset == NULL))
  3224. {
  3225. *err = REG_ESPACE;
  3226. return NULL;
  3227. }
  3228. mbcset = (re_charset_t *) calloc (sizeof (re_charset_t), 1);
  3229. if (__glibc_unlikely (mbcset == NULL))
  3230. {
  3231. re_free (sbcset);
  3232. *err = REG_ESPACE;
  3233. return NULL;
  3234. }
  3235. mbcset->non_match = non_match;
  3236. /* We don't care the syntax in this case. */
  3237. ret = build_charclass (trans, sbcset, mbcset, &alloc, class_name, 0);
  3238. if (__glibc_unlikely (ret != REG_NOERROR))
  3239. {
  3240. re_free (sbcset);
  3241. free_charset (mbcset);
  3242. *err = ret;
  3243. return NULL;
  3244. }
  3245. /* \w match '_' also. */
  3246. for (; *extra; extra++)
  3247. bitset_set (sbcset, *extra);
  3248. /* If it is non-matching list. */
  3249. if (non_match)
  3250. bitset_not (sbcset);
  3251. /* Ensure only single byte characters are set. */
  3252. if (dfa->mb_cur_max > 1)
  3253. bitset_mask (sbcset, dfa->sb_char);
  3254. /* Build a tree for simple bracket. */
  3255. re_token_t br_token = { .type = SIMPLE_BRACKET, .opr.sbcset = sbcset };
  3256. tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3257. if (__glibc_unlikely (tree == NULL))
  3258. goto build_word_op_espace;
  3259. if (dfa->mb_cur_max > 1)
  3260. {
  3261. bin_tree_t *mbc_tree;
  3262. /* Build a tree for complex bracket. */
  3263. br_token.type = COMPLEX_BRACKET;
  3264. br_token.opr.mbcset = mbcset;
  3265. dfa->has_mb_node = 1;
  3266. mbc_tree = create_token_tree (dfa, NULL, NULL, &br_token);
  3267. if (__glibc_unlikely (mbc_tree == NULL))
  3268. goto build_word_op_espace;
  3269. /* Then join them by ALT node. */
  3270. tree = create_tree (dfa, tree, mbc_tree, OP_ALT);
  3271. if (__glibc_likely (mbc_tree != NULL))
  3272. return tree;
  3273. }
  3274. else
  3275. {
  3276. free_charset (mbcset);
  3277. return tree;
  3278. }
  3279. build_word_op_espace:
  3280. re_free (sbcset);
  3281. free_charset (mbcset);
  3282. *err = REG_ESPACE;
  3283. return NULL;
  3284. }
  3285. /* This is intended for the expressions like "a{1,3}".
  3286. Fetch a number from 'input', and return the number.
  3287. Return -1 if the number field is empty like "{,1}".
  3288. Return RE_DUP_MAX + 1 if the number field is too large.
  3289. Return -2 if an error occurred. */
  3290. static Idx
  3291. fetch_number (re_string_t *input, re_token_t *token, reg_syntax_t syntax)
  3292. {
  3293. Idx num = -1;
  3294. unsigned char c;
  3295. while (1)
  3296. {
  3297. fetch_token (token, input, syntax);
  3298. c = token->opr.c;
  3299. if (__glibc_unlikely (token->type == END_OF_RE))
  3300. return -2;
  3301. if (token->type == OP_CLOSE_DUP_NUM || c == ',')
  3302. break;
  3303. num = ((token->type != CHARACTER || c < '0' || '9' < c || num == -2)
  3304. ? -2
  3305. : num == -1
  3306. ? c - '0'
  3307. : MIN (RE_DUP_MAX + 1, num * 10 + c - '0'));
  3308. }
  3309. return num;
  3310. }
  3311. static void
  3312. free_charset (re_charset_t *cset)
  3313. {
  3314. re_free (cset->mbchars);
  3315. #ifdef _LIBC
  3316. re_free (cset->coll_syms);
  3317. re_free (cset->equiv_classes);
  3318. #endif
  3319. re_free (cset->range_starts);
  3320. re_free (cset->range_ends);
  3321. re_free (cset->char_classes);
  3322. re_free (cset);
  3323. }
  3324. /* Functions for binary tree operation. */
  3325. /* Create a tree node. */
  3326. static bin_tree_t *
  3327. create_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
  3328. re_token_type_t type)
  3329. {
  3330. re_token_t t = { .type = type };
  3331. return create_token_tree (dfa, left, right, &t);
  3332. }
  3333. static bin_tree_t *
  3334. create_token_tree (re_dfa_t *dfa, bin_tree_t *left, bin_tree_t *right,
  3335. const re_token_t *token)
  3336. {
  3337. bin_tree_t *tree;
  3338. if (__glibc_unlikely (dfa->str_tree_storage_idx == BIN_TREE_STORAGE_SIZE))
  3339. {
  3340. bin_tree_storage_t *storage = re_malloc (bin_tree_storage_t, 1);
  3341. if (storage == NULL)
  3342. return NULL;
  3343. storage->next = dfa->str_tree_storage;
  3344. dfa->str_tree_storage = storage;
  3345. dfa->str_tree_storage_idx = 0;
  3346. }
  3347. tree = &dfa->str_tree_storage->data[dfa->str_tree_storage_idx++];
  3348. tree->parent = NULL;
  3349. tree->left = left;
  3350. tree->right = right;
  3351. tree->token = *token;
  3352. tree->token.duplicated = 0;
  3353. tree->token.opt_subexp = 0;
  3354. tree->first = NULL;
  3355. tree->next = NULL;
  3356. tree->node_idx = -1;
  3357. if (left != NULL)
  3358. left->parent = tree;
  3359. if (right != NULL)
  3360. right->parent = tree;
  3361. return tree;
  3362. }
  3363. /* Mark the tree SRC as an optional subexpression.
  3364. To be called from preorder or postorder. */
  3365. static reg_errcode_t
  3366. mark_opt_subexp (void *extra, bin_tree_t *node)
  3367. {
  3368. Idx idx = (uintptr_t) extra;
  3369. if (node->token.type == SUBEXP && node->token.opr.idx == idx)
  3370. node->token.opt_subexp = 1;
  3371. return REG_NOERROR;
  3372. }
  3373. /* Free the allocated memory inside NODE. */
  3374. static void
  3375. free_token (re_token_t *node)
  3376. {
  3377. if (node->type == COMPLEX_BRACKET && node->duplicated == 0)
  3378. free_charset (node->opr.mbcset);
  3379. else if (node->type == SIMPLE_BRACKET && node->duplicated == 0)
  3380. re_free (node->opr.sbcset);
  3381. }
  3382. /* Worker function for tree walking. Free the allocated memory inside NODE
  3383. and its children. */
  3384. static reg_errcode_t
  3385. free_tree (void *extra, bin_tree_t *node)
  3386. {
  3387. free_token (&node->token);
  3388. return REG_NOERROR;
  3389. }
  3390. /* Duplicate the node SRC, and return new node. This is a preorder
  3391. visit similar to the one implemented by the generic visitor, but
  3392. we need more infrastructure to maintain two parallel trees --- so,
  3393. it's easier to duplicate. */
  3394. static bin_tree_t *
  3395. duplicate_tree (const bin_tree_t *root, re_dfa_t *dfa)
  3396. {
  3397. const bin_tree_t *node;
  3398. bin_tree_t *dup_root;
  3399. bin_tree_t **p_new = &dup_root, *dup_node = root->parent;
  3400. for (node = root; ; )
  3401. {
  3402. /* Create a new tree and link it back to the current parent. */
  3403. *p_new = create_token_tree (dfa, NULL, NULL, &node->token);
  3404. if (*p_new == NULL)
  3405. return NULL;
  3406. (*p_new)->parent = dup_node;
  3407. (*p_new)->token.duplicated = 1;
  3408. dup_node = *p_new;
  3409. /* Go to the left node, or up and to the right. */
  3410. if (node->left)
  3411. {
  3412. node = node->left;
  3413. p_new = &dup_node->left;
  3414. }
  3415. else
  3416. {
  3417. const bin_tree_t *prev = NULL;
  3418. while (node->right == prev || node->right == NULL)
  3419. {
  3420. prev = node;
  3421. node = node->parent;
  3422. dup_node = dup_node->parent;
  3423. if (!node)
  3424. return dup_root;
  3425. }
  3426. node = node->right;
  3427. p_new = &dup_node->right;
  3428. }
  3429. }
  3430. }