1    	/*
2    	** $Id: lbaselib.c,v 1.312 2015/10/29 15:21:04 roberto Exp $
3    	** Basic library
4    	** See Copyright Notice in lua.h
5    	*/
6    	
7    	#define lbaselib_c
8    	#define LUA_LIB
9    	
10   	#include "lprefix.h"
11   	
12   	
13   	#include <ctype.h>
14   	#include <stdio.h>
15   	#include <stdlib.h>
16   	#include <string.h>
17   	
18   	#include "lua.h"
19   	
20   	#include "lauxlib.h"
21   	#include "lualib.h"
22   	
23   	
24   	static int luaB_print (lua_State *L) {
25   	  int n = lua_gettop(L);  /* number of arguments */
26   	  int i;
27   	  lua_getglobal(L, "tostring");
28   	  for (i=1; i<=n; i++) {
29   	    const char *s;
30   	    size_t l;
31   	    lua_pushvalue(L, -1);  /* function to be called */
32   	    lua_pushvalue(L, i);   /* value to print */
33   	    lua_call(L, 1, 1);
34   	    s = lua_tolstring(L, -1, &l);  /* get result */
35   	    if (s == NULL)
36   	      return luaL_error(L, "'tostring' must return a string to 'print'");
37   	    if (i>1) lua_writestring("\t", 1);
38   	    lua_writestring(s, l);
39   	    lua_pop(L, 1);  /* pop result */
40   	  }
41   	  lua_writeline();
42   	  return 0;
43   	}
44   	
45   	
46   	#define SPACECHARS	" \f\n\r\t\v"
47   	
48   	static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
49   	  lua_Unsigned n = 0;
50   	  int neg = 0;
51   	  s += strspn(s, SPACECHARS);  /* skip initial spaces */
52   	  if (*s == '-') { s++; neg = 1; }  /* handle signal */
53   	  else if (*s == '+') s++;
54   	  if (!isalnum((unsigned char)*s))  /* no digit? */
55   	    return NULL;
56   	  do {
57   	    int digit = (isdigit((unsigned char)*s)) ? *s - '0'
58   	                   : (toupper((unsigned char)*s) - 'A') + 10;
59   	    if (digit >= base) return NULL;  /* invalid numeral */
60   	    n = n * base + digit;
61   	    s++;
62   	  } while (isalnum((unsigned char)*s));
63   	  s += strspn(s, SPACECHARS);  /* skip trailing spaces */
64   	  *pn = (lua_Integer)((neg) ? (0u - n) : n);
65   	  return s;
66   	}
67   	
68   	
69   	static int luaB_tonumber (lua_State *L) {
70   	  if (lua_isnoneornil(L, 2)) {  /* standard conversion? */
71   	    luaL_checkany(L, 1);
72   	    if (lua_type(L, 1) == LUA_TNUMBER) {  /* already a number? */
73   	      lua_settop(L, 1);  /* yes; return it */
74   	      return 1;
75   	    }
76   	    else {
77   	      size_t l;
78   	      const char *s = lua_tolstring(L, 1, &l);
79   	      if (s != NULL && lua_stringtonumber(L, s) == l + 1)
80   	        return 1;  /* successful conversion to number */
81   	      /* else not a number */
82   	    }
83   	  }
84   	  else {
85   	    size_t l;
86   	    const char *s;
87   	    lua_Integer n = 0;  /* to avoid warnings */
88   	    lua_Integer base = luaL_checkinteger(L, 2);
89   	    luaL_checktype(L, 1, LUA_TSTRING);  /* no numbers as strings */
90   	    s = lua_tolstring(L, 1, &l);
91   	    luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
92   	    if (b_str2int(s, (int)base, &n) == s + l) {
93   	      lua_pushinteger(L, n);
94   	      return 1;
95   	    }  /* else not a number */
96   	  }  /* else not a number */
97   	  lua_pushnil(L);  /* not a number */
98   	  return 1;
99   	}
100  	
101  	
102  	static int luaB_error (lua_State *L) {
103  	  int level = (int)luaL_optinteger(L, 2, 1);
104  	  lua_settop(L, 1);
105  	  if (lua_isstring(L, 1) && level > 0) {  /* add extra information? */
106  	    luaL_where(L, level);
107  	    lua_pushvalue(L, 1);
108  	    lua_concat(L, 2);
109  	  }
110  	  return lua_error(L);
111  	}
112  	
113  	
114  	static int luaB_getmetatable (lua_State *L) {
115  	  luaL_checkany(L, 1);
(1) Event cond_false: Condition "!lua_getmetatable(L, 1)", taking false branch.
116  	  if (!lua_getmetatable(L, 1)) {
117  	    lua_pushnil(L);
118  	    return 1;  /* no metatable */
(2) Event if_end: End of if statement.
119  	  }
(3) Event check_return: Calling "luaL_getmetafield" without checking return value (as is done elsewhere 4 out of 5 times).
Also see events: [example_checked][example_checked][example_checked][example_checked]
120  	  luaL_getmetafield(L, 1, "__metatable");
121  	  return 1;  /* returns either __metatable field (if present) or metatable */
122  	}
123  	
124  	
125  	static int luaB_setmetatable (lua_State *L) {
126  	  int t = lua_type(L, 2);
127  	  luaL_checktype(L, 1, LUA_TTABLE);
128  	  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
129  	                    "nil or table expected");
(7) Event example_checked: Example 4: "luaL_getmetafield(L, 1, "__metatable")" has its value checked in "luaL_getmetafield(L, 1, "__metatable") != 0".
Also see events: [check_return][example_checked][example_checked][example_checked]
130  	  if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
131  	    return luaL_error(L, "cannot change a protected metatable");
132  	  lua_settop(L, 2);
133  	  lua_setmetatable(L, 1);
134  	  return 1;
135  	}
136  	
137  	
138  	static int luaB_rawequal (lua_State *L) {
139  	  luaL_checkany(L, 1);
140  	  luaL_checkany(L, 2);
141  	  lua_pushboolean(L, lua_rawequal(L, 1, 2));
142  	  return 1;
143  	}
144  	
145  	
146  	static int luaB_rawlen (lua_State *L) {
147  	  int t = lua_type(L, 1);
148  	  luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
149  	                   "table or string expected");
150  	  lua_pushinteger(L, lua_rawlen(L, 1));
151  	  return 1;
152  	}
153  	
154  	
155  	static int luaB_rawget (lua_State *L) {
156  	  luaL_checktype(L, 1, LUA_TTABLE);
157  	  luaL_checkany(L, 2);
158  	  lua_settop(L, 2);
159  	  lua_rawget(L, 1);
160  	  return 1;
161  	}
162  	
163  	static int luaB_rawset (lua_State *L) {
164  	  luaL_checktype(L, 1, LUA_TTABLE);
165  	  luaL_checkany(L, 2);
166  	  luaL_checkany(L, 3);
167  	  lua_settop(L, 3);
168  	  lua_rawset(L, 1);
169  	  return 1;
170  	}
171  	
172  	
173  	static int luaB_collectgarbage (lua_State *L) {
174  	  static const char *const opts[] = {"stop", "restart", "collect",
175  	    "count", "step", "setpause", "setstepmul",
176  	    "isrunning", NULL};
177  	  static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
178  	    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
179  	    LUA_GCISRUNNING};
180  	  int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
181  	  int ex = (int)luaL_optinteger(L, 2, 0);
182  	  int res = lua_gc(L, o, ex);
183  	  switch (o) {
184  	    case LUA_GCCOUNT: {
185  	      int b = lua_gc(L, LUA_GCCOUNTB, 0);
186  	      lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
187  	      return 1;
188  	    }
189  	    case LUA_GCSTEP: case LUA_GCISRUNNING: {
190  	      lua_pushboolean(L, res);
191  	      return 1;
192  	    }
193  	    default: {
194  	      lua_pushinteger(L, res);
195  	      return 1;
196  	    }
197  	  }
198  	}
199  	
200  	
201  	static int luaB_type (lua_State *L) {
202  	  int t = lua_type(L, 1);
203  	  luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
204  	  lua_pushstring(L, lua_typename(L, t));
205  	  return 1;
206  	}
207  	
208  	
209  	static int pairsmeta (lua_State *L, const char *method, int iszero,
210  	                      lua_CFunction iter) {
(6) Event example_checked: Example 3: "luaL_getmetafield(L, 1, method)" has its value checked in "luaL_getmetafield(L, 1, method) == 0".
Also see events: [check_return][example_checked][example_checked][example_checked]
211  	  if (luaL_getmetafield(L, 1, method) == LUA_TNIL) {  /* no metamethod? */
212  	    luaL_checktype(L, 1, LUA_TTABLE);  /* argument must be a table */
213  	    lua_pushcfunction(L, iter);  /* will return generator, */
214  	    lua_pushvalue(L, 1);  /* state, */
215  	    if (iszero) lua_pushinteger(L, 0);  /* and initial value */
216  	    else lua_pushnil(L);
217  	  }
218  	  else {
219  	    lua_pushvalue(L, 1);  /* argument 'self' to metamethod */
220  	    lua_call(L, 1, 3);  /* get 3 values from metamethod */
221  	  }
222  	  return 3;
223  	}
224  	
225  	
226  	static int luaB_next (lua_State *L) {
227  	  luaL_checktype(L, 1, LUA_TTABLE);
228  	  lua_settop(L, 2);  /* create a 2nd argument if there isn't one */
229  	  if (lua_next(L, 1))
230  	    return 2;
231  	  else {
232  	    lua_pushnil(L);
233  	    return 1;
234  	  }
235  	}
236  	
237  	
238  	static int luaB_pairs (lua_State *L) {
239  	  return pairsmeta(L, "__pairs", 0, luaB_next);
240  	}
241  	
242  	
243  	/*
244  	** Traversal function for 'ipairs'
245  	*/
246  	static int ipairsaux (lua_State *L) {
247  	  lua_Integer i = luaL_checkinteger(L, 2) + 1;
248  	  lua_pushinteger(L, i);
249  	  return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
250  	}
251  	
252  	
253  	/*
254  	** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
255  	** traverse a table, depending on whether the table has metamethods
256  	** that can affect the traversal.
257  	*/
258  	static int luaB_ipairs (lua_State *L) {
259  	#if defined(LUA_COMPAT_IPAIRS)
260  	  return pairsmeta(L, "__ipairs", 1, ipairsaux);
261  	#else
262  	  luaL_checkany(L, 1);
263  	  lua_pushcfunction(L, ipairsaux);  /* iteration function */
264  	  lua_pushvalue(L, 1);  /* state */
265  	  lua_pushinteger(L, 0);  /* initial value */
266  	  return 3;
267  	#endif
268  	}
269  	
270  	
271  	static int load_aux (lua_State *L, int status, int envidx) {
272  	  if (status == LUA_OK) {
273  	    if (envidx != 0) {  /* 'env' parameter? */
274  	      lua_pushvalue(L, envidx);  /* environment for loaded function */
275  	      if (!lua_setupvalue(L, -2, 1))  /* set it as 1st upvalue */
276  	        lua_pop(L, 1);  /* remove 'env' if not used by previous call */
277  	    }
278  	    return 1;
279  	  }
280  	  else {  /* error (message is on top of the stack) */
281  	    lua_pushnil(L);
282  	    lua_insert(L, -2);  /* put before error message */
283  	    return 2;  /* return nil plus error message */
284  	  }
285  	}
286  	
287  	
288  	static int luaB_loadfile (lua_State *L) {
289  	  const char *fname = luaL_optstring(L, 1, NULL);
290  	  const char *mode = luaL_optstring(L, 2, NULL);
291  	  int env = (!lua_isnone(L, 3) ? 3 : 0);  /* 'env' index or 0 if no 'env' */
292  	  int status = luaL_loadfilex(L, fname, mode);
293  	  return load_aux(L, status, env);
294  	}
295  	
296  	
297  	/*
298  	** {======================================================
299  	** Generic Read function
300  	** =======================================================
301  	*/
302  	
303  	
304  	/*
305  	** reserved slot, above all arguments, to hold a copy of the returned
306  	** string to avoid it being collected while parsed. 'load' has four
307  	** optional arguments (chunk, source name, mode, and environment).
308  	*/
309  	#define RESERVEDSLOT	5
310  	
311  	
312  	/*
313  	** Reader for generic 'load' function: 'lua_load' uses the
314  	** stack for internal stuff, so the reader cannot change the
315  	** stack top. Instead, it keeps its resulting string in a
316  	** reserved slot inside the stack.
317  	*/
318  	static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
319  	  (void)(ud);  /* not used */
320  	  luaL_checkstack(L, 2, "too many nested functions");
321  	  lua_pushvalue(L, 1);  /* get function */
322  	  lua_call(L, 0, 1);  /* call it */
323  	  if (lua_isnil(L, -1)) {
324  	    lua_pop(L, 1);  /* pop result */
325  	    *size = 0;
326  	    return NULL;
327  	  }
328  	  else if (!lua_isstring(L, -1))
329  	    luaL_error(L, "reader function must return a string");
330  	  lua_replace(L, RESERVEDSLOT);  /* save string in reserved slot */
331  	  return lua_tolstring(L, RESERVEDSLOT, size);
332  	}
333  	
334  	
335  	static int luaB_load (lua_State *L) {
336  	  int status;
337  	  size_t l;
338  	  const char *s = lua_tolstring(L, 1, &l);
339  	  const char *mode = luaL_optstring(L, 3, "bt");
340  	  int env = (!lua_isnone(L, 4) ? 4 : 0);  /* 'env' index or 0 if no 'env' */
341  	  if (s != NULL) {  /* loading a string? */
342  	    const char *chunkname = luaL_optstring(L, 2, s);
343  	    status = luaL_loadbufferx(L, s, l, chunkname, mode);
344  	  }
345  	  else {  /* loading from a reader function */
346  	    const char *chunkname = luaL_optstring(L, 2, "=(load)");
347  	    luaL_checktype(L, 1, LUA_TFUNCTION);
348  	    lua_settop(L, RESERVEDSLOT);  /* create reserved slot */
349  	    status = lua_load(L, generic_reader, NULL, chunkname, mode);
350  	  }
351  	  return load_aux(L, status, env);
352  	}
353  	
354  	/* }====================================================== */
355  	
356  	
357  	static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
358  	  (void)d1;  (void)d2;  /* only to match 'lua_Kfunction' prototype */
359  	  return lua_gettop(L) - 1;
360  	}
361  	
362  	
363  	static int luaB_dofile (lua_State *L) {
364  	  const char *fname = luaL_optstring(L, 1, NULL);
365  	  lua_settop(L, 1);
366  	  if (luaL_loadfile(L, fname) != LUA_OK)
367  	    return lua_error(L);
368  	  lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
369  	  return dofilecont(L, 0, 0);
370  	}
371  	
372  	
373  	static int luaB_assert (lua_State *L) {
374  	  if (lua_toboolean(L, 1))  /* condition is true? */
375  	    return lua_gettop(L);  /* return all arguments */
376  	  else {  /* error */
377  	    luaL_checkany(L, 1);  /* there must be a condition */
378  	    lua_remove(L, 1);  /* remove it */
379  	    lua_pushliteral(L, "assertion failed!");  /* default message */
380  	    lua_settop(L, 1);  /* leave only message (default if no other one) */
381  	    return luaB_error(L);  /* call 'error' */
382  	  }
383  	}
384  	
385  	
386  	static int luaB_select (lua_State *L) {
387  	  int n = lua_gettop(L);
388  	  if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
389  	    lua_pushinteger(L, n-1);
390  	    return 1;
391  	  }
392  	  else {
393  	    lua_Integer i = luaL_checkinteger(L, 1);
394  	    if (i < 0) i = n + i;
395  	    else if (i > n) i = n;
396  	    luaL_argcheck(L, 1 <= i, 1, "index out of range");
397  	    return n - (int)i;
398  	  }
399  	}
400  	
401  	
402  	/*
403  	** Continuation function for 'pcall' and 'xpcall'. Both functions
404  	** already pushed a 'true' before doing the call, so in case of success
405  	** 'finishpcall' only has to return everything in the stack minus
406  	** 'extra' values (where 'extra' is exactly the number of items to be
407  	** ignored).
408  	*/
409  	static int finishpcall (lua_State *L, int status, lua_KContext extra) {
410  	  if (status != LUA_OK && status != LUA_YIELD) {  /* error? */
411  	    lua_pushboolean(L, 0);  /* first result (false) */
412  	    lua_pushvalue(L, -2);  /* error message */
413  	    return 2;  /* return false, msg */
414  	  }
415  	  else
416  	    return lua_gettop(L) - (int)extra;  /* return all results */
417  	}
418  	
419  	
420  	static int luaB_pcall (lua_State *L) {
421  	  int status;
422  	  luaL_checkany(L, 1);
423  	  lua_pushboolean(L, 1);  /* first result if no errors */
424  	  lua_insert(L, 1);  /* put it in place */
425  	  status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
426  	  return finishpcall(L, status, 0);
427  	}
428  	
429  	
430  	/*
431  	** Do a protected call with error handling. After 'lua_rotate', the
432  	** stack will have <f, err, true, f, [args...]>; so, the function passes
433  	** 2 to 'finishpcall' to skip the 2 first values when returning results.
434  	*/
435  	static int luaB_xpcall (lua_State *L) {
436  	  int status;
437  	  int n = lua_gettop(L);
438  	  luaL_checktype(L, 2, LUA_TFUNCTION);  /* check error function */
439  	  lua_pushboolean(L, 1);  /* first result */
440  	  lua_pushvalue(L, 1);  /* function */
441  	  lua_rotate(L, 3, 2);  /* move them below function's arguments */
442  	  status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
443  	  return finishpcall(L, status, 2);
444  	}
445  	
446  	
447  	static int luaB_tostring (lua_State *L) {
448  	  luaL_checkany(L, 1);
449  	  luaL_tolstring(L, 1, NULL);
450  	  return 1;
451  	}
452  	
453  	
454  	static const luaL_Reg base_funcs[] = {
455  	  {"assert", luaB_assert},
456  	  {"collectgarbage", luaB_collectgarbage},
457  	  {"dofile", luaB_dofile},
458  	  {"error", luaB_error},
459  	  {"getmetatable", luaB_getmetatable},
460  	  {"ipairs", luaB_ipairs},
461  	  {"loadfile", luaB_loadfile},
462  	  {"load", luaB_load},
463  	#if defined(LUA_COMPAT_LOADSTRING)
464  	  {"loadstring", luaB_load},
465  	#endif
466  	  {"next", luaB_next},
467  	  {"pairs", luaB_pairs},
468  	  {"pcall", luaB_pcall},
469  	  {"print", luaB_print},
470  	  {"rawequal", luaB_rawequal},
471  	  {"rawlen", luaB_rawlen},
472  	  {"rawget", luaB_rawget},
473  	  {"rawset", luaB_rawset},
474  	  {"select", luaB_select},
475  	  {"setmetatable", luaB_setmetatable},
476  	  {"tonumber", luaB_tonumber},
477  	  {"tostring", luaB_tostring},
478  	  {"type", luaB_type},
479  	  {"xpcall", luaB_xpcall},
480  	  /* placeholders */
481  	  {"_G", NULL},
482  	  {"_VERSION", NULL},
483  	  {NULL, NULL}
484  	};
485  	
486  	
487  	LUAMOD_API int luaopen_base (lua_State *L) {
488  	  /* open lib into global table */
489  	  lua_pushglobaltable(L);
490  	  luaL_setfuncs(L, base_funcs, 0);
491  	  /* set global _G */
492  	  lua_pushvalue(L, -1);
493  	  lua_setfield(L, -2, "_G");
494  	  /* set global _VERSION */
495  	  lua_pushliteral(L, LUA_VERSION);
496  	  lua_setfield(L, -2, "_VERSION");
497  	  return 1;
498  	}
499  	
500