regcomp.c 110 KB

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