Coverage Report

Created: 2025-08-25 07:03

/src/testdir/build/lua-master/source/lobject.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
** $Id: lobject.c $
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 <float.h>
14
#include <locale.h>
15
#include <math.h>
16
#include <stdarg.h>
17
#include <stdio.h>
18
#include <stdlib.h>
19
#include <string.h>
20
21
#include "lua.h"
22
23
#include "lctype.h"
24
#include "ldebug.h"
25
#include "ldo.h"
26
#include "lmem.h"
27
#include "lobject.h"
28
#include "lstate.h"
29
#include "lstring.h"
30
#include "lvm.h"
31
32
33
/*
34
** Computes ceil(log2(x)), which is the smallest integer n such that
35
** x <= (1 << n).
36
*/
37
42.9M
lu_byte luaO_ceillog2 (unsigned int x) {
38
42.9M
  static const lu_byte log_2[256] = {  /* log_2[i - 1] = ceil(log2(i)) */
39
42.9M
    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,
40
42.9M
    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,
41
42.9M
    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,
42
42.9M
    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,
43
42.9M
    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
42.9M
    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,
45
42.9M
    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
42.9M
    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
47
42.9M
  };
48
42.9M
  int l = 0;
49
42.9M
  x--;
50
44.2M
  while (x >= 256) { l += 8; x >>= 8; }
51
42.9M
  return cast_byte(l + log_2[x]);
52
42.9M
}
53
54
/*
55
** Encodes 'p'% as a floating-point byte, represented as (eeeexxxx).
56
** The exponent is represented using excess-7. Mimicking IEEE 754, the
57
** representation normalizes the number when possible, assuming an extra
58
** 1 before the mantissa (xxxx) and adding one to the exponent (eeee)
59
** to signal that. So, the real value is (1xxxx) * 2^(eeee - 7 - 1) if
60
** eeee != 0, and (xxxx) * 2^-7 otherwise (subnormal numbers).
61
*/
62
358k
lu_byte luaO_codeparam (unsigned int p) {
63
358k
  if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u)  /* overflow? */
64
0
    return 0xFF;  /* return maximum value */
65
358k
  else {
66
358k
    p = (cast(l_uint32, p) * 128 + 99) / 100;  /* round up the division */
67
358k
    if (p < 0x10) {  /* subnormal number? */
68
      /* exponent bits are already zero; nothing else to do */
69
0
      return cast_byte(p);
70
0
    }
71
358k
    else {  /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */
72
      /* preserve 5 bits in 'p' */
73
358k
      unsigned log = luaO_ceillog2(p + 1) - 5u;
74
358k
      return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4));
75
358k
    }
76
358k
  }
77
358k
}
78
79
80
/*
81
** Computes 'p' times 'x', where 'p' is a floating-point byte. Roughly,
82
** we have to multiply 'x' by the mantissa and then shift accordingly to
83
** the exponent.  If the exponent is positive, both the multiplication
84
** and the shift increase 'x', so we have to care only about overflows.
85
** For negative exponents, however, multiplying before the shift keeps
86
** more significant bits, as long as the multiplication does not
87
** overflow, so we check which order is best.
88
*/
89
4.11M
l_mem luaO_applyparam (lu_byte p, l_mem x) {
90
4.11M
  unsigned int m = p & 0xF;  /* mantissa */
91
4.11M
  int e = (p >> 4);  /* exponent */
92
4.11M
  if (e > 0) {  /* normalized? */
93
4.11M
    e--;  /* correct exponent */
94
4.11M
    m += 0x10;  /* correct mantissa; maximum value is 0x1F */
95
4.11M
  }
96
4.11M
  e -= 7;  /* correct excess-7 */
97
4.11M
  if (e >= 0) {
98
970k
    if (x < (MAX_LMEM / 0x1F) >> e)  /* no overflow? */
99
970k
      return (x * m) << e;  /* order doesn't matter here */
100
0
    else  /* real overflow */
101
0
      return MAX_LMEM;
102
970k
  }
103
3.14M
  else {  /* negative exponent */
104
3.14M
    e = -e;
105
3.14M
    if (x < MAX_LMEM / 0x1F)  /* multiplication cannot overflow? */
106
3.14M
      return (x * m) >> e;  /* multiplying first gives more precision */
107
0
    else if ((x >> e) <  MAX_LMEM / 0x1F)  /* cannot overflow after shift? */
108
0
      return (x >> e) * m;
109
0
    else  /* real overflow */
110
0
      return MAX_LMEM;
111
3.14M
  }
112
4.11M
}
113
114
115
static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
116
2.95M
                                                   lua_Integer v2) {
117
2.95M
  switch (op) {
118
149k
    case LUA_OPADD: return intop(+, v1, v2);
119
205k
    case LUA_OPSUB:return intop(-, v1, v2);
120
76.1k
    case LUA_OPMUL:return intop(*, v1, v2);
121
367k
    case LUA_OPMOD: return luaV_mod(L, v1, v2);
122
312k
    case LUA_OPIDIV: return luaV_idiv(L, v1, v2);
123
10.2k
    case LUA_OPBAND: return intop(&, v1, v2);
124
5.44k
    case LUA_OPBOR: return intop(|, v1, v2);
125
84.7k
    case LUA_OPBXOR: return intop(^, v1, v2);
126
15.5k
    case LUA_OPSHL: return luaV_shiftl(v1, v2);
127
160k
    case LUA_OPSHR: return luaV_shiftr(v1, v2);
128
353k
    case LUA_OPUNM: return intop(-, 0, v1);
129
1.21M
    case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
130
0
    default: lua_assert(0); return 0;
131
2.95M
  }
132
2.95M
}
133
134
135
static lua_Number numarith (lua_State *L, int op, lua_Number v1,
136
4.18M
                                                  lua_Number v2) {
137
4.18M
  switch (op) {
138
44.1k
    case LUA_OPADD: return luai_numadd(L, v1, v2);
139
375k
    case LUA_OPSUB: return luai_numsub(L, v1, v2);
140
174k
    case LUA_OPMUL: return luai_nummul(L, v1, v2);
141
422k
    case LUA_OPDIV: return luai_numdiv(L, v1, v2);
142
2.50M
    case LUA_OPPOW: return luai_numpow(L, v1, v2);
143
31.2k
    case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
144
588k
    case LUA_OPUNM: return luai_numunm(L, v1);
145
51.2k
    case LUA_OPMOD: return luaV_modf(L, v1, v2);
146
0
    default: lua_assert(0); return 0;
147
4.18M
  }
148
4.18M
}
149
150
151
int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2,
152
7.14M
                   TValue *res) {
153
7.14M
  switch (op) {
154
100k
    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
155
276k
    case LUA_OPSHL: case LUA_OPSHR:
156
1.48M
    case LUA_OPBNOT: {  /* operate only on integers */
157
1.48M
      lua_Integer i1; lua_Integer i2;
158
1.48M
      if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {
159
1.48M
        setivalue(res, intarith(L, op, i1, i2));
160
1.48M
        return 1;
161
1.48M
      }
162
0
      else return 0;  /* fail */
163
1.48M
    }
164
2.92M
    case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */
165
2.92M
      lua_Number n1; lua_Number n2;
166
2.92M
      if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
167
2.92M
        setfltvalue(res, numarith(L, op, n1, n2));
168
2.92M
        return 1;
169
2.92M
      }
170
0
      else return 0;  /* fail */
171
2.92M
    }
172
2.73M
    default: {  /* other operations */
173
2.73M
      lua_Number n1; lua_Number n2;
174
2.73M
      if (ttisinteger(p1) && ttisinteger(p2)) {
175
1.46M
        setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
176
1.46M
        return 1;
177
1.46M
      }
178
1.26M
      else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
179
1.26M
        setfltvalue(res, numarith(L, op, n1, n2));
180
1.26M
        return 1;
181
1.26M
      }
182
0
      else return 0;  /* fail */
183
2.73M
    }
184
7.14M
  }
185
7.14M
}
186
187
188
void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
189
541k
                 StkId res) {
190
541k
  if (!luaO_rawarith(L, op, p1, p2, s2v(res))) {
191
    /* could not perform raw operation; try metamethod */
192
0
    luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
193
0
  }
194
541k
}
195
196
197
3.49M
lu_byte luaO_hexavalue (int c) {
198
3.49M
  lua_assert(lisxdigit(c));
199
3.49M
  if (lisdigit(c)) return cast_byte(c - '0');
200
3.49M
  else return cast_byte((ltolower(c) - 'a') + 10);
201
3.49M
}
202
203
204
112M
static int isneg (const char **s) {
205
112M
  if (**s == '-') { (*s)++; return 1; }
206
111M
  else if (**s == '+') (*s)++;
207
111M
  return 0;
208
112M
}
209
210
211
212
/*
213
** {==================================================================
214
** Lua's implementation for 'lua_strx2number'
215
** ===================================================================
216
*/
217
218
#if !defined(lua_strx2number)
219
220
/* maximum number of significant digits to read (to avoid overflows
221
   even with single floats) */
222
#define MAXSIGDIG 30
223
224
/*
225
** convert a hexadecimal numeric string to a number, following
226
** C99 specification for 'strtod'
227
*/
228
static lua_Number lua_strx2number (const char *s, char **endptr) {
229
  int dot = lua_getlocaledecpoint();
230
  lua_Number r = l_mathop(0.0);  /* result (accumulator) */
231
  int sigdig = 0;  /* number of significant digits */
232
  int nosigdig = 0;  /* number of non-significant digits */
233
  int e = 0;  /* exponent correction */
234
  int neg;  /* 1 if number is negative */
235
  int hasdot = 0;  /* true after seen a dot */
236
  *endptr = cast_charp(s);  /* nothing is valid yet */
237
  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
238
  neg = isneg(&s);  /* check sign */
239
  if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */
240
    return l_mathop(0.0);  /* invalid format (no '0x') */
241
  for (s += 2; ; s++) {  /* skip '0x' and read numeral */
242
    if (*s == dot) {
243
      if (hasdot) break;  /* second dot? stop loop */
244
      else hasdot = 1;
245
    }
246
    else if (lisxdigit(cast_uchar(*s))) {
247
      if (sigdig == 0 && *s == '0')  /* non-significant digit (zero)? */
248
        nosigdig++;
249
      else if (++sigdig <= MAXSIGDIG)  /* can read it without overflow? */
250
          r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
251
      else e++;  /* too many digits; ignore, but still count for exponent */
252
      if (hasdot) e--;  /* decimal digit? correct exponent */
253
    }
254
    else break;  /* neither a dot nor a digit */
255
  }
256
  if (nosigdig + sigdig == 0)  /* no digits? */
257
    return l_mathop(0.0);  /* invalid format */
258
  *endptr = cast_charp(s);  /* valid up to here */
259
  e *= 4;  /* each digit multiplies/divides value by 2^4 */
260
  if (*s == 'p' || *s == 'P') {  /* exponent part? */
261
    int exp1 = 0;  /* exponent value */
262
    int neg1;  /* exponent sign */
263
    s++;  /* skip 'p' */
264
    neg1 = isneg(&s);  /* sign */
265
    if (!lisdigit(cast_uchar(*s)))
266
      return l_mathop(0.0);  /* invalid; must have at least one digit */
267
    while (lisdigit(cast_uchar(*s)))  /* read exponent */
268
      exp1 = exp1 * 10 + *(s++) - '0';
269
    if (neg1) exp1 = -exp1;
270
    e += exp1;
271
    *endptr = cast_charp(s);  /* valid up to here */
272
  }
273
  if (neg) r = -r;
274
  return l_mathop(ldexp)(r, e);
275
}
276
277
#endif
278
/* }====================================================== */
279
280
281
/* maximum length of a numeral to be converted to a number */
282
#if !defined (L_MAXLENNUM)
283
51.4k
#define L_MAXLENNUM 200
284
#endif
285
286
/*
287
** Convert string 's' to a Lua number (put in 'result'). Return NULL on
288
** fail or the address of the ending '\0' on success. ('mode' == 'x')
289
** means a hexadecimal numeral.
290
*/
291
21.0M
static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
292
21.0M
  char *endptr;
293
21.0M
  *result = (mode == 'x') ? lua_strx2number(s, &endptr)  /* try to convert */
294
21.0M
                          : lua_str2number(s, &endptr);
295
21.0M
  if (endptr == s) return NULL;  /* nothing recognized? */
296
3.74M
  while (lisspace(cast_uchar(*endptr))) endptr++;  /* skip trailing spaces */
297
3.74M
  return (*endptr == '\0') ? endptr : NULL;  /* OK iff no trailing chars */
298
21.0M
}
299
300
301
/*
302
** Convert string 's' to a Lua number (put in 'result') handling the
303
** current locale.
304
** This function accepts both the current locale or a dot as the radix
305
** mark. If the conversion fails, it may mean number has a dot but
306
** locale accepts something else. In that case, the code copies 's'
307
** to a buffer (because 's' is read-only), changes the dot to the
308
** current locale radix mark, and tries to convert again.
309
** The variable 'mode' checks for special characters in the string:
310
** - 'n' means 'inf' or 'nan' (which should be rejected)
311
** - 'x' means a hexadecimal numeral
312
** - '.' just optimizes the search for the common case (no special chars)
313
*/
314
96.1M
static const char *l_str2d (const char *s, lua_Number *result) {
315
96.1M
  const char *endptr;
316
96.1M
  const char *pmode = strpbrk(s, ".xXnN");  /* look for special chars */
317
96.1M
  int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
318
96.1M
  if (mode == 'n')  /* reject 'inf' and 'nan' */
319
75.2M
    return NULL;
320
20.9M
  endptr = l_str2dloc(s, result, mode);  /* try to convert */
321
20.9M
  if (endptr == NULL) {  /* failed? may be a different locale */
322
17.5M
    char buff[L_MAXLENNUM + 1];
323
17.5M
    const char *pdot = strchr(s, '.');
324
17.5M
    if (pdot == NULL || strlen(s) > L_MAXLENNUM)
325
17.5M
      return NULL;  /* string too long or no dot; fail */
326
46.5k
    strcpy(buff, s);  /* copy string to buffer */
327
46.5k
    buff[pdot - s] = lua_getlocaledecpoint();  /* correct decimal point */
328
46.5k
    endptr = l_str2dloc(buff, result, mode);  /* try again */
329
46.5k
    if (endptr != NULL)
330
0
      endptr = s + (endptr - buff);  /* make relative to 's' */
331
46.5k
  }
332
3.42M
  return endptr;
333
20.9M
}
334
335
336
58.0M
#define MAXBY10   cast(lua_Unsigned, LUA_MAXINTEGER / 10)
337
6.52k
#define MAXLASTD  cast_int(LUA_MAXINTEGER % 10)
338
339
112M
static const char *l_str2int (const char *s, lua_Integer *result) {
340
112M
  lua_Unsigned a = 0;
341
112M
  int empty = 1;
342
112M
  int neg;
343
112M
  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
344
112M
  neg = isneg(&s);
345
112M
  if (s[0] == '0' &&
346
112M
      (s[1] == 'x' || s[1] == 'X')) {  /* hex? */
347
91.5k
    s += 2;  /* skip '0x' */
348
2.80M
    for (; lisxdigit(cast_uchar(*s)); s++) {
349
2.80M
      a = a * 16 + luaO_hexavalue(*s);
350
2.80M
      empty = 0;
351
2.80M
    }
352
91.5k
  }
353
112M
  else {  /* decimal */
354
112M
    for (; lisdigit(cast_uchar(*s)); s++) {
355
57.8M
      int d = *s - '0';
356
57.8M
      if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg))  /* overflow? */
357
110k
        return NULL;  /* do not accept it (as integer) */
358
57.7M
      a = a * 10 + cast_uint(d);
359
57.7M
      empty = 0;
360
57.7M
    }
361
112M
  }
362
112M
  while (lisspace(cast_uchar(*s))) s++;  /* skip trailing spaces */
363
112M
  if (empty || *s != '\0') return NULL;  /* something wrong in the numeral */
364
15.9M
  else {
365
15.9M
    *result = l_castU2S((neg) ? 0u - a : a);
366
15.9M
    return s;
367
15.9M
  }
368
112M
}
369
370
371
112M
size_t luaO_str2num (const char *s, TValue *o) {
372
112M
  lua_Integer i; lua_Number n;
373
112M
  const char *e;
374
112M
  if ((e = l_str2int(s, &i)) != NULL) {  /* try as an integer */
375
15.9M
    setivalue(o, i);
376
15.9M
  }
377
96.1M
  else if ((e = l_str2d(s, &n)) != NULL) {  /* else try as a float */
378
3.38M
    setfltvalue(o, n);
379
3.38M
  }
380
92.8M
  else
381
92.8M
    return 0;  /* conversion failed */
382
19.3M
  return ct_diff2sz(e - s) + 1;  /* success; return string size */
383
112M
}
384
385
386
83.5k
int luaO_utf8esc (char *buff, l_uint32 x) {
387
83.5k
  int n = 1;  /* number of bytes put in buffer (backwards) */
388
83.5k
  lua_assert(x <= 0x7FFFFFFFu);
389
83.5k
  if (x < 0x80)  /* ASCII? */
390
12.3k
    buff[UTF8BUFFSZ - 1] = cast_char(x);
391
71.1k
  else {  /* need continuation bytes */
392
71.1k
    unsigned int mfb = 0x3f;  /* maximum that fits in first byte */
393
86.4k
    do {  /* add continuation bytes */
394
86.4k
      buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
395
86.4k
      x >>= 6;  /* remove added bits */
396
86.4k
      mfb >>= 1;  /* now there is one less bit available in first byte */
397
86.4k
    } while (x > mfb);  /* still needs continuation byte? */
398
71.1k
    buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x);  /* add first byte */
399
71.1k
  }
400
83.5k
  return n;
401
83.5k
}
402
403
404
/*
405
** The size of the buffer for the conversion of a number to a string
406
** 'LUA_N2SBUFFSZ' must be enough to accommodate both LUA_INTEGER_FMT
407
** and LUA_NUMBER_FMT.  For a long long int, this is 19 digits plus a
408
** sign and a final '\0', adding to 21. For a long double, it can go to
409
** a sign, the dot, an exponent letter, an exponent sign, 4 exponent
410
** digits, the final '\0', plus the significant digits, which are
411
** approximately the *_DIG attribute.
412
*/
413
#if LUA_N2SBUFFSZ < (20 + l_floatatt(DIG))
414
#error "invalid value for LUA_N2SBUFFSZ"
415
#endif
416
417
418
/*
419
** Convert a float to a string, adding it to a buffer. First try with
420
** a not too large number of digits, to avoid noise (for instance,
421
** 1.1 going to "1.1000000000000001"). If that lose precision, so
422
** that reading the result back gives a different number, then do the
423
** conversion again with extra precision. Moreover, if the numeral looks
424
** like an integer (without a decimal point or an exponent), add ".0" to
425
** its end.
426
*/
427
13.6M
static int tostringbuffFloat (lua_Number n, char *buff) {
428
  /* first conversion */
429
13.6M
  int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT,
430
13.6M
                            (LUAI_UACNUMBER)n);
431
13.6M
  lua_Number check = lua_str2number(buff, NULL);  /* read it back */
432
13.6M
  if (check != n) {  /* not enough precision? */
433
    /* convert again with more precision */
434
2.94M
    len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N,
435
2.94M
                          (LUAI_UACNUMBER)n);
436
2.94M
  }
437
  /* looks like an integer? */
438
13.6M
  if (buff[strspn(buff, "-0123456789")] == '\0') {
439
5.79M
    buff[len++] = lua_getlocaledecpoint();
440
5.79M
    buff[len++] = '0';  /* adds '.0' to result */
441
5.79M
  }
442
13.6M
  return len;
443
13.6M
}
444
445
446
/*
447
** Convert a number object to a string, adding it to a buffer.
448
*/
449
44.9M
unsigned luaO_tostringbuff (const TValue *obj, char *buff) {
450
44.9M
  int len;
451
44.9M
  lua_assert(ttisnumber(obj));
452
44.9M
  if (ttisinteger(obj))
453
31.3M
    len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj));
454
13.6M
  else
455
13.6M
    len = tostringbuffFloat(fltvalue(obj), buff);
456
44.9M
  lua_assert(len < LUA_N2SBUFFSZ);
457
44.9M
  return cast_uint(len);
458
44.9M
}
459
460
461
/*
462
** Convert a number object to a Lua string, replacing the value at 'obj'
463
*/
464
11.8M
void luaO_tostring (lua_State *L, TValue *obj) {
465
11.8M
  char buff[LUA_N2SBUFFSZ];
466
11.8M
  unsigned len = luaO_tostringbuff(obj, buff);
467
11.8M
  setsvalue(L, obj, luaS_newlstr(L, buff, len));
468
11.8M
}
469
470
471
472
473
/*
474
** {==================================================================
475
** 'luaO_pushvfstring'
476
** ===================================================================
477
*/
478
479
/*
480
** Size for buffer space used by 'luaO_pushvfstring'. It should be
481
** (LUA_IDSIZE + LUA_N2SBUFFSZ) + a minimal space for basic messages,
482
** so that 'luaG_addinfo' can work directly on the static buffer.
483
*/
484
#define BUFVFS    cast_uint(LUA_IDSIZE + LUA_N2SBUFFSZ + 95)
485
486
/*
487
** Buffer used by 'luaO_pushvfstring'. 'err' signals an error while
488
** building result (memory error [1] or buffer overflow [2]).
489
*/
490
typedef struct BuffFS {
491
  lua_State *L;
492
  char *b;
493
  size_t buffsize;
494
  size_t blen;  /* length of string in 'buff' */
495
  int err;
496
  char space[BUFVFS];  /* initial buffer */
497
} BuffFS;
498
499
500
27.6M
static void initbuff (lua_State *L, BuffFS *buff) {
501
27.6M
  buff->L = L;
502
27.6M
  buff->b = buff->space;
503
27.6M
  buff->buffsize = sizeof(buff->space);
504
27.6M
  buff->blen = 0;
505
27.6M
  buff->err = 0;
506
27.6M
}
507
508
509
/*
510
** Push final result from 'luaO_pushvfstring'. This function may raise
511
** errors explicitly or through memory errors, so it must run protected.
512
*/
513
27.6M
static void pushbuff (lua_State *L, void *ud) {
514
27.6M
  BuffFS *buff = cast(BuffFS*, ud);
515
27.6M
  switch (buff->err) {
516
0
    case 1:  /* memory error */
517
0
      luaD_throw(L, LUA_ERRMEM);
518
0
      break;
519
0
    case 2:  /* length overflow: Add "..." at the end of result */
520
0
      if (buff->buffsize - buff->blen < 3)
521
0
        strcpy(buff->b + buff->blen - 3, "...");  /* 'blen' must be > 3 */
522
0
      else {  /* there is enough space left for the "..." */
523
0
        strcpy(buff->b + buff->blen, "...");
524
0
        buff->blen += 3;
525
0
      }
526
      /* FALLTHROUGH */
527
27.6M
    default: {  /* no errors, but it can raise one creating the new string */
528
27.6M
      TString *ts = luaS_newlstr(L, buff->b, buff->blen);
529
27.6M
      setsvalue2s(L, L->top.p, ts);
530
27.6M
      L->top.p++;
531
27.6M
    }
532
27.6M
  }
533
27.6M
}
534
535
536
27.6M
static const char *clearbuff (BuffFS *buff) {
537
27.6M
  lua_State *L = buff->L;
538
27.6M
  const char *res;
539
27.6M
  if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK)  /* errors? */
540
0
    res = NULL;  /* error message is on the top of the stack */
541
27.6M
  else
542
27.6M
    res = getstr(tsvalue(s2v(L->top.p - 1)));
543
27.6M
  if (buff->b != buff->space)  /* using dynamic buffer? */
544
572k
    luaM_freearray(L, buff->b, buff->buffsize);  /* free it */
545
27.6M
  return res;
546
27.6M
}
547
548
549
139M
static void addstr2buff (BuffFS *buff, const char *str, size_t slen) {
550
139M
  size_t left = buff->buffsize - buff->blen;  /* space left in the buffer */
551
139M
  if (buff->err)  /* do nothing else after an error */
552
0
    return;
553
139M
  if (slen > left) {  /* new string doesn't fit into current buffer? */
554
616k
    if (slen > ((MAX_SIZE/2) - buff->blen)) {  /* overflow? */
555
0
      memcpy(buff->b + buff->blen, str, left);  /* copy what it can */
556
0
      buff->blen = buff->buffsize;
557
0
      buff->err = 2;  /* doesn't add anything else */
558
0
      return;
559
0
    }
560
616k
    else {
561
616k
      size_t newsize = buff->buffsize + slen;  /* limited to MAX_SIZE/2 */
562
616k
      char *newb =
563
616k
        (buff->b == buff->space)  /* still using static space? */
564
616k
        ? luaM_reallocvector(buff->L, NULL, 0, newsize, char)
565
616k
        : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize,
566
616k
                                                               char);
567
616k
      if (newb == NULL) {  /* allocation error? */
568
0
        buff->err = 1;  /* signal a memory error */
569
0
        return;
570
0
      }
571
616k
      if (buff->b == buff->space)  /* new buffer (not reallocated)? */
572
572k
        memcpy(newb, buff->b, buff->blen);  /* copy previous content */
573
616k
      buff->b = newb;  /* set new (larger) buffer... */
574
616k
      buff->buffsize = newsize;  /* ...and its new size */
575
616k
    }
576
616k
  }
577
139M
  memcpy(buff->b + buff->blen, str, slen);  /* copy new content */
578
139M
  buff->blen += slen;
579
139M
}
580
581
582
/*
583
** Add a numeral to the buffer.
584
*/
585
10.1M
static void addnum2buff (BuffFS *buff, TValue *num) {
586
10.1M
  char numbuff[LUA_N2SBUFFSZ];
587
10.1M
  unsigned len = luaO_tostringbuff(num, numbuff);
588
10.1M
  addstr2buff(buff, numbuff, len);
589
10.1M
}
590
591
592
/*
593
** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'
594
   conventional formats, plus Lua-specific '%I' and '%U'
595
*/
596
27.6M
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
597
27.6M
  BuffFS buff;  /* holds last part of the result */
598
27.6M
  const char *e;  /* points to next '%' */
599
27.6M
  initbuff(L, &buff);
600
83.3M
  while ((e = strchr(fmt, '%')) != NULL) {
601
55.7M
    addstr2buff(&buff, fmt, ct_diff2sz(e - fmt));  /* add 'fmt' up to '%' */
602
55.7M
    switch (*(e + 1)) {  /* conversion specifier */
603
43.2M
      case 's': {  /* zero-terminated string */
604
43.2M
        const char *s = va_arg(argp, char *);
605
43.2M
        if (s == NULL) s = "(null)";
606
43.2M
        addstr2buff(&buff, s, strlen(s));
607
43.2M
        break;
608
0
      }
609
992k
      case 'c': {  /* an 'int' as a character */
610
992k
        char c = cast_char(va_arg(argp, int));
611
992k
        addstr2buff(&buff, &c, sizeof(char));
612
992k
        break;
613
0
      }
614
10.1M
      case 'd': {  /* an 'int' */
615
10.1M
        TValue num;
616
10.1M
        setivalue(&num, va_arg(argp, int));
617
10.1M
        addnum2buff(&buff, &num);
618
10.1M
        break;
619
0
      }
620
1
      case 'I': {  /* a 'lua_Integer' */
621
1
        TValue num;
622
1
        setivalue(&num, cast_Integer(va_arg(argp, l_uacInt)));
623
1
        addnum2buff(&buff, &num);
624
1
        break;
625
0
      }
626
14
      case 'f': {  /* a 'lua_Number' */
627
14
        TValue num;
628
14
        setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
629
14
        addnum2buff(&buff, &num);
630
14
        break;
631
0
      }
632
1.27M
      case 'p': {  /* a pointer */
633
1.27M
        char bf[LUA_N2SBUFFSZ];  /* enough space for '%p' */
634
1.27M
        void *p = va_arg(argp, void *);
635
1.27M
        int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p);
636
1.27M
        addstr2buff(&buff, bf, cast_uint(len));
637
1.27M
        break;
638
0
      }
639
819
      case 'U': {  /* an 'unsigned long' as a UTF-8 sequence */
640
819
        char bf[UTF8BUFFSZ];
641
819
        unsigned long arg = va_arg(argp, unsigned long);
642
819
        int len = luaO_utf8esc(bf, cast(l_uint32, arg));
643
819
        addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len));
644
819
        break;
645
0
      }
646
68.8k
      case '%': {
647
68.8k
        addstr2buff(&buff, "%", 1);
648
68.8k
        break;
649
0
      }
650
0
      default: {
651
0
        addstr2buff(&buff, e, 2);  /* keep unknown format in the result */
652
0
        break;
653
0
      }
654
55.7M
    }
655
55.7M
    fmt = e + 2;  /* skip '%' and the specifier */
656
55.7M
  }
657
27.6M
  addstr2buff(&buff, fmt, strlen(fmt));  /* rest of 'fmt' */
658
27.6M
  return clearbuff(&buff);  /* empty buffer into a new string */
659
27.6M
}
660
661
662
17.8M
const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
663
17.8M
  const char *msg;
664
17.8M
  va_list argp;
665
17.8M
  va_start(argp, fmt);
666
17.8M
  msg = luaO_pushvfstring(L, fmt, argp);
667
17.8M
  va_end(argp);
668
17.8M
  if (msg == NULL)  /* error? */
669
0
    luaD_throw(L, LUA_ERRMEM);
670
17.8M
  return msg;
671
17.8M
}
672
673
/* }================================================================== */
674
675
676
#define RETS  "..."
677
#define PRE "[string \""
678
13.4M
#define POS "\"]"
679
680
34.4M
#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
681
682
16.7M
void luaO_chunkid (char *out, const char *source, size_t srclen) {
683
16.7M
  size_t bufflen = LUA_IDSIZE;  /* free space in buffer */
684
16.7M
  if (*source == '=') {  /* 'literal' source */
685
3.31M
    if (srclen <= bufflen)  /* small enough? */
686
3.31M
      memcpy(out, source + 1, srclen * sizeof(char));
687
5.76k
    else {  /* truncate it */
688
5.76k
      addstr(out, source + 1, bufflen - 1);
689
5.76k
      *out = '\0';
690
5.76k
    }
691
3.31M
  }
692
13.4M
  else if (*source == '@') {  /* file name */
693
10.7k
    if (srclen <= bufflen)  /* small enough? */
694
8.29k
      memcpy(out, source + 1, srclen * sizeof(char));
695
2.48k
    else {  /* add '...' before rest of name */
696
2.48k
      addstr(out, RETS, LL(RETS));
697
2.48k
      bufflen -= LL(RETS);
698
2.48k
      memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
699
2.48k
    }
700
10.7k
  }
701
13.4M
  else {  /* string; format as [string "source"] */
702
13.4M
    const char *nl = strchr(source, '\n');  /* find first new line (if any) */
703
13.4M
    addstr(out, PRE, LL(PRE));  /* add prefix */
704
13.4M
    bufflen -= LL(PRE RETS POS) + 1;  /* save space for prefix+suffix+'\0' */
705
13.4M
    if (srclen < bufflen && nl == NULL) {  /* small one-line source? */
706
5.87M
      addstr(out, source, srclen);  /* keep it */
707
5.87M
    }
708
7.54M
    else {
709
7.54M
      if (nl != NULL)
710
6.47M
        srclen = ct_diff2sz(nl - source);  /* stop at first newline */
711
7.54M
      if (srclen > bufflen) srclen = bufflen;
712
7.54M
      addstr(out, source, srclen);
713
7.54M
      addstr(out, RETS, LL(RETS));
714
7.54M
    }
715
13.4M
    memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
716
13.4M
  }
717
16.7M
}
718