lauxlib.c 28 KB

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