lauxlib.c 35 KB

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