php_pcre.c 88 KB

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