ltests.c 56 KB

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