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