interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / ltests.c

2247 lines · 59587 bytes Raw Blame History
1/*
2** $Id: ltests.c $
3** Internal Module for Debugging of the Lua Implementation
4** See Copyright Notice in lua.h
5*/
6
7#define ltests_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
13#include <limits.h>
14#include <setjmp.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18
19#include "lua.h"
20
21#include "lapi.h"
22#include "lauxlib.h"
23#include "lcode.h"
24#include "lctype.h"
25#include "ldebug.h"
26#include "ldo.h"
27#include "lfunc.h"
28#include "lmem.h"
29#include "lopcodes.h"
30#include "lopnames.h"
31#include "lstate.h"
32#include "lstring.h"
33#include "ltable.h"
34#include "lualib.h"
35
36
37
38/*
39** The whole module only makes sense with LUA_DEBUG on
40*/
41#if defined(LUA_DEBUG)
42
43
44void *l_Trick = 0;
45
46
47#define obj_at(L,k) s2v(L->ci->func.p + (k))
48
49
50static int runC (lua_State *L, lua_State *L1, const char *pc);
51
52
53static void setnameval (lua_State *L, const char *name, int val) {
54 lua_pushinteger(L, val);
55 lua_setfield(L, -2, name);
56}
57
58
59static void pushobject (lua_State *L, const TValue *o) {
60 setobj2s(L, L->top.p, o);
61 api_incr_top(L);
62}
63
64
65static void badexit (const char *fmt, const char *s1, const char *s2) {
66 fprintf(stderr, fmt, s1);
67 if (s2)
68 fprintf(stderr, "extra info: %s\n", s2);
69 /* avoid assertion failures when exiting */
70 l_memcontrol.numblocks = l_memcontrol.total = 0;
71 exit(EXIT_FAILURE);
72}
73
74
75static int tpanic (lua_State *L) {
76 const char *msg = (lua_type(L, -1) == LUA_TSTRING)
77 ? lua_tostring(L, -1)
78 : "error object is not a string";
79 return (badexit("PANIC: unprotected error in call to Lua API (%s)\n",
80 msg, NULL),
81 0); /* do not return to Lua */
82}
83
84
85/*
86** Warning function for tests. First, it concatenates all parts of
87** a warning in buffer 'buff'. Then, it has three modes:
88** - 0.normal: messages starting with '#' are shown on standard output;
89** - other messages abort the tests (they represent real warning
90** conditions; the standard tests should not generate these conditions
91** unexpectedly);
92** - 1.allow: all messages are shown;
93** - 2.store: all warnings go to the global '_WARN';
94*/
95static void warnf (void *ud, const char *msg, int tocont) {
96 lua_State *L = cast(lua_State *, ud);
97 static char buff[200] = ""; /* should be enough for tests... */
98 static int onoff = 0;
99 static int mode = 0; /* start in normal mode */
100 static int lasttocont = 0;
101 if (!lasttocont && !tocont && *msg == '@') { /* control message? */
102 if (buff[0] != '\0')
103 badexit("Control warning during warning: %s\naborting...\n", msg, buff);
104 if (strcmp(msg, "@off") == 0)
105 onoff = 0;
106 else if (strcmp(msg, "@on") == 0)
107 onoff = 1;
108 else if (strcmp(msg, "@normal") == 0)
109 mode = 0;
110 else if (strcmp(msg, "@allow") == 0)
111 mode = 1;
112 else if (strcmp(msg, "@store") == 0)
113 mode = 2;
114 else
115 badexit("Invalid control warning in test mode: %s\naborting...\n",
116 msg, NULL);
117 return;
118 }
119 lasttocont = tocont;
120 if (strlen(msg) >= sizeof(buff) - strlen(buff))
121 badexit("warnf-buffer overflow (%s)\n", msg, buff);
122 strcat(buff, msg); /* add new message to current warning */
123 if (!tocont) { /* message finished? */
124 lua_unlock(L);
125 luaL_checkstack(L, 1, "warn stack space");
126 lua_getglobal(L, "_WARN");
127 if (!lua_toboolean(L, -1))
128 lua_pop(L, 1); /* ok, no previous unexpected warning */
129 else {
130 badexit("Unhandled warning in store mode: %s\naborting...\n",
131 lua_tostring(L, -1), buff);
132 }
133 lua_lock(L);
134 switch (mode) {
135 case 0: { /* normal */
136 if (buff[0] != '#' && onoff) /* unexpected warning? */
137 badexit("Unexpected warning in test mode: %s\naborting...\n",
138 buff, NULL);
139 } /* FALLTHROUGH */
140 case 1: { /* allow */
141 if (onoff)
142 fprintf(stderr, "Lua warning: %s\n", buff); /* print warning */
143 break;
144 }
145 case 2: { /* store */
146 lua_unlock(L);
147 luaL_checkstack(L, 1, "warn stack space");
148 lua_pushstring(L, buff);
149 lua_setglobal(L, "_WARN"); /* assign message to global '_WARN' */
150 lua_lock(L);
151 break;
152 }
153 }
154 buff[0] = '\0'; /* prepare buffer for next warning */
155 }
156}
157
158
159/*
160** {======================================================================
161** Controlled version for realloc.
162** =======================================================================
163*/
164
165#define MARK 0x55 /* 01010101 (a nice pattern) */
166
167typedef union memHeader {
168 LUAI_MAXALIGN;
169 struct {
170 size_t size;
171 int type;
172 } d;
173} memHeader;
174
175
176#if !defined(EXTERNMEMCHECK)
177
178/* full memory check */
179#define MARKSIZE 16 /* size of marks after each block */
180#define fillmem(mem,size) memset(mem, -MARK, size)
181
182#else
183
184/* external memory check: don't do it twice */
185#define MARKSIZE 0
186#define fillmem(mem,size) /* empty */
187
188#endif
189
190
191Memcontrol l_memcontrol =
192 {0, 0UL, 0UL, 0UL, 0UL, (~0UL),
193 {0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL}};
194
195
196static void freeblock (Memcontrol *mc, memHeader *block) {
197 if (block) {
198 size_t size = block->d.size;
199 int i;
200 for (i = 0; i < MARKSIZE; i++) /* check marks after block */
201 lua_assert(*(cast_charp(block + 1) + size + i) == MARK);
202 mc->objcount[block->d.type]--;
203 fillmem(block, sizeof(memHeader) + size + MARKSIZE); /* erase block */
204 free(block); /* actually free block */
205 mc->numblocks--; /* update counts */
206 mc->total -= size;
207 }
208}
209
210
211void *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) {
212 Memcontrol *mc = cast(Memcontrol *, ud);
213 memHeader *block = cast(memHeader *, b);
214 int type;
215 if (mc->memlimit == 0) { /* first time? */
216 char *limit = getenv("MEMLIMIT"); /* initialize memory limit */
217 mc->memlimit = limit ? strtoul(limit, NULL, 10) : ULONG_MAX;
218 }
219 if (block == NULL) {
220 type = (oldsize < LUA_NUMTYPES) ? cast_int(oldsize) : 0;
221 oldsize = 0;
222 }
223 else {
224 block--; /* go to real header */
225 type = block->d.type;
226 lua_assert(oldsize == block->d.size);
227 }
228 if (size == 0) {
229 freeblock(mc, block);
230 return NULL;
231 }
232 if (mc->failnext) {
233 mc->failnext = 0;
234 return NULL; /* fake a single memory allocation error */
235 }
236 if (mc->countlimit != ~0UL && size != oldsize) { /* count limit in use? */
237 if (mc->countlimit == 0)
238 return NULL; /* fake a memory allocation error */
239 mc->countlimit--;
240 }
241 if (size > oldsize && mc->total+size-oldsize > mc->memlimit)
242 return NULL; /* fake a memory allocation error */
243 else {
244 memHeader *newblock;
245 int i;
246 size_t commonsize = (oldsize < size) ? oldsize : size;
247 size_t realsize = sizeof(memHeader) + size + MARKSIZE;
248 if (realsize < size) return NULL; /* arithmetic overflow! */
249 newblock = cast(memHeader *, malloc(realsize)); /* alloc a new block */
250 if (newblock == NULL)
251 return NULL; /* really out of memory? */
252 if (block) {
253 memcpy(newblock + 1, block + 1, commonsize); /* copy old contents */
254 freeblock(mc, block); /* erase (and check) old copy */
255 }
256 /* initialize new part of the block with something weird */
257 fillmem(cast_charp(newblock + 1) + commonsize, size - commonsize);
258 /* initialize marks after block */
259 for (i = 0; i < MARKSIZE; i++)
260 *(cast_charp(newblock + 1) + size + i) = MARK;
261 newblock->d.size = size;
262 newblock->d.type = type;
263 mc->total += size;
264 if (mc->total > mc->maxmem)
265 mc->maxmem = mc->total;
266 mc->numblocks++;
267 mc->objcount[type]++;
268 return newblock + 1;
269 }
270}
271
272
273/* }====================================================================== */
274
275
276
277/*
278** {=====================================================================
279** Functions to check memory consistency.
280** Most of these checks are done through asserts, so this code does
281** not make sense with asserts off. For this reason, it uses 'assert'
282** directly, instead of 'lua_assert'.
283** ======================================================================
284*/
285
286#include <assert.h>
287
288/*
289** Check GC invariants. For incremental mode, a black object cannot
290** point to a white one. For generational mode, really old objects
291** cannot point to young objects. Both old1 and touched2 objects
292** cannot point to new objects (but can point to survivals).
293** (Threads and open upvalues, despite being marked "really old",
294** continue to be visited in all collections, and therefore can point to
295** new objects. They, and only they, are old but gray.)
296*/
297static int testobjref1 (global_State *g, GCObject *f, GCObject *t) {
298 if (isdead(g,t)) return 0;
299 if (issweepphase(g))
300 return 1; /* no invariants */
301 else if (g->gckind != KGC_GENMINOR)
302 return !(isblack(f) && iswhite(t)); /* basic incremental invariant */
303 else { /* generational mode */
304 if ((getage(f) == G_OLD && isblack(f)) && !isold(t))
305 return 0;
306 if ((getage(f) == G_OLD1 || getage(f) == G_TOUCHED2) &&
307 getage(t) == G_NEW)
308 return 0;
309 return 1;
310 }
311}
312
313
314static void printobj (global_State *g, GCObject *o) {
315 printf("||%s(%p)-%c%c(%02X)||",
316 ttypename(novariant(o->tt)), (void *)o,
317 isdead(g,o) ? 'd' : isblack(o) ? 'b' : iswhite(o) ? 'w' : 'g',
318 "ns01oTt"[getage(o)], o->marked);
319 if (o->tt == LUA_VSHRSTR || o->tt == LUA_VLNGSTR)
320 printf(" '%s'", getstr(gco2ts(o)));
321}
322
323
324void lua_printobj (lua_State *L, struct GCObject *o) {
325 printobj(G(L), o);
326}
327
328
329void lua_printvalue (TValue *v) {
330 switch (ttypetag(v)) {
331 case LUA_VNUMINT: case LUA_VNUMFLT: {
332 char buff[LUA_N2SBUFFSZ];
333 unsigned len = luaO_tostringbuff(v, buff);
334 buff[len] = '\0';
335 printf("%s", buff);
336 break;
337 }
338 case LUA_VSHRSTR:
339 printf("'%s'", getstr(tsvalue(v))); break;
340 case LUA_VLNGSTR:
341 printf("'%.30s...'", getstr(tsvalue(v))); break;
342 case LUA_VFALSE:
343 printf("%s", "false"); break;
344 case LUA_VTRUE:
345 printf("%s", "true"); break;
346 case LUA_VLIGHTUSERDATA:
347 printf("light udata: %p", pvalue(v)); break;
348 case LUA_VUSERDATA:
349 printf("full udata: %p", uvalue(v)); break;
350 case LUA_VNIL:
351 printf("nil"); break;
352 case LUA_VLCF:
353 printf("light C function: %p", fvalue(v)); break;
354 case LUA_VCCL:
355 printf("C closure: %p", clCvalue(v)); break;
356 case LUA_VLCL:
357 printf("Lua function: %p", clLvalue(v)); break;
358 case LUA_VTHREAD:
359 printf("thread: %p", thvalue(v)); break;
360 case LUA_VTABLE:
361 printf("table: %p", hvalue(v)); break;
362 default:
363 lua_assert(0);
364 }
365}
366
367
368static int testobjref (global_State *g, GCObject *f, GCObject *t) {
369 int r1 = testobjref1(g, f, t);
370 if (!r1) {
371 printf("%d(%02X) - ", g->gcstate, g->currentwhite);
372 printobj(g, f);
373 printf(" -> ");
374 printobj(g, t);
375 printf("\n");
376 }
377 return r1;
378}
379
380
381static void checkobjref (global_State *g, GCObject *f, GCObject *t) {
382 assert(testobjref(g, f, t));
383}
384
385
386/*
387** Version where 't' can be NULL. In that case, it should not apply the
388** macro 'obj2gco' over the object. ('t' may have several types, so this
389** definition must be a macro.) Most checks need this version, because
390** the check may run while an object is still being created.
391*/
392#define checkobjrefN(g,f,t) { if (t) checkobjref(g,f,obj2gco(t)); }
393
394
395static void checkvalref (global_State *g, GCObject *f, const TValue *t) {
396 assert(!iscollectable(t) || (righttt(t) && testobjref(g, f, gcvalue(t))));
397}
398
399
400static void checktable (global_State *g, Table *h) {
401 unsigned int i;
402 unsigned int asize = h->asize;
403 Node *n, *limit = gnode(h, sizenode(h));
404 GCObject *hgc = obj2gco(h);
405 checkobjrefN(g, hgc, h->metatable);
406 for (i = 0; i < asize; i++) {
407 TValue aux;
408 arr2obj(h, i, &aux);
409 checkvalref(g, hgc, &aux);
410 }
411 for (n = gnode(h, 0); n < limit; n++) {
412 if (!isempty(gval(n))) {
413 TValue k;
414 getnodekey(mainthread(g), &k, n);
415 assert(!keyisnil(n));
416 checkvalref(g, hgc, &k);
417 checkvalref(g, hgc, gval(n));
418 }
419 }
420}
421
422
423static void checkudata (global_State *g, Udata *u) {
424 int i;
425 GCObject *hgc = obj2gco(u);
426 checkobjrefN(g, hgc, u->metatable);
427 for (i = 0; i < u->nuvalue; i++)
428 checkvalref(g, hgc, &u->uv[i].uv);
429}
430
431
432static void checkproto (global_State *g, Proto *f) {
433 int i;
434 GCObject *fgc = obj2gco(f);
435 checkobjrefN(g, fgc, f->source);
436 for (i=0; i<f->sizek; i++) {
437 if (iscollectable(f->k + i))
438 checkobjref(g, fgc, gcvalue(f->k + i));
439 }
440 for (i=0; i<f->sizeupvalues; i++)
441 checkobjrefN(g, fgc, f->upvalues[i].name);
442 for (i=0; i<f->sizep; i++)
443 checkobjrefN(g, fgc, f->p[i]);
444 for (i=0; i<f->sizelocvars; i++)
445 checkobjrefN(g, fgc, f->locvars[i].varname);
446}
447
448
449static void checkCclosure (global_State *g, CClosure *cl) {
450 GCObject *clgc = obj2gco(cl);
451 int i;
452 for (i = 0; i < cl->nupvalues; i++)
453 checkvalref(g, clgc, &cl->upvalue[i]);
454}
455
456
457static void checkLclosure (global_State *g, LClosure *cl) {
458 GCObject *clgc = obj2gco(cl);
459 int i;
460 checkobjrefN(g, clgc, cl->p);
461 for (i=0; i<cl->nupvalues; i++) {
462 UpVal *uv = cl->upvals[i];
463 if (uv) {
464 checkobjrefN(g, clgc, uv);
465 if (!upisopen(uv))
466 checkvalref(g, obj2gco(uv), uv->v.p);
467 }
468 }
469}
470
471
472static int lua_checkpc (CallInfo *ci) {
473 if (!isLua(ci)) return 1;
474 else {
475 StkId f = ci->func.p;
476 Proto *p = clLvalue(s2v(f))->p;
477 return p->code <= ci->u.l.savedpc &&
478 ci->u.l.savedpc <= p->code + p->sizecode;
479 }
480}
481
482
483static void check_stack (global_State *g, lua_State *L1) {
484 StkId o;
485 CallInfo *ci;
486 UpVal *uv;
487 assert(!isdead(g, L1));
488 if (L1->stack.p == NULL) { /* incomplete thread? */
489 assert(L1->openupval == NULL && L1->ci == NULL);
490 return;
491 }
492 for (uv = L1->openupval; uv != NULL; uv = uv->u.open.next)
493 assert(upisopen(uv)); /* must be open */
494 assert(L1->top.p <= L1->stack_last.p);
495 assert(L1->tbclist.p <= L1->top.p);
496 for (ci = L1->ci; ci != NULL; ci = ci->previous) {
497 assert(ci->top.p <= L1->stack_last.p);
498 assert(lua_checkpc(ci));
499 }
500 for (o = L1->stack.p; o < L1->stack_last.p; o++)
501 checkliveness(L1, s2v(o)); /* entire stack must have valid values */
502}
503
504
505static void checkrefs (global_State *g, GCObject *o) {
506 switch (o->tt) {
507 case LUA_VUSERDATA: {
508 checkudata(g, gco2u(o));
509 break;
510 }
511 case LUA_VUPVAL: {
512 checkvalref(g, o, gco2upv(o)->v.p);
513 break;
514 }
515 case LUA_VTABLE: {
516 checktable(g, gco2t(o));
517 break;
518 }
519 case LUA_VTHREAD: {
520 check_stack(g, gco2th(o));
521 break;
522 }
523 case LUA_VLCL: {
524 checkLclosure(g, gco2lcl(o));
525 break;
526 }
527 case LUA_VCCL: {
528 checkCclosure(g, gco2ccl(o));
529 break;
530 }
531 case LUA_VPROTO: {
532 checkproto(g, gco2p(o));
533 break;
534 }
535 case LUA_VSHRSTR:
536 case LUA_VLNGSTR: {
537 assert(!isgray(o)); /* strings are never gray */
538 break;
539 }
540 default: assert(0);
541 }
542}
543
544
545/*
546** Check consistency of an object:
547** - Dead objects can only happen in the 'allgc' list during a sweep
548** phase (controlled by the caller through 'maybedead').
549** - During pause, all objects must be white.
550** - In generational mode:
551** * objects must be old enough for their lists ('listage').
552** * old objects cannot be white.
553** * old objects must be black, except for 'touched1', 'old0',
554** threads, and open upvalues.
555** * 'touched1' objects must be gray.
556*/
557static void checkobject (global_State *g, GCObject *o, int maybedead,
558 int listage) {
559 if (isdead(g, o))
560 assert(maybedead);
561 else {
562 assert(g->gcstate != GCSpause || iswhite(o));
563 if (g->gckind == KGC_GENMINOR) { /* generational mode? */
564 assert(getage(o) >= listage);
565 if (isold(o)) {
566 assert(!iswhite(o));
567 assert(isblack(o) ||
568 getage(o) == G_TOUCHED1 ||
569 getage(o) == G_OLD0 ||
570 o->tt == LUA_VTHREAD ||
571 (o->tt == LUA_VUPVAL && upisopen(gco2upv(o))));
572 }
573 assert(getage(o) != G_TOUCHED1 || isgray(o));
574 }
575 checkrefs(g, o);
576 }
577}
578
579
580static l_mem checkgraylist (global_State *g, GCObject *o) {
581 int total = 0; /* count number of elements in the list */
582 cast_void(g); /* better to keep it if we need to print an object */
583 while (o) {
584 assert(!!isgray(o) ^ (getage(o) == G_TOUCHED2));
585 assert(!testbit(o->marked, TESTBIT));
586 if (keepinvariant(g))
587 l_setbit(o->marked, TESTBIT); /* mark that object is in a gray list */
588 total++;
589 switch (o->tt) {
590 case LUA_VTABLE: o = gco2t(o)->gclist; break;
591 case LUA_VLCL: o = gco2lcl(o)->gclist; break;
592 case LUA_VCCL: o = gco2ccl(o)->gclist; break;
593 case LUA_VTHREAD: o = gco2th(o)->gclist; break;
594 case LUA_VPROTO: o = gco2p(o)->gclist; break;
595 case LUA_VUSERDATA:
596 assert(gco2u(o)->nuvalue > 0);
597 o = gco2u(o)->gclist;
598 break;
599 default: assert(0); /* other objects cannot be in a gray list */
600 }
601 }
602 return total;
603}
604
605
606/*
607** Check objects in gray lists.
608*/
609static l_mem checkgrays (global_State *g) {
610 l_mem total = 0; /* count number of elements in all lists */
611 if (!keepinvariant(g)) return total;
612 total += checkgraylist(g, g->gray);
613 total += checkgraylist(g, g->grayagain);
614 total += checkgraylist(g, g->weak);
615 total += checkgraylist(g, g->allweak);
616 total += checkgraylist(g, g->ephemeron);
617 return total;
618}
619
620
621/*
622** Check whether 'o' should be in a gray list. If so, increment
623** 'count' and check its TESTBIT. (It must have been previously set by
624** 'checkgraylist'.)
625*/
626static void incifingray (global_State *g, GCObject *o, l_mem *count) {
627 if (!keepinvariant(g))
628 return; /* gray lists not being kept in these phases */
629 if (o->tt == LUA_VUPVAL) {
630 /* only open upvalues can be gray */
631 assert(!isgray(o) || upisopen(gco2upv(o)));
632 return; /* upvalues are never in gray lists */
633 }
634 /* these are the ones that must be in gray lists */
635 if (isgray(o) || getage(o) == G_TOUCHED2) {
636 (*count)++;
637 assert(testbit(o->marked, TESTBIT));
638 resetbit(o->marked, TESTBIT); /* prepare for next cycle */
639 }
640}
641
642
643static l_mem checklist (global_State *g, int maybedead, int tof,
644 GCObject *newl, GCObject *survival, GCObject *old, GCObject *reallyold) {
645 GCObject *o;
646 l_mem total = 0; /* number of object that should be in gray lists */
647 for (o = newl; o != survival; o = o->next) {
648 checkobject(g, o, maybedead, G_NEW);
649 incifingray(g, o, &total);
650 assert(!tof == !tofinalize(o));
651 }
652 for (o = survival; o != old; o = o->next) {
653 checkobject(g, o, 0, G_SURVIVAL);
654 incifingray(g, o, &total);
655 assert(!tof == !tofinalize(o));
656 }
657 for (o = old; o != reallyold; o = o->next) {
658 checkobject(g, o, 0, G_OLD1);
659 incifingray(g, o, &total);
660 assert(!tof == !tofinalize(o));
661 }
662 for (o = reallyold; o != NULL; o = o->next) {
663 checkobject(g, o, 0, G_OLD);
664 incifingray(g, o, &total);
665 assert(!tof == !tofinalize(o));
666 }
667 return total;
668}
669
670
671int lua_checkmemory (lua_State *L) {
672 global_State *g = G(L);
673 GCObject *o;
674 int maybedead;
675 l_mem totalin; /* total of objects that are in gray lists */
676 l_mem totalshould; /* total of objects that should be in gray lists */
677 if (keepinvariant(g)) {
678 assert(!iswhite(mainthread(g)));
679 assert(!iswhite(gcvalue(&g->l_registry)));
680 }
681 assert(!isdead(g, gcvalue(&g->l_registry)));
682 assert(g->sweepgc == NULL || issweepphase(g));
683 totalin = checkgrays(g);
684
685 /* check 'fixedgc' list */
686 for (o = g->fixedgc; o != NULL; o = o->next) {
687 assert(o->tt == LUA_VSHRSTR && isgray(o) && getage(o) == G_OLD);
688 }
689
690 /* check 'allgc' list */
691 maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);
692 totalshould = checklist(g, maybedead, 0, g->allgc,
693 g->survival, g->old1, g->reallyold);
694
695 /* check 'finobj' list */
696 totalshould += checklist(g, 0, 1, g->finobj,
697 g->finobjsur, g->finobjold1, g->finobjrold);
698
699 /* check 'tobefnz' list */
700 for (o = g->tobefnz; o != NULL; o = o->next) {
701 checkobject(g, o, 0, G_NEW);
702 incifingray(g, o, &totalshould);
703 assert(tofinalize(o));
704 assert(o->tt == LUA_VUSERDATA || o->tt == LUA_VTABLE);
705 }
706 if (keepinvariant(g))
707 assert(totalin == totalshould);
708 return 0;
709}
710
711/* }====================================================== */
712
713
714
715/*
716** {======================================================
717** Disassembler
718** =======================================================
719*/
720
721
722static char *buildop (Proto *p, int pc, char *buff) {
723 char *obuff = buff;
724 Instruction i = p->code[pc];
725 OpCode o = GET_OPCODE(i);
726 const char *name = opnames[o];
727 int line = luaG_getfuncline(p, pc);
728 int lineinfo = (p->lineinfo != NULL) ? p->lineinfo[pc] : 0;
729 if (lineinfo == ABSLINEINFO)
730 buff += sprintf(buff, "(__");
731 else
732 buff += sprintf(buff, "(%2d", lineinfo);
733 buff += sprintf(buff, " - %4d) %4d - ", line, pc);
734 switch (getOpMode(o)) {
735 case iABC:
736 sprintf(buff, "%-12s%4d %4d %4d%s", name,
737 GETARG_A(i), GETARG_B(i), GETARG_C(i),
738 GETARG_k(i) ? " (k)" : "");
739 break;
740 case ivABC:
741 sprintf(buff, "%-12s%4d %4d %4d%s", name,
742 GETARG_A(i), GETARG_vB(i), GETARG_vC(i),
743 GETARG_k(i) ? " (k)" : "");
744 break;
745 case iABx:
746 sprintf(buff, "%-12s%4d %4d", name, GETARG_A(i), GETARG_Bx(i));
747 break;
748 case iAsBx:
749 sprintf(buff, "%-12s%4d %4d", name, GETARG_A(i), GETARG_sBx(i));
750 break;
751 case iAx:
752 sprintf(buff, "%-12s%4d", name, GETARG_Ax(i));
753 break;
754 case isJ:
755 sprintf(buff, "%-12s%4d", name, GETARG_sJ(i));
756 break;
757 }
758 return obuff;
759}
760
761
762#if 0
763void luaI_printcode (Proto *pt, int size) {
764 int pc;
765 for (pc=0; pc<size; pc++) {
766 char buff[100];
767 printf("%s\n", buildop(pt, pc, buff));
768 }
769 printf("-------\n");
770}
771
772
773void luaI_printinst (Proto *pt, int pc) {
774 char buff[100];
775 printf("%s\n", buildop(pt, pc, buff));
776}
777#endif
778
779
780static int listcode (lua_State *L) {
781 int pc;
782 Proto *p;
783 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
784 1, "Lua function expected");
785 p = getproto(obj_at(L, 1));
786 lua_newtable(L);
787 setnameval(L, "maxstack", p->maxstacksize);
788 setnameval(L, "numparams", p->numparams);
789 for (pc=0; pc<p->sizecode; pc++) {
790 char buff[100];
791 lua_pushinteger(L, pc+1);
792 lua_pushstring(L, buildop(p, pc, buff));
793 lua_settable(L, -3);
794 }
795 return 1;
796}
797
798
799static int printcode (lua_State *L) {
800 int pc;
801 Proto *p;
802 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
803 1, "Lua function expected");
804 p = getproto(obj_at(L, 1));
805 printf("maxstack: %d\n", p->maxstacksize);
806 printf("numparams: %d\n", p->numparams);
807 for (pc=0; pc<p->sizecode; pc++) {
808 char buff[100];
809 printf("%s\n", buildop(p, pc, buff));
810 }
811 return 0;
812}
813
814
815static int listk (lua_State *L) {
816 Proto *p;
817 int i;
818 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
819 1, "Lua function expected");
820 p = getproto(obj_at(L, 1));
821 lua_createtable(L, p->sizek, 0);
822 for (i=0; i<p->sizek; i++) {
823 pushobject(L, p->k+i);
824 lua_rawseti(L, -2, i+1);
825 }
826 return 1;
827}
828
829
830static int listabslineinfo (lua_State *L) {
831 Proto *p;
832 int i;
833 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
834 1, "Lua function expected");
835 p = getproto(obj_at(L, 1));
836 luaL_argcheck(L, p->abslineinfo != NULL, 1, "function has no debug info");
837 lua_createtable(L, 2 * p->sizeabslineinfo, 0);
838 for (i=0; i < p->sizeabslineinfo; i++) {
839 lua_pushinteger(L, p->abslineinfo[i].pc);
840 lua_rawseti(L, -2, 2 * i + 1);
841 lua_pushinteger(L, p->abslineinfo[i].line);
842 lua_rawseti(L, -2, 2 * i + 2);
843 }
844 return 1;
845}
846
847
848static int listlocals (lua_State *L) {
849 Proto *p;
850 int pc = cast_int(luaL_checkinteger(L, 2)) - 1;
851 int i = 0;
852 const char *name;
853 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
854 1, "Lua function expected");
855 p = getproto(obj_at(L, 1));
856 while ((name = luaF_getlocalname(p, cast_uint(++i), pc)) != NULL)
857 lua_pushstring(L, name);
858 return i-1;
859}
860
861/* }====================================================== */
862
863
864
865void lua_printstack (lua_State *L) {
866 int i;
867 int n = lua_gettop(L);
868 printf("stack: >>\n");
869 for (i = 1; i <= n; i++) {
870 printf("%3d: ", i);
871 lua_printvalue(s2v(L->ci->func.p + i));
872 printf("\n");
873 }
874 printf("<<\n");
875}
876
877
878int lua_printallstack (lua_State *L) {
879 StkId p;
880 int i = 1;
881 CallInfo *ci = &L->base_ci;
882 printf("stack: >>\n");
883 for (p = L->stack.p; p < L->top.p; p++) {
884 if (ci != NULL && p == ci->func.p) {
885 printf(" ---\n");
886 if (ci == L->ci)
887 ci = NULL; /* printed last frame */
888 else
889 ci = ci->next;
890 }
891 printf("%3d: ", i++);
892 lua_printvalue(s2v(p));
893 printf("\n");
894 }
895 printf("<<\n");
896 return 0;
897}
898
899
900static int get_limits (lua_State *L) {
901 lua_createtable(L, 0, 5);
902 setnameval(L, "IS32INT", LUAI_IS32INT);
903 setnameval(L, "MAXARG_Ax", MAXARG_Ax);
904 setnameval(L, "MAXARG_Bx", MAXARG_Bx);
905 setnameval(L, "OFFSET_sBx", OFFSET_sBx);
906 setnameval(L, "NUM_OPCODES", NUM_OPCODES);
907 return 1;
908}
909
910
911static int get_sizes (lua_State *L) {
912 lua_newtable(L);
913 setnameval(L, "Lua state", sizeof(lua_State));
914 setnameval(L, "global state", sizeof(global_State));
915 setnameval(L, "TValue", sizeof(TValue));
916 setnameval(L, "Node", sizeof(Node));
917 setnameval(L, "stack Value", sizeof(StackValue));
918 return 1;
919}
920
921
922static int mem_query (lua_State *L) {
923 if (lua_isnone(L, 1)) {
924 lua_pushinteger(L, cast_Integer(l_memcontrol.total));
925 lua_pushinteger(L, cast_Integer(l_memcontrol.numblocks));
926 lua_pushinteger(L, cast_Integer(l_memcontrol.maxmem));
927 return 3;
928 }
929 else if (lua_isnumber(L, 1)) {
930 unsigned long limit = cast(unsigned long, luaL_checkinteger(L, 1));
931 if (limit == 0) limit = ULONG_MAX;
932 l_memcontrol.memlimit = limit;
933 return 0;
934 }
935 else {
936 const char *t = luaL_checkstring(L, 1);
937 int i;
938 for (i = LUA_NUMTYPES - 1; i >= 0; i--) {
939 if (strcmp(t, ttypename(i)) == 0) {
940 lua_pushinteger(L, cast_Integer(l_memcontrol.objcount[i]));
941 return 1;
942 }
943 }
944 return luaL_error(L, "unknown type '%s'", t);
945 }
946}
947
948
949static int alloc_count (lua_State *L) {
950 if (lua_isnone(L, 1))
951 l_memcontrol.countlimit = cast(unsigned long, ~0L);
952 else
953 l_memcontrol.countlimit = cast(unsigned long, luaL_checkinteger(L, 1));
954 return 0;
955}
956
957
958static int alloc_failnext (lua_State *L) {
959 UNUSED(L);
960 l_memcontrol.failnext = 1;
961 return 0;
962}
963
964
965static int settrick (lua_State *L) {
966 if (ttisnil(obj_at(L, 1)))
967 l_Trick = NULL;
968 else
969 l_Trick = gcvalue(obj_at(L, 1));
970 return 0;
971}
972
973
974static int gc_color (lua_State *L) {
975 TValue *o;
976 luaL_checkany(L, 1);
977 o = obj_at(L, 1);
978 if (!iscollectable(o))
979 lua_pushstring(L, "no collectable");
980 else {
981 GCObject *obj = gcvalue(o);
982 lua_pushstring(L, isdead(G(L), obj) ? "dead" :
983 iswhite(obj) ? "white" :
984 isblack(obj) ? "black" : "gray");
985 }
986 return 1;
987}
988
989
990static int gc_age (lua_State *L) {
991 TValue *o;
992 luaL_checkany(L, 1);
993 o = obj_at(L, 1);
994 if (!iscollectable(o))
995 lua_pushstring(L, "no collectable");
996 else {
997 static const char *gennames[] = {"new", "survival", "old0", "old1",
998 "old", "touched1", "touched2"};
999 GCObject *obj = gcvalue(o);
1000 lua_pushstring(L, gennames[getage(obj)]);
1001 }
1002 return 1;
1003}
1004
1005
1006static int gc_printobj (lua_State *L) {
1007 TValue *o;
1008 luaL_checkany(L, 1);
1009 o = obj_at(L, 1);
1010 if (!iscollectable(o))
1011 printf("no collectable\n");
1012 else {
1013 GCObject *obj = gcvalue(o);
1014 printobj(G(L), obj);
1015 printf("\n");
1016 }
1017 return 0;
1018}
1019
1020
1021static const char *const statenames[] = {
1022 "propagate", "enteratomic", "atomic", "sweepallgc", "sweepfinobj",
1023 "sweeptobefnz", "sweepend", "callfin", "pause", ""};
1024
1025static int gc_state (lua_State *L) {
1026 static const int states[] = {
1027 GCSpropagate, GCSenteratomic, GCSatomic, GCSswpallgc, GCSswpfinobj,
1028 GCSswptobefnz, GCSswpend, GCScallfin, GCSpause, -1};
1029 int option = states[luaL_checkoption(L, 1, "", statenames)];
1030 global_State *g = G(L);
1031 if (option == -1) {
1032 lua_pushstring(L, statenames[g->gcstate]);
1033 return 1;
1034 }
1035 else {
1036 if (g->gckind != KGC_INC)
1037 luaL_error(L, "cannot change states in generational mode");
1038 lua_lock(L);
1039 if (option < g->gcstate) { /* must cross 'pause'? */
1040 luaC_runtilstate(L, GCSpause, 1); /* run until pause */
1041 }
1042 luaC_runtilstate(L, option, 0); /* do not skip propagation state */
1043 lua_assert(g->gcstate == option);
1044 lua_unlock(L);
1045 return 0;
1046 }
1047}
1048
1049
1050static int tracinggc = 0;
1051void luai_tracegctest (lua_State *L, int first) {
1052 if (!tracinggc) return;
1053 else {
1054 global_State *g = G(L);
1055 lua_unlock(L);
1056 g->gcstp = GCSTPGC;
1057 lua_checkstack(L, 10);
1058 lua_getfield(L, LUA_REGISTRYINDEX, "tracegc");
1059 lua_pushboolean(L, first);
1060 lua_call(L, 1, 0);
1061 g->gcstp = 0;
1062 lua_lock(L);
1063 }
1064}
1065
1066
1067static int tracegc (lua_State *L) {
1068 if (lua_isnil(L, 1))
1069 tracinggc = 0;
1070 else {
1071 tracinggc = 1;
1072 lua_setfield(L, LUA_REGISTRYINDEX, "tracegc");
1073 }
1074 return 0;
1075}
1076
1077
1078static int hash_query (lua_State *L) {
1079 if (lua_isnone(L, 2)) {
1080 TString *ts;
1081 luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, "string expected");
1082 ts = tsvalue(obj_at(L, 1));
1083 if (ts->tt == LUA_VLNGSTR)
1084 luaS_hashlongstr(ts); /* make sure long string has a hash */
1085 lua_pushinteger(L, cast_int(ts->hash));
1086 }
1087 else {
1088 TValue *o = obj_at(L, 1);
1089 Table *t;
1090 luaL_checktype(L, 2, LUA_TTABLE);
1091 t = hvalue(obj_at(L, 2));
1092 lua_pushinteger(L, cast_Integer(luaH_mainposition(t, o) - t->node));
1093 }
1094 return 1;
1095}
1096
1097
1098static int stacklevel (lua_State *L) {
1099 int a = 0;
1100 lua_pushinteger(L, cast_Integer(L->top.p - L->stack.p));
1101 lua_pushinteger(L, stacksize(L));
1102 lua_pushinteger(L, cast_Integer(L->nCcalls));
1103 lua_pushinteger(L, L->nci);
1104 lua_pushinteger(L, (lua_Integer)(size_t)&a);
1105 return 5;
1106}
1107
1108
1109static int resetCI (lua_State *L) {
1110 CallInfo *ci = L->ci;
1111 while (ci->next != NULL) {
1112 CallInfo *tofree = ci->next;
1113 ci->next = ci->next->next;
1114 luaM_free(L, tofree);
1115 L->nci--;
1116 }
1117 return 0;
1118}
1119
1120
1121static int reallocstack (lua_State *L) {
1122 int n = cast_int(luaL_checkinteger(L, 1));
1123 lua_lock(L);
1124 luaD_reallocstack(L, cast_int(L->top.p - L->stack.p) + n, 1);
1125 lua_unlock(L);
1126 return 0;
1127}
1128
1129
1130static int table_query (lua_State *L) {
1131 const Table *t;
1132 int i = cast_int(luaL_optinteger(L, 2, -1));
1133 unsigned int asize;
1134 luaL_checktype(L, 1, LUA_TTABLE);
1135 t = hvalue(obj_at(L, 1));
1136 asize = t->asize;
1137 if (i == -1) {
1138 lua_pushinteger(L, cast_Integer(asize));
1139 lua_pushinteger(L, cast_Integer(allocsizenode(t)));
1140 lua_pushinteger(L, cast_Integer(asize > 0 ? *lenhint(t) : 0));
1141 return 3;
1142 }
1143 else if (cast_uint(i) < asize) {
1144 lua_pushinteger(L, i);
1145 if (!tagisempty(*getArrTag(t, i)))
1146 arr2obj(t, cast_uint(i), s2v(L->top.p));
1147 else
1148 setnilvalue2s(L->top.p);
1149 api_incr_top(L);
1150 lua_pushnil(L);
1151 }
1152 else if (cast_uint(i -= cast_int(asize)) < sizenode(t)) {
1153 TValue k;
1154 getnodekey(L, &k, gnode(t, i));
1155 if (!isempty(gval(gnode(t, i))) ||
1156 ttisnil(&k) ||
1157 ttisnumber(&k)) {
1158 pushobject(L, &k);
1159 }
1160 else
1161 lua_pushliteral(L, "<undef>");
1162 if (!isempty(gval(gnode(t, i))))
1163 pushobject(L, gval(gnode(t, i)));
1164 else
1165 lua_pushnil(L);
1166 lua_pushinteger(L, gnext(&t->node[i]));
1167 }
1168 return 3;
1169}
1170
1171
1172static int gc_query (lua_State *L) {
1173 global_State *g = G(L);
1174 lua_pushstring(L, g->gckind == KGC_INC ? "inc"
1175 : g->gckind == KGC_GENMAJOR ? "genmajor"
1176 : "genminor");
1177 lua_pushstring(L, statenames[g->gcstate]);
1178 lua_pushinteger(L, cast_st2S(gettotalbytes(g)));
1179 lua_pushinteger(L, cast_st2S(g->GCdebt));
1180 lua_pushinteger(L, cast_st2S(g->GCmarked));
1181 lua_pushinteger(L, cast_st2S(g->GCmajorminor));
1182 return 6;
1183}
1184
1185
1186static int test_codeparam (lua_State *L) {
1187 lua_Integer p = luaL_checkinteger(L, 1);
1188 lua_pushinteger(L, luaO_codeparam(cast_uint(p)));
1189 return 1;
1190}
1191
1192
1193static int test_applyparam (lua_State *L) {
1194 lua_Integer p = luaL_checkinteger(L, 1);
1195 lua_Integer x = luaL_checkinteger(L, 2);
1196 lua_pushinteger(L, cast_Integer(luaO_applyparam(cast_byte(p), x)));
1197 return 1;
1198}
1199
1200
1201static int string_query (lua_State *L) {
1202 stringtable *tb = &G(L)->strt;
1203 int s = cast_int(luaL_optinteger(L, 1, 0)) - 1;
1204 if (s == -1) {
1205 lua_pushinteger(L ,tb->size);
1206 lua_pushinteger(L ,tb->nuse);
1207 return 2;
1208 }
1209 else if (s < tb->size) {
1210 TString *ts;
1211 int n = 0;
1212 for (ts = tb->hash[s]; ts != NULL; ts = ts->u.hnext) {
1213 setsvalue2s(L, L->top.p, ts);
1214 api_incr_top(L);
1215 n++;
1216 }
1217 return n;
1218 }
1219 else return 0;
1220}
1221
1222
1223static int getreftable (lua_State *L) {
1224 if (lua_istable(L, 2)) /* is there a table as second argument? */
1225 return 2; /* use it as the table */
1226 else
1227 return LUA_REGISTRYINDEX; /* default is to use the register */
1228}
1229
1230
1231static int tref (lua_State *L) {
1232 int t = getreftable(L);
1233 int level = lua_gettop(L);
1234 luaL_checkany(L, 1);
1235 lua_pushvalue(L, 1);
1236 lua_pushinteger(L, luaL_ref(L, t));
1237 cast_void(level); /* to avoid warnings */
1238 lua_assert(lua_gettop(L) == level+1); /* +1 for result */
1239 return 1;
1240}
1241
1242
1243static int getref (lua_State *L) {
1244 int t = getreftable(L);
1245 int level = lua_gettop(L);
1246 lua_rawgeti(L, t, luaL_checkinteger(L, 1));
1247 cast_void(level); /* to avoid warnings */
1248 lua_assert(lua_gettop(L) == level+1);
1249 return 1;
1250}
1251
1252static int unref (lua_State *L) {
1253 int t = getreftable(L);
1254 int level = lua_gettop(L);
1255 luaL_unref(L, t, cast_int(luaL_checkinteger(L, 1)));
1256 cast_void(level); /* to avoid warnings */
1257 lua_assert(lua_gettop(L) == level);
1258 return 0;
1259}
1260
1261
1262static int upvalue (lua_State *L) {
1263 int n = cast_int(luaL_checkinteger(L, 2));
1264 luaL_checktype(L, 1, LUA_TFUNCTION);
1265 if (lua_isnone(L, 3)) {
1266 const char *name = lua_getupvalue(L, 1, n);
1267 if (name == NULL) return 0;
1268 lua_pushstring(L, name);
1269 return 2;
1270 }
1271 else {
1272 const char *name = lua_setupvalue(L, 1, n);
1273 lua_pushstring(L, name);
1274 return 1;
1275 }
1276}
1277
1278
1279static int newuserdata (lua_State *L) {
1280 size_t size = cast_sizet(luaL_optinteger(L, 1, 0));
1281 int nuv = cast_int(luaL_optinteger(L, 2, 0));
1282 char *p = cast_charp(lua_newuserdatauv(L, size, nuv));
1283 while (size--) *p++ = '\0';
1284 return 1;
1285}
1286
1287
1288static int pushuserdata (lua_State *L) {
1289 lua_Integer u = luaL_checkinteger(L, 1);
1290 lua_pushlightuserdata(L, cast_voidp(cast_sizet(u)));
1291 return 1;
1292}
1293
1294
1295static int udataval (lua_State *L) {
1296 lua_pushinteger(L, cast_st2S(cast_sizet(lua_touserdata(L, 1))));
1297 return 1;
1298}
1299
1300
1301static int doonnewstack (lua_State *L) {
1302 lua_State *L1 = lua_newthread(L);
1303 size_t l;
1304 const char *s = luaL_checklstring(L, 1, &l);
1305 int status = luaL_loadbufferx(L1, s, l, s, "t");
1306 if (status == LUA_OK)
1307 status = lua_pcall(L1, 0, 0, 0);
1308 lua_pushinteger(L, status);
1309 return 1;
1310}
1311
1312
1313static int s2d (lua_State *L) {
1314 lua_pushnumber(L, cast_num(*cast(const double *, luaL_checkstring(L, 1))));
1315 return 1;
1316}
1317
1318
1319static int d2s (lua_State *L) {
1320 double d = cast(double, luaL_checknumber(L, 1));
1321 lua_pushlstring(L, cast_charp(&d), sizeof(d));
1322 return 1;
1323}
1324
1325
1326static int num2int (lua_State *L) {
1327 lua_pushinteger(L, lua_tointeger(L, 1));
1328 return 1;
1329}
1330
1331
1332static int makeseed (lua_State *L) {
1333 lua_pushinteger(L, cast_Integer(luaL_makeseed(L)));
1334 return 1;
1335}
1336
1337
1338static int newstate (lua_State *L) {
1339 void *ud;
1340 lua_Alloc f = lua_getallocf(L, &ud);
1341 lua_State *L1 = lua_newstate(f, ud, 0);
1342 if (L1) {
1343 lua_atpanic(L1, tpanic);
1344 lua_pushlightuserdata(L, L1);
1345 }
1346 else
1347 lua_pushnil(L);
1348 return 1;
1349}
1350
1351
1352static lua_State *getstate (lua_State *L) {
1353 lua_State *L1 = cast(lua_State *, lua_touserdata(L, 1));
1354 luaL_argcheck(L, L1 != NULL, 1, "state expected");
1355 return L1;
1356}
1357
1358
1359static int loadlib (lua_State *L) {
1360 lua_State *L1 = getstate(L);
1361 int load = cast_int(luaL_checkinteger(L, 2));
1362 int preload = cast_int(luaL_checkinteger(L, 3));
1363 luaL_openselectedlibs(L1, load, preload);
1364 luaL_requiref(L1, "T", luaB_opentests, 0);
1365 lua_assert(lua_type(L1, -1) == LUA_TTABLE);
1366 /* 'requiref' should not reload module already loaded... */
1367 luaL_requiref(L1, "T", NULL, 1); /* seg. fault if it reloads */
1368 /* ...but should return the same module */
1369 lua_assert(lua_compare(L1, -1, -2, LUA_OPEQ));
1370 return 0;
1371}
1372
1373static int closestate (lua_State *L) {
1374 lua_State *L1 = getstate(L);
1375 lua_close(L1);
1376 return 0;
1377}
1378
1379static int doremote (lua_State *L) {
1380 lua_State *L1 = getstate(L);
1381 size_t lcode;
1382 const char *code = luaL_checklstring(L, 2, &lcode);
1383 int status;
1384 lua_settop(L1, 0);
1385 status = luaL_loadbufferx(L1, code, lcode, code, "t");
1386 if (status == LUA_OK)
1387 status = lua_pcall(L1, 0, LUA_MULTRET, 0);
1388 if (status != LUA_OK) {
1389 lua_pushnil(L);
1390 lua_pushstring(L, lua_tostring(L1, -1));
1391 lua_pushinteger(L, status);
1392 return 3;
1393 }
1394 else {
1395 int i = 0;
1396 while (!lua_isnone(L1, ++i))
1397 lua_pushstring(L, lua_tostring(L1, i));
1398 lua_pop(L1, i-1);
1399 return i-1;
1400 }
1401}
1402
1403
1404static int log2_aux (lua_State *L) {
1405 unsigned int x = (unsigned int)luaL_checkinteger(L, 1);
1406 lua_pushinteger(L, luaO_ceillog2(x));
1407 return 1;
1408}
1409
1410
1411struct Aux { jmp_buf jb; const char *paniccode; lua_State *L; };
1412
1413/*
1414** does a long-jump back to "main program".
1415*/
1416static int panicback (lua_State *L) {
1417 struct Aux *b;
1418 lua_checkstack(L, 1); /* open space for 'Aux' struct */
1419 lua_getfield(L, LUA_REGISTRYINDEX, "_jmpbuf"); /* get 'Aux' struct */
1420 b = (struct Aux *)lua_touserdata(L, -1);
1421 lua_pop(L, 1); /* remove 'Aux' struct */
1422 runC(b->L, L, b->paniccode); /* run optional panic code */
1423 longjmp(b->jb, 1);
1424 return 1; /* to avoid warnings */
1425}
1426
1427static int checkpanic (lua_State *L) {
1428 struct Aux b;
1429 void *ud;
1430 lua_State *L1;
1431 const char *code = luaL_checkstring(L, 1);
1432 lua_Alloc f = lua_getallocf(L, &ud);
1433 b.paniccode = luaL_optstring(L, 2, "");
1434 b.L = L;
1435 L1 = lua_newstate(f, ud, 0); /* create new state */
1436 if (L1 == NULL) { /* error? */
1437 lua_pushstring(L, MEMERRMSG);
1438 return 1;
1439 }
1440 lua_atpanic(L1, panicback); /* set its panic function */
1441 lua_pushlightuserdata(L1, &b);
1442 lua_setfield(L1, LUA_REGISTRYINDEX, "_jmpbuf"); /* store 'Aux' struct */
1443 if (setjmp(b.jb) == 0) { /* set jump buffer */
1444 runC(L, L1, code); /* run code unprotected */
1445 lua_pushliteral(L, "no errors");
1446 }
1447 else { /* error handling */
1448 /* move error message to original state */
1449 lua_pushstring(L, lua_tostring(L1, -1));
1450 }
1451 lua_close(L1);
1452 return 1;
1453}
1454
1455
1456static int externKstr (lua_State *L) {
1457 size_t len;
1458 const char *s = luaL_checklstring(L, 1, &len);
1459 lua_pushexternalstring(L, s, len, NULL, NULL);
1460 return 1;
1461}
1462
1463
1464/*
1465** Create a buffer with the content of a given string and then
1466** create an external string using that buffer. Use the allocation
1467** function from Lua to create and free the buffer.
1468*/
1469static int externstr (lua_State *L) {
1470 size_t len;
1471 const char *s = luaL_checklstring(L, 1, &len);
1472 void *ud;
1473 lua_Alloc allocf = lua_getallocf(L, &ud); /* get allocation function */
1474 /* create the buffer */
1475 char *buff = cast_charp((*allocf)(ud, NULL, 0, len + 1));
1476 if (buff == NULL) { /* memory error? */
1477 lua_pushliteral(L, "not enough memory");
1478 lua_error(L); /* raise a memory error */
1479 }
1480 /* copy string content to buffer, including ending 0 */
1481 memcpy(buff, s, (len + 1) * sizeof(char));
1482 /* create external string */
1483 lua_pushexternalstring(L, buff, len, allocf, ud);
1484 return 1;
1485}
1486
1487
1488/*
1489** {====================================================================
1490** function to test the API with C. It interprets a kind of assembler
1491** language with calls to the API, so the test can be driven by Lua code
1492** =====================================================================
1493*/
1494
1495
1496static void sethookaux (lua_State *L, int mask, int count, const char *code);
1497
1498static const char *const delimits = " \t\n,;";
1499
1500static void skip (const char **pc) {
1501 for (;;) {
1502 if (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
1503 else if (**pc == '#') { /* comment? */
1504 while (**pc != '\n' && **pc != '\0') (*pc)++; /* until end-of-line */
1505 }
1506 else break;
1507 }
1508}
1509
1510static int getnum_aux (lua_State *L, lua_State *L1, const char **pc) {
1511 int res = 0;
1512 int sig = 1;
1513 skip(pc);
1514 if (**pc == '.') {
1515 res = cast_int(lua_tointeger(L1, -1));
1516 lua_pop(L1, 1);
1517 (*pc)++;
1518 return res;
1519 }
1520 else if (**pc == '*') {
1521 res = lua_gettop(L1);
1522 (*pc)++;
1523 return res;
1524 }
1525 else if (**pc == '!') {
1526 (*pc)++;
1527 if (**pc == 'G')
1528 res = LUA_RIDX_GLOBALS;
1529 else if (**pc == 'M')
1530 res = LUA_RIDX_MAINTHREAD;
1531 else lua_assert(0);
1532 (*pc)++;
1533 return res;
1534 }
1535 else if (**pc == '-') {
1536 sig = -1;
1537 (*pc)++;
1538 }
1539 if (!lisdigit(cast_uchar(**pc)))
1540 luaL_error(L, "number expected (%s)", *pc);
1541 while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0';
1542 return sig*res;
1543}
1544
1545static const char *getstring_aux (lua_State *L, char *buff, const char **pc) {
1546 int i = 0;
1547 skip(pc);
1548 if (**pc == '"' || **pc == '\'') { /* quoted string? */
1549 int quote = *(*pc)++;
1550 while (**pc != quote) {
1551 if (**pc == '\0') luaL_error(L, "unfinished string in C script");
1552 buff[i++] = *(*pc)++;
1553 }
1554 (*pc)++;
1555 }
1556 else {
1557 while (**pc != '\0' && !strchr(delimits, **pc))
1558 buff[i++] = *(*pc)++;
1559 }
1560 buff[i] = '\0';
1561 return buff;
1562}
1563
1564
1565static int getindex_aux (lua_State *L, lua_State *L1, const char **pc) {
1566 skip(pc);
1567 switch (*(*pc)++) {
1568 case 'R': return LUA_REGISTRYINDEX;
1569 case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc));
1570 default: {
1571 int n;
1572 (*pc)--; /* to read again */
1573 n = getnum_aux(L, L1, pc);
1574 if (n == 0) return 0;
1575 else return lua_absindex(L1, n);
1576 }
1577 }
1578}
1579
1580
1581static const char *const statcodes[] = {"OK", "YIELD", "ERRRUN",
1582 "ERRSYNTAX", MEMERRMSG, "ERRERR"};
1583
1584/*
1585** Avoid these stat codes from being collected, to avoid possible
1586** memory error when pushing them.
1587*/
1588static void regcodes (lua_State *L) {
1589 unsigned int i;
1590 for (i = 0; i < sizeof(statcodes) / sizeof(statcodes[0]); i++) {
1591 lua_pushboolean(L, 1);
1592 lua_setfield(L, LUA_REGISTRYINDEX, statcodes[i]);
1593 }
1594}
1595
1596
1597#define EQ(s1) (strcmp(s1, inst) == 0)
1598
1599#define getnum (getnum_aux(L, L1, &pc))
1600#define getstring (getstring_aux(L, buff, &pc))
1601#define getindex (getindex_aux(L, L1, &pc))
1602
1603
1604static int testC (lua_State *L);
1605static int Cfunck (lua_State *L, int status, lua_KContext ctx);
1606
1607/*
1608** arithmetic operation encoding for 'arith' instruction
1609** LUA_OPIDIV -> \
1610** LUA_OPSHL -> <
1611** LUA_OPSHR -> >
1612** LUA_OPUNM -> _
1613** LUA_OPBNOT -> !
1614*/
1615static const char ops[] = "+-*%^/\\&|~<>_!";
1616
1617static int runC (lua_State *L, lua_State *L1, const char *pc) {
1618 char buff[300];
1619 int status = 0;
1620 if (pc == NULL) return luaL_error(L, "attempt to runC null script");
1621 for (;;) {
1622 const char *inst = getstring;
1623 if EQ("") return 0;
1624 else if EQ("absindex") {
1625 lua_pushinteger(L1, getindex);
1626 }
1627 else if EQ("append") {
1628 int t = getindex;
1629 int i = cast_int(lua_rawlen(L1, t));
1630 lua_rawseti(L1, t, i + 1);
1631 }
1632 else if EQ("arith") {
1633 int op;
1634 skip(&pc);
1635 op = cast_int(strchr(ops, *pc++) - ops);
1636 lua_arith(L1, op);
1637 }
1638 else if EQ("call") {
1639 int narg = getnum;
1640 int nres = getnum;
1641 lua_call(L1, narg, nres);
1642 }
1643 else if EQ("callk") {
1644 int narg = getnum;
1645 int nres = getnum;
1646 int i = getindex;
1647 lua_callk(L1, narg, nres, i, Cfunck);
1648 }
1649 else if EQ("checkstack") {
1650 int sz = getnum;
1651 const char *msg = getstring;
1652 if (*msg == '\0')
1653 msg = NULL; /* to test 'luaL_checkstack' with no message */
1654 luaL_checkstack(L1, sz, msg);
1655 }
1656 else if EQ("rawcheckstack") {
1657 int sz = getnum;
1658 lua_pushboolean(L1, lua_checkstack(L1, sz));
1659 }
1660 else if EQ("compare") {
1661 const char *opt = getstring; /* EQ, LT, or LE */
1662 int op = (opt[0] == 'E') ? LUA_OPEQ
1663 : (opt[1] == 'T') ? LUA_OPLT : LUA_OPLE;
1664 int a = getindex;
1665 int b = getindex;
1666 lua_pushboolean(L1, lua_compare(L1, a, b, op));
1667 }
1668 else if EQ("concat") {
1669 lua_concat(L1, getnum);
1670 }
1671 else if EQ("copy") {
1672 int f = getindex;
1673 lua_copy(L1, f, getindex);
1674 }
1675 else if EQ("func2num") {
1676 lua_CFunction func = lua_tocfunction(L1, getindex);
1677 lua_pushinteger(L1, cast_st2S(cast_sizet(func)));
1678 }
1679 else if EQ("getfield") {
1680 int t = getindex;
1681 int tp = lua_getfield(L1, t, getstring);
1682 lua_assert(tp == lua_type(L1, -1));
1683 }
1684 else if EQ("getglobal") {
1685 lua_getglobal(L1, getstring);
1686 }
1687 else if EQ("getmetatable") {
1688 if (lua_getmetatable(L1, getindex) == 0)
1689 lua_pushnil(L1);
1690 }
1691 else if EQ("gettable") {
1692 int tp = lua_gettable(L1, getindex);
1693 lua_assert(tp == lua_type(L1, -1));
1694 }
1695 else if EQ("gettop") {
1696 lua_pushinteger(L1, lua_gettop(L1));
1697 }
1698 else if EQ("gsub") {
1699 int a = getnum; int b = getnum; int c = getnum;
1700 luaL_gsub(L1, lua_tostring(L1, a),
1701 lua_tostring(L1, b),
1702 lua_tostring(L1, c));
1703 }
1704 else if EQ("insert") {
1705 lua_insert(L1, getnum);
1706 }
1707 else if EQ("iscfunction") {
1708 lua_pushboolean(L1, lua_iscfunction(L1, getindex));
1709 }
1710 else if EQ("isfunction") {
1711 lua_pushboolean(L1, lua_isfunction(L1, getindex));
1712 }
1713 else if EQ("isnil") {
1714 lua_pushboolean(L1, lua_isnil(L1, getindex));
1715 }
1716 else if EQ("isnull") {
1717 lua_pushboolean(L1, lua_isnone(L1, getindex));
1718 }
1719 else if EQ("isnumber") {
1720 lua_pushboolean(L1, lua_isnumber(L1, getindex));
1721 }
1722 else if EQ("isstring") {
1723 lua_pushboolean(L1, lua_isstring(L1, getindex));
1724 }
1725 else if EQ("istable") {
1726 lua_pushboolean(L1, lua_istable(L1, getindex));
1727 }
1728 else if EQ("isudataval") {
1729 lua_pushboolean(L1, lua_islightuserdata(L1, getindex));
1730 }
1731 else if EQ("isuserdata") {
1732 lua_pushboolean(L1, lua_isuserdata(L1, getindex));
1733 }
1734 else if EQ("len") {
1735 lua_len(L1, getindex);
1736 }
1737 else if EQ("Llen") {
1738 lua_pushinteger(L1, luaL_len(L1, getindex));
1739 }
1740 else if EQ("loadfile") {
1741 luaL_loadfilex(L1, luaL_checkstring(L1, getnum), "t");
1742 }
1743 else if EQ("loadstring") {
1744 size_t slen;
1745 const char *s = luaL_checklstring(L1, getnum, &slen);
1746 const char *name = getstring;
1747 const char *mode = getstring;
1748 luaL_loadbufferx(L1, s, slen, name, mode);
1749 }
1750 else if EQ("newmetatable") {
1751 lua_pushboolean(L1, luaL_newmetatable(L1, getstring));
1752 }
1753 else if EQ("newtable") {
1754 lua_newtable(L1);
1755 }
1756 else if EQ("newthread") {
1757 lua_newthread(L1);
1758 }
1759 else if EQ("resetthread") {
1760 lua_pushinteger(L1, lua_resetthread(L1)); /* deprecated */
1761 }
1762 else if EQ("newuserdata") {
1763 lua_newuserdata(L1, cast_sizet(getnum));
1764 }
1765 else if EQ("next") {
1766 lua_next(L1, -2);
1767 }
1768 else if EQ("objsize") {
1769 lua_pushinteger(L1, l_castU2S(lua_rawlen(L1, getindex)));
1770 }
1771 else if EQ("pcall") {
1772 int narg = getnum;
1773 int nres = getnum;
1774 status = lua_pcall(L1, narg, nres, getnum);
1775 }
1776 else if EQ("pcallk") {
1777 int narg = getnum;
1778 int nres = getnum;
1779 int i = getindex;
1780 status = lua_pcallk(L1, narg, nres, 0, i, Cfunck);
1781 }
1782 else if EQ("pop") {
1783 lua_pop(L1, getnum);
1784 }
1785 else if EQ("printstack") {
1786 int n = getnum;
1787 if (n != 0) {
1788 lua_printvalue(s2v(L->ci->func.p + n));
1789 printf("\n");
1790 }
1791 else lua_printstack(L1);
1792 }
1793 else if EQ("print") {
1794 const char *msg = getstring;
1795 printf("%s\n", msg);
1796 }
1797 else if EQ("warningC") {
1798 const char *msg = getstring;
1799 lua_warning(L1, msg, 1);
1800 }
1801 else if EQ("warning") {
1802 const char *msg = getstring;
1803 lua_warning(L1, msg, 0);
1804 }
1805 else if EQ("pushbool") {
1806 lua_pushboolean(L1, getnum);
1807 }
1808 else if EQ("pushcclosure") {
1809 lua_pushcclosure(L1, testC, getnum);
1810 }
1811 else if EQ("pushint") {
1812 lua_pushinteger(L1, getnum);
1813 }
1814 else if EQ("pushnil") {
1815 lua_pushnil(L1);
1816 }
1817 else if EQ("pushnum") {
1818 lua_pushnumber(L1, (lua_Number)getnum);
1819 }
1820 else if EQ("pushstatus") {
1821 lua_pushstring(L1, statcodes[status]);
1822 }
1823 else if EQ("pushstring") {
1824 lua_pushstring(L1, getstring);
1825 }
1826 else if EQ("pushupvalueindex") {
1827 lua_pushinteger(L1, lua_upvalueindex(getnum));
1828 }
1829 else if EQ("pushvalue") {
1830 lua_pushvalue(L1, getindex);
1831 }
1832 else if EQ("pushfstringI") {
1833 lua_pushfstring(L1, lua_tostring(L, -2), (int)lua_tointeger(L, -1));
1834 }
1835 else if EQ("pushfstringS") {
1836 lua_pushfstring(L1, lua_tostring(L, -2), lua_tostring(L, -1));
1837 }
1838 else if EQ("pushfstringP") {
1839 lua_pushfstring(L1, lua_tostring(L, -2), lua_topointer(L, -1));
1840 }
1841 else if EQ("rawget") {
1842 int t = getindex;
1843 lua_rawget(L1, t);
1844 }
1845 else if EQ("rawgeti") {
1846 int t = getindex;
1847 lua_rawgeti(L1, t, getnum);
1848 }
1849 else if EQ("rawgetp") {
1850 int t = getindex;
1851 lua_rawgetp(L1, t, cast_voidp(cast_sizet(getnum)));
1852 }
1853 else if EQ("rawset") {
1854 int t = getindex;
1855 lua_rawset(L1, t);
1856 }
1857 else if EQ("rawseti") {
1858 int t = getindex;
1859 lua_rawseti(L1, t, getnum);
1860 }
1861 else if EQ("rawsetp") {
1862 int t = getindex;
1863 lua_rawsetp(L1, t, cast_voidp(cast_sizet(getnum)));
1864 }
1865 else if EQ("remove") {
1866 lua_remove(L1, getnum);
1867 }
1868 else if EQ("replace") {
1869 lua_replace(L1, getindex);
1870 }
1871 else if EQ("resume") {
1872 int i = getindex;
1873 int nres;
1874 status = lua_resume(lua_tothread(L1, i), L, getnum, &nres);
1875 }
1876 else if EQ("traceback") {
1877 const char *msg = getstring;
1878 int level = getnum;
1879 luaL_traceback(L1, L1, msg, level);
1880 }
1881 else if EQ("threadstatus") {
1882 lua_pushstring(L1, statcodes[lua_status(L1)]);
1883 }
1884 else if EQ("alloccount") {
1885 l_memcontrol.countlimit = cast_uint(getnum);
1886 }
1887 else if EQ("return") {
1888 int n = getnum;
1889 if (L1 != L) {
1890 int i;
1891 for (i = 0; i < n; i++) {
1892 int idx = -(n - i);
1893 switch (lua_type(L1, idx)) {
1894 case LUA_TBOOLEAN:
1895 lua_pushboolean(L, lua_toboolean(L1, idx));
1896 break;
1897 default:
1898 lua_pushstring(L, lua_tostring(L1, idx));
1899 break;
1900 }
1901 }
1902 }
1903 return n;
1904 }
1905 else if EQ("rotate") {
1906 int i = getindex;
1907 lua_rotate(L1, i, getnum);
1908 }
1909 else if EQ("setfield") {
1910 int t = getindex;
1911 const char *s = getstring;
1912 lua_setfield(L1, t, s);
1913 }
1914 else if EQ("seti") {
1915 int t = getindex;
1916 lua_seti(L1, t, getnum);
1917 }
1918 else if EQ("setglobal") {
1919 const char *s = getstring;
1920 lua_setglobal(L1, s);
1921 }
1922 else if EQ("sethook") {
1923 int mask = getnum;
1924 int count = getnum;
1925 const char *s = getstring;
1926 sethookaux(L1, mask, count, s);
1927 }
1928 else if EQ("setmetatable") {
1929 int idx = getindex;
1930 lua_setmetatable(L1, idx);
1931 }
1932 else if EQ("settable") {
1933 lua_settable(L1, getindex);
1934 }
1935 else if EQ("settop") {
1936 lua_settop(L1, getnum);
1937 }
1938 else if EQ("testudata") {
1939 int i = getindex;
1940 lua_pushboolean(L1, luaL_testudata(L1, i, getstring) != NULL);
1941 }
1942 else if EQ("error") {
1943 lua_error(L1);
1944 }
1945 else if EQ("abort") {
1946 abort();
1947 }
1948 else if EQ("throw") {
1949#if defined(__cplusplus)
1950static struct X { int x; } x;
1951 throw x;
1952#else
1953 luaL_error(L1, "C++");
1954#endif
1955 break;
1956 }
1957 else if EQ("tobool") {
1958 lua_pushboolean(L1, lua_toboolean(L1, getindex));
1959 }
1960 else if EQ("tocfunction") {
1961 lua_pushcfunction(L1, lua_tocfunction(L1, getindex));
1962 }
1963 else if EQ("tointeger") {
1964 lua_pushinteger(L1, lua_tointeger(L1, getindex));
1965 }
1966 else if EQ("tonumber") {
1967 lua_pushnumber(L1, lua_tonumber(L1, getindex));
1968 }
1969 else if EQ("topointer") {
1970 lua_pushlightuserdata(L1, cast_voidp(lua_topointer(L1, getindex)));
1971 }
1972 else if EQ("touserdata") {
1973 lua_pushlightuserdata(L1, lua_touserdata(L1, getindex));
1974 }
1975 else if EQ("tostring") {
1976 const char *s = lua_tostring(L1, getindex);
1977 const char *s1 = lua_pushstring(L1, s);
1978 cast_void(s1); /* to avoid warnings */
1979 lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);
1980 }
1981 else if EQ("Ltolstring") {
1982 luaL_tolstring(L1, getindex, NULL);
1983 }
1984 else if EQ("type") {
1985 lua_pushstring(L1, luaL_typename(L1, getnum));
1986 }
1987 else if EQ("xmove") {
1988 int f = getindex;
1989 int t = getindex;
1990 lua_State *fs = (f == 0) ? L1 : lua_tothread(L1, f);
1991 lua_State *ts = (t == 0) ? L1 : lua_tothread(L1, t);
1992 int n = getnum;
1993 if (n == 0) n = lua_gettop(fs);
1994 lua_xmove(fs, ts, n);
1995 }
1996 else if EQ("isyieldable") {
1997 lua_pushboolean(L1, lua_isyieldable(lua_tothread(L1, getindex)));
1998 }
1999 else if EQ("yield") {
2000 return lua_yield(L1, getnum);
2001 }
2002 else if EQ("yieldk") {
2003 int nres = getnum;
2004 int i = getindex;
2005 return lua_yieldk(L1, nres, i, Cfunck);
2006 }
2007 else if EQ("toclose") {
2008 lua_toclose(L1, getnum);
2009 }
2010 else if EQ("closeslot") {
2011 lua_closeslot(L1, getnum);
2012 }
2013 else if EQ("argerror") {
2014 int arg = getnum;
2015 luaL_argerror(L1, arg, getstring);
2016 }
2017 else luaL_error(L, "unknown instruction %s", buff);
2018 }
2019 return 0;
2020}
2021
2022
2023static int testC (lua_State *L) {
2024 lua_State *L1;
2025 const char *pc;
2026 if (lua_isuserdata(L, 1)) {
2027 L1 = getstate(L);
2028 pc = luaL_checkstring(L, 2);
2029 }
2030 else if (lua_isthread(L, 1)) {
2031 L1 = lua_tothread(L, 1);
2032 pc = luaL_checkstring(L, 2);
2033 }
2034 else {
2035 L1 = L;
2036 pc = luaL_checkstring(L, 1);
2037 }
2038 return runC(L, L1, pc);
2039}
2040
2041
2042static int Cfunc (lua_State *L) {
2043 return runC(L, L, lua_tostring(L, lua_upvalueindex(1)));
2044}
2045
2046
2047static int Cfunck (lua_State *L, int status, lua_KContext ctx) {
2048 lua_pushstring(L, statcodes[status]);
2049 lua_setglobal(L, "status");
2050 lua_pushinteger(L, cast_Integer(ctx));
2051 lua_setglobal(L, "ctx");
2052 return runC(L, L, lua_tostring(L, cast_int(ctx)));
2053}
2054
2055
2056static int makeCfunc (lua_State *L) {
2057 luaL_checkstring(L, 1);
2058 lua_pushcclosure(L, Cfunc, lua_gettop(L));
2059 return 1;
2060}
2061
2062
2063/* }====================================================== */
2064
2065
2066/*
2067** {======================================================
2068** tests for C hooks
2069** =======================================================
2070*/
2071
2072/*
2073** C hook that runs the C script stored in registry.C_HOOK[L]
2074*/
2075static void Chook (lua_State *L, lua_Debug *ar) {
2076 const char *scpt;
2077 const char *const events [] = {"call", "ret", "line", "count", "tailcall"};
2078 lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK");
2079 lua_pushlightuserdata(L, L);
2080 lua_gettable(L, -2); /* get C_HOOK[L] (script saved by sethookaux) */
2081 scpt = lua_tostring(L, -1); /* not very religious (string will be popped) */
2082 lua_pop(L, 2); /* remove C_HOOK and script */
2083 lua_pushstring(L, events[ar->event]); /* may be used by script */
2084 lua_pushinteger(L, ar->currentline); /* may be used by script */
2085 runC(L, L, scpt); /* run script from C_HOOK[L] */
2086}
2087
2088
2089/*
2090** sets 'registry.C_HOOK[L] = scpt' and sets 'Chook' as a hook
2091*/
2092static void sethookaux (lua_State *L, int mask, int count, const char *scpt) {
2093 if (*scpt == '\0') { /* no script? */
2094 lua_sethook(L, NULL, 0, 0); /* turn off hooks */
2095 return;
2096 }
2097 lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* get C_HOOK table */
2098 if (!lua_istable(L, -1)) { /* no hook table? */
2099 lua_pop(L, 1); /* remove previous value */
2100 lua_newtable(L); /* create new C_HOOK table */
2101 lua_pushvalue(L, -1);
2102 lua_setfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* register it */
2103 }
2104 lua_pushlightuserdata(L, L);
2105 lua_pushstring(L, scpt);
2106 lua_settable(L, -3); /* C_HOOK[L] = script */
2107 lua_sethook(L, Chook, mask, count);
2108}
2109
2110
2111static int sethook (lua_State *L) {
2112 if (lua_isnoneornil(L, 1))
2113 lua_sethook(L, NULL, 0, 0); /* turn off hooks */
2114 else {
2115 const char *scpt = luaL_checkstring(L, 1);
2116 const char *smask = luaL_checkstring(L, 2);
2117 int count = cast_int(luaL_optinteger(L, 3, 0));
2118 int mask = 0;
2119 if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
2120 if (strchr(smask, 'r')) mask |= LUA_MASKRET;
2121 if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
2122 if (count > 0) mask |= LUA_MASKCOUNT;
2123 sethookaux(L, mask, count, scpt);
2124 }
2125 return 0;
2126}
2127
2128
2129static int coresume (lua_State *L) {
2130 int status, nres;
2131 lua_State *co = lua_tothread(L, 1);
2132 luaL_argcheck(L, co, 1, "coroutine expected");
2133 status = lua_resume(co, L, 0, &nres);
2134 if (status != LUA_OK && status != LUA_YIELD) {
2135 lua_pushboolean(L, 0);
2136 lua_insert(L, -2);
2137 return 2; /* return false + error message */
2138 }
2139 else {
2140 lua_pushboolean(L, 1);
2141 return 1;
2142 }
2143}
2144
2145#if !defined(LUA_USE_POSIX)
2146
2147#define nonblock NULL
2148
2149#else
2150
2151#include <unistd.h>
2152#include <fcntl.h>
2153
2154static int nonblock (lua_State *L) {
2155 FILE *f = cast(luaL_Stream*, luaL_checkudata(L, 1, LUA_FILEHANDLE))->f;
2156 int fd = fileno(f);
2157 int flags = fcntl(fd, F_GETFL, 0);
2158 flags |= O_NONBLOCK;
2159 fcntl(fd, F_SETFL, flags);
2160 return 0;
2161}
2162#endif
2163
2164/* }====================================================== */
2165
2166
2167
2168static const struct luaL_Reg tests_funcs[] = {
2169 {"checkmemory", lua_checkmemory},
2170 {"closestate", closestate},
2171 {"d2s", d2s},
2172 {"doonnewstack", doonnewstack},
2173 {"doremote", doremote},
2174 {"gccolor", gc_color},
2175 {"gcage", gc_age},
2176 {"gcstate", gc_state},
2177 {"tracegc", tracegc},
2178 {"pobj", gc_printobj},
2179 {"getref", getref},
2180 {"hash", hash_query},
2181 {"log2", log2_aux},
2182 {"limits", get_limits},
2183 {"listcode", listcode},
2184 {"printcode", printcode},
2185 {"printallstack", lua_printallstack},
2186 {"listk", listk},
2187 {"listabslineinfo", listabslineinfo},
2188 {"listlocals", listlocals},
2189 {"loadlib", loadlib},
2190 {"checkpanic", checkpanic},
2191 {"newstate", newstate},
2192 {"newuserdata", newuserdata},
2193 {"num2int", num2int},
2194 {"makeseed", makeseed},
2195 {"pushuserdata", pushuserdata},
2196 {"gcquery", gc_query},
2197 {"querystr", string_query},
2198 {"querytab", table_query},
2199 {"codeparam", test_codeparam},
2200 {"applyparam", test_applyparam},
2201 {"ref", tref},
2202 {"resume", coresume},
2203 {"s2d", s2d},
2204 {"sethook", sethook},
2205 {"stacklevel", stacklevel},
2206 {"resetCI", resetCI},
2207 {"reallocstack", reallocstack},
2208 {"sizes", get_sizes},
2209 {"testC", testC},
2210 {"makeCfunc", makeCfunc},
2211 {"totalmem", mem_query},
2212 {"alloccount", alloc_count},
2213 {"allocfailnext", alloc_failnext},
2214 {"trick", settrick},
2215 {"udataval", udataval},
2216 {"unref", unref},
2217 {"upvalue", upvalue},
2218 {"externKstr", externKstr},
2219 {"externstr", externstr},
2220 {"nonblock", nonblock},
2221 {NULL, NULL}
2222};
2223
2224
2225static void checkfinalmem (void) {
2226 lua_assert(l_memcontrol.numblocks == 0);
2227 lua_assert(l_memcontrol.total == 0);
2228}
2229
2230
2231int luaB_opentests (lua_State *L) {
2232 void *ud;
2233 lua_Alloc f = lua_getallocf(L, &ud);
2234 lua_atpanic(L, &tpanic);
2235 lua_setwarnf(L, &warnf, L);
2236 lua_pushboolean(L, 0);
2237 lua_setglobal(L, "_WARN"); /* _WARN = false */
2238 regcodes(L);
2239 atexit(checkfinalmem);
2240 lua_assert(f == debug_realloc && ud == cast_voidp(&l_memcontrol));
2241 lua_setallocf(L, f, ud); /* exercise this function */
2242 luaL_newlib(L, tests_funcs);
2243 return 1;
2244}
2245
2246#endif
2247