ltests.c 52 KB

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