PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LCOV - code coverage report
Current view: top level - ext/pcre - php_pcre.c (source / functions) Hit Total Coverage
Test: PHP Code Coverage Lines: 876 953 91.9 %
Date: 2016-09-18 Functions: 33 34 97.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :    +----------------------------------------------------------------------+
       3             :    | PHP Version 7                                                        |
       4             :    +----------------------------------------------------------------------+
       5             :    | Copyright (c) 1997-2016 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             : 
      19             : /* $Id$ */
      20             : 
      21             : #include "php.h"
      22             : #include "php_ini.h"
      23             : #include "php_globals.h"
      24             : #include "php_pcre.h"
      25             : #include "ext/standard/info.h"
      26             : #include "ext/standard/basic_functions.h"
      27             : #include "zend_smart_str.h"
      28             : 
      29             : #if HAVE_PCRE || HAVE_BUNDLED_PCRE
      30             : 
      31             : #include "ext/standard/php_string.h"
      32             : 
      33             : #define PREG_PATTERN_ORDER                      1
      34             : #define PREG_SET_ORDER                          2
      35             : #define PREG_OFFSET_CAPTURE                     (1<<8)
      36             : 
      37             : #define PREG_SPLIT_NO_EMPTY                     (1<<0)
      38             : #define PREG_SPLIT_DELIM_CAPTURE        (1<<1)
      39             : #define PREG_SPLIT_OFFSET_CAPTURE       (1<<2)
      40             : 
      41             : #define PREG_REPLACE_EVAL                       (1<<0)
      42             : 
      43             : #define PREG_GREP_INVERT                        (1<<0)
      44             : 
      45             : #define PCRE_CACHE_SIZE 4096
      46             : 
      47             : /* not fully functional workaround for libpcre < 8.0, see bug #70232 */
      48             : #ifndef PCRE_NOTEMPTY_ATSTART
      49             : # define PCRE_NOTEMPTY_ATSTART PCRE_NOTEMPTY
      50             : #endif
      51             : 
      52             : enum {
      53             :         PHP_PCRE_NO_ERROR = 0,
      54             :         PHP_PCRE_INTERNAL_ERROR,
      55             :         PHP_PCRE_BACKTRACK_LIMIT_ERROR,
      56             :         PHP_PCRE_RECURSION_LIMIT_ERROR,
      57             :         PHP_PCRE_BAD_UTF8_ERROR,
      58             :         PHP_PCRE_BAD_UTF8_OFFSET_ERROR,
      59             :         PHP_PCRE_JIT_STACKLIMIT_ERROR
      60             : };
      61             : 
      62             : 
      63             : PHPAPI ZEND_DECLARE_MODULE_GLOBALS(pcre)
      64             : 
      65             : #ifdef PCRE_STUDY_JIT_COMPILE
      66             : #define PCRE_JIT_STACK_MIN_SIZE (32 * 1024)
      67             : #define PCRE_JIT_STACK_MAX_SIZE (64 * 1024)
      68             : ZEND_TLS pcre_jit_stack *jit_stack = NULL;
      69             : #endif
      70             : 
      71          17 : static void pcre_handle_exec_error(int pcre_code) /* {{{ */
      72             : {
      73          17 :         int preg_code = 0;
      74             : 
      75          17 :         switch (pcre_code) {
      76             :                 case PCRE_ERROR_MATCHLIMIT:
      77           4 :                         preg_code = PHP_PCRE_BACKTRACK_LIMIT_ERROR;
      78           4 :                         break;
      79             : 
      80             :                 case PCRE_ERROR_RECURSIONLIMIT:
      81           2 :                         preg_code = PHP_PCRE_RECURSION_LIMIT_ERROR;
      82           2 :                         break;
      83             : 
      84             :                 case PCRE_ERROR_BADUTF8:
      85           8 :                         preg_code = PHP_PCRE_BAD_UTF8_ERROR;
      86           8 :                         break;
      87             : 
      88             :                 case PCRE_ERROR_BADUTF8_OFFSET:
      89           1 :                         preg_code = PHP_PCRE_BAD_UTF8_OFFSET_ERROR;
      90           1 :                         break;
      91             :                 
      92             : #ifdef PCRE_STUDY_JIT_COMPILE
      93             :                 case PCRE_ERROR_JIT_STACKLIMIT:
      94           1 :                         preg_code = PHP_PCRE_JIT_STACKLIMIT_ERROR;
      95           1 :                         break;
      96             : #endif
      97             : 
      98             :                 default:
      99           1 :                         preg_code = PHP_PCRE_INTERNAL_ERROR;
     100             :                         break;
     101             :         }
     102             : 
     103          17 :         PCRE_G(error_code) = preg_code;
     104          17 : }
     105             : /* }}} */
     106             : 
     107       63297 : static void php_free_pcre_cache(zval *data) /* {{{ */
     108             : {
     109       63297 :         pcre_cache_entry *pce = (pcre_cache_entry *) Z_PTR_P(data);
     110       63297 :         if (!pce) return;
     111       63297 :         pcre_free(pce->re);
     112       63297 :         if (pce->extra) {
     113       63289 :                 pcre_free_study(pce->extra);
     114             :         }
     115             : #if HAVE_SETLOCALE
     116       63297 :         if ((void*)pce->tables) pefree((void*)pce->tables, 1);
     117       63297 :         if (pce->locale) {
     118           8 :                 zend_string_release(pce->locale);
     119             :         }
     120             : #endif
     121       63297 :         pefree(pce, 1);
     122             : }
     123             : /* }}} */
     124             : 
     125       23922 : static PHP_GINIT_FUNCTION(pcre) /* {{{ */
     126             : {
     127       23922 :         zend_hash_init(&pcre_globals->pcre_cache, 0, NULL, php_free_pcre_cache, 1);
     128       23922 :         pcre_globals->backtrack_limit = 0;
     129       23922 :         pcre_globals->recursion_limit = 0;
     130       23922 :         pcre_globals->error_code      = PHP_PCRE_NO_ERROR;
     131       23922 : }
     132             : /* }}} */
     133             : 
     134       23963 : static PHP_GSHUTDOWN_FUNCTION(pcre) /* {{{ */
     135             : {
     136       23963 :         zend_hash_destroy(&pcre_globals->pcre_cache);
     137             : 
     138             : #ifdef PCRE_STUDY_JIT_COMPILE
     139             :         /* Stack may only be destroyed when no cached patterns
     140             :                 possibly associated with it do exist. */
     141       23963 :         if (jit_stack) {
     142       23913 :                 pcre_jit_stack_free(jit_stack);
     143       23913 :                 jit_stack = NULL;
     144             :         }
     145             : #endif
     146             : 
     147       23963 : }
     148             : /* }}} */
     149             : 
     150             : PHP_INI_BEGIN()
     151             :         STD_PHP_INI_ENTRY("pcre.backtrack_limit", "1000000", PHP_INI_ALL, OnUpdateLong, backtrack_limit, zend_pcre_globals, pcre_globals)
     152             :         STD_PHP_INI_ENTRY("pcre.recursion_limit", "100000",  PHP_INI_ALL, OnUpdateLong, recursion_limit, zend_pcre_globals, pcre_globals)
     153             : #ifdef PCRE_STUDY_JIT_COMPILE
     154             :         STD_PHP_INI_ENTRY("pcre.jit",             "1",       PHP_INI_ALL, OnUpdateBool, jit,             zend_pcre_globals, pcre_globals)
     155             : #endif
     156             : PHP_INI_END()
     157             : 
     158             : 
     159             : /* {{{ PHP_MINFO_FUNCTION(pcre) */
     160         150 : static PHP_MINFO_FUNCTION(pcre)
     161             : {
     162         150 :         int jit_yes = 0;
     163             : 
     164         150 :         php_info_print_table_start();
     165         150 :         php_info_print_table_row(2, "PCRE (Perl Compatible Regular Expressions) Support", "enabled" );
     166         150 :         php_info_print_table_row(2, "PCRE Library Version", pcre_version() );
     167             : 
     168         150 :         if (!pcre_config(PCRE_CONFIG_JIT, &jit_yes)) {
     169         150 :                 php_info_print_table_row(2, "PCRE JIT Support", jit_yes ? "enabled" : "disabled");
     170             :         } else {
     171           0 :                 php_info_print_table_row(2, "PCRE JIT Support", "unknown" );
     172             :         }
     173             : 
     174         150 :         php_info_print_table_end();
     175             : 
     176         150 :         DISPLAY_INI_ENTRIES();
     177         150 : }
     178             : /* }}} */
     179             : 
     180             : /* {{{ PHP_MINIT_FUNCTION(pcre) */
     181       23922 : static PHP_MINIT_FUNCTION(pcre)
     182             : {
     183       23922 :         REGISTER_INI_ENTRIES();
     184             : 
     185       23922 :         REGISTER_LONG_CONSTANT("PREG_PATTERN_ORDER", PREG_PATTERN_ORDER, CONST_CS | CONST_PERSISTENT);
     186       23922 :         REGISTER_LONG_CONSTANT("PREG_SET_ORDER", PREG_SET_ORDER, CONST_CS | CONST_PERSISTENT);
     187       23922 :         REGISTER_LONG_CONSTANT("PREG_OFFSET_CAPTURE", PREG_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
     188       23922 :         REGISTER_LONG_CONSTANT("PREG_SPLIT_NO_EMPTY", PREG_SPLIT_NO_EMPTY, CONST_CS | CONST_PERSISTENT);
     189       23922 :         REGISTER_LONG_CONSTANT("PREG_SPLIT_DELIM_CAPTURE", PREG_SPLIT_DELIM_CAPTURE, CONST_CS | CONST_PERSISTENT);
     190       23922 :         REGISTER_LONG_CONSTANT("PREG_SPLIT_OFFSET_CAPTURE", PREG_SPLIT_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
     191       23922 :         REGISTER_LONG_CONSTANT("PREG_GREP_INVERT", PREG_GREP_INVERT, CONST_CS | CONST_PERSISTENT);
     192             : 
     193       23922 :         REGISTER_LONG_CONSTANT("PREG_NO_ERROR", PHP_PCRE_NO_ERROR, CONST_CS | CONST_PERSISTENT);
     194       23922 :         REGISTER_LONG_CONSTANT("PREG_INTERNAL_ERROR", PHP_PCRE_INTERNAL_ERROR, CONST_CS | CONST_PERSISTENT);
     195       23922 :         REGISTER_LONG_CONSTANT("PREG_BACKTRACK_LIMIT_ERROR", PHP_PCRE_BACKTRACK_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
     196       23922 :         REGISTER_LONG_CONSTANT("PREG_RECURSION_LIMIT_ERROR", PHP_PCRE_RECURSION_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
     197       23922 :         REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_ERROR", PHP_PCRE_BAD_UTF8_ERROR, CONST_CS | CONST_PERSISTENT);
     198       23922 :         REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_OFFSET_ERROR", PHP_PCRE_BAD_UTF8_OFFSET_ERROR, CONST_CS | CONST_PERSISTENT);
     199       23922 :         REGISTER_LONG_CONSTANT("PREG_JIT_STACKLIMIT_ERROR", PHP_PCRE_JIT_STACKLIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
     200       23922 :         REGISTER_STRING_CONSTANT("PCRE_VERSION", (char *)pcre_version(), CONST_CS | CONST_PERSISTENT);
     201             : 
     202       23922 :         return SUCCESS;
     203             : }
     204             : /* }}} */
     205             : 
     206             : /* {{{ PHP_MSHUTDOWN_FUNCTION(pcre) */
     207       23963 : static PHP_MSHUTDOWN_FUNCTION(pcre)
     208             : {
     209       23963 :         UNREGISTER_INI_ENTRIES();
     210             : 
     211       23963 :         return SUCCESS;
     212             : }
     213             : /* }}} */
     214             : 
     215             : #ifdef PCRE_STUDY_JIT_COMPILE
     216             : /* {{{ PHP_RINIT_FUNCTION(pcre) */
     217       23876 : static PHP_RINIT_FUNCTION(pcre)
     218             : {
     219       23876 :         if (PCRE_G(jit) && jit_stack == NULL) {
     220       23870 :                 jit_stack = pcre_jit_stack_alloc(PCRE_JIT_STACK_MIN_SIZE,PCRE_JIT_STACK_MAX_SIZE);
     221             :         }
     222             : 
     223       23876 :         return SUCCESS;
     224             : }
     225             : /* }}} */
     226             : #endif
     227             : 
     228             : /* {{{ static pcre_clean_cache */
     229      274432 : static int pcre_clean_cache(zval *data, void *arg)
     230             : {
     231      274432 :         pcre_cache_entry *pce = (pcre_cache_entry *) Z_PTR_P(data);
     232      274432 :         int *num_clean = (int *)arg;
     233             : 
     234      274432 :         if (*num_clean > 0 && !pce->refcount) {
     235       34304 :                 (*num_clean)--;
     236       34304 :                 return ZEND_HASH_APPLY_REMOVE;
     237             :         } else {
     238      240128 :                 return ZEND_HASH_APPLY_KEEP;
     239             :         }
     240             : }
     241             : /* }}} */
     242             : 
     243             : /* {{{ static make_subpats_table */
     244          13 : static char **make_subpats_table(int num_subpats, pcre_cache_entry *pce)
     245             : {
     246          13 :         pcre_extra *extra = pce->extra;
     247          13 :         int name_cnt = pce->name_count, name_size, ni = 0;
     248             :         int rc;
     249             :         char *name_table;
     250             :         unsigned short name_idx;
     251             :         char **subpat_names;
     252             :         int rc1, rc2;
     253             : 
     254          13 :         rc1 = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMETABLE, &name_table);
     255          13 :         rc2 = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMEENTRYSIZE, &name_size);
     256          13 :         rc = rc2 ? rc2 : rc1;
     257          13 :         if (rc < 0) {
     258           0 :                 php_error_docref(NULL, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
     259           0 :                 return NULL;
     260             :         }
     261             : 
     262          13 :         subpat_names = (char **)ecalloc(num_subpats, sizeof(char *));
     263         486 :         while (ni++ < name_cnt) {
     264         460 :                 name_idx = 0x100 * (unsigned char)name_table[0] + (unsigned char)name_table[1];
     265         460 :                 subpat_names[name_idx] = name_table + 2;
     266         920 :                 if (is_numeric_string(subpat_names[name_idx], strlen(subpat_names[name_idx]), NULL, NULL, 0) > 0) {
     267           0 :                         php_error_docref(NULL, E_WARNING, "Numeric named subpatterns are not allowed");
     268           0 :                         efree(subpat_names);
     269           0 :                         return NULL;
     270             :                 }
     271         460 :                 name_table += name_size;
     272             :         }
     273          13 :         return subpat_names;
     274             : }
     275             : /* }}} */
     276             : 
     277             : /* {{{ static calculate_unit_length */
     278             : /* Calculates the byte length of the next character. Assumes valid UTF-8 for PCRE_UTF8. */
     279             : static zend_always_inline int calculate_unit_length(pcre_cache_entry *pce, char *start)
     280             : {
     281             :         int unit_len;
     282             : 
     283          79 :         if (pce->compile_options & PCRE_UTF8) {
     284          22 :                 char *end = start;
     285             : 
     286             :                 /* skip continuation bytes */
     287          35 :                 while ((*++end & 0xC0) == 0x80);
     288          22 :                 unit_len = end - start;
     289             :         } else {
     290          57 :                 unit_len = 1;
     291             :         }
     292          79 :         return unit_len;
     293             : }
     294             : /* }}} */
     295             : 
     296             : /* {{{ pcre_get_compiled_regex_cache
     297             :  */
     298     1997085 : PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache(zend_string *regex)
     299             : {
     300     1997085 :         pcre                            *re = NULL;
     301             :         pcre_extra                      *extra;
     302     1997085 :         int                                      coptions = 0;
     303     1997085 :         int                                      soptions = 0;
     304             :         const char                      *error;
     305             :         int                                      erroffset;
     306             :         char                             delimiter;
     307             :         char                             start_delimiter;
     308             :         char                             end_delimiter;
     309             :         char                            *p, *pp;
     310             :         char                            *pattern;
     311     1997085 :         int                                      do_study = 0;
     312     1997085 :         int                                      poptions = 0;
     313     1997085 :         unsigned const char *tables = NULL;
     314             :         pcre_cache_entry        *pce;
     315             :         pcre_cache_entry         new_entry;
     316             :         int                                      rc;
     317             : 
     318             :         /* Try to lookup the cached regex entry, and if successful, just pass
     319             :            back the compiled pattern, otherwise go on and compile it. */
     320     1997085 :         pce = zend_hash_find_ptr(&PCRE_G(pcre_cache), regex);
     321     1997085 :         if (pce) {
     322             : #if HAVE_SETLOCALE
     323     1933827 :                 if (pce->locale == BG(locale_string) ||
     324          40 :                     (pce->locale && BG(locale_string) &&
     325          20 :                      ZSTR_LEN(pce->locale) == ZSTR_LEN(BG(locale_string)) &&
     326          18 :                      !memcmp(ZSTR_VAL(pce->locale), ZSTR_VAL(BG(locale_string)), ZSTR_LEN(pce->locale))) ||
     327           2 :                     (!pce->locale &&
     328           0 :                      ZSTR_LEN(BG(locale_string)) == 1 &&
     329           0 :                      ZSTR_VAL(BG(locale_string))[0] == 'C') ||
     330           2 :                     (!BG(locale_string) &&
     331           0 :                      ZSTR_LEN(pce->locale) == 1 &&
     332           0 :                      ZSTR_VAL(pce->locale)[0] == 'C')) {
     333     1933743 :                         return pce;
     334             :                 }
     335             : #else
     336             :                 return pce;
     337             : #endif
     338             :         }
     339             : 
     340       63342 :         p = ZSTR_VAL(regex);
     341             : 
     342             :         /* Parse through the leading whitespace, and display a warning if we
     343             :            get to the end without encountering a delimiter. */
     344       63342 :         while (isspace((int)*(unsigned char *)p)) p++;
     345       63342 :         if (*p == 0) {
     346           5 :                 php_error_docref(NULL, E_WARNING,
     347           5 :                                                  p < ZSTR_VAL(regex) + ZSTR_LEN(regex) ? "Null byte in regex" : "Empty regular expression");
     348           5 :                 return NULL;
     349             :         }
     350             : 
     351             :         /* Get the delimiter and display a warning if it is alphanumeric
     352             :            or a backslash. */
     353       63337 :         delimiter = *p++;
     354       63337 :         if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') {
     355           7 :                 php_error_docref(NULL,E_WARNING, "Delimiter must not be alphanumeric or backslash");
     356           7 :                 return NULL;
     357             :         }
     358             : 
     359       63330 :         start_delimiter = delimiter;
     360       63330 :         if ((pp = strchr("([{< )]}> )]}>", delimiter)))
     361          30 :                 delimiter = pp[5];
     362       63330 :         end_delimiter = delimiter;
     363             : 
     364       63330 :         pp = p;
     365             : 
     366       63330 :         if (start_delimiter == end_delimiter) {
     367             :                 /* We need to iterate through the pattern, searching for the ending delimiter,
     368             :                    but skipping the backslashed delimiters.  If the ending delimiter is not
     369             :                    found, display a warning. */
     370    17262595 :                 while (*pp != 0) {
     371    17199285 :                         if (*pp == '\\' && pp[1] != 0) pp++;
     372    15976813 :                         else if (*pp == delimiter)
     373       63290 :                                 break;
     374    17135995 :                         pp++;
     375             :                 }
     376             :         } else {
     377             :                 /* We iterate through the pattern, searching for the matching ending
     378             :                  * delimiter. For each matching starting delimiter, we increment nesting
     379             :                  * level, and decrement it for each matching ending delimiter. If we
     380             :                  * reach the end of the pattern without matching, display a warning.
     381             :                  */
     382          30 :                 int brackets = 1;       /* brackets nesting level */
     383         923 :                 while (*pp != 0) {
     384         890 :                         if (*pp == '\\' && pp[1] != 0) pp++;
     385         768 :                         else if (*pp == end_delimiter && --brackets <= 0)
     386             :                                 break;
     387         741 :                         else if (*pp == start_delimiter)
     388          24 :                                 brackets++;
     389         863 :                         pp++;
     390             :                 }
     391             :         }
     392             : 
     393       63330 :         if (*pp == 0) {
     394          13 :                 if (pp < ZSTR_VAL(regex) + ZSTR_LEN(regex)) {
     395           4 :                         php_error_docref(NULL,E_WARNING, "Null byte in regex");
     396           9 :                 } else if (start_delimiter == end_delimiter) {
     397           8 :                         php_error_docref(NULL,E_WARNING, "No ending delimiter '%c' found", delimiter);
     398             :                 } else {
     399           1 :                         php_error_docref(NULL,E_WARNING, "No ending matching delimiter '%c' found", delimiter);
     400             :                 }
     401          13 :                 return NULL;
     402             :         }
     403             : 
     404             :         /* Make a copy of the actual pattern. */
     405       63317 :         pattern = estrndup(p, pp-p);
     406             : 
     407             :         /* Move on to the options */
     408       63317 :         pp++;
     409             : 
     410             :         /* Parse through the options, setting appropriate flags.  Display
     411             :            a warning if we encounter an unknown modifier. */
     412      141604 :         while (pp < ZSTR_VAL(regex) + ZSTR_LEN(regex)) {
     413       14988 :                 switch (*pp++) {
     414             :                         /* Perl compatible options */
     415        1946 :                         case 'i':       coptions |= PCRE_CASELESS;              break;
     416        2398 :                         case 'm':       coptions |= PCRE_MULTILINE;             break;
     417       10524 :                         case 's':       coptions |= PCRE_DOTALL;                break;
     418           6 :                         case 'x':       coptions |= PCRE_EXTENDED;              break;
     419             : 
     420             :                         /* PCRE specific options */
     421           2 :                         case 'A':       coptions |= PCRE_ANCHORED;              break;
     422          10 :                         case 'D':       coptions |= PCRE_DOLLAR_ENDONLY;break;
     423          25 :                         case 'S':       do_study  = 1;                                  break;
     424          20 :                         case 'U':       coptions |= PCRE_UNGREEDY;              break;
     425           1 :                         case 'X':       coptions |= PCRE_EXTRA;                 break;
     426          33 :                         case 'u':       coptions |= PCRE_UTF8;
     427             :         /* In  PCRE,  by  default, \d, \D, \s, \S, \w, and \W recognize only ASCII
     428             :        characters, even in UTF-8 mode. However, this can be changed by setting
     429             :        the PCRE_UCP option. */
     430             : #ifdef PCRE_UCP
     431          33 :                                                 coptions |= PCRE_UCP;
     432             : #endif
     433          33 :                                 break;
     434           1 :                         case 'J':       coptions |= PCRE_DUPNAMES;              break;
     435             : 
     436             :                         /* Custom preg options */
     437           2 :                         case 'e':       poptions |= PREG_REPLACE_EVAL;  break;
     438             : 
     439             :                         case ' ':
     440             :                         case '\n':
     441           2 :                                 break;
     442             : 
     443             :                         default:
     444          18 :                                 if (pp[-1]) {
     445          13 :                                         php_error_docref(NULL,E_WARNING, "Unknown modifier '%c'", pp[-1]);
     446             :                                 } else {
     447           5 :                                         php_error_docref(NULL,E_WARNING, "Null byte in regex");
     448             :                                 }
     449          18 :                                 efree(pattern);
     450          18 :                                 return NULL;
     451             :                 }
     452             :         }
     453             : 
     454             : #if HAVE_SETLOCALE
     455       63311 :         if (BG(locale_string) &&
     456          12 :             (ZSTR_LEN(BG(locale_string)) != 1 || ZSTR_VAL(BG(locale_string))[0] != 'C')) {
     457           4 :                 tables = pcre_maketables();
     458             :         }
     459             : #endif
     460             : 
     461             :         /* Compile pattern and display a warning if compilation failed. */
     462       63299 :         re = pcre_compile(pattern,
     463             :                                           coptions,
     464             :                                           &error,
     465             :                                           &erroffset,
     466             :                                           tables);
     467             : 
     468       63299 :         if (re == NULL) {
     469           6 :                 php_error_docref(NULL,E_WARNING, "Compilation failed: %s at offset %d", error, erroffset);
     470           6 :                 efree(pattern);
     471           6 :                 if (tables) {
     472           0 :                         pefree((void*)tables, 1);
     473             :                 }
     474           6 :                 return NULL;
     475             :         }
     476             : 
     477             : #ifdef PCRE_STUDY_JIT_COMPILE
     478       63293 :         if (PCRE_G(jit)) {
     479             :                 /* Enable PCRE JIT compiler */
     480       63285 :                 do_study = 1;
     481       63285 :                 soptions |= PCRE_STUDY_JIT_COMPILE;
     482             :         }
     483             : #endif
     484             : 
     485             :         /* If study option was specified, study the pattern and
     486             :            store the result in extra for passing to pcre_exec. */
     487       63293 :         if (do_study) {
     488       63285 :                 extra = pcre_study(re, soptions, &error);
     489       63285 :                 if (extra) {
     490       63285 :                         extra->flags |= PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
     491       63285 :                         extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
     492       63285 :                         extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
     493             : #ifdef PCRE_STUDY_JIT_COMPILE
     494       63285 :                         if (PCRE_G(jit) && jit_stack) {
     495       63285 :                                 pcre_assign_jit_stack(extra, NULL, jit_stack);
     496             :                         }
     497             : #endif
     498             :                 }
     499       63285 :                 if (error != NULL) {
     500           0 :                         php_error_docref(NULL, E_WARNING, "Error while studying pattern");
     501             :                 }
     502             :         } else {
     503           8 :                 extra = NULL;
     504             :         }
     505             : 
     506       63293 :         efree(pattern);
     507             : 
     508             :         /*
     509             :          * If we reached cache limit, clean out the items from the head of the list;
     510             :          * these are supposedly the oldest ones (but not necessarily the least used
     511             :          * ones).
     512             :          */
     513       63293 :         if (zend_hash_num_elements(&PCRE_G(pcre_cache)) == PCRE_CACHE_SIZE) {
     514          67 :                 int num_clean = PCRE_CACHE_SIZE / 8;
     515          67 :                 zend_hash_apply_with_argument(&PCRE_G(pcre_cache), pcre_clean_cache, &num_clean);
     516             :         }
     517             : 
     518             :         /* Store the compiled pattern and extra info in the cache. */
     519       63293 :         new_entry.re = re;
     520       63293 :         new_entry.extra = extra;
     521       63293 :         new_entry.preg_options = poptions;
     522       63293 :         new_entry.compile_options = coptions;
     523             : #if HAVE_SETLOCALE
     524       63301 :         new_entry.locale = BG(locale_string) ?
     525          16 :                 ((GC_FLAGS(BG(locale_string)) & IS_STR_PERSISTENT) ?
     526           0 :                         zend_string_copy(BG(locale_string)) :
     527           8 :                         zend_string_init(ZSTR_VAL(BG(locale_string)), ZSTR_LEN(BG(locale_string)), 1)) :
     528             :                 NULL;
     529       63293 :         new_entry.tables = tables;
     530             : #endif
     531       63293 :         new_entry.refcount = 0;
     532             : 
     533       63293 :         rc = pcre_fullinfo(re, extra, PCRE_INFO_CAPTURECOUNT, &new_entry.capture_count);
     534       63293 :         if (rc < 0) {
     535           0 :                 php_error_docref(NULL, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
     536           0 :                 return NULL;
     537             :         }
     538             : 
     539       63293 :         rc = pcre_fullinfo(re, extra, PCRE_INFO_NAMECOUNT, &new_entry.name_count);
     540       63293 :         if (rc < 0) {
     541           0 :                 php_error_docref(NULL, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
     542           0 :                 return NULL;
     543             :         }
     544             : 
     545             :         /*
     546             :          * Interned strings are not duplicated when stored in HashTable,
     547             :          * but all the interned strings created during HTTP request are removed
     548             :          * at end of request. However PCRE_G(pcre_cache) must be consistent
     549             :          * on the next request as well. So we disable usage of interned strings
     550             :          * as hash keys especually for this table.
     551             :          * See bug #63180
     552             :          */
     553       63293 :         if (!ZSTR_IS_INTERNED(regex) || !(GC_FLAGS(regex) & IS_STR_PERMANENT)) {
     554      126584 :                 zend_string *str = zend_string_init(ZSTR_VAL(regex), ZSTR_LEN(regex), 1);
     555       63292 :                 GC_REFCOUNT(str) = 0; /* will be incremented by zend_hash_update_mem() */
     556       63292 :                 ZSTR_H(str) = ZSTR_H(regex);
     557       63292 :                 regex = str;
     558             :         }
     559             : 
     560       63293 :         pce = zend_hash_update_mem(&PCRE_G(pcre_cache), regex, &new_entry, sizeof(pcre_cache_entry));
     561             : 
     562       63293 :         return pce;
     563             : }
     564             : /* }}} */
     565             : 
     566             : /* {{{ pcre_get_compiled_regex
     567             :  */
     568      132749 : PHPAPI pcre* pcre_get_compiled_regex(zend_string *regex, pcre_extra **extra, int *preg_options)
     569             : {
     570      132749 :         pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex);
     571             : 
     572      132749 :         if (extra) {
     573      132749 :                 *extra = pce ? pce->extra : NULL;
     574             :         }
     575      132749 :         if (preg_options) {
     576      132749 :                 *preg_options = pce ? pce->preg_options : 0;
     577             :         }
     578             : 
     579      132749 :         return pce ? pce->re : NULL;
     580             : }
     581             : /* }}} */
     582             : 
     583             : /* {{{ pcre_get_compiled_regex_ex
     584             :  */
     585           0 : PHPAPI pcre* pcre_get_compiled_regex_ex(zend_string *regex, pcre_extra **extra, int *preg_options, int *compile_options)
     586             : {
     587           0 :         pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex);
     588             : 
     589           0 :         if (extra) {
     590           0 :                 *extra = pce ? pce->extra : NULL;
     591             :         }
     592           0 :         if (preg_options) {
     593           0 :                 *preg_options = pce ? pce->preg_options : 0;
     594             :         }
     595           0 :         if (compile_options) {
     596           0 :                 *compile_options = pce ? pce->compile_options : 0;
     597             :         }
     598             : 
     599           0 :         return pce ? pce->re : NULL;
     600             : }
     601             : /* }}} */
     602             : 
     603             : /* {{{ add_offset_pair */
     604          75 : static inline void add_offset_pair(zval *result, char *str, int len, int offset, char *name)
     605             : {
     606             :         zval match_pair, tmp;
     607             : 
     608          75 :         array_init_size(&match_pair, 2);
     609             : 
     610             :         /* Add (match, offset) to the return value */
     611         150 :         ZVAL_STRINGL(&tmp, str, len);
     612          75 :         zend_hash_next_index_insert_new(Z_ARRVAL(match_pair), &tmp);
     613          75 :         ZVAL_LONG(&tmp, offset);
     614          75 :         zend_hash_next_index_insert_new(Z_ARRVAL(match_pair), &tmp);
     615             : 
     616          75 :         if (name) {
     617             :                 Z_ADDREF(match_pair);
     618           2 :                 zend_hash_str_update(Z_ARRVAL_P(result), name, strlen(name), &match_pair);
     619             :         }
     620          75 :         zend_hash_next_index_insert(Z_ARRVAL_P(result), &match_pair);
     621          75 : }
     622             : /* }}} */
     623             : 
     624     1806279 : static void php_do_pcre_match(INTERNAL_FUNCTION_PARAMETERS, int global) /* {{{ */
     625             : {
     626             :         /* parameters */
     627             :         zend_string              *regex;                        /* Regular expression */
     628             :         zend_string              *subject;                      /* String to match against */
     629             :         pcre_cache_entry *pce;                          /* Compiled regular expression */
     630     1806279 :         zval                     *subpats = NULL;       /* Array for subpatterns */
     631     1806279 :         zend_long                 flags = 0;            /* Match control flags */
     632     1806279 :         zend_long                 start_offset = 0;     /* Where the new search starts */
     633             : 
     634     1806279 :         ZEND_PARSE_PARAMETERS_START(2, 5)
     635     5418813 :                 Z_PARAM_STR(regex)
     636     5418801 :                 Z_PARAM_STR(subject)
     637     1806263 :                 Z_PARAM_OPTIONAL
     638     4248855 :                 Z_PARAM_ZVAL_EX(subpats, 0, 1)
     639     1230513 :                 Z_PARAM_LONG(flags)
     640          61 :                 Z_PARAM_LONG(start_offset)
     641     1806279 :         ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
     642             : 
     643     1806263 :         if (ZEND_SIZE_T_INT_OVFL(ZSTR_LEN(subject))) {
     644           0 :                         php_error_docref(NULL, E_WARNING, "Subject is too long");
     645           0 :                         RETURN_FALSE;
     646             :         }
     647             : 
     648             :         /* Compile regex or get it from cache. */
     649     1806263 :         if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
     650          27 :                 RETURN_FALSE;
     651             :         }
     652             : 
     653     1806236 :         pce->refcount++;
     654     1806236 :         php_pcre_match_impl(pce, ZSTR_VAL(subject), (int)ZSTR_LEN(subject), return_value, subpats,
     655             :                 global, ZEND_NUM_ARGS() >= 4, flags, start_offset);
     656     1806236 :         pce->refcount--;
     657             : }
     658             : /* }}} */
     659             : 
     660             : /* {{{ php_pcre_match_impl() */
     661     1807775 : PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value,
     662             :         zval *subpats, int global, int use_flags, zend_long flags, zend_long start_offset)
     663             : {
     664             :         zval                     result_set,            /* Holds a set of subpatterns after
     665             :                                                                                    a global match */
     666     1807775 :                                     *match_sets = NULL; /* An array of sets of matches for each
     667             :                                                                                    subpattern after a global match */
     668     1807775 :         pcre_extra              *extra = pce->extra;/* Holds results of studying */
     669             :         pcre_extra               extra_data;            /* Used locally for exec options */
     670     1807775 :         int                              exoptions = 0;         /* Execution options */
     671     1807775 :         int                              count = 0;                     /* Count of matched subpatterns */
     672             :         int                             *offsets;                       /* Array of subpattern offsets */
     673             :         int                              num_subpats;           /* Number of captured subpatterns */
     674             :         int                              size_offsets;          /* Size of the offsets array */
     675             :         int                              matched;                       /* Has anything matched */
     676     1807775 :         int                              g_notempty = 0;        /* If the match should not be empty */
     677             :         const char         **stringlist;                /* Holds list of subpatterns */
     678             :         char               **subpat_names;              /* Array for named subpatterns */
     679             :         int                              i;
     680             :         int                              subpats_order;         /* Order of subpattern matches */
     681             :         int                              offset_capture;    /* Capture match offsets: yes/no */
     682     1807775 :         unsigned char   *mark = NULL;       /* Target for MARK name */
     683             :         zval            marks;                  /* Array of marks for PREG_PATTERN_ORDER */
     684             :         ALLOCA_FLAG(use_heap);
     685             : 
     686     1807775 :         ZVAL_UNDEF(&marks);
     687             : 
     688             :         /* Overwrite the passed-in value for subpatterns with an empty array. */
     689     1807775 :         if (subpats != NULL) {
     690             :                 zval_dtor(subpats);
     691     1231965 :                 array_init(subpats);
     692             :         }
     693             : 
     694     1807775 :         subpats_order = global ? PREG_PATTERN_ORDER : 0;
     695             : 
     696     1807775 :         if (use_flags) {
     697        1517 :                 offset_capture = flags & PREG_OFFSET_CAPTURE;
     698             : 
     699             :                 /*
     700             :                  * subpats_order is pre-set to pattern mode so we change it only if
     701             :                  * necessary.
     702             :                  */
     703        1517 :                 if (flags & 0xff) {
     704          25 :                         subpats_order = flags & 0xff;
     705             :                 }
     706        1517 :                 if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) ||
     707             :                         (!global && subpats_order != 0)) {
     708           1 :                         php_error_docref(NULL, E_WARNING, "Invalid flags specified");
     709           1 :                         return;
     710             :                 }
     711             :         } else {
     712     1806258 :                 offset_capture = 0;
     713             :         }
     714             : 
     715             :         /* Negative offset counts from the end of the string. */
     716     1807774 :         if (start_offset < 0) {
     717           5 :                 start_offset = subject_len + start_offset;
     718           5 :                 if (start_offset < 0) {
     719           1 :                         start_offset = 0;
     720             :                 }
     721             :         }
     722             : 
     723     1807774 :         if (extra == NULL) {
     724           6 :                 extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
     725           6 :                 extra = &extra_data;
     726             :         }
     727     1807774 :         extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
     728     1807774 :         extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
     729             : #ifdef PCRE_EXTRA_MARK
     730     1807774 :         extra->mark = &mark;
     731     1807774 :         extra->flags |= PCRE_EXTRA_MARK;
     732             : #endif
     733             : 
     734             :         /* Calculate the size of the offsets array, and allocate memory for it. */
     735     1807774 :         num_subpats = pce->capture_count + 1;
     736     1807774 :         size_offsets = num_subpats * 3;
     737             : 
     738             :         /*
     739             :          * Build a mapping from subpattern numbers to their names. We will
     740             :          * allocate the table only if there are any named subpatterns.
     741             :          */
     742     1807774 :         subpat_names = NULL;
     743     1807774 :         if (pce->name_count > 0) {
     744          12 :                 subpat_names = make_subpats_table(num_subpats, pce);
     745          12 :                 if (!subpat_names) {
     746           0 :                         RETURN_FALSE;
     747             :                 }
     748             :         }
     749             : 
     750     1807774 :         if (size_offsets <= 32) {
     751     1807762 :                 offsets = (int *)do_alloca(size_offsets * sizeof(int), use_heap);
     752             :         } else {
     753          12 :                 offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
     754             :         }
     755     1807774 :         memset(offsets, 0, size_offsets*sizeof(int));
     756             :         /* Allocate match sets array and initialize the values. */
     757     1807774 :         if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
     758         119 :                 match_sets = (zval *)safe_emalloc(num_subpats, sizeof(zval), 0);
     759         380 :                 for (i=0; i<num_subpats; i++) {
     760         261 :                         array_init(&match_sets[i]);
     761             :                 }
     762             :         }
     763             : 
     764     1807774 :         matched = 0;
     765     1807774 :         PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
     766             : 
     767             :         do {
     768             :                 /* Execute the regular expression. */
     769     1807987 :                 count = pcre_exec(pce->re, extra, subject, (int)subject_len, (int)start_offset,
     770             :                                                   exoptions|g_notempty, offsets, size_offsets);
     771             : 
     772             :                 /* the string was already proved to be valid UTF-8 */
     773     1807987 :                 exoptions |= PCRE_NO_UTF8_CHECK;
     774             : 
     775             :                 /* Check for too many substrings condition. */
     776     1807987 :                 if (count == 0) {
     777           0 :                         php_error_docref(NULL, E_NOTICE, "Matched, but too many substrings");
     778           0 :                         count = size_offsets/3;
     779             :                 }
     780             : 
     781             :                 /* If something has matched */
     782     1807987 :                 if (count > 0) {
     783       95625 :                         matched++;
     784             : 
     785             :                         /* If subpatterns array has been passed, fill it in with values. */
     786       95625 :                         if (subpats != NULL) {
     787             :                                 /* Try to get the list of substrings and display a warning if failed. */
     788       48108 :                                 if ((offsets[1] - offsets[0] < 0) || pcre_get_substring_list(subject, offsets, count, &stringlist) < 0) {
     789           1 :                                         if (subpat_names) {
     790           0 :                                                 efree(subpat_names);
     791             :                                         }
     792           1 :                                         if (size_offsets <= 32) {
     793           1 :                                                 free_alloca(offsets, use_heap);
     794             :                                         } else {
     795           0 :                                                 efree(offsets);
     796             :                                         }
     797           1 :                                         if (match_sets) efree(match_sets);
     798           1 :                                         php_error_docref(NULL, E_WARNING, "Get subpatterns list failed");
     799           1 :                                         RETURN_FALSE;
     800             :                                 }
     801             : 
     802       48107 :                                 if (global) {   /* global pattern matching */
     803         346 :                                         if (subpats && subpats_order == PREG_PATTERN_ORDER) {
     804             :                                                 /* For each subpattern, insert it into the appropriate array. */
     805         148 :                                                 if (offset_capture) {
     806          22 :                                                         for (i = 0; i < count; i++) {
     807          24 :                                                                 add_offset_pair(&match_sets[i], (char *)stringlist[i],
     808          24 :                                                                                                 offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL);
     809             :                                                         }
     810             :                                                 } else {
     811         357 :                                                         for (i = 0; i < count; i++) {
     812         219 :                                                                 add_next_index_stringl(&match_sets[i], (char *)stringlist[i],
     813         219 :                                                                                                            offsets[(i<<1)+1] - offsets[i<<1]);
     814             :                                                         }
     815             :                                                 }
     816             :                                                 /* Add MARK, if available */
     817         148 :                                                 if (mark) {
     818           2 :                                                         if (Z_TYPE(marks) == IS_UNDEF) {
     819           1 :                                                                 array_init(&marks);
     820             :                                                         }
     821           2 :                                                         add_index_string(&marks, matched - 1, (char *) mark);
     822             :                                                 }
     823             :                                                 /*
     824             :                                                  * If the number of captured subpatterns on this run is
     825             :                                                  * less than the total possible number, pad the result
     826             :                                                  * arrays with empty strings.
     827             :                                                  */
     828         148 :                                                 if (count < num_subpats) {
     829          11 :                                                         for (; i < num_subpats; i++) {
     830           7 :                                                                 add_next_index_string(&match_sets[i], "");
     831             :                                                         }
     832             :                                                 }
     833             :                                         } else {
     834             :                                                 /* Allocate the result set array */
     835          50 :                                                 array_init_size(&result_set, count + (mark ? 1 : 0));
     836             : 
     837             :                                                 /* Add all the subpatterns to it */
     838          50 :                                                 if (subpat_names) {
     839           8 :                                                         if (offset_capture) {
     840           0 :                                                                 for (i = 0; i < count; i++) {
     841           0 :                                                                         add_offset_pair(&result_set, (char *)stringlist[i],
     842           0 :                                                                                                         offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]);
     843             :                                                                 }
     844             :                                                         } else {
     845          40 :                                                                 for (i = 0; i < count; i++) {
     846          32 :                                                                         if (subpat_names[i]) {
     847          22 :                                                                                 add_assoc_stringl(&result_set, subpat_names[i], (char *)stringlist[i],
     848             :                                                                                                                            offsets[(i<<1)+1] - offsets[i<<1]);
     849             :                                                                         }
     850          32 :                                                                         add_next_index_stringl(&result_set, (char *)stringlist[i],
     851          32 :                                                                                                                    offsets[(i<<1)+1] - offsets[i<<1]);
     852             :                                                                 }
     853             :                                                         }
     854             :                                                 } else {
     855          42 :                                                         if (offset_capture) {
     856          10 :                                                                 for (i = 0; i < count; i++) {
     857          14 :                                                                         add_offset_pair(&result_set, (char *)stringlist[i],
     858          14 :                                                                                                         offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL);
     859             :                                                                 }
     860             :                                                         } else {
     861         343 :                                                                 for (i = 0; i < count; i++) {
     862         304 :                                                                         add_next_index_stringl(&result_set, (char *)stringlist[i],
     863         304 :                                                                                                                    offsets[(i<<1)+1] - offsets[i<<1]);
     864             :                                                                 }
     865             :                                                         }
     866             :                                                 }
     867             :                                                 /* Add MARK, if available */
     868          50 :                                                 if (mark) {
     869           2 :                                                         add_assoc_string_ex(&result_set, "MARK", sizeof("MARK") - 1, (char *)mark);
     870             :                                                 }
     871             :                                                 /* And add it to the output array */
     872          50 :                                                 zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set);
     873             :                                         }
     874             :                                 } else {                        /* single pattern matching */
     875             :                                         /* For each subpattern, insert it into the subpatterns array. */
     876       47909 :                                         if (subpat_names) {
     877           6 :                                                 if (offset_capture) {
     878           5 :                                                         for (i = 0; i < count; i++) {
     879          12 :                                                                 add_offset_pair(subpats, (char *)stringlist[i],
     880           4 :                                                                                                 offsets[(i<<1)+1] - offsets[i<<1],
     881           8 :                                                                                                 offsets[i<<1], subpat_names[i]);
     882             :                                                         }
     883             :                                                 } else {
     884         317 :                                                         for (i = 0; i < count; i++) {
     885         312 :                                                                 if (subpat_names[i]) {
     886         304 :                                                                         add_assoc_stringl(subpats, subpat_names[i], (char *)stringlist[i],
     887             :                                                                                                           offsets[(i<<1)+1] - offsets[i<<1]);
     888             :                                                                 }
     889         312 :                                                                 add_next_index_stringl(subpats, (char *)stringlist[i],
     890         312 :                                                                                                            offsets[(i<<1)+1] - offsets[i<<1]);
     891             :                                                         }
     892             :                                                 }
     893             :                                         } else {
     894       47903 :                                                 if (offset_capture) {
     895          19 :                                                         for (i = 0; i < count; i++) {
     896          22 :                                                                 add_offset_pair(subpats, (char *)stringlist[i],
     897          11 :                                                                                                 offsets[(i<<1)+1] - offsets[i<<1],
     898          11 :                                                                                                 offsets[i<<1], NULL);
     899             :                                                         }
     900             :                                                 } else {
     901      146204 :                                                         for (i = 0; i < count; i++) {
     902       98309 :                                                                 add_next_index_stringl(subpats, (char *)stringlist[i],
     903       98309 :                                                                                                            offsets[(i<<1)+1] - offsets[i<<1]);
     904             :                                                         }
     905             :                                                 }
     906             :                                         }
     907             :                                         /* Add MARK, if available */
     908       47909 :                                         if (mark) {
     909           1 :                                                 add_assoc_string_ex(subpats, "MARK", sizeof("MARK") - 1, (char *)mark);
     910             :                                         }
     911             :                                 }
     912             : 
     913       48107 :                                 pcre_free((void *) stringlist);
     914             :                         }
     915     1712362 :                 } else if (count == PCRE_ERROR_NOMATCH) {
     916             :                         /* If we previously set PCRE_NOTEMPTY_ATSTART after a null match,
     917             :                            this is not necessarily the end. We need to advance
     918             :                            the start offset, and continue. Fudge the offset values
     919             :                            to achieve this, unless we're already at the end of the string. */
     920     1712355 :                         if (g_notempty != 0 && start_offset < subject_len) {
     921          12 :                                 int unit_len = calculate_unit_length(pce, subject + start_offset);
     922             :                                 
     923           6 :                                 offsets[0] = (int)start_offset;
     924           6 :                                 offsets[1] = (int)(start_offset + unit_len);
     925             :                         } else
     926             :                                 break;
     927             :                 } else {
     928           7 :                         pcre_handle_exec_error(count);
     929           7 :                         break;
     930             :                 }
     931             : 
     932             :                 /* If we have matched an empty string, mimic what Perl's /g options does.
     933             :                    This turns out to be rather cunning. First we set PCRE_NOTEMPTY_ATSTART and try
     934             :                    the match again at the same point. If this fails (picked up above) we
     935             :                    advance to the next character. */
     936       95630 :                 g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY_ATSTART | PCRE_ANCHORED : 0;
     937             : 
     938             :                 /* Advance to the position right after the last full match */
     939       95630 :                 start_offset = offsets[1];
     940       95630 :         } while (global);
     941             : 
     942             :         /* Add the match sets to the output array and clean up */
     943     1807773 :         if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
     944         119 :                 if (subpat_names) {
     945          10 :                         for (i = 0; i < num_subpats; i++) {
     946           8 :                                 if (subpat_names[i]) {
     947           5 :                                         zend_hash_str_update(Z_ARRVAL_P(subpats), subpat_names[i],
     948             :                                                                          strlen(subpat_names[i]), &match_sets[i]);
     949           5 :                                         Z_ADDREF(match_sets[i]);
     950             :                                 }
     951           8 :                                 zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i]);
     952             :                         }
     953             :                 } else {
     954         370 :                         for (i = 0; i < num_subpats; i++) {
     955         253 :                                 zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i]);
     956             :                         }
     957             :                 }
     958         119 :                 efree(match_sets);
     959             : 
     960         119 :                 if (Z_TYPE(marks) != IS_UNDEF) {
     961           1 :                         add_assoc_zval(subpats, "MARK", &marks);
     962             :                 }
     963             :         }
     964             : 
     965     1807773 :         if (size_offsets <= 32) {
     966     1807761 :                 free_alloca(offsets, use_heap);
     967             :         } else {
     968          12 :                 efree(offsets);
     969             :         }
     970     1807773 :         if (subpat_names) {
     971          12 :                 efree(subpat_names);
     972             :         }
     973             : 
     974             :         /* Did we encounter an error? */
     975     1807773 :         if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) {
     976     1807766 :                 RETVAL_LONG(matched);
     977             :         } else {
     978           7 :                 RETVAL_FALSE;
     979             :         }
     980             : }
     981             : /* }}} */
     982             : 
     983             : /* {{{ proto int preg_match(string pattern, string subject [, array &subpatterns [, int flags [, int offset]]])
     984             :    Perform a Perl-style regular expression match */
     985     1806166 : static PHP_FUNCTION(preg_match)
     986             : {
     987     1806166 :         php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
     988     1806166 : }
     989             : /* }}} */
     990             : 
     991             : /* {{{ proto int preg_match_all(string pattern, string subject [, array &subpatterns [, int flags [, int offset]]])
     992             :    Perform a Perl-style global regular expression match */
     993         113 : static PHP_FUNCTION(preg_match_all)
     994             : {
     995         113 :         php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
     996         113 : }
     997             : /* }}} */
     998             : 
     999             : /* {{{ preg_get_backref
    1000             :  */
    1001         126 : static int preg_get_backref(char **str, int *backref)
    1002             : {
    1003         126 :         register char in_brace = 0;
    1004         126 :         register char *walk = *str;
    1005             : 
    1006         126 :         if (walk[1] == 0)
    1007           8 :                 return 0;
    1008             : 
    1009         118 :         if (*walk == '$' && walk[1] == '{') {
    1010          14 :                 in_brace = 1;
    1011          14 :                 walk++;
    1012             :         }
    1013         118 :         walk++;
    1014             : 
    1015         236 :         if (*walk >= '0' && *walk <= '9') {
    1016         118 :                 *backref = *walk - '0';
    1017         118 :                 walk++;
    1018             :         } else
    1019           0 :                 return 0;
    1020             : 
    1021         118 :         if (*walk && *walk >= '0' && *walk <= '9') {
    1022           2 :                 *backref = *backref * 10 + *walk - '0';
    1023           2 :                 walk++;
    1024             :         }
    1025             : 
    1026         118 :         if (in_brace) {
    1027          14 :                 if (*walk != '}')
    1028           6 :                         return 0;
    1029             :                 else
    1030           8 :                         walk++;
    1031             :         }
    1032             : 
    1033         112 :         *str = walk;
    1034         112 :         return 1;
    1035             : }
    1036             : /* }}} */
    1037             : 
    1038             : /* {{{ preg_do_repl_func
    1039             :  */
    1040          69 : static zend_string *preg_do_repl_func(zval *function, char *subject, int *offsets, char **subpat_names, int count, unsigned char *mark)
    1041             : {
    1042             :         zend_string *result_str;
    1043             :         zval             retval;                        /* Function return value */
    1044             :         zval         args[1];                   /* Argument to pass to function */
    1045             :         int                      i;
    1046             : 
    1047          69 :         array_init_size(&args[0], count + (mark ? 1 : 0));
    1048          69 :         if (subpat_names) {
    1049           3 :                 for (i = 0; i < count; i++) {
    1050           2 :                         if (subpat_names[i]) {
    1051           1 :                                 add_assoc_stringl(&args[0], subpat_names[i], &subject[offsets[i<<1]] , offsets[(i<<1)+1] - offsets[i<<1]);
    1052             :                         }
    1053           2 :                         add_next_index_stringl(&args[0], &subject[offsets[i<<1]], offsets[(i<<1)+1] - offsets[i<<1]);
    1054             :                 }
    1055             :         } else {
    1056         167 :                 for (i = 0; i < count; i++) {
    1057          99 :                         add_next_index_stringl(&args[0], &subject[offsets[i<<1]], offsets[(i<<1)+1] - offsets[i<<1]);
    1058             :                 }
    1059             :         }
    1060          69 :         if (mark) {
    1061           2 :                 add_assoc_string(&args[0], "MARK", (char *) mark);
    1062             :         }
    1063             : 
    1064         205 :         if (call_user_function_ex(EG(function_table), NULL, function, &retval, 1, args, 0, NULL) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
    1065          67 :                 result_str = zval_get_string(&retval);
    1066          67 :                 zval_ptr_dtor(&retval);
    1067             :         } else {
    1068           2 :                 if (!EG(exception)) {
    1069           0 :                         php_error_docref(NULL, E_WARNING, "Unable to call custom replacement function");
    1070             :                 }
    1071             : 
    1072           4 :                 result_str = zend_string_init(&subject[offsets[0]], offsets[1] - offsets[0], 0);
    1073             :         }
    1074             : 
    1075          69 :         zval_ptr_dtor(&args[0]);
    1076             : 
    1077          69 :         return result_str;
    1078             : }
    1079             : /* }}} */
    1080             : 
    1081             : /* {{{ php_pcre_replace
    1082             :  */
    1083       37449 : PHPAPI zend_string *php_pcre_replace(zend_string *regex,
    1084             :                                                           zend_string *subject_str,
    1085             :                                                           char *subject, int subject_len,
    1086             :                                                           zval *replace_val, int is_callable_replace,
    1087             :                                                           int limit, int *replace_count)
    1088             : {
    1089             :         pcre_cache_entry        *pce;                       /* Compiled regular expression */
    1090             :         zend_string                     *result;                        /* Function result */
    1091             : 
    1092             :         /* Compile regex or get it from cache. */
    1093       37449 :         if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
    1094          12 :                 return NULL;
    1095             :         }
    1096       37437 :         pce->refcount++;
    1097       37437 :         result = php_pcre_replace_impl(pce, subject_str, subject, subject_len, replace_val,
    1098             :                 is_callable_replace, limit, replace_count);
    1099       37437 :         pce->refcount--;
    1100             : 
    1101       37437 :         return result;
    1102             : }
    1103             : /* }}} */
    1104             : 
    1105             : /* {{{ php_pcre_replace_impl() */
    1106       37452 : PHPAPI zend_string *php_pcre_replace_impl(pcre_cache_entry *pce, zend_string *subject_str, char *subject, int subject_len, zval *replace_val, int is_callable_replace, int limit, int *replace_count)
    1107             : {
    1108       37452 :         pcre_extra              *extra = pce->extra;/* Holds results of studying */
    1109             :         pcre_extra               extra_data;            /* Used locally for exec options */
    1110       37452 :         int                              exoptions = 0;         /* Execution options */
    1111       37452 :         int                              count = 0;                     /* Count of matched subpatterns */
    1112             :         int                             *offsets;                       /* Array of subpattern offsets */
    1113             :         char                    **subpat_names;         /* Array for named subpatterns */
    1114             :         int                              num_subpats;           /* Number of captured subpatterns */
    1115             :         int                              size_offsets;          /* Size of the offsets array */
    1116             :         size_t                   new_len;                       /* Length of needed storage */
    1117             :         size_t                   alloc_len;                     /* Actual allocated length */
    1118             :         int                              match_len;                     /* Length of the current match */
    1119             :         int                              backref;                       /* Backreference number */
    1120             :         int                              start_offset;          /* Where the new search starts */
    1121       37452 :         int                              g_notempty=0;          /* If the match should not be empty */
    1122       37452 :         int                              replace_len=0;         /* Length of replacement string */
    1123       37452 :         char                    *replace=NULL,          /* Replacement string */
    1124             :                                         *walkbuf,                       /* Location of current replacement in the result */
    1125             :                                         *walk,                          /* Used to walk the replacement string */
    1126             :                                         *match,                         /* The current match */
    1127             :                                         *piece,                         /* The current piece of subject */
    1128       37452 :                                         *replace_end=NULL,      /* End of replacement string */
    1129             :                                          walk_last;                     /* Last walked character */
    1130             :         int                              result_len;            /* Length of result */
    1131       37452 :         unsigned char   *mark = NULL;       /* Target for MARK name */
    1132             :         zend_string             *result;                        /* Result of replacement */
    1133       37452 :         zend_string     *eval_result=NULL;  /* Result of custom function */
    1134             : 
    1135             :         ALLOCA_FLAG(use_heap);
    1136             : 
    1137       37452 :         if (extra == NULL) {
    1138           2 :                 extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
    1139           2 :                 extra = &extra_data;
    1140             :         }
    1141             : 
    1142       37452 :         extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
    1143       37452 :         extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
    1144             : 
    1145       37452 :         if (UNEXPECTED(pce->preg_options & PREG_REPLACE_EVAL)) {
    1146           1 :                 php_error_docref(NULL, E_WARNING, "The /e modifier is no longer supported, use preg_replace_callback instead");
    1147           1 :                 return NULL;
    1148             :         }
    1149             : 
    1150       37451 :         if (!is_callable_replace) {
    1151       37401 :                 replace = Z_STRVAL_P(replace_val);
    1152       37401 :                 replace_len = (int)Z_STRLEN_P(replace_val);
    1153       37401 :                 replace_end = replace + replace_len;
    1154             :         }
    1155             : 
    1156             :         /* Calculate the size of the offsets array, and allocate memory for it. */
    1157       37451 :         num_subpats = pce->capture_count + 1;
    1158       37451 :         size_offsets = num_subpats * 3;
    1159       37451 :         if (size_offsets <= 32) {
    1160       37448 :                 offsets = (int *)do_alloca(size_offsets * sizeof(int), use_heap);
    1161             :         } else {
    1162           3 :                 offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
    1163             :         }
    1164             : 
    1165             :         /*
    1166             :          * Build a mapping from subpattern numbers to their names. We will
    1167             :          * allocate the table only if there are any named subpatterns.
    1168             :          */
    1169       37451 :         subpat_names = NULL;
    1170       37451 :         if (UNEXPECTED(pce->name_count > 0)) {
    1171           1 :                 subpat_names = make_subpats_table(num_subpats, pce);
    1172           1 :                 if (!subpat_names) {
    1173           0 :                         if (size_offsets <= 32) {
    1174           0 :                                 free_alloca(offsets, use_heap);
    1175             :                         } else {
    1176           0 :                                 efree(offsets);
    1177             :                         }
    1178           0 :                         return NULL;
    1179             :                 }
    1180             :         }
    1181             : 
    1182       37451 :         alloc_len = 0;
    1183       37451 :         result = NULL;
    1184             : 
    1185             :         /* Initialize */
    1186       37451 :         match = NULL;
    1187       37451 :         start_offset = 0;
    1188       37451 :         result_len = 0;
    1189       37451 :         PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
    1190             : 
    1191             :         while (1) {
    1192             : #ifdef PCRE_EXTRA_MARK
    1193       52495 :                 extra->mark = &mark;
    1194       52495 :                 extra->flags |= PCRE_EXTRA_MARK;
    1195             : #endif
    1196             :                 /* Execute the regular expression. */
    1197       52495 :                 count = pcre_exec(pce->re, extra, subject, subject_len, start_offset,
    1198             :                                                   exoptions|g_notempty, offsets, size_offsets);
    1199             : 
    1200             :                 /* the string was already proved to be valid UTF-8 */
    1201       52495 :                 exoptions |= PCRE_NO_UTF8_CHECK;
    1202             : 
    1203             :                 /* Check for too many substrings condition. */
    1204       52495 :                 if (UNEXPECTED(count == 0)) {
    1205           0 :                         php_error_docref(NULL,E_NOTICE, "Matched, but too many substrings");
    1206           0 :                         count = size_offsets / 3;
    1207             :                 }
    1208             : 
    1209       52495 :                 piece = subject + start_offset;
    1210             : 
    1211             :                 /* if (EXPECTED(count > 0 && (limit == -1 || limit > 0))) */
    1212       67527 :                 if (EXPECTED(count > 0 && (offsets[1] - offsets[0] >= 0) && limit)) {
    1213       15032 :                         if (UNEXPECTED(replace_count)) {
    1214       15032 :                                 ++*replace_count;
    1215             :                         }
    1216             : 
    1217             :                         /* Set the match location in subject */
    1218       15032 :                         match = subject + offsets[0];
    1219             : 
    1220       15032 :                         new_len = result_len + offsets[0] - start_offset; /* part before the match */
    1221             :                         
    1222             :                         /* if (!is_callable_replace) */
    1223       15032 :                         if (EXPECTED(replace)) {
    1224             :                                 /* do regular substitution */
    1225       14963 :                                 walk = replace;
    1226       14963 :                                 walk_last = 0;
    1227             : 
    1228       61373 :                                 while (walk < replace_end) {
    1229       31447 :                                         if ('\\' == *walk || '$' == *walk) {
    1230          63 :                                                 if (walk_last == '\\') {
    1231           0 :                                                         walk++;
    1232           0 :                                                         walk_last = 0;
    1233           0 :                                                         continue;
    1234             :                                                 }
    1235          63 :                                                 if (preg_get_backref(&walk, &backref)) {
    1236          56 :                                                         if (backref < count)
    1237          55 :                                                                 new_len += offsets[(backref<<1)+1] - offsets[backref<<1];
    1238          56 :                                                         continue;
    1239             :                                                 }
    1240             :                                         }
    1241       31391 :                                         new_len++;
    1242       31391 :                                         walk++;
    1243       31391 :                                         walk_last = walk[-1];
    1244             :                                 }
    1245             : 
    1246       14963 :                                 if (new_len >= alloc_len) {
    1247        9345 :                                         alloc_len = alloc_len + 2 * new_len;
    1248        9345 :                                         if (result == NULL) {
    1249        8861 :                                                 result = zend_string_alloc(alloc_len, 0);
    1250             :                                         } else {
    1251         484 :                                                 result = zend_string_extend(result, alloc_len, 0);
    1252             :                                         }
    1253             :                                 }
    1254             : 
    1255             :                                 /* copy the part of the string before the match */
    1256       14963 :                                 memcpy(&ZSTR_VAL(result)[result_len], piece, match-piece);
    1257       14963 :                                 result_len += (int)(match-piece);
    1258             : 
    1259             :                                 /* copy replacement and backrefs */
    1260       14963 :                                 walkbuf = ZSTR_VAL(result) + result_len;
    1261             : 
    1262       14963 :                                 walk = replace;
    1263       14963 :                                 walk_last = 0;
    1264       61373 :                                 while (walk < replace_end) {
    1265       31447 :                                         if ('\\' == *walk || '$' == *walk) {
    1266          63 :                                                 if (walk_last == '\\') {
    1267           0 :                                                         *(walkbuf-1) = *walk++;
    1268           0 :                                                         walk_last = 0;
    1269           0 :                                                         continue;
    1270             :                                                 }
    1271          63 :                                                 if (preg_get_backref(&walk, &backref)) {
    1272          56 :                                                         if (backref < count) {
    1273          55 :                                                                 match_len = offsets[(backref<<1)+1] - offsets[backref<<1];
    1274          55 :                                                                 memcpy(walkbuf, subject + offsets[backref<<1], match_len);
    1275          55 :                                                                 walkbuf += match_len;
    1276             :                                                         }
    1277          56 :                                                         continue;
    1278             :                                                 }
    1279             :                                         }
    1280       31391 :                                         *walkbuf++ = *walk++;
    1281       31391 :                                         walk_last = walk[-1];
    1282             :                                 }
    1283       14963 :                                 *walkbuf = '\0';
    1284             :                                 /* increment the result length by how much we've added to the string */
    1285       14963 :                                 result_len += (int)(walkbuf - (ZSTR_VAL(result) + result_len));
    1286             :                         } else {
    1287             :                                 /* Use custom function to get replacement string and its length. */
    1288          69 :                                 eval_result = preg_do_repl_func(replace_val, subject, offsets, subpat_names, count, mark);
    1289             :                                 ZEND_ASSERT(eval_result);
    1290          69 :                                 new_len += (int)ZSTR_LEN(eval_result);
    1291          69 :                                 if (new_len >= alloc_len) {
    1292          61 :                                         alloc_len = alloc_len + 2 * new_len;
    1293          61 :                                         if (result == NULL) {
    1294          38 :                                                 result = zend_string_alloc(alloc_len, 0);
    1295             :                                         } else {
    1296          23 :                                                 result = zend_string_extend(result, alloc_len, 0);
    1297             :                                         }
    1298             :                                 }
    1299             :                                 /* copy the part of the string before the match */
    1300          69 :                                 memcpy(ZSTR_VAL(result) + result_len, piece, match-piece);
    1301          69 :                                 result_len += (int)(match-piece);
    1302             : 
    1303             :                                 /* copy replacement and backrefs */
    1304          69 :                                 walkbuf = ZSTR_VAL(result) + result_len;
    1305             : 
    1306             :                                 /* If using custom function, copy result to the buffer and clean up. */
    1307          69 :                                 memcpy(walkbuf, ZSTR_VAL(eval_result), ZSTR_LEN(eval_result));
    1308          69 :                                 result_len += (int)ZSTR_LEN(eval_result);
    1309             :                                 zend_string_release(eval_result);
    1310             :                         }
    1311             : 
    1312       15032 :                         if (EXPECTED(limit)) {
    1313       15032 :                                 limit--;
    1314             :                         }
    1315       37475 :                 } else if (count == PCRE_ERROR_NOMATCH || UNEXPECTED(limit == 0)) {
    1316             :                         /* If we previously set PCRE_NOTEMPTY_ATSTART after a null match,
    1317             :                            this is not necessarily the end. We need to advance
    1318             :                            the start offset, and continue. Fudge the offset values
    1319             :                            to achieve this, unless we're already at the end of the string. */
    1320       37467 :                         if (g_notempty != 0 && start_offset < subject_len) {
    1321          12 :                                 int unit_len = calculate_unit_length(pce, piece);
    1322             : 
    1323          12 :                                 offsets[0] = start_offset;
    1324          12 :                                 offsets[1] = start_offset + unit_len;
    1325          12 :                                 memcpy(ZSTR_VAL(result) + result_len, piece, unit_len);
    1326          12 :                                 result_len += unit_len;
    1327             :                         } else {
    1328       37443 :                                 if (!result && subject_str) {
    1329       28544 :                                         result = zend_string_copy(subject_str);
    1330       28544 :                                         break;
    1331             :                                 }
    1332        8899 :                                 new_len = result_len + subject_len - start_offset;
    1333        8899 :                                 if (new_len >= alloc_len) {
    1334         296 :                                         alloc_len = new_len; /* now we know exactly how long it is */
    1335         296 :                                         if (NULL != result) {
    1336         296 :                                                 result = zend_string_realloc(result, alloc_len, 0);
    1337             :                                         } else {
    1338           0 :                                                 result = zend_string_alloc(alloc_len, 0);
    1339             :                                         }
    1340             :                                 }
    1341             :                                 /* stick that last bit of string on our output */
    1342        8899 :                                 memcpy(ZSTR_VAL(result) + result_len, piece, subject_len - start_offset);
    1343        8899 :                                 result_len += subject_len - start_offset;
    1344        8899 :                                 ZSTR_VAL(result)[result_len] = '\0';
    1345        8899 :                                 ZSTR_LEN(result) = result_len;
    1346        8899 :                                 break;
    1347             :                         }
    1348             :                 } else {
    1349           8 :                         pcre_handle_exec_error(count);
    1350           8 :                         if (result) {
    1351             :                                 zend_string_free(result);
    1352           0 :                                 result = NULL;
    1353             :                         }
    1354           8 :                         break;
    1355             :                 }
    1356             : 
    1357             :                 /* If we have matched an empty string, mimic what Perl's /g options does.
    1358             :                    This turns out to be rather cunning. First we set PCRE_NOTEMPTY_ATSTART and try
    1359             :                    the match again at the same point. If this fails (picked up above) we
    1360             :                    advance to the next character. */
    1361       15044 :                 g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY_ATSTART | PCRE_ANCHORED : 0;
    1362             : 
    1363             :                 /* Advance to the next piece. */
    1364       15044 :                 start_offset = offsets[1];
    1365       15044 :         }
    1366             : 
    1367       37451 :         if (size_offsets <= 32) {
    1368       37448 :                 free_alloca(offsets, use_heap);
    1369             :         } else {
    1370           3 :                 efree(offsets);
    1371             :         }
    1372       37451 :         if (UNEXPECTED(subpat_names)) {
    1373           1 :                 efree(subpat_names);
    1374             :         }
    1375             : 
    1376       37451 :         return result;
    1377             : }
    1378             : /* }}} */
    1379             : 
    1380             : /* {{{ php_replace_in_subject
    1381             :  */
    1382       37407 : static zend_string *php_replace_in_subject(zval *regex, zval *replace, zval *subject, int limit, int is_callable_replace, int *replace_count)
    1383             : {
    1384             :         zval            *regex_entry,
    1385             :                                 *replace_value,
    1386             :                                  empty_replace;
    1387             :         zend_string *result;
    1388             :         uint32_t replace_idx;
    1389       37407 :         zend_string     *subject_str = zval_get_string(subject);
    1390             : 
    1391             :         /* FIXME: This might need to be changed to ZSTR_EMPTY_ALLOC(). Check if this zval could be dtor()'ed somehow */
    1392       37407 :         ZVAL_EMPTY_STRING(&empty_replace);
    1393             : 
    1394       37407 :         if (ZEND_SIZE_T_INT_OVFL(ZSTR_LEN(subject_str))) {
    1395           0 :                         php_error_docref(NULL, E_WARNING, "Subject is too long");
    1396           0 :                         return NULL;
    1397             :         }
    1398             : 
    1399             :         /* If regex is an array */
    1400       37407 :         if (Z_TYPE_P(regex) == IS_ARRAY) {
    1401          22 :                 replace_value = replace;
    1402          22 :                 replace_idx = 0;
    1403             : 
    1404             :                 /* For each entry in the regex array, get the entry */
    1405         149 :                 ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(regex), regex_entry) {
    1406             :                         zval replace_str;
    1407             :                         /* Make sure we're dealing with strings. */
    1408          64 :                         zend_string *regex_str = zval_get_string(regex_entry);
    1409             : 
    1410          64 :                         ZVAL_UNDEF(&replace_str);
    1411             :                         /* If replace is an array and not a callable construct */
    1412          64 :                         if (Z_TYPE_P(replace) == IS_ARRAY && !is_callable_replace) {
    1413             :                                 /* Get current entry */
    1414          98 :                                 while (replace_idx < Z_ARRVAL_P(replace)->nNumUsed) {
    1415          94 :                                         if (Z_TYPE(Z_ARRVAL_P(replace)->arData[replace_idx].val) != IS_UNDEF) {
    1416          47 :                                                 ZVAL_COPY(&replace_str, &Z_ARRVAL_P(replace)->arData[replace_idx].val);
    1417          47 :                                                 break;
    1418             :                                         }
    1419           0 :                                         replace_idx++;
    1420             :                                 }
    1421          49 :                                 if (!Z_ISUNDEF(replace_str)) {
    1422          47 :                                         if (!is_callable_replace) {
    1423          47 :                                                 convert_to_string(&replace_str);
    1424             :                                         }
    1425          47 :                                         replace_value = &replace_str;
    1426          47 :                                         replace_idx++;
    1427             :                                 } else {
    1428             :                                         /* We've run out of replacement strings, so use an empty one */
    1429           2 :                                         replace_value = &empty_replace;
    1430             :                                 }
    1431             :                         }
    1432             : 
    1433             :                         /* Do the actual replacement and put the result back into subject_str
    1434             :                            for further replacements. */
    1435          64 :                         if ((result = php_pcre_replace(regex_str,
    1436             :                                                                                    subject_str,
    1437             :                                                                                    ZSTR_VAL(subject_str),
    1438             :                                                                                    (int)ZSTR_LEN(subject_str),
    1439             :                                                                                    replace_value,
    1440             :                                                                                    is_callable_replace,
    1441             :                                                                                    limit,
    1442             :                                                                                    replace_count)) != NULL) {
    1443             :                                 zend_string_release(subject_str);
    1444          63 :                                 subject_str = result;
    1445             :                         } else {
    1446             :                                 zend_string_release(subject_str);
    1447             :                                 zend_string_release(regex_str);
    1448             :                                 zval_dtor(&replace_str);
    1449           1 :                                 return NULL;
    1450             :                         }
    1451             : 
    1452             :                         zend_string_release(regex_str);
    1453             :                         zval_dtor(&replace_str);
    1454             :                 } ZEND_HASH_FOREACH_END();
    1455             : 
    1456          21 :                 return subject_str;
    1457             :         } else {
    1458       37385 :                 result = php_pcre_replace(Z_STR_P(regex),
    1459             :                                                                   subject_str,
    1460             :                                                                   ZSTR_VAL(subject_str),
    1461             :                                                                   (int)ZSTR_LEN(subject_str),
    1462             :                                                                   replace,
    1463             :                                                                   is_callable_replace,
    1464             :                                                                   limit,
    1465             :                                                                   replace_count);
    1466             :                 zend_string_release(subject_str);
    1467       37385 :                 return result;
    1468             :         }
    1469             : }
    1470             : /* }}} */
    1471             : 
    1472             : /* {{{ preg_replace_impl
    1473             :  */
    1474       37397 : static int preg_replace_impl(zval *return_value, zval *regex, zval *replace, zval *subject, zend_long limit_val, int is_callable_replace, int is_filter)
    1475             : {
    1476             :         zval            *subject_entry;
    1477             :         zend_string     *result;
    1478             :         zend_string     *string_key;
    1479             :         zend_ulong       num_key;
    1480       37397 :         int                      replace_count = 0, old_replace_count;
    1481             : 
    1482       74783 :         if (Z_TYPE_P(replace) != IS_ARRAY && (Z_TYPE_P(replace) != IS_OBJECT || !is_callable_replace)) {
    1483       37376 :                 convert_to_string_ex(replace);
    1484             :         }
    1485             : 
    1486       37395 :         if (Z_TYPE_P(regex) != IS_ARRAY) {
    1487       37385 :                 convert_to_string_ex(regex);
    1488             :         }
    1489             : 
    1490             :         /* if subject is an array */
    1491       37394 :         if (Z_TYPE_P(subject) == IS_ARRAY) {
    1492           6 :                 array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(subject)));
    1493             : 
    1494             :                 /* For each subject entry, convert it to string, then perform replacement
    1495             :                    and add the result to the return_value array. */
    1496          44 :                 ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(subject), num_key, string_key, subject_entry) {
    1497          19 :                         old_replace_count = replace_count;
    1498          19 :                         if ((result = php_replace_in_subject(regex, replace, subject_entry, limit_val, is_callable_replace, &replace_count)) != NULL) {
    1499          36 :                                 if (!is_filter || replace_count > old_replace_count) {
    1500             :                                         /* Add to return array */
    1501             :                                         zval zv;
    1502             : 
    1503          17 :                                         ZVAL_STR(&zv, result);
    1504          17 :                                         if (string_key) {
    1505           1 :                                                 zend_hash_add_new(Z_ARRVAL_P(return_value), string_key, &zv);
    1506             :                                         } else {
    1507          16 :                                                 zend_hash_index_add_new(Z_ARRVAL_P(return_value), num_key, &zv);
    1508             :                                         }
    1509             :                                 } else {
    1510             :                                         zend_string_release(result);
    1511             :                                 }
    1512             :                         }
    1513             :                 } ZEND_HASH_FOREACH_END();
    1514             :         } else {        
    1515             :                 /* if subject is not an array */
    1516       37388 :                 old_replace_count = replace_count;
    1517       37388 :                 if ((result = php_replace_in_subject(regex, replace, subject, limit_val, is_callable_replace, &replace_count)) != NULL) {
    1518       74734 :                         if (!is_filter || replace_count > old_replace_count) {
    1519       37367 :                                 RETVAL_STR(result);
    1520             :                         } else {
    1521             :                                 zend_string_release(result);
    1522             :                         }
    1523             :                 }
    1524             :         }
    1525             :         
    1526       37394 :         return replace_count;
    1527             : }
    1528             : /* }}} */
    1529             : 
    1530             : /* {{{ proto mixed preg_replace(mixed regex, mixed replace, mixed subject [, int limit [, int &count]])
    1531             :    Perform Perl-style regular expression replacement. */
    1532       37350 : static PHP_FUNCTION(preg_replace)
    1533             : {
    1534       37350 :         zval *regex, *replace, *subject, *zcount = NULL;
    1535       37350 :         zend_long limit = -1;
    1536             :         int replace_count;
    1537             : 
    1538             :         /* Get function parameters and do error-checking. */
    1539       37350 :         ZEND_PARSE_PARAMETERS_START(3, 5)
    1540       37347 :                 Z_PARAM_ZVAL(regex)
    1541       37347 :                 Z_PARAM_ZVAL(replace)
    1542       37347 :                 Z_PARAM_ZVAL(subject)
    1543       37347 :                 Z_PARAM_OPTIONAL
    1544       37387 :                 Z_PARAM_LONG(limit)
    1545          27 :                 Z_PARAM_ZVAL_EX(zcount, 0, 1)
    1546       37350 :         ZEND_PARSE_PARAMETERS_END();
    1547             : 
    1548       74702 :         if (Z_TYPE_P(replace) == IS_ARRAY && Z_TYPE_P(regex) != IS_ARRAY) {
    1549           3 :                 php_error_docref(NULL, E_WARNING, "Parameter mismatch, pattern is a string while replacement is an array");
    1550           3 :                 RETURN_FALSE;
    1551             :         }
    1552             : 
    1553       37344 :         replace_count = preg_replace_impl(return_value, regex, replace, subject, limit, 0, 0);
    1554       37341 :         if (zcount) {
    1555           7 :                 zval_dtor(zcount);
    1556           7 :                 ZVAL_LONG(zcount, replace_count);
    1557             :         }
    1558             : }
    1559             : /* }}} */
    1560             : 
    1561             : /* {{{ proto mixed preg_replace_callback(mixed regex, mixed callback, mixed subject [, int limit [, int &count]])
    1562             :    Perform Perl-style regular expression replacement using replacement callback. */
    1563          50 : static PHP_FUNCTION(preg_replace_callback)
    1564             : {
    1565          50 :         zval *regex, *replace, *subject, *zcount = NULL;
    1566          50 :         zend_long limit = -1;
    1567             :         zend_string     *callback_name;
    1568             :         int replace_count;
    1569             : 
    1570             :         /* Get function parameters and do error-checking. */
    1571          50 :         ZEND_PARSE_PARAMETERS_START(3, 5)
    1572          44 :                 Z_PARAM_ZVAL(regex)
    1573          44 :                 Z_PARAM_ZVAL(replace)
    1574          44 :                 Z_PARAM_ZVAL(subject)
    1575          44 :                 Z_PARAM_OPTIONAL
    1576          58 :                 Z_PARAM_LONG(limit)
    1577           6 :                 Z_PARAM_ZVAL_EX(zcount, 0, 1)
    1578          50 :         ZEND_PARSE_PARAMETERS_END();
    1579             : 
    1580          41 :         if (!zend_is_callable(replace, 0, &callback_name)) {
    1581           3 :                 php_error_docref(NULL, E_WARNING, "Requires argument 2, '%s', to be a valid callback", ZSTR_VAL(callback_name));
    1582           3 :                 zend_string_release(callback_name);
    1583           3 :                 ZVAL_COPY(return_value, subject);
    1584           3 :                 return;
    1585             :         }
    1586          38 :         zend_string_release(callback_name);
    1587             : 
    1588          38 :         replace_count = preg_replace_impl(return_value, regex, replace, subject, limit, 1, 0);
    1589          38 :         if (zcount) {
    1590           1 :                 zval_dtor(zcount);
    1591           1 :                 ZVAL_LONG(zcount, replace_count);
    1592             :         }
    1593             : }
    1594             : /* }}} */
    1595             : 
    1596             : /* {{{ proto mixed preg_replace_callback_array(array pattern, mixed subject [, int limit [, int &count]])
    1597             :    Perform Perl-style regular expression replacement using replacement callback. */
    1598          12 : static PHP_FUNCTION(preg_replace_callback_array)
    1599             : {
    1600          12 :         zval regex, zv, *replace, *subject, *pattern, *zcount = NULL;
    1601          12 :         zend_long limit = -1;
    1602             :         zend_string *str_idx;
    1603             :         zend_string *callback_name;
    1604          12 :         int replace_count = 0;
    1605             : 
    1606             :         /* Get function parameters and do error-checking. */
    1607          12 :         ZEND_PARSE_PARAMETERS_START(2, 4)
    1608          30 :                 Z_PARAM_ARRAY(pattern)
    1609           7 :                 Z_PARAM_ZVAL(subject)
    1610           7 :                 Z_PARAM_OPTIONAL
    1611          13 :                 Z_PARAM_LONG(limit)
    1612           4 :                 Z_PARAM_ZVAL_EX(zcount, 0, 1)
    1613          12 :         ZEND_PARSE_PARAMETERS_END();
    1614             :         
    1615           6 :         ZVAL_UNDEF(&zv);
    1616          33 :         ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(pattern), str_idx, replace) {
    1617          15 :                 if (str_idx) {
    1618          15 :                         ZVAL_STR_COPY(&regex, str_idx);
    1619             :                 } else {
    1620           0 :                         php_error_docref(NULL, E_WARNING, "Delimiter must not be alphanumeric or backslash");
    1621           0 :                         zval_ptr_dtor(return_value);
    1622           0 :                         RETURN_NULL();
    1623             :                 }               
    1624             : 
    1625          15 :                 if (!zend_is_callable(replace, 0, &callback_name)) {
    1626           1 :                         php_error_docref(NULL, E_WARNING, "'%s' is not a valid callback", ZSTR_VAL(callback_name));
    1627           1 :                         zend_string_release(callback_name);
    1628           1 :                         zval_ptr_dtor(&regex);
    1629           1 :                         zval_ptr_dtor(return_value);
    1630           1 :                         ZVAL_COPY(return_value, subject);
    1631           1 :                         return;
    1632             :                 }
    1633          14 :                 zend_string_release(callback_name);
    1634             : 
    1635          14 :                 if (Z_ISNULL_P(return_value)) {
    1636           5 :                         replace_count += preg_replace_impl(&zv, &regex, replace, subject, limit, 1, 0);
    1637             :                 } else {
    1638           9 :                         replace_count += preg_replace_impl(&zv, &regex, replace, return_value, limit, 1, 0);
    1639           9 :                         zval_ptr_dtor(return_value);
    1640             :                 }
    1641             : 
    1642          14 :                 zval_ptr_dtor(&regex);
    1643             : 
    1644          14 :                 if (Z_ISUNDEF(zv)) {
    1645           1 :                         RETURN_NULL();  
    1646             :                 }
    1647             : 
    1648          13 :                 ZVAL_COPY_VALUE(return_value, &zv);
    1649             : 
    1650          13 :                 if (UNEXPECTED(EG(exception))) {
    1651           1 :                         zval_ptr_dtor(return_value);
    1652           1 :                         RETURN_NULL();  
    1653             :                 }
    1654             :         } ZEND_HASH_FOREACH_END();
    1655             : 
    1656           3 :         if (zcount) {
    1657           1 :                 zval_dtor(zcount);
    1658           1 :                 ZVAL_LONG(zcount, replace_count);
    1659             :         }
    1660             : }
    1661             : /* }}} */
    1662             : 
    1663             : /* {{{ proto mixed preg_filter(mixed regex, mixed replace, mixed subject [, int limit [, int &count]])
    1664             :    Perform Perl-style regular expression replacement and only return matches. */
    1665           1 : static PHP_FUNCTION(preg_filter)
    1666             : {
    1667           1 :         zval *regex, *replace, *subject, *zcount = NULL;
    1668           1 :         zend_long limit = -1;
    1669             :         int replace_count;
    1670             : 
    1671             :         /* Get function parameters and do error-checking. */
    1672           1 :         ZEND_PARSE_PARAMETERS_START(3, 5)
    1673           1 :                 Z_PARAM_ZVAL(regex)
    1674           1 :                 Z_PARAM_ZVAL(replace)
    1675           1 :                 Z_PARAM_ZVAL(subject)
    1676           1 :                 Z_PARAM_OPTIONAL
    1677           1 :                 Z_PARAM_LONG(limit)
    1678           0 :                 Z_PARAM_ZVAL_EX(zcount, 0, 1)
    1679           1 :         ZEND_PARSE_PARAMETERS_END();
    1680             : 
    1681           3 :         if (Z_TYPE_P(replace) == IS_ARRAY && Z_TYPE_P(regex) != IS_ARRAY) {
    1682           0 :                 php_error_docref(NULL, E_WARNING, "Parameter mismatch, pattern is a string while replacement is an array");
    1683           0 :                 RETURN_FALSE;
    1684             :         }
    1685             : 
    1686           1 :         replace_count = preg_replace_impl(return_value, regex, replace, subject, limit, 0, 1);
    1687           1 :         if (zcount) {
    1688           0 :                 zval_dtor(zcount);
    1689           0 :                 ZVAL_LONG(zcount, replace_count);
    1690             :         }
    1691             : }
    1692             : /* }}} */
    1693             : 
    1694             : /* {{{ proto array preg_split(string pattern, string subject [, int limit [, int flags]])
    1695             :    Split string into an array using a perl-style regular expression as a delimiter */
    1696       10898 : static PHP_FUNCTION(preg_split)
    1697             : {
    1698             :         zend_string                     *regex;                 /* Regular expression */
    1699             :         zend_string                     *subject;               /* String to match against */
    1700       10898 :         zend_long                        limit_val = -1;/* Integer value of limit */
    1701       10898 :         zend_long                        flags = 0;             /* Match control flags */
    1702             :         pcre_cache_entry        *pce;                   /* Compiled regular expression */
    1703             : 
    1704             :         /* Get function parameters and do error checking */
    1705       10898 :         ZEND_PARSE_PARAMETERS_START(2, 4)
    1706       32682 :                 Z_PARAM_STR(regex)
    1707       32676 :                 Z_PARAM_STR(subject)
    1708       10890 :                 Z_PARAM_OPTIONAL
    1709       10946 :                 Z_PARAM_LONG(limit_val)
    1710          60 :                 Z_PARAM_LONG(flags)
    1711       10898 :         ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
    1712             : 
    1713       10890 :         if (ZEND_SIZE_T_INT_OVFL(ZSTR_LEN(subject))) {
    1714           0 :                         php_error_docref(NULL, E_WARNING, "Subject is too long");
    1715           0 :                         RETURN_FALSE;
    1716             :         }
    1717             : 
    1718             :         /* Compile regex or get it from cache. */
    1719       10890 :         if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
    1720           5 :                 RETURN_FALSE;
    1721             :         }
    1722             : 
    1723       10885 :         pce->refcount++;
    1724       10885 :         php_pcre_split_impl(pce, ZSTR_VAL(subject), (int)ZSTR_LEN(subject), return_value, (int)limit_val, flags);
    1725       10885 :         pce->refcount--;
    1726             : }
    1727             : /* }}} */
    1728             : 
    1729             : /* {{{ php_pcre_split
    1730             :  */
    1731       10900 : PHPAPI void php_pcre_split_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value,
    1732             :         zend_long limit_val, zend_long flags)
    1733             : {
    1734       10900 :         pcre_extra              *extra = pce->extra;/* Holds results of studying */
    1735             :         pcre_extra               extra_data;            /* Used locally for exec options */
    1736             :         int                             *offsets;                       /* Array of subpattern offsets */
    1737             :         int                              size_offsets;          /* Size of the offsets array */
    1738       10900 :         int                              exoptions = 0;         /* Execution options */
    1739       10900 :         int                              count = 0;                     /* Count of matched subpatterns */
    1740             :         int                              start_offset;          /* Where the new search starts */
    1741             :         int                              next_offset;           /* End of the last delimiter match + 1 */
    1742       10900 :         int                              g_notempty = 0;        /* If the match should not be empty */
    1743             :         char                    *last_match;            /* Location of last match */
    1744             :         int                              no_empty;                      /* If NO_EMPTY flag is set */
    1745             :         int                              delim_capture;         /* If delimiters should be captured */
    1746             :         int                              offset_capture;        /* If offsets should be captured */
    1747             :         zval                     tmp;
    1748             :         ALLOCA_FLAG(use_heap);
    1749             : 
    1750       10900 :         no_empty = flags & PREG_SPLIT_NO_EMPTY;
    1751       10900 :         delim_capture = flags & PREG_SPLIT_DELIM_CAPTURE;
    1752       10900 :         offset_capture = flags & PREG_SPLIT_OFFSET_CAPTURE;
    1753             : 
    1754       10900 :         if (limit_val == 0) {
    1755           1 :                 limit_val = -1;
    1756             :         }
    1757             : 
    1758       10900 :         if (extra == NULL) {
    1759           7 :                 extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
    1760           7 :                 extra = &extra_data;
    1761             :         }
    1762       10900 :         extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
    1763       10900 :         extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
    1764             : #ifdef PCRE_EXTRA_MARK
    1765       10900 :         extra->flags &= ~PCRE_EXTRA_MARK;
    1766             : #endif
    1767             : 
    1768             :         /* Initialize return value */
    1769       10900 :         array_init(return_value);
    1770             : 
    1771             :         /* Calculate the size of the offsets array, and allocate memory for it. */
    1772       10900 :         size_offsets = (pce->capture_count + 1) * 3;
    1773       10900 :         if (size_offsets <= 32) {
    1774       10900 :                 offsets = (int *)do_alloca(size_offsets * sizeof(int), use_heap);
    1775             :         } else {
    1776           0 :                 offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
    1777             :         }
    1778             : 
    1779             :         /* Start at the beginning of the string */
    1780       10900 :         start_offset = 0;
    1781       10900 :         next_offset = 0;
    1782       10900 :         last_match = subject;
    1783       10900 :         PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
    1784             : 
    1785             :         /* Get next piece if no limit or limit not yet reached and something matched*/
    1786       34646 :         while ((limit_val == -1 || limit_val > 1)) {
    1787       23736 :                 count = pcre_exec(pce->re, extra, subject,
    1788             :                                                   subject_len, start_offset,
    1789             :                                                   exoptions|g_notempty, offsets, size_offsets);
    1790             : 
    1791             :                 /* the string was already proved to be valid UTF-8 */
    1792       23736 :                 exoptions |= PCRE_NO_UTF8_CHECK;
    1793             : 
    1794             :                 /* Check for too many substrings condition. */
    1795       23736 :                 if (count == 0) {
    1796           0 :                         php_error_docref(NULL,E_NOTICE, "Matched, but too many substrings");
    1797           0 :                         count = size_offsets/3;
    1798             :                 }
    1799             : 
    1800             :                 /* If something matched */
    1801       36521 :                 if (count > 0 && (offsets[1] - offsets[0] >= 0)) {
    1802       12785 :                         if (!no_empty || &subject[offsets[0]] != last_match) {
    1803             : 
    1804       12726 :                                 if (offset_capture) {
    1805             :                                         /* Add (match, offset) pair to the return value */
    1806          26 :                                         add_offset_pair(return_value, last_match, (int)(&subject[offsets[0]]-last_match), next_offset, NULL);
    1807             :                                 } else {
    1808             :                                         /* Add the piece to the return value */
    1809       25400 :                                         ZVAL_STRINGL(&tmp, last_match, &subject[offsets[0]]-last_match);
    1810       12700 :                                         zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &tmp);
    1811             :                                 }
    1812             : 
    1813             :                                 /* One less left to do */
    1814       12726 :                                 if (limit_val != -1)
    1815          13 :                                         limit_val--;
    1816             :                         }
    1817             : 
    1818       12785 :                         last_match = &subject[offsets[1]];
    1819       12785 :                         next_offset = offsets[1];
    1820             : 
    1821       12785 :                         if (delim_capture) {
    1822             :                                 int i, match_len;
    1823          62 :                                 for (i = 1; i < count; i++) {
    1824          31 :                                         match_len = offsets[(i<<1)+1] - offsets[i<<1];
    1825             :                                         /* If we have matched a delimiter */
    1826          31 :                                         if (!no_empty || match_len > 0) {
    1827          21 :                                                 if (offset_capture) {
    1828          10 :                                                         add_offset_pair(return_value, &subject[offsets[i<<1]], match_len, offsets[i<<1], NULL);
    1829             :                                                 } else {
    1830          22 :                                                         ZVAL_STRINGL(&tmp, &subject[offsets[i<<1]], match_len);
    1831          11 :                                                         zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &tmp);
    1832             :                                                 }
    1833             :                                         }
    1834             :                                 }
    1835             :                         }
    1836       10951 :                 } else if (count == PCRE_ERROR_NOMATCH) {
    1837             :                         /* If we previously set PCRE_NOTEMPTY_ATSTART after a null match,
    1838             :                            this is not necessarily the end. We need to advance
    1839             :                            the start offset, and continue. Fudge the offset values
    1840             :                            to achieve this, unless we're already at the end of the string. */
    1841       10949 :                         if (g_notempty != 0 && start_offset < subject_len) {
    1842          61 :                                 offsets[0] = start_offset;
    1843         122 :                                 offsets[1] = start_offset + calculate_unit_length(pce, subject + start_offset);
    1844             :                         } else {
    1845             :                                 break;
    1846             :                         }
    1847             :                 } else {
    1848           2 :                         pcre_handle_exec_error(count);
    1849           2 :                         break;
    1850             :                 }
    1851             : 
    1852             :                 /* If we have matched an empty string, mimic what Perl's /g options does.
    1853             :                    This turns out to be rather cunning. First we set PCRE_NOTEMPTY_ATSTART and try
    1854             :                    the match again at the same point. If this fails (picked up above) we
    1855             :                    advance to the next character. */
    1856       12846 :                 g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY_ATSTART | PCRE_ANCHORED : 0;
    1857             : 
    1858             :                 /* Advance to the position right after the last full match */
    1859       12846 :                 start_offset = offsets[1];
    1860             :         }
    1861             : 
    1862             : 
    1863       10900 :         start_offset = (int)(last_match - subject); /* the offset might have been incremented, but without further successful matches */
    1864             : 
    1865       10900 :         if (!no_empty || start_offset < subject_len)
    1866             :         {
    1867       10892 :                 if (offset_capture) {
    1868             :                         /* Add the last (match, offset) pair to the return value */
    1869           5 :                         add_offset_pair(return_value, &subject[start_offset], subject_len - start_offset, start_offset, NULL);
    1870             :                 } else {
    1871             :                         /* Add the last piece to the return value */
    1872       21774 :                         ZVAL_STRINGL(&tmp, last_match, subject + subject_len - last_match);
    1873       10887 :                         zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &tmp);
    1874             :                 }
    1875             :         }
    1876             : 
    1877             : 
    1878             :         /* Clean up */
    1879       10900 :         if (size_offsets <= 32) {
    1880       10900 :                 free_alloca(offsets, use_heap);
    1881             :         } else {
    1882           0 :                 efree(offsets);
    1883             :         }
    1884       10900 : }
    1885             : /* }}} */
    1886             : 
    1887             : /* {{{ proto string preg_quote(string str [, string delim_char])
    1888             :    Quote regular expression characters plus an optional character */
    1889        9167 : static PHP_FUNCTION(preg_quote)
    1890             : {
    1891             :         size_t           in_str_len;
    1892             :         char    *in_str;                /* Input string argument */
    1893             :         char    *in_str_end;    /* End of the input string */
    1894        9167 :         size_t           delim_len = 0;
    1895        9167 :         char    *delim = NULL;  /* Additional delimiter argument */
    1896             :         zend_string     *out_str;       /* Output string with quoted characters */
    1897             :         char    *p,                             /* Iterator for input string */
    1898             :                         *q,                             /* Iterator for output string */
    1899        9167 :                          delim_char=0,  /* Delimiter character to be quoted */
    1900             :                          c;                             /* Current character */
    1901        9167 :         zend_bool quote_delim = 0; /* Whether to quote additional delim char */
    1902             : 
    1903             :         /* Get the arguments and check for errors */
    1904        9167 :         ZEND_PARSE_PARAMETERS_START(1, 2)
    1905       27492 :                 Z_PARAM_STRING(in_str, in_str_len)
    1906        9162 :                 Z_PARAM_OPTIONAL
    1907       27478 :                 Z_PARAM_STRING(delim, delim_len)
    1908        9167 :         ZEND_PARSE_PARAMETERS_END();
    1909             : 
    1910        9162 :         in_str_end = in_str + in_str_len;
    1911             : 
    1912             :         /* Nothing to do if we got an empty string */
    1913        9162 :         if (in_str == in_str_end) {
    1914           5 :                 RETURN_EMPTY_STRING();
    1915             :         }
    1916             : 
    1917        9157 :         if (delim && *delim) {
    1918        9154 :                 delim_char = delim[0];
    1919        9154 :                 quote_delim = 1;
    1920             :         }
    1921             : 
    1922             :         /* Allocate enough memory so that even if each character
    1923             :            is quoted, we won't run out of room */
    1924       18314 :         out_str = zend_string_safe_alloc(4, in_str_len, 0, 0);
    1925             : 
    1926             :         /* Go through the string and quote necessary characters */
    1927     7913989 :         for (p = in_str, q = ZSTR_VAL(out_str); p != in_str_end; p++) {
    1928     7904832 :                 c = *p;
    1929     7904832 :                 switch(c) {
    1930             :                         case '.':
    1931             :                         case '\\':
    1932             :                         case '+':
    1933             :                         case '*':
    1934             :                         case '?':
    1935             :                         case '[':
    1936             :                         case '^':
    1937             :                         case ']':
    1938             :                         case '$':
    1939             :                         case '(':
    1940             :                         case ')':
    1941             :                         case '{':
    1942             :                         case '}':
    1943             :                         case '=':
    1944             :                         case '!':
    1945             :                         case '>':
    1946             :                         case '<':
    1947             :                         case '|':
    1948             :                         case ':':
    1949             :                         case '-':
    1950     1108714 :                                 *q++ = '\\';
    1951     1108714 :                                 *q++ = c;
    1952     1108714 :                                 break;
    1953             : 
    1954             :                         case '\0':
    1955        1086 :                                 *q++ = '\\';
    1956        1086 :                                 *q++ = '0';
    1957        1086 :                                 *q++ = '0';
    1958        1086 :                                 *q++ = '0';
    1959        1086 :                                 break;
    1960             : 
    1961             :                         default:
    1962     6795032 :                                 if (quote_delim && c == delim_char)
    1963       15450 :                                         *q++ = '\\';
    1964     6795032 :                                 *q++ = c;
    1965             :                                 break;
    1966             :                 }
    1967             :         }
    1968        9157 :         *q = '\0';
    1969             : 
    1970             :         /* Reallocate string and return it */
    1971       18314 :         out_str = zend_string_truncate(out_str, q - ZSTR_VAL(out_str), 0);
    1972        9157 :         RETURN_NEW_STR(out_str);
    1973             : }
    1974             : /* }}} */
    1975             : 
    1976             : /* {{{ proto array preg_grep(string regex, array input [, int flags])
    1977             :    Searches array and returns entries which match regex */
    1978        8221 : static PHP_FUNCTION(preg_grep)
    1979             : {
    1980             :         zend_string                     *regex;                 /* Regular expression */
    1981             :         zval                            *input;                 /* Input array */
    1982        8221 :         zend_long                        flags = 0;             /* Match control flags */
    1983             :         pcre_cache_entry        *pce;                   /* Compiled regular expression */
    1984             : 
    1985             :         /* Get arguments and do error checking */
    1986        8221 :         ZEND_PARSE_PARAMETERS_START(2, 3)
    1987       24651 :                 Z_PARAM_STR(regex)
    1988       24645 :                 Z_PARAM_ARRAY(input)
    1989        8212 :                 Z_PARAM_OPTIONAL
    1990        8218 :                 Z_PARAM_LONG(flags)
    1991        8221 :         ZEND_PARSE_PARAMETERS_END();
    1992             : 
    1993             :         /* Compile regex or get it from cache. */
    1994        8212 :         if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
    1995           5 :                 RETURN_FALSE;
    1996             :         }
    1997             : 
    1998        8207 :         pce->refcount++;
    1999        8207 :         php_pcre_grep_impl(pce, input, return_value, flags);
    2000        8207 :         pce->refcount--;
    2001             : }
    2002             : /* }}} */
    2003             : 
    2004        8207 : PHPAPI void  php_pcre_grep_impl(pcre_cache_entry *pce, zval *input, zval *return_value, zend_long flags) /* {{{ */
    2005             : {
    2006             :         zval                *entry;                             /* An entry in the input array */
    2007        8207 :         pcre_extra              *extra = pce->extra;/* Holds results of studying */
    2008             :         pcre_extra               extra_data;            /* Used locally for exec options */
    2009             :         int                             *offsets;                       /* Array of subpattern offsets */
    2010             :         int                              size_offsets;          /* Size of the offsets array */
    2011        8207 :         int                              count = 0;                     /* Count of matched subpatterns */
    2012             :         zend_string             *string_key;
    2013             :         zend_ulong               num_key;
    2014             :         zend_bool                invert;                        /* Whether to return non-matching
    2015             :                                                                                    entries */
    2016             :         ALLOCA_FLAG(use_heap);
    2017             : 
    2018        8207 :         invert = flags & PREG_GREP_INVERT ? 1 : 0;
    2019             : 
    2020        8207 :         if (extra == NULL) {
    2021           0 :                 extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
    2022           0 :                 extra = &extra_data;
    2023             :         }
    2024        8207 :         extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
    2025        8207 :         extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
    2026             : #ifdef PCRE_EXTRA_MARK
    2027        8207 :         extra->flags &= ~PCRE_EXTRA_MARK;
    2028             : #endif
    2029             : 
    2030             :         /* Calculate the size of the offsets array, and allocate memory for it. */
    2031        8207 :         size_offsets = (pce->capture_count + 1) * 3;
    2032        8207 :         if (size_offsets <= 32) {
    2033        8207 :                 offsets = (int *)do_alloca(size_offsets * sizeof(int), use_heap);
    2034             :         } else {
    2035           0 :                 offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
    2036             :         }
    2037             : 
    2038             :         /* Initialize return array */
    2039        8207 :         array_init(return_value);
    2040             : 
    2041        8207 :         PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
    2042             : 
    2043             :         /* Go through the input array */
    2044       24747 :         ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(input), num_key, string_key, entry) {
    2045        8270 :                 zend_string *subject_str = zval_get_string(entry);
    2046             : 
    2047             :                 /* Perform the match */
    2048        8270 :                 count = pcre_exec(pce->re, extra, ZSTR_VAL(subject_str),
    2049             :                                                   (int)ZSTR_LEN(subject_str), 0,
    2050             :                                                   0, offsets, size_offsets);
    2051             : 
    2052             :                 /* Check for too many substrings condition. */
    2053        8270 :                 if (count == 0) {
    2054           0 :                         php_error_docref(NULL, E_NOTICE, "Matched, but too many substrings");
    2055           0 :                         count = size_offsets/3;
    2056        8270 :                 } else if (count < 0 && count != PCRE_ERROR_NOMATCH) {
    2057           0 :                         pcre_handle_exec_error(count);
    2058             :                         zend_string_release(subject_str);
    2059           0 :                         break;
    2060             :                 }
    2061             : 
    2062             :                 /* If the entry fits our requirements */
    2063        8270 :                 if ((count > 0 && !invert) || (count == PCRE_ERROR_NOMATCH && invert)) {
    2064        8225 :                         if (Z_REFCOUNTED_P(entry)) {
    2065             :                                 Z_ADDREF_P(entry);
    2066             :                         }
    2067             : 
    2068             :                         /* Add to return array */
    2069        8225 :                         if (string_key) {
    2070           3 :                                 zend_hash_update(Z_ARRVAL_P(return_value), string_key, entry);
    2071             :                         } else {
    2072        8222 :                                 zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry);
    2073             :                         }
    2074             :                 }
    2075             : 
    2076             :                 zend_string_release(subject_str);
    2077             :         } ZEND_HASH_FOREACH_END();
    2078             : 
    2079             :         /* Clean up */
    2080        8207 :         if (size_offsets <= 32) {
    2081        8207 :                 free_alloca(offsets, use_heap);
    2082             :         } else {
    2083           0 :                 efree(offsets);
    2084             :         }
    2085        8207 : }
    2086             : /* }}} */
    2087             : 
    2088             : /* {{{ proto int preg_last_error()
    2089             :    Returns the error code of the last regexp execution. */
    2090          18 : static PHP_FUNCTION(preg_last_error)
    2091             : {
    2092          18 :         ZEND_PARSE_PARAMETERS_START(0, 0)
    2093          18 :         ZEND_PARSE_PARAMETERS_END();
    2094             : 
    2095          16 :         RETURN_LONG(PCRE_G(error_code));
    2096             : }
    2097             : /* }}} */
    2098             : 
    2099             : /* {{{ module definition structures */
    2100             : 
    2101             : /* {{{ arginfo */
    2102             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_match, 0, 0, 2)
    2103             :     ZEND_ARG_INFO(0, pattern)
    2104             :     ZEND_ARG_INFO(0, subject)
    2105             :     ZEND_ARG_INFO(1, subpatterns) /* array */
    2106             :     ZEND_ARG_INFO(0, flags)
    2107             :     ZEND_ARG_INFO(0, offset)
    2108             : ZEND_END_ARG_INFO()
    2109             : 
    2110             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_match_all, 0, 0, 2)
    2111             :     ZEND_ARG_INFO(0, pattern)
    2112             :     ZEND_ARG_INFO(0, subject)
    2113             :     ZEND_ARG_INFO(1, subpatterns) /* array */
    2114             :     ZEND_ARG_INFO(0, flags)
    2115             :     ZEND_ARG_INFO(0, offset)
    2116             : ZEND_END_ARG_INFO()
    2117             : 
    2118             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_replace, 0, 0, 3)
    2119             :     ZEND_ARG_INFO(0, regex)
    2120             :     ZEND_ARG_INFO(0, replace)
    2121             :     ZEND_ARG_INFO(0, subject)
    2122             :     ZEND_ARG_INFO(0, limit)
    2123             :     ZEND_ARG_INFO(1, count)
    2124             : ZEND_END_ARG_INFO()
    2125             : 
    2126             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_replace_callback, 0, 0, 3)
    2127             :     ZEND_ARG_INFO(0, regex)
    2128             :     ZEND_ARG_INFO(0, callback)
    2129             :     ZEND_ARG_INFO(0, subject)
    2130             :     ZEND_ARG_INFO(0, limit)
    2131             :     ZEND_ARG_INFO(1, count)
    2132             : ZEND_END_ARG_INFO()
    2133             : 
    2134             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_replace_callback_array, 0, 0, 2)
    2135             :     ZEND_ARG_INFO(0, pattern)
    2136             :     ZEND_ARG_INFO(0, subject)
    2137             :     ZEND_ARG_INFO(0, limit)
    2138             :     ZEND_ARG_INFO(1, count)
    2139             : ZEND_END_ARG_INFO()
    2140             : 
    2141             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_split, 0, 0, 2)
    2142             :     ZEND_ARG_INFO(0, pattern)
    2143             :     ZEND_ARG_INFO(0, subject)
    2144             :     ZEND_ARG_INFO(0, limit)
    2145             :     ZEND_ARG_INFO(0, flags)
    2146             : ZEND_END_ARG_INFO()
    2147             : 
    2148             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_quote, 0, 0, 1)
    2149             :     ZEND_ARG_INFO(0, str)
    2150             :     ZEND_ARG_INFO(0, delim_char)
    2151             : ZEND_END_ARG_INFO()
    2152             : 
    2153             : ZEND_BEGIN_ARG_INFO_EX(arginfo_preg_grep, 0, 0, 2)
    2154             :     ZEND_ARG_INFO(0, regex)
    2155             :     ZEND_ARG_INFO(0, input) /* array */
    2156             :     ZEND_ARG_INFO(0, flags)
    2157             : ZEND_END_ARG_INFO()
    2158             : 
    2159             : ZEND_BEGIN_ARG_INFO(arginfo_preg_last_error, 0)
    2160             : ZEND_END_ARG_INFO()
    2161             : /* }}} */
    2162             : 
    2163             : static const zend_function_entry pcre_functions[] = {
    2164             :         PHP_FE(preg_match,                                      arginfo_preg_match)
    2165             :         PHP_FE(preg_match_all,                          arginfo_preg_match_all)
    2166             :         PHP_FE(preg_replace,                            arginfo_preg_replace)
    2167             :         PHP_FE(preg_replace_callback,           arginfo_preg_replace_callback)
    2168             :         PHP_FE(preg_replace_callback_array,     arginfo_preg_replace_callback_array)
    2169             :         PHP_FE(preg_filter,                                     arginfo_preg_replace)
    2170             :         PHP_FE(preg_split,                                      arginfo_preg_split)
    2171             :         PHP_FE(preg_quote,                                      arginfo_preg_quote)
    2172             :         PHP_FE(preg_grep,                                       arginfo_preg_grep)
    2173             :         PHP_FE(preg_last_error,                         arginfo_preg_last_error)
    2174             :         PHP_FE_END
    2175             : };
    2176             : 
    2177             : zend_module_entry pcre_module_entry = {
    2178             :         STANDARD_MODULE_HEADER,
    2179             :    "pcre",
    2180             :         pcre_functions,
    2181             :         PHP_MINIT(pcre),
    2182             :         PHP_MSHUTDOWN(pcre),
    2183             : #ifdef PCRE_STUDY_JIT_COMPILE
    2184             :         PHP_RINIT(pcre),
    2185             : #else
    2186             :         NULL
    2187             : #endif
    2188             :         NULL,
    2189             :         PHP_MINFO(pcre),
    2190             :         PHP_PCRE_VERSION,
    2191             :         PHP_MODULE_GLOBALS(pcre),
    2192             :         PHP_GINIT(pcre),
    2193             :         PHP_GSHUTDOWN(pcre),
    2194             :         NULL,
    2195             :         STANDARD_MODULE_PROPERTIES_EX
    2196             : };
    2197             : 
    2198             : #ifdef COMPILE_DL_PCRE
    2199             : ZEND_GET_MODULE(pcre)
    2200             : #endif
    2201             : 
    2202             : /* }}} */
    2203             : 
    2204             : #endif /* HAVE_PCRE || HAVE_BUNDLED_PCRE */
    2205             : 
    2206             : /*
    2207             :  * Local variables:
    2208             :  * tab-width: 4
    2209             :  * c-basic-offset: 4
    2210             :  * End:
    2211             :  * vim600: sw=4 ts=4 fdm=marker
    2212             :  * vim<600: sw=4 ts=4
    2213             :  */

Generated by: LCOV version 1.10

Generated at Sun, 18 Sep 2016 08:20:12 +0000 (8 days ago)

Copyright © 2005-2016 The PHP Group
All rights reserved.