ltests.c 54 KB

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