lauxlib.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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 (pushglobalfuncname(L, ar)) { /* try first a global name */
  79. lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
  80. lua_remove(L, -2); /* remove name */
  81. }
  82. else if (*ar->namewhat != '\0') /* is there a name from code? */
  83. lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
  84. else if (*ar->what == 'm') /* main? */
  85. lua_pushliteral(L, "main chunk");
  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. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  147. return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
  148. lua_getinfo(L, "n", &ar);
  149. if (strcmp(ar.namewhat, "method") == 0) {
  150. arg--; /* do not count 'self' */
  151. if (arg == 0) /* error is in the self argument itself? */
  152. return luaL_error(L, "calling '%s' on bad self (%s)",
  153. ar.name, extramsg);
  154. }
  155. if (ar.name == NULL)
  156. ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
  157. return luaL_error(L, "bad argument #%d to '%s' (%s)",
  158. arg, ar.name, extramsg);
  159. }
  160. LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
  161. const char *msg;
  162. const char *typearg; /* name for the type of the actual argument */
  163. if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
  164. typearg = lua_tostring(L, -1); /* use the given type name */
  165. else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
  166. typearg = "light userdata"; /* special name for messages */
  167. else
  168. typearg = luaL_typename(L, arg); /* standard name */
  169. msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
  170. return luaL_argerror(L, arg, msg);
  171. }
  172. static void tag_error (lua_State *L, int arg, int tag) {
  173. luaL_typeerror(L, arg, lua_typename(L, tag));
  174. }
  175. /*
  176. ** The use of 'lua_pushfstring' ensures this function does not
  177. ** need reserved stack space when called.
  178. */
  179. LUALIB_API void luaL_where (lua_State *L, int level) {
  180. lua_Debug ar;
  181. if (lua_getstack(L, level, &ar)) { /* check function at level */
  182. lua_getinfo(L, "Sl", &ar); /* get info about it */
  183. if (ar.currentline > 0) { /* is there info? */
  184. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  185. return;
  186. }
  187. }
  188. lua_pushfstring(L, ""); /* else, no information available... */
  189. }
  190. /*
  191. ** Again, the use of 'lua_pushvfstring' ensures this function does
  192. ** not need reserved stack space when called. (At worst, it generates
  193. ** an error with "stack overflow" instead of the given message.)
  194. */
  195. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  196. va_list argp;
  197. va_start(argp, fmt);
  198. luaL_where(L, 1);
  199. lua_pushvfstring(L, fmt, argp);
  200. va_end(argp);
  201. lua_concat(L, 2);
  202. return lua_error(L);
  203. }
  204. LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
  205. int en = errno; /* calls to Lua API may change this value */
  206. if (stat) {
  207. lua_pushboolean(L, 1);
  208. return 1;
  209. }
  210. else {
  211. const char *msg;
  212. luaL_pushfail(L);
  213. msg = (en != 0) ? strerror(en) : "(no extra info)";
  214. if (fname)
  215. lua_pushfstring(L, "%s: %s", fname, msg);
  216. else
  217. lua_pushstring(L, msg);
  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. /*
  552. ** The previously freed references form a linked list: t[1] is the index
  553. ** of a first free index, t[t[1]] is the index of the second element,
  554. ** etc. A zero signals the end of the list.
  555. */
  556. LUALIB_API int luaL_ref (lua_State *L, int t) {
  557. int ref;
  558. if (lua_isnil(L, -1)) {
  559. lua_pop(L, 1); /* remove from stack */
  560. return LUA_REFNIL; /* 'nil' has a unique fixed reference */
  561. }
  562. t = lua_absindex(L, t);
  563. if (lua_rawgeti(L, t, 1) == LUA_TNUMBER) /* already initialized? */
  564. ref = (int)lua_tointeger(L, -1); /* ref = t[1] */
  565. else { /* first access */
  566. lua_assert(!lua_toboolean(L, -1)); /* must be nil or false */
  567. ref = 0; /* list is empty */
  568. lua_pushinteger(L, 0); /* initialize as an empty list */
  569. lua_rawseti(L, t, 1); /* ref = t[1] = 0 */
  570. }
  571. lua_pop(L, 1); /* remove element from stack */
  572. if (ref != 0) { /* any free element? */
  573. lua_rawgeti(L, t, ref); /* remove it from list */
  574. lua_rawseti(L, t, 1); /* (t[1] = t[ref]) */
  575. }
  576. else /* no free elements */
  577. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  578. lua_rawseti(L, t, ref);
  579. return ref;
  580. }
  581. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  582. if (ref >= 0) {
  583. t = lua_absindex(L, t);
  584. lua_rawgeti(L, t, 1);
  585. lua_assert(lua_isinteger(L, -1));
  586. lua_rawseti(L, t, ref); /* t[ref] = t[1] */
  587. lua_pushinteger(L, ref);
  588. lua_rawseti(L, t, 1); /* t[1] = ref */
  589. }
  590. }
  591. /* }====================================================== */
  592. /*
  593. ** {======================================================
  594. ** Load functions
  595. ** =======================================================
  596. */
  597. typedef struct LoadF {
  598. int n; /* number of pre-read characters */
  599. FILE *f; /* file being read */
  600. char buff[BUFSIZ]; /* area for reading file */
  601. } LoadF;
  602. static const char *getF (lua_State *L, void *ud, size_t *size) {
  603. LoadF *lf = (LoadF *)ud;
  604. (void)L; /* not used */
  605. if (lf->n > 0) { /* are there pre-read characters to be read? */
  606. *size = lf->n; /* return them (chars already in buffer) */
  607. lf->n = 0; /* no more pre-read characters */
  608. }
  609. else { /* read a block from file */
  610. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  611. 'getF' called 'fread', it might still wait for user input.
  612. The next check avoids this problem. */
  613. if (feof(lf->f)) return NULL;
  614. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  615. }
  616. return lf->buff;
  617. }
  618. static int errfile (lua_State *L, const char *what, int fnameindex) {
  619. int err = errno;
  620. const char *filename = lua_tostring(L, fnameindex) + 1;
  621. if (err != 0)
  622. lua_pushfstring(L, "cannot %s %s: %s", what, filename, strerror(err));
  623. else
  624. lua_pushfstring(L, "cannot %s %s", what, filename);
  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. errno = 0;
  672. lf.f = fopen(filename, "r");
  673. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  674. }
  675. lf.n = 0;
  676. if (skipcomment(lf.f, &c)) /* read initial portion */
  677. lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */
  678. if (c == LUA_SIGNATURE[0]) { /* binary file? */
  679. lf.n = 0; /* remove possible newline */
  680. if (filename) { /* "real" file? */
  681. errno = 0;
  682. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  683. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  684. skipcomment(lf.f, &c); /* re-read initial portion */
  685. }
  686. }
  687. if (c != EOF)
  688. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  689. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  690. readstatus = ferror(lf.f);
  691. errno = 0; /* no useful error number until here */
  692. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  693. if (readstatus) {
  694. lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
  695. return errfile(L, "read", fnameindex);
  696. }
  697. lua_remove(L, fnameindex);
  698. return status;
  699. }
  700. typedef struct LoadS {
  701. const char *s;
  702. size_t size;
  703. } LoadS;
  704. static const char *getS (lua_State *L, void *ud, size_t *size) {
  705. LoadS *ls = (LoadS *)ud;
  706. (void)L; /* not used */
  707. if (ls->size == 0) return NULL;
  708. *size = ls->size;
  709. ls->size = 0;
  710. return ls->s;
  711. }
  712. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  713. const char *name, const char *mode) {
  714. LoadS ls;
  715. ls.s = buff;
  716. ls.size = size;
  717. return lua_load(L, getS, &ls, name, mode);
  718. }
  719. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  720. return luaL_loadbuffer(L, s, strlen(s), s);
  721. }
  722. /* }====================================================== */
  723. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  724. if (!lua_getmetatable(L, obj)) /* no metatable? */
  725. return LUA_TNIL;
  726. else {
  727. int tt;
  728. lua_pushstring(L, event);
  729. tt = lua_rawget(L, -2);
  730. if (tt == LUA_TNIL) /* is metafield nil? */
  731. lua_pop(L, 2); /* remove metatable and metafield */
  732. else
  733. lua_remove(L, -2); /* remove only metatable */
  734. return tt; /* return metafield type */
  735. }
  736. }
  737. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  738. obj = lua_absindex(L, obj);
  739. if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
  740. return 0;
  741. lua_pushvalue(L, obj);
  742. lua_call(L, 1, 1);
  743. return 1;
  744. }
  745. LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
  746. lua_Integer l;
  747. int isnum;
  748. lua_len(L, idx);
  749. l = lua_tointegerx(L, -1, &isnum);
  750. if (l_unlikely(!isnum))
  751. luaL_error(L, "object length is not an integer");
  752. lua_pop(L, 1); /* remove object */
  753. return l;
  754. }
  755. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  756. idx = lua_absindex(L,idx);
  757. if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
  758. if (!lua_isstring(L, -1))
  759. luaL_error(L, "'__tostring' must return a string");
  760. }
  761. else {
  762. switch (lua_type(L, idx)) {
  763. case LUA_TNUMBER: {
  764. if (lua_isinteger(L, idx))
  765. lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
  766. else
  767. lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
  768. break;
  769. }
  770. case LUA_TSTRING:
  771. lua_pushvalue(L, idx);
  772. break;
  773. case LUA_TBOOLEAN:
  774. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  775. break;
  776. case LUA_TNIL:
  777. lua_pushliteral(L, "nil");
  778. break;
  779. default: {
  780. int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
  781. const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
  782. luaL_typename(L, idx);
  783. lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
  784. if (tt != LUA_TNIL)
  785. lua_remove(L, -2); /* remove '__name' */
  786. break;
  787. }
  788. }
  789. }
  790. return lua_tolstring(L, -1, len);
  791. }
  792. /*
  793. ** set functions from list 'l' into table at top - 'nup'; each
  794. ** function gets the 'nup' elements at the top as upvalues.
  795. ** Returns with only the table at the stack.
  796. */
  797. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  798. luaL_checkstack(L, nup, "too many upvalues");
  799. for (; l->name != NULL; l++) { /* fill the table with given functions */
  800. if (l->func == NULL) /* placeholder? */
  801. lua_pushboolean(L, 0);
  802. else {
  803. int i;
  804. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  805. lua_pushvalue(L, -nup);
  806. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  807. }
  808. lua_setfield(L, -(nup + 2), l->name);
  809. }
  810. lua_pop(L, nup); /* remove upvalues */
  811. }
  812. /*
  813. ** ensure that stack[idx][fname] has a table and push that table
  814. ** into the stack
  815. */
  816. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  817. if (lua_getfield(L, idx, fname) == LUA_TTABLE)
  818. return 1; /* table already there */
  819. else {
  820. lua_pop(L, 1); /* remove previous result */
  821. idx = lua_absindex(L, idx);
  822. lua_newtable(L);
  823. lua_pushvalue(L, -1); /* copy to be left at top */
  824. lua_setfield(L, idx, fname); /* assign new table to field */
  825. return 0; /* false, because did not find table there */
  826. }
  827. }
  828. /*
  829. ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
  830. ** to open a module, registers the result in 'package.loaded' table and,
  831. ** if 'glb' is true, also registers the result in the global table.
  832. ** Leaves resulting module on the top.
  833. */
  834. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  835. lua_CFunction openf, int glb) {
  836. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  837. lua_getfield(L, -1, modname); /* LOADED[modname] */
  838. if (!lua_toboolean(L, -1)) { /* package not already loaded? */
  839. lua_pop(L, 1); /* remove field */
  840. lua_pushcfunction(L, openf);
  841. lua_pushstring(L, modname); /* argument to open function */
  842. lua_call(L, 1, 1); /* call 'openf' to open module */
  843. lua_pushvalue(L, -1); /* make copy of module (call result) */
  844. lua_setfield(L, -3, modname); /* LOADED[modname] = module */
  845. }
  846. lua_remove(L, -2); /* remove LOADED table */
  847. if (glb) {
  848. lua_pushvalue(L, -1); /* copy of module */
  849. lua_setglobal(L, modname); /* _G[modname] = module */
  850. }
  851. }
  852. LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
  853. const char *p, const char *r) {
  854. const char *wild;
  855. size_t l = strlen(p);
  856. while ((wild = strstr(s, p)) != NULL) {
  857. luaL_addlstring(b, s, wild - s); /* push prefix */
  858. luaL_addstring(b, r); /* push replacement in place of pattern */
  859. s = wild + l; /* continue after 'p' */
  860. }
  861. luaL_addstring(b, s); /* push last suffix */
  862. }
  863. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s,
  864. const char *p, const char *r) {
  865. luaL_Buffer b;
  866. luaL_buffinit(L, &b);
  867. luaL_addgsub(&b, s, p, r);
  868. luaL_pushresult(&b);
  869. return lua_tostring(L, -1);
  870. }
  871. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  872. (void)ud; (void)osize; /* not used */
  873. if (nsize == 0) {
  874. free(ptr);
  875. return NULL;
  876. }
  877. else
  878. return realloc(ptr, nsize);
  879. }
  880. /*
  881. ** Standard panic function just prints an error message. The test
  882. ** with 'lua_type' avoids possible memory errors in 'lua_tostring'.
  883. */
  884. static int panic (lua_State *L) {
  885. const char *msg = (lua_type(L, -1) == LUA_TSTRING)
  886. ? lua_tostring(L, -1)
  887. : "error object is not a string";
  888. lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  889. msg);
  890. return 0; /* return to Lua to abort */
  891. }
  892. /*
  893. ** Warning functions:
  894. ** warnfoff: warning system is off
  895. ** warnfon: ready to start a new message
  896. ** warnfcont: previous message is to be continued
  897. */
  898. static void warnfoff (void *ud, const char *message, int tocont);
  899. static void warnfon (void *ud, const char *message, int tocont);
  900. static void warnfcont (void *ud, const char *message, int tocont);
  901. /*
  902. ** Check whether message is a control message. If so, execute the
  903. ** control or ignore it if unknown.
  904. */
  905. static int checkcontrol (lua_State *L, const char *message, int tocont) {
  906. if (tocont || *(message++) != '@') /* not a control message? */
  907. return 0;
  908. else {
  909. if (strcmp(message, "off") == 0)
  910. lua_setwarnf(L, warnfoff, L); /* turn warnings off */
  911. else if (strcmp(message, "on") == 0)
  912. lua_setwarnf(L, warnfon, L); /* turn warnings on */
  913. return 1; /* it was a control message */
  914. }
  915. }
  916. static void warnfoff (void *ud, const char *message, int tocont) {
  917. checkcontrol((lua_State *)ud, message, tocont);
  918. }
  919. /*
  920. ** Writes the message and handle 'tocont', finishing the message
  921. ** if needed and setting the next warn function.
  922. */
  923. static void warnfcont (void *ud, const char *message, int tocont) {
  924. lua_State *L = (lua_State *)ud;
  925. lua_writestringerror("%s", message); /* write message */
  926. if (tocont) /* not the last part? */
  927. lua_setwarnf(L, warnfcont, L); /* to be continued */
  928. else { /* last part */
  929. lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
  930. lua_setwarnf(L, warnfon, L); /* next call is a new message */
  931. }
  932. }
  933. static void warnfon (void *ud, const char *message, int tocont) {
  934. if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */
  935. return; /* nothing else to be done */
  936. lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
  937. warnfcont(ud, message, tocont); /* finish processing */
  938. }
  939. /*
  940. ** A function to compute an unsigned int with some level of
  941. ** randomness. Rely on Address Space Layout Randomization (if present)
  942. ** and the current time.
  943. */
  944. #if !defined(luai_makeseed)
  945. #include <time.h>
  946. /* Size for the buffer, in bytes */
  947. #define BUFSEEDB (sizeof(void*) + sizeof(time_t))
  948. /* Size for the buffer in int's, rounded up */
  949. #define BUFSEED ((BUFSEEDB + sizeof(int) - 1) / sizeof(int))
  950. /*
  951. ** Copy the contents of variable 'v' into the buffer pointed by 'b'.
  952. ** (The '&b[0]' disguises 'b' to fix an absurd warning from clang.)
  953. */
  954. #define addbuff(b,v) (memcpy(&b[0], &(v), sizeof(v)), b += sizeof(v))
  955. static unsigned int luai_makeseed (void) {
  956. unsigned int buff[BUFSEED];
  957. unsigned int res;
  958. unsigned int i;
  959. time_t t = time(NULL);
  960. char *b = (char*)buff;
  961. addbuff(b, b); /* local variable's address */
  962. addbuff(b, t); /* time */
  963. /* fill (rare but possible) remain of the buffer with zeros */
  964. memset(b, 0, sizeof(buff) - BUFSEEDB);
  965. res = buff[0];
  966. for (i = 1; i < BUFSEED; i++)
  967. res ^= (res >> 3) + (res << 7) + buff[i];
  968. return res;
  969. }
  970. #endif
  971. LUALIB_API unsigned int luaL_makeseed (lua_State *L) {
  972. (void)L; /* unused */
  973. return luai_makeseed();
  974. }
  975. LUALIB_API lua_State *luaL_newstate (void) {
  976. lua_State *L = lua_newstate(l_alloc, NULL, luai_makeseed());
  977. if (l_likely(L)) {
  978. lua_atpanic(L, &panic);
  979. lua_setwarnf(L, warnfoff, L); /* default is warnings off */
  980. }
  981. return L;
  982. }
  983. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
  984. lua_Number v = lua_version(L);
  985. if (sz != LUAL_NUMSIZES) /* check numeric types */
  986. luaL_error(L, "core and library have incompatible numeric types");
  987. else if (v != ver)
  988. luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
  989. (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
  990. }