lauxlib.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. #include "lauxlib.h"
  25. #define LUA_LIB
  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, luaL_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_testudata (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)) /* not the same? */
  256. p = NULL; /* value is a userdata with wrong metatable */
  257. lua_pop(L, 2); /* remove both metatables */
  258. return p;
  259. }
  260. }
  261. return NULL; /* value is not a userdata with a metatable */
  262. }
  263. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  264. void *p = luaL_testudata(L, ud, tname);
  265. if (p == NULL) luaL_typerror(L, ud, tname);
  266. return p;
  267. }
  268. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
  269. if (!lua_checkstack(L, space))
  270. luaL_error(L, "stack overflow (%s)", mes);
  271. }
  272. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  273. if (lua_type(L, narg) != t)
  274. tag_error(L, narg, t);
  275. }
  276. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  277. if (lua_type(L, narg) == LUA_TNONE)
  278. luaL_argerror(L, narg, "value expected");
  279. }
  280. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  281. const char *s = lua_tolstring(L, narg, len);
  282. if (!s) tag_error(L, narg, LUA_TSTRING);
  283. return s;
  284. }
  285. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  286. const char *def, size_t *len) {
  287. if (lua_isnoneornil(L, narg)) {
  288. if (len)
  289. *len = (def ? strlen(def) : 0);
  290. return def;
  291. }
  292. else return luaL_checklstring(L, narg, len);
  293. }
  294. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  295. lua_Number d = lua_tonumber(L, narg);
  296. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  297. tag_error(L, narg, LUA_TNUMBER);
  298. return d;
  299. }
  300. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  301. return luaL_opt(L, luaL_checknumber, narg, def);
  302. }
  303. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  304. lua_Integer d = lua_tointeger(L, narg);
  305. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  306. tag_error(L, narg, LUA_TNUMBER);
  307. return d;
  308. }
  309. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  310. lua_Integer def) {
  311. return luaL_opt(L, luaL_checkinteger, narg, def);
  312. }
  313. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  314. if (!lua_getmetatable(L, obj)) /* no metatable? */
  315. return 0;
  316. lua_pushstring(L, event);
  317. lua_rawget(L, -2);
  318. if (lua_isnil(L, -1)) {
  319. lua_pop(L, 2); /* remove metatable and metafield */
  320. return 0;
  321. }
  322. else {
  323. lua_remove(L, -2); /* remove only metatable */
  324. return 1;
  325. }
  326. }
  327. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  328. obj = abs_index(L, obj);
  329. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  330. return 0;
  331. lua_pushvalue(L, obj);
  332. lua_call(L, 1, 1);
  333. return 1;
  334. }
  335. LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
  336. const luaL_Reg *l) {
  337. luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
  338. }
  339. LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
  340. const luaL_Reg *l) {
  341. luaI_openlib(L, libname, l, 0, LUA_USELIGHTFUNCTIONS);
  342. }
  343. static int libsize (const luaL_Reg *l) {
  344. int size = 0;
  345. for (; l->name; l++) size++;
  346. return size;
  347. }
  348. LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
  349. const luaL_Reg *l, int nup, int ftype) {
  350. if (libname) {
  351. int size = libsize(l);
  352. /* check whether lib already exists */
  353. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
  354. lua_getfield(L, -1, libname); /* get _LOADED[libname] */
  355. if (!lua_istable(L, -1)) { /* not found? */
  356. lua_pop(L, 1); /* remove previous result */
  357. /* try global variable (and create one if it does not exist) */
  358. if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
  359. luaL_error(L, "name conflict for module " LUA_QS, libname);
  360. lua_pushvalue(L, -1);
  361. lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
  362. }
  363. lua_remove(L, -2); /* remove _LOADED table */
  364. lua_insert(L, -(nup+1)); /* move library table to below upvalues */
  365. }
  366. for (; l->name; l++) {
  367. int i;
  368. for (i=0; i<nup; i++) /* copy upvalues to the top */
  369. lua_pushvalue(L, -nup);
  370. if (ftype == LUA_USELIGHTFUNCTIONS)
  371. lua_pushcfunction(L, l->func);
  372. else
  373. lua_pushcclosure(L, l->func, nup);
  374. lua_setfield(L, -(nup+2), l->name);
  375. }
  376. lua_pop(L, nup); /* remove upvalues */
  377. }
  378. /*
  379. ** {======================================================
  380. ** getn-setn: size for arrays
  381. ** =======================================================
  382. */
  383. #if defined(LUA_COMPAT_GETN)
  384. static int checkint (lua_State *L, int topop) {
  385. int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
  386. lua_pop(L, topop);
  387. return n;
  388. }
  389. static void getsizes (lua_State *L) {
  390. lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
  391. if (lua_isnil(L, -1)) { /* no `size' table? */
  392. lua_pop(L, 1); /* remove nil */
  393. lua_newtable(L); /* create it */
  394. lua_pushvalue(L, -1); /* `size' will be its own metatable */
  395. lua_setmetatable(L, -2);
  396. lua_pushliteral(L, "kv");
  397. lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
  398. lua_pushvalue(L, -1);
  399. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */
  400. }
  401. }
  402. LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
  403. t = abs_index(L, t);
  404. lua_pushliteral(L, "n");
  405. lua_rawget(L, t);
  406. if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
  407. lua_pushliteral(L, "n"); /* use it */
  408. lua_pushinteger(L, n);
  409. lua_rawset(L, t);
  410. }
  411. else { /* use `sizes' */
  412. getsizes(L);
  413. lua_pushvalue(L, t);
  414. lua_pushinteger(L, n);
  415. lua_rawset(L, -3); /* sizes[t] = n */
  416. lua_pop(L, 1); /* remove `sizes' */
  417. }
  418. }
  419. LUALIB_API int luaL_getn (lua_State *L, int t) {
  420. int n;
  421. t = abs_index(L, t);
  422. lua_pushliteral(L, "n"); /* try t.n */
  423. lua_rawget(L, t);
  424. if ((n = checkint(L, 1)) >= 0) return n;
  425. getsizes(L); /* else try sizes[t] */
  426. lua_pushvalue(L, t);
  427. lua_rawget(L, -2);
  428. if ((n = checkint(L, 2)) >= 0) return n;
  429. return (int)lua_objlen(L, t);
  430. }
  431. #endif
  432. /* }====================================================== */
  433. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  434. const char *r) {
  435. const char *wild;
  436. size_t l = strlen(p);
  437. luaL_Buffer b;
  438. luaL_buffinit(L, &b);
  439. while ((wild = strstr(s, p)) != NULL) {
  440. luaL_addlstring(&b, s, wild - s); /* push prefix */
  441. luaL_addstring(&b, r); /* push replacement in place of pattern */
  442. s = wild + l; /* continue after `p' */
  443. }
  444. luaL_addstring(&b, s); /* push last suffix */
  445. luaL_pushresult(&b);
  446. return lua_tostring(L, -1);
  447. }
  448. LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
  449. const char *fname, int szhint) {
  450. const char *e;
  451. lua_pushvalue(L, idx);
  452. do {
  453. e = strchr(fname, '.');
  454. if (e == NULL) e = fname + strlen(fname);
  455. lua_pushlstring(L, fname, e - fname);
  456. lua_rawget(L, -2);
  457. if (lua_isnil(L, -1)) { /* no such field? */
  458. lua_pop(L, 1); /* remove this nil */
  459. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  460. lua_pushlstring(L, fname, e - fname);
  461. lua_pushvalue(L, -2);
  462. lua_settable(L, -4); /* set new table into field */
  463. }
  464. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  465. lua_pop(L, 2); /* remove table and value */
  466. return fname; /* return problematic part of the name */
  467. }
  468. lua_remove(L, -2); /* remove previous table */
  469. fname = e + 1;
  470. } while (*e == '.');
  471. return NULL;
  472. }
  473. /*
  474. ** {======================================================
  475. ** Generic Buffer manipulation
  476. ** =======================================================
  477. */
  478. #define bufflen(B) ((B)->p - (B)->buffer)
  479. #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
  480. #define LIMIT (LUA_MINSTACK/2)
  481. static int emptybuffer (luaL_Buffer *B) {
  482. size_t l = bufflen(B);
  483. if (l == 0) return 0; /* put nothing on stack */
  484. else {
  485. lua_pushlstring(B->L, B->buffer, l);
  486. B->p = B->buffer;
  487. B->lvl++;
  488. return 1;
  489. }
  490. }
  491. static void adjuststack (luaL_Buffer *B) {
  492. if (B->lvl > 1) {
  493. lua_State *L = B->L;
  494. int toget = 1; /* number of levels to concat */
  495. size_t toplen = lua_strlen(L, -1);
  496. do {
  497. size_t l = lua_strlen(L, -(toget+1));
  498. if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
  499. toplen += l;
  500. toget++;
  501. }
  502. else break;
  503. } while (toget < B->lvl);
  504. lua_concat(L, toget);
  505. B->lvl = B->lvl - toget + 1;
  506. }
  507. }
  508. LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
  509. if (emptybuffer(B))
  510. adjuststack(B);
  511. return B->buffer;
  512. }
  513. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  514. while (l--)
  515. luaL_addchar(B, *s++);
  516. }
  517. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  518. luaL_addlstring(B, s, strlen(s));
  519. }
  520. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  521. emptybuffer(B);
  522. lua_concat(B->L, B->lvl);
  523. B->lvl = 1;
  524. }
  525. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  526. lua_State *L = B->L;
  527. size_t vl;
  528. const char *s = lua_tolstring(L, -1, &vl);
  529. if (vl <= bufffree(B)) { /* fit into buffer? */
  530. memcpy(B->p, s, vl); /* put it there */
  531. B->p += vl;
  532. lua_pop(L, 1); /* remove from stack */
  533. }
  534. else {
  535. if (emptybuffer(B))
  536. lua_insert(L, -2); /* put buffer before new value */
  537. B->lvl++; /* add new value into B stack */
  538. adjuststack(B);
  539. }
  540. }
  541. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  542. B->L = L;
  543. B->p = B->buffer;
  544. B->lvl = 0;
  545. }
  546. /* }====================================================== */
  547. LUALIB_API int luaL_ref (lua_State *L, int t) {
  548. int ref;
  549. t = abs_index(L, t);
  550. if (lua_isnil(L, -1)) {
  551. lua_pop(L, 1); /* remove from stack */
  552. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  553. }
  554. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  555. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  556. lua_pop(L, 1); /* remove it from stack */
  557. if (ref != 0) { /* any free element? */
  558. lua_rawgeti(L, t, ref); /* remove it from list */
  559. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  560. }
  561. else { /* no free elements */
  562. ref = (int)lua_objlen(L, t);
  563. ref++; /* create new reference */
  564. }
  565. lua_rawseti(L, t, ref);
  566. return ref;
  567. }
  568. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  569. if (ref >= 0) {
  570. t = abs_index(L, t);
  571. lua_rawgeti(L, t, FREELIST_REF);
  572. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  573. lua_pushinteger(L, ref);
  574. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  575. }
  576. }
  577. LUALIB_API void (luaL_reref) (lua_State *L, int t, int *ref) {
  578. int reft;
  579. /*
  580. * If the ref is positive and the entry in table t exists then
  581. * overwrite the value otherwise fall through to luaL_ref()
  582. */
  583. if (ref) {
  584. if (*ref >= 0) {
  585. t = abs_index(L, t);
  586. lua_rawgeti(L, t, *ref);
  587. reft = lua_type(L, -1);
  588. lua_pop(L, 1);
  589. if (reft != LUA_TNIL) {
  590. lua_rawseti(L, t, *ref);
  591. return;
  592. }
  593. }
  594. *ref = luaL_ref(L, t);
  595. }
  596. }
  597. /*
  598. ** {======================================================
  599. ** Load functions
  600. ** =======================================================
  601. */
  602. typedef struct LoadF {
  603. int extraline;
  604. #ifdef LUA_CROSS_COMPILER
  605. FILE *f;
  606. #else
  607. int f;
  608. #endif
  609. char buff[LUAL_BUFFERSIZE];
  610. } LoadF;
  611. #ifdef LUA_CROSS_COMPILER
  612. # define freopen_bin(f,fn) freopen(f,"rb",fn)
  613. # define read_buff(b,f) fread(b, 1, sizeof (b), f)
  614. #else
  615. # define strerror(n) ""
  616. #undef feof
  617. # define feof(f) vfs_eof(f)
  618. #undef fopen
  619. # define fopen(f, m) vfs_open(f, m)
  620. # define freopen_bin(fn,f) ((void) vfs_close(f), vfs_open(fn, "r"))
  621. #undef getc
  622. # define getc(f) vfs_getc(f)
  623. #undef ungetc
  624. # define ungetc(c,f) vfs_ungetc(c, f)
  625. # define read_buff(b,f) vfs_read(f, b, sizeof (b))
  626. #endif
  627. static const char *getF (lua_State *L, void *ud, size_t *size) {
  628. LoadF *lf = (LoadF *)ud;
  629. (void)L;
  630. if (lf->extraline) {
  631. lf->extraline = 0;
  632. *size = 1;
  633. return "\n";
  634. }
  635. if (feof(lf->f)) return NULL;
  636. *size = read_buff(lf->buff, lf->f);
  637. return (*size > 0) ? lf->buff : NULL;
  638. }
  639. static int errfile (lua_State *L, const char *what, int fnameindex) {
  640. const char *serr = strerror(errno);
  641. const char *filename = lua_tostring(L, fnameindex) + 1;
  642. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  643. lua_remove(L, fnameindex);
  644. return LUA_ERRFILE;
  645. }
  646. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  647. LoadF lf;
  648. int status, readstatus;
  649. int c;
  650. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  651. lf.extraline = 0;
  652. if (filename == NULL) {
  653. #ifdef LUA_CROSS_COMPILER
  654. lua_pushliteral(L, "=stdin");
  655. lf.f = stdin;
  656. #else
  657. return luaL_error(L, "filename is NULL");
  658. #endif
  659. }
  660. else {
  661. lua_pushfstring(L, "@%s", filename);
  662. lf.f = fopen(filename, "r");
  663. if (!lf.f) return errfile(L, "open", fnameindex);
  664. }
  665. c = getc(lf.f);
  666. if (c == '#') { /* Unix exec. file? */
  667. lf.extraline = 1;
  668. while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  669. if (c == '\n') c = getc(lf.f);
  670. }
  671. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  672. lf.f = freopen_bin(filename, lf.f); /* reopen in binary mode */
  673. if (!lf.f) return errfile(L, "reopen", fnameindex);
  674. /* skip eventual `#!...' */
  675. while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) {}
  676. lf.extraline = 0;
  677. }
  678. ungetc(c, lf.f);
  679. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  680. #ifdef LUA_CROSS_COMPILER
  681. readstatus = ferror(lf.f);
  682. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  683. if (readstatus) {
  684. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  685. return errfile(L, "read", fnameindex);
  686. }
  687. #else
  688. (void) readstatus; /* avoid compile error */
  689. if (filename) vfs_close(lf.f); /* close file (even in case of errors) */
  690. #endif
  691. lua_remove(L, fnameindex);
  692. return status;
  693. }
  694. typedef struct LoadS {
  695. const char *s;
  696. size_t size;
  697. } LoadS;
  698. static const char *getS (lua_State *L, void *ud, size_t *size) {
  699. LoadS *ls = (LoadS *)ud;
  700. (void)L;
  701. if (L == NULL && size == NULL) // direct mode check
  702. return NULL;
  703. if (ls->size == 0) return NULL;
  704. *size = ls->size;
  705. ls->size = 0;
  706. return ls->s;
  707. }
  708. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  709. const char *name) {
  710. LoadS ls;
  711. ls.s = buff;
  712. ls.size = size;
  713. return lua_load(L, getS, &ls, name);
  714. }
  715. LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
  716. return luaL_loadbuffer(L, s, strlen(s), s);
  717. }
  718. /* }====================================================== */
  719. static int l_check_memlimit(lua_State *L, size_t needbytes) {
  720. global_State *g = G(L);
  721. int cycle_count = 0;
  722. lu_mem limit = g->memlimit - needbytes;
  723. /* don't allow allocation if it requires more memory then the total limit. */
  724. if (needbytes > g->memlimit) return 1;
  725. /* make sure the GC is not disabled. */
  726. if (!is_block_gc(L)) {
  727. while (g->totalbytes >= limit) {
  728. /* only allow the GC to finished atleast 1 full cycle. */
  729. if (g->gcstate == GCSpause && ++cycle_count > 1) break;
  730. luaC_step(L);
  731. }
  732. }
  733. return (g->totalbytes >= limit) ? 1 : 0;
  734. }
  735. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  736. lua_State *L = (lua_State *)ud;
  737. int mode = L == NULL ? 0 : G(L)->egcmode;
  738. void *nptr;
  739. if (nsize == 0) {
  740. #ifdef DEBUG_ALLOCATOR
  741. return (void *)this_realloc(ptr, osize, nsize);
  742. #else
  743. free(ptr);
  744. return NULL;
  745. #endif
  746. }
  747. if (L != NULL && (mode & EGC_ALWAYS)) /* always collect memory if requested */
  748. luaC_fullgc(L);
  749. #ifndef LUA_CROSS_COMPILER
  750. if (L != NULL && (mode & EGC_ON_MEM_LIMIT) && G(L)->memlimit < 0 &&
  751. (system_get_free_heap_size() < (-G(L)->memlimit)))
  752. luaC_fullgc(L);
  753. #endif
  754. if(nsize > osize && L != NULL) {
  755. #if defined(LUA_STRESS_EMERGENCY_GC)
  756. luaC_fullgc(L);
  757. #endif
  758. if(G(L)->memlimit > 0 && (mode & EGC_ON_MEM_LIMIT) && l_check_memlimit(L, nsize - osize))
  759. return NULL;
  760. }
  761. nptr = (void *)this_realloc(ptr, osize, nsize);
  762. if (nptr == NULL && L != NULL && (mode & EGC_ON_ALLOC_FAILURE)) {
  763. luaC_fullgc(L); /* emergency full collection. */
  764. nptr = (void *)this_realloc(ptr, osize, nsize); /* try allocation again */
  765. }
  766. return nptr;
  767. }
  768. LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) {
  769. dbg_printf("ASSERT@%s(%d): %s\n", file, line, message);
  770. #if defined(LUA_CROSS_COMPILER)
  771. exit(1);
  772. #endif
  773. }
  774. #ifdef DEVELOPMENT_USE_GDB
  775. /*
  776. * This is a simple stub used by lua_assert() if DEVELOPMENT_USE_GDB is defined.
  777. * Instead of crashing out with an assert error, this hook starts the GDB remote
  778. * stub if not already running and then issues a break. The rationale here is
  779. * that when testing the developer might be using screen/PuTTY to work interactively
  780. * with the Lua Interpreter via UART0. However if an assert triggers, then there
  781. * is the option to exit the interactive session and start the Xtensa remote GDB
  782. * which will then sync up with the remote GDB client to allow forensics of the error.
  783. */
  784. extern void gdbstub_init(void);
  785. extern void gdbstub_redirect_output(int);
  786. LUALIB_API void lua_debugbreak (void) {
  787. #ifdef LUA_CROSS_COMPILER
  788. puts(" lua_debugbreak "); /* allows gdb BT analysis of assert fails */
  789. #else
  790. static int repeat_entry = 0;
  791. if (repeat_entry == 0) {
  792. dbg_printf("Start up the gdb stub if not already started\n");
  793. gdbstub_init();
  794. gdbstub_redirect_output(1);
  795. repeat_entry = 1;
  796. }
  797. asm("break 0,0" ::);
  798. #endif
  799. }
  800. #endif
  801. static int panic (lua_State *L) {
  802. (void)L; /* to avoid warnings */
  803. lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  804. lua_tostring(L, -1));
  805. while (1) {}
  806. return 0;
  807. }
  808. LUALIB_API lua_State *luaL_newstate (void) {
  809. lua_State *L = lua_newstate(l_alloc, NULL);
  810. lua_setallocf(L, l_alloc, L); /* allocator need lua_State. */
  811. if (L) lua_atpanic(L, &panic);
  812. return L;
  813. }