regcomp.c 108 KB

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