ltests.c 57 KB

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