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