1    	/*
2    	** $Id: lobject.c,v 2.108 2015/11/02 16:09:30 roberto Exp $
3    	** Some generic functions over Lua objects
4    	** See Copyright Notice in lua.h
5    	*/
6    	
7    	#define lobject_c
8    	#define LUA_CORE
9    	
10   	#include "lprefix.h"
11   	
12   	
13   	#include <locale.h>
14   	#include <math.h>
15   	#include <stdarg.h>
16   	#include <stdio.h>
17   	#include <stdlib.h>
18   	#include <string.h>
19   	
20   	#include "lua.h"
21   	
22   	#include "lctype.h"
23   	#include "ldebug.h"
24   	#include "ldo.h"
25   	#include "lmem.h"
26   	#include "lobject.h"
27   	#include "lstate.h"
28   	#include "lstring.h"
29   	#include "lvm.h"
30   	
31   	
32   	
33   	LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
34   	
35   	
36   	/*
37   	** converts an integer to a "floating point byte", represented as
38   	** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
39   	** eeeee != 0 and (xxx) otherwise.
40   	*/
41   	int luaO_int2fb (unsigned int x) {
42   	  int e = 0;  /* exponent */
43   	  if (x < 8) return x;
44   	  while (x >= (8 << 4)) {  /* coarse steps */
45   	    x = (x + 0xf) >> 4;  /* x = ceil(x / 16) */
46   	    e += 4;
47   	  }
48   	  while (x >= (8 << 1)) {  /* fine steps */
49   	    x = (x + 1) >> 1;  /* x = ceil(x / 2) */
50   	    e++;
51   	  }
52   	  return ((e+1) << 3) | (cast_int(x) - 8);
53   	}
54   	
55   	
56   	/* converts back */
57   	int luaO_fb2int (int x) {
58   	  return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1);
59   	}
60   	
61   	
62   	/*
63   	** Computes ceil(log2(x))
64   	*/
65   	int luaO_ceillog2 (unsigned int x) {
66   	  static const lu_byte log_2[256] = {  /* log_2[i] = ceil(log2(i - 1)) */
67   	    0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
68   	    6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
69   	    7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
70   	    7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
71   	    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
72   	    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
73   	    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
74   	    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
75   	  };
76   	  int l = 0;
77   	  x--;
78   	  while (x >= 256) { l += 8; x >>= 8; }
79   	  return l + log_2[x];
80   	}
81   	
82   	
83   	static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
84   	                                                   lua_Integer v2) {
85   	  switch (op) {
86   	    case LUA_OPADD: return intop(+, v1, v2);
87   	    case LUA_OPSUB:return intop(-, v1, v2);
88   	    case LUA_OPMUL:return intop(*, v1, v2);
89   	    case LUA_OPMOD: return luaV_mod(L, v1, v2);
90   	    case LUA_OPIDIV: return luaV_div(L, v1, v2);
91   	    case LUA_OPBAND: return intop(&, v1, v2);
92   	    case LUA_OPBOR: return intop(|, v1, v2);
93   	    case LUA_OPBXOR: return intop(^, v1, v2);
94   	    case LUA_OPSHL: return luaV_shiftl(v1, v2);
95   	    case LUA_OPSHR: return luaV_shiftl(v1, -v2);
96   	    case LUA_OPUNM: return intop(-, 0, v1);
97   	    case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
98   	    default: lua_assert(0); return 0;
99   	  }
100  	}
101  	
102  	
103  	static lua_Number numarith (lua_State *L, int op, lua_Number v1,
104  	                                                  lua_Number v2) {
105  	  switch (op) {
106  	    case LUA_OPADD: return luai_numadd(L, v1, v2);
107  	    case LUA_OPSUB: return luai_numsub(L, v1, v2);
108  	    case LUA_OPMUL: return luai_nummul(L, v1, v2);
109  	    case LUA_OPDIV: return luai_numdiv(L, v1, v2);
110  	    case LUA_OPPOW: return luai_numpow(L, v1, v2);
111  	    case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
112  	    case LUA_OPUNM: return luai_numunm(L, v1);
113  	    case LUA_OPMOD: {
114  	      lua_Number m;
115  	      luai_nummod(L, v1, v2, m);
116  	      return m;
117  	    }
118  	    default: lua_assert(0); return 0;
119  	  }
120  	}
121  	
122  	
123  	void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
124  	                 TValue *res) {
125  	  switch (op) {
126  	    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
127  	    case LUA_OPSHL: case LUA_OPSHR:
128  	    case LUA_OPBNOT: {  /* operate only on integers */
129  	      lua_Integer i1; lua_Integer i2;
130  	      if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
131  	        setivalue(res, intarith(L, op, i1, i2));
132  	        return;
133  	      }
134  	      else break;  /* go to the end */
135  	    }
136  	    case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */
137  	      lua_Number n1; lua_Number n2;
138  	      if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
139  	        setfltvalue(res, numarith(L, op, n1, n2));
140  	        return;
141  	      }
142  	      else break;  /* go to the end */
143  	    }
144  	    default: {  /* other operations */
145  	      lua_Number n1; lua_Number n2;
146  	      if (ttisinteger(p1) && ttisinteger(p2)) {
147  	        setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
148  	        return;
149  	      }
150  	      else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
151  	        setfltvalue(res, numarith(L, op, n1, n2));
152  	        return;
153  	      }
154  	      else break;  /* go to the end */
155  	    }
156  	  }
157  	  /* could not perform raw operation; try metamethod */
158  	  lua_assert(L != NULL);  /* should not fail when folding (compile time) */
159  	  luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
160  	}
161  	
162  	
163  	int luaO_hexavalue (int c) {
164  	  if (lisdigit(c)) return c - '0';
165  	  else return (ltolower(c) - 'a') + 10;
166  	}
167  	
168  	
169  	static int isneg (const char **s) {
170  	  if (**s == '-') { (*s)++; return 1; }
171  	  else if (**s == '+') (*s)++;
172  	  return 0;
173  	}
174  	
175  	
176  	
177  	/*
178  	** {==================================================================
179  	** Lua's implementation for 'lua_strx2number'
180  	** ===================================================================
181  	*/
182  	
183  	#if !defined(lua_strx2number)
184  	
185  	/* maximum number of significant digits to read (to avoid overflows
186  	   even with single floats) */
187  	#define MAXSIGDIG	30
188  	
189  	/*
190  	** convert an hexadecimal numeric string to a number, following
191  	** C99 specification for 'strtod'
192  	*/
193  	static lua_Number lua_strx2number (const char *s, char **endptr) {
194  	  int dot = lua_getlocaledecpoint();
195  	  lua_Number r = 0.0;  /* result (accumulator) */
196  	  int sigdig = 0;  /* number of significant digits */
197  	  int nosigdig = 0;  /* number of non-significant digits */
198  	  int e = 0;  /* exponent correction */
199  	  int neg;  /* 1 if number is negative */
200  	  int hasdot = 0;  /* true after seen a dot */
201  	  *endptr = cast(char *, s);  /* nothing is valid yet */
202  	  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
203  	  neg = isneg(&s);  /* check signal */
204  	  if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */
205  	    return 0.0;  /* invalid format (no '0x') */
206  	  for (s += 2; ; s++) {  /* skip '0x' and read numeral */
207  	    if (*s == dot) {
208  	      if (hasdot) break;  /* second dot? stop loop */
209  	      else hasdot = 1;
210  	    }
211  	    else if (lisxdigit(cast_uchar(*s))) {
212  	      if (sigdig == 0 && *s == '0')  /* non-significant digit (zero)? */
213  	        nosigdig++;
214  	      else if (++sigdig <= MAXSIGDIG)  /* can read it without overflow? */
215  	          r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
216  	      else e++; /* too many digits; ignore, but still count for exponent */
217  	      if (hasdot) e--;  /* decimal digit? correct exponent */
218  	    }
219  	    else break;  /* neither a dot nor a digit */
220  	  }
221  	  if (nosigdig + sigdig == 0)  /* no digits? */
222  	    return 0.0;  /* invalid format */
223  	  *endptr = cast(char *, s);  /* valid up to here */
224  	  e *= 4;  /* each digit multiplies/divides value by 2^4 */
225  	  if (*s == 'p' || *s == 'P') {  /* exponent part? */
226  	    int exp1 = 0;  /* exponent value */
227  	    int neg1;  /* exponent signal */
228  	    s++;  /* skip 'p' */
229  	    neg1 = isneg(&s);  /* signal */
230  	    if (!lisdigit(cast_uchar(*s)))
231  	      return 0.0;  /* invalid; must have at least one digit */
232  	    while (lisdigit(cast_uchar(*s)))  /* read exponent */
233  	      exp1 = exp1 * 10 + *(s++) - '0';
234  	    if (neg1) exp1 = -exp1;
235  	    e += exp1;
236  	    *endptr = cast(char *, s);  /* valid up to here */
237  	  }
238  	  if (neg) r = -r;
239  	  return l_mathop(ldexp)(r, e);
240  	}
241  	
242  	#endif
243  	/* }====================================================== */
244  	
245  	
246  	static const char *l_str2d (const char *s, lua_Number *result) {
247  	  char *endptr;
248  	  if (strpbrk(s, "nN"))  /* reject 'inf' and 'nan' */
249  	    return NULL;
250  	  else if (strpbrk(s, "xX"))  /* hex? */
251  	    *result = lua_strx2number(s, &endptr);
252  	  else
253  	    *result = lua_str2number(s, &endptr);
254  	  if (endptr == s) return NULL;  /* nothing recognized */
255  	  while (lisspace(cast_uchar(*endptr))) endptr++;
256  	  return (*endptr == '\0' ? endptr : NULL);  /* OK if no trailing characters */
257  	}
258  	
259  	
260  	static const char *l_str2int (const char *s, lua_Integer *result) {
261  	  lua_Unsigned a = 0;
262  	  int empty = 1;
263  	  int neg;
(1) Event deref_parm: Directly dereferencing parameter "s".
264  	  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
265  	  neg = isneg(&s);
266  	  if (s[0] == '0' &&
267  	      (s[1] == 'x' || s[1] == 'X')) {  /* hex? */
268  	    s += 2;  /* skip '0x' */
269  	    for (; lisxdigit(cast_uchar(*s)); s++) {
270  	      a = a * 16 + luaO_hexavalue(*s);
271  	      empty = 0;
272  	    }
273  	  }
274  	  else {  /* decimal */
275  	    for (; lisdigit(cast_uchar(*s)); s++) {
276  	      a = a * 10 + *s - '0';
277  	      empty = 0;
278  	    }
279  	  }
280  	  while (lisspace(cast_uchar(*s))) s++;  /* skip trailing spaces */
281  	  if (empty || *s != '\0') return NULL;  /* something wrong in the numeral */
282  	  else {
283  	    *result = l_castU2S((neg) ? 0u - a : a);
284  	    return s;
285  	  }
286  	}
287  	
288  	
289  	size_t luaO_str2num (const char *s, TValue *o) {
290  	  lua_Integer i; lua_Number n;
291  	  const char *e;
(1) Event deref_parm_in_call: Function "l_str2int" dereferences "s". [details]
292  	  if ((e = l_str2int(s, &i)) != NULL) {  /* try as an integer */
293  	    setivalue(o, i);
294  	  }
295  	  else if ((e = l_str2d(s, &n)) != NULL) {  /* else try as a float */
296  	    setfltvalue(o, n);
297  	  }
298  	  else
299  	    return 0;  /* conversion failed */
300  	  return (e - s) + 1;  /* success; return string size */
301  	}
302  	
303  	
304  	int luaO_utf8esc (char *buff, unsigned long x) {
305  	  int n = 1;  /* number of bytes put in buffer (backwards) */
306  	  lua_assert(x <= 0x10FFFF);
307  	  if (x < 0x80)  /* ascii? */
308  	    buff[UTF8BUFFSZ - 1] = cast(char, x);
309  	  else {  /* need continuation bytes */
310  	    unsigned int mfb = 0x3f;  /* maximum that fits in first byte */
311  	    do {  /* add continuation bytes */
312  	      buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
313  	      x >>= 6;  /* remove added bits */
314  	      mfb >>= 1;  /* now there is one less bit available in first byte */
315  	    } while (x > mfb);  /* still needs continuation byte? */
316  	    buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x);  /* add first byte */
317  	  }
318  	  return n;
319  	}
320  	
321  	
322  	/* maximum length of the conversion of a number to a string */
323  	#define MAXNUMBER2STR	50
324  	
325  	
326  	/*
327  	** Convert a number object to a string
328  	*/
329  	void luaO_tostring (lua_State *L, StkId obj) {
330  	  char buff[MAXNUMBER2STR];
331  	  size_t len;
332  	  lua_assert(ttisnumber(obj));
333  	  if (ttisinteger(obj))
334  	    len = lua_integer2str(buff, sizeof(buff), ivalue(obj));
335  	  else {
336  	    len = lua_number2str(buff, sizeof(buff), fltvalue(obj));
337  	#if !defined(LUA_COMPAT_FLOATSTRING)
338  	    if (buff[strspn(buff, "-0123456789")] == '\0') {  /* looks like an int? */
339  	      buff[len++] = lua_getlocaledecpoint();
340  	      buff[len++] = '0';  /* adds '.0' to result */
341  	    }
342  	#endif
343  	  }
344  	  setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
345  	}
346  	
347  	
348  	static void pushstr (lua_State *L, const char *str, size_t l) {
349  	  setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
350  	  luaD_inctop(L);
351  	}
352  	
353  	
354  	/* this function handles only '%d', '%c', '%f', '%p', and '%s' 
355  	   conventional formats, plus Lua-specific '%I' and '%U' */
356  	const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
357  	  int n = 0;
358  	  for (;;) {
359  	    const char *e = strchr(fmt, '%');
360  	    if (e == NULL) break;
361  	    pushstr(L, fmt, e - fmt);
362  	    switch (*(e+1)) {
363  	      case 's': {
364  	        const char *s = va_arg(argp, char *);
365  	        if (s == NULL) s = "(null)";
366  	        pushstr(L, s, strlen(s));
367  	        break;
368  	      }
369  	      case 'c': {
370  	        char buff = cast(char, va_arg(argp, int));
371  	        if (lisprint(cast_uchar(buff)))
372  	          pushstr(L, &buff, 1);
373  	        else  /* non-printable character; print its code */
374  	          luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
375  	        break;
376  	      }
377  	      case 'd': {
378  	        setivalue(L->top, va_arg(argp, int));
379  	        goto top2str;
380  	      }
381  	      case 'I': {
382  	        setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt)));
383  	        goto top2str;
384  	      }
385  	      case 'f': {
386  	        setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
387  	      top2str:
388  	        luaD_inctop(L);
389  	        luaO_tostring(L, L->top - 1);
390  	        break;
391  	      }
392  	      case 'p': {
393  	        char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
394  	        int l = l_sprintf(buff, sizeof(buff), "%p", va_arg(argp, void *));
395  	        pushstr(L, buff, l);
396  	        break;
397  	      }
398  	      case 'U': {
399  	        char buff[UTF8BUFFSZ];
400  	        int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
401  	        pushstr(L, buff + UTF8BUFFSZ - l, l);
402  	        break;
403  	      }
404  	      case '%': {
405  	        pushstr(L, "%", 1);
406  	        break;
407  	      }
408  	      default: {
409  	        luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
410  	                         *(e + 1));
411  	      }
412  	    }
413  	    n += 2;
414  	    fmt = e+2;
415  	  }
416  	  luaD_checkstack(L, 1);
417  	  pushstr(L, fmt, strlen(fmt));
418  	  if (n > 0) luaV_concat(L, n + 1);
419  	  return svalue(L->top - 1);
420  	}
421  	
422  	
423  	const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
424  	  const char *msg;
425  	  va_list argp;
426  	  va_start(argp, fmt);
427  	  msg = luaO_pushvfstring(L, fmt, argp);
428  	  va_end(argp);
429  	  return msg;
430  	}
431  	
432  	
433  	/* number of chars of a literal string without the ending \0 */
434  	#define LL(x)	(sizeof(x)/sizeof(char) - 1)
435  	
436  	#define RETS	"..."
437  	#define PRE	"[string \""
438  	#define POS	"\"]"
439  	
440  	#define addstr(a,b,l)	( memcpy(a,b,(l) * sizeof(char)), a += (l) )
441  	
442  	void luaO_chunkid (char *out, const char *source, size_t bufflen) {
443  	  size_t l = strlen(source);
444  	  if (*source == '=') {  /* 'literal' source */
445  	    if (l <= bufflen)  /* small enough? */
446  	      memcpy(out, source + 1, l * sizeof(char));
447  	    else {  /* truncate it */
448  	      addstr(out, source + 1, bufflen - 1);
449  	      *out = '\0';
450  	    }
451  	  }
452  	  else if (*source == '@') {  /* file name */
453  	    if (l <= bufflen)  /* small enough? */
454  	      memcpy(out, source + 1, l * sizeof(char));
455  	    else {  /* add '...' before rest of name */
456  	      addstr(out, RETS, LL(RETS));
457  	      bufflen -= LL(RETS);
458  	      memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
459  	    }
460  	  }
461  	  else {  /* string; format as [string "source"] */
462  	    const char *nl = strchr(source, '\n');  /* find first new line (if any) */
463  	    addstr(out, PRE, LL(PRE));  /* add prefix */
464  	    bufflen -= LL(PRE RETS POS) + 1;  /* save space for prefix+suffix+'\0' */
465  	    if (l < bufflen && nl == NULL) {  /* small one-line source? */
466  	      addstr(out, source, l);  /* keep it */
467  	    }
468  	    else {
469  	      if (nl != NULL) l = nl - source;  /* stop at first newline */
470  	      if (l > bufflen) l = bufflen;
471  	      addstr(out, source, l);
472  	      addstr(out, RETS, LL(RETS));
473  	    }
474  	    memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
475  	  }
476  	}
477  	
478