lpvm.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. #include <limits.h>
  2. #include <string.h>
  3. #include "lua.h"
  4. #include "lauxlib.h"
  5. #include "lpcap.h"
  6. #include "lptypes.h"
  7. #include "lpvm.h"
  8. #include "lpprint.h"
  9. /* initial size for call/backtrack stack */
  10. #if !defined(INITBACK)
  11. #define INITBACK MAXBACK
  12. #endif
  13. #define getoffset(p) (((p) + 1)->offset)
  14. static const Instruction giveup = {{IGiveup, 0, {0}}};
  15. int charinset (const Instruction *i, const byte *buff, uint c) {
  16. c -= i->i.aux2.set.offset;
  17. if (c >= ((uint)i->i.aux2.set.size /* size in instructions... */
  18. * (uint)sizeof(Instruction) /* in bytes... */
  19. * 8u)) /* in bits */
  20. return i->i.aux1; /* out of range; return default value */
  21. return testchar(buff, c);
  22. }
  23. /*
  24. ** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
  25. */
  26. static const char *utf8_decode (const char *o, int *val) {
  27. static const uint limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFFu};
  28. const unsigned char *s = (const unsigned char *)o;
  29. uint c = s[0]; /* first byte */
  30. uint res = 0; /* final result */
  31. if (c < 0x80) /* ascii? */
  32. res = c;
  33. else {
  34. int count = 0; /* to count number of continuation bytes */
  35. while (c & 0x40) { /* still have continuation bytes? */
  36. int cc = s[++count]; /* read next byte */
  37. if ((cc & 0xC0) != 0x80) /* not a continuation byte? */
  38. return NULL; /* invalid byte sequence */
  39. res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
  40. c <<= 1; /* to test next bit */
  41. }
  42. res |= (c & 0x7F) << (count * 5); /* add first byte */
  43. if (count > 3 || res > 0x10FFFFu || res <= limits[count])
  44. return NULL; /* invalid byte sequence */
  45. s += count; /* skip continuation bytes read */
  46. }
  47. *val = res;
  48. return (const char *)s + 1; /* +1 to include first byte */
  49. }
  50. /*
  51. ** {======================================================
  52. ** Virtual Machine
  53. ** =======================================================
  54. */
  55. typedef struct Stack {
  56. const char *s; /* saved position (or NULL for calls) */
  57. const Instruction *p; /* next instruction */
  58. int caplevel;
  59. } Stack;
  60. #define getstackbase(L, ptop) ((Stack *)lua_touserdata(L, stackidx(ptop)))
  61. /*
  62. ** Ensures the size of array 'capture' (with size '*capsize' and
  63. ** 'captop' elements being used) is enough to accomodate 'n' extra
  64. ** elements plus one. (Because several opcodes add stuff to the capture
  65. ** array, it is simpler to ensure the array always has at least one free
  66. ** slot upfront and check its size later.)
  67. */
  68. /* new size in number of elements cannot overflow integers, and new
  69. size in bytes cannot overflow size_t. */
  70. #define MAXNEWSIZE \
  71. (((size_t)INT_MAX) <= (~(size_t)0 / sizeof(Capture)) ? \
  72. ((size_t)INT_MAX) : (~(size_t)0 / sizeof(Capture)))
  73. static Capture *growcap (lua_State *L, Capture *capture, int *capsize,
  74. int captop, int n, int ptop) {
  75. if (*capsize - captop > n)
  76. return capture; /* no need to grow array */
  77. else { /* must grow */
  78. Capture *newc;
  79. uint newsize = captop + n + 1; /* minimum size needed */
  80. if (newsize < (MAXNEWSIZE / 3) * 2)
  81. newsize += newsize / 2; /* 1.5 that size, if not too big */
  82. else if (newsize < (MAXNEWSIZE / 9) * 8)
  83. newsize += newsize / 8; /* else, try 9/8 that size */
  84. else
  85. luaL_error(L, "too many captures");
  86. newc = (Capture *)lua_newuserdata(L, newsize * sizeof(Capture));
  87. memcpy(newc, capture, captop * sizeof(Capture));
  88. *capsize = newsize;
  89. lua_replace(L, caplistidx(ptop));
  90. return newc;
  91. }
  92. }
  93. /*
  94. ** Double the size of the stack
  95. */
  96. static Stack *doublestack (lua_State *L, Stack **stacklimit, int ptop) {
  97. Stack *stack = getstackbase(L, ptop);
  98. Stack *newstack;
  99. int n = *stacklimit - stack; /* current stack size */
  100. int max, newn;
  101. lua_getfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
  102. max = lua_tointeger(L, -1); /* maximum allowed size */
  103. lua_pop(L, 1);
  104. if (n >= max) /* already at maximum size? */
  105. luaL_error(L, "backtrack stack overflow (current limit is %d)", max);
  106. newn = 2 * n; /* new size */
  107. if (newn > max) newn = max;
  108. newstack = (Stack *)lua_newuserdata(L, newn * sizeof(Stack));
  109. memcpy(newstack, stack, n * sizeof(Stack));
  110. lua_replace(L, stackidx(ptop));
  111. *stacklimit = newstack + newn;
  112. return newstack + n; /* return next position */
  113. }
  114. /*
  115. ** Interpret the result of a dynamic capture: false -> fail;
  116. ** true -> keep current position; number -> next position.
  117. ** Return new subject position. 'fr' is stack index where
  118. ** is the result; 'curr' is current subject position; 'limit'
  119. ** is subject's size.
  120. */
  121. static int resdyncaptures (lua_State *L, int fr, int curr, int limit) {
  122. lua_Integer res;
  123. if (!lua_toboolean(L, fr)) { /* false value? */
  124. lua_settop(L, fr - 1); /* remove results */
  125. return -1; /* and fail */
  126. }
  127. else if (lua_isboolean(L, fr)) /* true? */
  128. res = curr; /* keep current position */
  129. else {
  130. res = lua_tointeger(L, fr) - 1; /* new position */
  131. if (res < curr || res > limit)
  132. luaL_error(L, "invalid position returned by match-time capture");
  133. }
  134. lua_remove(L, fr); /* remove first result (offset) */
  135. return res;
  136. }
  137. /*
  138. ** Add capture values returned by a dynamic capture to the list
  139. ** 'capture', nested inside a group. 'fd' indexes the first capture
  140. ** value, 'n' is the number of values (at least 1). The open group
  141. ** capture is already in 'capture', before the place for the new entries.
  142. */
  143. static void adddyncaptures (Index_t index, Capture *capture, int n, int fd) {
  144. int i;
  145. assert(capture[-1].kind == Cgroup && capture[-1].siz == 0);
  146. capture[-1].idx = 0; /* make group capture an anonymous group */
  147. for (i = 0; i < n; i++) { /* add runtime captures */
  148. capture[i].kind = Cruntime;
  149. capture[i].siz = 1; /* mark it as closed */
  150. capture[i].idx = fd + i; /* stack index of capture value */
  151. capture[i].index = index;
  152. }
  153. capture[n].kind = Cclose; /* close group */
  154. capture[n].siz = 1;
  155. capture[n].index = index;
  156. }
  157. /*
  158. ** Remove dynamic captures from the Lua stack (called in case of failure)
  159. */
  160. static int removedyncap (lua_State *L, Capture *capture,
  161. int level, int last) {
  162. int id = finddyncap(capture + level, capture + last); /* index of 1st cap. */
  163. int top = lua_gettop(L);
  164. if (id == 0) return 0; /* no dynamic captures? */
  165. lua_settop(L, id - 1); /* remove captures */
  166. return top - id + 1; /* number of values removed */
  167. }
  168. /*
  169. ** Find the corresponding 'open' capture before 'cap', when that capture
  170. ** can become a full capture. If a full capture c1 is followed by an
  171. ** empty capture c2, there is no way to know whether c2 is inside
  172. ** c1. So, full captures can enclose only captures that start *before*
  173. ** its end.
  174. */
  175. static Capture *findopen (Capture *cap, Index_t currindex) {
  176. int i;
  177. cap--; /* check last capture */
  178. /* Must it be inside current one, but starts where current one ends? */
  179. if (!isopencap(cap) && cap->index == currindex)
  180. return NULL; /* current one cannot be a full capture */
  181. /* else, look for an 'open' capture */
  182. for (i = 0; i < MAXLOP; i++, cap--) {
  183. if (currindex - cap->index >= UCHAR_MAX)
  184. return NULL; /* capture too long for a full capture */
  185. else if (isopencap(cap)) /* open capture? */
  186. return cap; /* that's the one to be closed */
  187. else if (cap->kind == Cclose)
  188. return NULL; /* a full capture should not nest a non-full one */
  189. }
  190. return NULL; /* not found within allowed search limit */
  191. }
  192. /*
  193. ** Opcode interpreter
  194. */
  195. const char *match (lua_State *L, const char *o, const char *s, const char *e,
  196. Instruction *op, Capture *capture, int ptop) {
  197. Stack stackbase[INITBACK];
  198. Stack *stacklimit = stackbase + INITBACK;
  199. Stack *stack = stackbase; /* point to first empty slot in stack */
  200. int capsize = INITCAPSIZE;
  201. int captop = 0; /* point to first empty slot in captures */
  202. int ndyncap = 0; /* number of dynamic captures (in Lua stack) */
  203. const Instruction *p = op; /* current instruction */
  204. stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
  205. lua_pushlightuserdata(L, stackbase);
  206. for (;;) {
  207. #if defined(DEBUG)
  208. printf("-------------------------------------\n");
  209. printcaplist(capture, capture + captop);
  210. printf("s: |%s| stck:%d, dyncaps:%d, caps:%d ",
  211. s, (int)(stack - getstackbase(L, ptop)), ndyncap, captop);
  212. printinst(op, p);
  213. #endif
  214. assert(stackidx(ptop) + ndyncap == lua_gettop(L) && ndyncap <= captop);
  215. switch ((Opcode)p->i.code) {
  216. case IEnd: {
  217. assert(stack == getstackbase(L, ptop) + 1);
  218. capture[captop].kind = Cclose;
  219. capture[captop].index = MAXINDT;
  220. return s;
  221. }
  222. case IGiveup: {
  223. assert(stack == getstackbase(L, ptop));
  224. return NULL;
  225. }
  226. case IRet: {
  227. assert(stack > getstackbase(L, ptop) && (stack - 1)->s == NULL);
  228. p = (--stack)->p;
  229. continue;
  230. }
  231. case IAny: {
  232. if (s < e) { p++; s++; }
  233. else goto fail;
  234. continue;
  235. }
  236. case IUTFR: {
  237. int codepoint;
  238. if (s >= e)
  239. goto fail;
  240. s = utf8_decode (s, &codepoint);
  241. if (s && p[1].offset <= codepoint && codepoint <= utf_to(p))
  242. p += 2;
  243. else
  244. goto fail;
  245. continue;
  246. }
  247. case ITestAny: {
  248. if (s < e) p += 2;
  249. else p += getoffset(p);
  250. continue;
  251. }
  252. case IChar: {
  253. if ((byte)*s == p->i.aux1 && s < e) { p++; s++; }
  254. else goto fail;
  255. continue;
  256. }
  257. case ITestChar: {
  258. if ((byte)*s == p->i.aux1 && s < e) p += 2;
  259. else p += getoffset(p);
  260. continue;
  261. }
  262. case ISet: {
  263. uint c = (byte)*s;
  264. if (charinset(p, (p+1)->buff, c) && s < e)
  265. { p += 1 + p->i.aux2.set.size; s++; }
  266. else goto fail;
  267. continue;
  268. }
  269. case ITestSet: {
  270. uint c = (byte)*s;
  271. if (charinset(p, (p + 2)->buff, c) && s < e)
  272. p += 2 + p->i.aux2.set.size;
  273. else p += getoffset(p);
  274. continue;
  275. }
  276. case IBehind: {
  277. int n = p->i.aux1;
  278. if (n > s - o) goto fail;
  279. s -= n; p++;
  280. continue;
  281. }
  282. case ISpan: {
  283. for (; s < e; s++) {
  284. uint c = (byte)*s;
  285. if (!charinset(p, (p+1)->buff, c)) break;
  286. }
  287. p += 1 + p->i.aux2.set.size;
  288. continue;
  289. }
  290. case IJmp: {
  291. p += getoffset(p);
  292. continue;
  293. }
  294. case IChoice: {
  295. if (stack == stacklimit)
  296. stack = doublestack(L, &stacklimit, ptop);
  297. stack->p = p + getoffset(p);
  298. stack->s = s;
  299. stack->caplevel = captop;
  300. stack++;
  301. p += 2;
  302. continue;
  303. }
  304. case ICall: {
  305. if (stack == stacklimit)
  306. stack = doublestack(L, &stacklimit, ptop);
  307. stack->s = NULL;
  308. stack->p = p + 2; /* save return address */
  309. stack++;
  310. p += getoffset(p);
  311. continue;
  312. }
  313. case ICommit: {
  314. assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
  315. stack--;
  316. p += getoffset(p);
  317. continue;
  318. }
  319. case IPartialCommit: {
  320. assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
  321. (stack - 1)->s = s;
  322. (stack - 1)->caplevel = captop;
  323. p += getoffset(p);
  324. continue;
  325. }
  326. case IBackCommit: {
  327. assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
  328. s = (--stack)->s;
  329. if (ndyncap > 0) /* are there matchtime captures? */
  330. ndyncap -= removedyncap(L, capture, stack->caplevel, captop);
  331. captop = stack->caplevel;
  332. p += getoffset(p);
  333. continue;
  334. }
  335. case IFailTwice:
  336. assert(stack > getstackbase(L, ptop));
  337. stack--;
  338. /* FALLTHROUGH */
  339. case IFail:
  340. fail: { /* pattern failed: try to backtrack */
  341. do { /* remove pending calls */
  342. assert(stack > getstackbase(L, ptop));
  343. s = (--stack)->s;
  344. } while (s == NULL);
  345. if (ndyncap > 0) /* is there matchtime captures? */
  346. ndyncap -= removedyncap(L, capture, stack->caplevel, captop);
  347. captop = stack->caplevel;
  348. p = stack->p;
  349. #if defined(DEBUG)
  350. printf("**FAIL**\n");
  351. #endif
  352. continue;
  353. }
  354. case ICloseRunTime: {
  355. CapState cs;
  356. int rem, res, n;
  357. int fr = lua_gettop(L) + 1; /* stack index of first result */
  358. cs.reclevel = 0; cs.L = L;
  359. cs.s = o; cs.ocap = capture; cs.ptop = ptop;
  360. n = runtimecap(&cs, capture + captop, s, &rem); /* call function */
  361. captop -= n; /* remove nested captures */
  362. ndyncap -= rem; /* update number of dynamic captures */
  363. fr -= rem; /* 'rem' items were popped from Lua stack */
  364. res = resdyncaptures(L, fr, s - o, e - o); /* get result */
  365. if (res == -1) /* fail? */
  366. goto fail;
  367. s = o + res; /* else update current position */
  368. n = lua_gettop(L) - fr + 1; /* number of new captures */
  369. ndyncap += n; /* update number of dynamic captures */
  370. if (n == 0) /* no new captures? */
  371. captop--; /* remove open group */
  372. else { /* new captures; keep original open group */
  373. if (fr + n >= SHRT_MAX)
  374. luaL_error(L, "too many results in match-time capture");
  375. /* add new captures + close group to 'capture' list */
  376. capture = growcap(L, capture, &capsize, captop, n + 1, ptop);
  377. adddyncaptures(s - o, capture + captop, n, fr);
  378. captop += n + 1; /* new captures + close group */
  379. }
  380. p++;
  381. continue;
  382. }
  383. case ICloseCapture: {
  384. Capture *open = findopen(capture + captop, s - o);
  385. assert(captop > 0);
  386. if (open) { /* if possible, turn capture into a full capture */
  387. open->siz = (s - o) - open->index + 1;
  388. p++;
  389. continue;
  390. }
  391. else { /* must create a close capture */
  392. capture[captop].siz = 1; /* mark entry as closed */
  393. capture[captop].index = s - o;
  394. goto pushcapture;
  395. }
  396. }
  397. case IOpenCapture:
  398. capture[captop].siz = 0; /* mark entry as open */
  399. capture[captop].index = s - o;
  400. goto pushcapture;
  401. case IFullCapture:
  402. capture[captop].siz = getoff(p) + 1; /* save capture size */
  403. capture[captop].index = s - o - getoff(p);
  404. /* goto pushcapture; */
  405. pushcapture: {
  406. capture[captop].idx = p->i.aux2.key;
  407. capture[captop].kind = getkind(p);
  408. captop++;
  409. capture = growcap(L, capture, &capsize, captop, 0, ptop);
  410. p++;
  411. continue;
  412. }
  413. default: assert(0); return NULL;
  414. }
  415. }
  416. }
  417. /* }====================================================== */