php_pcre.c 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | https://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Author: Andrei Zmievski <andrei@php.net> |
  14. +----------------------------------------------------------------------+
  15. */
  16. #include "php.h"
  17. #include "php_ini.h"
  18. #include "php_globals.h"
  19. #include "php_pcre.h"
  20. #include "php_pcre_arginfo.h"
  21. #include "ext/standard/info.h"
  22. #include "ext/standard/basic_functions.h"
  23. #include "zend_smart_str.h"
  24. #include "SAPI.h"
  25. #include "ext/standard/php_string.h"
  26. #define PREG_PATTERN_ORDER 1
  27. #define PREG_SET_ORDER 2
  28. #define PREG_OFFSET_CAPTURE (1<<8)
  29. #define PREG_UNMATCHED_AS_NULL (1<<9)
  30. #define PREG_SPLIT_NO_EMPTY (1<<0)
  31. #define PREG_SPLIT_DELIM_CAPTURE (1<<1)
  32. #define PREG_SPLIT_OFFSET_CAPTURE (1<<2)
  33. #define PREG_REPLACE_EVAL (1<<0)
  34. #define PREG_GREP_INVERT (1<<0)
  35. #define PREG_JIT (1<<3)
  36. #define PCRE_CACHE_SIZE 4096
  37. struct _pcre_cache_entry {
  38. pcre2_code *re;
  39. uint32_t preg_options;
  40. uint32_t capture_count;
  41. uint32_t name_count;
  42. uint32_t compile_options;
  43. uint32_t refcount;
  44. };
  45. PHPAPI ZEND_DECLARE_MODULE_GLOBALS(pcre)
  46. #ifdef HAVE_PCRE_JIT_SUPPORT
  47. #define PCRE_JIT_STACK_MIN_SIZE (32 * 1024)
  48. #define PCRE_JIT_STACK_MAX_SIZE (192 * 1024)
  49. ZEND_TLS pcre2_jit_stack *jit_stack = NULL;
  50. #endif
  51. /* General context using (infallible) system allocator. */
  52. ZEND_TLS pcre2_general_context *gctx = NULL;
  53. /* These two are global per thread for now. Though it is possible to use these
  54. per pattern. Either one can copy it and use in pce, or one does no global
  55. contexts at all, but creates for every pce. */
  56. ZEND_TLS pcre2_compile_context *cctx = NULL;
  57. ZEND_TLS pcre2_match_context *mctx = NULL;
  58. ZEND_TLS pcre2_match_data *mdata = NULL;
  59. ZEND_TLS bool mdata_used = 0;
  60. ZEND_TLS uint8_t pcre2_init_ok = 0;
  61. #if defined(ZTS) && defined(HAVE_PCRE_JIT_SUPPORT)
  62. static MUTEX_T pcre_mt = NULL;
  63. #define php_pcre_mutex_alloc() \
  64. if (tsrm_is_main_thread() && !pcre_mt) pcre_mt = tsrm_mutex_alloc();
  65. #define php_pcre_mutex_free() \
  66. if (tsrm_is_main_thread() && pcre_mt) { tsrm_mutex_free(pcre_mt); pcre_mt = NULL; }
  67. #define php_pcre_mutex_lock() tsrm_mutex_lock(pcre_mt);
  68. #define php_pcre_mutex_unlock() tsrm_mutex_unlock(pcre_mt);
  69. #else
  70. #define php_pcre_mutex_alloc()
  71. #define php_pcre_mutex_free()
  72. #define php_pcre_mutex_lock()
  73. #define php_pcre_mutex_unlock()
  74. #endif
  75. ZEND_TLS HashTable char_tables;
  76. static void php_pcre_free_char_table(zval *data)
  77. {/*{{{*/
  78. void *ptr = Z_PTR_P(data);
  79. pefree(ptr, 1);
  80. }/*}}}*/
  81. static void pcre_handle_exec_error(int pcre_code) /* {{{ */
  82. {
  83. int preg_code = 0;
  84. switch (pcre_code) {
  85. case PCRE2_ERROR_MATCHLIMIT:
  86. preg_code = PHP_PCRE_BACKTRACK_LIMIT_ERROR;
  87. break;
  88. case PCRE2_ERROR_RECURSIONLIMIT:
  89. preg_code = PHP_PCRE_RECURSION_LIMIT_ERROR;
  90. break;
  91. case PCRE2_ERROR_BADUTFOFFSET:
  92. preg_code = PHP_PCRE_BAD_UTF8_OFFSET_ERROR;
  93. break;
  94. #ifdef HAVE_PCRE_JIT_SUPPORT
  95. case PCRE2_ERROR_JIT_STACKLIMIT:
  96. preg_code = PHP_PCRE_JIT_STACKLIMIT_ERROR;
  97. break;
  98. #endif
  99. default:
  100. if (pcre_code <= PCRE2_ERROR_UTF8_ERR1 && pcre_code >= PCRE2_ERROR_UTF8_ERR21) {
  101. preg_code = PHP_PCRE_BAD_UTF8_ERROR;
  102. } else {
  103. preg_code = PHP_PCRE_INTERNAL_ERROR;
  104. }
  105. break;
  106. }
  107. PCRE_G(error_code) = preg_code;
  108. }
  109. /* }}} */
  110. static const char *php_pcre_get_error_msg(php_pcre_error_code error_code) /* {{{ */
  111. {
  112. switch (error_code) {
  113. case PHP_PCRE_NO_ERROR:
  114. return "No error";
  115. case PHP_PCRE_INTERNAL_ERROR:
  116. return "Internal error";
  117. case PHP_PCRE_BAD_UTF8_ERROR:
  118. return "Malformed UTF-8 characters, possibly incorrectly encoded";
  119. case PHP_PCRE_BAD_UTF8_OFFSET_ERROR:
  120. return "The offset did not correspond to the beginning of a valid UTF-8 code point";
  121. case PHP_PCRE_BACKTRACK_LIMIT_ERROR:
  122. return "Backtrack limit exhausted";
  123. case PHP_PCRE_RECURSION_LIMIT_ERROR:
  124. return "Recursion limit exhausted";
  125. #ifdef HAVE_PCRE_JIT_SUPPORT
  126. case PHP_PCRE_JIT_STACKLIMIT_ERROR:
  127. return "JIT stack limit exhausted";
  128. #endif
  129. default:
  130. return "Unknown error";
  131. }
  132. }
  133. /* }}} */
  134. static void php_free_pcre_cache(zval *data) /* {{{ */
  135. {
  136. pcre_cache_entry *pce = (pcre_cache_entry *) Z_PTR_P(data);
  137. if (!pce) return;
  138. pcre2_code_free(pce->re);
  139. free(pce);
  140. }
  141. /* }}} */
  142. static void php_efree_pcre_cache(zval *data) /* {{{ */
  143. {
  144. pcre_cache_entry *pce = (pcre_cache_entry *) Z_PTR_P(data);
  145. if (!pce) return;
  146. pcre2_code_free(pce->re);
  147. efree(pce);
  148. }
  149. /* }}} */
  150. static void *php_pcre_malloc(PCRE2_SIZE size, void *data)
  151. {
  152. return pemalloc(size, 1);
  153. }
  154. static void php_pcre_free(void *block, void *data)
  155. {
  156. pefree(block, 1);
  157. }
  158. static void *php_pcre_emalloc(PCRE2_SIZE size, void *data)
  159. {
  160. return emalloc(size);
  161. }
  162. static void php_pcre_efree(void *block, void *data)
  163. {
  164. efree(block);
  165. }
  166. #ifdef PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK
  167. /* pcre 10.38 needs PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK, disabled by default */
  168. #define PHP_PCRE_DEFAULT_EXTRA_COPTIONS PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK
  169. #else
  170. #define PHP_PCRE_DEFAULT_EXTRA_COPTIONS 0
  171. #endif
  172. #define PHP_PCRE_PREALLOC_MDATA_SIZE 32
  173. static void php_pcre_init_pcre2(uint8_t jit)
  174. {/*{{{*/
  175. if (!gctx) {
  176. gctx = pcre2_general_context_create(php_pcre_malloc, php_pcre_free, NULL);
  177. if (!gctx) {
  178. pcre2_init_ok = 0;
  179. return;
  180. }
  181. }
  182. if (!cctx) {
  183. cctx = pcre2_compile_context_create(gctx);
  184. if (!cctx) {
  185. pcre2_init_ok = 0;
  186. return;
  187. }
  188. }
  189. pcre2_set_compile_extra_options(cctx, PHP_PCRE_DEFAULT_EXTRA_COPTIONS);
  190. if (!mctx) {
  191. mctx = pcre2_match_context_create(gctx);
  192. if (!mctx) {
  193. pcre2_init_ok = 0;
  194. return;
  195. }
  196. }
  197. #ifdef HAVE_PCRE_JIT_SUPPORT
  198. if (jit && !jit_stack) {
  199. jit_stack = pcre2_jit_stack_create(PCRE_JIT_STACK_MIN_SIZE, PCRE_JIT_STACK_MAX_SIZE, gctx);
  200. if (!jit_stack) {
  201. pcre2_init_ok = 0;
  202. return;
  203. }
  204. }
  205. #endif
  206. if (!mdata) {
  207. mdata = pcre2_match_data_create(PHP_PCRE_PREALLOC_MDATA_SIZE, gctx);
  208. if (!mdata) {
  209. pcre2_init_ok = 0;
  210. return;
  211. }
  212. }
  213. pcre2_init_ok = 1;
  214. }/*}}}*/
  215. static void php_pcre_shutdown_pcre2(void)
  216. {/*{{{*/
  217. if (gctx) {
  218. pcre2_general_context_free(gctx);
  219. gctx = NULL;
  220. }
  221. if (cctx) {
  222. pcre2_compile_context_free(cctx);
  223. cctx = NULL;
  224. }
  225. if (mctx) {
  226. pcre2_match_context_free(mctx);
  227. mctx = NULL;
  228. }
  229. #ifdef HAVE_PCRE_JIT_SUPPORT
  230. /* Stack may only be destroyed when no cached patterns
  231. possibly associated with it do exist. */
  232. if (jit_stack) {
  233. pcre2_jit_stack_free(jit_stack);
  234. jit_stack = NULL;
  235. }
  236. #endif
  237. if (mdata) {
  238. pcre2_match_data_free(mdata);
  239. mdata = NULL;
  240. }
  241. pcre2_init_ok = 0;
  242. }/*}}}*/
  243. static PHP_GINIT_FUNCTION(pcre) /* {{{ */
  244. {
  245. php_pcre_mutex_alloc();
  246. /* If we're on the CLI SAPI, there will only be one request, so we don't need the
  247. * cache to survive after RSHUTDOWN. */
  248. pcre_globals->per_request_cache = strcmp(sapi_module.name, "cli") == 0;
  249. if (!pcre_globals->per_request_cache) {
  250. zend_hash_init(&pcre_globals->pcre_cache, 0, NULL, php_free_pcre_cache, 1);
  251. }
  252. pcre_globals->backtrack_limit = 0;
  253. pcre_globals->recursion_limit = 0;
  254. pcre_globals->error_code = PHP_PCRE_NO_ERROR;
  255. ZVAL_UNDEF(&pcre_globals->unmatched_null_pair);
  256. ZVAL_UNDEF(&pcre_globals->unmatched_empty_pair);
  257. #ifdef HAVE_PCRE_JIT_SUPPORT
  258. pcre_globals->jit = 1;
  259. #endif
  260. php_pcre_init_pcre2(1);
  261. zend_hash_init(&char_tables, 1, NULL, php_pcre_free_char_table, 1);
  262. }
  263. /* }}} */
  264. static PHP_GSHUTDOWN_FUNCTION(pcre) /* {{{ */
  265. {
  266. if (!pcre_globals->per_request_cache) {
  267. zend_hash_destroy(&pcre_globals->pcre_cache);
  268. }
  269. php_pcre_shutdown_pcre2();
  270. zend_hash_destroy(&char_tables);
  271. php_pcre_mutex_free();
  272. }
  273. /* }}} */
  274. static PHP_INI_MH(OnUpdateBacktrackLimit)
  275. {/*{{{*/
  276. OnUpdateLong(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  277. if (mctx) {
  278. pcre2_set_match_limit(mctx, (uint32_t)PCRE_G(backtrack_limit));
  279. }
  280. return SUCCESS;
  281. }/*}}}*/
  282. static PHP_INI_MH(OnUpdateRecursionLimit)
  283. {/*{{{*/
  284. OnUpdateLong(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  285. if (mctx) {
  286. pcre2_set_depth_limit(mctx, (uint32_t)PCRE_G(recursion_limit));
  287. }
  288. return SUCCESS;
  289. }/*}}}*/
  290. #ifdef HAVE_PCRE_JIT_SUPPORT
  291. static PHP_INI_MH(OnUpdateJit)
  292. {/*{{{*/
  293. OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  294. if (PCRE_G(jit) && jit_stack) {
  295. pcre2_jit_stack_assign(mctx, NULL, jit_stack);
  296. } else {
  297. pcre2_jit_stack_assign(mctx, NULL, NULL);
  298. }
  299. return SUCCESS;
  300. }/*}}}*/
  301. #endif
  302. PHP_INI_BEGIN()
  303. STD_PHP_INI_ENTRY("pcre.backtrack_limit", "1000000", PHP_INI_ALL, OnUpdateBacktrackLimit, backtrack_limit, zend_pcre_globals, pcre_globals)
  304. STD_PHP_INI_ENTRY("pcre.recursion_limit", "100000", PHP_INI_ALL, OnUpdateRecursionLimit, recursion_limit, zend_pcre_globals, pcre_globals)
  305. #ifdef HAVE_PCRE_JIT_SUPPORT
  306. STD_PHP_INI_ENTRY("pcre.jit", "1", PHP_INI_ALL, OnUpdateJit, jit, zend_pcre_globals, pcre_globals)
  307. #endif
  308. PHP_INI_END()
  309. static char *_pcre2_config_str(uint32_t what)
  310. {/*{{{*/
  311. int len = pcre2_config(what, NULL);
  312. char *ret = (char *) malloc(len + 1);
  313. len = pcre2_config(what, ret);
  314. if (!len) {
  315. free(ret);
  316. return NULL;
  317. }
  318. return ret;
  319. }/*}}}*/
  320. /* {{{ PHP_MINFO_FUNCTION(pcre) */
  321. static PHP_MINFO_FUNCTION(pcre)
  322. {
  323. #ifdef HAVE_PCRE_JIT_SUPPORT
  324. uint32_t flag = 0;
  325. char *jit_target = _pcre2_config_str(PCRE2_CONFIG_JITTARGET);
  326. #endif
  327. char *version = _pcre2_config_str(PCRE2_CONFIG_VERSION);
  328. char *unicode = _pcre2_config_str(PCRE2_CONFIG_UNICODE_VERSION);
  329. php_info_print_table_start();
  330. php_info_print_table_row(2, "PCRE (Perl Compatible Regular Expressions) Support", "enabled" );
  331. php_info_print_table_row(2, "PCRE Library Version", version);
  332. free(version);
  333. php_info_print_table_row(2, "PCRE Unicode Version", unicode);
  334. free(unicode);
  335. #ifdef HAVE_PCRE_JIT_SUPPORT
  336. if (!pcre2_config(PCRE2_CONFIG_JIT, &flag)) {
  337. php_info_print_table_row(2, "PCRE JIT Support", flag ? "enabled" : "disabled");
  338. } else {
  339. php_info_print_table_row(2, "PCRE JIT Support", "unknown" );
  340. }
  341. if (jit_target) {
  342. php_info_print_table_row(2, "PCRE JIT Target", jit_target);
  343. }
  344. free(jit_target);
  345. #else
  346. php_info_print_table_row(2, "PCRE JIT Support", "not compiled in" );
  347. #endif
  348. #ifdef HAVE_PCRE_VALGRIND_SUPPORT
  349. php_info_print_table_row(2, "PCRE Valgrind Support", "enabled" );
  350. #endif
  351. php_info_print_table_end();
  352. DISPLAY_INI_ENTRIES();
  353. }
  354. /* }}} */
  355. /* {{{ PHP_MINIT_FUNCTION(pcre) */
  356. static PHP_MINIT_FUNCTION(pcre)
  357. {
  358. char *version;
  359. #ifdef HAVE_PCRE_JIT_SUPPORT
  360. if (UNEXPECTED(!pcre2_init_ok)) {
  361. /* Retry. */
  362. php_pcre_init_pcre2(PCRE_G(jit));
  363. if (!pcre2_init_ok) {
  364. return FAILURE;
  365. }
  366. }
  367. #endif
  368. REGISTER_INI_ENTRIES();
  369. REGISTER_LONG_CONSTANT("PREG_PATTERN_ORDER", PREG_PATTERN_ORDER, CONST_CS | CONST_PERSISTENT);
  370. REGISTER_LONG_CONSTANT("PREG_SET_ORDER", PREG_SET_ORDER, CONST_CS | CONST_PERSISTENT);
  371. REGISTER_LONG_CONSTANT("PREG_OFFSET_CAPTURE", PREG_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
  372. REGISTER_LONG_CONSTANT("PREG_UNMATCHED_AS_NULL", PREG_UNMATCHED_AS_NULL, CONST_CS | CONST_PERSISTENT);
  373. REGISTER_LONG_CONSTANT("PREG_SPLIT_NO_EMPTY", PREG_SPLIT_NO_EMPTY, CONST_CS | CONST_PERSISTENT);
  374. REGISTER_LONG_CONSTANT("PREG_SPLIT_DELIM_CAPTURE", PREG_SPLIT_DELIM_CAPTURE, CONST_CS | CONST_PERSISTENT);
  375. REGISTER_LONG_CONSTANT("PREG_SPLIT_OFFSET_CAPTURE", PREG_SPLIT_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
  376. REGISTER_LONG_CONSTANT("PREG_GREP_INVERT", PREG_GREP_INVERT, CONST_CS | CONST_PERSISTENT);
  377. REGISTER_LONG_CONSTANT("PREG_NO_ERROR", PHP_PCRE_NO_ERROR, CONST_CS | CONST_PERSISTENT);
  378. REGISTER_LONG_CONSTANT("PREG_INTERNAL_ERROR", PHP_PCRE_INTERNAL_ERROR, CONST_CS | CONST_PERSISTENT);
  379. REGISTER_LONG_CONSTANT("PREG_BACKTRACK_LIMIT_ERROR", PHP_PCRE_BACKTRACK_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
  380. REGISTER_LONG_CONSTANT("PREG_RECURSION_LIMIT_ERROR", PHP_PCRE_RECURSION_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
  381. REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_ERROR", PHP_PCRE_BAD_UTF8_ERROR, CONST_CS | CONST_PERSISTENT);
  382. REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_OFFSET_ERROR", PHP_PCRE_BAD_UTF8_OFFSET_ERROR, CONST_CS | CONST_PERSISTENT);
  383. REGISTER_LONG_CONSTANT("PREG_JIT_STACKLIMIT_ERROR", PHP_PCRE_JIT_STACKLIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
  384. version = _pcre2_config_str(PCRE2_CONFIG_VERSION);
  385. REGISTER_STRING_CONSTANT("PCRE_VERSION", version, CONST_CS | CONST_PERSISTENT);
  386. free(version);
  387. REGISTER_LONG_CONSTANT("PCRE_VERSION_MAJOR", PCRE2_MAJOR, CONST_CS | CONST_PERSISTENT);
  388. REGISTER_LONG_CONSTANT("PCRE_VERSION_MINOR", PCRE2_MINOR, CONST_CS | CONST_PERSISTENT);
  389. #ifdef HAVE_PCRE_JIT_SUPPORT
  390. REGISTER_BOOL_CONSTANT("PCRE_JIT_SUPPORT", 1, CONST_CS | CONST_PERSISTENT);
  391. #else
  392. REGISTER_BOOL_CONSTANT("PCRE_JIT_SUPPORT", 0, CONST_CS | CONST_PERSISTENT);
  393. #endif
  394. return SUCCESS;
  395. }
  396. /* }}} */
  397. /* {{{ PHP_MSHUTDOWN_FUNCTION(pcre) */
  398. static PHP_MSHUTDOWN_FUNCTION(pcre)
  399. {
  400. UNREGISTER_INI_ENTRIES();
  401. return SUCCESS;
  402. }
  403. /* }}} */
  404. /* {{{ PHP_RINIT_FUNCTION(pcre) */
  405. static PHP_RINIT_FUNCTION(pcre)
  406. {
  407. #ifdef HAVE_PCRE_JIT_SUPPORT
  408. if (UNEXPECTED(!pcre2_init_ok)) {
  409. /* Retry. */
  410. php_pcre_mutex_lock();
  411. php_pcre_init_pcre2(PCRE_G(jit));
  412. if (!pcre2_init_ok) {
  413. php_pcre_mutex_unlock();
  414. return FAILURE;
  415. }
  416. php_pcre_mutex_unlock();
  417. }
  418. mdata_used = 0;
  419. #endif
  420. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  421. PCRE_G(gctx_zmm) = pcre2_general_context_create(php_pcre_emalloc, php_pcre_efree, NULL);
  422. if (!PCRE_G(gctx_zmm)) {
  423. return FAILURE;
  424. }
  425. if (PCRE_G(per_request_cache)) {
  426. zend_hash_init(&PCRE_G(pcre_cache), 0, NULL, php_efree_pcre_cache, 0);
  427. }
  428. return SUCCESS;
  429. }
  430. /* }}} */
  431. static PHP_RSHUTDOWN_FUNCTION(pcre)
  432. {
  433. pcre2_general_context_free(PCRE_G(gctx_zmm));
  434. PCRE_G(gctx_zmm) = NULL;
  435. if (PCRE_G(per_request_cache)) {
  436. zend_hash_destroy(&PCRE_G(pcre_cache));
  437. }
  438. zval_ptr_dtor(&PCRE_G(unmatched_null_pair));
  439. zval_ptr_dtor(&PCRE_G(unmatched_empty_pair));
  440. ZVAL_UNDEF(&PCRE_G(unmatched_null_pair));
  441. ZVAL_UNDEF(&PCRE_G(unmatched_empty_pair));
  442. return SUCCESS;
  443. }
  444. /* {{{ static pcre_clean_cache */
  445. static int pcre_clean_cache(zval *data, void *arg)
  446. {
  447. pcre_cache_entry *pce = (pcre_cache_entry *) Z_PTR_P(data);
  448. int *num_clean = (int *)arg;
  449. if (*num_clean > 0 && !pce->refcount) {
  450. (*num_clean)--;
  451. return ZEND_HASH_APPLY_REMOVE;
  452. } else {
  453. return ZEND_HASH_APPLY_KEEP;
  454. }
  455. }
  456. /* }}} */
  457. static void free_subpats_table(zend_string **subpat_names, uint32_t num_subpats) {
  458. uint32_t i;
  459. for (i = 0; i < num_subpats; i++) {
  460. if (subpat_names[i]) {
  461. zend_string_release(subpat_names[i]);
  462. }
  463. }
  464. efree(subpat_names);
  465. }
  466. /* {{{ static make_subpats_table */
  467. static zend_string **make_subpats_table(uint32_t num_subpats, pcre_cache_entry *pce)
  468. {
  469. uint32_t name_cnt = pce->name_count, name_size, ni = 0;
  470. char *name_table;
  471. zend_string **subpat_names;
  472. int rc1, rc2;
  473. rc1 = pcre2_pattern_info(pce->re, PCRE2_INFO_NAMETABLE, &name_table);
  474. rc2 = pcre2_pattern_info(pce->re, PCRE2_INFO_NAMEENTRYSIZE, &name_size);
  475. if (rc1 < 0 || rc2 < 0) {
  476. php_error_docref(NULL, E_WARNING, "Internal pcre2_pattern_info() error %d", rc1 < 0 ? rc1 : rc2);
  477. return NULL;
  478. }
  479. subpat_names = ecalloc(num_subpats, sizeof(zend_string *));
  480. while (ni++ < name_cnt) {
  481. unsigned short name_idx = 0x100 * (unsigned char)name_table[0] + (unsigned char)name_table[1];
  482. const char *name = name_table + 2;
  483. subpat_names[name_idx] = zend_string_init(name, strlen(name), 0);
  484. if (is_numeric_string(ZSTR_VAL(subpat_names[name_idx]), ZSTR_LEN(subpat_names[name_idx]), NULL, NULL, 0) > 0) {
  485. php_error_docref(NULL, E_WARNING, "Numeric named subpatterns are not allowed");
  486. free_subpats_table(subpat_names, num_subpats);
  487. return NULL;
  488. }
  489. name_table += name_size;
  490. }
  491. return subpat_names;
  492. }
  493. /* }}} */
  494. /* {{{ static calculate_unit_length */
  495. /* Calculates the byte length of the next character. Assumes valid UTF-8 for PCRE2_UTF. */
  496. static zend_always_inline size_t calculate_unit_length(pcre_cache_entry *pce, const char *start)
  497. {
  498. size_t unit_len;
  499. if (pce->compile_options & PCRE2_UTF) {
  500. const char *end = start;
  501. /* skip continuation bytes */
  502. while ((*++end & 0xC0) == 0x80);
  503. unit_len = end - start;
  504. } else {
  505. unit_len = 1;
  506. }
  507. return unit_len;
  508. }
  509. /* }}} */
  510. /* {{{ pcre_get_compiled_regex_cache */
  511. PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache_ex(zend_string *regex, int locale_aware)
  512. {
  513. pcre2_code *re = NULL;
  514. #if 10 == PCRE2_MAJOR && 37 == PCRE2_MINOR && !HAVE_BUNDLED_PCRE
  515. uint32_t coptions = PCRE2_NO_START_OPTIMIZE;
  516. #else
  517. uint32_t coptions = 0;
  518. #endif
  519. PCRE2_UCHAR error[128];
  520. PCRE2_SIZE erroffset;
  521. int errnumber;
  522. char delimiter;
  523. char start_delimiter;
  524. char end_delimiter;
  525. char *p, *pp;
  526. char *pattern;
  527. size_t pattern_len;
  528. uint32_t poptions = 0;
  529. const uint8_t *tables = NULL;
  530. zval *zv;
  531. pcre_cache_entry new_entry;
  532. int rc;
  533. zend_string *key;
  534. pcre_cache_entry *ret;
  535. if (locale_aware && BG(ctype_string)) {
  536. key = zend_string_concat2(
  537. ZSTR_VAL(BG(ctype_string)), ZSTR_LEN(BG(ctype_string)),
  538. ZSTR_VAL(regex), ZSTR_LEN(regex));
  539. } else {
  540. key = regex;
  541. }
  542. /* Try to lookup the cached regex entry, and if successful, just pass
  543. back the compiled pattern, otherwise go on and compile it. */
  544. zv = zend_hash_find(&PCRE_G(pcre_cache), key);
  545. if (zv) {
  546. if (key != regex) {
  547. zend_string_release_ex(key, 0);
  548. }
  549. return (pcre_cache_entry*)Z_PTR_P(zv);
  550. }
  551. p = ZSTR_VAL(regex);
  552. /* Parse through the leading whitespace, and display a warning if we
  553. get to the end without encountering a delimiter. */
  554. while (isspace((int)*(unsigned char *)p)) p++;
  555. if (*p == 0) {
  556. if (key != regex) {
  557. zend_string_release_ex(key, 0);
  558. }
  559. php_error_docref(NULL, E_WARNING,
  560. p < ZSTR_VAL(regex) + ZSTR_LEN(regex) ? "Null byte in regex" : "Empty regular expression");
  561. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  562. return NULL;
  563. }
  564. /* Get the delimiter and display a warning if it is alphanumeric
  565. or a backslash. */
  566. delimiter = *p++;
  567. if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') {
  568. if (key != regex) {
  569. zend_string_release_ex(key, 0);
  570. }
  571. php_error_docref(NULL,E_WARNING, "Delimiter must not be alphanumeric or backslash");
  572. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  573. return NULL;
  574. }
  575. start_delimiter = delimiter;
  576. if ((pp = strchr("([{< )]}> )]}>", delimiter)))
  577. delimiter = pp[5];
  578. end_delimiter = delimiter;
  579. pp = p;
  580. if (start_delimiter == end_delimiter) {
  581. /* We need to iterate through the pattern, searching for the ending delimiter,
  582. but skipping the backslashed delimiters. If the ending delimiter is not
  583. found, display a warning. */
  584. while (*pp != 0) {
  585. if (*pp == '\\' && pp[1] != 0) pp++;
  586. else if (*pp == delimiter)
  587. break;
  588. pp++;
  589. }
  590. } else {
  591. /* We iterate through the pattern, searching for the matching ending
  592. * delimiter. For each matching starting delimiter, we increment nesting
  593. * level, and decrement it for each matching ending delimiter. If we
  594. * reach the end of the pattern without matching, display a warning.
  595. */
  596. int brackets = 1; /* brackets nesting level */
  597. while (*pp != 0) {
  598. if (*pp == '\\' && pp[1] != 0) pp++;
  599. else if (*pp == end_delimiter && --brackets <= 0)
  600. break;
  601. else if (*pp == start_delimiter)
  602. brackets++;
  603. pp++;
  604. }
  605. }
  606. if (*pp == 0) {
  607. if (key != regex) {
  608. zend_string_release_ex(key, 0);
  609. }
  610. if (pp < ZSTR_VAL(regex) + ZSTR_LEN(regex)) {
  611. php_error_docref(NULL,E_WARNING, "Null byte in regex");
  612. } else if (start_delimiter == end_delimiter) {
  613. php_error_docref(NULL,E_WARNING, "No ending delimiter '%c' found", delimiter);
  614. } else {
  615. php_error_docref(NULL,E_WARNING, "No ending matching delimiter '%c' found", delimiter);
  616. }
  617. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  618. return NULL;
  619. }
  620. /* Make a copy of the actual pattern. */
  621. pattern_len = pp - p;
  622. pattern = estrndup(p, pattern_len);
  623. /* Move on to the options */
  624. pp++;
  625. /* Parse through the options, setting appropriate flags. Display
  626. a warning if we encounter an unknown modifier. */
  627. while (pp < ZSTR_VAL(regex) + ZSTR_LEN(regex)) {
  628. switch (*pp++) {
  629. /* Perl compatible options */
  630. case 'i': coptions |= PCRE2_CASELESS; break;
  631. case 'm': coptions |= PCRE2_MULTILINE; break;
  632. case 's': coptions |= PCRE2_DOTALL; break;
  633. case 'x': coptions |= PCRE2_EXTENDED; break;
  634. /* PCRE specific options */
  635. case 'A': coptions |= PCRE2_ANCHORED; break;
  636. case 'D': coptions |= PCRE2_DOLLAR_ENDONLY;break;
  637. case 'S': /* Pass. */ break;
  638. case 'X': /* Pass. */ break;
  639. case 'U': coptions |= PCRE2_UNGREEDY; break;
  640. case 'u': coptions |= PCRE2_UTF;
  641. /* In PCRE, by default, \d, \D, \s, \S, \w, and \W recognize only ASCII
  642. characters, even in UTF-8 mode. However, this can be changed by setting
  643. the PCRE2_UCP option. */
  644. #ifdef PCRE2_UCP
  645. coptions |= PCRE2_UCP;
  646. #endif
  647. break;
  648. case 'J': coptions |= PCRE2_DUPNAMES; break;
  649. /* Custom preg options */
  650. case 'e': poptions |= PREG_REPLACE_EVAL; break;
  651. case ' ':
  652. case '\n':
  653. case '\r':
  654. break;
  655. default:
  656. if (pp[-1]) {
  657. php_error_docref(NULL,E_WARNING, "Unknown modifier '%c'", pp[-1]);
  658. } else {
  659. php_error_docref(NULL,E_WARNING, "Null byte in regex");
  660. }
  661. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  662. efree(pattern);
  663. if (key != regex) {
  664. zend_string_release_ex(key, 0);
  665. }
  666. return NULL;
  667. }
  668. }
  669. if (poptions & PREG_REPLACE_EVAL) {
  670. php_error_docref(NULL, E_WARNING, "The /e modifier is no longer supported, use preg_replace_callback instead");
  671. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  672. efree(pattern);
  673. if (key != regex) {
  674. zend_string_release_ex(key, 0);
  675. }
  676. return NULL;
  677. }
  678. if (key != regex) {
  679. tables = (uint8_t *)zend_hash_find_ptr(&char_tables, BG(ctype_string));
  680. if (!tables) {
  681. zend_string *_k;
  682. tables = pcre2_maketables(gctx);
  683. if (UNEXPECTED(!tables)) {
  684. php_error_docref(NULL,E_WARNING, "Failed to generate locale character tables");
  685. pcre_handle_exec_error(PCRE2_ERROR_NOMEMORY);
  686. zend_string_release_ex(key, 0);
  687. efree(pattern);
  688. return NULL;
  689. }
  690. _k = zend_string_init(ZSTR_VAL(BG(ctype_string)), ZSTR_LEN(BG(ctype_string)), 1);
  691. GC_MAKE_PERSISTENT_LOCAL(_k);
  692. zend_hash_add_ptr(&char_tables, _k, (void *)tables);
  693. zend_string_release(_k);
  694. }
  695. }
  696. pcre2_set_character_tables(cctx, tables);
  697. /* Compile pattern and display a warning if compilation failed. */
  698. re = pcre2_compile((PCRE2_SPTR)pattern, pattern_len, coptions, &errnumber, &erroffset, cctx);
  699. if (re == NULL) {
  700. if (key != regex) {
  701. zend_string_release_ex(key, 0);
  702. }
  703. pcre2_get_error_message(errnumber, error, sizeof(error));
  704. php_error_docref(NULL,E_WARNING, "Compilation failed: %s at offset %zu", error, erroffset);
  705. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  706. efree(pattern);
  707. return NULL;
  708. }
  709. #ifdef HAVE_PCRE_JIT_SUPPORT
  710. if (PCRE_G(jit)) {
  711. /* Enable PCRE JIT compiler */
  712. rc = pcre2_jit_compile(re, PCRE2_JIT_COMPLETE);
  713. if (EXPECTED(rc >= 0)) {
  714. size_t jit_size = 0;
  715. if (!pcre2_pattern_info(re, PCRE2_INFO_JITSIZE, &jit_size) && jit_size > 0) {
  716. poptions |= PREG_JIT;
  717. }
  718. } else if (rc == PCRE2_ERROR_NOMEMORY) {
  719. php_error_docref(NULL, E_WARNING,
  720. "Allocation of JIT memory failed, PCRE JIT will be disabled. "
  721. "This is likely caused by security restrictions. "
  722. "Either grant PHP permission to allocate executable memory, or set pcre.jit=0");
  723. PCRE_G(jit) = 0;
  724. } else {
  725. pcre2_get_error_message(rc, error, sizeof(error));
  726. php_error_docref(NULL, E_WARNING, "JIT compilation failed: %s", error);
  727. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  728. }
  729. }
  730. #endif
  731. efree(pattern);
  732. /*
  733. * If we reached cache limit, clean out the items from the head of the list;
  734. * these are supposedly the oldest ones (but not necessarily the least used
  735. * ones).
  736. */
  737. if (zend_hash_num_elements(&PCRE_G(pcre_cache)) == PCRE_CACHE_SIZE) {
  738. int num_clean = PCRE_CACHE_SIZE / 8;
  739. zend_hash_apply_with_argument(&PCRE_G(pcre_cache), pcre_clean_cache, &num_clean);
  740. }
  741. /* Store the compiled pattern and extra info in the cache. */
  742. new_entry.re = re;
  743. new_entry.preg_options = poptions;
  744. new_entry.compile_options = coptions;
  745. new_entry.refcount = 0;
  746. rc = pcre2_pattern_info(re, PCRE2_INFO_CAPTURECOUNT, &new_entry.capture_count);
  747. if (rc < 0) {
  748. if (key != regex) {
  749. zend_string_release_ex(key, 0);
  750. }
  751. php_error_docref(NULL, E_WARNING, "Internal pcre2_pattern_info() error %d", rc);
  752. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  753. return NULL;
  754. }
  755. rc = pcre2_pattern_info(re, PCRE2_INFO_NAMECOUNT, &new_entry.name_count);
  756. if (rc < 0) {
  757. if (key != regex) {
  758. zend_string_release_ex(key, 0);
  759. }
  760. php_error_docref(NULL, E_WARNING, "Internal pcre_pattern_info() error %d", rc);
  761. pcre_handle_exec_error(PCRE2_ERROR_INTERNAL);
  762. return NULL;
  763. }
  764. /*
  765. * Interned strings are not duplicated when stored in HashTable,
  766. * but all the interned strings created during HTTP request are removed
  767. * at end of request. However PCRE_G(pcre_cache) must be consistent
  768. * on the next request as well. So we disable usage of interned strings
  769. * as hash keys especually for this table.
  770. * See bug #63180
  771. */
  772. if (!(GC_FLAGS(key) & IS_STR_PERMANENT) && !PCRE_G(per_request_cache)) {
  773. zend_string *str = zend_string_init(ZSTR_VAL(key), ZSTR_LEN(key), 1);
  774. GC_MAKE_PERSISTENT_LOCAL(str);
  775. ret = zend_hash_add_new_mem(&PCRE_G(pcre_cache), str, &new_entry, sizeof(pcre_cache_entry));
  776. zend_string_release(str);
  777. } else {
  778. ret = zend_hash_add_new_mem(&PCRE_G(pcre_cache), key, &new_entry, sizeof(pcre_cache_entry));
  779. }
  780. if (key != regex) {
  781. zend_string_release_ex(key, 0);
  782. }
  783. return ret;
  784. }
  785. /* }}} */
  786. /* {{{ pcre_get_compiled_regex_cache */
  787. PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache(zend_string *regex)
  788. {
  789. return pcre_get_compiled_regex_cache_ex(regex, 1);
  790. }
  791. /* }}} */
  792. /* {{{ pcre_get_compiled_regex */
  793. PHPAPI pcre2_code *pcre_get_compiled_regex(zend_string *regex, uint32_t *capture_count)
  794. {
  795. pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex);
  796. if (capture_count) {
  797. *capture_count = pce ? pce->capture_count : 0;
  798. }
  799. return pce ? pce->re : NULL;
  800. }
  801. /* }}} */
  802. /* {{{ pcre_get_compiled_regex_ex */
  803. PHPAPI pcre2_code* pcre_get_compiled_regex_ex(zend_string *regex, uint32_t *capture_count, uint32_t *preg_options, uint32_t *compile_options)
  804. {
  805. pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex);
  806. if (preg_options) {
  807. *preg_options = pce ? pce->preg_options : 0;
  808. }
  809. if (compile_options) {
  810. *compile_options = pce ? pce->compile_options : 0;
  811. }
  812. if (capture_count) {
  813. *capture_count = pce ? pce->capture_count : 0;
  814. }
  815. return pce ? pce->re : NULL;
  816. }
  817. /* }}} */
  818. /* XXX For the cases where it's only about match yes/no and no capture
  819. required, perhaps just a minimum sized data would suffice. */
  820. PHPAPI pcre2_match_data *php_pcre_create_match_data(uint32_t capture_count, pcre2_code *re)
  821. {/*{{{*/
  822. assert(NULL != re);
  823. if (EXPECTED(!mdata_used)) {
  824. int rc = 0;
  825. if (!capture_count) {
  826. /* As we deal with a non cached pattern, no other way to gather this info. */
  827. rc = pcre2_pattern_info(re, PCRE2_INFO_CAPTURECOUNT, &capture_count);
  828. }
  829. if (rc >= 0 && capture_count + 1 <= PHP_PCRE_PREALLOC_MDATA_SIZE) {
  830. mdata_used = 1;
  831. return mdata;
  832. }
  833. }
  834. return pcre2_match_data_create_from_pattern(re, gctx);
  835. }/*}}}*/
  836. PHPAPI void php_pcre_free_match_data(pcre2_match_data *match_data)
  837. {/*{{{*/
  838. if (UNEXPECTED(match_data != mdata)) {
  839. pcre2_match_data_free(match_data);
  840. } else {
  841. mdata_used = 0;
  842. }
  843. }/*}}}*/
  844. static void init_unmatched_null_pair(void) {
  845. zval val1, val2;
  846. ZVAL_NULL(&val1);
  847. ZVAL_LONG(&val2, -1);
  848. ZVAL_ARR(&PCRE_G(unmatched_null_pair), zend_new_pair(&val1, &val2));
  849. }
  850. static void init_unmatched_empty_pair(void) {
  851. zval val1, val2;
  852. ZVAL_EMPTY_STRING(&val1);
  853. ZVAL_LONG(&val2, -1);
  854. ZVAL_ARR(&PCRE_G(unmatched_empty_pair), zend_new_pair(&val1, &val2));
  855. }
  856. static zend_always_inline void populate_match_value_str(
  857. zval *val, const char *subject, PCRE2_SIZE start_offset, PCRE2_SIZE end_offset) {
  858. ZVAL_STRINGL_FAST(val, subject + start_offset, end_offset - start_offset);
  859. }
  860. static inline void populate_match_value(
  861. zval *val, const char *subject, PCRE2_SIZE start_offset, PCRE2_SIZE end_offset,
  862. uint32_t unmatched_as_null) {
  863. if (PCRE2_UNSET == start_offset) {
  864. if (unmatched_as_null) {
  865. ZVAL_NULL(val);
  866. } else {
  867. ZVAL_EMPTY_STRING(val);
  868. }
  869. } else {
  870. populate_match_value_str(val, subject, start_offset, end_offset);
  871. }
  872. }
  873. static inline void add_named(
  874. zval *subpats, zend_string *name, zval *val, bool unmatched) {
  875. /* If the DUPNAMES option is used, multiple subpatterns might have the same name.
  876. * In this case we want to preserve the one that actually has a value. */
  877. if (!unmatched) {
  878. zend_hash_update(Z_ARRVAL_P(subpats), name, val);
  879. } else {
  880. if (!zend_hash_add(Z_ARRVAL_P(subpats), name, val)) {
  881. return;
  882. }
  883. }
  884. Z_TRY_ADDREF_P(val);
  885. }
  886. /* {{{ add_offset_pair */
  887. static inline void add_offset_pair(
  888. zval *result, const char *subject, PCRE2_SIZE start_offset, PCRE2_SIZE end_offset,
  889. zend_string *name, uint32_t unmatched_as_null)
  890. {
  891. zval match_pair;
  892. /* Add (match, offset) to the return value */
  893. if (PCRE2_UNSET == start_offset) {
  894. if (unmatched_as_null) {
  895. if (Z_ISUNDEF(PCRE_G(unmatched_null_pair))) {
  896. init_unmatched_null_pair();
  897. }
  898. ZVAL_COPY(&match_pair, &PCRE_G(unmatched_null_pair));
  899. } else {
  900. if (Z_ISUNDEF(PCRE_G(unmatched_empty_pair))) {
  901. init_unmatched_empty_pair();
  902. }
  903. ZVAL_COPY(&match_pair, &PCRE_G(unmatched_empty_pair));
  904. }
  905. } else {
  906. zval val1, val2;
  907. populate_match_value_str(&val1, subject, start_offset, end_offset);
  908. ZVAL_LONG(&val2, start_offset);
  909. ZVAL_ARR(&match_pair, zend_new_pair(&val1, &val2));
  910. }
  911. if (name) {
  912. add_named(result, name, &match_pair, start_offset == PCRE2_UNSET);
  913. }
  914. zend_hash_next_index_insert(Z_ARRVAL_P(result), &match_pair);
  915. }
  916. /* }}} */
  917. static void populate_subpat_array(
  918. zval *subpats, const char *subject, PCRE2_SIZE *offsets, zend_string **subpat_names,
  919. uint32_t num_subpats, int count, const PCRE2_SPTR mark, zend_long flags) {
  920. bool offset_capture = (flags & PREG_OFFSET_CAPTURE) != 0;
  921. bool unmatched_as_null = (flags & PREG_UNMATCHED_AS_NULL) != 0;
  922. zval val;
  923. int i;
  924. if (subpat_names) {
  925. if (offset_capture) {
  926. for (i = 0; i < count; i++) {
  927. add_offset_pair(
  928. subpats, subject, offsets[2*i], offsets[2*i+1],
  929. subpat_names[i], unmatched_as_null);
  930. }
  931. if (unmatched_as_null) {
  932. for (i = count; i < num_subpats; i++) {
  933. add_offset_pair(subpats, NULL, PCRE2_UNSET, PCRE2_UNSET, subpat_names[i], 1);
  934. }
  935. }
  936. } else {
  937. for (i = 0; i < count; i++) {
  938. populate_match_value(
  939. &val, subject, offsets[2*i], offsets[2*i+1], unmatched_as_null);
  940. if (subpat_names[i]) {
  941. add_named(subpats, subpat_names[i], &val, offsets[2*i] == PCRE2_UNSET);
  942. }
  943. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &val);
  944. }
  945. if (unmatched_as_null) {
  946. for (i = count; i < num_subpats; i++) {
  947. ZVAL_NULL(&val);
  948. if (subpat_names[i]) {
  949. zend_hash_add(Z_ARRVAL_P(subpats), subpat_names[i], &val);
  950. }
  951. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &val);
  952. }
  953. }
  954. }
  955. } else {
  956. if (offset_capture) {
  957. for (i = 0; i < count; i++) {
  958. add_offset_pair(
  959. subpats, subject, offsets[2*i], offsets[2*i+1], NULL, unmatched_as_null);
  960. }
  961. if (unmatched_as_null) {
  962. for (i = count; i < num_subpats; i++) {
  963. add_offset_pair(subpats, NULL, PCRE2_UNSET, PCRE2_UNSET, NULL, 1);
  964. }
  965. }
  966. } else {
  967. for (i = 0; i < count; i++) {
  968. populate_match_value(
  969. &val, subject, offsets[2*i], offsets[2*i+1], unmatched_as_null);
  970. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &val);
  971. }
  972. if (unmatched_as_null) {
  973. for (i = count; i < num_subpats; i++) {
  974. add_next_index_null(subpats);
  975. }
  976. }
  977. }
  978. }
  979. /* Add MARK, if available */
  980. if (mark) {
  981. add_assoc_string_ex(subpats, "MARK", sizeof("MARK") - 1, (char *)mark);
  982. }
  983. }
  984. static void php_do_pcre_match(INTERNAL_FUNCTION_PARAMETERS, int global) /* {{{ */
  985. {
  986. /* parameters */
  987. zend_string *regex; /* Regular expression */
  988. zend_string *subject; /* String to match against */
  989. pcre_cache_entry *pce; /* Compiled regular expression */
  990. zval *subpats = NULL; /* Array for subpatterns */
  991. zend_long flags = 0; /* Match control flags */
  992. zend_long start_offset = 0; /* Where the new search starts */
  993. ZEND_PARSE_PARAMETERS_START(2, 5)
  994. Z_PARAM_STR(regex)
  995. Z_PARAM_STR(subject)
  996. Z_PARAM_OPTIONAL
  997. Z_PARAM_ZVAL(subpats)
  998. Z_PARAM_LONG(flags)
  999. Z_PARAM_LONG(start_offset)
  1000. ZEND_PARSE_PARAMETERS_END();
  1001. /* Compile regex or get it from cache. */
  1002. if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
  1003. RETURN_FALSE;
  1004. }
  1005. pce->refcount++;
  1006. php_pcre_match_impl(pce, subject, return_value, subpats,
  1007. global, ZEND_NUM_ARGS() >= 4, flags, start_offset);
  1008. pce->refcount--;
  1009. }
  1010. /* }}} */
  1011. static zend_always_inline bool is_known_valid_utf8(
  1012. zend_string *subject_str, PCRE2_SIZE start_offset) {
  1013. if (!(GC_FLAGS(subject_str) & IS_STR_VALID_UTF8)) {
  1014. /* We don't know whether the string is valid UTF-8 or not. */
  1015. return 0;
  1016. }
  1017. if (start_offset == ZSTR_LEN(subject_str)) {
  1018. /* Degenerate case: Offset points to end of string. */
  1019. return 1;
  1020. }
  1021. /* Check that the offset does not point to an UTF-8 continuation byte. */
  1022. return (ZSTR_VAL(subject_str)[start_offset] & 0xc0) != 0x80;
  1023. }
  1024. /* {{{ php_pcre_match_impl() */
  1025. PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, zend_string *subject_str, zval *return_value,
  1026. zval *subpats, int global, int use_flags, zend_long flags, zend_off_t start_offset)
  1027. {
  1028. zval result_set, /* Holds a set of subpatterns after
  1029. a global match */
  1030. *match_sets = NULL; /* An array of sets of matches for each
  1031. subpattern after a global match */
  1032. uint32_t options; /* Execution options */
  1033. int count; /* Count of matched subpatterns */
  1034. PCRE2_SIZE *offsets; /* Array of subpattern offsets */
  1035. uint32_t num_subpats; /* Number of captured subpatterns */
  1036. int matched; /* Has anything matched */
  1037. zend_string **subpat_names; /* Array for named subpatterns */
  1038. size_t i;
  1039. uint32_t subpats_order; /* Order of subpattern matches */
  1040. uint32_t offset_capture; /* Capture match offsets: yes/no */
  1041. uint32_t unmatched_as_null; /* Null non-matches: yes/no */
  1042. PCRE2_SPTR mark = NULL; /* Target for MARK name */
  1043. zval marks; /* Array of marks for PREG_PATTERN_ORDER */
  1044. pcre2_match_data *match_data;
  1045. PCRE2_SIZE start_offset2, orig_start_offset;
  1046. char *subject = ZSTR_VAL(subject_str);
  1047. size_t subject_len = ZSTR_LEN(subject_str);
  1048. ZVAL_UNDEF(&marks);
  1049. /* Overwrite the passed-in value for subpatterns with an empty array. */
  1050. if (subpats != NULL) {
  1051. subpats = zend_try_array_init(subpats);
  1052. if (!subpats) {
  1053. RETURN_THROWS();
  1054. }
  1055. }
  1056. subpats_order = global ? PREG_PATTERN_ORDER : 0;
  1057. if (use_flags) {
  1058. offset_capture = flags & PREG_OFFSET_CAPTURE;
  1059. unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL;
  1060. /*
  1061. * subpats_order is pre-set to pattern mode so we change it only if
  1062. * necessary.
  1063. */
  1064. if (flags & 0xff) {
  1065. subpats_order = flags & 0xff;
  1066. }
  1067. if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) ||
  1068. (!global && subpats_order != 0)) {
  1069. zend_argument_value_error(4, "must be a PREG_* constant");
  1070. RETURN_THROWS();
  1071. }
  1072. } else {
  1073. offset_capture = 0;
  1074. unmatched_as_null = 0;
  1075. }
  1076. /* Negative offset counts from the end of the string. */
  1077. if (start_offset < 0) {
  1078. if ((PCRE2_SIZE)-start_offset <= subject_len) {
  1079. start_offset2 = subject_len + start_offset;
  1080. } else {
  1081. start_offset2 = 0;
  1082. }
  1083. } else {
  1084. start_offset2 = (PCRE2_SIZE)start_offset;
  1085. }
  1086. if (start_offset2 > subject_len) {
  1087. pcre_handle_exec_error(PCRE2_ERROR_BADOFFSET);
  1088. RETURN_FALSE;
  1089. }
  1090. /* Calculate the size of the offsets array, and allocate memory for it. */
  1091. num_subpats = pce->capture_count + 1;
  1092. /*
  1093. * Build a mapping from subpattern numbers to their names. We will
  1094. * allocate the table only if there are any named subpatterns.
  1095. */
  1096. subpat_names = NULL;
  1097. if (subpats && pce->name_count > 0) {
  1098. subpat_names = make_subpats_table(num_subpats, pce);
  1099. if (!subpat_names) {
  1100. RETURN_FALSE;
  1101. }
  1102. }
  1103. /* Allocate match sets array and initialize the values. */
  1104. if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
  1105. match_sets = (zval *)safe_emalloc(num_subpats, sizeof(zval), 0);
  1106. for (i=0; i<num_subpats; i++) {
  1107. array_init(&match_sets[i]);
  1108. }
  1109. }
  1110. matched = 0;
  1111. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  1112. if (!mdata_used && num_subpats <= PHP_PCRE_PREALLOC_MDATA_SIZE) {
  1113. match_data = mdata;
  1114. } else {
  1115. match_data = pcre2_match_data_create_from_pattern(pce->re, PCRE_G(gctx_zmm));
  1116. if (!match_data) {
  1117. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  1118. if (subpat_names) {
  1119. free_subpats_table(subpat_names, num_subpats);
  1120. }
  1121. if (match_sets) {
  1122. efree(match_sets);
  1123. }
  1124. RETURN_FALSE;
  1125. }
  1126. }
  1127. orig_start_offset = start_offset2;
  1128. options =
  1129. (pce->compile_options & PCRE2_UTF) && !is_known_valid_utf8(subject_str, orig_start_offset)
  1130. ? 0 : PCRE2_NO_UTF_CHECK;
  1131. /* Execute the regular expression. */
  1132. #ifdef HAVE_PCRE_JIT_SUPPORT
  1133. if ((pce->preg_options & PREG_JIT) && options) {
  1134. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset2,
  1135. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1136. } else
  1137. #endif
  1138. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset2,
  1139. options, match_data, mctx);
  1140. while (1) {
  1141. /* If something has matched */
  1142. if (count >= 0) {
  1143. /* Check for too many substrings condition. */
  1144. if (UNEXPECTED(count == 0)) {
  1145. php_error_docref(NULL, E_NOTICE, "Matched, but too many substrings");
  1146. count = num_subpats;
  1147. }
  1148. matched:
  1149. matched++;
  1150. offsets = pcre2_get_ovector_pointer(match_data);
  1151. /* If subpatterns array has been passed, fill it in with values. */
  1152. if (subpats != NULL) {
  1153. /* Try to get the list of substrings and display a warning if failed. */
  1154. if (offsets[1] < offsets[0]) {
  1155. if (subpat_names) {
  1156. free_subpats_table(subpat_names, num_subpats);
  1157. }
  1158. if (match_sets) efree(match_sets);
  1159. php_error_docref(NULL, E_WARNING, "Get subpatterns list failed");
  1160. RETURN_FALSE;
  1161. }
  1162. if (global) { /* global pattern matching */
  1163. if (subpats && subpats_order == PREG_PATTERN_ORDER) {
  1164. /* For each subpattern, insert it into the appropriate array. */
  1165. if (offset_capture) {
  1166. for (i = 0; i < count; i++) {
  1167. add_offset_pair(
  1168. &match_sets[i], subject, offsets[2*i], offsets[2*i+1],
  1169. NULL, unmatched_as_null);
  1170. }
  1171. } else {
  1172. for (i = 0; i < count; i++) {
  1173. zval val;
  1174. populate_match_value(
  1175. &val, subject, offsets[2*i], offsets[2*i+1], unmatched_as_null);
  1176. zend_hash_next_index_insert_new(Z_ARRVAL(match_sets[i]), &val);
  1177. }
  1178. }
  1179. mark = pcre2_get_mark(match_data);
  1180. /* Add MARK, if available */
  1181. if (mark) {
  1182. if (Z_TYPE(marks) == IS_UNDEF) {
  1183. array_init(&marks);
  1184. }
  1185. add_index_string(&marks, matched - 1, (char *) mark);
  1186. }
  1187. /*
  1188. * If the number of captured subpatterns on this run is
  1189. * less than the total possible number, pad the result
  1190. * arrays with NULLs or empty strings.
  1191. */
  1192. if (count < num_subpats) {
  1193. for (; i < num_subpats; i++) {
  1194. if (offset_capture) {
  1195. add_offset_pair(
  1196. &match_sets[i], NULL, PCRE2_UNSET, PCRE2_UNSET,
  1197. NULL, unmatched_as_null);
  1198. } else if (unmatched_as_null) {
  1199. add_next_index_null(&match_sets[i]);
  1200. } else {
  1201. add_next_index_str(&match_sets[i], ZSTR_EMPTY_ALLOC());
  1202. }
  1203. }
  1204. }
  1205. } else {
  1206. /* Allocate and populate the result set array */
  1207. array_init_size(&result_set, count + (mark ? 1 : 0));
  1208. mark = pcre2_get_mark(match_data);
  1209. populate_subpat_array(
  1210. &result_set, subject, offsets, subpat_names,
  1211. num_subpats, count, mark, flags);
  1212. /* And add it to the output array */
  1213. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set);
  1214. }
  1215. } else { /* single pattern matching */
  1216. /* For each subpattern, insert it into the subpatterns array. */
  1217. mark = pcre2_get_mark(match_data);
  1218. populate_subpat_array(
  1219. subpats, subject, offsets, subpat_names, num_subpats, count, mark, flags);
  1220. break;
  1221. }
  1222. }
  1223. /* Advance to the next piece. */
  1224. start_offset2 = offsets[1];
  1225. /* If we have matched an empty string, mimic what Perl's /g options does.
  1226. This turns out to be rather cunning. First we set PCRE2_NOTEMPTY_ATSTART and try
  1227. the match again at the same point. If this fails (picked up above) we
  1228. advance to the next character. */
  1229. if (start_offset2 == offsets[0]) {
  1230. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset2,
  1231. PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED, match_data, mctx);
  1232. if (count >= 0) {
  1233. if (global) {
  1234. goto matched;
  1235. } else {
  1236. break;
  1237. }
  1238. } else if (count == PCRE2_ERROR_NOMATCH) {
  1239. /* If we previously set PCRE2_NOTEMPTY_ATSTART after a null match,
  1240. this is not necessarily the end. We need to advance
  1241. the start offset, and continue. Fudge the offset values
  1242. to achieve this, unless we're already at the end of the string. */
  1243. if (start_offset2 < subject_len) {
  1244. size_t unit_len = calculate_unit_length(pce, subject + start_offset2);
  1245. start_offset2 += unit_len;
  1246. } else {
  1247. break;
  1248. }
  1249. } else {
  1250. goto error;
  1251. }
  1252. }
  1253. } else if (count == PCRE2_ERROR_NOMATCH) {
  1254. break;
  1255. } else {
  1256. error:
  1257. pcre_handle_exec_error(count);
  1258. break;
  1259. }
  1260. if (!global) {
  1261. break;
  1262. }
  1263. /* Execute the regular expression. */
  1264. #ifdef HAVE_PCRE_JIT_SUPPORT
  1265. if ((pce->preg_options & PREG_JIT)) {
  1266. if (PCRE2_UNSET == start_offset2 || start_offset2 > subject_len) {
  1267. pcre_handle_exec_error(PCRE2_ERROR_BADOFFSET);
  1268. break;
  1269. }
  1270. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset2,
  1271. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1272. } else
  1273. #endif
  1274. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset2,
  1275. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1276. }
  1277. if (match_data != mdata) {
  1278. pcre2_match_data_free(match_data);
  1279. }
  1280. /* Add the match sets to the output array and clean up */
  1281. if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
  1282. if (subpat_names) {
  1283. for (i = 0; i < num_subpats; i++) {
  1284. if (subpat_names[i]) {
  1285. zend_hash_update(Z_ARRVAL_P(subpats), subpat_names[i], &match_sets[i]);
  1286. Z_ADDREF(match_sets[i]);
  1287. }
  1288. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i]);
  1289. }
  1290. } else {
  1291. for (i = 0; i < num_subpats; i++) {
  1292. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i]);
  1293. }
  1294. }
  1295. efree(match_sets);
  1296. if (Z_TYPE(marks) != IS_UNDEF) {
  1297. add_assoc_zval(subpats, "MARK", &marks);
  1298. }
  1299. }
  1300. if (subpat_names) {
  1301. free_subpats_table(subpat_names, num_subpats);
  1302. }
  1303. if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) {
  1304. /* If there was no error and we're in /u mode, remember that the string is valid UTF-8. */
  1305. if ((pce->compile_options & PCRE2_UTF)
  1306. && !ZSTR_IS_INTERNED(subject_str) && orig_start_offset == 0) {
  1307. GC_ADD_FLAGS(subject_str, IS_STR_VALID_UTF8);
  1308. }
  1309. RETVAL_LONG(matched);
  1310. } else {
  1311. RETVAL_FALSE;
  1312. }
  1313. }
  1314. /* }}} */
  1315. /* {{{ Perform a Perl-style regular expression match */
  1316. PHP_FUNCTION(preg_match)
  1317. {
  1318. php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
  1319. }
  1320. /* }}} */
  1321. /* {{{ Perform a Perl-style global regular expression match */
  1322. PHP_FUNCTION(preg_match_all)
  1323. {
  1324. php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
  1325. }
  1326. /* }}} */
  1327. /* {{{ preg_get_backref */
  1328. static int preg_get_backref(char **str, int *backref)
  1329. {
  1330. char in_brace = 0;
  1331. char *walk = *str;
  1332. if (walk[1] == 0)
  1333. return 0;
  1334. if (*walk == '$' && walk[1] == '{') {
  1335. in_brace = 1;
  1336. walk++;
  1337. }
  1338. walk++;
  1339. if (*walk >= '0' && *walk <= '9') {
  1340. *backref = *walk - '0';
  1341. walk++;
  1342. } else
  1343. return 0;
  1344. if (*walk && *walk >= '0' && *walk <= '9') {
  1345. *backref = *backref * 10 + *walk - '0';
  1346. walk++;
  1347. }
  1348. if (in_brace) {
  1349. if (*walk != '}')
  1350. return 0;
  1351. else
  1352. walk++;
  1353. }
  1354. *str = walk;
  1355. return 1;
  1356. }
  1357. /* }}} */
  1358. /* {{{ preg_do_repl_func */
  1359. static zend_string *preg_do_repl_func(zend_fcall_info *fci, zend_fcall_info_cache *fcc, const char *subject, PCRE2_SIZE *offsets, zend_string **subpat_names, uint32_t num_subpats, int count, const PCRE2_SPTR mark, zend_long flags)
  1360. {
  1361. zend_string *result_str;
  1362. zval retval; /* Function return value */
  1363. zval arg; /* Argument to pass to function */
  1364. array_init_size(&arg, count + (mark ? 1 : 0));
  1365. populate_subpat_array(&arg, subject, offsets, subpat_names, num_subpats, count, mark, flags);
  1366. fci->retval = &retval;
  1367. fci->param_count = 1;
  1368. fci->params = &arg;
  1369. if (zend_call_function(fci, fcc) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
  1370. if (EXPECTED(Z_TYPE(retval) == IS_STRING)) {
  1371. result_str = Z_STR(retval);
  1372. } else {
  1373. result_str = zval_get_string_func(&retval);
  1374. zval_ptr_dtor(&retval);
  1375. }
  1376. } else {
  1377. if (!EG(exception)) {
  1378. php_error_docref(NULL, E_WARNING, "Unable to call custom replacement function");
  1379. }
  1380. result_str = zend_string_init(&subject[offsets[0]], offsets[1] - offsets[0], 0);
  1381. }
  1382. zval_ptr_dtor(&arg);
  1383. return result_str;
  1384. }
  1385. /* }}} */
  1386. /* {{{ php_pcre_replace */
  1387. PHPAPI zend_string *php_pcre_replace(zend_string *regex,
  1388. zend_string *subject_str,
  1389. const char *subject, size_t subject_len,
  1390. zend_string *replace_str,
  1391. size_t limit, size_t *replace_count)
  1392. {
  1393. pcre_cache_entry *pce; /* Compiled regular expression */
  1394. zend_string *result; /* Function result */
  1395. /* Abort on pending exception, e.g. thrown from __toString(). */
  1396. if (UNEXPECTED(EG(exception))) {
  1397. return NULL;
  1398. }
  1399. /* Compile regex or get it from cache. */
  1400. if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
  1401. return NULL;
  1402. }
  1403. pce->refcount++;
  1404. result = php_pcre_replace_impl(pce, subject_str, subject, subject_len, replace_str,
  1405. limit, replace_count);
  1406. pce->refcount--;
  1407. return result;
  1408. }
  1409. /* }}} */
  1410. /* {{{ php_pcre_replace_impl() */
  1411. PHPAPI zend_string *php_pcre_replace_impl(pcre_cache_entry *pce, zend_string *subject_str, const char *subject, size_t subject_len, zend_string *replace_str, size_t limit, size_t *replace_count)
  1412. {
  1413. uint32_t options; /* Execution options */
  1414. int count; /* Count of matched subpatterns */
  1415. PCRE2_SIZE *offsets; /* Array of subpattern offsets */
  1416. uint32_t num_subpats; /* Number of captured subpatterns */
  1417. size_t new_len; /* Length of needed storage */
  1418. size_t alloc_len; /* Actual allocated length */
  1419. size_t match_len; /* Length of the current match */
  1420. int backref; /* Backreference number */
  1421. PCRE2_SIZE start_offset; /* Where the new search starts */
  1422. size_t last_end_offset; /* Where the last search ended */
  1423. char *walkbuf, /* Location of current replacement in the result */
  1424. *walk, /* Used to walk the replacement string */
  1425. walk_last; /* Last walked character */
  1426. const char *match, /* The current match */
  1427. *piece, /* The current piece of subject */
  1428. *replace_end; /* End of replacement string */
  1429. size_t result_len; /* Length of result */
  1430. zend_string *result; /* Result of replacement */
  1431. pcre2_match_data *match_data;
  1432. /* Calculate the size of the offsets array, and allocate memory for it. */
  1433. num_subpats = pce->capture_count + 1;
  1434. alloc_len = 0;
  1435. result = NULL;
  1436. /* Initialize */
  1437. match = NULL;
  1438. start_offset = 0;
  1439. last_end_offset = 0;
  1440. result_len = 0;
  1441. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  1442. if (!mdata_used && num_subpats <= PHP_PCRE_PREALLOC_MDATA_SIZE) {
  1443. match_data = mdata;
  1444. } else {
  1445. match_data = pcre2_match_data_create_from_pattern(pce->re, PCRE_G(gctx_zmm));
  1446. if (!match_data) {
  1447. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  1448. return NULL;
  1449. }
  1450. }
  1451. options = (pce->compile_options & PCRE2_UTF) ? 0 : PCRE2_NO_UTF_CHECK;
  1452. /* Execute the regular expression. */
  1453. #ifdef HAVE_PCRE_JIT_SUPPORT
  1454. if ((pce->preg_options & PREG_JIT) && options) {
  1455. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1456. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1457. } else
  1458. #endif
  1459. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1460. options, match_data, mctx);
  1461. while (1) {
  1462. piece = subject + last_end_offset;
  1463. if (count >= 0 && limit > 0) {
  1464. bool simple_string;
  1465. /* Check for too many substrings condition. */
  1466. if (UNEXPECTED(count == 0)) {
  1467. php_error_docref(NULL,E_NOTICE, "Matched, but too many substrings");
  1468. count = num_subpats;
  1469. }
  1470. matched:
  1471. offsets = pcre2_get_ovector_pointer(match_data);
  1472. if (UNEXPECTED(offsets[1] < offsets[0])) {
  1473. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  1474. if (result) {
  1475. zend_string_release_ex(result, 0);
  1476. result = NULL;
  1477. }
  1478. break;
  1479. }
  1480. if (replace_count) {
  1481. ++*replace_count;
  1482. }
  1483. /* Set the match location in subject */
  1484. match = subject + offsets[0];
  1485. new_len = result_len + offsets[0] - last_end_offset; /* part before the match */
  1486. walk = ZSTR_VAL(replace_str);
  1487. replace_end = walk + ZSTR_LEN(replace_str);
  1488. walk_last = 0;
  1489. simple_string = 1;
  1490. while (walk < replace_end) {
  1491. if ('\\' == *walk || '$' == *walk) {
  1492. simple_string = 0;
  1493. if (walk_last == '\\') {
  1494. walk++;
  1495. walk_last = 0;
  1496. continue;
  1497. }
  1498. if (preg_get_backref(&walk, &backref)) {
  1499. if (backref < count)
  1500. new_len += offsets[(backref<<1)+1] - offsets[backref<<1];
  1501. continue;
  1502. }
  1503. }
  1504. new_len++;
  1505. walk++;
  1506. walk_last = walk[-1];
  1507. }
  1508. if (new_len >= alloc_len) {
  1509. alloc_len = zend_safe_address_guarded(2, new_len, ZSTR_MAX_OVERHEAD) - ZSTR_MAX_OVERHEAD;
  1510. if (result == NULL) {
  1511. result = zend_string_alloc(alloc_len, 0);
  1512. } else {
  1513. result = zend_string_extend(result, alloc_len, 0);
  1514. }
  1515. }
  1516. if (match-piece > 0) {
  1517. /* copy the part of the string before the match */
  1518. memcpy(&ZSTR_VAL(result)[result_len], piece, match-piece);
  1519. result_len += (match-piece);
  1520. }
  1521. if (simple_string) {
  1522. /* copy replacement */
  1523. memcpy(&ZSTR_VAL(result)[result_len], ZSTR_VAL(replace_str), ZSTR_LEN(replace_str)+1);
  1524. result_len += ZSTR_LEN(replace_str);
  1525. } else {
  1526. /* copy replacement and backrefs */
  1527. walkbuf = ZSTR_VAL(result) + result_len;
  1528. walk = ZSTR_VAL(replace_str);
  1529. walk_last = 0;
  1530. while (walk < replace_end) {
  1531. if ('\\' == *walk || '$' == *walk) {
  1532. if (walk_last == '\\') {
  1533. *(walkbuf-1) = *walk++;
  1534. walk_last = 0;
  1535. continue;
  1536. }
  1537. if (preg_get_backref(&walk, &backref)) {
  1538. if (backref < count) {
  1539. match_len = offsets[(backref<<1)+1] - offsets[backref<<1];
  1540. memcpy(walkbuf, subject + offsets[backref<<1], match_len);
  1541. walkbuf += match_len;
  1542. }
  1543. continue;
  1544. }
  1545. }
  1546. *walkbuf++ = *walk++;
  1547. walk_last = walk[-1];
  1548. }
  1549. *walkbuf = '\0';
  1550. /* increment the result length by how much we've added to the string */
  1551. result_len += (walkbuf - (ZSTR_VAL(result) + result_len));
  1552. }
  1553. limit--;
  1554. /* Advance to the next piece. */
  1555. start_offset = last_end_offset = offsets[1];
  1556. /* If we have matched an empty string, mimic what Perl's /g options does.
  1557. This turns out to be rather cunning. First we set PCRE2_NOTEMPTY_ATSTART and try
  1558. the match again at the same point. If this fails (picked up above) we
  1559. advance to the next character. */
  1560. if (start_offset == offsets[0]) {
  1561. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1562. PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED, match_data, mctx);
  1563. piece = subject + start_offset;
  1564. if (count >= 0 && limit > 0) {
  1565. goto matched;
  1566. } else if (count == PCRE2_ERROR_NOMATCH || limit == 0) {
  1567. /* If we previously set PCRE2_NOTEMPTY_ATSTART after a null match,
  1568. this is not necessarily the end. We need to advance
  1569. the start offset, and continue. Fudge the offset values
  1570. to achieve this, unless we're already at the end of the string. */
  1571. if (start_offset < subject_len) {
  1572. size_t unit_len = calculate_unit_length(pce, piece);
  1573. start_offset += unit_len;
  1574. } else {
  1575. goto not_matched;
  1576. }
  1577. } else {
  1578. goto error;
  1579. }
  1580. }
  1581. } else if (count == PCRE2_ERROR_NOMATCH || limit == 0) {
  1582. not_matched:
  1583. if (!result && subject_str) {
  1584. result = zend_string_copy(subject_str);
  1585. break;
  1586. }
  1587. /* now we know exactly how long it is */
  1588. alloc_len = result_len + subject_len - last_end_offset;
  1589. if (NULL != result) {
  1590. result = zend_string_realloc(result, alloc_len, 0);
  1591. } else {
  1592. result = zend_string_alloc(alloc_len, 0);
  1593. }
  1594. /* stick that last bit of string on our output */
  1595. memcpy(ZSTR_VAL(result) + result_len, piece, subject_len - last_end_offset);
  1596. result_len += subject_len - last_end_offset;
  1597. ZSTR_VAL(result)[result_len] = '\0';
  1598. ZSTR_LEN(result) = result_len;
  1599. break;
  1600. } else {
  1601. error:
  1602. pcre_handle_exec_error(count);
  1603. if (result) {
  1604. zend_string_release_ex(result, 0);
  1605. result = NULL;
  1606. }
  1607. break;
  1608. }
  1609. #ifdef HAVE_PCRE_JIT_SUPPORT
  1610. if (pce->preg_options & PREG_JIT) {
  1611. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1612. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1613. } else
  1614. #endif
  1615. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1616. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1617. }
  1618. if (match_data != mdata) {
  1619. pcre2_match_data_free(match_data);
  1620. }
  1621. return result;
  1622. }
  1623. /* }}} */
  1624. /* {{{ php_pcre_replace_func_impl() */
  1625. static zend_string *php_pcre_replace_func_impl(pcre_cache_entry *pce, zend_string *subject_str, const char *subject, size_t subject_len, zend_fcall_info *fci, zend_fcall_info_cache *fcc, size_t limit, size_t *replace_count, zend_long flags)
  1626. {
  1627. uint32_t options; /* Execution options */
  1628. int count; /* Count of matched subpatterns */
  1629. PCRE2_SIZE *offsets; /* Array of subpattern offsets */
  1630. zend_string **subpat_names; /* Array for named subpatterns */
  1631. uint32_t num_subpats; /* Number of captured subpatterns */
  1632. size_t new_len; /* Length of needed storage */
  1633. size_t alloc_len; /* Actual allocated length */
  1634. PCRE2_SIZE start_offset; /* Where the new search starts */
  1635. size_t last_end_offset; /* Where the last search ended */
  1636. const char *match, /* The current match */
  1637. *piece; /* The current piece of subject */
  1638. size_t result_len; /* Length of result */
  1639. zend_string *result; /* Result of replacement */
  1640. zend_string *eval_result; /* Result of custom function */
  1641. pcre2_match_data *match_data;
  1642. bool old_mdata_used;
  1643. /* Calculate the size of the offsets array, and allocate memory for it. */
  1644. num_subpats = pce->capture_count + 1;
  1645. /*
  1646. * Build a mapping from subpattern numbers to their names. We will
  1647. * allocate the table only if there are any named subpatterns.
  1648. */
  1649. subpat_names = NULL;
  1650. if (UNEXPECTED(pce->name_count > 0)) {
  1651. subpat_names = make_subpats_table(num_subpats, pce);
  1652. if (!subpat_names) {
  1653. return NULL;
  1654. }
  1655. }
  1656. alloc_len = 0;
  1657. result = NULL;
  1658. /* Initialize */
  1659. match = NULL;
  1660. start_offset = 0;
  1661. last_end_offset = 0;
  1662. result_len = 0;
  1663. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  1664. old_mdata_used = mdata_used;
  1665. if (!old_mdata_used && num_subpats <= PHP_PCRE_PREALLOC_MDATA_SIZE) {
  1666. mdata_used = 1;
  1667. match_data = mdata;
  1668. } else {
  1669. match_data = pcre2_match_data_create_from_pattern(pce->re, PCRE_G(gctx_zmm));
  1670. if (!match_data) {
  1671. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  1672. if (subpat_names) {
  1673. free_subpats_table(subpat_names, num_subpats);
  1674. }
  1675. mdata_used = old_mdata_used;
  1676. return NULL;
  1677. }
  1678. }
  1679. options = (pce->compile_options & PCRE2_UTF) ? 0 : PCRE2_NO_UTF_CHECK;
  1680. /* Execute the regular expression. */
  1681. #ifdef HAVE_PCRE_JIT_SUPPORT
  1682. if ((pce->preg_options & PREG_JIT) && options) {
  1683. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1684. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1685. } else
  1686. #endif
  1687. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1688. options, match_data, mctx);
  1689. while (1) {
  1690. piece = subject + last_end_offset;
  1691. if (count >= 0 && limit) {
  1692. /* Check for too many substrings condition. */
  1693. if (UNEXPECTED(count == 0)) {
  1694. php_error_docref(NULL,E_NOTICE, "Matched, but too many substrings");
  1695. count = num_subpats;
  1696. }
  1697. matched:
  1698. offsets = pcre2_get_ovector_pointer(match_data);
  1699. if (UNEXPECTED(offsets[1] < offsets[0])) {
  1700. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  1701. if (result) {
  1702. zend_string_release_ex(result, 0);
  1703. result = NULL;
  1704. }
  1705. break;
  1706. }
  1707. if (replace_count) {
  1708. ++*replace_count;
  1709. }
  1710. /* Set the match location in subject */
  1711. match = subject + offsets[0];
  1712. new_len = result_len + offsets[0] - last_end_offset; /* part before the match */
  1713. /* Use custom function to get replacement string and its length. */
  1714. eval_result = preg_do_repl_func(
  1715. fci, fcc, subject, offsets, subpat_names, num_subpats, count,
  1716. pcre2_get_mark(match_data), flags);
  1717. ZEND_ASSERT(eval_result);
  1718. new_len = zend_safe_address_guarded(1, ZSTR_LEN(eval_result) + ZSTR_MAX_OVERHEAD, new_len) -ZSTR_MAX_OVERHEAD;
  1719. if (new_len >= alloc_len) {
  1720. alloc_len = zend_safe_address_guarded(2, new_len, ZSTR_MAX_OVERHEAD) - ZSTR_MAX_OVERHEAD;
  1721. if (result == NULL) {
  1722. result = zend_string_alloc(alloc_len, 0);
  1723. } else {
  1724. result = zend_string_extend(result, alloc_len, 0);
  1725. }
  1726. }
  1727. if (match-piece > 0) {
  1728. /* copy the part of the string before the match */
  1729. memcpy(ZSTR_VAL(result) + result_len, piece, match-piece);
  1730. result_len += (match-piece);
  1731. }
  1732. /* If using custom function, copy result to the buffer and clean up. */
  1733. memcpy(ZSTR_VAL(result) + result_len, ZSTR_VAL(eval_result), ZSTR_LEN(eval_result));
  1734. result_len += ZSTR_LEN(eval_result);
  1735. zend_string_release_ex(eval_result, 0);
  1736. limit--;
  1737. /* Advance to the next piece. */
  1738. start_offset = last_end_offset = offsets[1];
  1739. /* If we have matched an empty string, mimic what Perl's /g options does.
  1740. This turns out to be rather cunning. First we set PCRE2_NOTEMPTY_ATSTART and try
  1741. the match again at the same point. If this fails (picked up above) we
  1742. advance to the next character. */
  1743. if (start_offset == offsets[0]) {
  1744. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1745. PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED, match_data, mctx);
  1746. piece = subject + start_offset;
  1747. if (count >= 0 && limit) {
  1748. goto matched;
  1749. } else if (count == PCRE2_ERROR_NOMATCH || limit == 0) {
  1750. /* If we previously set PCRE2_NOTEMPTY_ATSTART after a null match,
  1751. this is not necessarily the end. We need to advance
  1752. the start offset, and continue. Fudge the offset values
  1753. to achieve this, unless we're already at the end of the string. */
  1754. if (start_offset < subject_len) {
  1755. size_t unit_len = calculate_unit_length(pce, piece);
  1756. start_offset += unit_len;
  1757. } else {
  1758. goto not_matched;
  1759. }
  1760. } else {
  1761. goto error;
  1762. }
  1763. }
  1764. } else if (count == PCRE2_ERROR_NOMATCH || limit == 0) {
  1765. not_matched:
  1766. if (!result && subject_str) {
  1767. result = zend_string_copy(subject_str);
  1768. break;
  1769. }
  1770. /* now we know exactly how long it is */
  1771. alloc_len = result_len + subject_len - last_end_offset;
  1772. if (NULL != result) {
  1773. result = zend_string_realloc(result, alloc_len, 0);
  1774. } else {
  1775. result = zend_string_alloc(alloc_len, 0);
  1776. }
  1777. /* stick that last bit of string on our output */
  1778. memcpy(ZSTR_VAL(result) + result_len, piece, subject_len - last_end_offset);
  1779. result_len += subject_len - last_end_offset;
  1780. ZSTR_VAL(result)[result_len] = '\0';
  1781. ZSTR_LEN(result) = result_len;
  1782. break;
  1783. } else {
  1784. error:
  1785. pcre_handle_exec_error(count);
  1786. if (result) {
  1787. zend_string_release_ex(result, 0);
  1788. result = NULL;
  1789. }
  1790. break;
  1791. }
  1792. #ifdef HAVE_PCRE_JIT_SUPPORT
  1793. if ((pce->preg_options & PREG_JIT)) {
  1794. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1795. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1796. } else
  1797. #endif
  1798. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, subject_len, start_offset,
  1799. PCRE2_NO_UTF_CHECK, match_data, mctx);
  1800. }
  1801. if (match_data != mdata) {
  1802. pcre2_match_data_free(match_data);
  1803. }
  1804. mdata_used = old_mdata_used;
  1805. if (UNEXPECTED(subpat_names)) {
  1806. free_subpats_table(subpat_names, num_subpats);
  1807. }
  1808. return result;
  1809. }
  1810. /* }}} */
  1811. /* {{{ php_pcre_replace_func */
  1812. static zend_always_inline zend_string *php_pcre_replace_func(zend_string *regex,
  1813. zend_string *subject_str,
  1814. zend_fcall_info *fci, zend_fcall_info_cache *fcc,
  1815. size_t limit, size_t *replace_count, zend_long flags)
  1816. {
  1817. pcre_cache_entry *pce; /* Compiled regular expression */
  1818. zend_string *result; /* Function result */
  1819. /* Compile regex or get it from cache. */
  1820. if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
  1821. return NULL;
  1822. }
  1823. pce->refcount++;
  1824. result = php_pcre_replace_func_impl(
  1825. pce, subject_str, ZSTR_VAL(subject_str), ZSTR_LEN(subject_str), fci, fcc,
  1826. limit, replace_count, flags);
  1827. pce->refcount--;
  1828. return result;
  1829. }
  1830. /* }}} */
  1831. /* {{{ php_pcre_replace_array */
  1832. static zend_string *php_pcre_replace_array(HashTable *regex,
  1833. zend_string *replace_str, HashTable *replace_ht,
  1834. zend_string *subject_str, size_t limit, size_t *replace_count)
  1835. {
  1836. zval *regex_entry;
  1837. zend_string *result;
  1838. zend_string_addref(subject_str);
  1839. if (replace_ht) {
  1840. uint32_t replace_idx = 0;
  1841. /* For each entry in the regex array, get the entry */
  1842. ZEND_HASH_FOREACH_VAL(regex, regex_entry) {
  1843. /* Make sure we're dealing with strings. */
  1844. zend_string *tmp_regex_str;
  1845. zend_string *regex_str = zval_get_tmp_string(regex_entry, &tmp_regex_str);
  1846. zend_string *replace_entry_str, *tmp_replace_entry_str;
  1847. zval *zv;
  1848. /* Get current entry */
  1849. while (1) {
  1850. if (replace_idx == replace_ht->nNumUsed) {
  1851. replace_entry_str = ZSTR_EMPTY_ALLOC();
  1852. tmp_replace_entry_str = NULL;
  1853. break;
  1854. }
  1855. zv = &replace_ht->arData[replace_idx].val;
  1856. replace_idx++;
  1857. if (Z_TYPE_P(zv) != IS_UNDEF) {
  1858. replace_entry_str = zval_get_tmp_string(zv, &tmp_replace_entry_str);
  1859. break;
  1860. }
  1861. }
  1862. /* Do the actual replacement and put the result back into subject_str
  1863. for further replacements. */
  1864. result = php_pcre_replace(regex_str, subject_str, ZSTR_VAL(subject_str),
  1865. ZSTR_LEN(subject_str), replace_entry_str, limit, replace_count);
  1866. zend_tmp_string_release(tmp_replace_entry_str);
  1867. zend_tmp_string_release(tmp_regex_str);
  1868. zend_string_release_ex(subject_str, 0);
  1869. subject_str = result;
  1870. if (UNEXPECTED(result == NULL)) {
  1871. break;
  1872. }
  1873. } ZEND_HASH_FOREACH_END();
  1874. } else {
  1875. ZEND_ASSERT(replace_str != NULL);
  1876. /* For each entry in the regex array, get the entry */
  1877. ZEND_HASH_FOREACH_VAL(regex, regex_entry) {
  1878. /* Make sure we're dealing with strings. */
  1879. zend_string *tmp_regex_str;
  1880. zend_string *regex_str = zval_get_tmp_string(regex_entry, &tmp_regex_str);
  1881. /* Do the actual replacement and put the result back into subject_str
  1882. for further replacements. */
  1883. result = php_pcre_replace(regex_str, subject_str, ZSTR_VAL(subject_str),
  1884. ZSTR_LEN(subject_str), replace_str, limit, replace_count);
  1885. zend_tmp_string_release(tmp_regex_str);
  1886. zend_string_release_ex(subject_str, 0);
  1887. subject_str = result;
  1888. if (UNEXPECTED(result == NULL)) {
  1889. break;
  1890. }
  1891. } ZEND_HASH_FOREACH_END();
  1892. }
  1893. return subject_str;
  1894. }
  1895. /* }}} */
  1896. /* {{{ php_replace_in_subject */
  1897. static zend_always_inline zend_string *php_replace_in_subject(
  1898. zend_string *regex_str, HashTable *regex_ht,
  1899. zend_string *replace_str, HashTable *replace_ht,
  1900. zend_string *subject, size_t limit, size_t *replace_count)
  1901. {
  1902. zend_string *result;
  1903. if (regex_str) {
  1904. ZEND_ASSERT(replace_str != NULL);
  1905. result = php_pcre_replace(regex_str, subject, ZSTR_VAL(subject), ZSTR_LEN(subject),
  1906. replace_str, limit, replace_count);
  1907. } else {
  1908. ZEND_ASSERT(regex_ht != NULL);
  1909. result = php_pcre_replace_array(regex_ht, replace_str, replace_ht, subject,
  1910. limit, replace_count);
  1911. }
  1912. return result;
  1913. }
  1914. /* }}} */
  1915. /* {{{ php_replace_in_subject_func */
  1916. static zend_string *php_replace_in_subject_func(zend_string *regex_str, HashTable *regex_ht,
  1917. zend_fcall_info *fci, zend_fcall_info_cache *fcc,
  1918. zend_string *subject, size_t limit, size_t *replace_count, zend_long flags)
  1919. {
  1920. zend_string *result;
  1921. if (regex_str) {
  1922. result = php_pcre_replace_func(
  1923. regex_str, subject, fci, fcc, limit, replace_count, flags);
  1924. return result;
  1925. } else {
  1926. /* If regex is an array */
  1927. zval *regex_entry;
  1928. ZEND_ASSERT(regex_ht != NULL);
  1929. zend_string_addref(subject);
  1930. /* For each entry in the regex array, get the entry */
  1931. ZEND_HASH_FOREACH_VAL(regex_ht, regex_entry) {
  1932. /* Make sure we're dealing with strings. */
  1933. zend_string *tmp_regex_entry_str;
  1934. zend_string *regex_entry_str = zval_get_tmp_string(regex_entry, &tmp_regex_entry_str);
  1935. /* Do the actual replacement and put the result back into subject
  1936. for further replacements. */
  1937. result = php_pcre_replace_func(
  1938. regex_entry_str, subject, fci, fcc, limit, replace_count, flags);
  1939. zend_tmp_string_release(tmp_regex_entry_str);
  1940. zend_string_release(subject);
  1941. subject = result;
  1942. if (UNEXPECTED(result == NULL)) {
  1943. break;
  1944. }
  1945. } ZEND_HASH_FOREACH_END();
  1946. return subject;
  1947. }
  1948. }
  1949. /* }}} */
  1950. /* {{{ preg_replace_func_impl */
  1951. static size_t preg_replace_func_impl(zval *return_value,
  1952. zend_string *regex_str, HashTable *regex_ht,
  1953. zend_fcall_info *fci, zend_fcall_info_cache *fcc,
  1954. zend_string *subject_str, HashTable *subject_ht, zend_long limit_val, zend_long flags)
  1955. {
  1956. zend_string *result;
  1957. size_t replace_count = 0;
  1958. if (subject_str) {
  1959. result = php_replace_in_subject_func(
  1960. regex_str, regex_ht, fci, fcc, subject_str, limit_val, &replace_count, flags);
  1961. if (result != NULL) {
  1962. RETVAL_STR(result);
  1963. } else {
  1964. RETVAL_NULL();
  1965. }
  1966. } else {
  1967. /* if subject is an array */
  1968. zval *subject_entry, zv;
  1969. zend_string *string_key;
  1970. zend_ulong num_key;
  1971. ZEND_ASSERT(subject_ht != NULL);
  1972. array_init_size(return_value, zend_hash_num_elements(subject_ht));
  1973. /* For each subject entry, convert it to string, then perform replacement
  1974. and add the result to the return_value array. */
  1975. ZEND_HASH_FOREACH_KEY_VAL(subject_ht, num_key, string_key, subject_entry) {
  1976. zend_string *tmp_subject_entry_str;
  1977. zend_string *subject_entry_str = zval_get_tmp_string(subject_entry, &tmp_subject_entry_str);
  1978. result = php_replace_in_subject_func(
  1979. regex_str, regex_ht, fci, fcc, subject_entry_str, limit_val, &replace_count, flags);
  1980. if (result != NULL) {
  1981. /* Add to return array */
  1982. ZVAL_STR(&zv, result);
  1983. if (string_key) {
  1984. zend_hash_add_new(Z_ARRVAL_P(return_value), string_key, &zv);
  1985. } else {
  1986. zend_hash_index_add_new(Z_ARRVAL_P(return_value), num_key, &zv);
  1987. }
  1988. }
  1989. zend_tmp_string_release(tmp_subject_entry_str);
  1990. } ZEND_HASH_FOREACH_END();
  1991. }
  1992. return replace_count;
  1993. }
  1994. /* }}} */
  1995. /* {{{ preg_replace_common */
  1996. static void preg_replace_common(INTERNAL_FUNCTION_PARAMETERS, bool is_filter)
  1997. {
  1998. zval *zcount = NULL;
  1999. zend_string *regex_str;
  2000. HashTable *regex_ht;
  2001. zend_string *replace_str;
  2002. HashTable *replace_ht;
  2003. zend_string *subject_str;
  2004. HashTable *subject_ht;
  2005. zend_long limit = -1;
  2006. size_t replace_count = 0;
  2007. zend_string *result;
  2008. size_t old_replace_count;
  2009. /* Get function parameters and do error-checking. */
  2010. ZEND_PARSE_PARAMETERS_START(3, 5)
  2011. Z_PARAM_ARRAY_HT_OR_STR(regex_ht, regex_str)
  2012. Z_PARAM_ARRAY_HT_OR_STR(replace_ht, replace_str)
  2013. Z_PARAM_ARRAY_HT_OR_STR(subject_ht, subject_str)
  2014. Z_PARAM_OPTIONAL
  2015. Z_PARAM_LONG(limit)
  2016. Z_PARAM_ZVAL(zcount)
  2017. ZEND_PARSE_PARAMETERS_END();
  2018. /* If replace is an array then the regex argument needs to also be an array */
  2019. if (replace_ht && !regex_ht) {
  2020. zend_argument_type_error(1, "must be of type array when argument #2 ($replacement) is an array, string given");
  2021. RETURN_THROWS();
  2022. }
  2023. if (subject_str) {
  2024. old_replace_count = replace_count;
  2025. result = php_replace_in_subject(regex_str, regex_ht, replace_str, replace_ht,
  2026. subject_str, limit, &replace_count);
  2027. if (result != NULL) {
  2028. if (!is_filter || replace_count > old_replace_count) {
  2029. RETVAL_STR(result);
  2030. } else {
  2031. zend_string_release_ex(result, 0);
  2032. RETVAL_NULL();
  2033. }
  2034. } else {
  2035. RETVAL_NULL();
  2036. }
  2037. } else {
  2038. /* if subject is an array */
  2039. zval *subject_entry, zv;
  2040. zend_string *string_key;
  2041. zend_ulong num_key;
  2042. ZEND_ASSERT(subject_ht != NULL);
  2043. array_init_size(return_value, zend_hash_num_elements(subject_ht));
  2044. /* For each subject entry, convert it to string, then perform replacement
  2045. and add the result to the return_value array. */
  2046. ZEND_HASH_FOREACH_KEY_VAL(subject_ht, num_key, string_key, subject_entry) {
  2047. old_replace_count = replace_count;
  2048. zend_string *tmp_subject_entry_str;
  2049. zend_string *subject_entry_str = zval_get_tmp_string(subject_entry, &tmp_subject_entry_str);
  2050. result = php_replace_in_subject(regex_str, regex_ht, replace_str, replace_ht,
  2051. subject_entry_str, limit, &replace_count);
  2052. if (result != NULL) {
  2053. if (!is_filter || replace_count > old_replace_count) {
  2054. /* Add to return array */
  2055. ZVAL_STR(&zv, result);
  2056. if (string_key) {
  2057. zend_hash_add_new(Z_ARRVAL_P(return_value), string_key, &zv);
  2058. } else {
  2059. zend_hash_index_add_new(Z_ARRVAL_P(return_value), num_key, &zv);
  2060. }
  2061. } else {
  2062. zend_string_release_ex(result, 0);
  2063. }
  2064. }
  2065. zend_tmp_string_release(tmp_subject_entry_str);
  2066. } ZEND_HASH_FOREACH_END();
  2067. }
  2068. if (zcount) {
  2069. ZEND_TRY_ASSIGN_REF_LONG(zcount, replace_count);
  2070. }
  2071. }
  2072. /* }}} */
  2073. /* {{{ Perform Perl-style regular expression replacement. */
  2074. PHP_FUNCTION(preg_replace)
  2075. {
  2076. preg_replace_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, false);
  2077. }
  2078. /* }}} */
  2079. /* {{{ Perform Perl-style regular expression replacement using replacement callback. */
  2080. PHP_FUNCTION(preg_replace_callback)
  2081. {
  2082. zval *zcount = NULL;
  2083. zend_string *regex_str;
  2084. HashTable *regex_ht;
  2085. zend_string *subject_str;
  2086. HashTable *subject_ht;
  2087. zend_long limit = -1, flags = 0;
  2088. size_t replace_count;
  2089. zend_fcall_info fci;
  2090. zend_fcall_info_cache fcc;
  2091. /* Get function parameters and do error-checking. */
  2092. ZEND_PARSE_PARAMETERS_START(3, 6)
  2093. Z_PARAM_ARRAY_HT_OR_STR(regex_ht, regex_str)
  2094. Z_PARAM_FUNC(fci, fcc)
  2095. Z_PARAM_ARRAY_HT_OR_STR(subject_ht, subject_str)
  2096. Z_PARAM_OPTIONAL
  2097. Z_PARAM_LONG(limit)
  2098. Z_PARAM_ZVAL(zcount)
  2099. Z_PARAM_LONG(flags)
  2100. ZEND_PARSE_PARAMETERS_END();
  2101. replace_count = preg_replace_func_impl(return_value, regex_str, regex_ht,
  2102. &fci, &fcc,
  2103. subject_str, subject_ht, limit, flags);
  2104. if (zcount) {
  2105. ZEND_TRY_ASSIGN_REF_LONG(zcount, replace_count);
  2106. }
  2107. }
  2108. /* }}} */
  2109. /* {{{ Perform Perl-style regular expression replacement using replacement callback. */
  2110. PHP_FUNCTION(preg_replace_callback_array)
  2111. {
  2112. zval zv, *replace, *zcount = NULL;
  2113. HashTable *pattern, *subject_ht;
  2114. zend_string *subject_str, *str_idx_regex;
  2115. zend_long limit = -1, flags = 0;
  2116. size_t replace_count = 0;
  2117. zend_fcall_info fci;
  2118. zend_fcall_info_cache fcc;
  2119. /* Get function parameters and do error-checking. */
  2120. ZEND_PARSE_PARAMETERS_START(2, 5)
  2121. Z_PARAM_ARRAY_HT(pattern)
  2122. Z_PARAM_ARRAY_HT_OR_STR(subject_ht, subject_str)
  2123. Z_PARAM_OPTIONAL
  2124. Z_PARAM_LONG(limit)
  2125. Z_PARAM_ZVAL(zcount)
  2126. Z_PARAM_LONG(flags)
  2127. ZEND_PARSE_PARAMETERS_END();
  2128. fci.size = sizeof(fci);
  2129. fci.object = NULL;
  2130. fci.named_params = NULL;
  2131. if (subject_ht) {
  2132. GC_TRY_ADDREF(subject_ht);
  2133. } else {
  2134. GC_TRY_ADDREF(subject_str);
  2135. }
  2136. ZEND_HASH_FOREACH_STR_KEY_VAL(pattern, str_idx_regex, replace) {
  2137. if (!str_idx_regex) {
  2138. php_error_docref(NULL, E_WARNING, "Delimiter must not be alphanumeric or backslash");
  2139. RETVAL_NULL();
  2140. goto error;
  2141. }
  2142. if (!zend_is_callable_ex(replace, NULL, 0, NULL, &fcc, NULL)) {
  2143. zend_argument_type_error(1, "must contain only valid callbacks");
  2144. goto error;
  2145. }
  2146. ZVAL_COPY_VALUE(&fci.function_name, replace);
  2147. replace_count += preg_replace_func_impl(&zv, str_idx_regex, /* regex_ht */ NULL, &fci, &fcc,
  2148. subject_str, subject_ht, limit, flags);
  2149. switch (Z_TYPE(zv)) {
  2150. case IS_ARRAY:
  2151. ZEND_ASSERT(subject_ht);
  2152. zend_array_release(subject_ht);
  2153. subject_ht = Z_ARR(zv);
  2154. break;
  2155. case IS_STRING:
  2156. ZEND_ASSERT(subject_str);
  2157. zend_string_release(subject_str);
  2158. subject_str = Z_STR(zv);
  2159. break;
  2160. case IS_NULL:
  2161. RETVAL_NULL();
  2162. goto error;
  2163. EMPTY_SWITCH_DEFAULT_CASE()
  2164. }
  2165. if (EG(exception)) {
  2166. goto error;
  2167. }
  2168. } ZEND_HASH_FOREACH_END();
  2169. if (zcount) {
  2170. ZEND_TRY_ASSIGN_REF_LONG(zcount, replace_count);
  2171. }
  2172. if (subject_ht) {
  2173. RETURN_ARR(subject_ht);
  2174. } else {
  2175. RETURN_STR(subject_str);
  2176. }
  2177. error:
  2178. if (subject_ht) {
  2179. zend_array_release(subject_ht);
  2180. } else {
  2181. zend_string_release(subject_str);
  2182. }
  2183. }
  2184. /* }}} */
  2185. /* {{{ Perform Perl-style regular expression replacement and only return matches. */
  2186. PHP_FUNCTION(preg_filter)
  2187. {
  2188. preg_replace_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, true);
  2189. }
  2190. /* }}} */
  2191. /* {{{ Split string into an array using a perl-style regular expression as a delimiter */
  2192. PHP_FUNCTION(preg_split)
  2193. {
  2194. zend_string *regex; /* Regular expression */
  2195. zend_string *subject; /* String to match against */
  2196. zend_long limit_val = -1;/* Integer value of limit */
  2197. zend_long flags = 0; /* Match control flags */
  2198. pcre_cache_entry *pce; /* Compiled regular expression */
  2199. /* Get function parameters and do error checking */
  2200. ZEND_PARSE_PARAMETERS_START(2, 4)
  2201. Z_PARAM_STR(regex)
  2202. Z_PARAM_STR(subject)
  2203. Z_PARAM_OPTIONAL
  2204. Z_PARAM_LONG(limit_val)
  2205. Z_PARAM_LONG(flags)
  2206. ZEND_PARSE_PARAMETERS_END();
  2207. /* Compile regex or get it from cache. */
  2208. if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
  2209. RETURN_FALSE;
  2210. }
  2211. pce->refcount++;
  2212. php_pcre_split_impl(pce, subject, return_value, limit_val, flags);
  2213. pce->refcount--;
  2214. }
  2215. /* }}} */
  2216. /* {{{ php_pcre_split */
  2217. PHPAPI void php_pcre_split_impl(pcre_cache_entry *pce, zend_string *subject_str, zval *return_value,
  2218. zend_long limit_val, zend_long flags)
  2219. {
  2220. PCRE2_SIZE *offsets; /* Array of subpattern offsets */
  2221. uint32_t options; /* Execution options */
  2222. int count; /* Count of matched subpatterns */
  2223. PCRE2_SIZE start_offset; /* Where the new search starts */
  2224. PCRE2_SIZE last_match_offset; /* Location of last match */
  2225. uint32_t no_empty; /* If NO_EMPTY flag is set */
  2226. uint32_t delim_capture; /* If delimiters should be captured */
  2227. uint32_t offset_capture; /* If offsets should be captured */
  2228. uint32_t num_subpats; /* Number of captured subpatterns */
  2229. zval tmp;
  2230. pcre2_match_data *match_data;
  2231. char *subject = ZSTR_VAL(subject_str);
  2232. no_empty = flags & PREG_SPLIT_NO_EMPTY;
  2233. delim_capture = flags & PREG_SPLIT_DELIM_CAPTURE;
  2234. offset_capture = flags & PREG_SPLIT_OFFSET_CAPTURE;
  2235. /* Initialize return value */
  2236. array_init(return_value);
  2237. /* Calculate the size of the offsets array, and allocate memory for it. */
  2238. num_subpats = pce->capture_count + 1;
  2239. /* Start at the beginning of the string */
  2240. start_offset = 0;
  2241. last_match_offset = 0;
  2242. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  2243. if (limit_val == -1) {
  2244. /* pass */
  2245. } else if (limit_val == 0) {
  2246. limit_val = -1;
  2247. } else if (limit_val <= 1) {
  2248. goto last;
  2249. }
  2250. if (!mdata_used && num_subpats <= PHP_PCRE_PREALLOC_MDATA_SIZE) {
  2251. match_data = mdata;
  2252. } else {
  2253. match_data = pcre2_match_data_create_from_pattern(pce->re, PCRE_G(gctx_zmm));
  2254. if (!match_data) {
  2255. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  2256. zval_ptr_dtor(return_value);
  2257. RETURN_FALSE;
  2258. }
  2259. }
  2260. options = (pce->compile_options & PCRE2_UTF) ? 0 : PCRE2_NO_UTF_CHECK;
  2261. #ifdef HAVE_PCRE_JIT_SUPPORT
  2262. if ((pce->preg_options & PREG_JIT) && options) {
  2263. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, ZSTR_LEN(subject_str), start_offset,
  2264. PCRE2_NO_UTF_CHECK, match_data, mctx);
  2265. } else
  2266. #endif
  2267. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, ZSTR_LEN(subject_str), start_offset,
  2268. options, match_data, mctx);
  2269. while (1) {
  2270. /* If something matched */
  2271. if (count >= 0) {
  2272. /* Check for too many substrings condition. */
  2273. if (UNEXPECTED(count == 0)) {
  2274. php_error_docref(NULL,E_NOTICE, "Matched, but too many substrings");
  2275. count = num_subpats;
  2276. }
  2277. matched:
  2278. offsets = pcre2_get_ovector_pointer(match_data);
  2279. if (UNEXPECTED(offsets[1] < offsets[0])) {
  2280. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  2281. break;
  2282. }
  2283. if (!no_empty || offsets[0] != last_match_offset) {
  2284. if (offset_capture) {
  2285. /* Add (match, offset) pair to the return value */
  2286. add_offset_pair(
  2287. return_value, subject, last_match_offset, offsets[0],
  2288. NULL, 0);
  2289. } else {
  2290. /* Add the piece to the return value */
  2291. populate_match_value_str(&tmp, subject, last_match_offset, offsets[0]);
  2292. zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &tmp);
  2293. }
  2294. /* One less left to do */
  2295. if (limit_val != -1)
  2296. limit_val--;
  2297. }
  2298. if (delim_capture) {
  2299. size_t i;
  2300. for (i = 1; i < count; i++) {
  2301. /* If we have matched a delimiter */
  2302. if (!no_empty || offsets[2*i] != offsets[2*i+1]) {
  2303. if (offset_capture) {
  2304. add_offset_pair(
  2305. return_value, subject, offsets[2*i], offsets[2*i+1], NULL, 0);
  2306. } else {
  2307. populate_match_value_str(&tmp, subject, offsets[2*i], offsets[2*i+1]);
  2308. zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &tmp);
  2309. }
  2310. }
  2311. }
  2312. }
  2313. /* Advance to the position right after the last full match */
  2314. start_offset = last_match_offset = offsets[1];
  2315. /* If we have matched an empty string, mimic what Perl's /g options does.
  2316. This turns out to be rather cunning. First we set PCRE2_NOTEMPTY_ATSTART and try
  2317. the match again at the same point. If this fails (picked up above) we
  2318. advance to the next character. */
  2319. if (start_offset == offsets[0]) {
  2320. /* Get next piece if no limit or limit not yet reached and something matched*/
  2321. if (limit_val != -1 && limit_val <= 1) {
  2322. break;
  2323. }
  2324. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, ZSTR_LEN(subject_str), start_offset,
  2325. PCRE2_NO_UTF_CHECK | PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED, match_data, mctx);
  2326. if (count >= 0) {
  2327. goto matched;
  2328. } else if (count == PCRE2_ERROR_NOMATCH) {
  2329. /* If we previously set PCRE2_NOTEMPTY_ATSTART after a null match,
  2330. this is not necessarily the end. We need to advance
  2331. the start offset, and continue. Fudge the offset values
  2332. to achieve this, unless we're already at the end of the string. */
  2333. if (start_offset < ZSTR_LEN(subject_str)) {
  2334. start_offset += calculate_unit_length(pce, subject + start_offset);
  2335. } else {
  2336. break;
  2337. }
  2338. } else {
  2339. goto error;
  2340. }
  2341. }
  2342. } else if (count == PCRE2_ERROR_NOMATCH) {
  2343. break;
  2344. } else {
  2345. error:
  2346. pcre_handle_exec_error(count);
  2347. break;
  2348. }
  2349. /* Get next piece if no limit or limit not yet reached and something matched*/
  2350. if (limit_val != -1 && limit_val <= 1) {
  2351. break;
  2352. }
  2353. #ifdef HAVE_PCRE_JIT_SUPPORT
  2354. if (pce->preg_options & PREG_JIT) {
  2355. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)subject, ZSTR_LEN(subject_str), start_offset,
  2356. PCRE2_NO_UTF_CHECK, match_data, mctx);
  2357. } else
  2358. #endif
  2359. count = pcre2_match(pce->re, (PCRE2_SPTR)subject, ZSTR_LEN(subject_str), start_offset,
  2360. PCRE2_NO_UTF_CHECK, match_data, mctx);
  2361. }
  2362. if (match_data != mdata) {
  2363. pcre2_match_data_free(match_data);
  2364. }
  2365. if (PCRE_G(error_code) != PHP_PCRE_NO_ERROR) {
  2366. zval_ptr_dtor(return_value);
  2367. RETURN_FALSE;
  2368. }
  2369. last:
  2370. start_offset = last_match_offset; /* the offset might have been incremented, but without further successful matches */
  2371. if (!no_empty || start_offset < ZSTR_LEN(subject_str)) {
  2372. if (offset_capture) {
  2373. /* Add the last (match, offset) pair to the return value */
  2374. add_offset_pair(return_value, subject, start_offset, ZSTR_LEN(subject_str), NULL, 0);
  2375. } else {
  2376. /* Add the last piece to the return value */
  2377. if (start_offset == 0) {
  2378. ZVAL_STR_COPY(&tmp, subject_str);
  2379. } else {
  2380. populate_match_value_str(&tmp, subject, start_offset, ZSTR_LEN(subject_str));
  2381. }
  2382. zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &tmp);
  2383. }
  2384. }
  2385. }
  2386. /* }}} */
  2387. /* {{{ Quote regular expression characters plus an optional character */
  2388. PHP_FUNCTION(preg_quote)
  2389. {
  2390. zend_string *str; /* Input string argument */
  2391. zend_string *delim = NULL; /* Additional delimiter argument */
  2392. char *in_str; /* Input string */
  2393. char *in_str_end; /* End of the input string */
  2394. zend_string *out_str; /* Output string with quoted characters */
  2395. size_t extra_len; /* Number of additional characters */
  2396. char *p, /* Iterator for input string */
  2397. *q, /* Iterator for output string */
  2398. delim_char = '\0', /* Delimiter character to be quoted */
  2399. c; /* Current character */
  2400. /* Get the arguments and check for errors */
  2401. ZEND_PARSE_PARAMETERS_START(1, 2)
  2402. Z_PARAM_STR(str)
  2403. Z_PARAM_OPTIONAL
  2404. Z_PARAM_STR_OR_NULL(delim)
  2405. ZEND_PARSE_PARAMETERS_END();
  2406. /* Nothing to do if we got an empty string */
  2407. if (ZSTR_LEN(str) == 0) {
  2408. RETURN_EMPTY_STRING();
  2409. }
  2410. in_str = ZSTR_VAL(str);
  2411. in_str_end = in_str + ZSTR_LEN(str);
  2412. if (delim) {
  2413. delim_char = ZSTR_VAL(delim)[0];
  2414. }
  2415. /* Go through the string and quote necessary characters */
  2416. extra_len = 0;
  2417. p = in_str;
  2418. do {
  2419. c = *p;
  2420. switch(c) {
  2421. case '.':
  2422. case '\\':
  2423. case '+':
  2424. case '*':
  2425. case '?':
  2426. case '[':
  2427. case '^':
  2428. case ']':
  2429. case '$':
  2430. case '(':
  2431. case ')':
  2432. case '{':
  2433. case '}':
  2434. case '=':
  2435. case '!':
  2436. case '>':
  2437. case '<':
  2438. case '|':
  2439. case ':':
  2440. case '-':
  2441. case '#':
  2442. extra_len++;
  2443. break;
  2444. case '\0':
  2445. extra_len+=3;
  2446. break;
  2447. default:
  2448. if (c == delim_char) {
  2449. extra_len++;
  2450. }
  2451. break;
  2452. }
  2453. p++;
  2454. } while (p != in_str_end);
  2455. if (extra_len == 0) {
  2456. RETURN_STR_COPY(str);
  2457. }
  2458. /* Allocate enough memory so that even if each character
  2459. is quoted, we won't run out of room */
  2460. out_str = zend_string_safe_alloc(1, ZSTR_LEN(str), extra_len, 0);
  2461. q = ZSTR_VAL(out_str);
  2462. p = in_str;
  2463. do {
  2464. c = *p;
  2465. switch(c) {
  2466. case '.':
  2467. case '\\':
  2468. case '+':
  2469. case '*':
  2470. case '?':
  2471. case '[':
  2472. case '^':
  2473. case ']':
  2474. case '$':
  2475. case '(':
  2476. case ')':
  2477. case '{':
  2478. case '}':
  2479. case '=':
  2480. case '!':
  2481. case '>':
  2482. case '<':
  2483. case '|':
  2484. case ':':
  2485. case '-':
  2486. case '#':
  2487. *q++ = '\\';
  2488. *q++ = c;
  2489. break;
  2490. case '\0':
  2491. *q++ = '\\';
  2492. *q++ = '0';
  2493. *q++ = '0';
  2494. *q++ = '0';
  2495. break;
  2496. default:
  2497. if (c == delim_char) {
  2498. *q++ = '\\';
  2499. }
  2500. *q++ = c;
  2501. break;
  2502. }
  2503. p++;
  2504. } while (p != in_str_end);
  2505. *q = '\0';
  2506. RETURN_NEW_STR(out_str);
  2507. }
  2508. /* }}} */
  2509. /* {{{ Searches array and returns entries which match regex */
  2510. PHP_FUNCTION(preg_grep)
  2511. {
  2512. zend_string *regex; /* Regular expression */
  2513. zval *input; /* Input array */
  2514. zend_long flags = 0; /* Match control flags */
  2515. pcre_cache_entry *pce; /* Compiled regular expression */
  2516. /* Get arguments and do error checking */
  2517. ZEND_PARSE_PARAMETERS_START(2, 3)
  2518. Z_PARAM_STR(regex)
  2519. Z_PARAM_ARRAY(input)
  2520. Z_PARAM_OPTIONAL
  2521. Z_PARAM_LONG(flags)
  2522. ZEND_PARSE_PARAMETERS_END();
  2523. /* Compile regex or get it from cache. */
  2524. if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
  2525. RETURN_FALSE;
  2526. }
  2527. pce->refcount++;
  2528. php_pcre_grep_impl(pce, input, return_value, flags);
  2529. pce->refcount--;
  2530. }
  2531. /* }}} */
  2532. PHPAPI void php_pcre_grep_impl(pcre_cache_entry *pce, zval *input, zval *return_value, zend_long flags) /* {{{ */
  2533. {
  2534. zval *entry; /* An entry in the input array */
  2535. uint32_t num_subpats; /* Number of captured subpatterns */
  2536. int count; /* Count of matched subpatterns */
  2537. uint32_t options; /* Execution options */
  2538. zend_string *string_key;
  2539. zend_ulong num_key;
  2540. bool invert; /* Whether to return non-matching
  2541. entries */
  2542. pcre2_match_data *match_data;
  2543. invert = flags & PREG_GREP_INVERT ? 1 : 0;
  2544. /* Calculate the size of the offsets array, and allocate memory for it. */
  2545. num_subpats = pce->capture_count + 1;
  2546. /* Initialize return array */
  2547. array_init(return_value);
  2548. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  2549. if (!mdata_used && num_subpats <= PHP_PCRE_PREALLOC_MDATA_SIZE) {
  2550. match_data = mdata;
  2551. } else {
  2552. match_data = pcre2_match_data_create_from_pattern(pce->re, PCRE_G(gctx_zmm));
  2553. if (!match_data) {
  2554. PCRE_G(error_code) = PHP_PCRE_INTERNAL_ERROR;
  2555. return;
  2556. }
  2557. }
  2558. options = (pce->compile_options & PCRE2_UTF) ? 0 : PCRE2_NO_UTF_CHECK;
  2559. /* Go through the input array */
  2560. ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(input), num_key, string_key, entry) {
  2561. zend_string *tmp_subject_str;
  2562. zend_string *subject_str = zval_get_tmp_string(entry, &tmp_subject_str);
  2563. /* Perform the match */
  2564. #ifdef HAVE_PCRE_JIT_SUPPORT
  2565. if ((pce->preg_options & PREG_JIT) && options) {
  2566. count = pcre2_jit_match(pce->re, (PCRE2_SPTR)ZSTR_VAL(subject_str), ZSTR_LEN(subject_str), 0,
  2567. PCRE2_NO_UTF_CHECK, match_data, mctx);
  2568. } else
  2569. #endif
  2570. count = pcre2_match(pce->re, (PCRE2_SPTR)ZSTR_VAL(subject_str), ZSTR_LEN(subject_str), 0,
  2571. options, match_data, mctx);
  2572. /* If the entry fits our requirements */
  2573. if (count >= 0) {
  2574. /* Check for too many substrings condition. */
  2575. if (UNEXPECTED(count == 0)) {
  2576. php_error_docref(NULL, E_NOTICE, "Matched, but too many substrings");
  2577. }
  2578. if (!invert) {
  2579. Z_TRY_ADDREF_P(entry);
  2580. /* Add to return array */
  2581. if (string_key) {
  2582. zend_hash_update(Z_ARRVAL_P(return_value), string_key, entry);
  2583. } else {
  2584. zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry);
  2585. }
  2586. }
  2587. } else if (count == PCRE2_ERROR_NOMATCH) {
  2588. if (invert) {
  2589. Z_TRY_ADDREF_P(entry);
  2590. /* Add to return array */
  2591. if (string_key) {
  2592. zend_hash_update(Z_ARRVAL_P(return_value), string_key, entry);
  2593. } else {
  2594. zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry);
  2595. }
  2596. }
  2597. } else {
  2598. pcre_handle_exec_error(count);
  2599. zend_tmp_string_release(tmp_subject_str);
  2600. break;
  2601. }
  2602. zend_tmp_string_release(tmp_subject_str);
  2603. } ZEND_HASH_FOREACH_END();
  2604. if (match_data != mdata) {
  2605. pcre2_match_data_free(match_data);
  2606. }
  2607. }
  2608. /* }}} */
  2609. /* {{{ Returns the error code of the last regexp execution. */
  2610. PHP_FUNCTION(preg_last_error)
  2611. {
  2612. ZEND_PARSE_PARAMETERS_NONE();
  2613. RETURN_LONG(PCRE_G(error_code));
  2614. }
  2615. /* }}} */
  2616. /* {{{ Returns the error message of the last regexp execution. */
  2617. PHP_FUNCTION(preg_last_error_msg)
  2618. {
  2619. ZEND_PARSE_PARAMETERS_NONE();
  2620. RETURN_STRING(php_pcre_get_error_msg(PCRE_G(error_code)));
  2621. }
  2622. /* }}} */
  2623. /* {{{ module definition structures */
  2624. zend_module_entry pcre_module_entry = {
  2625. STANDARD_MODULE_HEADER,
  2626. "pcre",
  2627. ext_functions,
  2628. PHP_MINIT(pcre),
  2629. PHP_MSHUTDOWN(pcre),
  2630. PHP_RINIT(pcre),
  2631. PHP_RSHUTDOWN(pcre),
  2632. PHP_MINFO(pcre),
  2633. PHP_PCRE_VERSION,
  2634. PHP_MODULE_GLOBALS(pcre),
  2635. PHP_GINIT(pcre),
  2636. PHP_GSHUTDOWN(pcre),
  2637. NULL,
  2638. STANDARD_MODULE_PROPERTIES_EX
  2639. };
  2640. #ifdef COMPILE_DL_PCRE
  2641. ZEND_GET_MODULE(pcre)
  2642. #endif
  2643. /* }}} */
  2644. PHPAPI pcre2_match_context *php_pcre_mctx(void)
  2645. {/*{{{*/
  2646. return mctx;
  2647. }/*}}}*/
  2648. PHPAPI pcre2_general_context *php_pcre_gctx(void)
  2649. {/*{{{*/
  2650. return gctx;
  2651. }/*}}}*/
  2652. PHPAPI pcre2_compile_context *php_pcre_cctx(void)
  2653. {/*{{{*/
  2654. return cctx;
  2655. }/*}}}*/
  2656. PHPAPI void php_pcre_pce_incref(pcre_cache_entry *pce)
  2657. {/*{{{*/
  2658. assert(NULL != pce);
  2659. pce->refcount++;
  2660. }/*}}}*/
  2661. PHPAPI void php_pcre_pce_decref(pcre_cache_entry *pce)
  2662. {/*{{{*/
  2663. assert(NULL != pce);
  2664. assert(0 != pce->refcount);
  2665. pce->refcount--;
  2666. }/*}}}*/
  2667. PHPAPI pcre2_code *php_pcre_pce_re(pcre_cache_entry *pce)
  2668. {/*{{{*/
  2669. assert(NULL != pce);
  2670. return pce->re;
  2671. }/*}}}*/