Merge pull request #2593 from Akury83/master
[RRG-proxmark3.git] / client / deps / liblua / lobject.c
blob423df18b2b3aad41e4469b2c9ff41bb218eda67a
1 /*
2 ** $Id: lobject.c $
3 ** Some generic functions over Lua objects
4 ** See Copyright Notice in lua.h
5 */
7 #define lobject_c
8 #define LUA_CORE
10 #include "lprefix.h"
13 #include <locale.h>
14 #include <math.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
20 #include "lua.h"
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"
33 ** Computes ceil(log2(x))
35 int luaO_ceillog2(unsigned int x) {
36 static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */
37 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,
38 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,
39 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,
40 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,
41 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,
42 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,
43 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,
44 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
46 int l = 0;
47 x--;
48 while (x >= 256) { l += 8; x >>= 8; }
49 return l + log_2[x];
53 static lua_Integer intarith(lua_State *L, int op, lua_Integer v1,
54 lua_Integer v2) {
55 switch (op) {
56 case LUA_OPADD:
57 return intop(+, v1, v2);
58 case LUA_OPSUB:
59 return intop(-, v1, v2);
60 case LUA_OPMUL:
61 return intop(*, v1, v2);
62 case LUA_OPMOD:
63 return luaV_mod(L, v1, v2);
64 case LUA_OPIDIV:
65 return luaV_idiv(L, v1, v2);
66 case LUA_OPBAND:
67 return intop(&, v1, v2);
68 case LUA_OPBOR:
69 return intop( |, v1, v2);
70 case LUA_OPBXOR:
71 return intop(^, v1, v2);
72 case LUA_OPSHL:
73 return luaV_shiftl(v1, v2);
74 case LUA_OPSHR:
75 return luaV_shiftr(v1, v2);
76 case LUA_OPUNM:
77 return intop(-, 0, v1);
78 case LUA_OPBNOT:
79 return intop(^, ~l_castS2U(0), v1);
80 default:
81 lua_assert(0);
82 return 0;
87 static lua_Number numarith(lua_State *L, int op, lua_Number v1,
88 lua_Number v2) {
89 switch (op) {
90 case LUA_OPADD:
91 return luai_numadd(L, v1, v2);
92 case LUA_OPSUB:
93 return luai_numsub(L, v1, v2);
94 case LUA_OPMUL:
95 return luai_nummul(L, v1, v2);
96 case LUA_OPDIV:
97 return luai_numdiv(L, v1, v2);
98 case LUA_OPPOW:
99 return luai_numpow(L, v1, v2);
100 case LUA_OPIDIV:
101 return luai_numidiv(L, v1, v2);
102 case LUA_OPUNM:
103 return luai_numunm(L, v1);
104 case LUA_OPMOD:
105 return luaV_modf(L, v1, v2);
106 default:
107 lua_assert(0);
108 return 0;
113 int luaO_rawarith(lua_State *L, int op, const TValue *p1, const TValue *p2,
114 TValue *res) {
115 switch (op) {
116 case LUA_OPBAND:
117 case LUA_OPBOR:
118 case LUA_OPBXOR:
119 case LUA_OPSHL:
120 case LUA_OPSHR:
121 case LUA_OPBNOT: { /* operate only on integers */
122 lua_Integer i1;
123 lua_Integer i2;
124 if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {
125 setivalue(res, intarith(L, op, i1, i2));
126 return 1;
127 } else return 0; /* fail */
129 case LUA_OPDIV:
130 case LUA_OPPOW: { /* operate only on floats */
131 lua_Number n1;
132 lua_Number n2;
133 if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
134 setfltvalue(res, numarith(L, op, n1, n2));
135 return 1;
136 } else return 0; /* fail */
138 default: { /* other operations */
139 lua_Number n1;
140 lua_Number n2;
141 if (ttisinteger(p1) && ttisinteger(p2)) {
142 setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
143 return 1;
144 } else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
145 setfltvalue(res, numarith(L, op, n1, n2));
146 return 1;
147 } else return 0; /* fail */
153 void luaO_arith(lua_State *L, int op, const TValue *p1, const TValue *p2,
154 StkId res) {
155 if (!luaO_rawarith(L, op, p1, p2, s2v(res))) {
156 /* could not perform raw operation; try metamethod */
157 luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
162 int luaO_hexavalue(int c) {
163 if (lisdigit(c)) return c - '0';
164 else return (ltolower(c) - 'a') + 10;
168 static int isneg(const char **s) {
169 if (**s == '-') { (*s)++; return 1; }
170 else if (**s == '+')(*s)++;
171 return 0;
177 ** {==================================================================
178 ** Lua's implementation for 'lua_strx2number'
179 ** ===================================================================
182 #if !defined(lua_strx2number)
184 /* maximum number of significant digits to read (to avoid overflows
185 even with single floats) */
186 #define MAXSIGDIG 30
189 ** convert a hexadecimal numeric string to a number, following
190 ** C99 specification for 'strtod'
192 static lua_Number lua_strx2number(const char *s, char **endptr) {
193 int dot = lua_getlocaledecpoint();
194 lua_Number r = l_mathop(0.0); /* result (accumulator) */
195 int sigdig = 0; /* number of significant digits */
196 int nosigdig = 0; /* number of non-significant digits */
197 int e = 0; /* exponent correction */
198 int neg; /* 1 if number is negative */
199 int hasdot = 0; /* true after seen a dot */
200 *endptr = cast_charp(s); /* nothing is valid yet */
201 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
202 neg = isneg(&s); /* check sign */
203 if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
204 return l_mathop(0.0); /* invalid format (no '0x') */
205 for (s += 2; ; s++) { /* skip '0x' and read numeral */
206 if (*s == dot) {
207 if (hasdot) break; /* second dot? stop loop */
208 else hasdot = 1;
209 } else if (lisxdigit(cast_uchar(*s))) {
210 if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
211 nosigdig++;
212 else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
213 r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
214 else e++; /* too many digits; ignore, but still count for exponent */
215 if (hasdot) e--; /* decimal digit? correct exponent */
216 } else break; /* neither a dot nor a digit */
218 if (nosigdig + sigdig == 0) /* no digits? */
219 return l_mathop(0.0); /* invalid format */
220 *endptr = cast_charp(s); /* valid up to here */
221 e *= 4; /* each digit multiplies/divides value by 2^4 */
222 if (*s == 'p' || *s == 'P') { /* exponent part? */
223 int exp1 = 0; /* exponent value */
224 int neg1; /* exponent sign */
225 s++; /* skip 'p' */
226 neg1 = isneg(&s); /* sign */
227 if (!lisdigit(cast_uchar(*s)))
228 return l_mathop(0.0); /* invalid; must have at least one digit */
229 while (lisdigit(cast_uchar(*s))) /* read exponent */
230 exp1 = exp1 * 10 + *(s++) - '0';
231 if (neg1) exp1 = -exp1;
232 e += exp1;
233 *endptr = cast_charp(s); /* valid up to here */
235 if (neg) r = -r;
236 return l_mathop(ldexp)(r, e);
239 #endif
240 /* }====================================================== */
243 /* maximum length of a numeral to be converted to a number */
244 #if !defined (L_MAXLENNUM)
245 #define L_MAXLENNUM 200
246 #endif
249 ** Convert string 's' to a Lua number (put in 'result'). Return NULL on
250 ** fail or the address of the ending '\0' on success. ('mode' == 'x')
251 ** means a hexadecimal numeral.
253 static const char *l_str2dloc(const char *s, lua_Number *result, int mode) {
254 char *endptr;
255 *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
256 : lua_str2number(s, &endptr);
257 if (endptr == s) return NULL; /* nothing recognized? */
258 while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
259 return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */
264 ** Convert string 's' to a Lua number (put in 'result') handling the
265 ** current locale.
266 ** This function accepts both the current locale or a dot as the radix
267 ** mark. If the conversion fails, it may mean number has a dot but
268 ** locale accepts something else. In that case, the code copies 's'
269 ** to a buffer (because 's' is read-only), changes the dot to the
270 ** current locale radix mark, and tries to convert again.
271 ** The variable 'mode' checks for special characters in the string:
272 ** - 'n' means 'inf' or 'nan' (which should be rejected)
273 ** - 'x' means a hexadecimal numeral
274 ** - '.' just optimizes the search for the common case (no special chars)
276 static const char *l_str2d(const char *s, lua_Number *result) {
277 const char *endptr;
278 const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */
279 int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
280 if (mode == 'n') /* reject 'inf' and 'nan' */
281 return NULL;
282 endptr = l_str2dloc(s, result, mode); /* try to convert */
283 if (endptr == NULL) { /* failed? may be a different locale */
284 char buff[L_MAXLENNUM + 1];
285 const char *pdot = strchr(s, '.');
286 if (pdot == NULL || strlen(s) > L_MAXLENNUM)
287 return NULL; /* string too long or no dot; fail */
288 strcpy(buff, s); /* copy string to buffer */
289 buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
290 endptr = l_str2dloc(buff, result, mode); /* try again */
291 if (endptr != NULL)
292 endptr = s + (endptr - buff); /* make relative to 's' */
294 return endptr;
298 #define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10)
299 #define MAXLASTD cast_int(LUA_MAXINTEGER % 10)
301 static const char *l_str2int(const char *s, lua_Integer *result) {
302 lua_Unsigned a = 0;
303 int empty = 1;
304 int neg;
305 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
306 neg = isneg(&s);
307 if (s[0] == '0' &&
308 (s[1] == 'x' || s[1] == 'X')) { /* hex? */
309 s += 2; /* skip '0x' */
310 for (; lisxdigit(cast_uchar(*s)); s++) {
311 a = a * 16 + luaO_hexavalue(*s);
312 empty = 0;
314 } else { /* decimal */
315 for (; lisdigit(cast_uchar(*s)); s++) {
316 int d = *s - '0';
317 if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */
318 return NULL; /* do not accept it (as integer) */
319 a = a * 10 + d;
320 empty = 0;
323 while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
324 if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
325 else {
326 *result = l_castU2S((neg) ? 0u - a : a);
327 return s;
332 size_t luaO_str2num(const char *s, TValue *o) {
333 lua_Integer i;
334 lua_Number n;
335 const char *e;
336 if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
337 setivalue(o, i);
338 } else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
339 setfltvalue(o, n);
340 } else
341 return 0; /* conversion failed */
342 return (e - s) + 1; /* success; return string size */
346 int luaO_utf8esc(char *buff, unsigned long x) {
347 int n = 1; /* number of bytes put in buffer (backwards) */
348 lua_assert(x <= 0x7FFFFFFFu);
349 if (x < 0x80) /* ascii? */
350 buff[UTF8BUFFSZ - 1] = cast_char(x);
351 else { /* need continuation bytes */
352 unsigned int mfb = 0x3f; /* maximum that fits in first byte */
353 do { /* add continuation bytes */
354 buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
355 x >>= 6; /* remove added bits */
356 mfb >>= 1; /* now there is one less bit available in first byte */
357 } while (x > mfb); /* still needs continuation byte? */
358 buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */
360 return n;
365 ** Maximum length of the conversion of a number to a string. Must be
366 ** enough to accommodate both LUA_INTEGER_FMT and LUA_NUMBER_FMT.
367 ** (For a long long int, this is 19 digits plus a sign and a final '\0',
368 ** adding to 21. For a long double, it can go to a sign, 33 digits,
369 ** the dot, an exponent letter, an exponent sign, 5 exponent digits,
370 ** and a final '\0', adding to 43.)
372 #define MAXNUMBER2STR 44
376 ** Convert a number object to a string, adding it to a buffer
378 static int tostringbuff(TValue *obj, char *buff) {
379 int len;
380 lua_assert(ttisnumber(obj));
381 if (ttisinteger(obj))
382 len = lua_integer2str(buff, MAXNUMBER2STR, ivalue(obj));
383 else {
384 len = lua_number2str(buff, MAXNUMBER2STR, fltvalue(obj));
385 if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
386 buff[len++] = lua_getlocaledecpoint();
387 buff[len++] = '0'; /* adds '.0' to result */
390 return len;
395 ** Convert a number object to a Lua string, replacing the value at 'obj'
397 void luaO_tostring(lua_State *L, TValue *obj) {
398 char buff[MAXNUMBER2STR];
399 int len = tostringbuff(obj, buff);
400 setsvalue(L, obj, luaS_newlstr(L, buff, len));
407 ** {==================================================================
408 ** 'luaO_pushvfstring'
409 ** ===================================================================
413 ** Size for buffer space used by 'luaO_pushvfstring'. It should be
414 ** (LUA_IDSIZE + MAXNUMBER2STR) + a minimal space for basic messages,
415 ** so that 'luaG_addinfo' can work directly on the buffer.
417 #define BUFVFS (LUA_IDSIZE + MAXNUMBER2STR + 95)
419 /* buffer used by 'luaO_pushvfstring' */
420 typedef struct BuffFS {
421 lua_State *L;
422 int pushed; /* true if there is a part of the result on the stack */
423 int blen; /* length of partial string in 'space' */
424 char space[BUFVFS]; /* holds last part of the result */
425 } BuffFS;
429 ** Push given string to the stack, as part of the result, and
430 ** join it to previous partial result if there is one.
431 ** It may call 'luaV_concat' while using one slot from EXTRA_STACK.
432 ** This call cannot invoke metamethods, as both operands must be
433 ** strings. It can, however, raise an error if the result is too
434 ** long. In that case, 'luaV_concat' frees the extra slot before
435 ** raising the error.
437 static void pushstr(BuffFS *buff, const char *str, size_t lstr) {
438 lua_State *L = buff->L;
439 setsvalue2s(L, L->top.p, luaS_newlstr(L, str, lstr));
440 L->top.p++; /* may use one slot from EXTRA_STACK */
441 if (!buff->pushed) /* no previous string on the stack? */
442 buff->pushed = 1; /* now there is one */
443 else /* join previous string with new one */
444 luaV_concat(L, 2);
449 ** empty the buffer space into the stack
451 static void clearbuff(BuffFS *buff) {
452 pushstr(buff, buff->space, buff->blen); /* push buffer contents */
453 buff->blen = 0; /* space now is empty */
458 ** Get a space of size 'sz' in the buffer. If buffer has not enough
459 ** space, empty it. 'sz' must fit in an empty buffer.
461 static char *getbuff(BuffFS *buff, int sz) {
462 lua_assert(buff->blen <= BUFVFS);
463 lua_assert(sz <= BUFVFS);
464 if (sz > BUFVFS - buff->blen) /* not enough space? */
465 clearbuff(buff);
466 return buff->space + buff->blen;
470 #define addsize(b,sz) ((b)->blen += (sz))
474 ** Add 'str' to the buffer. If string is larger than the buffer space,
475 ** push the string directly to the stack.
477 static void addstr2buff(BuffFS *buff, const char *str, size_t slen) {
478 if (slen <= BUFVFS) { /* does string fit into buffer? */
479 char *bf = getbuff(buff, cast_int(slen));
480 memcpy(bf, str, slen); /* add string to buffer */
481 addsize(buff, cast_int(slen));
482 } else { /* string larger than buffer */
483 clearbuff(buff); /* string comes after buffer's content */
484 pushstr(buff, str, slen); /* push string */
490 ** Add a numeral to the buffer.
492 static void addnum2buff(BuffFS *buff, TValue *num) {
493 char *numbuff = getbuff(buff, MAXNUMBER2STR);
494 int len = tostringbuff(num, numbuff); /* format number into 'numbuff' */
495 addsize(buff, len);
500 ** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'
501 conventional formats, plus Lua-specific '%I' and '%U'
503 const char *luaO_pushvfstring(lua_State *L, const char *fmt, va_list argp) {
504 BuffFS buff; /* holds last part of the result */
505 const char *e; /* points to next '%' */
506 buff.pushed = buff.blen = 0;
507 buff.L = L;
508 while ((e = strchr(fmt, '%')) != NULL) {
509 addstr2buff(&buff, fmt, e - fmt); /* add 'fmt' up to '%' */
510 switch (*(e + 1)) { /* conversion specifier */
511 case 's': { /* zero-terminated string */
512 const char *s = va_arg(argp, char *);
513 if (s == NULL) s = "(null)";
514 addstr2buff(&buff, s, strlen(s));
515 break;
517 case 'c': { /* an 'int' as a character */
518 char c = cast_uchar(va_arg(argp, int));
519 addstr2buff(&buff, &c, sizeof(char));
520 break;
522 case 'd': { /* an 'int' */
523 TValue num;
524 setivalue(&num, va_arg(argp, int));
525 addnum2buff(&buff, &num);
526 break;
528 case 'I': { /* a 'lua_Integer' */
529 TValue num;
530 setivalue(&num, cast(lua_Integer, va_arg(argp, l_uacInt)));
531 addnum2buff(&buff, &num);
532 break;
534 case 'f': { /* a 'lua_Number' */
535 TValue num;
536 setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
537 addnum2buff(&buff, &num);
538 break;
540 case 'p': { /* a pointer */
541 const int sz = 3 * sizeof(void *) + 8; /* enough space for '%p' */
542 char *bf = getbuff(&buff, sz);
543 void *p = va_arg(argp, void *);
544 int len = lua_pointer2str(bf, sz, p);
545 addsize(&buff, len);
546 break;
548 case 'U': { /* a 'long' as a UTF-8 sequence */
549 char bf[UTF8BUFFSZ];
550 int len = luaO_utf8esc(bf, va_arg(argp, long));
551 addstr2buff(&buff, bf + UTF8BUFFSZ - len, len);
552 break;
554 case '%': {
555 addstr2buff(&buff, "%", 1);
556 break;
558 default: {
559 luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
560 *(e + 1));
563 fmt = e + 2; /* skip '%' and the specifier */
565 addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */
566 clearbuff(&buff); /* empty buffer into the stack */
567 lua_assert(buff.pushed == 1);
568 return getstr(tsvalue(s2v(L->top.p - 1)));
572 const char *luaO_pushfstring(lua_State *L, const char *fmt, ...) {
573 const char *msg;
574 va_list argp;
575 va_start(argp, fmt);
576 msg = luaO_pushvfstring(L, fmt, argp);
577 va_end(argp);
578 return msg;
581 /* }================================================================== */
584 #define RETS "..."
585 #define PRE "[string \""
586 #define POS "\"]"
588 #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
590 void luaO_chunkid(char *out, const char *source, size_t srclen) {
591 size_t bufflen = LUA_IDSIZE; /* free space in buffer */
592 if (*source == '=') { /* 'literal' source */
593 if (srclen <= bufflen) /* small enough? */
594 memcpy(out, source + 1, srclen * sizeof(char));
595 else { /* truncate it */
596 addstr(out, source + 1, bufflen - 1);
597 *out = '\0';
599 } else if (*source == '@') { /* file name */
600 if (srclen <= bufflen) /* small enough? */
601 memcpy(out, source + 1, srclen * sizeof(char));
602 else { /* add '...' before rest of name */
603 addstr(out, RETS, LL(RETS));
604 bufflen -= LL(RETS);
605 memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
607 } else { /* string; format as [string "source"] */
608 const char *nl = strchr(source, '\n'); /* find first new line (if any) */
609 addstr(out, PRE, LL(PRE)); /* add prefix */
610 bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
611 if (srclen < bufflen && nl == NULL) { /* small one-line source? */
612 addstr(out, source, srclen); /* keep it */
613 } else {
614 if (nl != NULL) srclen = nl - source; /* stop at first newline */
615 if (srclen > bufflen) srclen = bufflen;
616 addstr(out, source, srclen);
617 addstr(out, RETS, LL(RETS));
619 memcpy(out, POS, (LL(POS) + 1) * sizeof(char));