ltests.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  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_NUMTYPES) ? 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_GENMINOR)
  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) &&
  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. ** * 'touched1' objects must be gray.
  438. */
  439. static void checkobject (global_State *g, GCObject *o, int maybedead,
  440. int listage) {
  441. if (isdead(g, o))
  442. assert(maybedead);
  443. else {
  444. assert(g->gcstate != GCSpause || iswhite(o));
  445. if (g->gckind == KGC_GENMINOR) { /* generational mode? */
  446. assert(getage(o) >= listage);
  447. if (isold(o)) {
  448. assert(!iswhite(o));
  449. assert(isblack(o) ||
  450. getage(o) == G_TOUCHED1 ||
  451. getage(o) == G_OLD0 ||
  452. o->tt == LUA_VTHREAD ||
  453. (o->tt == LUA_VUPVAL && upisopen(gco2upv(o))));
  454. }
  455. assert(getage(o) != G_TOUCHED1 || isgray(o));
  456. }
  457. checkrefs(g, o);
  458. }
  459. }
  460. static l_obj checkgraylist (global_State *g, GCObject *o) {
  461. int total = 0; /* count number of elements in the list */
  462. cast_void(g); /* better to keep it if we need to print an object */
  463. while (o) {
  464. assert(!!isgray(o) ^ (getage(o) == G_TOUCHED2));
  465. assert(!testbit(o->marked, TESTBIT));
  466. if (keepinvariant(g))
  467. l_setbit(o->marked, TESTBIT); /* mark that object is in a gray list */
  468. total++;
  469. switch (o->tt) {
  470. case LUA_VTABLE: o = gco2t(o)->gclist; break;
  471. case LUA_VLCL: o = gco2lcl(o)->gclist; break;
  472. case LUA_VCCL: o = gco2ccl(o)->gclist; break;
  473. case LUA_VTHREAD: o = gco2th(o)->gclist; break;
  474. case LUA_VPROTO: o = gco2p(o)->gclist; break;
  475. case LUA_VUSERDATA:
  476. assert(gco2u(o)->nuvalue > 0);
  477. o = gco2u(o)->gclist;
  478. break;
  479. default: assert(0); /* other objects cannot be in a gray list */
  480. }
  481. }
  482. return total;
  483. }
  484. /*
  485. ** Check objects in gray lists.
  486. */
  487. static l_obj checkgrays (global_State *g) {
  488. int total = 0; /* count number of elements in all lists */
  489. if (!keepinvariant(g)) return total;
  490. total += checkgraylist(g, g->gray);
  491. total += checkgraylist(g, g->grayagain);
  492. total += checkgraylist(g, g->weak);
  493. total += checkgraylist(g, g->allweak);
  494. total += checkgraylist(g, g->ephemeron);
  495. return total;
  496. }
  497. /*
  498. ** Check whether 'o' should be in a gray list. If so, increment
  499. ** 'count' and check its TESTBIT. (It must have been previously set by
  500. ** 'checkgraylist'.)
  501. */
  502. static void incifingray (global_State *g, GCObject *o, l_obj *count) {
  503. if (!keepinvariant(g))
  504. return; /* gray lists not being kept in these phases */
  505. if (o->tt == LUA_VUPVAL) {
  506. /* only open upvalues can be gray */
  507. assert(!isgray(o) || upisopen(gco2upv(o)));
  508. return; /* upvalues are never in gray lists */
  509. }
  510. /* these are the ones that must be in gray lists */
  511. if (isgray(o) || getage(o) == G_TOUCHED2) {
  512. (*count)++;
  513. assert(testbit(o->marked, TESTBIT));
  514. resetbit(o->marked, TESTBIT); /* prepare for next cycle */
  515. }
  516. }
  517. static l_obj checklist (global_State *g, int maybedead, int tof,
  518. GCObject *newl, GCObject *survival, GCObject *old, GCObject *reallyold) {
  519. GCObject *o;
  520. l_obj total = 0; /* number of object that should be in gray lists */
  521. for (o = newl; o != survival; o = o->next) {
  522. checkobject(g, o, maybedead, G_NEW);
  523. incifingray(g, o, &total);
  524. assert(!tof == !tofinalize(o));
  525. }
  526. for (o = survival; o != old; o = o->next) {
  527. checkobject(g, o, 0, G_SURVIVAL);
  528. incifingray(g, o, &total);
  529. assert(!tof == !tofinalize(o));
  530. }
  531. for (o = old; o != reallyold; o = o->next) {
  532. checkobject(g, o, 0, G_OLD1);
  533. incifingray(g, o, &total);
  534. assert(!tof == !tofinalize(o));
  535. }
  536. for (o = reallyold; o != NULL; o = o->next) {
  537. checkobject(g, o, 0, G_OLD);
  538. incifingray(g, o, &total);
  539. assert(!tof == !tofinalize(o));
  540. }
  541. return total;
  542. }
  543. int lua_checkmemory (lua_State *L) {
  544. global_State *g = G(L);
  545. GCObject *o;
  546. int maybedead;
  547. l_obj totalin; /* total of objects that are in gray lists */
  548. l_obj totalshould; /* total of objects that should be in gray lists */
  549. if (keepinvariant(g)) {
  550. assert(!iswhite(g->mainthread));
  551. assert(!iswhite(gcvalue(&g->l_registry)));
  552. }
  553. assert(!isdead(g, gcvalue(&g->l_registry)));
  554. assert(g->sweepgc == NULL || issweepphase(g));
  555. totalin = checkgrays(g);
  556. /* check 'fixedgc' list */
  557. for (o = g->fixedgc; o != NULL; o = o->next) {
  558. assert(o->tt == LUA_VSHRSTR && isgray(o) && getage(o) == G_OLD);
  559. }
  560. /* check 'allgc' list */
  561. maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);
  562. totalshould = checklist(g, maybedead, 0, g->allgc,
  563. g->survival, g->old1, g->reallyold);
  564. /* check 'finobj' list */
  565. totalshould += checklist(g, 0, 1, g->finobj,
  566. g->finobjsur, g->finobjold1, g->finobjrold);
  567. /* check 'tobefnz' list */
  568. for (o = g->tobefnz; o != NULL; o = o->next) {
  569. checkobject(g, o, 0, G_NEW);
  570. incifingray(g, o, &totalshould);
  571. assert(tofinalize(o));
  572. assert(o->tt == LUA_VUSERDATA || o->tt == LUA_VTABLE);
  573. }
  574. if (keepinvariant(g))
  575. assert(totalin == totalshould);
  576. return 0;
  577. }
  578. /* }====================================================== */
  579. /*
  580. ** {======================================================
  581. ** Disassembler
  582. ** =======================================================
  583. */
  584. static char *buildop (Proto *p, int pc, char *buff) {
  585. char *obuff = buff;
  586. Instruction i = p->code[pc];
  587. OpCode o = GET_OPCODE(i);
  588. const char *name = opnames[o];
  589. int line = luaG_getfuncline(p, pc);
  590. int lineinfo = (p->lineinfo != NULL) ? p->lineinfo[pc] : 0;
  591. if (lineinfo == ABSLINEINFO)
  592. buff += sprintf(buff, "(__");
  593. else
  594. buff += sprintf(buff, "(%2d", lineinfo);
  595. buff += sprintf(buff, " - %4d) %4d - ", line, pc);
  596. switch (getOpMode(o)) {
  597. case iABC:
  598. sprintf(buff, "%-12s%4d %4d %4d%s", name,
  599. GETARG_A(i), GETARG_B(i), GETARG_C(i),
  600. GETARG_k(i) ? " (k)" : "");
  601. break;
  602. case iABx:
  603. sprintf(buff, "%-12s%4d %4d", name, GETARG_A(i), GETARG_Bx(i));
  604. break;
  605. case iAsBx:
  606. sprintf(buff, "%-12s%4d %4d", name, GETARG_A(i), GETARG_sBx(i));
  607. break;
  608. case iAx:
  609. sprintf(buff, "%-12s%4d", name, GETARG_Ax(i));
  610. break;
  611. case isJ:
  612. sprintf(buff, "%-12s%4d", name, GETARG_sJ(i));
  613. break;
  614. }
  615. return obuff;
  616. }
  617. #if 0
  618. void luaI_printcode (Proto *pt, int size) {
  619. int pc;
  620. for (pc=0; pc<size; pc++) {
  621. char buff[100];
  622. printf("%s\n", buildop(pt, pc, buff));
  623. }
  624. printf("-------\n");
  625. }
  626. void luaI_printinst (Proto *pt, int pc) {
  627. char buff[100];
  628. printf("%s\n", buildop(pt, pc, buff));
  629. }
  630. #endif
  631. static int listcode (lua_State *L) {
  632. int pc;
  633. Proto *p;
  634. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
  635. 1, "Lua function expected");
  636. p = getproto(obj_at(L, 1));
  637. lua_newtable(L);
  638. setnameval(L, "maxstack", p->maxstacksize);
  639. setnameval(L, "numparams", p->numparams);
  640. for (pc=0; pc<p->sizecode; pc++) {
  641. char buff[100];
  642. lua_pushinteger(L, pc+1);
  643. lua_pushstring(L, buildop(p, pc, buff));
  644. lua_settable(L, -3);
  645. }
  646. return 1;
  647. }
  648. static int printcode (lua_State *L) {
  649. int pc;
  650. Proto *p;
  651. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
  652. 1, "Lua function expected");
  653. p = getproto(obj_at(L, 1));
  654. printf("maxstack: %d\n", p->maxstacksize);
  655. printf("numparams: %d\n", p->numparams);
  656. for (pc=0; pc<p->sizecode; pc++) {
  657. char buff[100];
  658. printf("%s\n", buildop(p, pc, buff));
  659. }
  660. return 0;
  661. }
  662. static int listk (lua_State *L) {
  663. Proto *p;
  664. int i;
  665. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
  666. 1, "Lua function expected");
  667. p = getproto(obj_at(L, 1));
  668. lua_createtable(L, p->sizek, 0);
  669. for (i=0; i<p->sizek; i++) {
  670. pushobject(L, p->k+i);
  671. lua_rawseti(L, -2, i+1);
  672. }
  673. return 1;
  674. }
  675. static int listabslineinfo (lua_State *L) {
  676. Proto *p;
  677. int i;
  678. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
  679. 1, "Lua function expected");
  680. p = getproto(obj_at(L, 1));
  681. luaL_argcheck(L, p->abslineinfo != NULL, 1, "function has no debug info");
  682. lua_createtable(L, 2 * p->sizeabslineinfo, 0);
  683. for (i=0; i < p->sizeabslineinfo; i++) {
  684. lua_pushinteger(L, p->abslineinfo[i].pc);
  685. lua_rawseti(L, -2, 2 * i + 1);
  686. lua_pushinteger(L, p->abslineinfo[i].line);
  687. lua_rawseti(L, -2, 2 * i + 2);
  688. }
  689. return 1;
  690. }
  691. static int listlocals (lua_State *L) {
  692. Proto *p;
  693. int pc = cast_int(luaL_checkinteger(L, 2)) - 1;
  694. int i = 0;
  695. const char *name;
  696. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
  697. 1, "Lua function expected");
  698. p = getproto(obj_at(L, 1));
  699. while ((name = luaF_getlocalname(p, ++i, pc)) != NULL)
  700. lua_pushstring(L, name);
  701. return i-1;
  702. }
  703. /* }====================================================== */
  704. static void printstack (lua_State *L) {
  705. int i;
  706. int n = lua_gettop(L);
  707. printf("stack: >>\n");
  708. for (i = 1; i <= n; i++) {
  709. printf("%3d: %s\n", i, luaL_tolstring(L, i, NULL));
  710. lua_pop(L, 1);
  711. }
  712. printf("<<\n");
  713. }
  714. static int get_limits (lua_State *L) {
  715. lua_createtable(L, 0, 6);
  716. setnameval(L, "IS32INT", LUAI_IS32INT);
  717. setnameval(L, "MAXARG_Ax", MAXARG_Ax);
  718. setnameval(L, "MAXARG_Bx", MAXARG_Bx);
  719. setnameval(L, "OFFSET_sBx", OFFSET_sBx);
  720. setnameval(L, "LFPF", LFIELDS_PER_FLUSH);
  721. setnameval(L, "NUM_OPCODES", NUM_OPCODES);
  722. return 1;
  723. }
  724. static int mem_query (lua_State *L) {
  725. if (lua_isnone(L, 1)) {
  726. lua_pushinteger(L, l_memcontrol.total);
  727. lua_pushinteger(L, l_memcontrol.numblocks);
  728. lua_pushinteger(L, l_memcontrol.maxmem);
  729. return 3;
  730. }
  731. else if (lua_isnumber(L, 1)) {
  732. unsigned long limit = cast(unsigned long, luaL_checkinteger(L, 1));
  733. if (limit == 0) limit = ULONG_MAX;
  734. l_memcontrol.memlimit = limit;
  735. return 0;
  736. }
  737. else {
  738. const char *t = luaL_checkstring(L, 1);
  739. int i;
  740. for (i = LUA_NUMTYPES - 1; i >= 0; i--) {
  741. if (strcmp(t, ttypename(i)) == 0) {
  742. lua_pushinteger(L, l_memcontrol.objcount[i]);
  743. return 1;
  744. }
  745. }
  746. return luaL_error(L, "unknown type '%s'", t);
  747. }
  748. }
  749. static int alloc_count (lua_State *L) {
  750. if (lua_isnone(L, 1))
  751. l_memcontrol.countlimit = ~0L;
  752. else
  753. l_memcontrol.countlimit = luaL_checkinteger(L, 1);
  754. return 0;
  755. }
  756. static int alloc_failnext (lua_State *L) {
  757. UNUSED(L);
  758. l_memcontrol.failnext = 1;
  759. return 0;
  760. }
  761. static int settrick (lua_State *L) {
  762. if (ttisnil(obj_at(L, 1)))
  763. l_Trick = NULL;
  764. else
  765. l_Trick = gcvalue(obj_at(L, 1));
  766. return 0;
  767. }
  768. static int gc_color (lua_State *L) {
  769. TValue *o;
  770. luaL_checkany(L, 1);
  771. o = obj_at(L, 1);
  772. if (!iscollectable(o))
  773. lua_pushstring(L, "no collectable");
  774. else {
  775. GCObject *obj = gcvalue(o);
  776. lua_pushstring(L, isdead(G(L), obj) ? "dead" :
  777. iswhite(obj) ? "white" :
  778. isblack(obj) ? "black" : "gray");
  779. }
  780. return 1;
  781. }
  782. static int gc_age (lua_State *L) {
  783. TValue *o;
  784. luaL_checkany(L, 1);
  785. o = obj_at(L, 1);
  786. if (!iscollectable(o))
  787. lua_pushstring(L, "no collectable");
  788. else {
  789. static const char *gennames[] = {"new", "survival", "old0", "old1",
  790. "old", "touched1", "touched2"};
  791. GCObject *obj = gcvalue(o);
  792. lua_pushstring(L, gennames[getage(obj)]);
  793. }
  794. return 1;
  795. }
  796. static int gc_printobj (lua_State *L) {
  797. TValue *o;
  798. luaL_checkany(L, 1);
  799. o = obj_at(L, 1);
  800. if (!iscollectable(o))
  801. printf("no collectable\n");
  802. else {
  803. GCObject *obj = gcvalue(o);
  804. printobj(G(L), obj);
  805. printf("\n");
  806. }
  807. return 0;
  808. }
  809. static int gc_state (lua_State *L) {
  810. static const char *statenames[] = {
  811. "propagate", "atomic", "sweepallgc", "sweepfinobj",
  812. "sweeptobefnz", "sweepend", "callfin", "pause", ""};
  813. static const int states[] = {
  814. GCSpropagate, GCSenteratomic, GCSswpallgc, GCSswpfinobj,
  815. GCSswptobefnz, GCSswpend, GCScallfin, GCSpause, -1};
  816. int option = states[luaL_checkoption(L, 1, "", statenames)];
  817. if (option == -1) {
  818. lua_pushstring(L, statenames[G(L)->gcstate]);
  819. return 1;
  820. }
  821. else {
  822. global_State *g = G(L);
  823. if (G(L)->gckind != KGC_INC)
  824. luaL_error(L, "cannot change states in generational mode");
  825. lua_lock(L);
  826. if (option < g->gcstate) { /* must cross 'pause'? */
  827. luaC_runtilstate(L, GCSpause, 1); /* run until pause */
  828. }
  829. luaC_runtilstate(L, option, 0); /* do not skip propagation state */
  830. lua_assert(G(L)->gcstate == option);
  831. lua_unlock(L);
  832. return 0;
  833. }
  834. }
  835. static int hash_query (lua_State *L) {
  836. if (lua_isnone(L, 2)) {
  837. luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, "string expected");
  838. lua_pushinteger(L, tsvalue(obj_at(L, 1))->hash);
  839. }
  840. else {
  841. TValue *o = obj_at(L, 1);
  842. Table *t;
  843. luaL_checktype(L, 2, LUA_TTABLE);
  844. t = hvalue(obj_at(L, 2));
  845. lua_pushinteger(L, luaH_mainposition(t, o) - t->node);
  846. }
  847. return 1;
  848. }
  849. static int stacklevel (lua_State *L) {
  850. unsigned long a = 0;
  851. lua_pushinteger(L, (L->top.p - L->stack.p));
  852. lua_pushinteger(L, stacksize(L));
  853. lua_pushinteger(L, L->nCcalls);
  854. lua_pushinteger(L, L->nci);
  855. lua_pushinteger(L, (unsigned long)&a);
  856. return 5;
  857. }
  858. static int table_query (lua_State *L) {
  859. const Table *t;
  860. int i = cast_int(luaL_optinteger(L, 2, -1));
  861. unsigned int asize;
  862. luaL_checktype(L, 1, LUA_TTABLE);
  863. t = hvalue(obj_at(L, 1));
  864. asize = luaH_realasize(t);
  865. if (i == -1) {
  866. lua_pushinteger(L, asize);
  867. lua_pushinteger(L, allocsizenode(t));
  868. lua_pushinteger(L, t->alimit);
  869. return 3;
  870. }
  871. else if ((unsigned int)i < asize) {
  872. lua_pushinteger(L, i);
  873. arr2obj(t, i + 1, s2v(L->top.p));
  874. api_incr_top(L);
  875. lua_pushnil(L);
  876. }
  877. else if ((i -= asize) < sizenode(t)) {
  878. TValue k;
  879. getnodekey(L, &k, gnode(t, i));
  880. if (!isempty(gval(gnode(t, i))) ||
  881. ttisnil(&k) ||
  882. ttisnumber(&k)) {
  883. pushobject(L, &k);
  884. }
  885. else
  886. lua_pushliteral(L, "<undef>");
  887. pushobject(L, gval(gnode(t, i)));
  888. if (gnext(&t->node[i]) != 0)
  889. lua_pushinteger(L, gnext(&t->node[i]));
  890. else
  891. lua_pushnil(L);
  892. }
  893. return 3;
  894. }
  895. static int query_GCparams (lua_State *L) {
  896. global_State *g = G(L);
  897. lua_pushinteger(L, gettotalobjs(g));
  898. lua_pushinteger(L, g->GCdebt);
  899. lua_pushinteger(L, applygcparam(g, MINORMUL, 100));
  900. lua_pushinteger(L, applygcparam(g, MAJORMINOR, 100));
  901. lua_pushinteger(L, applygcparam(g, MINORMAJOR, 100));
  902. lua_pushinteger(L, applygcparam(g, PAUSE, 100));
  903. lua_pushinteger(L, applygcparam(g, STEPMUL, 100));
  904. lua_pushinteger(L, applygcparam(g, STEPSIZE, 100));
  905. return 8;
  906. }
  907. static int test_codeparam (lua_State *L) {
  908. lua_Integer p = luaL_checkinteger(L, 1);
  909. lua_pushinteger(L, luaO_codeparam(p));
  910. return 1;
  911. }
  912. static int test_applyparam (lua_State *L) {
  913. lua_Integer p = luaL_checkinteger(L, 1);
  914. lua_Integer x = luaL_checkinteger(L, 2);
  915. lua_pushinteger(L, luaO_applyparam(p, x));
  916. return 1;
  917. }
  918. static int string_query (lua_State *L) {
  919. stringtable *tb = &G(L)->strt;
  920. int s = cast_int(luaL_optinteger(L, 1, 0)) - 1;
  921. if (s == -1) {
  922. lua_pushinteger(L ,tb->size);
  923. lua_pushinteger(L ,tb->nuse);
  924. return 2;
  925. }
  926. else if (s < tb->size) {
  927. TString *ts;
  928. int n = 0;
  929. for (ts = tb->hash[s]; ts != NULL; ts = ts->u.hnext) {
  930. setsvalue2s(L, L->top.p, ts);
  931. api_incr_top(L);
  932. n++;
  933. }
  934. return n;
  935. }
  936. else return 0;
  937. }
  938. static int getreftable (lua_State *L) {
  939. if (lua_istable(L, 2)) /* is there a table as second argument? */
  940. return 2; /* use it as the table */
  941. else
  942. return LUA_REGISTRYINDEX; /* default is to use the register */
  943. }
  944. static int tref (lua_State *L) {
  945. int t = getreftable(L);
  946. int level = lua_gettop(L);
  947. luaL_checkany(L, 1);
  948. lua_pushvalue(L, 1);
  949. lua_pushinteger(L, luaL_ref(L, t));
  950. cast_void(level); /* to avoid warnings */
  951. lua_assert(lua_gettop(L) == level+1); /* +1 for result */
  952. return 1;
  953. }
  954. static int getref (lua_State *L) {
  955. int t = getreftable(L);
  956. int level = lua_gettop(L);
  957. lua_rawgeti(L, t, luaL_checkinteger(L, 1));
  958. cast_void(level); /* to avoid warnings */
  959. lua_assert(lua_gettop(L) == level+1);
  960. return 1;
  961. }
  962. static int unref (lua_State *L) {
  963. int t = getreftable(L);
  964. int level = lua_gettop(L);
  965. luaL_unref(L, t, cast_int(luaL_checkinteger(L, 1)));
  966. cast_void(level); /* to avoid warnings */
  967. lua_assert(lua_gettop(L) == level);
  968. return 0;
  969. }
  970. static int upvalue (lua_State *L) {
  971. int n = cast_int(luaL_checkinteger(L, 2));
  972. luaL_checktype(L, 1, LUA_TFUNCTION);
  973. if (lua_isnone(L, 3)) {
  974. const char *name = lua_getupvalue(L, 1, n);
  975. if (name == NULL) return 0;
  976. lua_pushstring(L, name);
  977. return 2;
  978. }
  979. else {
  980. const char *name = lua_setupvalue(L, 1, n);
  981. lua_pushstring(L, name);
  982. return 1;
  983. }
  984. }
  985. static int newuserdata (lua_State *L) {
  986. size_t size = cast_sizet(luaL_optinteger(L, 1, 0));
  987. int nuv = luaL_optinteger(L, 2, 0);
  988. char *p = cast_charp(lua_newuserdatauv(L, size, nuv));
  989. while (size--) *p++ = '\0';
  990. return 1;
  991. }
  992. static int pushuserdata (lua_State *L) {
  993. lua_Integer u = luaL_checkinteger(L, 1);
  994. lua_pushlightuserdata(L, cast_voidp(cast_sizet(u)));
  995. return 1;
  996. }
  997. static int udataval (lua_State *L) {
  998. lua_pushinteger(L, cast(long, lua_touserdata(L, 1)));
  999. return 1;
  1000. }
  1001. static int doonnewstack (lua_State *L) {
  1002. lua_State *L1 = lua_newthread(L);
  1003. size_t l;
  1004. const char *s = luaL_checklstring(L, 1, &l);
  1005. int status = luaL_loadbuffer(L1, s, l, s);
  1006. if (status == LUA_OK)
  1007. status = lua_pcall(L1, 0, 0, 0);
  1008. lua_pushinteger(L, status);
  1009. return 1;
  1010. }
  1011. static int s2d (lua_State *L) {
  1012. lua_pushnumber(L, cast_num(*cast(const double *, luaL_checkstring(L, 1))));
  1013. return 1;
  1014. }
  1015. static int d2s (lua_State *L) {
  1016. double d = cast(double, luaL_checknumber(L, 1));
  1017. lua_pushlstring(L, cast_charp(&d), sizeof(d));
  1018. return 1;
  1019. }
  1020. static int num2int (lua_State *L) {
  1021. lua_pushinteger(L, lua_tointeger(L, 1));
  1022. return 1;
  1023. }
  1024. static int makeseed (lua_State *L) {
  1025. lua_pushinteger(L, luaL_makeseed(L));
  1026. return 1;
  1027. }
  1028. static int newstate (lua_State *L) {
  1029. void *ud;
  1030. lua_Alloc f = lua_getallocf(L, &ud);
  1031. lua_State *L1 = lua_newstate(f, ud, 0);
  1032. if (L1) {
  1033. lua_atpanic(L1, tpanic);
  1034. lua_pushlightuserdata(L, L1);
  1035. }
  1036. else
  1037. lua_pushnil(L);
  1038. return 1;
  1039. }
  1040. static lua_State *getstate (lua_State *L) {
  1041. lua_State *L1 = cast(lua_State *, lua_touserdata(L, 1));
  1042. luaL_argcheck(L, L1 != NULL, 1, "state expected");
  1043. return L1;
  1044. }
  1045. static int loadlib (lua_State *L) {
  1046. lua_State *L1 = getstate(L);
  1047. int what = luaL_checkinteger(L, 2);
  1048. luaL_openselectedlibs(L1, what);
  1049. luaL_requiref(L1, "T", luaB_opentests, 0);
  1050. lua_assert(lua_type(L1, -1) == LUA_TTABLE);
  1051. /* 'requiref' should not reload module already loaded... */
  1052. luaL_requiref(L1, "T", NULL, 1); /* seg. fault if it reloads */
  1053. /* ...but should return the same module */
  1054. lua_assert(lua_compare(L1, -1, -2, LUA_OPEQ));
  1055. return 0;
  1056. }
  1057. static int closestate (lua_State *L) {
  1058. lua_State *L1 = getstate(L);
  1059. lua_close(L1);
  1060. return 0;
  1061. }
  1062. static int doremote (lua_State *L) {
  1063. lua_State *L1 = getstate(L);
  1064. size_t lcode;
  1065. const char *code = luaL_checklstring(L, 2, &lcode);
  1066. int status;
  1067. lua_settop(L1, 0);
  1068. status = luaL_loadbuffer(L1, code, lcode, code);
  1069. if (status == LUA_OK)
  1070. status = lua_pcall(L1, 0, LUA_MULTRET, 0);
  1071. if (status != LUA_OK) {
  1072. lua_pushnil(L);
  1073. lua_pushstring(L, lua_tostring(L1, -1));
  1074. lua_pushinteger(L, status);
  1075. return 3;
  1076. }
  1077. else {
  1078. int i = 0;
  1079. while (!lua_isnone(L1, ++i))
  1080. lua_pushstring(L, lua_tostring(L1, i));
  1081. lua_pop(L1, i-1);
  1082. return i-1;
  1083. }
  1084. }
  1085. static int log2_aux (lua_State *L) {
  1086. unsigned int x = (unsigned int)luaL_checkinteger(L, 1);
  1087. lua_pushinteger(L, luaO_ceillog2(x));
  1088. return 1;
  1089. }
  1090. struct Aux { jmp_buf jb; const char *paniccode; lua_State *L; };
  1091. /*
  1092. ** does a long-jump back to "main program".
  1093. */
  1094. static int panicback (lua_State *L) {
  1095. struct Aux *b;
  1096. lua_checkstack(L, 1); /* open space for 'Aux' struct */
  1097. lua_getfield(L, LUA_REGISTRYINDEX, "_jmpbuf"); /* get 'Aux' struct */
  1098. b = (struct Aux *)lua_touserdata(L, -1);
  1099. lua_pop(L, 1); /* remove 'Aux' struct */
  1100. runC(b->L, L, b->paniccode); /* run optional panic code */
  1101. longjmp(b->jb, 1);
  1102. return 1; /* to avoid warnings */
  1103. }
  1104. static int checkpanic (lua_State *L) {
  1105. struct Aux b;
  1106. void *ud;
  1107. lua_State *L1;
  1108. const char *code = luaL_checkstring(L, 1);
  1109. lua_Alloc f = lua_getallocf(L, &ud);
  1110. b.paniccode = luaL_optstring(L, 2, "");
  1111. b.L = L;
  1112. L1 = lua_newstate(f, ud, 0); /* create new state */
  1113. if (L1 == NULL) { /* error? */
  1114. lua_pushnil(L);
  1115. return 1;
  1116. }
  1117. lua_atpanic(L1, panicback); /* set its panic function */
  1118. lua_pushlightuserdata(L1, &b);
  1119. lua_setfield(L1, LUA_REGISTRYINDEX, "_jmpbuf"); /* store 'Aux' struct */
  1120. if (setjmp(b.jb) == 0) { /* set jump buffer */
  1121. runC(L, L1, code); /* run code unprotected */
  1122. lua_pushliteral(L, "no errors");
  1123. }
  1124. else { /* error handling */
  1125. /* move error message to original state */
  1126. lua_pushstring(L, lua_tostring(L1, -1));
  1127. }
  1128. lua_close(L1);
  1129. return 1;
  1130. }
  1131. static int externKstr (lua_State *L) {
  1132. size_t len;
  1133. const char *s = luaL_checklstring(L, 1, &len);
  1134. lua_pushextlstring(L, s, len, NULL, NULL);
  1135. return 1;
  1136. }
  1137. /*
  1138. ** Create a buffer with the content of a given string and then
  1139. ** create an external string using that buffer. Use the allocation
  1140. ** function from Lua to create and free the buffer.
  1141. */
  1142. static int externstr (lua_State *L) {
  1143. size_t len;
  1144. const char *s = luaL_checklstring(L, 1, &len);
  1145. void *ud;
  1146. lua_Alloc allocf = lua_getallocf(L, &ud); /* get allocation function */
  1147. /* create the buffer */
  1148. char *buff = cast_charp((*allocf)(ud, NULL, 0, len + 1));
  1149. if (buff == NULL) { /* memory error? */
  1150. lua_pushliteral(L, "not enough memory");
  1151. lua_error(L); /* raise a memory error */
  1152. }
  1153. /* copy string content to buffer, including ending 0 */
  1154. memcpy(buff, s, (len + 1) * sizeof(char));
  1155. /* create external string */
  1156. lua_pushextlstring(L, buff, len, allocf, ud);
  1157. return 1;
  1158. }
  1159. /*
  1160. ** {====================================================================
  1161. ** function to test the API with C. It interprets a kind of assembler
  1162. ** language with calls to the API, so the test can be driven by Lua code
  1163. ** =====================================================================
  1164. */
  1165. static void sethookaux (lua_State *L, int mask, int count, const char *code);
  1166. static const char *const delimits = " \t\n,;";
  1167. static void skip (const char **pc) {
  1168. for (;;) {
  1169. if (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
  1170. else if (**pc == '#') { /* comment? */
  1171. while (**pc != '\n' && **pc != '\0') (*pc)++; /* until end-of-line */
  1172. }
  1173. else break;
  1174. }
  1175. }
  1176. static int getnum_aux (lua_State *L, lua_State *L1, const char **pc) {
  1177. int res = 0;
  1178. int sig = 1;
  1179. skip(pc);
  1180. if (**pc == '.') {
  1181. res = cast_int(lua_tointeger(L1, -1));
  1182. lua_pop(L1, 1);
  1183. (*pc)++;
  1184. return res;
  1185. }
  1186. else if (**pc == '*') {
  1187. res = lua_gettop(L1);
  1188. (*pc)++;
  1189. return res;
  1190. }
  1191. else if (**pc == '!') {
  1192. (*pc)++;
  1193. if (**pc == 'G')
  1194. res = LUA_RIDX_GLOBALS;
  1195. else if (**pc == 'M')
  1196. res = LUA_RIDX_MAINTHREAD;
  1197. else lua_assert(0);
  1198. (*pc)++;
  1199. return res;
  1200. }
  1201. else if (**pc == '-') {
  1202. sig = -1;
  1203. (*pc)++;
  1204. }
  1205. if (!lisdigit(cast_uchar(**pc)))
  1206. luaL_error(L, "number expected (%s)", *pc);
  1207. while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0';
  1208. return sig*res;
  1209. }
  1210. static const char *getstring_aux (lua_State *L, char *buff, const char **pc) {
  1211. int i = 0;
  1212. skip(pc);
  1213. if (**pc == '"' || **pc == '\'') { /* quoted string? */
  1214. int quote = *(*pc)++;
  1215. while (**pc != quote) {
  1216. if (**pc == '\0') luaL_error(L, "unfinished string in C script");
  1217. buff[i++] = *(*pc)++;
  1218. }
  1219. (*pc)++;
  1220. }
  1221. else {
  1222. while (**pc != '\0' && !strchr(delimits, **pc))
  1223. buff[i++] = *(*pc)++;
  1224. }
  1225. buff[i] = '\0';
  1226. return buff;
  1227. }
  1228. static int getindex_aux (lua_State *L, lua_State *L1, const char **pc) {
  1229. skip(pc);
  1230. switch (*(*pc)++) {
  1231. case 'R': return LUA_REGISTRYINDEX;
  1232. case 'G': return luaL_error(L, "deprecated index 'G'");
  1233. case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc));
  1234. default: (*pc)--; return getnum_aux(L, L1, pc);
  1235. }
  1236. }
  1237. static const char *const statcodes[] = {"OK", "YIELD", "ERRRUN",
  1238. "ERRSYNTAX", MEMERRMSG, "ERRGCMM", "ERRERR"};
  1239. /*
  1240. ** Avoid these stat codes from being collected, to avoid possible
  1241. ** memory error when pushing them.
  1242. */
  1243. static void regcodes (lua_State *L) {
  1244. unsigned int i;
  1245. for (i = 0; i < sizeof(statcodes) / sizeof(statcodes[0]); i++) {
  1246. lua_pushboolean(L, 1);
  1247. lua_setfield(L, LUA_REGISTRYINDEX, statcodes[i]);
  1248. }
  1249. }
  1250. #define EQ(s1) (strcmp(s1, inst) == 0)
  1251. #define getnum (getnum_aux(L, L1, &pc))
  1252. #define getstring (getstring_aux(L, buff, &pc))
  1253. #define getindex (getindex_aux(L, L1, &pc))
  1254. static int testC (lua_State *L);
  1255. static int Cfunck (lua_State *L, int status, lua_KContext ctx);
  1256. /*
  1257. ** arithmetic operation encoding for 'arith' instruction
  1258. ** LUA_OPIDIV -> \
  1259. ** LUA_OPSHL -> <
  1260. ** LUA_OPSHR -> >
  1261. ** LUA_OPUNM -> _
  1262. ** LUA_OPBNOT -> !
  1263. */
  1264. static const char ops[] = "+-*%^/\\&|~<>_!";
  1265. static int runC (lua_State *L, lua_State *L1, const char *pc) {
  1266. char buff[300];
  1267. int status = 0;
  1268. if (pc == NULL) return luaL_error(L, "attempt to runC null script");
  1269. for (;;) {
  1270. const char *inst = getstring;
  1271. if EQ("") return 0;
  1272. else if EQ("absindex") {
  1273. lua_pushnumber(L1, lua_absindex(L1, getindex));
  1274. }
  1275. else if EQ("append") {
  1276. int t = getindex;
  1277. int i = lua_rawlen(L1, t);
  1278. lua_rawseti(L1, t, i + 1);
  1279. }
  1280. else if EQ("arith") {
  1281. int op;
  1282. skip(&pc);
  1283. op = strchr(ops, *pc++) - ops;
  1284. lua_arith(L1, op);
  1285. }
  1286. else if EQ("call") {
  1287. int narg = getnum;
  1288. int nres = getnum;
  1289. lua_call(L1, narg, nres);
  1290. }
  1291. else if EQ("callk") {
  1292. int narg = getnum;
  1293. int nres = getnum;
  1294. int i = getindex;
  1295. lua_callk(L1, narg, nres, i, Cfunck);
  1296. }
  1297. else if EQ("checkstack") {
  1298. int sz = getnum;
  1299. const char *msg = getstring;
  1300. if (*msg == '\0')
  1301. msg = NULL; /* to test 'luaL_checkstack' with no message */
  1302. luaL_checkstack(L1, sz, msg);
  1303. }
  1304. else if EQ("rawcheckstack") {
  1305. int sz = getnum;
  1306. lua_pushboolean(L1, lua_checkstack(L1, sz));
  1307. }
  1308. else if EQ("compare") {
  1309. const char *opt = getstring; /* EQ, LT, or LE */
  1310. int op = (opt[0] == 'E') ? LUA_OPEQ
  1311. : (opt[1] == 'T') ? LUA_OPLT : LUA_OPLE;
  1312. int a = getindex;
  1313. int b = getindex;
  1314. lua_pushboolean(L1, lua_compare(L1, a, b, op));
  1315. }
  1316. else if EQ("concat") {
  1317. lua_concat(L1, getnum);
  1318. }
  1319. else if EQ("copy") {
  1320. int f = getindex;
  1321. lua_copy(L1, f, getindex);
  1322. }
  1323. else if EQ("func2num") {
  1324. lua_CFunction func = lua_tocfunction(L1, getindex);
  1325. lua_pushnumber(L1, cast_sizet(func));
  1326. }
  1327. else if EQ("getfield") {
  1328. int t = getindex;
  1329. lua_getfield(L1, t, getstring);
  1330. }
  1331. else if EQ("getglobal") {
  1332. lua_getglobal(L1, getstring);
  1333. }
  1334. else if EQ("getmetatable") {
  1335. if (lua_getmetatable(L1, getindex) == 0)
  1336. lua_pushnil(L1);
  1337. }
  1338. else if EQ("gettable") {
  1339. lua_gettable(L1, getindex);
  1340. }
  1341. else if EQ("gettop") {
  1342. lua_pushinteger(L1, lua_gettop(L1));
  1343. }
  1344. else if EQ("gsub") {
  1345. int a = getnum; int b = getnum; int c = getnum;
  1346. luaL_gsub(L1, lua_tostring(L1, a),
  1347. lua_tostring(L1, b),
  1348. lua_tostring(L1, c));
  1349. }
  1350. else if EQ("insert") {
  1351. lua_insert(L1, getnum);
  1352. }
  1353. else if EQ("iscfunction") {
  1354. lua_pushboolean(L1, lua_iscfunction(L1, getindex));
  1355. }
  1356. else if EQ("isfunction") {
  1357. lua_pushboolean(L1, lua_isfunction(L1, getindex));
  1358. }
  1359. else if EQ("isnil") {
  1360. lua_pushboolean(L1, lua_isnil(L1, getindex));
  1361. }
  1362. else if EQ("isnull") {
  1363. lua_pushboolean(L1, lua_isnone(L1, getindex));
  1364. }
  1365. else if EQ("isnumber") {
  1366. lua_pushboolean(L1, lua_isnumber(L1, getindex));
  1367. }
  1368. else if EQ("isstring") {
  1369. lua_pushboolean(L1, lua_isstring(L1, getindex));
  1370. }
  1371. else if EQ("istable") {
  1372. lua_pushboolean(L1, lua_istable(L1, getindex));
  1373. }
  1374. else if EQ("isudataval") {
  1375. lua_pushboolean(L1, lua_islightuserdata(L1, getindex));
  1376. }
  1377. else if EQ("isuserdata") {
  1378. lua_pushboolean(L1, lua_isuserdata(L1, getindex));
  1379. }
  1380. else if EQ("len") {
  1381. lua_len(L1, getindex);
  1382. }
  1383. else if EQ("Llen") {
  1384. lua_pushinteger(L1, luaL_len(L1, getindex));
  1385. }
  1386. else if EQ("loadfile") {
  1387. luaL_loadfile(L1, luaL_checkstring(L1, getnum));
  1388. }
  1389. else if EQ("loadstring") {
  1390. size_t slen;
  1391. const char *s = luaL_checklstring(L1, getnum, &slen);
  1392. const char *name = getstring;
  1393. const char *mode = getstring;
  1394. luaL_loadbufferx(L1, s, slen, name, mode);
  1395. }
  1396. else if EQ("newmetatable") {
  1397. lua_pushboolean(L1, luaL_newmetatable(L1, getstring));
  1398. }
  1399. else if EQ("newtable") {
  1400. lua_newtable(L1);
  1401. }
  1402. else if EQ("newthread") {
  1403. lua_newthread(L1);
  1404. }
  1405. else if EQ("resetthread") {
  1406. lua_pushinteger(L1, lua_resetthread(L1)); /* deprecated */
  1407. }
  1408. else if EQ("newuserdata") {
  1409. lua_newuserdata(L1, getnum);
  1410. }
  1411. else if EQ("next") {
  1412. lua_next(L1, -2);
  1413. }
  1414. else if EQ("objsize") {
  1415. lua_pushinteger(L1, lua_rawlen(L1, getindex));
  1416. }
  1417. else if EQ("pcall") {
  1418. int narg = getnum;
  1419. int nres = getnum;
  1420. status = lua_pcall(L1, narg, nres, getnum);
  1421. }
  1422. else if EQ("pcallk") {
  1423. int narg = getnum;
  1424. int nres = getnum;
  1425. int i = getindex;
  1426. status = lua_pcallk(L1, narg, nres, 0, i, Cfunck);
  1427. }
  1428. else if EQ("pop") {
  1429. lua_pop(L1, getnum);
  1430. }
  1431. else if EQ("printstack") {
  1432. int n = getnum;
  1433. if (n != 0) {
  1434. printf("%s\n", luaL_tolstring(L1, n, NULL));
  1435. lua_pop(L1, 1);
  1436. }
  1437. else printstack(L1);
  1438. }
  1439. else if EQ("print") {
  1440. const char *msg = getstring;
  1441. printf("%s\n", msg);
  1442. }
  1443. else if EQ("warningC") {
  1444. const char *msg = getstring;
  1445. lua_warning(L1, msg, 1);
  1446. }
  1447. else if EQ("warning") {
  1448. const char *msg = getstring;
  1449. lua_warning(L1, msg, 0);
  1450. }
  1451. else if EQ("pushbool") {
  1452. lua_pushboolean(L1, getnum);
  1453. }
  1454. else if EQ("pushcclosure") {
  1455. lua_pushcclosure(L1, testC, getnum);
  1456. }
  1457. else if EQ("pushint") {
  1458. lua_pushinteger(L1, getnum);
  1459. }
  1460. else if EQ("pushnil") {
  1461. lua_pushnil(L1);
  1462. }
  1463. else if EQ("pushnum") {
  1464. lua_pushnumber(L1, (lua_Number)getnum);
  1465. }
  1466. else if EQ("pushstatus") {
  1467. lua_pushstring(L1, statcodes[status]);
  1468. }
  1469. else if EQ("pushstring") {
  1470. lua_pushstring(L1, getstring);
  1471. }
  1472. else if EQ("pushupvalueindex") {
  1473. lua_pushinteger(L1, lua_upvalueindex(getnum));
  1474. }
  1475. else if EQ("pushvalue") {
  1476. lua_pushvalue(L1, getindex);
  1477. }
  1478. else if EQ("pushfstringI") {
  1479. lua_pushfstring(L1, lua_tostring(L, -2), (int)lua_tointeger(L, -1));
  1480. }
  1481. else if EQ("pushfstringS") {
  1482. lua_pushfstring(L1, lua_tostring(L, -2), lua_tostring(L, -1));
  1483. }
  1484. else if EQ("pushfstringP") {
  1485. lua_pushfstring(L1, lua_tostring(L, -2), lua_topointer(L, -1));
  1486. }
  1487. else if EQ("rawget") {
  1488. int t = getindex;
  1489. lua_rawget(L1, t);
  1490. }
  1491. else if EQ("rawgeti") {
  1492. int t = getindex;
  1493. lua_rawgeti(L1, t, getnum);
  1494. }
  1495. else if EQ("rawgetp") {
  1496. int t = getindex;
  1497. lua_rawgetp(L1, t, cast_voidp(cast_sizet(getnum)));
  1498. }
  1499. else if EQ("rawset") {
  1500. int t = getindex;
  1501. lua_rawset(L1, t);
  1502. }
  1503. else if EQ("rawseti") {
  1504. int t = getindex;
  1505. lua_rawseti(L1, t, getnum);
  1506. }
  1507. else if EQ("rawsetp") {
  1508. int t = getindex;
  1509. lua_rawsetp(L1, t, cast_voidp(cast_sizet(getnum)));
  1510. }
  1511. else if EQ("remove") {
  1512. lua_remove(L1, getnum);
  1513. }
  1514. else if EQ("replace") {
  1515. lua_replace(L1, getindex);
  1516. }
  1517. else if EQ("resume") {
  1518. int i = getindex;
  1519. int nres;
  1520. status = lua_resume(lua_tothread(L1, i), L, getnum, &nres);
  1521. }
  1522. else if EQ("return") {
  1523. int n = getnum;
  1524. if (L1 != L) {
  1525. int i;
  1526. for (i = 0; i < n; i++) {
  1527. int idx = -(n - i);
  1528. switch (lua_type(L1, idx)) {
  1529. case LUA_TBOOLEAN:
  1530. lua_pushboolean(L, lua_toboolean(L1, idx));
  1531. break;
  1532. default:
  1533. lua_pushstring(L, lua_tostring(L1, idx));
  1534. break;
  1535. }
  1536. }
  1537. }
  1538. return n;
  1539. }
  1540. else if EQ("rotate") {
  1541. int i = getindex;
  1542. lua_rotate(L1, i, getnum);
  1543. }
  1544. else if EQ("setfield") {
  1545. int t = getindex;
  1546. const char *s = getstring;
  1547. lua_setfield(L1, t, s);
  1548. }
  1549. else if EQ("seti") {
  1550. int t = getindex;
  1551. lua_seti(L1, t, getnum);
  1552. }
  1553. else if EQ("setglobal") {
  1554. const char *s = getstring;
  1555. lua_setglobal(L1, s);
  1556. }
  1557. else if EQ("sethook") {
  1558. int mask = getnum;
  1559. int count = getnum;
  1560. const char *s = getstring;
  1561. sethookaux(L1, mask, count, s);
  1562. }
  1563. else if EQ("setmetatable") {
  1564. int idx = getindex;
  1565. lua_setmetatable(L1, idx);
  1566. }
  1567. else if EQ("settable") {
  1568. lua_settable(L1, getindex);
  1569. }
  1570. else if EQ("settop") {
  1571. lua_settop(L1, getnum);
  1572. }
  1573. else if EQ("testudata") {
  1574. int i = getindex;
  1575. lua_pushboolean(L1, luaL_testudata(L1, i, getstring) != NULL);
  1576. }
  1577. else if EQ("error") {
  1578. lua_error(L1);
  1579. }
  1580. else if EQ("abort") {
  1581. abort();
  1582. }
  1583. else if EQ("throw") {
  1584. #if defined(__cplusplus)
  1585. static struct X { int x; } x;
  1586. throw x;
  1587. #else
  1588. luaL_error(L1, "C++");
  1589. #endif
  1590. break;
  1591. }
  1592. else if EQ("tobool") {
  1593. lua_pushboolean(L1, lua_toboolean(L1, getindex));
  1594. }
  1595. else if EQ("tocfunction") {
  1596. lua_pushcfunction(L1, lua_tocfunction(L1, getindex));
  1597. }
  1598. else if EQ("tointeger") {
  1599. lua_pushinteger(L1, lua_tointeger(L1, getindex));
  1600. }
  1601. else if EQ("tonumber") {
  1602. lua_pushnumber(L1, lua_tonumber(L1, getindex));
  1603. }
  1604. else if EQ("topointer") {
  1605. lua_pushlightuserdata(L1, cast_voidp(lua_topointer(L1, getindex)));
  1606. }
  1607. else if EQ("touserdata") {
  1608. lua_pushlightuserdata(L1, lua_touserdata(L1, getindex));
  1609. }
  1610. else if EQ("tostring") {
  1611. const char *s = lua_tostring(L1, getindex);
  1612. const char *s1 = lua_pushstring(L1, s);
  1613. cast_void(s1); /* to avoid warnings */
  1614. lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);
  1615. }
  1616. else if EQ("Ltolstring") {
  1617. luaL_tolstring(L1, getindex, NULL);
  1618. }
  1619. else if EQ("type") {
  1620. lua_pushstring(L1, luaL_typename(L1, getnum));
  1621. }
  1622. else if EQ("xmove") {
  1623. int f = getindex;
  1624. int t = getindex;
  1625. lua_State *fs = (f == 0) ? L1 : lua_tothread(L1, f);
  1626. lua_State *ts = (t == 0) ? L1 : lua_tothread(L1, t);
  1627. int n = getnum;
  1628. if (n == 0) n = lua_gettop(fs);
  1629. lua_xmove(fs, ts, n);
  1630. }
  1631. else if EQ("isyieldable") {
  1632. lua_pushboolean(L1, lua_isyieldable(lua_tothread(L1, getindex)));
  1633. }
  1634. else if EQ("yield") {
  1635. return lua_yield(L1, getnum);
  1636. }
  1637. else if EQ("yieldk") {
  1638. int nres = getnum;
  1639. int i = getindex;
  1640. return lua_yieldk(L1, nres, i, Cfunck);
  1641. }
  1642. else if EQ("toclose") {
  1643. lua_toclose(L1, getnum);
  1644. }
  1645. else if EQ("closeslot") {
  1646. lua_closeslot(L1, getnum);
  1647. }
  1648. else luaL_error(L, "unknown instruction %s", buff);
  1649. }
  1650. return 0;
  1651. }
  1652. static int testC (lua_State *L) {
  1653. lua_State *L1;
  1654. const char *pc;
  1655. if (lua_isuserdata(L, 1)) {
  1656. L1 = getstate(L);
  1657. pc = luaL_checkstring(L, 2);
  1658. }
  1659. else if (lua_isthread(L, 1)) {
  1660. L1 = lua_tothread(L, 1);
  1661. pc = luaL_checkstring(L, 2);
  1662. }
  1663. else {
  1664. L1 = L;
  1665. pc = luaL_checkstring(L, 1);
  1666. }
  1667. return runC(L, L1, pc);
  1668. }
  1669. static int Cfunc (lua_State *L) {
  1670. return runC(L, L, lua_tostring(L, lua_upvalueindex(1)));
  1671. }
  1672. static int Cfunck (lua_State *L, int status, lua_KContext ctx) {
  1673. lua_pushstring(L, statcodes[status]);
  1674. lua_setglobal(L, "status");
  1675. lua_pushinteger(L, ctx);
  1676. lua_setglobal(L, "ctx");
  1677. return runC(L, L, lua_tostring(L, ctx));
  1678. }
  1679. static int makeCfunc (lua_State *L) {
  1680. luaL_checkstring(L, 1);
  1681. lua_pushcclosure(L, Cfunc, lua_gettop(L));
  1682. return 1;
  1683. }
  1684. /* }====================================================== */
  1685. /*
  1686. ** {======================================================
  1687. ** tests for C hooks
  1688. ** =======================================================
  1689. */
  1690. /*
  1691. ** C hook that runs the C script stored in registry.C_HOOK[L]
  1692. */
  1693. static void Chook (lua_State *L, lua_Debug *ar) {
  1694. const char *scpt;
  1695. const char *const events [] = {"call", "ret", "line", "count", "tailcall"};
  1696. lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK");
  1697. lua_pushlightuserdata(L, L);
  1698. lua_gettable(L, -2); /* get C_HOOK[L] (script saved by sethookaux) */
  1699. scpt = lua_tostring(L, -1); /* not very religious (string will be popped) */
  1700. lua_pop(L, 2); /* remove C_HOOK and script */
  1701. lua_pushstring(L, events[ar->event]); /* may be used by script */
  1702. lua_pushinteger(L, ar->currentline); /* may be used by script */
  1703. runC(L, L, scpt); /* run script from C_HOOK[L] */
  1704. }
  1705. /*
  1706. ** sets 'registry.C_HOOK[L] = scpt' and sets 'Chook' as a hook
  1707. */
  1708. static void sethookaux (lua_State *L, int mask, int count, const char *scpt) {
  1709. if (*scpt == '\0') { /* no script? */
  1710. lua_sethook(L, NULL, 0, 0); /* turn off hooks */
  1711. return;
  1712. }
  1713. lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* get C_HOOK table */
  1714. if (!lua_istable(L, -1)) { /* no hook table? */
  1715. lua_pop(L, 1); /* remove previous value */
  1716. lua_newtable(L); /* create new C_HOOK table */
  1717. lua_pushvalue(L, -1);
  1718. lua_setfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* register it */
  1719. }
  1720. lua_pushlightuserdata(L, L);
  1721. lua_pushstring(L, scpt);
  1722. lua_settable(L, -3); /* C_HOOK[L] = script */
  1723. lua_sethook(L, Chook, mask, count);
  1724. }
  1725. static int sethook (lua_State *L) {
  1726. if (lua_isnoneornil(L, 1))
  1727. lua_sethook(L, NULL, 0, 0); /* turn off hooks */
  1728. else {
  1729. const char *scpt = luaL_checkstring(L, 1);
  1730. const char *smask = luaL_checkstring(L, 2);
  1731. int count = cast_int(luaL_optinteger(L, 3, 0));
  1732. int mask = 0;
  1733. if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
  1734. if (strchr(smask, 'r')) mask |= LUA_MASKRET;
  1735. if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
  1736. if (count > 0) mask |= LUA_MASKCOUNT;
  1737. sethookaux(L, mask, count, scpt);
  1738. }
  1739. return 0;
  1740. }
  1741. static int coresume (lua_State *L) {
  1742. int status, nres;
  1743. lua_State *co = lua_tothread(L, 1);
  1744. luaL_argcheck(L, co, 1, "coroutine expected");
  1745. status = lua_resume(co, L, 0, &nres);
  1746. if (status != LUA_OK && status != LUA_YIELD) {
  1747. lua_pushboolean(L, 0);
  1748. lua_insert(L, -2);
  1749. return 2; /* return false + error message */
  1750. }
  1751. else {
  1752. lua_pushboolean(L, 1);
  1753. return 1;
  1754. }
  1755. }
  1756. /* }====================================================== */
  1757. static const struct luaL_Reg tests_funcs[] = {
  1758. {"checkmemory", lua_checkmemory},
  1759. {"closestate", closestate},
  1760. {"d2s", d2s},
  1761. {"doonnewstack", doonnewstack},
  1762. {"doremote", doremote},
  1763. {"gccolor", gc_color},
  1764. {"gcage", gc_age},
  1765. {"gcstate", gc_state},
  1766. {"pobj", gc_printobj},
  1767. {"getref", getref},
  1768. {"hash", hash_query},
  1769. {"log2", log2_aux},
  1770. {"limits", get_limits},
  1771. {"listcode", listcode},
  1772. {"printcode", printcode},
  1773. {"listk", listk},
  1774. {"listabslineinfo", listabslineinfo},
  1775. {"listlocals", listlocals},
  1776. {"loadlib", loadlib},
  1777. {"checkpanic", checkpanic},
  1778. {"newstate", newstate},
  1779. {"newuserdata", newuserdata},
  1780. {"num2int", num2int},
  1781. {"makeseed", makeseed},
  1782. {"pushuserdata", pushuserdata},
  1783. {"querystr", string_query},
  1784. {"querytab", table_query},
  1785. {"queryGCparams", query_GCparams},
  1786. {"codeparam", test_codeparam},
  1787. {"applyparam", test_applyparam},
  1788. {"ref", tref},
  1789. {"resume", coresume},
  1790. {"s2d", s2d},
  1791. {"sethook", sethook},
  1792. {"stacklevel", stacklevel},
  1793. {"testC", testC},
  1794. {"makeCfunc", makeCfunc},
  1795. {"totalmem", mem_query},
  1796. {"alloccount", alloc_count},
  1797. {"allocfailnext", alloc_failnext},
  1798. {"trick", settrick},
  1799. {"udataval", udataval},
  1800. {"unref", unref},
  1801. {"upvalue", upvalue},
  1802. {"externKstr", externKstr},
  1803. {"externstr", externstr},
  1804. {NULL, NULL}
  1805. };
  1806. static void checkfinalmem (void) {
  1807. lua_assert(l_memcontrol.numblocks == 0);
  1808. lua_assert(l_memcontrol.total == 0);
  1809. }
  1810. int luaB_opentests (lua_State *L) {
  1811. void *ud;
  1812. lua_Alloc f = lua_getallocf(L, &ud);
  1813. lua_atpanic(L, &tpanic);
  1814. lua_setwarnf(L, &warnf, L);
  1815. lua_pushboolean(L, 0);
  1816. lua_setglobal(L, "_WARN"); /* _WARN = false */
  1817. regcodes(L);
  1818. atexit(checkfinalmem);
  1819. lua_assert(f == debug_realloc && ud == cast_voidp(&l_memcontrol));
  1820. lua_setallocf(L, f, ud); /* exercise this function */
  1821. luaL_newlib(L, tests_funcs);
  1822. return 1;
  1823. }
  1824. #endif