lauxlib.c 35 KB

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