2
0

lauxlib.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. /*
  2. ** $Id: lauxlib.c $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lauxlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <errno.h>
  10. #include <stdarg.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. /*
  15. ** This file uses only the official API of Lua.
  16. ** Any function declared here could be written as an application function.
  17. */
  18. #include "lua.h"
  19. #include "lauxlib.h"
  20. #if !defined(MAX_SIZET)
  21. /* maximum value for size_t */
  22. #define MAX_SIZET ((size_t)(~(size_t)0))
  23. #endif
  24. /*
  25. ** {======================================================
  26. ** Traceback
  27. ** =======================================================
  28. */
  29. #define LEVELS1 10 /* size of the first part of the stack */
  30. #define LEVELS2 11 /* size of the second part of the stack */
  31. /*
  32. ** Search for 'objidx' in table at index -1. ('objidx' must be an
  33. ** absolute index.) Return 1 + string at top if it found a good name.
  34. */
  35. static int findfield (lua_State *L, int objidx, int level) {
  36. if (level == 0 || !lua_istable(L, -1))
  37. return 0; /* not found */
  38. lua_pushnil(L); /* start 'next' loop */
  39. while (lua_next(L, -2)) { /* for each pair in table */
  40. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  41. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  42. lua_pop(L, 1); /* remove value (but keep name) */
  43. return 1;
  44. }
  45. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  46. /* stack: lib_name, lib_table, field_name (top) */
  47. lua_pushliteral(L, "."); /* place '.' between the two names */
  48. lua_replace(L, -3); /* (in the slot occupied by table) */
  49. lua_concat(L, 3); /* lib_name.field_name */
  50. return 1;
  51. }
  52. }
  53. lua_pop(L, 1); /* remove value */
  54. }
  55. return 0; /* not found */
  56. }
  57. /*
  58. ** Search for a name for a function in all loaded modules
  59. */
  60. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  61. int top = lua_gettop(L);
  62. lua_getinfo(L, "f", ar); /* push function */
  63. lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  64. luaL_checkstack(L, 6, "not enough stack"); /* slots for 'findfield' */
  65. if (findfield(L, top + 1, 2)) {
  66. const char *name = lua_tostring(L, -1);
  67. if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */
  68. lua_pushstring(L, name + 3); /* push name without prefix */
  69. lua_remove(L, -2); /* remove original name */
  70. }
  71. lua_copy(L, -1, top + 1); /* copy name to proper place */
  72. lua_settop(L, top + 1); /* remove table "loaded" and name copy */
  73. return 1;
  74. }
  75. else {
  76. lua_settop(L, top); /* remove function and global table */
  77. return 0;
  78. }
  79. }
  80. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  81. if (pushglobalfuncname(L, ar)) { /* try first a global name */
  82. lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
  83. lua_remove(L, -2); /* remove name */
  84. }
  85. else if (*ar->namewhat != '\0') /* is there a name from code? */
  86. lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
  87. else if (*ar->what == 'm') /* main? */
  88. lua_pushliteral(L, "main chunk");
  89. else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
  90. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  91. else /* nothing left... */
  92. lua_pushliteral(L, "?");
  93. }
  94. static int lastlevel (lua_State *L) {
  95. lua_Debug ar;
  96. int li = 1, le = 1;
  97. /* find an upper bound */
  98. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  99. /* do a binary search */
  100. while (li < le) {
  101. int m = (li + le)/2;
  102. if (lua_getstack(L, m, &ar)) li = m + 1;
  103. else le = m;
  104. }
  105. return le - 1;
  106. }
  107. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  108. const char *msg, int level) {
  109. luaL_Buffer b;
  110. lua_Debug ar;
  111. int last = lastlevel(L1);
  112. int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
  113. luaL_buffinit(L, &b);
  114. if (msg) {
  115. luaL_addstring(&b, msg);
  116. luaL_addchar(&b, '\n');
  117. }
  118. luaL_addstring(&b, "stack traceback:");
  119. while (lua_getstack(L1, level++, &ar)) {
  120. if (limit2show-- == 0) { /* too many levels? */
  121. int n = last - level - LEVELS2 + 1; /* number of levels to skip */
  122. lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n);
  123. luaL_addvalue(&b); /* add warning about skip */
  124. level += n; /* and skip to last levels */
  125. }
  126. else {
  127. lua_getinfo(L1, "Slnt", &ar);
  128. if (ar.currentline <= 0)
  129. lua_pushfstring(L, "\n\t%s: in ", ar.short_src);
  130. else
  131. lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline);
  132. luaL_addvalue(&b);
  133. pushfuncname(L, &ar);
  134. luaL_addvalue(&b);
  135. if (ar.istailcall)
  136. luaL_addstring(&b, "\n\t(...tail calls...)");
  137. }
  138. }
  139. luaL_pushresult(&b);
  140. }
  141. /* }====================================================== */
  142. /*
  143. ** {======================================================
  144. ** Error-report functions
  145. ** =======================================================
  146. */
  147. LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
  148. lua_Debug ar;
  149. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  150. return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
  151. lua_getinfo(L, "n", &ar);
  152. if (strcmp(ar.namewhat, "method") == 0) {
  153. arg--; /* do not count 'self' */
  154. if (arg == 0) /* error is in the self argument itself? */
  155. return luaL_error(L, "calling '%s' on bad self (%s)",
  156. ar.name, extramsg);
  157. }
  158. if (ar.name == NULL)
  159. ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
  160. return luaL_error(L, "bad argument #%d to '%s' (%s)",
  161. arg, ar.name, extramsg);
  162. }
  163. LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
  164. const char *msg;
  165. const char *typearg; /* name for the type of the actual argument */
  166. if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
  167. typearg = lua_tostring(L, -1); /* use the given type name */
  168. else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
  169. typearg = "light userdata"; /* special name for messages */
  170. else
  171. typearg = luaL_typename(L, arg); /* standard name */
  172. msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
  173. return luaL_argerror(L, arg, msg);
  174. }
  175. static void tag_error (lua_State *L, int arg, int tag) {
  176. luaL_typeerror(L, arg, lua_typename(L, tag));
  177. }
  178. /*
  179. ** The use of 'lua_pushfstring' ensures this function does not
  180. ** need reserved stack space when called.
  181. */
  182. LUALIB_API void luaL_where (lua_State *L, int level) {
  183. lua_Debug ar;
  184. if (lua_getstack(L, level, &ar)) { /* check function at level */
  185. lua_getinfo(L, "Sl", &ar); /* get info about it */
  186. if (ar.currentline > 0) { /* is there info? */
  187. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  188. return;
  189. }
  190. }
  191. lua_pushfstring(L, ""); /* else, no information available... */
  192. }
  193. /*
  194. ** Again, the use of 'lua_pushvfstring' ensures this function does
  195. ** not need reserved stack space when called. (At worst, it generates
  196. ** an error with "stack overflow" instead of the given message.)
  197. */
  198. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  199. va_list argp;
  200. va_start(argp, fmt);
  201. luaL_where(L, 1);
  202. lua_pushvfstring(L, fmt, argp);
  203. va_end(argp);
  204. lua_concat(L, 2);
  205. return lua_error(L);
  206. }
  207. LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
  208. int en = errno; /* calls to Lua API may change this value */
  209. if (stat) {
  210. lua_pushboolean(L, 1);
  211. return 1;
  212. }
  213. else {
  214. const char *msg;
  215. luaL_pushfail(L);
  216. msg = (en != 0) ? strerror(en) : "(no extra info)";
  217. if (fname)
  218. lua_pushfstring(L, "%s: %s", fname, msg);
  219. else
  220. lua_pushstring(L, msg);
  221. lua_pushinteger(L, en);
  222. return 3;
  223. }
  224. }
  225. #if !defined(l_inspectstat) /* { */
  226. #if defined(LUA_USE_POSIX)
  227. #include <sys/wait.h>
  228. /*
  229. ** use appropriate macros to interpret 'pclose' return status
  230. */
  231. #define l_inspectstat(stat,what) \
  232. if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
  233. else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
  234. #else
  235. #define l_inspectstat(stat,what) /* no op */
  236. #endif
  237. #endif /* } */
  238. LUALIB_API int luaL_execresult (lua_State *L, int stat) {
  239. if (stat != 0 && errno != 0) /* error with an 'errno'? */
  240. return luaL_fileresult(L, 0, NULL);
  241. else {
  242. const char *what = "exit"; /* type of termination */
  243. l_inspectstat(stat, what); /* interpret result */
  244. if (*what == 'e' && stat == 0) /* successful termination? */
  245. lua_pushboolean(L, 1);
  246. else
  247. luaL_pushfail(L);
  248. lua_pushstring(L, what);
  249. lua_pushinteger(L, stat);
  250. return 3; /* return true/fail,what,code */
  251. }
  252. }
  253. /* }====================================================== */
  254. /*
  255. ** {======================================================
  256. ** Userdata's metatable manipulation
  257. ** =======================================================
  258. */
  259. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  260. if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
  261. return 0; /* leave previous value on top, but return 0 */
  262. lua_pop(L, 1);
  263. lua_createtable(L, 0, 2); /* create metatable */
  264. lua_pushstring(L, tname);
  265. lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
  266. lua_pushvalue(L, -1);
  267. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  268. return 1;
  269. }
  270. LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  271. luaL_getmetatable(L, tname);
  272. lua_setmetatable(L, -2);
  273. }
  274. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  275. void *p = lua_touserdata(L, ud);
  276. if (p != NULL) { /* value is a userdata? */
  277. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  278. luaL_getmetatable(L, tname); /* get correct metatable */
  279. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  280. p = NULL; /* value is a userdata with wrong metatable */
  281. lua_pop(L, 2); /* remove both metatables */
  282. return p;
  283. }
  284. }
  285. return NULL; /* value is not a userdata with a metatable */
  286. }
  287. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  288. void *p = luaL_testudata(L, ud, tname);
  289. luaL_argexpected(L, p != NULL, ud, tname);
  290. return p;
  291. }
  292. /* }====================================================== */
  293. /*
  294. ** {======================================================
  295. ** Argument check functions
  296. ** =======================================================
  297. */
  298. LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
  299. const char *const lst[]) {
  300. const char *name = (def) ? luaL_optstring(L, arg, def) :
  301. luaL_checkstring(L, arg);
  302. int i;
  303. for (i=0; lst[i]; i++)
  304. if (strcmp(lst[i], name) == 0)
  305. return i;
  306. return luaL_argerror(L, arg,
  307. lua_pushfstring(L, "invalid option '%s'", name));
  308. }
  309. /*
  310. ** Ensures the stack has at least 'space' extra slots, raising an error
  311. ** if it cannot fulfill the request. (The error handling needs a few
  312. ** extra slots to format the error message. In case of an error without
  313. ** this extra space, Lua will generate the same 'stack overflow' error,
  314. ** but without 'msg'.)
  315. */
  316. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  317. if (l_unlikely(!lua_checkstack(L, space))) {
  318. if (msg)
  319. luaL_error(L, "stack overflow (%s)", msg);
  320. else
  321. luaL_error(L, "stack overflow");
  322. }
  323. }
  324. LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
  325. if (l_unlikely(lua_type(L, arg) != t))
  326. tag_error(L, arg, t);
  327. }
  328. LUALIB_API void luaL_checkany (lua_State *L, int arg) {
  329. if (l_unlikely(lua_type(L, arg) == LUA_TNONE))
  330. luaL_argerror(L, arg, "value expected");
  331. }
  332. LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
  333. const char *s = lua_tolstring(L, arg, len);
  334. if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING);
  335. return s;
  336. }
  337. LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
  338. const char *def, size_t *len) {
  339. if (lua_isnoneornil(L, arg)) {
  340. if (len)
  341. *len = (def ? strlen(def) : 0);
  342. return def;
  343. }
  344. else return luaL_checklstring(L, arg, len);
  345. }
  346. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
  347. int isnum;
  348. lua_Number d = lua_tonumberx(L, arg, &isnum);
  349. if (l_unlikely(!isnum))
  350. tag_error(L, arg, LUA_TNUMBER);
  351. return d;
  352. }
  353. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
  354. return luaL_opt(L, luaL_checknumber, arg, def);
  355. }
  356. static void interror (lua_State *L, int arg) {
  357. if (lua_isnumber(L, arg))
  358. luaL_argerror(L, arg, "number has no integer representation");
  359. else
  360. tag_error(L, arg, LUA_TNUMBER);
  361. }
  362. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
  363. int isnum;
  364. lua_Integer d = lua_tointegerx(L, arg, &isnum);
  365. if (l_unlikely(!isnum)) {
  366. interror(L, arg);
  367. }
  368. return d;
  369. }
  370. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
  371. lua_Integer def) {
  372. return luaL_opt(L, luaL_checkinteger, arg, def);
  373. }
  374. /* }====================================================== */
  375. /*
  376. ** {======================================================
  377. ** Generic Buffer manipulation
  378. ** =======================================================
  379. */
  380. /* userdata to box arbitrary data */
  381. typedef struct UBox {
  382. void *box;
  383. size_t bsize;
  384. } UBox;
  385. static void *resizebox (lua_State *L, int idx, size_t newsize) {
  386. void *ud;
  387. lua_Alloc allocf = lua_getallocf(L, &ud);
  388. UBox *box = (UBox *)lua_touserdata(L, idx);
  389. void *temp = allocf(ud, box->box, box->bsize, newsize);
  390. if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */
  391. lua_pushliteral(L, "not enough memory");
  392. lua_error(L); /* raise a memory error */
  393. }
  394. box->box = temp;
  395. box->bsize = newsize;
  396. return temp;
  397. }
  398. static int boxgc (lua_State *L) {
  399. resizebox(L, 1, 0);
  400. return 0;
  401. }
  402. static const luaL_Reg boxmt[] = { /* box metamethods */
  403. {"__gc", boxgc},
  404. {"__close", boxgc},
  405. {NULL, NULL}
  406. };
  407. static void newbox (lua_State *L) {
  408. UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);
  409. box->box = NULL;
  410. box->bsize = 0;
  411. if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */
  412. luaL_setfuncs(L, boxmt, 0); /* set its metamethods */
  413. lua_setmetatable(L, -2);
  414. }
  415. /*
  416. ** check whether buffer is using a userdata on the stack as a temporary
  417. ** buffer
  418. */
  419. #define buffonstack(B) ((B)->b != (B)->init.b)
  420. /*
  421. ** Whenever buffer is accessed, slot 'idx' must either be a box (which
  422. ** cannot be NULL) or it is a placeholder for the buffer.
  423. */
  424. #define checkbufferlevel(B,idx) \
  425. lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \
  426. : lua_touserdata(B->L, idx) == (void*)B)
  427. /*
  428. ** Compute new size for buffer 'B', enough to accommodate extra 'sz'
  429. ** bytes. (The test for "not big enough" also gets the case when the
  430. ** computation of 'newsize' overflows.)
  431. */
  432. static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
  433. size_t newsize = (B->size / 2) * 3; /* buffer size * 1.5 */
  434. if (l_unlikely(MAX_SIZET - sz < B->n)) /* overflow in (B->n + sz)? */
  435. return luaL_error(B->L, "buffer too large");
  436. if (newsize < B->n + sz) /* not big enough? */
  437. newsize = B->n + sz;
  438. return newsize;
  439. }
  440. /*
  441. ** Returns a pointer to a free area with at least 'sz' bytes in buffer
  442. ** 'B'. 'boxidx' is the relative position in the stack where is the
  443. ** buffer's box or its placeholder.
  444. */
  445. static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
  446. checkbufferlevel(B, boxidx);
  447. if (B->size - B->n >= sz) /* enough space? */
  448. return B->b + B->n;
  449. else {
  450. lua_State *L = B->L;
  451. char *newbuff;
  452. size_t newsize = newbuffsize(B, sz);
  453. /* create larger buffer */
  454. if (buffonstack(B)) /* buffer already has a box? */
  455. newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */
  456. else { /* no box yet */
  457. lua_remove(L, boxidx); /* remove placeholder */
  458. newbox(L); /* create a new box */
  459. lua_insert(L, boxidx); /* move box to its intended position */
  460. lua_toclose(L, boxidx);
  461. newbuff = (char *)resizebox(L, boxidx, newsize);
  462. memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
  463. }
  464. B->b = newbuff;
  465. B->size = newsize;
  466. return newbuff + B->n;
  467. }
  468. }
  469. /*
  470. ** returns a pointer to a free area with at least 'sz' bytes
  471. */
  472. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  473. return prepbuffsize(B, sz, -1);
  474. }
  475. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  476. if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
  477. char *b = prepbuffsize(B, l, -1);
  478. memcpy(b, s, l * sizeof(char));
  479. luaL_addsize(B, l);
  480. }
  481. }
  482. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  483. luaL_addlstring(B, s, strlen(s));
  484. }
  485. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  486. lua_State *L = B->L;
  487. checkbufferlevel(B, -1);
  488. lua_pushlstring(L, B->b, B->n);
  489. if (buffonstack(B))
  490. lua_closeslot(L, -2); /* close the box */
  491. lua_remove(L, -2); /* remove box or placeholder from the stack */
  492. }
  493. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  494. luaL_addsize(B, sz);
  495. luaL_pushresult(B);
  496. }
  497. /*
  498. ** 'luaL_addvalue' is the only function in the Buffer system where the
  499. ** box (if existent) is not on the top of the stack. So, instead of
  500. ** calling 'luaL_addlstring', it replicates the code using -2 as the
  501. ** last argument to 'prepbuffsize', signaling that the box is (or will
  502. ** be) below the string being added to the buffer. (Box creation can
  503. ** trigger an emergency GC, so we should not remove the string from the
  504. ** stack before we have the space guaranteed.)
  505. */
  506. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  507. lua_State *L = B->L;
  508. size_t len;
  509. const char *s = lua_tolstring(L, -1, &len);
  510. char *b = prepbuffsize(B, len, -2);
  511. memcpy(b, s, len * sizeof(char));
  512. luaL_addsize(B, len);
  513. lua_pop(L, 1); /* pop string */
  514. }
  515. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  516. B->L = L;
  517. B->b = B->init.b;
  518. B->n = 0;
  519. B->size = LUAL_BUFFERSIZE;
  520. lua_pushlightuserdata(L, (void*)B); /* push placeholder */
  521. }
  522. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  523. luaL_buffinit(L, B);
  524. return prepbuffsize(B, sz, -1);
  525. }
  526. /* }====================================================== */
  527. /*
  528. ** {======================================================
  529. ** Reference system
  530. ** =======================================================
  531. */
  532. /* index of free-list header (after the predefined values) */
  533. #define freelist (LUA_RIDX_LAST + 1)
  534. /*
  535. ** The previously freed references form a linked list:
  536. ** t[freelist] is the index of a first free index, or zero if list is
  537. ** empty; t[t[freelist]] is the index of the second element; etc.
  538. */
  539. LUALIB_API int luaL_ref (lua_State *L, int t) {
  540. int ref;
  541. if (lua_isnil(L, -1)) {
  542. lua_pop(L, 1); /* remove from stack */
  543. return LUA_REFNIL; /* 'nil' has a unique fixed reference */
  544. }
  545. t = lua_absindex(L, t);
  546. if (lua_rawgeti(L, t, freelist) == LUA_TNIL) { /* first access? */
  547. ref = 0; /* list is empty */
  548. lua_pushinteger(L, 0); /* initialize as an empty list */
  549. lua_rawseti(L, t, freelist); /* ref = t[freelist] = 0 */
  550. }
  551. else { /* already initialized */
  552. lua_assert(lua_isinteger(L, -1));
  553. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  554. }
  555. lua_pop(L, 1); /* remove element from stack */
  556. if (ref != 0) { /* any free element? */
  557. lua_rawgeti(L, t, ref); /* remove it from list */
  558. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  559. }
  560. else /* no free elements */
  561. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  562. lua_rawseti(L, t, ref);
  563. return ref;
  564. }
  565. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  566. if (ref >= 0) {
  567. t = lua_absindex(L, t);
  568. lua_rawgeti(L, t, freelist);
  569. lua_assert(lua_isinteger(L, -1));
  570. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  571. lua_pushinteger(L, ref);
  572. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  573. }
  574. }
  575. /* }====================================================== */
  576. /*
  577. ** {======================================================
  578. ** Load functions
  579. ** =======================================================
  580. */
  581. typedef struct LoadF {
  582. int n; /* number of pre-read characters */
  583. FILE *f; /* file being read */
  584. char buff[BUFSIZ]; /* area for reading file */
  585. } LoadF;
  586. static const char *getF (lua_State *L, void *ud, size_t *size) {
  587. LoadF *lf = (LoadF *)ud;
  588. (void)L; /* not used */
  589. if (lf->n > 0) { /* are there pre-read characters to be read? */
  590. *size = lf->n; /* return them (chars already in buffer) */
  591. lf->n = 0; /* no more pre-read characters */
  592. }
  593. else { /* read a block from file */
  594. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  595. 'getF' called 'fread', it might still wait for user input.
  596. The next check avoids this problem. */
  597. if (feof(lf->f)) return NULL;
  598. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  599. }
  600. return lf->buff;
  601. }
  602. static int errfile (lua_State *L, const char *what, int fnameindex) {
  603. int err = errno;
  604. const char *filename = lua_tostring(L, fnameindex) + 1;
  605. if (err != 0)
  606. lua_pushfstring(L, "cannot %s %s: %s", what, filename, strerror(err));
  607. else
  608. lua_pushfstring(L, "cannot %s %s", what, filename);
  609. lua_remove(L, fnameindex);
  610. return LUA_ERRFILE;
  611. }
  612. /*
  613. ** Skip an optional BOM at the start of a stream. If there is an
  614. ** incomplete BOM (the first character is correct but the rest is
  615. ** not), returns the first character anyway to force an error
  616. ** (as no chunk can start with 0xEF).
  617. */
  618. static int skipBOM (FILE *f) {
  619. int c = getc(f); /* read first character */
  620. if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF) /* correct BOM? */
  621. return getc(f); /* ignore BOM and return next char */
  622. else /* no (valid) BOM */
  623. return c; /* return first character */
  624. }
  625. /*
  626. ** reads the first character of file 'f' and skips an optional BOM mark
  627. ** in its beginning plus its first line if it starts with '#'. Returns
  628. ** true if it skipped the first line. In any case, '*cp' has the
  629. ** first "valid" character of the file (after the optional BOM and
  630. ** a first-line comment).
  631. */
  632. static int skipcomment (FILE *f, int *cp) {
  633. int c = *cp = skipBOM(f);
  634. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  635. do { /* skip first line */
  636. c = getc(f);
  637. } while (c != EOF && c != '\n');
  638. *cp = getc(f); /* next character after comment, if present */
  639. return 1; /* there was a comment */
  640. }
  641. else return 0; /* no comment */
  642. }
  643. LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
  644. const char *mode) {
  645. LoadF lf;
  646. int status, readstatus;
  647. int c;
  648. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  649. if (filename == NULL) {
  650. lua_pushliteral(L, "=stdin");
  651. lf.f = stdin;
  652. }
  653. else {
  654. lua_pushfstring(L, "@%s", filename);
  655. errno = 0;
  656. lf.f = fopen(filename, "r");
  657. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  658. }
  659. lf.n = 0;
  660. if (skipcomment(lf.f, &c)) /* read initial portion */
  661. lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */
  662. if (c == LUA_SIGNATURE[0]) { /* binary file? */
  663. lf.n = 0; /* remove possible newline */
  664. if (filename) { /* "real" file? */
  665. errno = 0;
  666. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  667. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  668. skipcomment(lf.f, &c); /* re-read initial portion */
  669. }
  670. }
  671. if (c != EOF)
  672. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  673. errno = 0;
  674. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  675. readstatus = ferror(lf.f);
  676. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  677. if (readstatus) {
  678. lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
  679. return errfile(L, "read", fnameindex);
  680. }
  681. lua_remove(L, fnameindex);
  682. return status;
  683. }
  684. typedef struct LoadS {
  685. const char *s;
  686. size_t size;
  687. } LoadS;
  688. static const char *getS (lua_State *L, void *ud, size_t *size) {
  689. LoadS *ls = (LoadS *)ud;
  690. (void)L; /* not used */
  691. if (ls->size == 0) return NULL;
  692. *size = ls->size;
  693. ls->size = 0;
  694. return ls->s;
  695. }
  696. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  697. const char *name, const char *mode) {
  698. LoadS ls;
  699. ls.s = buff;
  700. ls.size = size;
  701. return lua_load(L, getS, &ls, name, mode);
  702. }
  703. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  704. return luaL_loadbuffer(L, s, strlen(s), s);
  705. }
  706. /* }====================================================== */
  707. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  708. if (!lua_getmetatable(L, obj)) /* no metatable? */
  709. return LUA_TNIL;
  710. else {
  711. int tt;
  712. lua_pushstring(L, event);
  713. tt = lua_rawget(L, -2);
  714. if (tt == LUA_TNIL) /* is metafield nil? */
  715. lua_pop(L, 2); /* remove metatable and metafield */
  716. else
  717. lua_remove(L, -2); /* remove only metatable */
  718. return tt; /* return metafield type */
  719. }
  720. }
  721. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  722. obj = lua_absindex(L, obj);
  723. if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
  724. return 0;
  725. lua_pushvalue(L, obj);
  726. lua_call(L, 1, 1);
  727. return 1;
  728. }
  729. LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
  730. lua_Integer l;
  731. int isnum;
  732. lua_len(L, idx);
  733. l = lua_tointegerx(L, -1, &isnum);
  734. if (l_unlikely(!isnum))
  735. luaL_error(L, "object length is not an integer");
  736. lua_pop(L, 1); /* remove object */
  737. return l;
  738. }
  739. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  740. idx = lua_absindex(L,idx);
  741. if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
  742. if (!lua_isstring(L, -1))
  743. luaL_error(L, "'__tostring' must return a string");
  744. }
  745. else {
  746. switch (lua_type(L, idx)) {
  747. case LUA_TNUMBER: {
  748. if (lua_isinteger(L, idx))
  749. lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
  750. else
  751. lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
  752. break;
  753. }
  754. case LUA_TSTRING:
  755. lua_pushvalue(L, idx);
  756. break;
  757. case LUA_TBOOLEAN:
  758. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  759. break;
  760. case LUA_TNIL:
  761. lua_pushliteral(L, "nil");
  762. break;
  763. default: {
  764. int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
  765. const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
  766. luaL_typename(L, idx);
  767. lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
  768. if (tt != LUA_TNIL)
  769. lua_remove(L, -2); /* remove '__name' */
  770. break;
  771. }
  772. }
  773. }
  774. return lua_tolstring(L, -1, len);
  775. }
  776. /*
  777. ** set functions from list 'l' into table at top - 'nup'; each
  778. ** function gets the 'nup' elements at the top as upvalues.
  779. ** Returns with only the table at the stack.
  780. */
  781. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  782. luaL_checkstack(L, nup, "too many upvalues");
  783. for (; l->name != NULL; l++) { /* fill the table with given functions */
  784. if (l->func == NULL) /* placeholder? */
  785. lua_pushboolean(L, 0);
  786. else {
  787. int i;
  788. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  789. lua_pushvalue(L, -nup);
  790. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  791. }
  792. lua_setfield(L, -(nup + 2), l->name);
  793. }
  794. lua_pop(L, nup); /* remove upvalues */
  795. }
  796. /*
  797. ** ensure that stack[idx][fname] has a table and push that table
  798. ** into the stack
  799. */
  800. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  801. if (lua_getfield(L, idx, fname) == LUA_TTABLE)
  802. return 1; /* table already there */
  803. else {
  804. lua_pop(L, 1); /* remove previous result */
  805. idx = lua_absindex(L, idx);
  806. lua_newtable(L);
  807. lua_pushvalue(L, -1); /* copy to be left at top */
  808. lua_setfield(L, idx, fname); /* assign new table to field */
  809. return 0; /* false, because did not find table there */
  810. }
  811. }
  812. /*
  813. ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
  814. ** to open a module, registers the result in 'package.loaded' table and,
  815. ** if 'glb' is true, also registers the result in the global table.
  816. ** Leaves resulting module on the top.
  817. */
  818. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  819. lua_CFunction openf, int glb) {
  820. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  821. lua_getfield(L, -1, modname); /* LOADED[modname] */
  822. if (!lua_toboolean(L, -1)) { /* package not already loaded? */
  823. lua_pop(L, 1); /* remove field */
  824. lua_pushcfunction(L, openf);
  825. lua_pushstring(L, modname); /* argument to open function */
  826. lua_call(L, 1, 1); /* call 'openf' to open module */
  827. lua_pushvalue(L, -1); /* make copy of module (call result) */
  828. lua_setfield(L, -3, modname); /* LOADED[modname] = module */
  829. }
  830. lua_remove(L, -2); /* remove LOADED table */
  831. if (glb) {
  832. lua_pushvalue(L, -1); /* copy of module */
  833. lua_setglobal(L, modname); /* _G[modname] = module */
  834. }
  835. }
  836. LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
  837. const char *p, const char *r) {
  838. const char *wild;
  839. size_t l = strlen(p);
  840. while ((wild = strstr(s, p)) != NULL) {
  841. luaL_addlstring(b, s, wild - s); /* push prefix */
  842. luaL_addstring(b, r); /* push replacement in place of pattern */
  843. s = wild + l; /* continue after 'p' */
  844. }
  845. luaL_addstring(b, s); /* push last suffix */
  846. }
  847. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s,
  848. const char *p, const char *r) {
  849. luaL_Buffer b;
  850. luaL_buffinit(L, &b);
  851. luaL_addgsub(&b, s, p, r);
  852. luaL_pushresult(&b);
  853. return lua_tostring(L, -1);
  854. }
  855. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  856. (void)ud; (void)osize; /* not used */
  857. if (nsize == 0) {
  858. free(ptr);
  859. return NULL;
  860. }
  861. else
  862. return realloc(ptr, nsize);
  863. }
  864. /*
  865. ** Standard panic funcion just prints an error message. The test
  866. ** with 'lua_type' avoids possible memory errors in 'lua_tostring'.
  867. */
  868. static int panic (lua_State *L) {
  869. const char *msg = (lua_type(L, -1) == LUA_TSTRING)
  870. ? lua_tostring(L, -1)
  871. : "error object is not a string";
  872. lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  873. msg);
  874. return 0; /* return to Lua to abort */
  875. }
  876. /*
  877. ** Warning functions:
  878. ** warnfoff: warning system is off
  879. ** warnfon: ready to start a new message
  880. ** warnfcont: previous message is to be continued
  881. */
  882. static void warnfoff (void *ud, const char *message, int tocont);
  883. static void warnfon (void *ud, const char *message, int tocont);
  884. static void warnfcont (void *ud, const char *message, int tocont);
  885. /*
  886. ** Check whether message is a control message. If so, execute the
  887. ** control or ignore it if unknown.
  888. */
  889. static int checkcontrol (lua_State *L, const char *message, int tocont) {
  890. if (tocont || *(message++) != '@') /* not a control message? */
  891. return 0;
  892. else {
  893. if (strcmp(message, "off") == 0)
  894. lua_setwarnf(L, warnfoff, L); /* turn warnings off */
  895. else if (strcmp(message, "on") == 0)
  896. lua_setwarnf(L, warnfon, L); /* turn warnings on */
  897. return 1; /* it was a control message */
  898. }
  899. }
  900. static void warnfoff (void *ud, const char *message, int tocont) {
  901. checkcontrol((lua_State *)ud, message, tocont);
  902. }
  903. /*
  904. ** Writes the message and handle 'tocont', finishing the message
  905. ** if needed and setting the next warn function.
  906. */
  907. static void warnfcont (void *ud, const char *message, int tocont) {
  908. lua_State *L = (lua_State *)ud;
  909. lua_writestringerror("%s", message); /* write message */
  910. if (tocont) /* not the last part? */
  911. lua_setwarnf(L, warnfcont, L); /* to be continued */
  912. else { /* last part */
  913. lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
  914. lua_setwarnf(L, warnfon, L); /* next call is a new message */
  915. }
  916. }
  917. static void warnfon (void *ud, const char *message, int tocont) {
  918. if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */
  919. return; /* nothing else to be done */
  920. lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
  921. warnfcont(ud, message, tocont); /* finish processing */
  922. }
  923. LUALIB_API lua_State *luaL_newstate (void) {
  924. lua_State *L = lua_newstate(l_alloc, NULL);
  925. if (l_likely(L)) {
  926. lua_atpanic(L, &panic);
  927. lua_setwarnf(L, warnfoff, L); /* default is warnings off */
  928. }
  929. return L;
  930. }
  931. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
  932. lua_Number v = lua_version(L);
  933. if (sz != LUAL_NUMSIZES) /* check numeric types */
  934. luaL_error(L, "core and library have incompatible numeric types");
  935. else if (v != ver)
  936. luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
  937. (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
  938. }