lauxlib.c 26 KB

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