sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / misc / regexp.c
| 1 | /* |
| 2 | ** 2012-11-13 |
| 3 | ** |
| 4 | ** The author disclaims copyright to this source code. In place of |
| 5 | ** a legal notice, here is a blessing: |
| 6 | ** |
| 7 | ** May you do good and not evil. |
| 8 | ** May you find forgiveness for yourself and forgive others. |
| 9 | ** May you share freely, never taking more than you give. |
| 10 | ** |
| 11 | ****************************************************************************** |
| 12 | ** |
| 13 | ** The code in this file implements a compact but reasonably |
| 14 | ** efficient regular-expression matcher for posix extended regular |
| 15 | ** expressions against UTF8 text. |
| 16 | ** |
| 17 | ** This file is an SQLite extension. It registers a single function |
| 18 | ** named "regexp(A,B)" where A is the regular expression and B is the |
| 19 | ** string to be matched. By registering this function, SQLite will also |
| 20 | ** then implement the "B regexp A" operator. Note that with the function |
| 21 | ** the regular expression comes first, but with the operator it comes |
| 22 | ** second. |
| 23 | ** |
| 24 | ** The following regular expression syntax is supported: |
| 25 | ** |
| 26 | ** X* zero or more occurrences of X |
| 27 | ** X+ one or more occurrences of X |
| 28 | ** X? zero or one occurrences of X |
| 29 | ** X{p,q} between p and q occurrences of X |
| 30 | ** (X) match X |
| 31 | ** X|Y X or Y |
| 32 | ** ^X X occurring at the beginning of the string |
| 33 | ** X$ X occurring at the end of the string |
| 34 | ** . Match any single character |
| 35 | ** \c Character c where c is one of \{}()[]|*+?-. |
| 36 | ** \c C-language escapes for c in afnrtv. ex: \t or \n |
| 37 | ** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX |
| 38 | ** \xXX Where XX is exactly 2 hex digits, unicode value XX |
| 39 | ** [abc] Any single character from the set abc |
| 40 | ** [^abc] Any single character not in the set abc |
| 41 | ** [a-z] Any single character in the range a-z |
| 42 | ** [^a-z] Any single character not in the range a-z |
| 43 | ** \b Word boundary |
| 44 | ** \w Word character. [A-Za-z0-9_] |
| 45 | ** \W Non-word character |
| 46 | ** \d Digit |
| 47 | ** \D Non-digit |
| 48 | ** \s Whitespace character |
| 49 | ** \S Non-whitespace character |
| 50 | ** |
| 51 | ** A nondeterministic finite automaton (NFA) is used for matching, so the |
| 52 | ** performance is bounded by O(N*M) where N is the size of the regular |
| 53 | ** expression and M is the size of the input string. The matcher never |
| 54 | ** exhibits exponential behavior. Note that the X{p,q} operator expands |
| 55 | ** to p copies of X following by q-p copies of X? and that the size of the |
| 56 | ** regular expression in the O(N*M) performance bound is computed after |
| 57 | ** this expansion. |
| 58 | ** |
| 59 | ** To help prevent DoS attacks, the maximum size of the NFA is restricted. |
| 60 | */ |
| 61 | #include <string.h> |
| 62 | #include <stdlib.h> |
| 63 | #include "sqlite3ext.h" |
| 64 | SQLITE_EXTENSION_INIT1 |
| 65 | |
| 66 | /* |
| 67 | ** The following #defines change the names of some functions implemented in |
| 68 | ** this file to prevent name collisions with C-library functions of the |
| 69 | ** same name. |
| 70 | */ |
| 71 | #define re_match sqlite3re_match |
| 72 | #define re_compile sqlite3re_compile |
| 73 | #define re_free sqlite3re_free |
| 74 | |
| 75 | /* The end-of-input character */ |
| 76 | #define RE_EOF 0 /* End of input */ |
| 77 | #define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */ |
| 78 | |
| 79 | /* The NFA is implemented as sequence of opcodes taken from the following |
| 80 | ** set. Each opcode has a single integer argument. |
| 81 | */ |
| 82 | #define RE_OP_MATCH 1 /* Match the one character in the argument */ |
| 83 | #define RE_OP_ANY 2 /* Match any one character. (Implements ".") */ |
| 84 | #define RE_OP_ANYSTAR 3 /* Special optimized version of .* */ |
| 85 | #define RE_OP_FORK 4 /* Continue to both next and opcode at iArg */ |
| 86 | #define RE_OP_GOTO 5 /* Jump to opcode at iArg */ |
| 87 | #define RE_OP_ACCEPT 6 /* Halt and indicate a successful match */ |
| 88 | #define RE_OP_CC_INC 7 /* Beginning of a [...] character class */ |
| 89 | #define RE_OP_CC_EXC 8 /* Beginning of a [^...] character class */ |
| 90 | #define RE_OP_CC_VALUE 9 /* Single value in a character class */ |
| 91 | #define RE_OP_CC_RANGE 10 /* Range of values in a character class */ |
| 92 | #define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */ |
| 93 | #define RE_OP_NOTWORD 12 /* Not a perl word character */ |
| 94 | #define RE_OP_DIGIT 13 /* digit: [0-9] */ |
| 95 | #define RE_OP_NOTDIGIT 14 /* Not a digit */ |
| 96 | #define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */ |
| 97 | #define RE_OP_NOTSPACE 16 /* Not a digit */ |
| 98 | #define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */ |
| 99 | #define RE_OP_ATSTART 18 /* Currently at the start of the string */ |
| 100 | |
| 101 | /* Each opcode is a "state" in the NFA */ |
| 102 | typedef unsigned short ReStateNumber; |
| 103 | |
| 104 | /* Because this is an NFA and not a DFA, multiple states can be active at |
| 105 | ** once. An instance of the following object records all active states in |
| 106 | ** the NFA. The implementation is optimized for the common case where the |
| 107 | ** number of actives states is small. |
| 108 | */ |
| 109 | typedef struct ReStateSet { |
| 110 | unsigned nState; /* Number of current states */ |
| 111 | ReStateNumber *aState; /* Current states */ |
| 112 | } ReStateSet; |
| 113 | |
| 114 | /* An input string read one character at a time. |
| 115 | */ |
| 116 | typedef struct ReInput ReInput; |
| 117 | struct ReInput { |
| 118 | const unsigned char *z; /* All text */ |
| 119 | int i; /* Next byte to read */ |
| 120 | int mx; /* EOF when i>=mx */ |
| 121 | }; |
| 122 | |
| 123 | /* A compiled NFA (or an NFA that is in the process of being compiled) is |
| 124 | ** an instance of the following object. |
| 125 | */ |
| 126 | typedef struct ReCompiled ReCompiled; |
| 127 | struct ReCompiled { |
| 128 | ReInput sIn; /* Regular expression text */ |
| 129 | const char *zErr; /* Error message to return */ |
| 130 | char *aOp; /* Operators for the virtual machine */ |
| 131 | int *aArg; /* Arguments to each operator */ |
| 132 | unsigned (*xNextChar)(ReInput*); /* Next character function */ |
| 133 | unsigned char zInit[12]; /* Initial text to match */ |
| 134 | int nInit; /* Number of bytes in zInit */ |
| 135 | unsigned nState; /* Number of entries in aOp[] and aArg[] */ |
| 136 | unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */ |
| 137 | unsigned mxAlloc; /* Complexity limit */ |
| 138 | }; |
| 139 | |
| 140 | /* Add a state to the given state set if it is not already there */ |
| 141 | static void re_add_state(ReStateSet *pSet, int newState){ |
| 142 | unsigned i; |
| 143 | for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return; |
| 144 | pSet->aState[pSet->nState++] = (ReStateNumber)newState; |
| 145 | } |
| 146 | |
| 147 | /* Extract the next unicode character from *pzIn and return it. Advance |
| 148 | ** *pzIn to the first byte past the end of the character returned. To |
| 149 | ** be clear: this routine converts utf8 to unicode. This routine is |
| 150 | ** optimized for the common case where the next character is a single byte. |
| 151 | */ |
| 152 | static unsigned re_next_char(ReInput *p){ |
| 153 | unsigned c; |
| 154 | if( p->i>=p->mx ) return 0; |
| 155 | c = p->z[p->i++]; |
| 156 | if( c>=0x80 ){ |
| 157 | if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){ |
| 158 | c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); |
| 159 | if( c<0x80 ) c = 0xfffd; |
| 160 | }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80 |
| 161 | && (p->z[p->i+1]&0xc0)==0x80 ){ |
| 162 | c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); |
| 163 | p->i += 2; |
| 164 | if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd; |
| 165 | }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80 |
| 166 | && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ |
| 167 | c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) |
| 168 | | (p->z[p->i+2]&0x3f); |
| 169 | p->i += 3; |
| 170 | if( c<=0xffff || c>0x10ffff ) c = 0xfffd; |
| 171 | }else{ |
| 172 | c = 0xfffd; |
| 173 | } |
| 174 | } |
| 175 | return c; |
| 176 | } |
| 177 | static unsigned re_next_char_nocase(ReInput *p){ |
| 178 | unsigned c = re_next_char(p); |
| 179 | if( c>='A' && c<='Z' ) c += 'a' - 'A'; |
| 180 | return c; |
| 181 | } |
| 182 | |
| 183 | /* Return true if c is a perl "word" character: [A-Za-z0-9_] */ |
| 184 | static int re_word_char(int c){ |
| 185 | return (c>='0' && c<='9') || (c>='a' && c<='z') |
| 186 | || (c>='A' && c<='Z') || c=='_'; |
| 187 | } |
| 188 | |
| 189 | /* Return true if c is a "digit" character: [0-9] */ |
| 190 | static int re_digit_char(int c){ |
| 191 | return (c>='0' && c<='9'); |
| 192 | } |
| 193 | |
| 194 | /* Return true if c is a perl "space" character: [ \t\r\n\v\f] */ |
| 195 | static int re_space_char(int c){ |
| 196 | return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; |
| 197 | } |
| 198 | |
| 199 | /* Run a compiled regular expression on the zero-terminated input |
| 200 | ** string zIn[]. Return true on a match and false if there is no match. |
| 201 | */ |
| 202 | static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){ |
| 203 | ReStateSet aStateSet[2], *pThis, *pNext; |
| 204 | ReStateNumber aSpace[100]; |
| 205 | ReStateNumber *pToFree; |
| 206 | unsigned int i = 0; |
| 207 | unsigned int iSwap = 0; |
| 208 | int c = RE_START; |
| 209 | int cPrev = 0; |
| 210 | int rc = 0; |
| 211 | ReInput in; |
| 212 | |
| 213 | in.z = zIn; |
| 214 | in.i = 0; |
| 215 | in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn); |
| 216 | |
| 217 | /* Look for the initial prefix match, if there is one. */ |
| 218 | if( pRe->nInit ){ |
| 219 | unsigned char x = pRe->zInit[0]; |
| 220 | while( in.i+pRe->nInit<=in.mx |
| 221 | && (zIn[in.i]!=x || |
| 222 | strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) |
| 223 | ){ |
| 224 | in.i++; |
| 225 | } |
| 226 | if( in.i+pRe->nInit>in.mx ) return 0; |
| 227 | c = RE_START-1; |
| 228 | } |
| 229 | |
| 230 | if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ |
| 231 | pToFree = 0; |
| 232 | aStateSet[0].aState = aSpace; |
| 233 | }else{ |
| 234 | pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState ); |
| 235 | if( pToFree==0 ) return -1; |
| 236 | aStateSet[0].aState = pToFree; |
| 237 | } |
| 238 | aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; |
| 239 | pNext = &aStateSet[1]; |
| 240 | pNext->nState = 0; |
| 241 | re_add_state(pNext, 0); |
| 242 | while( c!=RE_EOF && pNext->nState>0 ){ |
| 243 | cPrev = c; |
| 244 | c = pRe->xNextChar(&in); |
| 245 | pThis = pNext; |
| 246 | pNext = &aStateSet[iSwap]; |
| 247 | iSwap = 1 - iSwap; |
| 248 | pNext->nState = 0; |
| 249 | for(i=0; i<pThis->nState; i++){ |
| 250 | int x = pThis->aState[i]; |
| 251 | switch( pRe->aOp[x] ){ |
| 252 | case RE_OP_MATCH: { |
| 253 | if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); |
| 254 | break; |
| 255 | } |
| 256 | case RE_OP_ATSTART: { |
| 257 | if( cPrev==RE_START ) re_add_state(pThis, x+1); |
| 258 | break; |
| 259 | } |
| 260 | case RE_OP_ANY: { |
| 261 | if( c!=0 ) re_add_state(pNext, x+1); |
| 262 | break; |
| 263 | } |
| 264 | case RE_OP_WORD: { |
| 265 | if( re_word_char(c) ) re_add_state(pNext, x+1); |
| 266 | break; |
| 267 | } |
| 268 | case RE_OP_NOTWORD: { |
| 269 | if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1); |
| 270 | break; |
| 271 | } |
| 272 | case RE_OP_DIGIT: { |
| 273 | if( re_digit_char(c) ) re_add_state(pNext, x+1); |
| 274 | break; |
| 275 | } |
| 276 | case RE_OP_NOTDIGIT: { |
| 277 | if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1); |
| 278 | break; |
| 279 | } |
| 280 | case RE_OP_SPACE: { |
| 281 | if( re_space_char(c) ) re_add_state(pNext, x+1); |
| 282 | break; |
| 283 | } |
| 284 | case RE_OP_NOTSPACE: { |
| 285 | if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1); |
| 286 | break; |
| 287 | } |
| 288 | case RE_OP_BOUNDARY: { |
| 289 | if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1); |
| 290 | break; |
| 291 | } |
| 292 | case RE_OP_ANYSTAR: { |
| 293 | re_add_state(pNext, x); |
| 294 | re_add_state(pThis, x+1); |
| 295 | break; |
| 296 | } |
| 297 | case RE_OP_FORK: { |
| 298 | re_add_state(pThis, x+pRe->aArg[x]); |
| 299 | re_add_state(pThis, x+1); |
| 300 | break; |
| 301 | } |
| 302 | case RE_OP_GOTO: { |
| 303 | re_add_state(pThis, x+pRe->aArg[x]); |
| 304 | break; |
| 305 | } |
| 306 | case RE_OP_ACCEPT: { |
| 307 | rc = 1; |
| 308 | goto re_match_end; |
| 309 | } |
| 310 | case RE_OP_CC_EXC: { |
| 311 | if( c==0 ) break; |
| 312 | /* fall-through */ goto re_op_cc_inc; |
| 313 | } |
| 314 | case RE_OP_CC_INC: re_op_cc_inc: { |
| 315 | int j = 1; |
| 316 | int n = pRe->aArg[x]; |
| 317 | int hit = 0; |
| 318 | for(j=1; j>0 && j<n; j++){ |
| 319 | if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){ |
| 320 | if( pRe->aArg[x+j]==c ){ |
| 321 | hit = 1; |
| 322 | j = -1; |
| 323 | } |
| 324 | }else{ |
| 325 | if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ |
| 326 | hit = 1; |
| 327 | j = -1; |
| 328 | }else{ |
| 329 | j++; |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; |
| 334 | if( hit ) re_add_state(pNext, x+n); |
| 335 | break; |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | for(i=0; i<pNext->nState; i++){ |
| 341 | int x = pNext->aState[i]; |
| 342 | while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x]; |
| 343 | if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; } |
| 344 | } |
| 345 | re_match_end: |
| 346 | sqlite3_free(pToFree); |
| 347 | return rc; |
| 348 | } |
| 349 | |
| 350 | /* Resize the opcode and argument arrays for an RE under construction. |
| 351 | */ |
| 352 | static int re_resize(ReCompiled *p, unsigned int N){ |
| 353 | char *aOp; |
| 354 | int *aArg; |
| 355 | if( N>p->mxAlloc ){ p->zErr = "REGEXP pattern too big"; return 1; } |
| 356 | aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0])); |
| 357 | if( aOp==0 ){ p->zErr = "out of memory"; return 1; } |
| 358 | p->aOp = aOp; |
| 359 | aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0])); |
| 360 | if( aArg==0 ){ p->zErr = "out of memory"; return 1; } |
| 361 | p->aArg = aArg; |
| 362 | p->nAlloc = N; |
| 363 | return 0; |
| 364 | } |
| 365 | |
| 366 | /* Insert a new opcode and argument into an RE under construction. The |
| 367 | ** insertion point is just prior to existing opcode iBefore. |
| 368 | */ |
| 369 | static int re_insert(ReCompiled *p, int iBefore, int op, int arg){ |
| 370 | int i; |
| 371 | if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; |
| 372 | for(i=p->nState; i>iBefore; i--){ |
| 373 | p->aOp[i] = p->aOp[i-1]; |
| 374 | p->aArg[i] = p->aArg[i-1]; |
| 375 | } |
| 376 | p->nState++; |
| 377 | p->aOp[iBefore] = (char)op; |
| 378 | p->aArg[iBefore] = arg; |
| 379 | return iBefore; |
| 380 | } |
| 381 | |
| 382 | /* Append a new opcode and argument to the end of the RE under construction. |
| 383 | */ |
| 384 | static int re_append(ReCompiled *p, int op, int arg){ |
| 385 | return re_insert(p, p->nState, op, arg); |
| 386 | } |
| 387 | |
| 388 | /* Make a copy of N opcodes starting at iStart onto the end of the RE |
| 389 | ** under construction. |
| 390 | */ |
| 391 | static void re_copy(ReCompiled *p, int iStart, unsigned int N){ |
| 392 | if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; |
| 393 | memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); |
| 394 | memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); |
| 395 | p->nState += N; |
| 396 | } |
| 397 | |
| 398 | /* Return true if c is a hexadecimal digit character: [0-9a-fA-F] |
| 399 | ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c). If |
| 400 | ** c is not a hex digit *pV is unchanged. |
| 401 | */ |
| 402 | static int re_hex(int c, int *pV){ |
| 403 | if( c>='0' && c<='9' ){ |
| 404 | c -= '0'; |
| 405 | }else if( c>='a' && c<='f' ){ |
| 406 | c -= 'a' - 10; |
| 407 | }else if( c>='A' && c<='F' ){ |
| 408 | c -= 'A' - 10; |
| 409 | }else{ |
| 410 | return 0; |
| 411 | } |
| 412 | *pV = (*pV)*16 + (c & 0xff); |
| 413 | return 1; |
| 414 | } |
| 415 | |
| 416 | /* A backslash character has been seen, read the next character and |
| 417 | ** return its interpretation. |
| 418 | */ |
| 419 | static unsigned re_esc_char(ReCompiled *p){ |
| 420 | static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]-"; |
| 421 | static const char zTrans[] = "\a\f\n\r\t\v"; |
| 422 | int i, v = 0; |
| 423 | char c; |
| 424 | if( p->sIn.i>=p->sIn.mx ){ |
| 425 | p->zErr = "unknown \\ escape"; |
| 426 | return 0; |
| 427 | } |
| 428 | c = p->sIn.z[p->sIn.i]; |
| 429 | if( c=='u' && p->sIn.i+4<p->sIn.mx ){ |
| 430 | const unsigned char *zIn = p->sIn.z + p->sIn.i; |
| 431 | if( re_hex(zIn[1],&v) |
| 432 | && re_hex(zIn[2],&v) |
| 433 | && re_hex(zIn[3],&v) |
| 434 | && re_hex(zIn[4],&v) |
| 435 | ){ |
| 436 | p->sIn.i += 5; |
| 437 | return v; |
| 438 | } |
| 439 | } |
| 440 | if( c=='x' && p->sIn.i+2<p->sIn.mx ){ |
| 441 | const unsigned char *zIn = p->sIn.z + p->sIn.i; |
| 442 | if( re_hex(zIn[1],&v) |
| 443 | && re_hex(zIn[2],&v) |
| 444 | ){ |
| 445 | p->sIn.i += 3; |
| 446 | return v; |
| 447 | } |
| 448 | } |
| 449 | for(i=0; zEsc[i] && zEsc[i]!=c; i++){} |
| 450 | if( zEsc[i] ){ |
| 451 | if( i<6 ) c = zTrans[i]; |
| 452 | p->sIn.i++; |
| 453 | }else{ |
| 454 | p->zErr = "unknown \\ escape"; |
| 455 | } |
| 456 | return c; |
| 457 | } |
| 458 | |
| 459 | /* Forward declaration */ |
| 460 | static const char *re_subcompile_string(ReCompiled*); |
| 461 | |
| 462 | /* Peek at the next byte of input */ |
| 463 | static unsigned char rePeek(ReCompiled *p){ |
| 464 | return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0; |
| 465 | } |
| 466 | |
| 467 | /* Compile RE text into a sequence of opcodes. Continue up to the |
| 468 | ** first unmatched ")" character, then return. If an error is found, |
| 469 | ** return a pointer to the error message string. |
| 470 | */ |
| 471 | static const char *re_subcompile_re(ReCompiled *p){ |
| 472 | const char *zErr; |
| 473 | int iStart, iEnd, iGoto; |
| 474 | iStart = p->nState; |
| 475 | zErr = re_subcompile_string(p); |
| 476 | if( zErr ) return zErr; |
| 477 | while( rePeek(p)=='|' ){ |
| 478 | iEnd = p->nState; |
| 479 | re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); |
| 480 | iGoto = re_append(p, RE_OP_GOTO, 0); |
| 481 | p->sIn.i++; |
| 482 | zErr = re_subcompile_string(p); |
| 483 | if( zErr ) return zErr; |
| 484 | p->aArg[iGoto] = p->nState - iGoto; |
| 485 | } |
| 486 | return 0; |
| 487 | } |
| 488 | |
| 489 | /* Compile an element of regular expression text (anything that can be |
| 490 | ** an operand to the "|" operator). Return NULL on success or a pointer |
| 491 | ** to the error message if there is a problem. |
| 492 | */ |
| 493 | static const char *re_subcompile_string(ReCompiled *p){ |
| 494 | int iPrev = -1; |
| 495 | int iStart; |
| 496 | unsigned c; |
| 497 | const char *zErr; |
| 498 | while( (c = p->xNextChar(&p->sIn))!=0 ){ |
| 499 | iStart = p->nState; |
| 500 | switch( c ){ |
| 501 | case '|': |
| 502 | case ')': { |
| 503 | p->sIn.i--; |
| 504 | return 0; |
| 505 | } |
| 506 | case '(': { |
| 507 | zErr = re_subcompile_re(p); |
| 508 | if( zErr ) return zErr; |
| 509 | if( rePeek(p)!=')' ) return "unmatched '('"; |
| 510 | p->sIn.i++; |
| 511 | break; |
| 512 | } |
| 513 | case '.': { |
| 514 | if( rePeek(p)=='*' ){ |
| 515 | re_append(p, RE_OP_ANYSTAR, 0); |
| 516 | p->sIn.i++; |
| 517 | }else{ |
| 518 | re_append(p, RE_OP_ANY, 0); |
| 519 | } |
| 520 | break; |
| 521 | } |
| 522 | case '*': { |
| 523 | if( iPrev<0 ) return "'*' without operand"; |
| 524 | re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); |
| 525 | re_append(p, RE_OP_FORK, iPrev - p->nState + 1); |
| 526 | break; |
| 527 | } |
| 528 | case '+': { |
| 529 | if( iPrev<0 ) return "'+' without operand"; |
| 530 | re_append(p, RE_OP_FORK, iPrev - p->nState); |
| 531 | break; |
| 532 | } |
| 533 | case '?': { |
| 534 | if( iPrev<0 ) return "'?' without operand"; |
| 535 | re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); |
| 536 | break; |
| 537 | } |
| 538 | case '$': { |
| 539 | re_append(p, RE_OP_MATCH, RE_EOF); |
| 540 | break; |
| 541 | } |
| 542 | case '^': { |
| 543 | re_append(p, RE_OP_ATSTART, 0); |
| 544 | break; |
| 545 | } |
| 546 | case '{': { |
| 547 | unsigned int m = 0, n = 0; |
| 548 | unsigned int sz, j; |
| 549 | if( iPrev<0 ) return "'{m,n}' without operand"; |
| 550 | while( (c=rePeek(p))>='0' && c<='9' ){ |
| 551 | m = m*10 + c - '0'; |
| 552 | if( m*2>p->mxAlloc ) return "REGEXP pattern too big"; |
| 553 | p->sIn.i++; |
| 554 | } |
| 555 | n = m; |
| 556 | if( c==',' ){ |
| 557 | p->sIn.i++; |
| 558 | n = 0; |
| 559 | while( (c=rePeek(p))>='0' && c<='9' ){ |
| 560 | n = n*10 + c-'0'; |
| 561 | if( n*2>p->mxAlloc ) return "REGEXP pattern too big"; |
| 562 | p->sIn.i++; |
| 563 | } |
| 564 | } |
| 565 | if( c!='}' ) return "unmatched '{'"; |
| 566 | if( n<m ) return "n less than m in '{m,n}'"; |
| 567 | p->sIn.i++; |
| 568 | sz = p->nState - iPrev; |
| 569 | if( m==0 ){ |
| 570 | if( n==0 ) return "both m and n are zero in '{m,n}'"; |
| 571 | re_insert(p, iPrev, RE_OP_FORK, sz+1); |
| 572 | iPrev++; |
| 573 | n--; |
| 574 | }else{ |
| 575 | for(j=1; j<m; j++) re_copy(p, iPrev, sz); |
| 576 | } |
| 577 | for(j=m; j<n; j++){ |
| 578 | re_append(p, RE_OP_FORK, sz+1); |
| 579 | re_copy(p, iPrev, sz); |
| 580 | } |
| 581 | if( n==0 && m>0 ){ |
| 582 | re_append(p, RE_OP_FORK, -(int)sz); |
| 583 | } |
| 584 | break; |
| 585 | } |
| 586 | case '[': { |
| 587 | unsigned int iFirst = p->nState; |
| 588 | if( rePeek(p)=='^' ){ |
| 589 | re_append(p, RE_OP_CC_EXC, 0); |
| 590 | p->sIn.i++; |
| 591 | }else{ |
| 592 | re_append(p, RE_OP_CC_INC, 0); |
| 593 | } |
| 594 | while( (c = p->xNextChar(&p->sIn))!=0 ){ |
| 595 | if( c=='[' && rePeek(p)==':' ){ |
| 596 | return "POSIX character classes not supported"; |
| 597 | } |
| 598 | if( c=='\\' ) c = re_esc_char(p); |
| 599 | if( rePeek(p)=='-' ){ |
| 600 | re_append(p, RE_OP_CC_RANGE, c); |
| 601 | p->sIn.i++; |
| 602 | c = p->xNextChar(&p->sIn); |
| 603 | if( c=='\\' ) c = re_esc_char(p); |
| 604 | re_append(p, RE_OP_CC_RANGE, c); |
| 605 | }else{ |
| 606 | re_append(p, RE_OP_CC_VALUE, c); |
| 607 | } |
| 608 | if( rePeek(p)==']' ){ p->sIn.i++; break; } |
| 609 | } |
| 610 | if( c==0 ) return "unclosed '['"; |
| 611 | if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst; |
| 612 | break; |
| 613 | } |
| 614 | case '\\': { |
| 615 | int specialOp = 0; |
| 616 | switch( rePeek(p) ){ |
| 617 | case 'b': specialOp = RE_OP_BOUNDARY; break; |
| 618 | case 'd': specialOp = RE_OP_DIGIT; break; |
| 619 | case 'D': specialOp = RE_OP_NOTDIGIT; break; |
| 620 | case 's': specialOp = RE_OP_SPACE; break; |
| 621 | case 'S': specialOp = RE_OP_NOTSPACE; break; |
| 622 | case 'w': specialOp = RE_OP_WORD; break; |
| 623 | case 'W': specialOp = RE_OP_NOTWORD; break; |
| 624 | } |
| 625 | if( specialOp ){ |
| 626 | p->sIn.i++; |
| 627 | re_append(p, specialOp, 0); |
| 628 | }else{ |
| 629 | c = re_esc_char(p); |
| 630 | re_append(p, RE_OP_MATCH, c); |
| 631 | } |
| 632 | break; |
| 633 | } |
| 634 | default: { |
| 635 | re_append(p, RE_OP_MATCH, c); |
| 636 | break; |
| 637 | } |
| 638 | } |
| 639 | iPrev = iStart; |
| 640 | } |
| 641 | return 0; |
| 642 | } |
| 643 | |
| 644 | /* Free and reclaim all the memory used by a previously compiled |
| 645 | ** regular expression. Applications should invoke this routine once |
| 646 | ** for every call to re_compile() to avoid memory leaks. |
| 647 | */ |
| 648 | static void re_free(ReCompiled *pRe){ |
| 649 | if( pRe ){ |
| 650 | sqlite3_free(pRe->aOp); |
| 651 | sqlite3_free(pRe->aArg); |
| 652 | sqlite3_free(pRe); |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | /* |
| 657 | ** Version of re_free() that accepts a pointer of type (void*). Required |
| 658 | ** to satisfy sanitizers when the re_free() function is called via a |
| 659 | ** function pointer. |
| 660 | */ |
| 661 | static void re_free_voidptr(void *p){ |
| 662 | re_free((ReCompiled*)p); |
| 663 | } |
| 664 | |
| 665 | /* |
| 666 | ** Compile a textual regular expression in zIn[] into a compiled regular |
| 667 | ** expression suitable for us by re_match() and return a pointer to the |
| 668 | ** compiled regular expression in *ppRe. Return NULL on success or an |
| 669 | ** error message if something goes wrong. |
| 670 | */ |
| 671 | static const char *re_compile( |
| 672 | ReCompiled **ppRe, /* OUT: write compiled NFA here */ |
| 673 | const char *zIn, /* Input regular expression */ |
| 674 | int mxRe, /* Complexity limit */ |
| 675 | int noCase /* True for caseless comparisons */ |
| 676 | ){ |
| 677 | ReCompiled *pRe; |
| 678 | const char *zErr; |
| 679 | int i, j; |
| 680 | |
| 681 | *ppRe = 0; |
| 682 | pRe = sqlite3_malloc64( sizeof(*pRe) ); |
| 683 | if( pRe==0 ){ |
| 684 | return "out of memory"; |
| 685 | } |
| 686 | memset(pRe, 0, sizeof(*pRe)); |
| 687 | pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; |
| 688 | pRe->mxAlloc = mxRe; |
| 689 | if( re_resize(pRe, 30) ){ |
| 690 | zErr = pRe->zErr; |
| 691 | re_free(pRe); |
| 692 | return zErr; |
| 693 | } |
| 694 | re_append(pRe, RE_OP_ANYSTAR, 0); |
| 695 | pRe->sIn.z = (unsigned char*)zIn; |
| 696 | pRe->sIn.i = 0; |
| 697 | pRe->sIn.mx = (int)strlen(zIn); |
| 698 | zErr = re_subcompile_re(pRe); |
| 699 | if( zErr ){ |
| 700 | re_free(pRe); |
| 701 | return zErr; |
| 702 | } |
| 703 | if( pRe->sIn.i>=pRe->sIn.mx ){ |
| 704 | re_append(pRe, RE_OP_ACCEPT, 0); |
| 705 | *ppRe = pRe; |
| 706 | }else{ |
| 707 | re_free(pRe); |
| 708 | return "unrecognized character"; |
| 709 | } |
| 710 | |
| 711 | /* If the regex begins with "^" and has no "|" at the top level, then |
| 712 | ** the whole regex is anchored at the start of the input and the |
| 713 | ** initial ".*" is not needed. Convert it into a no-op so that |
| 714 | ** re_match() can stop as soon as the start of the input fails to |
| 715 | ** match. A "|" at the top level would have caused a FORK to be |
| 716 | ** inserted at aOp[1], so aOp[1]==RE_OP_ATSTART is sufficient. Do |
| 717 | ** not remove the initial "^" itself, as there might be jumps back |
| 718 | ** to it, as in "^+". */ |
| 719 | if( pRe->aOp[1]==RE_OP_ATSTART ){ |
| 720 | pRe->aOp[0] = RE_OP_GOTO; |
| 721 | pRe->aArg[0] = 1; |
| 722 | } |
| 723 | |
| 724 | /* The following is a performance optimization. If the regex begins with |
| 725 | ** ".*" (if the input regex lacks an initial "^") and afterwards there are |
| 726 | ** one or more matching characters, enter those matching characters into |
| 727 | ** zInit[]. The re_match() routine can then search ahead in the input |
| 728 | ** string looking for the initial match without having to run the whole |
| 729 | ** regex engine over the string. Do not worry about trying to match |
| 730 | ** unicode characters beyond plane 0 - those are very rare and this is |
| 731 | ** just an optimization. */ |
| 732 | if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){ |
| 733 | for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ |
| 734 | unsigned x = pRe->aArg[i]; |
| 735 | if( x<=0x7f ){ |
| 736 | pRe->zInit[j++] = (unsigned char)x; |
| 737 | }else if( x<=0x7ff ){ |
| 738 | pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6)); |
| 739 | pRe->zInit[j++] = 0x80 | (x&0x3f); |
| 740 | }else if( x<=0xffff ){ |
| 741 | pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12)); |
| 742 | pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); |
| 743 | pRe->zInit[j++] = 0x80 | (x&0x3f); |
| 744 | }else{ |
| 745 | break; |
| 746 | } |
| 747 | } |
| 748 | if( j>0 && pRe->zInit[j-1]==0 ) j--; |
| 749 | pRe->nInit = j; |
| 750 | } |
| 751 | return pRe->zErr; |
| 752 | } |
| 753 | |
| 754 | /* |
| 755 | ** The value of LIMIT_MAX_PATTERN_LENGTH. |
| 756 | */ |
| 757 | static int re_maxlen(sqlite3_context *context){ |
| 758 | sqlite3 *db = sqlite3_context_db_handle(context); |
| 759 | return sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1); |
| 760 | } |
| 761 | |
| 762 | /* |
| 763 | ** Maximum NFA size given a maximum pattern length. |
| 764 | */ |
| 765 | static int re_maxnfa(int mxlen){ |
| 766 | return 75+mxlen/2; |
| 767 | } |
| 768 | |
| 769 | /* |
| 770 | ** Implementation of the regexp() SQL function. This function implements |
| 771 | ** the build-in REGEXP operator. The first argument to the function is the |
| 772 | ** pattern and the second argument is the string. So, the SQL statements: |
| 773 | ** |
| 774 | ** A REGEXP B |
| 775 | ** |
| 776 | ** is implemented as regexp(B,A). |
| 777 | */ |
| 778 | static void re_sql_func( |
| 779 | sqlite3_context *context, |
| 780 | int argc, |
| 781 | sqlite3_value **argv |
| 782 | ){ |
| 783 | ReCompiled *pRe; /* Compiled regular expression */ |
| 784 | const char *zPattern; /* The regular expression */ |
| 785 | const unsigned char *zStr;/* String being searched */ |
| 786 | const char *zErr; /* Compile error message */ |
| 787 | int setAux = 0; /* True to invoke sqlite3_set_auxdata() */ |
| 788 | |
| 789 | (void)argc; /* Unused */ |
| 790 | pRe = sqlite3_get_auxdata(context, 0); |
| 791 | if( pRe==0 ){ |
| 792 | int mxLen = re_maxlen(context); |
| 793 | int nPattern; |
| 794 | zPattern = (const char*)sqlite3_value_text(argv[0]); |
| 795 | if( zPattern==0 ) return; |
| 796 | nPattern = sqlite3_value_bytes(argv[0]); |
| 797 | if( nPattern>mxLen ){ |
| 798 | zErr = "REGEXP pattern too big"; |
| 799 | }else{ |
| 800 | zErr = re_compile(&pRe, zPattern, re_maxnfa(mxLen), |
| 801 | sqlite3_user_data(context)!=0); |
| 802 | } |
| 803 | if( zErr ){ |
| 804 | re_free(pRe); |
| 805 | sqlite3_result_error(context, zErr, -1); |
| 806 | return; |
| 807 | } |
| 808 | if( pRe==0 ){ |
| 809 | sqlite3_result_error_nomem(context); |
| 810 | return; |
| 811 | } |
| 812 | setAux = 1; |
| 813 | } |
| 814 | zStr = (const unsigned char*)sqlite3_value_text(argv[1]); |
| 815 | if( zStr!=0 ){ |
| 816 | sqlite3_result_int(context, re_match(pRe, zStr, -1)); |
| 817 | } |
| 818 | if( setAux ){ |
| 819 | sqlite3_set_auxdata(context, 0, pRe, re_free_voidptr); |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | #if defined(SQLITE_DEBUG) |
| 824 | /* |
| 825 | ** This function is used for testing and debugging only. It is only available |
| 826 | ** if the SQLITE_DEBUG compile-time option is used. |
| 827 | ** |
| 828 | ** Compile a regular expression and then convert the compiled expression into |
| 829 | ** text and return that text. |
| 830 | */ |
| 831 | static void re_bytecode_func( |
| 832 | sqlite3_context *context, |
| 833 | int argc, |
| 834 | sqlite3_value **argv |
| 835 | ){ |
| 836 | const char *zPattern; |
| 837 | const char *zErr; |
| 838 | ReCompiled *pRe; |
| 839 | sqlite3_str *pStr; |
| 840 | int i; |
| 841 | int n; |
| 842 | char *z; |
| 843 | static const char *ReOpName[] = { |
| 844 | "EOF", |
| 845 | "MATCH", |
| 846 | "ANY", |
| 847 | "ANYSTAR", |
| 848 | "FORK", |
| 849 | "GOTO", |
| 850 | "ACCEPT", |
| 851 | "CC_INC", |
| 852 | "CC_EXC", |
| 853 | "CC_VALUE", |
| 854 | "CC_RANGE", |
| 855 | "WORD", |
| 856 | "NOTWORD", |
| 857 | "DIGIT", |
| 858 | "NOTDIGIT", |
| 859 | "SPACE", |
| 860 | "NOTSPACE", |
| 861 | "BOUNDARY", |
| 862 | "ATSTART", |
| 863 | }; |
| 864 | |
| 865 | (void)argc; |
| 866 | zPattern = (const char*)sqlite3_value_text(argv[0]); |
| 867 | if( zPattern==0 ) return; |
| 868 | zErr = re_compile(&pRe, zPattern, re_maxnfa(re_maxlen(context)), |
| 869 | sqlite3_user_data(context)!=0); |
| 870 | if( zErr ){ |
| 871 | re_free(pRe); |
| 872 | sqlite3_result_error(context, zErr, -1); |
| 873 | return; |
| 874 | } |
| 875 | if( pRe==0 ){ |
| 876 | sqlite3_result_error_nomem(context); |
| 877 | return; |
| 878 | } |
| 879 | pStr = sqlite3_str_new(0); |
| 880 | if( pRe->nInit>0 ){ |
| 881 | sqlite3_str_appendf(pStr, "INIT "); |
| 882 | for(i=0; i<pRe->nInit; i++){ |
| 883 | sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]); |
| 884 | } |
| 885 | sqlite3_str_appendf(pStr, "\n"); |
| 886 | } |
| 887 | for(i=0; (unsigned)i<pRe->nState; i++){ |
| 888 | sqlite3_str_appendf(pStr, "%-8s %4d\n", |
| 889 | ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]); |
| 890 | } |
| 891 | if( sqlite3_str_errcode(pStr)==SQLITE_NOMEM ){ |
| 892 | sqlite3_str_finish(pStr); |
| 893 | re_free(pRe); |
| 894 | sqlite3_result_error_nomem(context); |
| 895 | return; |
| 896 | } |
| 897 | n = sqlite3_str_length(pStr); |
| 898 | z = sqlite3_str_finish(pStr); |
| 899 | sqlite3_result_text(context, z, n-1, sqlite3_free); |
| 900 | re_free(pRe); |
| 901 | } |
| 902 | |
| 903 | #endif /* SQLITE_DEBUG */ |
| 904 | |
| 905 | |
| 906 | /* |
| 907 | ** Invoke this routine to register the regexp() function with the |
| 908 | ** SQLite database connection. |
| 909 | */ |
| 910 | #ifdef _WIN32 |
| 911 | __declspec(dllexport) |
| 912 | #endif |
| 913 | int sqlite3_regexp_init( |
| 914 | sqlite3 *db, |
| 915 | char **pzErrMsg, |
| 916 | const sqlite3_api_routines *pApi |
| 917 | ){ |
| 918 | int rc = SQLITE_OK; |
| 919 | SQLITE_EXTENSION_INIT2(pApi); |
| 920 | (void)pzErrMsg; /* Unused */ |
| 921 | rc = sqlite3_create_function(db, "regexp", 2, |
| 922 | SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, |
| 923 | 0, re_sql_func, 0, 0); |
| 924 | if( rc==SQLITE_OK ){ |
| 925 | /* The regexpi(PATTERN,STRING) function is a case-insensitive version |
| 926 | ** of regexp(PATTERN,STRING). */ |
| 927 | rc = sqlite3_create_function(db, "regexpi", 2, |
| 928 | SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, |
| 929 | (void*)db, re_sql_func, 0, 0); |
| 930 | #if defined(SQLITE_DEBUG) |
| 931 | if( rc==SQLITE_OK ){ |
| 932 | rc = sqlite3_create_function(db, "regexp_bytecode", 1, |
| 933 | SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, |
| 934 | 0, re_bytecode_func, 0, 0); |
| 935 | } |
| 936 | #endif /* SQLITE_DEBUG */ |
| 937 | } |
| 938 | return rc; |
| 939 | } |