regcomp.c 111 KB

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