lauxlib.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. /*
  2. ** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define LUAC_CROSS_FILE
  7. #include "lua.h"
  8. #include C_HEADER_CTYPE
  9. #include C_HEADER_ERRNO
  10. #include C_HEADER_STDIO
  11. #include C_HEADER_STDLIB
  12. #include C_HEADER_STRING
  13. #ifndef LUA_CROSS_COMPILER
  14. #include "vfs.h"
  15. #else
  16. #endif
  17. /* This file uses only the official API of Lua.
  18. ** Any function declared here could be written as an application function.
  19. */
  20. #define lauxlib_c
  21. #define LUA_LIB
  22. #include "lrotable.h"
  23. #include "lauxlib.h"
  24. #include "lgc.h"
  25. #include "ldo.h"
  26. #include "lobject.h"
  27. #include "lstate.h"
  28. #include "legc.h"
  29. #define FREELIST_REF 0 /* free list of references */
  30. /* convert a stack index to positive */
  31. #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
  32. lua_gettop(L) + (i) + 1)
  33. // Parameters for luaI_openlib
  34. #define LUA_USECCLOSURES 0
  35. #define LUA_USELIGHTFUNCTIONS 1
  36. //#define DEBUG_ALLOCATOR
  37. #ifdef DEBUG_ALLOCATOR
  38. /*
  39. ** {======================================================================
  40. ** Diagnosticd version for realloc. This is enabled only if the
  41. ** DEBUG_ALLOCATOR is defined. It is a cutdown version of the allocator
  42. ** used in the Lua Test Suite -- a compromise between the ability catch
  43. ** most alloc/free errors and overruns and working within the RAM limits
  44. ** of the ESP8266 architecture. ONLY FOR HEAVY HACKERS
  45. ** =======================================================================
  46. */
  47. #define this_realloc debug_realloc
  48. #define ASSERT(s) if (!(s)) {asm ("break 0,0" ::);}
  49. #define MARK 0x55 /* 01010101 (a nice pattern) */
  50. #define MARK4 0x55555555
  51. #define MARKSIZE 4 /* size of marks after each block */
  52. #define fillmem(mem,size) memset(mem, -MARK, size)
  53. typedef struct Memcontrol { /* memory-allocator control variables */
  54. uint32_t numblocks;
  55. uint32_t total;
  56. uint32_t maxmem;
  57. uint32_t memlimit;
  58. } Memcontrol;
  59. static Memcontrol mc = {0,0,0,32768};
  60. typedef union MemHeader {
  61. L_Umaxalign a; /* ensures maximum alignment for Header */
  62. struct {
  63. size_t size;
  64. int mark;
  65. } d;
  66. } MemHeader;
  67. static void freeblock (MemHeader *block) {
  68. if (block) {
  69. size_t size = block->d.size;
  70. fillmem(block, sizeof(MemHeader) + size + MARKSIZE); /* erase block */
  71. c_free(block); /* actually free block */
  72. mc.numblocks--; /* update counts */
  73. mc.total -= size;
  74. }
  75. }
  76. void *debug_realloc (void *b, size_t oldsize, size_t size) {
  77. MemHeader *block = cast(MemHeader *, b);
  78. int i;
  79. if (block == NULL) {
  80. oldsize = 0;
  81. } else {
  82. block--; /* go to real header */
  83. ASSERT(block->d.mark == MARK4);
  84. ASSERT(oldsize == block->d.size);
  85. for (i = 0; i < MARKSIZE; i++) /* check marks after block */
  86. ASSERT (cast(char *, b)[oldsize + i] == MARK);
  87. }
  88. if (size == 0) {
  89. freeblock(block);
  90. return NULL;
  91. } else if (size > oldsize && mc.total+size-oldsize > mc.memlimit)
  92. return NULL; /* fake a memory allocation error */
  93. else {
  94. MemHeader *newblock;
  95. int i;
  96. size_t commonsize = (oldsize < size) ? oldsize : size;
  97. size_t realsize = sizeof(MemHeader) + size + MARKSIZE;
  98. newblock = cast(MemHeader *, c_malloc(realsize)); /* alloc a new block */
  99. if (newblock == NULL)
  100. return NULL; /* really out of memory? */
  101. if (block) {
  102. memcpy(newblock + 1, block + 1, commonsize); /* copy old contents */
  103. freeblock(block); /* erase (and check) old copy */
  104. }
  105. /* initialize new part of the block with something weird */
  106. fillmem(cast(char *, newblock + 1) + commonsize, size - commonsize);
  107. /* initialize marks after block */
  108. newblock->d.mark = MARK4;
  109. newblock->d.size = size;
  110. for (i = 0; i < MARKSIZE; i++)
  111. cast(char *, newblock + 1)[size + i] = MARK;
  112. mc.total += size;
  113. if (mc.total > mc.maxmem)
  114. mc.maxmem = mc.total;
  115. mc.numblocks++;
  116. return (newblock + 1);
  117. }
  118. }
  119. /* }====================================================================== */
  120. #else
  121. #define this_realloc(p,os,s) c_realloc(p,s)
  122. #endif
  123. /*
  124. ** {======================================================
  125. ** Error-report functions
  126. ** =======================================================
  127. */
  128. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  129. lua_Debug ar;
  130. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  131. return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
  132. lua_getinfo(L, "n", &ar);
  133. if (c_strcmp(ar.namewhat, "method") == 0) {
  134. narg--; /* do not count `self' */
  135. if (narg == 0) /* error is in the self argument itself? */
  136. return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
  137. ar.name, extramsg);
  138. }
  139. if (ar.name == NULL)
  140. ar.name = "?";
  141. return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
  142. narg, ar.name, extramsg);
  143. }
  144. LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
  145. const char *msg = lua_pushfstring(L, "%s expected, got %s",
  146. tname, luaL_typename(L, narg));
  147. return luaL_argerror(L, narg, msg);
  148. }
  149. static void tag_error (lua_State *L, int narg, int tag) {
  150. luaL_typerror(L, narg, lua_typename(L, tag));
  151. }
  152. LUALIB_API void luaL_where (lua_State *L, int level) {
  153. lua_Debug ar;
  154. if (lua_getstack(L, level, &ar)) { /* check function at level */
  155. lua_getinfo(L, "Sl", &ar); /* get info about it */
  156. if (ar.currentline > 0) { /* is there info? */
  157. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  158. return;
  159. }
  160. }
  161. lua_pushliteral(L, ""); /* else, no information available... */
  162. }
  163. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  164. va_list argp;
  165. va_start(argp, fmt);
  166. luaL_where(L, 1);
  167. lua_pushvfstring(L, fmt, argp);
  168. va_end(argp);
  169. lua_concat(L, 2);
  170. return lua_error(L);
  171. }
  172. /* }====================================================== */
  173. LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
  174. const char *const lst[]) {
  175. const char *name = (def) ? luaL_optstring(L, narg, def) :
  176. luaL_checkstring(L, narg);
  177. int i;
  178. for (i=0; lst[i]; i++)
  179. if (c_strcmp(lst[i], name) == 0)
  180. return i;
  181. return luaL_argerror(L, narg,
  182. lua_pushfstring(L, "invalid option " LUA_QS, name));
  183. }
  184. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  185. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  186. if (!lua_isnil(L, -1)) /* name already in use? */
  187. return 0; /* leave previous value on top, but return 0 */
  188. lua_pop(L, 1);
  189. lua_newtable(L); /* create metatable */
  190. lua_pushvalue(L, -1);
  191. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  192. return 1;
  193. }
  194. LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, void *p) {
  195. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  196. if (!lua_isnil(L, -1)) /* name already in use? */
  197. return 0; /* leave previous value on top, but return 0 */
  198. lua_pop(L, 1);
  199. lua_pushrotable(L, p);
  200. lua_pushvalue(L, -1);
  201. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  202. return 1;
  203. }
  204. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  205. void *p = lua_touserdata(L, ud);
  206. if (p != NULL) { /* value is a userdata? */
  207. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  208. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
  209. if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
  210. lua_pop(L, 2); /* remove both metatables */
  211. return p;
  212. }
  213. }
  214. }
  215. luaL_typerror(L, ud, tname); /* else error */
  216. return NULL; /* to avoid warnings */
  217. }
  218. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
  219. if (!lua_checkstack(L, space))
  220. luaL_error(L, "stack overflow (%s)", mes);
  221. }
  222. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  223. if (lua_type(L, narg) != t)
  224. tag_error(L, narg, t);
  225. }
  226. LUALIB_API void luaL_checkanyfunction (lua_State *L, int narg) {
  227. if (lua_type(L, narg) != LUA_TFUNCTION && lua_type(L, narg) != LUA_TLIGHTFUNCTION) {
  228. const char *msg = lua_pushfstring(L, "function or lightfunction expected, got %s",
  229. luaL_typename(L, narg));
  230. luaL_argerror(L, narg, msg);
  231. }
  232. }
  233. LUALIB_API void luaL_checkanytable (lua_State *L, int narg) {
  234. if (lua_type(L, narg) != LUA_TTABLE && lua_type(L, narg) != LUA_TROTABLE) {
  235. const char *msg = lua_pushfstring(L, "table or rotable expected, got %s",
  236. luaL_typename(L, narg));
  237. luaL_argerror(L, narg, msg);
  238. }
  239. }
  240. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  241. if (lua_type(L, narg) == LUA_TNONE)
  242. luaL_argerror(L, narg, "value expected");
  243. }
  244. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  245. const char *s = lua_tolstring(L, narg, len);
  246. if (!s) tag_error(L, narg, LUA_TSTRING);
  247. return s;
  248. }
  249. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  250. const char *def, size_t *len) {
  251. if (lua_isnoneornil(L, narg)) {
  252. if (len)
  253. *len = (def ? c_strlen(def) : 0);
  254. return def;
  255. }
  256. else return luaL_checklstring(L, narg, len);
  257. }
  258. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  259. lua_Number d = lua_tonumber(L, narg);
  260. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  261. tag_error(L, narg, LUA_TNUMBER);
  262. return d;
  263. }
  264. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  265. return luaL_opt(L, luaL_checknumber, narg, def);
  266. }
  267. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  268. lua_Integer d = lua_tointeger(L, narg);
  269. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  270. tag_error(L, narg, LUA_TNUMBER);
  271. return d;
  272. }
  273. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  274. lua_Integer def) {
  275. return luaL_opt(L, luaL_checkinteger, narg, def);
  276. }
  277. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  278. if (!lua_getmetatable(L, obj)) /* no metatable? */
  279. return 0;
  280. lua_pushstring(L, event);
  281. lua_rawget(L, -2);
  282. if (lua_isnil(L, -1)) {
  283. lua_pop(L, 2); /* remove metatable and metafield */
  284. return 0;
  285. }
  286. else {
  287. lua_remove(L, -2); /* remove only metatable */
  288. return 1;
  289. }
  290. }
  291. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  292. obj = abs_index(L, obj);
  293. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  294. return 0;
  295. lua_pushvalue(L, obj);
  296. lua_call(L, 1, 1);
  297. return 1;
  298. }
  299. LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
  300. const luaL_Reg *l) {
  301. luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
  302. }
  303. LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
  304. const luaL_Reg *l) {
  305. #if LUA_OPTIMIZE_MEMORY > 0
  306. luaI_openlib(L, libname, l, 0, LUA_USELIGHTFUNCTIONS);
  307. #else
  308. luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
  309. #endif
  310. }
  311. static int libsize (const luaL_Reg *l) {
  312. int size = 0;
  313. for (; l->name; l++) size++;
  314. return size;
  315. }
  316. LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
  317. const luaL_Reg *l, int nup, int ftype) {
  318. if (libname) {
  319. int size = libsize(l);
  320. /* check whether lib already exists */
  321. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
  322. lua_getfield(L, -1, libname); /* get _LOADED[libname] */
  323. if (!lua_istable(L, -1)) { /* not found? */
  324. lua_pop(L, 1); /* remove previous result */
  325. /* try global variable (and create one if it does not exist) */
  326. if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
  327. luaL_error(L, "name conflict for module " LUA_QS, libname);
  328. lua_pushvalue(L, -1);
  329. lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
  330. }
  331. lua_remove(L, -2); /* remove _LOADED table */
  332. lua_insert(L, -(nup+1)); /* move library table to below upvalues */
  333. }
  334. for (; l->name; l++) {
  335. int i;
  336. for (i=0; i<nup; i++) /* copy upvalues to the top */
  337. lua_pushvalue(L, -nup);
  338. if (ftype == LUA_USELIGHTFUNCTIONS)
  339. lua_pushlightfunction(L, l->func);
  340. else
  341. lua_pushcclosure(L, l->func, nup);
  342. lua_setfield(L, -(nup+2), l->name);
  343. }
  344. lua_pop(L, nup); /* remove upvalues */
  345. }
  346. /*
  347. ** {======================================================
  348. ** getn-setn: size for arrays
  349. ** =======================================================
  350. */
  351. #if defined(LUA_COMPAT_GETN)
  352. static int checkint (lua_State *L, int topop) {
  353. int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
  354. lua_pop(L, topop);
  355. return n;
  356. }
  357. static void getsizes (lua_State *L) {
  358. lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
  359. if (lua_isnil(L, -1)) { /* no `size' table? */
  360. lua_pop(L, 1); /* remove nil */
  361. lua_newtable(L); /* create it */
  362. lua_pushvalue(L, -1); /* `size' will be its own metatable */
  363. lua_setmetatable(L, -2);
  364. lua_pushliteral(L, "kv");
  365. lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
  366. lua_pushvalue(L, -1);
  367. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */
  368. }
  369. }
  370. LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
  371. t = abs_index(L, t);
  372. lua_pushliteral(L, "n");
  373. lua_rawget(L, t);
  374. if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
  375. lua_pushliteral(L, "n"); /* use it */
  376. lua_pushinteger(L, n);
  377. lua_rawset(L, t);
  378. }
  379. else { /* use `sizes' */
  380. getsizes(L);
  381. lua_pushvalue(L, t);
  382. lua_pushinteger(L, n);
  383. lua_rawset(L, -3); /* sizes[t] = n */
  384. lua_pop(L, 1); /* remove `sizes' */
  385. }
  386. }
  387. LUALIB_API int luaL_getn (lua_State *L, int t) {
  388. int n;
  389. t = abs_index(L, t);
  390. lua_pushliteral(L, "n"); /* try t.n */
  391. lua_rawget(L, t);
  392. if ((n = checkint(L, 1)) >= 0) return n;
  393. getsizes(L); /* else try sizes[t] */
  394. lua_pushvalue(L, t);
  395. lua_rawget(L, -2);
  396. if ((n = checkint(L, 2)) >= 0) return n;
  397. return (int)lua_objlen(L, t);
  398. }
  399. #endif
  400. /* }====================================================== */
  401. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  402. const char *r) {
  403. const char *wild;
  404. size_t l = c_strlen(p);
  405. luaL_Buffer b;
  406. luaL_buffinit(L, &b);
  407. while ((wild = c_strstr(s, p)) != NULL) {
  408. luaL_addlstring(&b, s, wild - s); /* push prefix */
  409. luaL_addstring(&b, r); /* push replacement in place of pattern */
  410. s = wild + l; /* continue after `p' */
  411. }
  412. luaL_addstring(&b, s); /* push last suffix */
  413. luaL_pushresult(&b);
  414. return lua_tostring(L, -1);
  415. }
  416. LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
  417. const char *fname, int szhint) {
  418. const char *e;
  419. lua_pushvalue(L, idx);
  420. do {
  421. e = c_strchr(fname, '.');
  422. if (e == NULL) e = fname + c_strlen(fname);
  423. lua_pushlstring(L, fname, e - fname);
  424. lua_rawget(L, -2);
  425. if (lua_isnil(L, -1)) {
  426. /* If looking for a global variable, check the rotables too */
  427. void *ptable = luaR_findglobal(fname, e - fname);
  428. if (ptable) {
  429. lua_pop(L, 1);
  430. lua_pushrotable(L, ptable);
  431. }
  432. }
  433. if (lua_isnil(L, -1)) { /* no such field? */
  434. lua_pop(L, 1); /* remove this nil */
  435. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  436. lua_pushlstring(L, fname, e - fname);
  437. lua_pushvalue(L, -2);
  438. lua_settable(L, -4); /* set new table into field */
  439. }
  440. else if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { /* field has a non-table value? */
  441. lua_pop(L, 2); /* remove table and value */
  442. return fname; /* return problematic part of the name */
  443. }
  444. lua_remove(L, -2); /* remove previous table */
  445. fname = e + 1;
  446. } while (*e == '.');
  447. return NULL;
  448. }
  449. /*
  450. ** {======================================================
  451. ** Generic Buffer manipulation
  452. ** =======================================================
  453. */
  454. #define bufflen(B) ((B)->p - (B)->buffer)
  455. #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
  456. #define LIMIT (LUA_MINSTACK/2)
  457. static int emptybuffer (luaL_Buffer *B) {
  458. size_t l = bufflen(B);
  459. if (l == 0) return 0; /* put nothing on stack */
  460. else {
  461. lua_pushlstring(B->L, B->buffer, l);
  462. B->p = B->buffer;
  463. B->lvl++;
  464. return 1;
  465. }
  466. }
  467. static void adjuststack (luaL_Buffer *B) {
  468. if (B->lvl > 1) {
  469. lua_State *L = B->L;
  470. int toget = 1; /* number of levels to concat */
  471. size_t toplen = lua_strlen(L, -1);
  472. do {
  473. size_t l = lua_strlen(L, -(toget+1));
  474. if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
  475. toplen += l;
  476. toget++;
  477. }
  478. else break;
  479. } while (toget < B->lvl);
  480. lua_concat(L, toget);
  481. B->lvl = B->lvl - toget + 1;
  482. }
  483. }
  484. LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
  485. if (emptybuffer(B))
  486. adjuststack(B);
  487. return B->buffer;
  488. }
  489. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  490. while (l--)
  491. luaL_addchar(B, *s++);
  492. }
  493. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  494. luaL_addlstring(B, s, c_strlen(s));
  495. }
  496. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  497. emptybuffer(B);
  498. lua_concat(B->L, B->lvl);
  499. B->lvl = 1;
  500. }
  501. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  502. lua_State *L = B->L;
  503. size_t vl;
  504. const char *s = lua_tolstring(L, -1, &vl);
  505. if (vl <= bufffree(B)) { /* fit into buffer? */
  506. c_memcpy(B->p, s, vl); /* put it there */
  507. B->p += vl;
  508. lua_pop(L, 1); /* remove from stack */
  509. }
  510. else {
  511. if (emptybuffer(B))
  512. lua_insert(L, -2); /* put buffer before new value */
  513. B->lvl++; /* add new value into B stack */
  514. adjuststack(B);
  515. }
  516. }
  517. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  518. B->L = L;
  519. B->p = B->buffer;
  520. B->lvl = 0;
  521. }
  522. /* }====================================================== */
  523. LUALIB_API int luaL_ref (lua_State *L, int t) {
  524. int ref;
  525. t = abs_index(L, t);
  526. if (lua_isnil(L, -1)) {
  527. lua_pop(L, 1); /* remove from stack */
  528. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  529. }
  530. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  531. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  532. lua_pop(L, 1); /* remove it from stack */
  533. if (ref != 0) { /* any free element? */
  534. lua_rawgeti(L, t, ref); /* remove it from list */
  535. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  536. }
  537. else { /* no free elements */
  538. ref = (int)lua_objlen(L, t);
  539. ref++; /* create new reference */
  540. }
  541. lua_rawseti(L, t, ref);
  542. return ref;
  543. }
  544. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  545. if (ref >= 0) {
  546. t = abs_index(L, t);
  547. lua_rawgeti(L, t, FREELIST_REF);
  548. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  549. lua_pushinteger(L, ref);
  550. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  551. }
  552. }
  553. /*
  554. ** {======================================================
  555. ** Load functions
  556. ** =======================================================
  557. */
  558. #ifdef LUA_CROSS_COMPILER
  559. typedef struct LoadF {
  560. int extraline;
  561. FILE *f;
  562. char buff[LUAL_BUFFERSIZE];
  563. } LoadF;
  564. static const char *getF (lua_State *L, void *ud, size_t *size) {
  565. LoadF *lf = (LoadF *)ud;
  566. (void)L;
  567. if (lf->extraline) {
  568. lf->extraline = 0;
  569. *size = 1;
  570. return "\n";
  571. }
  572. if (c_feof(lf->f)) return NULL;
  573. *size = c_fread(lf->buff, 1, sizeof(lf->buff), lf->f);
  574. return (*size > 0) ? lf->buff : NULL;
  575. }
  576. static int errfile (lua_State *L, const char *what, int fnameindex) {
  577. const char *serr = c_strerror(errno);
  578. const char *filename = lua_tostring(L, fnameindex) + 1;
  579. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  580. lua_remove(L, fnameindex);
  581. return LUA_ERRFILE;
  582. }
  583. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  584. LoadF lf;
  585. int status, readstatus;
  586. int c;
  587. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  588. lf.extraline = 0;
  589. if (filename == NULL) {
  590. lua_pushliteral(L, "=stdin");
  591. lf.f = c_stdin;
  592. }
  593. else {
  594. lua_pushfstring(L, "@%s", filename);
  595. lf.f = c_fopen(filename, "r");
  596. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  597. }
  598. c = c_getc(lf.f);
  599. if (c == '#') { /* Unix exec. file? */
  600. lf.extraline = 1;
  601. while ((c = c_getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  602. if (c == '\n') c = c_getc(lf.f);
  603. }
  604. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  605. lf.f = c_freopen(filename, "rb", lf.f); /* reopen in binary mode */
  606. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  607. /* skip eventual `#!...' */
  608. while ((c = c_getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
  609. lf.extraline = 0;
  610. }
  611. c_ungetc(c, lf.f);
  612. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  613. readstatus = c_ferror(lf.f);
  614. if (filename) c_fclose(lf.f); /* close file (even in case of errors) */
  615. if (readstatus) {
  616. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  617. return errfile(L, "read", fnameindex);
  618. }
  619. lua_remove(L, fnameindex);
  620. return status;
  621. }
  622. #else
  623. #include C_HEADER_FCNTL
  624. typedef struct LoadFSF {
  625. int extraline;
  626. int f;
  627. char buff[LUAL_BUFFERSIZE];
  628. } LoadFSF;
  629. static const char *getFSF (lua_State *L, void *ud, size_t *size) {
  630. LoadFSF *lf = (LoadFSF *)ud;
  631. (void)L;
  632. if (L == NULL && size == NULL) // Direct mode check
  633. return NULL;
  634. if (lf->extraline) {
  635. lf->extraline = 0;
  636. *size = 1;
  637. return "\n";
  638. }
  639. if (vfs_eof(lf->f)) return NULL;
  640. *size = vfs_read(lf->f, lf->buff, sizeof(lf->buff));
  641. return (*size > 0) ? lf->buff : NULL;
  642. }
  643. static int errfsfile (lua_State *L, const char *what, int fnameindex) {
  644. const char *filename = lua_tostring(L, fnameindex) + 1;
  645. lua_pushfstring(L, "cannot %s %s", what, filename);
  646. lua_remove(L, fnameindex);
  647. return LUA_ERRFILE;
  648. }
  649. LUALIB_API int luaL_loadfsfile (lua_State *L, const char *filename) {
  650. LoadFSF lf;
  651. int status, readstatus;
  652. int c;
  653. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  654. lf.extraline = 0;
  655. if (filename == NULL) {
  656. return luaL_error(L, "filename is NULL");
  657. }
  658. else {
  659. lua_pushfstring(L, "@%s", filename);
  660. lf.f = vfs_open(filename, "r");
  661. if (!lf.f) return errfsfile(L, "open", fnameindex);
  662. }
  663. // if(fs_size(lf.f)>LUAL_BUFFERSIZE)
  664. // return luaL_error(L, "file is too big");
  665. c = vfs_getc(lf.f);
  666. if (c == '#') { /* Unix exec. file? */
  667. lf.extraline = 1;
  668. while ((c = vfs_getc(lf.f)) != VFS_EOF && c != '\n') ; /* skip first line */
  669. if (c == '\n') c = vfs_getc(lf.f);
  670. }
  671. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  672. vfs_close(lf.f);
  673. lf.f = vfs_open(filename, "r"); /* reopen in binary mode */
  674. if (!lf.f) return errfsfile(L, "reopen", fnameindex);
  675. /* skip eventual `#!...' */
  676. while ((c = vfs_getc(lf.f)) != VFS_EOF && c != LUA_SIGNATURE[0]) ;
  677. lf.extraline = 0;
  678. }
  679. vfs_ungetc(c, lf.f);
  680. status = lua_load(L, getFSF, &lf, lua_tostring(L, -1));
  681. if (filename) vfs_close(lf.f); /* close file (even in case of errors) */
  682. lua_remove(L, fnameindex);
  683. return status;
  684. }
  685. #endif
  686. typedef struct LoadS {
  687. const char *s;
  688. size_t size;
  689. } LoadS;
  690. static const char *getS (lua_State *L, void *ud, size_t *size) {
  691. LoadS *ls = (LoadS *)ud;
  692. (void)L;
  693. if (L == NULL && size == NULL) // direct mode check
  694. return NULL;
  695. if (ls->size == 0) return NULL;
  696. *size = ls->size;
  697. ls->size = 0;
  698. return ls->s;
  699. }
  700. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  701. const char *name) {
  702. LoadS ls;
  703. ls.s = buff;
  704. ls.size = size;
  705. return lua_load(L, getS, &ls, name);
  706. }
  707. LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
  708. return luaL_loadbuffer(L, s, c_strlen(s), s);
  709. }
  710. /* }====================================================== */
  711. static int l_check_memlimit(lua_State *L, size_t needbytes) {
  712. global_State *g = G(L);
  713. int cycle_count = 0;
  714. lu_mem limit = g->memlimit - needbytes;
  715. /* don't allow allocation if it requires more memory then the total limit. */
  716. if (needbytes > g->memlimit) return 1;
  717. /* make sure the GC is not disabled. */
  718. if (!is_block_gc(L)) {
  719. while (g->totalbytes >= limit) {
  720. /* only allow the GC to finished atleast 1 full cycle. */
  721. if (g->gcstate == GCSpause && ++cycle_count > 1) break;
  722. luaC_step(L);
  723. }
  724. }
  725. return (g->totalbytes >= limit) ? 1 : 0;
  726. }
  727. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  728. lua_State *L = (lua_State *)ud;
  729. int mode = L == NULL ? 0 : G(L)->egcmode;
  730. void *nptr;
  731. if (nsize == 0) {
  732. #ifdef DEBUG_ALLOCATOR
  733. return (void *)this_realloc(ptr, osize, nsize);
  734. #else
  735. c_free(ptr);
  736. return NULL;
  737. #endif
  738. }
  739. if (L != NULL && (mode & EGC_ALWAYS)) /* always collect memory if requested */
  740. luaC_fullgc(L);
  741. if(nsize > osize && L != NULL) {
  742. #if defined(LUA_STRESS_EMERGENCY_GC)
  743. luaC_fullgc(L);
  744. #endif
  745. if(G(L)->memlimit > 0 && (mode & EGC_ON_MEM_LIMIT) && l_check_memlimit(L, nsize - osize))
  746. return NULL;
  747. }
  748. nptr = (void *)this_realloc(ptr, osize, nsize);
  749. if (nptr == NULL && L != NULL && (mode & EGC_ON_ALLOC_FAILURE)) {
  750. luaC_fullgc(L); /* emergency full collection. */
  751. nptr = (void *)this_realloc(ptr, osize, nsize); /* try allocation again */
  752. }
  753. return nptr;
  754. }
  755. LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) {
  756. dbg_printf("ASSERT@%s(%d): %s\n", file, line, message);
  757. #if defined(LUA_CROSS_COMPILER)
  758. exit(1);
  759. #endif
  760. }
  761. #ifdef DEVELOPMENT_USE_GDB
  762. /*
  763. * This is a simple stub used by lua_assert() if DEVELOPMENT_USE_GDB is defined.
  764. * Instead of crashing out with an assert error, this hook starts the GDB remote
  765. * stub if not already running and then issues a break. The rationale here is
  766. * that when testing the developer migght be using screen/PuTTY to work ineractively
  767. * with the Lua Interpreter via UART0. However if an assert triggers, then there
  768. * is the option to exit the interactive session and start the Xtensa remote GDB
  769. * which will then sync up with the remote GDB client to allow forensics of the error.
  770. */
  771. extern void gdbstub_init(void);
  772. LUALIB_API void luaL_dbgbreak(void) {
  773. static int repeat_entry = 0;
  774. if (repeat_entry == 0) {
  775. dbg_printf("Start up the gdb stub if not already started\n");
  776. gdbstub_init();
  777. repeat_entry = 1;
  778. }
  779. asm("break 0,0" ::);
  780. }
  781. #endif
  782. static int panic (lua_State *L) {
  783. (void)L; /* to avoid warnings */
  784. #if defined(LUA_USE_STDIO)
  785. c_fprintf(c_stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
  786. lua_tostring(L, -1));
  787. #else
  788. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  789. lua_tostring(L, -1));
  790. #endif
  791. while (1) {}
  792. return 0;
  793. }
  794. LUALIB_API lua_State *luaL_newstate (void) {
  795. lua_State *L = lua_newstate(l_alloc, NULL);
  796. lua_setallocf(L, l_alloc, L); /* allocator need lua_State. */
  797. if (L) lua_atpanic(L, &panic);
  798. return L;
  799. }