lauxlib.c 35 KB

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