lauxlib.c 34 KB

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