forked from php/php-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphp_pcre.c
2023 lines (1783 loc) · 59.7 KB
/
php_pcre.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2015 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Andrei Zmievski <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_ini.h"
#include "php_globals.h"
#include "php_pcre.h"
#include "ext/standard/info.h"
#include "ext/standard/basic_functions.h"
#include "zend_smart_str.h"
#if HAVE_PCRE || HAVE_BUNDLED_PCRE
#include "ext/standard/php_string.h"
#define PREG_PATTERN_ORDER 1
#define PREG_SET_ORDER 2
#define PREG_OFFSET_CAPTURE (1<<8)
#define PREG_SPLIT_NO_EMPTY (1<<0)
#define PREG_SPLIT_DELIM_CAPTURE (1<<1)
#define PREG_SPLIT_OFFSET_CAPTURE (1<<2)
#define PREG_REPLACE_EVAL (1<<0)
#define PREG_GREP_INVERT (1<<0)
#define PCRE_CACHE_SIZE 4096
enum {
PHP_PCRE_NO_ERROR = 0,
PHP_PCRE_INTERNAL_ERROR,
PHP_PCRE_BACKTRACK_LIMIT_ERROR,
PHP_PCRE_RECURSION_LIMIT_ERROR,
PHP_PCRE_BAD_UTF8_ERROR,
PHP_PCRE_BAD_UTF8_OFFSET_ERROR
};
ZEND_DECLARE_MODULE_GLOBALS(pcre)
static void pcre_handle_exec_error(int pcre_code) /* {{{ */
{
int preg_code = 0;
switch (pcre_code) {
case PCRE_ERROR_MATCHLIMIT:
preg_code = PHP_PCRE_BACKTRACK_LIMIT_ERROR;
break;
case PCRE_ERROR_RECURSIONLIMIT:
preg_code = PHP_PCRE_RECURSION_LIMIT_ERROR;
break;
case PCRE_ERROR_BADUTF8:
preg_code = PHP_PCRE_BAD_UTF8_ERROR;
break;
case PCRE_ERROR_BADUTF8_OFFSET:
preg_code = PHP_PCRE_BAD_UTF8_OFFSET_ERROR;
break;
default:
preg_code = PHP_PCRE_INTERNAL_ERROR;
break;
}
PCRE_G(error_code) = preg_code;
}
/* }}} */
static void php_free_pcre_cache(zval *data) /* {{{ */
{
pcre_cache_entry *pce = (pcre_cache_entry *) Z_PTR_P(data);
if (!pce) return;
pefree(pce->re, 1);
if (pce->extra) {
pcre_free_study(pce->extra);
}
#if HAVE_SETLOCALE
if ((void*)pce->tables) pefree((void*)pce->tables, 1);
if (pce->locale) {
zend_string_release(pce->locale);
}
#endif
pefree(pce, 1);
}
/* }}} */
static PHP_GINIT_FUNCTION(pcre) /* {{{ */
{
zend_hash_init(&pcre_globals->pcre_cache, 0, NULL, php_free_pcre_cache, 1);
pcre_globals->backtrack_limit = 0;
pcre_globals->recursion_limit = 0;
pcre_globals->error_code = PHP_PCRE_NO_ERROR;
}
/* }}} */
static PHP_GSHUTDOWN_FUNCTION(pcre) /* {{{ */
{
zend_hash_destroy(&pcre_globals->pcre_cache);
}
/* }}} */
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("pcre.backtrack_limit", "1000000", PHP_INI_ALL, OnUpdateLong, backtrack_limit, zend_pcre_globals, pcre_globals)
STD_PHP_INI_ENTRY("pcre.recursion_limit", "100000", PHP_INI_ALL, OnUpdateLong, recursion_limit, zend_pcre_globals, pcre_globals)
#ifdef PCRE_STUDY_JIT_COMPILE
STD_PHP_INI_ENTRY("pcre.jit", "1", PHP_INI_ALL, OnUpdateBool, jit, zend_pcre_globals, pcre_globals)
#endif
PHP_INI_END()
/* {{{ PHP_MINFO_FUNCTION(pcre) */
static PHP_MINFO_FUNCTION(pcre)
{
int jit_yes = 0;
php_info_print_table_start();
php_info_print_table_row(2, "PCRE (Perl Compatible Regular Expressions) Support", "enabled" );
php_info_print_table_row(2, "PCRE Library Version", pcre_version() );
if (!pcre_config(PCRE_CONFIG_JIT, &jit_yes)) {
php_info_print_table_row(2, "PCRE JIT Support", jit_yes ? "enabled" : "disabled");
} else {
php_info_print_table_row(2, "PCRE JIT Support", "unknown" );
}
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION(pcre) */
static PHP_MINIT_FUNCTION(pcre)
{
REGISTER_INI_ENTRIES();
REGISTER_LONG_CONSTANT("PREG_PATTERN_ORDER", PREG_PATTERN_ORDER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_SET_ORDER", PREG_SET_ORDER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_OFFSET_CAPTURE", PREG_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_SPLIT_NO_EMPTY", PREG_SPLIT_NO_EMPTY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_SPLIT_DELIM_CAPTURE", PREG_SPLIT_DELIM_CAPTURE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_SPLIT_OFFSET_CAPTURE", PREG_SPLIT_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_GREP_INVERT", PREG_GREP_INVERT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_NO_ERROR", PHP_PCRE_NO_ERROR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_INTERNAL_ERROR", PHP_PCRE_INTERNAL_ERROR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_BACKTRACK_LIMIT_ERROR", PHP_PCRE_BACKTRACK_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_RECURSION_LIMIT_ERROR", PHP_PCRE_RECURSION_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_ERROR", PHP_PCRE_BAD_UTF8_ERROR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_OFFSET_ERROR", PHP_PCRE_BAD_UTF8_OFFSET_ERROR, CONST_CS | CONST_PERSISTENT);
REGISTER_STRING_CONSTANT("PCRE_VERSION", (char *)pcre_version(), CONST_CS | CONST_PERSISTENT);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION(pcre) */
static PHP_MSHUTDOWN_FUNCTION(pcre)
{
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ static pcre_clean_cache */
static int pcre_clean_cache(zval *data, void *arg)
{
int *num_clean = (int *)arg;
if (*num_clean > 0) {
(*num_clean)--;
return 1;
} else {
return 0;
}
}
/* }}} */
/* {{{ static make_subpats_table */
static char **make_subpats_table(int num_subpats, pcre_cache_entry *pce)
{
pcre_extra *extra = pce->extra;
int name_cnt = pce->name_count, name_size, ni = 0;
int rc;
char *name_table;
unsigned short name_idx;
char **subpat_names;
int rc1, rc2;
rc1 = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMETABLE, &name_table);
rc2 = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMEENTRYSIZE, &name_size);
rc = rc2 ? rc2 : rc1;
if (rc < 0) {
php_error_docref(NULL, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
return NULL;
}
subpat_names = (char **)ecalloc(num_subpats, sizeof(char *));
while (ni++ < name_cnt) {
name_idx = 0xff * (unsigned char)name_table[0] + (unsigned char)name_table[1];
subpat_names[name_idx] = name_table + 2;
if (is_numeric_string(subpat_names[name_idx], strlen(subpat_names[name_idx]), NULL, NULL, 0) > 0) {
php_error_docref(NULL, E_WARNING, "Numeric named subpatterns are not allowed");
efree(subpat_names);
return NULL;
}
name_table += name_size;
}
return subpat_names;
}
/* }}} */
/* {{{ pcre_get_compiled_regex_cache
*/
PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache(zend_string *regex)
{
pcre *re = NULL;
pcre_extra *extra;
int coptions = 0;
int soptions = 0;
const char *error;
int erroffset;
char delimiter;
char start_delimiter;
char end_delimiter;
char *p, *pp;
char *pattern;
int do_study = 0;
int poptions = 0;
unsigned const char *tables = NULL;
pcre_cache_entry *pce;
pcre_cache_entry new_entry;
int rc;
/* Try to lookup the cached regex entry, and if successful, just pass
back the compiled pattern, otherwise go on and compile it. */
pce = zend_hash_find_ptr(&PCRE_G(pcre_cache), regex);
if (pce) {
#if HAVE_SETLOCALE
if (pce->locale == BG(locale_string) ||
(pce->locale && BG(locale_string) &&
pce->locale->len == BG(locale_string)->len &&
!memcmp(pce->locale->val, BG(locale_string)->val, pce->locale->len))) {
return pce;
}
#else
return pce;
#endif
}
p = regex->val;
/* Parse through the leading whitespace, and display a warning if we
get to the end without encountering a delimiter. */
while (isspace((int)*(unsigned char *)p)) p++;
if (*p == 0) {
php_error_docref(NULL, E_WARNING,
p < regex->val + regex->len ? "Null byte in regex" : "Empty regular expression");
return NULL;
}
/* Get the delimiter and display a warning if it is alphanumeric
or a backslash. */
delimiter = *p++;
if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') {
php_error_docref(NULL,E_WARNING, "Delimiter must not be alphanumeric or backslash");
return NULL;
}
start_delimiter = delimiter;
if ((pp = strchr("([{< )]}> )]}>", delimiter)))
delimiter = pp[5];
end_delimiter = delimiter;
pp = p;
if (start_delimiter == end_delimiter) {
/* We need to iterate through the pattern, searching for the ending delimiter,
but skipping the backslashed delimiters. If the ending delimiter is not
found, display a warning. */
while (*pp != 0) {
if (*pp == '\\' && pp[1] != 0) pp++;
else if (*pp == delimiter)
break;
pp++;
}
} else {
/* We iterate through the pattern, searching for the matching ending
* delimiter. For each matching starting delimiter, we increment nesting
* level, and decrement it for each matching ending delimiter. If we
* reach the end of the pattern without matching, display a warning.
*/
int brackets = 1; /* brackets nesting level */
while (*pp != 0) {
if (*pp == '\\' && pp[1] != 0) pp++;
else if (*pp == end_delimiter && --brackets <= 0)
break;
else if (*pp == start_delimiter)
brackets++;
pp++;
}
}
if (*pp == 0) {
if (pp < regex->val + regex->len) {
php_error_docref(NULL,E_WARNING, "Null byte in regex");
} else if (start_delimiter == end_delimiter) {
php_error_docref(NULL,E_WARNING, "No ending delimiter '%c' found", delimiter);
} else {
php_error_docref(NULL,E_WARNING, "No ending matching delimiter '%c' found", delimiter);
}
return NULL;
}
/* Make a copy of the actual pattern. */
pattern = estrndup(p, pp-p);
/* Move on to the options */
pp++;
/* Parse through the options, setting appropriate flags. Display
a warning if we encounter an unknown modifier. */
while (pp < regex->val + regex->len) {
switch (*pp++) {
/* Perl compatible options */
case 'i': coptions |= PCRE_CASELESS; break;
case 'm': coptions |= PCRE_MULTILINE; break;
case 's': coptions |= PCRE_DOTALL; break;
case 'x': coptions |= PCRE_EXTENDED; break;
/* PCRE specific options */
case 'A': coptions |= PCRE_ANCHORED; break;
case 'D': coptions |= PCRE_DOLLAR_ENDONLY;break;
case 'S': do_study = 1; break;
case 'U': coptions |= PCRE_UNGREEDY; break;
case 'X': coptions |= PCRE_EXTRA; break;
case 'u': coptions |= PCRE_UTF8;
/* In PCRE, by default, \d, \D, \s, \S, \w, and \W recognize only ASCII
characters, even in UTF-8 mode. However, this can be changed by setting
the PCRE_UCP option. */
#ifdef PCRE_UCP
coptions |= PCRE_UCP;
#endif
break;
/* Custom preg options */
case 'e': poptions |= PREG_REPLACE_EVAL; break;
case ' ':
case '\n':
break;
default:
if (pp[-1]) {
php_error_docref(NULL,E_WARNING, "Unknown modifier '%c'", pp[-1]);
} else {
php_error_docref(NULL,E_WARNING, "Null byte in regex");
}
efree(pattern);
return NULL;
}
}
#if HAVE_SETLOCALE
if (BG(locale_string) &&
(BG(locale_string)->len != 1 || BG(locale_string)->val[0] != 'C')) {
tables = pcre_maketables();
}
#endif
/* Compile pattern and display a warning if compilation failed. */
re = pcre_compile(pattern,
coptions,
&error,
&erroffset,
tables);
if (re == NULL) {
php_error_docref(NULL,E_WARNING, "Compilation failed: %s at offset %d", error, erroffset);
efree(pattern);
if (tables) {
pefree((void*)tables, 1);
}
return NULL;
}
#ifdef PCRE_STUDY_JIT_COMPILE
if (PCRE_G(jit)) {
/* Enable PCRE JIT compiler */
do_study = 1;
soptions |= PCRE_STUDY_JIT_COMPILE;
}
#endif
/* If study option was specified, study the pattern and
store the result in extra for passing to pcre_exec. */
if (do_study) {
extra = pcre_study(re, soptions, &error);
if (extra) {
extra->flags |= PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
}
if (error != NULL) {
php_error_docref(NULL, E_WARNING, "Error while studying pattern");
}
} else {
extra = NULL;
}
efree(pattern);
/*
* If we reached cache limit, clean out the items from the head of the list;
* these are supposedly the oldest ones (but not necessarily the least used
* ones).
*/
if (zend_hash_num_elements(&PCRE_G(pcre_cache)) == PCRE_CACHE_SIZE) {
int num_clean = PCRE_CACHE_SIZE / 8;
zend_hash_apply_with_argument(&PCRE_G(pcre_cache), pcre_clean_cache, &num_clean);
}
/* Store the compiled pattern and extra info in the cache. */
new_entry.re = re;
new_entry.extra = extra;
new_entry.preg_options = poptions;
new_entry.compile_options = coptions;
#if HAVE_SETLOCALE
new_entry.locale = BG(locale_string) ?
((GC_FLAGS(BG(locale_string)) & IS_STR_PERSISTENT) ?
zend_string_copy(BG(locale_string)) :
zend_string_init(BG(locale_string)->val, BG(locale_string)->len, 1)) :
NULL;
new_entry.tables = tables;
#endif
rc = pcre_fullinfo(re, extra, PCRE_INFO_CAPTURECOUNT, &new_entry.capture_count);
if (rc < 0) {
php_error_docref(NULL, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
return NULL;
}
rc = pcre_fullinfo(re, extra, PCRE_INFO_NAMECOUNT, &new_entry.name_count);
if (rc < 0) {
php_error_docref(NULL, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
return NULL;
}
/*
* Interned strings are not duplicated when stored in HashTable,
* but all the interned strings created during HTTP request are removed
* at end of request. However PCRE_G(pcre_cache) must be consistent
* on the next request as well. So we disable usage of interned strings
* as hash keys especually for this table.
* See bug #63180
*/
pce = zend_hash_str_update_mem(&PCRE_G(pcre_cache), regex->val, regex->len, &new_entry, sizeof(pcre_cache_entry));
return pce;
}
/* }}} */
/* {{{ pcre_get_compiled_regex
*/
PHPAPI pcre* pcre_get_compiled_regex(zend_string *regex, pcre_extra **extra, int *preg_options)
{
pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex);
if (extra) {
*extra = pce ? pce->extra : NULL;
}
if (preg_options) {
*preg_options = pce ? pce->preg_options : 0;
}
return pce ? pce->re : NULL;
}
/* }}} */
/* {{{ pcre_get_compiled_regex_ex
*/
PHPAPI pcre* pcre_get_compiled_regex_ex(zend_string *regex, pcre_extra **extra, int *preg_options, int *compile_options)
{
pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex);
if (extra) {
*extra = pce ? pce->extra : NULL;
}
if (preg_options) {
*preg_options = pce ? pce->preg_options : 0;
}
if (compile_options) {
*compile_options = pce ? pce->compile_options : 0;
}
return pce ? pce->re : NULL;
}
/* }}} */
/* {{{ add_offset_pair */
static inline void add_offset_pair(zval *result, char *str, int len, int offset, char *name)
{
zval match_pair, tmp;
array_init_size(&match_pair, 2);
/* Add (match, offset) to the return value */
ZVAL_STRINGL(&tmp, str, len);
zend_hash_next_index_insert_new(Z_ARRVAL(match_pair), &tmp);
ZVAL_LONG(&tmp, offset);
zend_hash_next_index_insert_new(Z_ARRVAL(match_pair), &tmp);
if (name) {
Z_ADDREF(match_pair);
zend_hash_str_update(Z_ARRVAL_P(result), name, strlen(name), &match_pair);
}
zend_hash_next_index_insert(Z_ARRVAL_P(result), &match_pair);
}
/* }}} */
static void php_do_pcre_match(INTERNAL_FUNCTION_PARAMETERS, int global) /* {{{ */
{
/* parameters */
zend_string *regex; /* Regular expression */
zend_string *subject; /* String to match against */
pcre_cache_entry *pce; /* Compiled regular expression */
zval *subpats = NULL; /* Array for subpatterns */
zend_long flags = 0; /* Match control flags */
zend_long start_offset = 0; /* Where the new search starts */
#ifndef FAST_ZPP
if (zend_parse_parameters(ZEND_NUM_ARGS(), "SS|z/ll", ®ex,
&subject, &subpats, &flags, &start_offset) == FAILURE) {
RETURN_FALSE;
}
#else
ZEND_PARSE_PARAMETERS_START(2, 5)
Z_PARAM_STR(regex)
Z_PARAM_STR(subject)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_EX(subpats, 0, 1)
Z_PARAM_LONG(flags)
Z_PARAM_LONG(start_offset)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
#endif
/* Compile regex or get it from cache. */
if ((pce = pcre_get_compiled_regex_cache(regex)) == NULL) {
RETURN_FALSE;
}
php_pcre_match_impl(pce, subject->val, (int)subject->len, return_value, subpats,
global, ZEND_NUM_ARGS() >= 4, flags, start_offset);
}
/* }}} */
/* {{{ php_pcre_match_impl() */
PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value,
zval *subpats, int global, int use_flags, zend_long flags, zend_long start_offset)
{
zval result_set, /* Holds a set of subpatterns after
a global match */
*match_sets = NULL; /* An array of sets of matches for each
subpattern after a global match */
pcre_extra *extra = pce->extra;/* Holds results of studying */
pcre_extra extra_data; /* Used locally for exec options */
int exoptions = 0; /* Execution options */
int count = 0; /* Count of matched subpatterns */
int *offsets; /* Array of subpattern offsets */
int num_subpats; /* Number of captured subpatterns */
int size_offsets; /* Size of the offsets array */
int matched; /* Has anything matched */
int g_notempty = 0; /* If the match should not be empty */
const char **stringlist; /* Holds list of subpatterns */
char **subpat_names; /* Array for named subpatterns */
int i;
int subpats_order; /* Order of subpattern matches */
int offset_capture; /* Capture match offsets: yes/no */
unsigned char *mark = NULL; /* Target for MARK name */
zval marks; /* Array of marks for PREG_PATTERN_ORDER */
ALLOCA_FLAG(use_heap);
ZVAL_UNDEF(&marks);
/* Overwrite the passed-in value for subpatterns with an empty array. */
if (subpats != NULL) {
zval_dtor(subpats);
array_init(subpats);
}
subpats_order = global ? PREG_PATTERN_ORDER : 0;
if (use_flags) {
offset_capture = flags & PREG_OFFSET_CAPTURE;
/*
* subpats_order is pre-set to pattern mode so we change it only if
* necessary.
*/
if (flags & 0xff) {
subpats_order = flags & 0xff;
}
if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) ||
(!global && subpats_order != 0)) {
php_error_docref(NULL, E_WARNING, "Invalid flags specified");
return;
}
} else {
offset_capture = 0;
}
/* Negative offset counts from the end of the string. */
if (start_offset < 0) {
start_offset = subject_len + start_offset;
if (start_offset < 0) {
start_offset = 0;
}
}
if (extra == NULL) {
extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
extra = &extra_data;
}
extra->match_limit = (unsigned long)PCRE_G(backtrack_limit);
extra->match_limit_recursion = (unsigned long)PCRE_G(recursion_limit);
#ifdef PCRE_EXTRA_MARK
extra->mark = &mark;
extra->flags |= PCRE_EXTRA_MARK;
#endif
/* Calculate the size of the offsets array, and allocate memory for it. */
num_subpats = pce->capture_count + 1;
size_offsets = num_subpats * 3;
/*
* Build a mapping from subpattern numbers to their names. We will
* allocate the table only if there are any named subpatterns.
*/
subpat_names = NULL;
if (pce->name_count > 0) {
subpat_names = make_subpats_table(num_subpats, pce);
if (!subpat_names) {
RETURN_FALSE;
}
}
if (size_offsets <= 32) {
offsets = (int *)do_alloca(size_offsets * sizeof(int), use_heap);
} else {
offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
}
memset(offsets, 0, size_offsets*sizeof(int));
/* Allocate match sets array and initialize the values. */
if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
match_sets = (zval *)safe_emalloc(num_subpats, sizeof(zval), 0);
for (i=0; i<num_subpats; i++) {
array_init(&match_sets[i]);
}
}
matched = 0;
PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
do {
/* Execute the regular expression. */
count = pcre_exec(pce->re, extra, subject, (int)subject_len, (int)start_offset,
exoptions|g_notempty, offsets, size_offsets);
/* the string was already proved to be valid UTF-8 */
exoptions |= PCRE_NO_UTF8_CHECK;
/* Check for too many substrings condition. */
if (count == 0) {
php_error_docref(NULL, E_NOTICE, "Matched, but too many substrings");
count = size_offsets/3;
}
/* If something has matched */
if (count > 0) {
matched++;
/* If subpatterns array has been passed, fill it in with values. */
if (subpats != NULL) {
/* Try to get the list of substrings and display a warning if failed. */
if (pcre_get_substring_list(subject, offsets, count, &stringlist) < 0) {
if (subpat_names) {
efree(subpat_names);
}
if (size_offsets <= 32) {
free_alloca(offsets, use_heap);
} else {
efree(offsets);
}
if (match_sets) efree(match_sets);
php_error_docref(NULL, E_WARNING, "Get subpatterns list failed");
RETURN_FALSE;
}
if (global) { /* global pattern matching */
if (subpats && subpats_order == PREG_PATTERN_ORDER) {
/* For each subpattern, insert it into the appropriate array. */
if (offset_capture) {
for (i = 0; i < count; i++) {
add_offset_pair(&match_sets[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL);
}
} else {
for (i = 0; i < count; i++) {
add_next_index_stringl(&match_sets[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
}
/* Add MARK, if available */
if (mark) {
if (Z_TYPE(marks) == IS_UNDEF) {
array_init(&marks);
}
add_index_string(&marks, matched - 1, (char *) mark);
}
/*
* If the number of captured subpatterns on this run is
* less than the total possible number, pad the result
* arrays with empty strings.
*/
if (count < num_subpats) {
for (; i < num_subpats; i++) {
add_next_index_string(&match_sets[i], "");
}
}
} else {
/* Allocate the result set array */
array_init_size(&result_set, count + (mark ? 1 : 0));
/* Add all the subpatterns to it */
if (subpat_names) {
if (offset_capture) {
for (i = 0; i < count; i++) {
add_offset_pair(&result_set, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]);
}
} else {
for (i = 0; i < count; i++) {
if (subpat_names[i]) {
add_assoc_stringl(&result_set, subpat_names[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
add_next_index_stringl(&result_set, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
}
} else {
if (offset_capture) {
for (i = 0; i < count; i++) {
add_offset_pair(&result_set, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL);
}
} else {
for (i = 0; i < count; i++) {
add_next_index_stringl(&result_set, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
}
}
/* Add MARK, if available */
if (mark) {
add_assoc_string_ex(&result_set, "MARK", sizeof("MARK") - 1, (char *)mark);
}
/* And add it to the output array */
zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set);
}
} else { /* single pattern matching */
/* For each subpattern, insert it into the subpatterns array. */
if (subpat_names) {
if (offset_capture) {
for (i = 0; i < count; i++) {
add_offset_pair(subpats, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1],
offsets[i<<1], subpat_names[i]);
}
} else {
for (i = 0; i < count; i++) {
if (subpat_names[i]) {
add_assoc_stringl(subpats, subpat_names[i], (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
add_next_index_stringl(subpats, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
}
} else {
if (offset_capture) {
for (i = 0; i < count; i++) {
add_offset_pair(subpats, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1],
offsets[i<<1], NULL);
}
} else {
for (i = 0; i < count; i++) {
add_next_index_stringl(subpats, (char *)stringlist[i],
offsets[(i<<1)+1] - offsets[i<<1]);
}
}
}
/* Add MARK, if available */
if (mark) {
add_assoc_string_ex(subpats, "MARK", sizeof("MARK") - 1, (char *)mark);
}
}
pcre_free((void *) stringlist);
}
} else if (count == PCRE_ERROR_NOMATCH) {
/* If we previously set PCRE_NOTEMPTY after a null match,
this is not necessarily the end. We need to advance
the start offset, and continue. Fudge the offset values
to achieve this, unless we're already at the end of the string. */
if (g_notempty != 0 && start_offset < subject_len) {
offsets[0] = (int)start_offset;
offsets[1] = (int)(start_offset + 1);
} else
break;
} else {
pcre_handle_exec_error(count);
break;
}
/* If we have matched an empty string, mimic what Perl's /g options does.
This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try
the match again at the same point. If this fails (picked up above) we
advance to the next character. */
g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0;
/* Advance to the position right after the last full match */
start_offset = offsets[1];
} while (global);
/* Add the match sets to the output array and clean up */
if (global && subpats && subpats_order == PREG_PATTERN_ORDER) {
if (subpat_names) {
for (i = 0; i < num_subpats; i++) {
if (subpat_names[i]) {
zend_hash_str_update(Z_ARRVAL_P(subpats), subpat_names[i],
strlen(subpat_names[i]), &match_sets[i]);
Z_ADDREF(match_sets[i]);
}
zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i]);
}
} else {
for (i = 0; i < num_subpats; i++) {
zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i]);
}
}
efree(match_sets);
if (Z_TYPE(marks) != IS_UNDEF) {
add_assoc_zval(subpats, "MARK", &marks);
}
}
if (size_offsets <= 32) {
free_alloca(offsets, use_heap);
} else {
efree(offsets);
}
if (subpat_names) {
efree(subpat_names);
}
/* Did we encounter an error? */
if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) {
RETVAL_LONG(matched);
} else {
RETVAL_FALSE;
}
}
/* }}} */
/* {{{ proto int preg_match(string pattern, string subject [, array &subpatterns [, int flags [, int offset]]])
Perform a Perl-style regular expression match */
static PHP_FUNCTION(preg_match)
{
php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto int preg_match_all(string pattern, string subject [, array &subpatterns [, int flags [, int offset]]])
Perform a Perl-style global regular expression match */
static PHP_FUNCTION(preg_match_all)
{
php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ preg_get_backref
*/
static int preg_get_backref(char **str, int *backref)
{
register char in_brace = 0;
register char *walk = *str;
if (walk[1] == 0)
return 0;
if (*walk == '$' && walk[1] == '{') {
in_brace = 1;
walk++;
}
walk++;
if (*walk >= '0' && *walk <= '9') {
*backref = *walk - '0';
walk++;
} else
return 0;
if (*walk && *walk >= '0' && *walk <= '9') {
*backref = *backref * 10 + *walk - '0';
walk++;
}
if (in_brace) {
if (*walk == 0 || *walk != '}')
return 0;
else
walk++;
}
*str = walk;
return 1;
}
/* }}} */
/* {{{ preg_do_repl_func
*/
static zend_string *preg_do_repl_func(zval *function, char *subject, int *offsets, char **subpat_names, int count, unsigned char *mark)
{
zend_string *result_str;
zval retval; /* Function return value */
zval args[1]; /* Argument to pass to function */
int i;
array_init_size(&args[0], count + (mark ? 1 : 0));
if (subpat_names) {
for (i = 0; i < count; i++) {
if (subpat_names[i]) {
add_assoc_stringl(&args[0], subpat_names[i], &subject[offsets[i<<1]] , offsets[(i<<1)+1] - offsets[i<<1]);
}
add_next_index_stringl(&args[0], &subject[offsets[i<<1]], offsets[(i<<1)+1] - offsets[i<<1]);
}
} else {
for (i = 0; i < count; i++) {
add_next_index_stringl(&args[0], &subject[offsets[i<<1]], offsets[(i<<1)+1] - offsets[i<<1]);
}
}
if (mark) {
add_assoc_string(&args[0], "MARK", (char *) mark);
}
if (call_user_function_ex(EG(function_table), NULL, function, &retval, 1, args, 0, NULL) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
result_str = zval_get_string(&retval);
zval_ptr_dtor(&retval);
} else {
if (!EG(exception)) {
php_error_docref(NULL, E_WARNING, "Unable to call custom replacement function");
}
result_str = zend_string_init(&subject[offsets[0]], offsets[1] - offsets[0], 0);
}
zval_ptr_dtor(&args[0]);
return result_str;
}
/* }}} */
/* {{{ php_pcre_replace
*/
PHPAPI zend_string *php_pcre_replace(zend_string *regex,