33 *
44 * POSIX: direct wrappers around <regex.h>.
55 * Windows: vendored TRE regex library (BSD-licensed).
6+ *
7+ * Both backends expand bounded repetition at compile time, so cbm_regcomp
8+ * sizes a pattern first (the compile-size guard below) and refuses one whose
9+ * compiled form would be too large, before the platform compiler allocates
10+ * anything.
611 */
712#include "foundation/constants.h"
813#include "foundation/compat_regex.h"
914
15+ #include <stdbool.h>
16+ #include <stdint.h>
1017#include <string.h>
1118
19+ /* ── Compile-size guard (shared by both backends) ─────────────────
20+ *
21+ * The platform compilers expand `X{m,n}` into n copies of X, so nested
22+ * intervals multiply: `((((a){20}){20}){20}){20}` is 160,000 expanded atoms
23+ * from 25 bytes of pattern. A K-way alternation additionally costs about K^2
24+ * position-set entries on the TRE-derived backends (macOS libc and the vendored
25+ * TRE), because every union node copies its branches' sets.
26+ *
27+ * Measured on macOS libc with REG_EXTENDED|REG_NOSUB: the nested shape costs
28+ * about 0.6 KB of heap per expanded atom, 1.1 KB with submatch tracking on,
29+ * 1.7 KB with REG_ICASE and 2.3 KB with both; a K-way alternation adds about
30+ * 70 B x K^2 on top of its branches (twice that under REG_ICASE), and an
31+ * alternation under an interval pays that for every copy, about 1 KB per unit
32+ * with REG_NOSUB and 2.8 KB with REG_ICASE plus submatches. glibc costs about
33+ * 0.45 KB per atom and expands intervals the same way.
34+ *
35+ * cbm_regcomp_estimate_units() counts expanded atoms in one linear pass with
36+ * saturating arithmetic and charges a K-way alternation K^2/8 units, the
37+ * measured ratio between the two costs. With CBM_REGEX_COMPILE_BUDGET_UNITS =
38+ * 32768 the heaviest accepted compile is a repeated alternation at about 30 MB
39+ * with REG_NOSUB and about 90 MB under the ICASE-plus-submatch flag set no
40+ * call site uses; the nested shape tops out at 13^4 = 28,561 units, about
41+ * 16 MB. `(\w{1,100}){1,20}` (2,000 units) and an alternation of 500 short
42+ * names (31,250 units plus its letters) remain accepted. */
43+
44+ enum { REGEX_GROUP_DEPTH_MAX = 64 };
45+
46+ typedef struct {
47+ uint64_t total ; /* units of this group so far; includes `last` */
48+ uint64_t last ; /* units of the element a following quantifier applies to */
49+ uint64_t branches ; /* alternatives in this group: 1 + the number of '|' */
50+ } regex_frame_t ;
51+
52+ static uint64_t regex_sat_add (uint64_t a , uint64_t b ) {
53+ return a > UINT64_MAX - b ? UINT64_MAX : a + b ;
54+ }
55+
56+ static uint64_t regex_sat_mul (uint64_t a , uint64_t b ) {
57+ if (a == 0 || b == 0 ) {
58+ return 0 ;
59+ }
60+ return a > UINT64_MAX / b ? UINT64_MAX : a * b ;
61+ }
62+
63+ static void regex_frame_atom (regex_frame_t * f , uint64_t units ) {
64+ f -> total = regex_sat_add (f -> total , units );
65+ f -> last = units ;
66+ }
67+
68+ /* An interval applies to the last element: n copies of it replace the one. */
69+ static void regex_frame_repeat_last (regex_frame_t * f , uint64_t copies ) {
70+ uint64_t grown = regex_sat_mul (f -> last , copies );
71+ f -> total = regex_sat_add (f -> total - f -> last , grown );
72+ f -> last = grown ;
73+ }
74+
75+ /* Units a closed group contributes to its parent: its content plus the K^2/8
76+ * alternation share, never less than one atom. */
77+ static uint64_t regex_frame_units (const regex_frame_t * f ) {
78+ uint64_t alternation = regex_sat_mul (f -> branches , f -> branches ) / 8 ;
79+ uint64_t units = regex_sat_add (f -> total , alternation );
80+ return units ? units : 1 ;
81+ }
82+
83+ /* Skip the bracket expression opening at p[i] == '['. Returns the index just
84+ * past its closing ']', or the end of the string when it is unterminated.
85+ * Nothing inside is an operator: `[]a]`, `[^]a]` and `[[:alpha:]]` are each
86+ * one atom, and a brace inside brackets never opens an interval. */
87+ static size_t regex_skip_bracket (const char * p , size_t i ) {
88+ size_t j = i + 1 ;
89+ if (p [j ] == '^' ) {
90+ j ++ ;
91+ }
92+ if (p [j ] == ']' ) {
93+ j ++ ;
94+ }
95+ while (p [j ] && p [j ] != ']' ) {
96+ if (p [j ] == '[' && (p [j + 1 ] == ':' || p [j + 1 ] == '=' || p [j + 1 ] == '.' )) {
97+ char close = p [j + 1 ];
98+ size_t k = j + 2 ;
99+ while (p [k ] && !(p [k ] == close && p [k + 1 ] == ']' )) {
100+ k ++ ;
101+ }
102+ j = p [k ] ? k + 2 : k ;
103+ } else {
104+ j ++ ;
105+ }
106+ }
107+ return p [j ] ? j + 1 : j ;
108+ }
109+
110+ static bool regex_parse_digits (const char * p , size_t * i , uint64_t * value ) {
111+ bool any = false;
112+ * value = 0 ;
113+ while (p [* i ] >= '0' && p [* i ] <= '9' ) {
114+ * value = regex_sat_add (regex_sat_mul (* value , 10 ), (uint64_t )(p [* i ] - '0' ));
115+ (* i )++ ;
116+ any = true;
117+ }
118+ return any ;
119+ }
120+
121+ /* Parse the interval body that starts at p[i], just past the opening brace
122+ * (`{` in extended syntax, `\{` in basic). On success stores the number of
123+ * copies the compiler will make (the upper bound, or the lower bound for
124+ * `{m,}`, at least 1) and the index just past the closing brace. Anything that
125+ * is not an interval leaves the brace to be counted as a literal, which is what
126+ * the backends that accept it do; the others reject the pattern. */
127+ static bool regex_parse_interval (const char * p , size_t i , bool extended , uint64_t * copies ,
128+ size_t * end ) {
129+ uint64_t lower = 0 ;
130+ uint64_t upper = 0 ;
131+ bool has_lower = regex_parse_digits (p , & i , & lower );
132+ bool has_upper = false;
133+ if (p [i ] == ',' ) {
134+ i ++ ;
135+ has_upper = regex_parse_digits (p , & i , & upper );
136+ } else {
137+ if (!has_lower ) {
138+ return false;
139+ }
140+ upper = lower ;
141+ has_upper = true;
142+ }
143+ if (extended ) {
144+ if (p [i ] != '}' ) {
145+ return false;
146+ }
147+ i ++ ;
148+ } else {
149+ if (p [i ] != '\\' || p [i + 1 ] != '}' ) {
150+ return false;
151+ }
152+ i += 2 ;
153+ }
154+ uint64_t n = has_upper ? upper : lower ;
155+ if (has_upper && lower > upper ) {
156+ n = lower ; /* `{5,3}` is rejected by the backends; count the larger bound */
157+ }
158+ * copies = n ? n : 1 ;
159+ * end = i ;
160+ return true;
161+ }
162+
163+ uint64_t cbm_regcomp_estimate_units (const char * pattern , int flags ) {
164+ const bool extended = (flags & CBM_REG_EXTENDED ) != 0 ;
165+ regex_frame_t frames [REGEX_GROUP_DEPTH_MAX ];
166+ int depth = 0 ;
167+ frames [0 ] = (regex_frame_t ){0 , 0 , 1 };
168+
169+ size_t i = 0 ;
170+ while (pattern [i ]) {
171+ char c = pattern [i ];
172+ if (c == '[' ) {
173+ i = regex_skip_bracket (pattern , i );
174+ regex_frame_atom (& frames [depth ], 1 );
175+ continue ;
176+ }
177+ /* In extended syntax the bare characters operate and `\x` is one
178+ * literal; in basic syntax only `\(`, `\)`, `\{`, `\|`, `\+`, `\?` and
179+ * a bare `*` operate. */
180+ char op = 0 ;
181+ size_t len = 1 ;
182+ if (c == '\\' ) {
183+ len = pattern [i + 1 ] ? 2 : 1 ;
184+ if (!extended && len == 2 && strchr ("(){|+?" , pattern [i + 1 ])) {
185+ op = pattern [i + 1 ];
186+ }
187+ } else if (extended ? strchr ("(){|*+?" , c ) != NULL : c == '*' ) {
188+ op = c ;
189+ }
190+ regex_frame_t * f = & frames [depth ];
191+ switch (op ) {
192+ case '(' :
193+ if (depth + 1 >= REGEX_GROUP_DEPTH_MAX ) {
194+ return UINT64_MAX ;
195+ }
196+ frames [++ depth ] = (regex_frame_t ){0 , 0 , 1 };
197+ break ;
198+ case ')' :
199+ if (depth == 0 ) {
200+ regex_frame_atom (f , 1 ); /* unmatched: a literal where accepted */
201+ break ;
202+ }
203+ depth -- ;
204+ regex_frame_atom (& frames [depth ], regex_frame_units (f ));
205+ break ;
206+ case '|' :
207+ f -> branches = regex_sat_add (f -> branches , 1 );
208+ f -> last = 0 ;
209+ break ;
210+ case '{' : {
211+ uint64_t copies = 0 ;
212+ size_t end = 0 ;
213+ if (regex_parse_interval (pattern , i + len , extended , & copies , & end )) {
214+ regex_frame_repeat_last (f , copies );
215+ i = end ;
216+ continue ;
217+ }
218+ regex_frame_atom (f , 1 );
219+ break ;
220+ }
221+ case '*' :
222+ case '+' :
223+ case '?' :
224+ break ; /* unbounded or optional repetition is not expanded */
225+ default :
226+ regex_frame_atom (f , 1 );
227+ break ;
228+ }
229+ i += len ;
230+ }
231+ while (depth > 0 ) {
232+ regex_frame_t * f = & frames [depth ];
233+ depth -- ;
234+ regex_frame_atom (& frames [depth ], regex_frame_units (f ));
235+ }
236+ return regex_frame_units (& frames [0 ]);
237+ }
238+
239+ /* Refuse a pattern before the platform compiler sees it. */
240+ static int regex_compile_guard (const char * pattern , int flags ) {
241+ size_t len = 0 ;
242+ while (len <= (size_t )CBM_REGEX_PATTERN_MAX_BYTES && pattern [len ]) {
243+ len ++ ;
244+ }
245+ if (len > (size_t )CBM_REGEX_PATTERN_MAX_BYTES ) {
246+ return CBM_REG_ETOOBIG ;
247+ }
248+ if (cbm_regcomp_estimate_units (pattern , flags ) > (uint64_t )CBM_REGEX_COMPILE_BUDGET_UNITS ) {
249+ return CBM_REG_ETOOBIG ;
250+ }
251+ return CBM_REG_OK ;
252+ }
253+
12254#ifdef _WIN32
13255
14256/* ── Windows: use vendored TRE regex ─────────────────────────── */
@@ -31,6 +273,10 @@ static int translate_flags_tre(int flags) {
31273}
32274
33275int cbm_regcomp (cbm_regex_t * r , const char * pattern , int flags ) {
276+ int refused = regex_compile_guard (pattern , flags );
277+ if (refused != CBM_REG_OK ) {
278+ return refused ;
279+ }
34280 regex_t * re = (regex_t * )r -> opaque ;
35281 int rc = tre_regcomp (re , pattern , translate_flags_tre (flags ));
36282 return rc == 0 ? CBM_REG_OK : rc ;
@@ -88,6 +334,10 @@ static int translate_flags(int flags) {
88334}
89335
90336int cbm_regcomp (cbm_regex_t * r , const char * pattern , int flags ) {
337+ int refused = regex_compile_guard (pattern , flags );
338+ if (refused != CBM_REG_OK ) {
339+ return refused ;
340+ }
91341 regex_t * re = (regex_t * )r -> opaque ;
92342 int rc = regcomp (re , pattern , translate_flags (flags ));
93343 return rc == 0 ? CBM_REG_OK : rc ;
0 commit comments