Coverage Report

Created: 2025-08-28 06:30

/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
39.6M
lu_byte luaO_ceillog2 (unsigned int x) {
38
39.6M
  static const lu_byte log_2[256] = {  /* log_2[i - 1] = ceil(log2(i)) */
39
39.6M
    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
39.6M
    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
39.6M
    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
39.6M
    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
39.6M
    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
39.6M
    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
39.6M
    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
39.6M
    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
39.6M
  };
48
39.6M
  int l = 0;
49
39.6M
  x--;
50
42.0M
  while (x >= 256) { l += 8; x >>= 8; }
51
39.6M
  return cast_byte(l + log_2[x]);
52
39.6M
}
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
348k
lu_byte luaO_codeparam (unsigned int p) {
63
348k
  if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u)  /* overflow? */
64
0
    return 0xFF;  /* return maximum value */
65
348k
  else {
66
348k
    p = (cast(l_uint32, p) * 128 + 99) / 100;  /* round up the division */
67
348k
    if (p < 0x10) {  /* subnormal number? */
68
      /* exponent bits are already zero; nothing else to do */
69
0
      return cast_byte(p);
70
0
    }
71
348k
    else {  /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */
72
      /* preserve 5 bits in 'p' */
73
348k
      unsigned log = luaO_ceillog2(p + 1) - 5u;
74
348k
      return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4));
75
348k
    }
76
348k
  }
77
348k
}
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
3.64M
l_mem luaO_applyparam (lu_byte p, l_mem x) {
90
3.64M
  int m = p & 0xF;  /* mantissa */
91
3.64M
  int e = (p >> 4);  /* exponent */
92
3.64M
  if (e > 0) {  /* normalized? */
93
3.64M
    e--;  /* correct exponent */
94
3.64M
    m += 0x10;  /* correct mantissa; maximum value is 0x1F */
95
3.64M
  }
96
3.64M
  e -= 7;  /* correct excess-7 */
97
3.64M
  if (e >= 0) {
98
863k
    if (x < (MAX_LMEM / 0x1F) >> e)  /* no overflow? */
99
863k
      return (x * m) << e;  /* order doesn't matter here */
100
0
    else  /* real overflow */
101
0
      return MAX_LMEM;
102
863k
  }
103
2.78M
  else {  /* negative exponent */
104
2.78M
    e = -e;
105
2.78M
    if (x < MAX_LMEM / 0x1F)  /* multiplication cannot overflow? */
106
2.78M
      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
2.78M
  }
112
3.64M
}
113
114
115
static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
116
3.31M
                                                   lua_Integer v2) {
117
3.31M
  switch (op) {
118
149k
    case LUA_OPADD: return intop(+, v1, v2);
119
740k
    case LUA_OPSUB:return intop(-, v1, v2);
120
57.9k
    case LUA_OPMUL:return intop(*, v1, v2);
121
306k
    case LUA_OPMOD: return luaV_mod(L, v1, v2);
122
289k
    case LUA_OPIDIV: return luaV_idiv(L, v1, v2);
123
10.6k
    case LUA_OPBAND: return intop(&, v1, v2);
124
5.52k
    case LUA_OPBOR: return intop(|, v1, v2);
125
71.4k
    case LUA_OPBXOR: return intop(^, v1, v2);
126
16.9k
    case LUA_OPSHL: return luaV_shiftl(v1, v2);
127
155k
    case LUA_OPSHR: return luaV_shiftr(v1, v2);
128
368k
    case LUA_OPUNM: return intop(-, 0, v1);
129
1.14M
    case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
130
0
    default: lua_assert(0); return 0;
131
3.31M
  }
132
3.31M
}
133
134
135
static lua_Number numarith (lua_State *L, int op, lua_Number v1,
136
3.90M
                                                  lua_Number v2) {
137
3.90M
  switch (op) {
138
38.7k
    case LUA_OPADD: return luai_numadd(L, v1, v2);
139
353k
    case LUA_OPSUB: return luai_numsub(L, v1, v2);
140
213k
    case LUA_OPMUL: return luai_nummul(L, v1, v2);
141
384k
    case LUA_OPDIV: return luai_numdiv(L, v1, v2);
142
2.29M
    case LUA_OPPOW: return luai_numpow(L, v1, v2);
143
30.9k
    case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
144
538k
    case LUA_OPUNM: return luai_numunm(L, v1);
145
49.6k
    case LUA_OPMOD: return luaV_modf(L, v1, v2);
146
0
    default: lua_assert(0); return 0;
147
3.90M
  }
148
3.90M
}
149
150
151
int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2,
152
7.22M
                   TValue *res) {
153
7.22M
  switch (op) {
154
87.6k
    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
155
260k
    case LUA_OPSHL: case LUA_OPSHR:
156
1.40M
    case LUA_OPBNOT: {  /* operate only on integers */
157
1.40M
      lua_Integer i1; lua_Integer i2;
158
1.40M
      if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {
159
1.40M
        setivalue(res, intarith(L, op, i1, i2));
160
1.40M
        return 1;
161
1.40M
      }
162
0
      else return 0;  /* fail */
163
1.40M
    }
164
2.68M
    case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */
165
2.68M
      lua_Number n1; lua_Number n2;
166
2.68M
      if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
167
2.68M
        setfltvalue(res, numarith(L, op, n1, n2));
168
2.68M
        return 1;
169
2.68M
      }
170
0
      else return 0;  /* fail */
171
2.68M
    }
172
3.13M
    default: {  /* other operations */
173
3.13M
      lua_Number n1; lua_Number n2;
174
3.13M
      if (ttisinteger(p1) && ttisinteger(p2)) {
175
1.91M
        setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
176
1.91M
        return 1;
177
1.91M
      }
178
1.22M
      else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
179
1.22M
        setfltvalue(res, numarith(L, op, n1, n2));
180
1.22M
        return 1;
181
1.22M
      }
182
0
      else return 0;  /* fail */
183
3.13M
    }
184
7.22M
  }
185
7.22M
}
186
187
188
void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
189
1.04M
                 StkId res) {
190
1.04M
  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
1.04M
}
195
196
197
3.42M
lu_byte luaO_hexavalue (int c) {
198
3.42M
  lua_assert(lisxdigit(c));
199
3.42M
  if (lisdigit(c)) return cast_byte(c - '0');
200
3.42M
  else return cast_byte((ltolower(c) - 'a') + 10);
201
3.42M
}
202
203
204
91.7M
static int isneg (const char **s) {
205
91.7M
  if (**s == '-') { (*s)++; return 1; }
206
91.4M
  else if (**s == '+') (*s)++;
207
91.4M
  return 0;
208
91.7M
}
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
54.6k
#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
18.3M
static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
292
18.3M
  char *endptr;
293
18.3M
  *result = (mode == 'x') ? lua_strx2number(s, &endptr)  /* try to convert */
294
18.3M
                          : lua_str2number(s, &endptr);
295
18.3M
  if (endptr == s) return NULL;  /* nothing recognized? */
296
3.38M
  while (lisspace(cast_uchar(*endptr))) endptr++;  /* skip trailing spaces */
297
3.38M
  return (*endptr == '\0') ? endptr : NULL;  /* OK iff no trailing chars */
298
18.3M
}
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
76.5M
static const char *l_str2d (const char *s, lua_Number *result) {
315
76.5M
  const char *endptr;
316
76.5M
  const char *pmode = strpbrk(s, ".xXnN");  /* look for special chars */
317
76.5M
  int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
318
76.5M
  if (mode == 'n')  /* reject 'inf' and 'nan' */
319
58.2M
    return NULL;
320
18.3M
  endptr = l_str2dloc(s, result, mode);  /* try to convert */
321
18.3M
  if (endptr == NULL) {  /* failed? may be a different locale */
322
15.2M
    char buff[L_MAXLENNUM + 1];
323
15.2M
    const char *pdot = strchr(s, '.');
324
15.2M
    if (pdot == NULL || strlen(s) > L_MAXLENNUM)
325
15.2M
      return NULL;  /* string too long or no dot; fail */
326
46.4k
    strcpy(buff, s);  /* copy string to buffer */
327
46.4k
    buff[pdot - s] = lua_getlocaledecpoint();  /* correct decimal point */
328
46.4k
    endptr = l_str2dloc(buff, result, mode);  /* try again */
329
46.4k
    if (endptr != NULL)
330
0
      endptr = s + (endptr - buff);  /* make relative to 's' */
331
46.4k
  }
332
3.07M
  return endptr;
333
18.3M
}
334
335
336
57.1M
#define MAXBY10   cast(lua_Unsigned, LUA_MAXINTEGER / 10)
337
8.50k
#define MAXLASTD  cast_int(LUA_MAXINTEGER % 10)
338
339
91.7M
static const char *l_str2int (const char *s, lua_Integer *result) {
340
91.7M
  lua_Unsigned a = 0;
341
91.7M
  int empty = 1;
342
91.7M
  int neg;
343
91.7M
  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
344
91.7M
  neg = isneg(&s);
345
91.7M
  if (s[0] == '0' &&
346
91.7M
      (s[1] == 'x' || s[1] == 'X')) {  /* hex? */
347
89.6k
    s += 2;  /* skip '0x' */
348
2.71M
    for (; lisxdigit(cast_uchar(*s)); s++) {
349
2.71M
      a = a * 16 + luaO_hexavalue(*s);
350
2.71M
      empty = 0;
351
2.71M
    }
352
89.6k
  }
353
91.6M
  else {  /* decimal */
354
91.6M
    for (; lisdigit(cast_uchar(*s)); s++) {
355
57.0M
      int d = *s - '0';
356
57.0M
      if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg))  /* overflow? */
357
111k
        return NULL;  /* do not accept it (as integer) */
358
56.9M
      a = a * 10 + cast_uint(d);
359
56.9M
      empty = 0;
360
56.9M
    }
361
91.6M
  }
362
91.6M
  while (lisspace(cast_uchar(*s))) s++;  /* skip trailing spaces */
363
91.6M
  if (empty || *s != '\0') return NULL;  /* something wrong in the numeral */
364
15.2M
  else {
365
15.2M
    *result = l_castU2S((neg) ? 0u - a : a);
366
15.2M
    return s;
367
15.2M
  }
368
91.6M
}
369
370
371
91.7M
size_t luaO_str2num (const char *s, TValue *o) {
372
91.7M
  lua_Integer i; lua_Number n;
373
91.7M
  const char *e;
374
91.7M
  if ((e = l_str2int(s, &i)) != NULL) {  /* try as an integer */
375
15.2M
    setivalue(o, i);
376
15.2M
  }
377
76.5M
  else if ((e = l_str2d(s, &n)) != NULL) {  /* else try as a float */
378
3.03M
    setfltvalue(o, n);
379
3.03M
  }
380
73.5M
  else
381
73.5M
    return 0;  /* conversion failed */
382
18.2M
  return ct_diff2sz(e - s) + 1;  /* success; return string size */
383
91.7M
}
384
385
386
84.0k
int luaO_utf8esc (char *buff, l_uint32 x) {
387
84.0k
  int n = 1;  /* number of bytes put in buffer (backwards) */
388
84.0k
  lua_assert(x <= 0x7FFFFFFFu);
389
84.0k
  if (x < 0x80)  /* ASCII? */
390
11.1k
    buff[UTF8BUFFSZ - 1] = cast_char(x);
391
72.8k
  else {  /* need continuation bytes */
392
72.8k
    unsigned int mfb = 0x3f;  /* maximum that fits in first byte */
393
91.6k
    do {  /* add continuation bytes */
394
91.6k
      buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
395
91.6k
      x >>= 6;  /* remove added bits */
396
91.6k
      mfb >>= 1;  /* now there is one less bit available in first byte */
397
91.6k
    } while (x > mfb);  /* still needs continuation byte? */
398
72.8k
    buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x);  /* add first byte */
399
72.8k
  }
400
84.0k
  return n;
401
84.0k
}
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
12.6M
static int tostringbuffFloat (lua_Number n, char *buff) {
428
  /* first conversion */
429
12.6M
  int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT,
430
12.6M
                            (LUAI_UACNUMBER)n);
431
12.6M
  lua_Number check = lua_str2number(buff, NULL);  /* read it back */
432
12.6M
  if (check != n) {  /* not enough precision? */
433
    /* convert again with more precision */
434
2.54M
    len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N,
435
2.54M
                          (LUAI_UACNUMBER)n);
436
2.54M
  }
437
  /* looks like an integer? */
438
12.6M
  if (buff[strspn(buff, "-0123456789")] == '\0') {
439
5.85M
    buff[len++] = lua_getlocaledecpoint();
440
5.85M
    buff[len++] = '0';  /* adds '.0' to result */
441
5.85M
  }
442
12.6M
  return len;
443
12.6M
}
444
445
446
/*
447
** Convert a number object to a string, adding it to a buffer.
448
*/
449
39.8M
unsigned luaO_tostringbuff (const TValue *obj, char *buff) {
450
39.8M
  int len;
451
39.8M
  lua_assert(ttisnumber(obj));
452
39.8M
  if (ttisinteger(obj))
453
27.1M
    len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj));
454
12.6M
  else
455
12.6M
    len = tostringbuffFloat(fltvalue(obj), buff);
456
39.8M
  lua_assert(len < LUA_N2SBUFFSZ);
457
39.8M
  return cast_uint(len);
458
39.8M
}
459
460
461
/*
462
** Convert a number object to a Lua string, replacing the value at 'obj'
463
*/
464
11.1M
void luaO_tostring (lua_State *L, TValue *obj) {
465
11.1M
  char buff[LUA_N2SBUFFSZ];
466
11.1M
  unsigned len = luaO_tostringbuff(obj, buff);
467
11.1M
  setsvalue(L, obj, luaS_newlstr(L, buff, len));
468
11.1M
}
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
24.0M
static void initbuff (lua_State *L, BuffFS *buff) {
501
24.0M
  buff->L = L;
502
24.0M
  buff->b = buff->space;
503
24.0M
  buff->buffsize = sizeof(buff->space);
504
24.0M
  buff->blen = 0;
505
24.0M
  buff->err = 0;
506
24.0M
}
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
24.0M
static void pushbuff (lua_State *L, void *ud) {
514
24.0M
  BuffFS *buff = cast(BuffFS*, ud);
515
24.0M
  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
24.0M
    default: {  /* no errors, but it can raise one creating the new string */
528
24.0M
      TString *ts = luaS_newlstr(L, buff->b, buff->blen);
529
24.0M
      setsvalue2s(L, L->top.p, ts);
530
24.0M
      L->top.p++;
531
24.0M
    }
532
24.0M
  }
533
24.0M
}
534
535
536
24.0M
static const char *clearbuff (BuffFS *buff) {
537
24.0M
  lua_State *L = buff->L;
538
24.0M
  const char *res;
539
24.0M
  if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK)  /* errors? */
540
0
    res = NULL;  /* error message is on the top of the stack */
541
24.0M
  else
542
24.0M
    res = getstr(tsvalue(s2v(L->top.p - 1)));
543
24.0M
  if (buff->b != buff->space)  /* using dynamic buffer? */
544
546k
    luaM_freearray(L, buff->b, buff->buffsize);  /* free it */
545
24.0M
  return res;
546
24.0M
}
547
548
549
121M
static void addstr2buff (BuffFS *buff, const char *str, size_t slen) {
550
121M
  size_t left = buff->buffsize - buff->blen;  /* space left in the buffer */
551
121M
  if (buff->err)  /* do nothing else after an error */
552
0
    return;
553
121M
  if (slen > left) {  /* new string doesn't fit into current buffer? */
554
580k
    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
580k
    else {
561
580k
      size_t newsize = buff->buffsize + slen;  /* limited to MAX_SIZE/2 */
562
580k
      char *newb =
563
580k
        (buff->b == buff->space)  /* still using static space? */
564
580k
        ? luaM_reallocvector(buff->L, NULL, 0, newsize, char)
565
580k
        : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize,
566
580k
                                                               char);
567
580k
      if (newb == NULL) {  /* allocation error? */
568
0
        buff->err = 1;  /* signal a memory error */
569
0
        return;
570
0
      }
571
580k
      if (buff->b == buff->space)  /* new buffer (not reallocated)? */
572
546k
        memcpy(newb, buff->b, buff->blen);  /* copy previous content */
573
580k
      buff->b = newb;  /* set new (larger) buffer... */
574
580k
      buff->buffsize = newsize;  /* ...and its new size */
575
580k
    }
576
580k
  }
577
121M
  memcpy(buff->b + buff->blen, str, slen);  /* copy new content */
578
121M
  buff->blen += slen;
579
121M
}
580
581
582
/*
583
** Add a numeral to the buffer.
584
*/
585
8.85M
static void addnum2buff (BuffFS *buff, TValue *num) {
586
8.85M
  char numbuff[LUA_N2SBUFFSZ];
587
8.85M
  unsigned len = luaO_tostringbuff(num, numbuff);
588
8.85M
  addstr2buff(buff, numbuff, len);
589
8.85M
}
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
24.0M
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
597
24.0M
  BuffFS buff;  /* holds last part of the result */
598
24.0M
  const char *e;  /* points to next '%' */
599
24.0M
  initbuff(L, &buff);
600
72.7M
  while ((e = strchr(fmt, '%')) != NULL) {
601
48.6M
    addstr2buff(&buff, fmt, ct_diff2sz(e - fmt));  /* add 'fmt' up to '%' */
602
48.6M
    switch (*(e + 1)) {  /* conversion specifier */
603
37.7M
      case 's': {  /* zero-terminated string */
604
37.7M
        const char *s = va_arg(argp, char *);
605
37.7M
        if (s == NULL) s = "(null)";
606
37.7M
        addstr2buff(&buff, s, strlen(s));
607
37.7M
        break;
608
0
      }
609
901k
      case 'c': {  /* an 'int' as a character */
610
901k
        char c = cast_char(va_arg(argp, int));
611
901k
        addstr2buff(&buff, &c, sizeof(char));
612
901k
        break;
613
0
      }
614
8.85M
      case 'd': {  /* an 'int' */
615
8.85M
        TValue num;
616
8.85M
        setivalue(&num, va_arg(argp, int));
617
8.85M
        addnum2buff(&buff, &num);
618
8.85M
        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
17
      case 'f': {  /* a 'lua_Number' */
627
17
        TValue num;
628
17
        setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
629
17
        addnum2buff(&buff, &num);
630
17
        break;
631
0
      }
632
1.11M
      case 'p': {  /* a pointer */
633
1.11M
        char bf[LUA_N2SBUFFSZ];  /* enough space for '%p' */
634
1.11M
        void *p = va_arg(argp, void *);
635
1.11M
        int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p);
636
1.11M
        addstr2buff(&buff, bf, cast_uint(len));
637
1.11M
        break;
638
0
      }
639
831
      case 'U': {  /* an 'unsigned long' as a UTF-8 sequence */
640
831
        char bf[UTF8BUFFSZ];
641
831
        unsigned long arg = va_arg(argp, unsigned long);
642
831
        int len = luaO_utf8esc(bf, cast(l_uint32, arg));
643
831
        addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len));
644
831
        break;
645
0
      }
646
26.8k
      case '%': {
647
26.8k
        addstr2buff(&buff, "%", 1);
648
26.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
48.6M
    }
655
48.6M
    fmt = e + 2;  /* skip '%' and the specifier */
656
48.6M
  }
657
24.0M
  addstr2buff(&buff, fmt, strlen(fmt));  /* rest of 'fmt' */
658
24.0M
  return clearbuff(&buff);  /* empty buffer into a new string */
659
24.0M
}
660
661
662
15.1M
const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
663
15.1M
  const char *msg;
664
15.1M
  va_list argp;
665
15.1M
  va_start(argp, fmt);
666
15.1M
  msg = luaO_pushvfstring(L, fmt, argp);
667
15.1M
  va_end(argp);
668
15.1M
  if (msg == NULL)  /* error? */
669
0
    luaD_throw(L, LUA_ERRMEM);
670
15.1M
  return msg;
671
15.1M
}
672
673
/* }================================================================== */
674
675
676
#define RETS  "..."
677
#define PRE "[string \""
678
11.7M
#define POS "\"]"
679
680
30.2M
#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
681
682
14.9M
void luaO_chunkid (char *out, const char *source, size_t srclen) {
683
14.9M
  size_t bufflen = LUA_IDSIZE;  /* free space in buffer */
684
14.9M
  if (*source == '=') {  /* 'literal' source */
685
3.14M
    if (srclen <= bufflen)  /* small enough? */
686
3.14M
      memcpy(out, source + 1, srclen * sizeof(char));
687
5.34k
    else {  /* truncate it */
688
5.34k
      addstr(out, source + 1, bufflen - 1);
689
5.34k
      *out = '\0';
690
5.34k
    }
691
3.14M
  }
692
11.8M
  else if (*source == '@') {  /* file name */
693
8.27k
    if (srclen <= bufflen)  /* small enough? */
694
6.30k
      memcpy(out, source + 1, srclen * sizeof(char));
695
1.97k
    else {  /* add '...' before rest of name */
696
1.97k
      addstr(out, RETS, LL(RETS));
697
1.97k
      bufflen -= LL(RETS);
698
1.97k
      memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
699
1.97k
    }
700
8.27k
  }
701
11.7M
  else {  /* string; format as [string "source"] */
702
11.7M
    const char *nl = strchr(source, '\n');  /* find first new line (if any) */
703
11.7M
    addstr(out, PRE, LL(PRE));  /* add prefix */
704
11.7M
    bufflen -= LL(PRE RETS POS) + 1;  /* save space for prefix+suffix+'\0' */
705
11.7M
    if (srclen < bufflen && nl == NULL) {  /* small one-line source? */
706
5.15M
      addstr(out, source, srclen);  /* keep it */
707
5.15M
    }
708
6.64M
    else {
709
6.64M
      if (nl != NULL)
710
5.67M
        srclen = ct_diff2sz(nl - source);  /* stop at first newline */
711
6.64M
      if (srclen > bufflen) srclen = bufflen;
712
6.64M
      addstr(out, source, srclen);
713
6.64M
      addstr(out, RETS, LL(RETS));
714
6.64M
    }
715
11.7M
    memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
716
11.7M
  }
717
14.9M
}
718