ltests.c 56 KB

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