ltests.c 57 KB

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