Coverage Report

Created: 2025-08-09 06:54

/src/testdir/build/lua-master/source/lstrlib.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
** $Id: lstrlib.c $
3
** Standard library for string operations and pattern-matching
4
** See Copyright Notice in lua.h
5
*/
6
7
#define lstrlib_c
8
#define LUA_LIB
9
10
#include "lprefix.h"
11
12
13
#include <ctype.h>
14
#include <float.h>
15
#include <limits.h>
16
#include <locale.h>
17
#include <math.h>
18
#include <stddef.h>
19
#include <stdio.h>
20
#include <stdlib.h>
21
#include <string.h>
22
23
#include "lua.h"
24
25
#include "lauxlib.h"
26
#include "lualib.h"
27
#include "llimits.h"
28
29
30
/*
31
** maximum number of captures that a pattern can do during
32
** pattern-matching. This limit is arbitrary, but must fit in
33
** an unsigned char.
34
*/
35
#if !defined(LUA_MAXCAPTURES)
36
101M
#define LUA_MAXCAPTURES   32
37
#endif
38
39
40
9.80k
static int str_len (lua_State *L) {
41
9.80k
  size_t l;
42
9.80k
  luaL_checklstring(L, 1, &l);
43
9.80k
  lua_pushinteger(L, (lua_Integer)l);
44
9.80k
  return 1;
45
9.80k
}
46
47
48
/*
49
** translate a relative initial string position
50
** (negative means back from end): clip result to [1, inf).
51
** The length of any string in Lua must fit in a lua_Integer,
52
** so there are no overflows in the casts.
53
** The inverted comparison avoids a possible overflow
54
** computing '-pos'.
55
*/
56
5.30M
static size_t posrelatI (lua_Integer pos, size_t len) {
57
5.30M
  if (pos > 0)
58
5.01M
    return (size_t)pos;
59
284k
  else if (pos == 0)
60
107k
    return 1;
61
177k
  else if (pos < -(lua_Integer)len)  /* inverted comparison */
62
9.81k
    return 1;  /* clip to 1 */
63
167k
  else return len + (size_t)pos + 1;
64
5.30M
}
65
66
67
/*
68
** Gets an optional ending string position from argument 'arg',
69
** with default value 'def'.
70
** Negative means back from end: clip result to [0, len]
71
*/
72
static size_t getendpos (lua_State *L, int arg, lua_Integer def,
73
4.50M
                         size_t len) {
74
4.50M
  lua_Integer pos = luaL_optinteger(L, arg, def);
75
4.50M
  if (pos > (lua_Integer)len)
76
1.79k
    return len;
77
4.50M
  else if (pos >= 0)
78
4.25M
    return (size_t)pos;
79
251k
  else if (pos < -(lua_Integer)len)
80
2.26k
    return 0;
81
249k
  else return len + (size_t)pos + 1;
82
4.50M
}
83
84
85
4.40M
static int str_sub (lua_State *L) {
86
4.40M
  size_t l;
87
4.40M
  const char *s = luaL_checklstring(L, 1, &l);
88
4.40M
  size_t start = posrelatI(luaL_checkinteger(L, 2), l);
89
4.40M
  size_t end = getendpos(L, 3, -1, l);
90
4.40M
  if (start <= end)
91
4.23M
    lua_pushlstring(L, s + start - 1, (end - start) + 1);
92
176k
  else lua_pushliteral(L, "");
93
4.40M
  return 1;
94
4.40M
}
95
96
97
127k
static int str_reverse (lua_State *L) {
98
127k
  size_t l, i;
99
127k
  luaL_Buffer b;
100
127k
  const char *s = luaL_checklstring(L, 1, &l);
101
127k
  char *p = luaL_buffinitsize(L, &b, l);
102
1.46G
  for (i = 0; i < l; i++)
103
1.46G
    p[i] = s[l - i - 1];
104
127k
  luaL_pushresultsize(&b, l);
105
127k
  return 1;
106
127k
}
107
108
109
2.32k
static int str_lower (lua_State *L) {
110
2.32k
  size_t l;
111
2.32k
  size_t i;
112
2.32k
  luaL_Buffer b;
113
2.32k
  const char *s = luaL_checklstring(L, 1, &l);
114
2.32k
  char *p = luaL_buffinitsize(L, &b, l);
115
85.0k
  for (i=0; i<l; i++)
116
82.7k
    p[i] = cast_char(tolower(cast_uchar(s[i])));
117
2.32k
  luaL_pushresultsize(&b, l);
118
2.32k
  return 1;
119
2.32k
}
120
121
122
1.25M
static int str_upper (lua_State *L) {
123
1.25M
  size_t l;
124
1.25M
  size_t i;
125
1.25M
  luaL_Buffer b;
126
1.25M
  const char *s = luaL_checklstring(L, 1, &l);
127
1.25M
  char *p = luaL_buffinitsize(L, &b, l);
128
7.01M
  for (i=0; i<l; i++)
129
5.76M
    p[i] = cast_char(toupper(cast_uchar(s[i])));
130
1.25M
  luaL_pushresultsize(&b, l);
131
1.25M
  return 1;
132
1.25M
}
133
134
135
/*
136
** MAX_SIZE is limited both by size_t and lua_Integer.
137
** When x <= MAX_SIZE, x can be safely cast to size_t or lua_Integer.
138
*/
139
166k
static int str_rep (lua_State *L) {
140
166k
  size_t len, lsep;
141
166k
  const char *s = luaL_checklstring(L, 1, &len);
142
166k
  lua_Integer n = luaL_checkinteger(L, 2);
143
166k
  const char *sep = luaL_optlstring(L, 3, "", &lsep);
144
166k
  if (n <= 0)
145
3.62k
    lua_pushliteral(L, "");
146
162k
  else if (l_unlikely(len > MAX_SIZE - lsep ||
147
162k
               cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))
148
705
    return luaL_error(L, "resulting string too large");
149
162k
  else {
150
162k
    size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;
151
162k
    luaL_Buffer b;
152
162k
    char *p = luaL_buffinitsize(L, &b, totallen);
153
128M
    while (n-- > 1) {  /* first n-1 copies (followed by separator) */
154
128M
      memcpy(p, s, len * sizeof(char)); p += len;
155
128M
      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
156
274k
        memcpy(p, sep, lsep * sizeof(char)); p += lsep;
157
274k
      }
158
128M
    }
159
162k
    memcpy(p, s, len * sizeof(char));  /* last copy without separator */
160
162k
    luaL_pushresultsize(&b, totallen);
161
162k
  }
162
165k
  return 1;
163
166k
}
164
165
166
118k
static int str_byte (lua_State *L) {
167
118k
  size_t l;
168
118k
  const char *s = luaL_checklstring(L, 1, &l);
169
118k
  lua_Integer pi = luaL_optinteger(L, 2, 1);
170
118k
  size_t posi = posrelatI(pi, l);
171
118k
  size_t pose = getendpos(L, 3, pi, l);
172
118k
  int n, i;
173
118k
  if (posi > pose) return 0;  /* empty interval; return no values */
174
117k
  if (l_unlikely(pose - posi >= (size_t)INT_MAX))  /* arithmetic overflow? */
175
0
    return luaL_error(L, "string slice too long");
176
117k
  n = (int)(pose -  posi) + 1;
177
117k
  luaL_checkstack(L, n, "string slice too long");
178
283k
  for (i=0; i<n; i++)
179
166k
    lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));
180
117k
  return n;
181
117k
}
182
183
184
33.3k
static int str_char (lua_State *L) {
185
33.3k
  int n = lua_gettop(L);  /* number of arguments */
186
33.3k
  int i;
187
33.3k
  luaL_Buffer b;
188
33.3k
  char *p = luaL_buffinitsize(L, &b, cast_uint(n));
189
131k
  for (i=1; i<=n; i++) {
190
98.0k
    lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
191
98.0k
    luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
192
98.0k
    p[i - 1] = cast_char(cast_uchar(c));
193
98.0k
  }
194
33.3k
  luaL_pushresultsize(&b, cast_uint(n));
195
33.3k
  return 1;
196
33.3k
}
197
198
199
/*
200
** Buffer to store the result of 'string.dump'. It must be initialized
201
** after the call to 'lua_dump', to ensure that the function is on the
202
** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might
203
** push stuff.)
204
*/
205
struct str_Writer {
206
  int init;  /* true iff buffer has been initialized */
207
  luaL_Buffer B;
208
};
209
210
211
1.53M
static int writer (lua_State *L, const void *b, size_t size, void *ud) {
212
1.53M
  struct str_Writer *state = (struct str_Writer *)ud;
213
1.53M
  if (!state->init) {
214
7.38k
    state->init = 1;
215
7.38k
    luaL_buffinit(L, &state->B);
216
7.38k
  }
217
1.53M
  if (b == NULL) {  /* finishing dump? */
218
7.38k
    luaL_pushresult(&state->B);  /* push result */
219
7.38k
    lua_replace(L, 1);  /* move it to reserved slot */
220
7.38k
  }
221
1.52M
  else
222
1.52M
    luaL_addlstring(&state->B, (const char *)b, size);
223
1.53M
  return 0;
224
1.53M
}
225
226
227
7.64k
static int str_dump (lua_State *L) {
228
7.64k
  struct str_Writer state;
229
7.64k
  int strip = lua_toboolean(L, 2);
230
7.64k
  luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
231
7.64k
                   1, "Lua function expected");
232
  /* ensure function is on the top of the stack and vacate slot 1 */
233
7.64k
  lua_pushvalue(L, 1);
234
7.64k
  state.init = 0;
235
7.64k
  lua_dump(L, writer, &state, strip);
236
7.64k
  lua_settop(L, 1);  /* leave final result on top */
237
7.64k
  return 1;
238
7.64k
}
239
240
241
242
/*
243
** {======================================================
244
** METAMETHODS
245
** =======================================================
246
*/
247
248
#if defined(LUA_NOCVTS2N) /* { */
249
250
/* no coercion from strings to numbers */
251
252
static const luaL_Reg stringmetamethods[] = {
253
  {"__index", NULL},  /* placeholder */
254
  {NULL, NULL}
255
};
256
257
#else   /* }{ */
258
259
980k
static int tonum (lua_State *L, int arg) {
260
980k
  if (lua_type(L, arg) == LUA_TNUMBER) {  /* already a number? */
261
402k
    lua_pushvalue(L, arg);
262
402k
    return 1;
263
402k
  }
264
578k
  else {  /* check whether it is a numerical string */
265
578k
    size_t len;
266
578k
    const char *s = lua_tolstring(L, arg, &len);
267
578k
    return (s != NULL && lua_stringtonumber(L, s) == len + 1);
268
578k
  }
269
980k
}
270
271
272
11.5k
static void trymt (lua_State *L, const char *mtname) {
273
11.5k
  lua_settop(L, 2);  /* back to the original arguments */
274
11.5k
  if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
275
11.5k
                 !luaL_getmetafield(L, 2, mtname)))
276
11.5k
    luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
277
11.5k
                  luaL_typename(L, -2), luaL_typename(L, -1));
278
11.5k
  lua_insert(L, -3);  /* put metamethod before arguments */
279
11.5k
  lua_call(L, 2, 1);  /* call metamethod */
280
11.5k
}
281
282
283
493k
static int arith (lua_State *L, int op, const char *mtname) {
284
493k
  if (tonum(L, 1) && tonum(L, 2))
285
482k
    lua_arith(L, op);  /* result will be on the top */
286
11.5k
  else
287
11.5k
    trymt(L, mtname);
288
493k
  return 1;
289
493k
}
290
291
292
174k
static int arith_add (lua_State *L) {
293
174k
  return arith(L, LUA_OPADD, "__add");
294
174k
}
295
296
111k
static int arith_sub (lua_State *L) {
297
111k
  return arith(L, LUA_OPSUB, "__sub");
298
111k
}
299
300
91.6k
static int arith_mul (lua_State *L) {
301
91.6k
  return arith(L, LUA_OPMUL, "__mul");
302
91.6k
}
303
304
76.6k
static int arith_mod (lua_State *L) {
305
76.6k
  return arith(L, LUA_OPMOD, "__mod");
306
76.6k
}
307
308
3.87k
static int arith_pow (lua_State *L) {
309
3.87k
  return arith(L, LUA_OPPOW, "__pow");
310
3.87k
}
311
312
9.31k
static int arith_div (lua_State *L) {
313
9.31k
  return arith(L, LUA_OPDIV, "__div");
314
9.31k
}
315
316
4.20k
static int arith_idiv (lua_State *L) {
317
4.20k
  return arith(L, LUA_OPIDIV, "__idiv");
318
4.20k
}
319
320
21.8k
static int arith_unm (lua_State *L) {
321
21.8k
  return arith(L, LUA_OPUNM, "__unm");
322
21.8k
}
323
324
325
static const luaL_Reg stringmetamethods[] = {
326
  {"__add", arith_add},
327
  {"__sub", arith_sub},
328
  {"__mul", arith_mul},
329
  {"__mod", arith_mod},
330
  {"__pow", arith_pow},
331
  {"__div", arith_div},
332
  {"__idiv", arith_idiv},
333
  {"__unm", arith_unm},
334
  {"__index", NULL},  /* placeholder */
335
  {NULL, NULL}
336
};
337
338
#endif    /* } */
339
340
/* }====================================================== */
341
342
/*
343
** {======================================================
344
** PATTERN MATCHING
345
** =======================================================
346
*/
347
348
349
343M
#define CAP_UNFINISHED  (-1)
350
13.9M
#define CAP_POSITION  (-2)
351
352
353
typedef struct MatchState {
354
  const char *src_init;  /* init of source string */
355
  const char *src_end;  /* end ('\0') of source string */
356
  const char *p_end;  /* end ('\0') of pattern */
357
  lua_State *L;
358
  int matchdepth;  /* control for recursive depth (to avoid C stack overflow) */
359
  int level;  /* total number of captures (finished or unfinished) */
360
  struct {
361
    const char *init;
362
    ptrdiff_t len;  /* length or special value (CAP_*) */
363
  } capture[LUA_MAXCAPTURES];
364
} MatchState;
365
366
367
/* recursive function */
368
static const char *match (MatchState *ms, const char *s, const char *p);
369
370
371
/* maximum recursion depth for 'match' */
372
#if !defined(MAXCCALLS)
373
2.24M
#define MAXCCALLS 200
374
#endif
375
376
377
293M
#define L_ESC   '%'
378
382k
#define SPECIALS  "^$*+?.([%-"
379
380
381
84.4M
static int check_capture (MatchState *ms, int l) {
382
84.4M
  l -= '1';
383
84.4M
  if (l_unlikely(l < 0 || l >= ms->level ||
384
84.4M
                 ms->capture[l].len == CAP_UNFINISHED))
385
19.1k
    return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
386
84.4M
  return l;
387
84.4M
}
388
389
390
97.6M
static int capture_to_close (MatchState *ms) {
391
97.6M
  int level = ms->level;
392
154M
  for (level--; level>=0; level--)
393
154M
    if (ms->capture[level].len == CAP_UNFINISHED) return level;
394
2.89k
  return luaL_error(ms->L, "invalid pattern capture");
395
97.6M
}
396
397
398
204M
static const char *classend (MatchState *ms, const char *p) {
399
204M
  switch (*p++) {
400
15.3M
    case L_ESC: {
401
15.3M
      if (l_unlikely(p == ms->p_end))
402
662
        luaL_error(ms->L, "malformed pattern (ends with '%%')");
403
15.3M
      return p+1;
404
0
    }
405
4.88M
    case '[': {
406
4.88M
      if (*p == '^') p++;
407
50.2M
      do {  /* look for a ']' */
408
50.2M
        if (l_unlikely(p == ms->p_end))
409
12.8k
          luaL_error(ms->L, "malformed pattern (missing ']')");
410
50.2M
        if (*(p++) == L_ESC && p < ms->p_end)
411
5.05M
          p++;  /* skip escapes (e.g. '%]') */
412
50.2M
      } while (*p != ']');
413
4.88M
      return p+1;
414
0
    }
415
184M
    default: {
416
184M
      return p;
417
0
    }
418
204M
  }
419
204M
}
420
421
422
24.0M
static int match_class (int c, int cl) {
423
24.0M
  int res;
424
24.0M
  switch (tolower(cl)) {
425
933k
    case 'a' : res = isalpha(c); break;
426
351
    case 'c' : res = iscntrl(c); break;
427
10.2M
    case 'd' : res = isdigit(c); break;
428
8.04k
    case 'g' : res = isgraph(c); break;
429
127
    case 'l' : res = islower(c); break;
430
2
    case 'p' : res = ispunct(c); break;
431
7.12M
    case 's' : res = isspace(c); break;
432
31
    case 'u' : res = isupper(c); break;
433
59.3k
    case 'w' : res = isalnum(c); break;
434
3.54k
    case 'x' : res = isxdigit(c); break;
435
114k
    case 'z' : res = (c == 0); break;  /* deprecated option */
436
5.54M
    default: return (cl == c);
437
24.0M
  }
438
18.4M
  return (islower(cl) ? res : !res);
439
24.0M
}
440
441
442
6.69M
static int matchbracketclass (int c, const char *p, const char *ec) {
443
6.69M
  int sig = 1;
444
6.69M
  if (*(p+1) == '^') {
445
1.82M
    sig = 0;
446
1.82M
    p++;  /* skip the '^' */
447
1.82M
  }
448
34.2M
  while (++p < ec) {
449
28.0M
    if (*p == L_ESC) {
450
4.75M
      p++;
451
4.75M
      if (match_class(c, cast_uchar(*p)))
452
46.8k
        return sig;
453
4.75M
    }
454
23.2M
    else if ((*(p+1) == '-') && (p+2 < ec)) {
455
146k
      p+=2;
456
146k
      if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
457
13.6k
        return sig;
458
146k
    }
459
23.1M
    else if (cast_uchar(*p) == c) return sig;
460
28.0M
  }
461
6.18M
  return !sig;
462
6.69M
}
463
464
465
static int singlematch (MatchState *ms, const char *s, const char *p,
466
374M
                        const char *ep) {
467
374M
  if (s >= ms->src_end)
468
2.19M
    return 0;
469
371M
  else {
470
371M
    int c = cast_uchar(*s);
471
371M
    switch (*p) {
472
136M
      case '.': return 1;  /* matches any char */
473
19.2M
      case L_ESC: return match_class(c, cast_uchar(*(p+1)));
474
6.35M
      case '[': return matchbracketclass(c, p, ep-1);
475
209M
      default:  return (cast_uchar(*p) == c);
476
371M
    }
477
371M
  }
478
374M
}
479
480
481
static const char *matchbalance (MatchState *ms, const char *s,
482
136k
                                   const char *p) {
483
136k
  if (l_unlikely(p >= ms->p_end - 1))
484
1.61k
    luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
485
136k
  if (*s != *p) return NULL;
486
1.63k
  else {
487
1.63k
    int b = *p;
488
1.63k
    int e = *(p+1);
489
1.63k
    int cont = 1;
490
65.7k
    while (++s < ms->src_end) {
491
64.1k
      if (*s == e) {
492
286
        if (--cont == 0) return s+1;
493
286
      }
494
63.8k
      else if (*s == b) cont++;
495
64.1k
    }
496
1.63k
  }
497
1.61k
  return NULL;  /* string ends out of balance */
498
136k
}
499
500
501
static const char *max_expand (MatchState *ms, const char *s,
502
1.63M
                                 const char *p, const char *ep) {
503
1.63M
  ptrdiff_t i = 0;  /* counts maximum expand for item */
504
131M
  while (singlematch(ms, s + i, p, ep))
505
129M
    i++;
506
  /* keeps trying to match with the maximum repetitions */
507
98.4M
  while (i>=0) {
508
98.1M
    const char *res = match(ms, (s+i), ep+1);
509
98.1M
    if (res) return res;
510
96.7M
    i--;  /* else didn't match; reduce 1 repetition to try again */
511
96.7M
  }
512
307k
  return NULL;
513
1.63M
}
514
515
516
static const char *min_expand (MatchState *ms, const char *s,
517
37.5k
                                 const char *p, const char *ep) {
518
38.4M
  for (;;) {
519
38.4M
    const char *res = match(ms, s, ep+1);
520
38.4M
    if (res != NULL)
521
7.03k
      return res;
522
38.4M
    else if (singlematch(ms, s, p, ep))
523
38.3M
      s++;  /* try with one more repetition */
524
30.5k
    else return NULL;
525
38.4M
  }
526
37.5k
}
527
528
529
static const char *start_capture (MatchState *ms, const char *s,
530
101M
                                    const char *p, int what) {
531
101M
  const char *res;
532
101M
  int level = ms->level;
533
101M
  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
534
101M
  ms->capture[level].init = s;
535
101M
  ms->capture[level].len = what;
536
101M
  ms->level = level+1;
537
101M
  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
538
99.1M
    ms->level--;  /* undo capture */
539
101M
  return res;
540
101M
}
541
542
543
static const char *end_capture (MatchState *ms, const char *s,
544
97.6M
                                  const char *p) {
545
97.6M
  int l = capture_to_close(ms);
546
97.6M
  const char *res;
547
97.6M
  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
548
97.6M
  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
549
96.3M
    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
550
97.6M
  return res;
551
97.6M
}
552
553
554
84.4M
static const char *match_capture (MatchState *ms, const char *s, int l) {
555
84.4M
  size_t len;
556
84.4M
  l = check_capture(ms, l);
557
84.4M
  len = cast_sizet(ms->capture[l].len);
558
84.4M
  if ((size_t)(ms->src_end-s) >= len &&
559
84.4M
      memcmp(ms->capture[l].init, s, len) == 0)
560
3.64M
    return s+len;
561
80.8M
  else return NULL;
562
84.4M
}
563
564
565
428M
static const char *match (MatchState *ms, const char *s, const char *p) {
566
428M
  if (l_unlikely(ms->matchdepth-- == 0))
567
0
    luaL_error(ms->L, "pattern too complex");
568
545M
  init: /* using goto to optimize tail recursion */
569
545M
  if (p != ms->p_end) {  /* end of pattern? */
570
541M
    switch (*p) {
571
101M
      case '(': {  /* start capture */
572
101M
        if (*(p + 1) == ')')  /* position capture? */
573
9.05M
          s = start_capture(ms, s, p + 2, CAP_POSITION);
574
92.5M
        else
575
92.5M
          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
576
101M
        break;
577
0
      }
578
97.6M
      case ')': {  /* end capture */
579
97.6M
        s = end_capture(ms, s, p + 1);
580
97.6M
        break;
581
0
      }
582
52.9M
      case '$': {
583
52.9M
        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
584
20.7k
          goto dflt;  /* no; go to default */
585
52.9M
        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
586
52.9M
        break;
587
52.9M
      }
588
100M
      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
589
100M
        switch (*(p + 1)) {
590
136k
          case 'b': {  /* balanced string? */
591
136k
            s = matchbalance(ms, s, p + 2);
592
136k
            if (s != NULL) {
593
12
              p += 4; goto init;  /* return match(ms, s, p + 4); */
594
12
            }  /* else fail (s == NULL) */
595
136k
            break;
596
136k
          }
597
306k
          case 'f': {  /* frontier? */
598
306k
            const char *ep; char previous;
599
306k
            p += 2;
600
306k
            if (l_unlikely(*p != '['))
601
1.09k
              luaL_error(ms->L, "missing '[' after '%%f' in pattern");
602
306k
            ep = classend(ms, p);  /* points to what is next */
603
306k
            previous = (s == ms->src_init) ? '\0' : *(s - 1);
604
306k
            if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
605
306k
               matchbracketclass(cast_uchar(*s), p, ep - 1)) {
606
12.5k
              p = ep; goto init;  /* return match(ms, s, ep); */
607
12.5k
            }
608
293k
            s = NULL;  /* match failed */
609
293k
            break;
610
306k
          }
611
56.5M
          case '0': case '1': case '2': case '3':
612
84.4M
          case '4': case '5': case '6': case '7':
613
84.4M
          case '8': case '9': {  /* capture results (%0-%9)? */
614
84.4M
            s = match_capture(ms, s, cast_uchar(*(p + 1)));
615
84.4M
            if (s != NULL) {
616
3.64M
              p += 2; goto init;  /* return match(ms, s, p + 2) */
617
3.64M
            }
618
80.8M
            break;
619
84.4M
          }
620
80.8M
          default: goto dflt;
621
100M
        }
622
81.2M
        break;
623
100M
      }
624
204M
      default: dflt: {  /* pattern class plus optional suffix */
625
204M
        const char *ep = classend(ms, p);  /* points to optional suffix */
626
        /* does not match at least once? */
627
204M
        if (!singlematch(ms, s, p, ep)) {
628
150M
          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
629
61.3M
            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
630
61.3M
          }
631
89.1M
          else  /* '+' or no suffix */
632
89.1M
            s = NULL;  /* fail */
633
150M
        }
634
53.8M
        else {  /* matched once */
635
53.8M
          switch (*ep) {  /* handle optional suffix */
636
47.4M
            case '?': {  /* optional */
637
47.4M
              const char *res;
638
47.4M
              if ((res = match(ms, s + 1, ep + 1)) != NULL)
639
176
                s = res;
640
47.4M
              else {
641
47.4M
                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
642
47.4M
              }
643
176
              break;
644
47.4M
            }
645
93.5k
            case '+':  /* 1 or more repetitions */
646
93.5k
              s++;  /* 1 match already done */
647
              /* FALLTHROUGH */
648
1.63M
            case '*':  /* 0 or more repetitions */
649
1.63M
              s = max_expand(ms, s, p, ep);
650
1.63M
              break;
651
37.5k
            case '-':  /* 0 or more repetitions (minimum) */
652
37.5k
              s = min_expand(ms, s, p, ep);
653
37.5k
              break;
654
4.77M
            default:  /* no suffix */
655
4.77M
              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
656
53.8M
          }
657
53.8M
        }
658
90.8M
        break;
659
204M
      }
660
541M
    }
661
541M
  }
662
428M
  ms->matchdepth++;
663
428M
  return s;
664
545M
}
665
666
667
668
static const char *lmemfind (const char *s1, size_t l1,
669
73.7k
                               const char *s2, size_t l2) {
670
73.7k
  if (l2 == 0) return s1;  /* empty strings are everywhere */
671
72.6k
  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
672
72.5k
  else {
673
72.5k
    const char *init;  /* to search for a '*s2' inside 's1' */
674
72.5k
    l2--;  /* 1st char will be checked by 'memchr' */
675
72.5k
    l1 = l1-l2;  /* 's2' cannot be found after that */
676
111k
    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
677
99.8k
      init++;   /* 1st char is already checked */
678
99.8k
      if (memcmp(init, s2+1, l2) == 0)
679
60.4k
        return init-1;
680
39.3k
      else {  /* correct 'l1' and 's1' to try again */
681
39.3k
        l1 -= ct_diff2sz(init - s1);
682
39.3k
        s1 = init;
683
39.3k
      }
684
99.8k
    }
685
12.1k
    return NULL;  /* not found */
686
72.5k
  }
687
73.7k
}
688
689
690
/*
691
** get information about the i-th capture. If there are no captures
692
** and 'i==0', return information about the whole match, which
693
** is the range 's'..'e'. If the capture is a string, return
694
** its length and put its address in '*cap'. If it is an integer
695
** (a position), push it on the stack and return CAP_POSITION.
696
*/
697
static ptrdiff_t get_onecapture (MatchState *ms, int i, const char *s,
698
3.02M
                              const char *e, const char **cap) {
699
3.02M
  if (i >= ms->level) {
700
1.17M
    if (l_unlikely(i != 0))
701
3.15k
      luaL_error(ms->L, "invalid capture index %%%d", i + 1);
702
1.17M
    *cap = s;
703
1.17M
    return (e - s);
704
1.17M
  }
705
1.84M
  else {
706
1.84M
    ptrdiff_t capl = ms->capture[i].len;
707
1.84M
    *cap = ms->capture[i].init;
708
1.84M
    if (l_unlikely(capl == CAP_UNFINISHED))
709
2.19k
      luaL_error(ms->L, "unfinished capture");
710
1.84M
    else if (capl == CAP_POSITION)
711
555k
      lua_pushinteger(ms->L,
712
555k
          ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
713
1.84M
    return capl;
714
1.84M
  }
715
3.02M
}
716
717
718
/*
719
** Push the i-th capture on the stack.
720
*/
721
static void push_onecapture (MatchState *ms, int i, const char *s,
722
1.63M
                                                    const char *e) {
723
1.63M
  const char *cap;
724
1.63M
  ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
725
1.63M
  if (l != CAP_POSITION)
726
1.62M
    lua_pushlstring(ms->L, cap, cast_sizet(l));
727
  /* else position was already pushed */
728
1.63M
}
729
730
731
1.61M
static int push_captures (MatchState *ms, const char *s, const char *e) {
732
1.61M
  int i;
733
1.61M
  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
734
1.61M
  luaL_checkstack(ms->L, nlevels, "too many captures");
735
3.24M
  for (i = 0; i < nlevels; i++)
736
1.63M
    push_onecapture(ms, i, s, e);
737
1.61M
  return nlevels;  /* number of strings pushed */
738
1.61M
}
739
740
741
/* check whether pattern has no special characters */
742
337k
static int nospecials (const char *p, size_t l) {
743
337k
  size_t upto = 0;
744
382k
  do {
745
382k
    if (strpbrk(p + upto, SPECIALS))
746
264k
      return 0;  /* pattern has a special character */
747
118k
    upto += strlen(p + upto) + 1;  /* may have more after \0 */
748
118k
  } while (upto <= l);
749
73.7k
  return 1;  /* no special chars found */
750
337k
}
751
752
753
static void prepstate (MatchState *ms, lua_State *L,
754
2.24M
                       const char *s, size_t ls, const char *p, size_t lp) {
755
2.24M
  ms->L = L;
756
2.24M
  ms->matchdepth = MAXCCALLS;
757
2.24M
  ms->src_init = s;
758
2.24M
  ms->src_end = s + ls;
759
2.24M
  ms->p_end = p + lp;
760
2.24M
}
761
762
763
45.4M
static void reprepstate (MatchState *ms) {
764
45.4M
  ms->level = 0;
765
45.4M
  lua_assert(ms->matchdepth == MAXCCALLS);
766
45.4M
}
767
768
769
511k
static int str_find_aux (lua_State *L, int find) {
770
511k
  size_t ls, lp;
771
511k
  const char *s = luaL_checklstring(L, 1, &ls);
772
511k
  const char *p = luaL_checklstring(L, 2, &lp);
773
511k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
774
511k
  if (init > ls) {  /* start after string's end? */
775
141k
    luaL_pushfail(L);  /* cannot find anything */
776
141k
    return 1;
777
141k
  }
778
  /* explicit request or no special characters? */
779
369k
  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
780
    /* do a plain search */
781
73.7k
    const char *s2 = lmemfind(s + init, ls - init, p, lp);
782
73.7k
    if (s2) {
783
61.5k
      lua_pushinteger(L, ct_diff2S(s2 - s) + 1);
784
61.5k
      lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));
785
61.5k
      return 2;
786
61.5k
    }
787
73.7k
  }
788
296k
  else {
789
296k
    MatchState ms;
790
296k
    const char *s1 = s + init;
791
296k
    int anchor = (*p == '^');
792
296k
    if (anchor) {
793
6.62k
      p++; lp--;  /* skip anchor character */
794
6.62k
    }
795
296k
    prepstate(&ms, L, s, ls, p, lp);
796
20.8M
    do {
797
20.8M
      const char *res;
798
20.8M
      reprepstate(&ms);
799
20.8M
      if ((res=match(&ms, s1, p)) != NULL) {
800
13.4k
        if (find) {
801
3.07k
          lua_pushinteger(L, ct_diff2S(s1 - s) + 1);  /* start */
802
3.07k
          lua_pushinteger(L, ct_diff2S(res - s));   /* end */
803
3.07k
          return push_captures(&ms, NULL, 0) + 2;
804
3.07k
        }
805
10.4k
        else
806
10.4k
          return push_captures(&ms, s1, res);
807
13.4k
      }
808
20.8M
    } while (s1++ < ms.src_end && !anchor);
809
296k
  }
810
294k
  luaL_pushfail(L);  /* not found */
811
294k
  return 1;
812
369k
}
813
814
815
361k
static int str_find (lua_State *L) {
816
361k
  return str_find_aux(L, 1);
817
361k
}
818
819
820
149k
static int str_match (lua_State *L) {
821
149k
  return str_find_aux(L, 0);
822
149k
}
823
824
825
/* state for 'gmatch' */
826
typedef struct GMatchState {
827
  const char *src;  /* current position */
828
  const char *p;  /* pattern */
829
  const char *lastmatch;  /* end of last match */
830
  MatchState ms;  /* match state */
831
} GMatchState;
832
833
834
172k
static int gmatch_aux (lua_State *L) {
835
172k
  GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
836
172k
  const char *src;
837
172k
  gm->ms.L = L;
838
3.71M
  for (src = gm->src; src <= gm->ms.src_end; src++) {
839
3.55M
    const char *e;
840
3.55M
    reprepstate(&gm->ms);
841
3.55M
    if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
842
9.21k
      gm->src = gm->lastmatch = e;
843
9.21k
      return push_captures(&gm->ms, src, e);
844
9.21k
    }
845
3.55M
  }
846
163k
  return 0;  /* not found */
847
172k
}
848
849
850
252k
static int gmatch (lua_State *L) {
851
252k
  size_t ls, lp;
852
252k
  const char *s = luaL_checklstring(L, 1, &ls);
853
252k
  const char *p = luaL_checklstring(L, 2, &lp);
854
252k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
855
252k
  GMatchState *gm;
856
252k
  lua_settop(L, 2);  /* keep strings on closure to avoid being collected */
857
252k
  gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
858
252k
  if (init > ls)  /* start after string's end? */
859
1.32k
    init = ls + 1;  /* avoid overflows in 's + init' */
860
252k
  prepstate(&gm->ms, L, s, ls, p, lp);
861
252k
  gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
862
252k
  lua_pushcclosure(L, gmatch_aux, 3);
863
252k
  return 1;
864
252k
}
865
866
867
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
868
1.40M
                                                   const char *e) {
869
1.40M
  size_t l;
870
1.40M
  lua_State *L = ms->L;
871
1.40M
  const char *news = lua_tolstring(L, 3, &l);
872
1.40M
  const char *p;
873
5.05M
  while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
874
3.65M
    luaL_addlstring(b, news, ct_diff2sz(p - news));
875
3.65M
    p++;  /* skip ESC */
876
3.65M
    if (*p == L_ESC)  /* '%%' */
877
1.49M
      luaL_addchar(b, *p);
878
2.15M
    else if (*p == '0')  /* '%0' */
879
769k
        luaL_addlstring(b, s, ct_diff2sz(e - s));
880
1.38M
    else if (isdigit(cast_uchar(*p))) {  /* '%n' */
881
1.38M
      const char *cap;
882
1.38M
      ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
883
1.38M
      if (resl == CAP_POSITION)
884
541k
        luaL_addvalue(b);  /* add position to accumulated result */
885
843k
      else
886
843k
        luaL_addlstring(b, cap, cast_sizet(resl));
887
1.38M
    }
888
1.25k
    else
889
1.25k
      luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
890
3.65M
    l -= ct_diff2sz(p + 1 - news);
891
3.65M
    news = p + 1;
892
3.65M
  }
893
1.40M
  luaL_addlstring(b, news, l);
894
1.40M
}
895
896
897
/*
898
** Add the replacement value to the string buffer 'b'.
899
** Return true if the original string was changed. (Function calls and
900
** table indexing resulting in nil or false do not change the subject.)
901
*/
902
static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
903
2.99M
                                      const char *e, int tr) {
904
2.99M
  lua_State *L = ms->L;
905
2.99M
  switch (tr) {
906
1.58M
    case LUA_TFUNCTION: {  /* call the function */
907
1.58M
      int n;
908
1.58M
      lua_pushvalue(L, 3);  /* push the function */
909
1.58M
      n = push_captures(ms, s, e);  /* all captures as arguments */
910
1.58M
      lua_call(L, n, 1);  /* call it */
911
1.58M
      break;
912
0
    }
913
7.40k
    case LUA_TTABLE: {  /* index the table */
914
7.40k
      push_onecapture(ms, 0, s, e);  /* first capture is the index */
915
7.40k
      lua_gettable(L, 3);
916
7.40k
      break;
917
0
    }
918
1.40M
    default: {  /* LUA_TNUMBER or LUA_TSTRING */
919
1.40M
      add_s(ms, b, s, e);  /* add value to the buffer */
920
1.40M
      return 1;  /* something changed */
921
0
    }
922
2.99M
  }
923
1.59M
  if (!lua_toboolean(L, -1)) {  /* nil or false? */
924
15.5k
    lua_pop(L, 1);  /* remove value */
925
15.5k
    luaL_addlstring(b, s, ct_diff2sz(e - s));  /* keep original text */
926
15.5k
    return 0;  /* no changes */
927
15.5k
  }
928
1.57M
  else if (l_unlikely(!lua_isstring(L, -1)))
929
0
    return luaL_error(L, "invalid replacement value (a %s)",
930
0
                         luaL_typename(L, -1));
931
1.57M
  else {
932
1.57M
    luaL_addvalue(b);  /* add result to accumulator */
933
1.57M
    return 1;  /* something changed */
934
1.57M
  }
935
1.59M
}
936
937
938
1.70M
static int str_gsub (lua_State *L) {
939
1.70M
  size_t srcl, lp;
940
1.70M
  const char *src = luaL_checklstring(L, 1, &srcl);  /* subject */
941
1.70M
  const char *p = luaL_checklstring(L, 2, &lp);  /* pattern */
942
1.70M
  const char *lastmatch = NULL;  /* end of last match */
943
1.70M
  int tr = lua_type(L, 3);  /* replacement type */
944
  /* max replacements */
945
1.70M
  lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
946
1.70M
  int anchor = (*p == '^');
947
1.70M
  lua_Integer n = 0;  /* replacement count */
948
1.70M
  int changed = 0;  /* change flag */
949
1.70M
  MatchState ms;
950
1.70M
  luaL_Buffer b;
951
1.70M
  luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
952
1.70M
                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
953
1.70M
                      "string/function/table");
954
1.70M
  luaL_buffinit(L, &b);
955
1.70M
  if (anchor) {
956
6.00k
    p++; lp--;  /* skip anchor character */
957
6.00k
  }
958
1.70M
  prepstate(&ms, L, src, srcl, p, lp);
959
21.0M
  while (n < max_s) {
960
21.0M
    const char *e;
961
21.0M
    reprepstate(&ms);  /* (re)prepare state for new match */
962
21.0M
    if ((e = match(&ms, src, p)) != NULL && e != lastmatch) {  /* match? */
963
2.99M
      n++;
964
2.99M
      changed = add_value(&ms, &b, src, e, tr) | changed;
965
2.99M
      src = lastmatch = e;
966
2.99M
    }
967
18.0M
    else if (src < ms.src_end)  /* otherwise, skip one character */
968
16.3M
      luaL_addchar(&b, *src++);
969
1.67M
    else break;  /* end of subject */
970
19.3M
    if (anchor) break;
971
19.3M
  }
972
1.70M
  if (!changed)  /* no changes? */
973
382k
    lua_pushvalue(L, 1);  /* return original string */
974
1.31M
  else {  /* something changed */
975
1.31M
    luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));
976
1.31M
    luaL_pushresult(&b);  /* create and return new string */
977
1.31M
  }
978
1.70M
  lua_pushinteger(L, n);  /* number of substitutions */
979
1.70M
  return 2;
980
1.70M
}
981
982
/* }====================================================== */
983
984
985
986
/*
987
** {======================================================
988
** STRING FORMAT
989
** =======================================================
990
*/
991
992
#if !defined(lua_number2strx) /* { */
993
994
/*
995
** Hexadecimal floating-point formatter
996
*/
997
998
#define SIZELENMOD  (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
999
1000
1001
/*
1002
** Number of bits that goes into the first digit. It can be any value
1003
** between 1 and 4; the following definition tries to align the number
1004
** to nibble boundaries by making what is left after that first digit a
1005
** multiple of 4.
1006
*/
1007
#define L_NBFD    ((l_floatatt(MANT_DIG) - 1)%4 + 1)
1008
1009
1010
/*
1011
** Add integer part of 'x' to buffer and return new 'x'
1012
*/
1013
static lua_Number adddigit (char *buff, unsigned n, lua_Number x) {
1014
  lua_Number dd = l_mathop(floor)(x);  /* get integer part from 'x' */
1015
  int d = (int)dd;
1016
  buff[n] = cast_char(d < 10 ? d + '0' : d - 10 + 'a');  /* add to buffer */
1017
  return x - dd;  /* return what is left */
1018
}
1019
1020
1021
static int num2straux (char *buff, unsigned sz, lua_Number x) {
1022
  /* if 'inf' or 'NaN', format it like '%g' */
1023
  if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)
1024
    return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);
1025
  else if (x == 0) {  /* can be -0... */
1026
    /* create "0" or "-0" followed by exponent */
1027
    return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x);
1028
  }
1029
  else {
1030
    int e;
1031
    lua_Number m = l_mathop(frexp)(x, &e);  /* 'x' fraction and exponent */
1032
    unsigned n = 0;  /* character count */
1033
    if (m < 0) {  /* is number negative? */
1034
      buff[n++] = '-';  /* add sign */
1035
      m = -m;  /* make it positive */
1036
    }
1037
    buff[n++] = '0'; buff[n++] = 'x';  /* add "0x" */
1038
    m = adddigit(buff, n++, m * (1 << L_NBFD));  /* add first digit */
1039
    e -= L_NBFD;  /* this digit goes before the radix point */
1040
    if (m > 0) {  /* more digits? */
1041
      buff[n++] = lua_getlocaledecpoint();  /* add radix point */
1042
      do {  /* add as many digits as needed */
1043
        m = adddigit(buff, n++, m * 16);
1044
      } while (m > 0);
1045
    }
1046
    n += cast_uint(l_sprintf(buff + n, sz - n, "p%+d", e));  /* add exponent */
1047
    lua_assert(n < sz);
1048
    return cast_int(n);
1049
  }
1050
}
1051
1052
1053
static int lua_number2strx (lua_State *L, char *buff, unsigned sz,
1054
                            const char *fmt, lua_Number x) {
1055
  int n = num2straux(buff, sz, x);
1056
  if (fmt[SIZELENMOD] == 'A') {
1057
    int i;
1058
    for (i = 0; i < n; i++)
1059
      buff[i] = cast_char(toupper(cast_uchar(buff[i])));
1060
  }
1061
  else if (l_unlikely(fmt[SIZELENMOD] != 'a'))
1062
    return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
1063
  return n;
1064
}
1065
1066
#endif        /* } */
1067
1068
1069
/*
1070
** Maximum size for items formatted with '%f'. This size is produced
1071
** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
1072
** and '\0') + number of decimal digits to represent maxfloat (which
1073
** is maximum exponent + 1). (99+3+1, adding some extra, 110)
1074
*/
1075
3.19k
#define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP))
1076
1077
1078
/*
1079
** All formats except '%f' do not need that large limit.  The other
1080
** float formats use exponents, so that they fit in the 99 limit for
1081
** significant digits; 's' for large strings and 'q' add items directly
1082
** to the buffer; all integer formats also fit in the 99 limit.  The
1083
** worst case are floats: they may need 99 significant digits, plus
1084
** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120.
1085
*/
1086
827k
#define MAX_ITEM  120
1087
1088
1089
/* valid flags in a format specification */
1090
#if !defined(L_FMTFLAGSF)
1091
1092
/* valid flags for a, A, e, E, f, F, g, and G conversions */
1093
1.29M
#define L_FMTFLAGSF "-+#0 "
1094
1095
/* valid flags for o, x, and X conversions */
1096
10.4k
#define L_FMTFLAGSX "-#0"
1097
1098
/* valid flags for d and i conversions */
1099
18.1k
#define L_FMTFLAGSI "-+0 "
1100
1101
/* valid flags for u conversions */
1102
7.68k
#define L_FMTFLAGSU "-0"
1103
1104
/* valid flags for c, p, and s conversions */
1105
77.4k
#define L_FMTFLAGSC "-"
1106
1107
#endif
1108
1109
1110
/*
1111
** Maximum size of each format specification (such as "%-099.99d"):
1112
** Initial '%', flags (up to 5), width (2), period, precision (2),
1113
** length modifier (8), conversion specifier, and final '\0', plus some
1114
** extra.
1115
*/
1116
799k
#define MAX_FORMAT  32
1117
1118
1119
25.2k
static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
1120
25.2k
  luaL_addchar(b, '"');
1121
67.6M
  while (len--) {
1122
67.6M
    if (*s == '"' || *s == '\\' || *s == '\n') {
1123
1.65M
      luaL_addchar(b, '\\');
1124
1.65M
      luaL_addchar(b, *s);
1125
1.65M
    }
1126
66.0M
    else if (iscntrl(cast_uchar(*s))) {
1127
2.19M
      char buff[10];
1128
2.19M
      if (!isdigit(cast_uchar(*(s+1))))
1129
2.18M
        l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
1130
7.13k
      else
1131
7.13k
        l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s));
1132
2.19M
      luaL_addstring(b, buff);
1133
2.19M
    }
1134
63.8M
    else
1135
63.8M
      luaL_addchar(b, *s);
1136
67.6M
    s++;
1137
67.6M
  }
1138
25.2k
  luaL_addchar(b, '"');
1139
25.2k
}
1140
1141
1142
/*
1143
** Serialize a floating-point number in such a way that it can be
1144
** scanned back by Lua. Use hexadecimal format for "common" numbers
1145
** (to preserve precision); inf, -inf, and NaN are handled separately.
1146
** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)
1147
*/
1148
1.43k
static int quotefloat (lua_State *L, char *buff, lua_Number n) {
1149
1.43k
  const char *s;  /* for the fixed representations */
1150
1.43k
  if (n == (lua_Number)HUGE_VAL)  /* inf? */
1151
779
    s = "1e9999";
1152
651
  else if (n == -(lua_Number)HUGE_VAL)  /* -inf? */
1153
0
    s = "-1e9999";
1154
651
  else if (n != n)  /* NaN? */
1155
302
    s = "(0/0)";
1156
349
  else {  /* format number as hexadecimal */
1157
349
    int  nb = lua_number2strx(L, buff, MAX_ITEM,
1158
349
                                 "%" LUA_NUMBER_FRMLEN "a", n);
1159
    /* ensures that 'buff' string uses a dot as the radix character */
1160
349
    if (memchr(buff, '.', cast_uint(nb)) == NULL) {  /* no dot? */
1161
347
      char point = lua_getlocaledecpoint();  /* try locale point */
1162
347
      char *ppoint = (char *)memchr(buff, point, cast_uint(nb));
1163
347
      if (ppoint) *ppoint = '.';  /* change it to a dot */
1164
347
    }
1165
349
    return nb;
1166
349
  }
1167
  /* for the fixed representations */
1168
1.08k
  return l_sprintf(buff, MAX_ITEM, "%s", s);
1169
1.43k
}
1170
1171
1172
28.2k
static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
1173
28.2k
  switch (lua_type(L, arg)) {
1174
25.2k
    case LUA_TSTRING: {
1175
25.2k
      size_t len;
1176
25.2k
      const char *s = lua_tolstring(L, arg, &len);
1177
25.2k
      addquoted(b, s, len);
1178
25.2k
      break;
1179
0
    }
1180
1.83k
    case LUA_TNUMBER: {
1181
1.83k
      char *buff = luaL_prepbuffsize(b, MAX_ITEM);
1182
1.83k
      int nb;
1183
1.83k
      if (!lua_isinteger(L, arg))  /* float? */
1184
1.43k
        nb = quotefloat(L, buff, lua_tonumber(L, arg));
1185
408
      else {  /* integers */
1186
408
        lua_Integer n = lua_tointeger(L, arg);
1187
408
        const char *format = (n == LUA_MININTEGER)  /* corner case? */
1188
408
                           ? "0x%" LUA_INTEGER_FRMLEN "x"  /* use hex */
1189
408
                           : LUA_INTEGER_FMT;  /* else use default format */
1190
408
        nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
1191
408
      }
1192
1.83k
      luaL_addsize(b, cast_uint(nb));
1193
1.83k
      break;
1194
0
    }
1195
1.12k
    case LUA_TNIL: case LUA_TBOOLEAN: {
1196
1.12k
      luaL_tolstring(L, arg, NULL);
1197
1.12k
      luaL_addvalue(b);
1198
1.12k
      break;
1199
908
    }
1200
0
    default: {
1201
0
      luaL_argerror(L, arg, "value has no literal form");
1202
0
    }
1203
28.2k
  }
1204
28.2k
}
1205
1206
1207
926k
static const char *get2digits (const char *s) {
1208
926k
  if (isdigit(cast_uchar(*s))) {
1209
398k
    s++;
1210
398k
    if (isdigit(cast_uchar(*s))) s++;  /* (2 digits at most) */
1211
398k
  }
1212
926k
  return s;
1213
926k
}
1214
1215
1216
/*
1217
** Check whether a conversion specification is valid. When called,
1218
** first character in 'form' must be '%' and last character must
1219
** be a valid conversion specifier. 'flags' are the accepted flags;
1220
** 'precision' signals whether to accept a precision.
1221
*/
1222
static void checkformat (lua_State *L, const char *form, const char *flags,
1223
589k
                                       int precision) {
1224
589k
  const char *spec = form + 1;  /* skip '%' */
1225
589k
  spec += strspn(spec, flags);  /* skip flags */
1226
589k
  if (*spec != '0') {  /* a width cannot start with '0' */
1227
579k
    spec = get2digits(spec);  /* skip width */
1228
579k
    if (*spec == '.' && precision) {
1229
347k
      spec++;
1230
347k
      spec = get2digits(spec);  /* skip precision */
1231
347k
    }
1232
579k
  }
1233
589k
  if (!isalpha(cast_uchar(*spec)))  /* did not go to the end? */
1234
17.2k
    luaL_error(L, "invalid conversion specification: '%s'", form);
1235
589k
}
1236
1237
1238
/*
1239
** Get a conversion specification and copy it to 'form'.
1240
** Return the address of its last character.
1241
*/
1242
static const char *getformat (lua_State *L, const char *strfrmt,
1243
799k
                                            char *form) {
1244
  /* spans flags, width, and precision ('0' is included as a flag) */
1245
799k
  size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
1246
799k
  len++;  /* adds following character (should be the specifier) */
1247
  /* still needs space for '%', '\0', plus a length modifier */
1248
799k
  if (len >= MAX_FORMAT - 10)
1249
9.05k
    luaL_error(L, "invalid format (too long)");
1250
799k
  *(form++) = '%';
1251
799k
  memcpy(form, strfrmt, len * sizeof(char));
1252
799k
  *(form + len) = '\0';
1253
799k
  return strfrmt + len - 1;
1254
799k
}
1255
1256
1257
/*
1258
** add length modifier into formats
1259
*/
1260
512k
static void addlenmod (char *form, const char *lenmod) {
1261
512k
  size_t l = strlen(form);
1262
512k
  size_t lm = strlen(lenmod);
1263
512k
  char spec = form[l - 1];
1264
512k
  strcpy(form + l - 1, lenmod);
1265
512k
  form[l + lm - 1] = spec;
1266
512k
  form[l + lm] = '\0';
1267
512k
}
1268
1269
1270
958k
static int str_format (lua_State *L) {
1271
958k
  int top = lua_gettop(L);
1272
958k
  int arg = 1;
1273
958k
  size_t sfl;
1274
958k
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
1275
958k
  const char *strfrmt_end = strfrmt+sfl;
1276
958k
  const char *flags;
1277
958k
  luaL_Buffer b;
1278
958k
  luaL_buffinit(L, &b);
1279
21.3M
  while (strfrmt < strfrmt_end) {
1280
20.5M
    if (*strfrmt != L_ESC)
1281
19.5M
      luaL_addchar(&b, *strfrmt++);
1282
982k
    else if (*++strfrmt == L_ESC)
1283
156k
      luaL_addchar(&b, *strfrmt++);  /* %% */
1284
825k
    else { /* format item */
1285
825k
      char form[MAX_FORMAT];  /* to store the format ('%...') */
1286
825k
      unsigned maxitem = MAX_ITEM;  /* maximum length for the result */
1287
825k
      char *buff = luaL_prepbuffsize(&b, maxitem);  /* to put result */
1288
825k
      int nb = 0;  /* number of bytes in result */
1289
825k
      if (++arg > top)
1290
26.7k
        return luaL_argerror(L, arg, "no value");
1291
799k
      strfrmt = getformat(L, strfrmt, form);
1292
799k
      switch (*strfrmt++) {
1293
18.3k
        case 'c': {
1294
18.3k
          checkformat(L, form, L_FMTFLAGSC, 0);
1295
18.3k
          nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
1296
18.3k
          break;
1297
0
        }
1298
18.1k
        case 'd': case 'i':
1299
18.1k
          flags = L_FMTFLAGSI;
1300
18.1k
          goto intcase;
1301
7.68k
        case 'u':
1302
7.68k
          flags = L_FMTFLAGSU;
1303
7.68k
          goto intcase;
1304
10.4k
        case 'o': case 'x': case 'X':
1305
10.4k
          flags = L_FMTFLAGSX;
1306
36.2k
         intcase: {
1307
36.2k
          lua_Integer n = luaL_checkinteger(L, arg);
1308
36.2k
          checkformat(L, form, flags, 1);
1309
36.2k
          addlenmod(form, LUA_INTEGER_FRMLEN);
1310
36.2k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
1311
36.2k
          break;
1312
10.4k
        }
1313
152k
        case 'a': case 'A':
1314
152k
          checkformat(L, form, L_FMTFLAGSF, 1);
1315
152k
          addlenmod(form, LUA_NUMBER_FRMLEN);
1316
152k
          nb = lua_number2strx(L, buff, maxitem, form,
1317
152k
                                  luaL_checknumber(L, arg));
1318
152k
          break;
1319
3.19k
        case 'f':
1320
3.19k
          maxitem = MAX_ITEMF;  /* extra space for '%f' */
1321
3.19k
          buff = luaL_prepbuffsize(&b, maxitem);
1322
          /* FALLTHROUGH */
1323
347k
        case 'e': case 'E': case 'g': case 'G': {
1324
347k
          lua_Number n = luaL_checknumber(L, arg);
1325
347k
          checkformat(L, form, L_FMTFLAGSF, 1);
1326
347k
          addlenmod(form, LUA_NUMBER_FRMLEN);
1327
347k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
1328
347k
          break;
1329
346k
        }
1330
11.8k
        case 'p': {
1331
11.8k
          const void *p = lua_topointer(L, arg);
1332
11.8k
          checkformat(L, form, L_FMTFLAGSC, 0);
1333
11.8k
          if (p == NULL) {  /* avoid calling 'printf' with argument NULL */
1334
361
            p = "(null)";  /* result */
1335
361
            form[strlen(form) - 1] = 's';  /* format it as a string */
1336
361
          }
1337
11.8k
          nb = l_sprintf(buff, maxitem, form, p);
1338
11.8k
          break;
1339
346k
        }
1340
28.2k
        case 'q': {
1341
28.2k
          if (form[2] != '\0')  /* modifiers? */
1342
38
            return luaL_error(L, "specifier '%%q' cannot have modifiers");
1343
28.2k
          addliteral(L, &b, arg);
1344
28.2k
          break;
1345
28.2k
        }
1346
185k
        case 's': {
1347
185k
          size_t l;
1348
185k
          const char *s = luaL_tolstring(L, arg, &l);
1349
185k
          if (form[2] == '\0')  /* no modifiers? */
1350
138k
            luaL_addvalue(&b);  /* keep entire string */
1351
47.2k
          else {
1352
47.2k
            luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
1353
47.2k
            checkformat(L, form, L_FMTFLAGSC, 1);
1354
47.2k
            if (strchr(form, '.') == NULL && l >= 100) {
1355
              /* no precision and string is too long to be formatted */
1356
23.0k
              luaL_addvalue(&b);  /* keep entire string */
1357
23.0k
            }
1358
24.2k
            else {  /* format the string into 'buff' */
1359
24.2k
              nb = l_sprintf(buff, maxitem, form, s);
1360
24.2k
              lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
1361
24.2k
            }
1362
47.2k
          }
1363
185k
          break;
1364
28.2k
        }
1365
9.06k
        default: {  /* also treat cases 'pnLlh' */
1366
9.06k
          return luaL_error(L, "invalid conversion '%s' to 'format'", form);
1367
28.2k
        }
1368
799k
      }
1369
718k
      lua_assert(cast_uint(nb) < maxitem);
1370
718k
      luaL_addsize(&b, cast_uint(nb));
1371
718k
    }
1372
20.5M
  }
1373
851k
  luaL_pushresult(&b);
1374
851k
  return 1;
1375
958k
}
1376
1377
/* }====================================================== */
1378
1379
1380
/*
1381
** {======================================================
1382
** PACK/UNPACK
1383
** =======================================================
1384
*/
1385
1386
1387
/* value used for padding */
1388
#if !defined(LUAL_PACKPADBYTE)
1389
183k
#define LUAL_PACKPADBYTE    0x00
1390
#endif
1391
1392
/* maximum size for the binary representation of an integer */
1393
#define MAXINTSIZE  16
1394
1395
/* number of bits in a character */
1396
4.05M
#define NB  CHAR_BIT
1397
1398
/* mask for one character (NB 1's) */
1399
1.44M
#define MC  ((1 << NB) - 1)
1400
1401
/* size of a lua_Integer */
1402
613k
#define SZINT ((int)sizeof(lua_Integer))
1403
1404
1405
/* dummy union to get native endianness */
1406
static const union {
1407
  int dummy;
1408
  char little;  /* true iff machine is little endian */
1409
} nativeendian = {1};
1410
1411
1412
/*
1413
** information to pack/unpack stuff
1414
*/
1415
typedef struct Header {
1416
  lua_State *L;
1417
  int islittle;
1418
  unsigned maxalign;
1419
} Header;
1420
1421
1422
/*
1423
** options for pack/unpack
1424
*/
1425
typedef enum KOption {
1426
  Kint,   /* signed integers */
1427
  Kuint,  /* unsigned integers */
1428
  Kfloat, /* single-precision floating-point numbers */
1429
  Knumber,  /* Lua "native" floating-point numbers */
1430
  Kdouble,  /* double-precision floating-point numbers */
1431
  Kchar,  /* fixed-length strings */
1432
  Kstring,  /* strings with prefixed length */
1433
  Kzstr,  /* zero-terminated strings */
1434
  Kpadding, /* padding */
1435
  Kpaddalign, /* padding for alignment */
1436
  Knop    /* no-op (configuration or spaces) */
1437
} KOption;
1438
1439
1440
/*
1441
** Read an integer numeral from string 'fmt' or return 'df' if
1442
** there is no numeral
1443
*/
1444
1.44M
static int digit (int c) { return '0' <= c && c <= '9'; }
1445
1446
608k
static size_t getnum (const char **fmt, size_t df) {
1447
608k
  if (!digit(**fmt))  /* no number? */
1448
391k
    return df;  /* return default value */
1449
216k
  else {
1450
216k
    size_t a = 0;
1451
834k
    do {
1452
834k
      a = a*10 + cast_uint(*((*fmt)++) - '0');
1453
834k
    } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);
1454
216k
    return a;
1455
216k
  }
1456
608k
}
1457
1458
1459
/*
1460
** Read an integer numeral and raises an error if it is larger
1461
** than the maximum size of integers.
1462
*/
1463
422k
static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
1464
422k
  size_t sz = getnum(fmt, df);
1465
422k
  if (l_unlikely((sz - 1u) >= MAXINTSIZE))
1466
3.08k
    return cast_uint(luaL_error(h->L,
1467
419k
               "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
1468
419k
  return cast_uint(sz);
1469
422k
}
1470
1471
1472
/*
1473
** Initialize Header
1474
*/
1475
465k
static void initheader (lua_State *L, Header *h) {
1476
465k
  h->L = L;
1477
465k
  h->islittle = nativeendian.little;
1478
465k
  h->maxalign = 1;
1479
465k
}
1480
1481
1482
/*
1483
** Read and classify next option. 'size' is filled with option's size.
1484
*/
1485
2.23M
static KOption getoption (Header *h, const char **fmt, size_t *size) {
1486
  /* dummy structure to get native alignment requirements */
1487
2.23M
  struct cD { char c; union { LUAI_MAXALIGN; } u; };
1488
2.23M
  int opt = *((*fmt)++);
1489
2.23M
  *size = 0;  /* default */
1490
2.23M
  switch (opt) {
1491
3.36k
    case 'b': *size = sizeof(char); return Kint;
1492
8.71k
    case 'B': *size = sizeof(char); return Kuint;
1493
59.0k
    case 'h': *size = sizeof(short); return Kint;
1494
1.08k
    case 'H': *size = sizeof(short); return Kuint;
1495
149k
    case 'l': *size = sizeof(long); return Kint;
1496
2.97k
    case 'L': *size = sizeof(long); return Kuint;
1497
200k
    case 'j': *size = sizeof(lua_Integer); return Kint;
1498
391
    case 'J': *size = sizeof(lua_Integer); return Kuint;
1499
925
    case 'T': *size = sizeof(size_t); return Kuint;
1500
5.24k
    case 'f': *size = sizeof(float); return Kfloat;
1501
5.94k
    case 'n': *size = sizeof(lua_Number); return Knumber;
1502
5.26k
    case 'd': *size = sizeof(double); return Kdouble;
1503
16.7k
    case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1504
4.88k
    case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1505
182k
    case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1506
185k
    case 'c':
1507
185k
      *size = getnum(fmt, cast_sizet(-1));
1508
185k
      if (l_unlikely(*size == cast_sizet(-1)))
1509
148
        luaL_error(h->L, "missing size for format option 'c'");
1510
185k
      return Kchar;
1511
942
    case 'z': return Kzstr;
1512
279k
    case 'x': *size = 1; return Kpadding;
1513
182k
    case 'X': return Kpaddalign;
1514
26.9k
    case ' ': break;
1515
81.5k
    case '<': h->islittle = 1; break;
1516
582k
    case '>': h->islittle = 0; break;
1517
4.42k
    case '=': h->islittle = nativeendian.little; break;
1518
218k
    case '!': {
1519
218k
      const size_t maxalign = offsetof(struct cD, u);
1520
218k
      h->maxalign = getnumlimit(h, fmt, maxalign);
1521
218k
      break;
1522
0
    }
1523
20.9k
    default: luaL_error(h->L, "invalid format option '%c'", opt);
1524
2.23M
  }
1525
912k
  return Knop;
1526
2.23M
}
1527
1528
1529
/*
1530
** Read, classify, and fill other details about the next option.
1531
** 'psize' is filled with option's size, 'notoalign' with its
1532
** alignment requirements.
1533
** Local variable 'size' gets the size to be aligned. (Kpadal option
1534
** always gets its full alignment, other options are limited by
1535
** the maximum alignment ('maxalign'). Kchar option needs no alignment
1536
** despite its size.
1537
*/
1538
static KOption getdetails (Header *h, size_t totalsize, const char **fmt,
1539
2.04M
                           size_t *psize, unsigned *ntoalign) {
1540
2.04M
  KOption opt = getoption(h, fmt, psize);
1541
2.04M
  size_t align = *psize;  /* usually, alignment follows size */
1542
2.04M
  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
1543
182k
    if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1544
1.31k
      luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1545
182k
  }
1546
2.04M
  if (align <= 1 || opt == Kchar)  /* need no alignment? */
1547
1.39M
    *ntoalign = 0;
1548
656k
  else {
1549
656k
    if (align > h->maxalign)  /* enforce maximum alignment */
1550
303k
      align = h->maxalign;
1551
656k
    if (l_unlikely(!ispow2(align))) {  /* not a power of 2? */
1552
1.00k
      *ntoalign = 0;  /* to avoid warnings */
1553
1.00k
      luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
1554
1.00k
    }
1555
655k
    else {
1556
      /* 'szmoda' = totalsize % align */
1557
655k
      unsigned szmoda = cast_uint(totalsize & (align - 1));
1558
655k
      *ntoalign = cast_uint((align - szmoda) & (align - 1));
1559
655k
    }
1560
656k
  }
1561
2.04M
  return opt;
1562
2.04M
}
1563
1564
1565
/*
1566
** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
1567
** The final 'if' handles the case when 'size' is larger than
1568
** the size of a Lua integer, correcting the extra sign-extension
1569
** bytes if necessary (by default they would be zeros).
1570
*/
1571
static void packint (luaL_Buffer *b, lua_Unsigned n,
1572
228k
                     int islittle, unsigned size, int neg) {
1573
228k
  char *buff = luaL_prepbuffsize(b, size);
1574
228k
  unsigned i;
1575
228k
  buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */
1576
1.44M
  for (i = 1; i < size; i++) {
1577
1.21M
    n >>= NB;
1578
1.21M
    buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1579
1.21M
  }
1580
228k
  if (neg && size > SZINT) {  /* negative number need sign extension? */
1581
44
    for (i = SZINT; i < size; i++)  /* correct extra bytes */
1582
22
      buff[islittle ? i : size - 1 - i] = (char)MC;
1583
22
  }
1584
228k
  luaL_addsize(b, size);  /* add result to buffer */
1585
228k
}
1586
1587
1588
/*
1589
** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
1590
** given 'islittle' is different from native endianness.
1591
*/
1592
static void copywithendian (char *dest, const char *src,
1593
12.6k
                            unsigned size, int islittle) {
1594
12.6k
  if (islittle == nativeendian.little)
1595
4.78k
    memcpy(dest, src, size);
1596
7.86k
  else {
1597
7.86k
    dest += size - 1;
1598
53.6k
    while (size-- != 0)
1599
45.7k
      *(dest--) = *(src++);
1600
7.86k
  }
1601
12.6k
}
1602
1603
1604
432k
static int str_pack (lua_State *L) {
1605
432k
  luaL_Buffer b;
1606
432k
  Header h;
1607
432k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1608
432k
  int arg = 1;  /* current argument to pack */
1609
432k
  size_t totalsize = 0;  /* accumulate total size of result */
1610
432k
  initheader(L, &h);
1611
432k
  lua_pushnil(L);  /* mark to separate arguments from string buffer */
1612
432k
  luaL_buffinit(L, &b);
1613
2.17M
  while (*fmt != '\0') {
1614
1.76M
    unsigned ntoalign;
1615
1.76M
    size_t size;
1616
1.76M
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1617
1.76M
    luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,
1618
1.76M
                     "result too long");
1619
1.76M
    totalsize += ntoalign + size;
1620
3.62M
    while (ntoalign-- > 0)
1621
1.86M
     luaL_addchar(&b, LUAL_PACKPADBYTE);  /* fill alignment */
1622
1.76M
    arg++;
1623
1.76M
    switch (opt) {
1624
70.1k
      case Kint: {  /* signed integers */
1625
70.1k
        lua_Integer n = luaL_checkinteger(L, arg);
1626
70.1k
        if (size < SZINT) {  /* need overflow check? */
1627
65.0k
          lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1628
65.0k
          luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1629
65.0k
        }
1630
70.1k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
1631
70.1k
        break;
1632
0
      }
1633
3.38k
      case Kuint: {  /* unsigned integers */
1634
3.38k
        lua_Integer n = luaL_checkinteger(L, arg);
1635
3.38k
        if (size < SZINT)  /* need overflow check? */
1636
1.70k
          luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1637
3.38k
                           arg, "unsigned overflow");
1638
3.38k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
1639
3.38k
        break;
1640
0
      }
1641
1.45k
      case Kfloat: {  /* C float */
1642
1.45k
        float f = (float)luaL_checknumber(L, arg);  /* get argument */
1643
1.45k
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1644
        /* move 'f' to final result, correcting endianness if needed */
1645
1.45k
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1646
1.45k
        luaL_addsize(&b, size);
1647
1.45k
        break;
1648
0
      }
1649
435
      case Knumber: {  /* Lua float */
1650
435
        lua_Number f = luaL_checknumber(L, arg);  /* get argument */
1651
435
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1652
        /* move 'f' to final result, correcting endianness if needed */
1653
435
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1654
435
        luaL_addsize(&b, size);
1655
435
        break;
1656
0
      }
1657
266
      case Kdouble: {  /* C double */
1658
266
        double f = (double)luaL_checknumber(L, arg);  /* get argument */
1659
266
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1660
        /* move 'f' to final result, correcting endianness if needed */
1661
266
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1662
266
        luaL_addsize(&b, size);
1663
266
        break;
1664
0
      }
1665
183k
      case Kchar: {  /* fixed-size string */
1666
183k
        size_t len;
1667
183k
        const char *s = luaL_checklstring(L, arg, &len);
1668
183k
        luaL_argcheck(L, len <= size, arg, "string longer than given size");
1669
183k
        luaL_addlstring(&b, s, len);  /* add string */
1670
183k
        if (len < size) {  /* does it need padding? */
1671
183k
          size_t psize = size - len;  /* pad size */
1672
183k
          char *buff = luaL_prepbuffsize(&b, psize);
1673
183k
          memset(buff, LUAL_PACKPADBYTE, psize);
1674
183k
          luaL_addsize(&b, psize);
1675
183k
        }
1676
183k
        break;
1677
0
      }
1678
161k
      case Kstring: {  /* strings with length count */
1679
161k
        size_t len;
1680
161k
        const char *s = luaL_checklstring(L, arg, &len);
1681
161k
        luaL_argcheck(L, size >= sizeof(lua_Unsigned) ||
1682
161k
                         len < ((lua_Unsigned)1 << (size * NB)),
1683
161k
                         arg, "string length does not fit in given size");
1684
        /* pack length */
1685
161k
        packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0);
1686
161k
        luaL_addlstring(&b, s, len);
1687
161k
        totalsize += len;
1688
161k
        break;
1689
0
      }
1690
10
      case Kzstr: {  /* zero-terminated string */
1691
10
        size_t len;
1692
10
        const char *s = luaL_checklstring(L, arg, &len);
1693
10
        luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1694
10
        luaL_addlstring(&b, s, len);
1695
10
        luaL_addchar(&b, '\0');  /* add zero at the end */
1696
10
        totalsize += len + 1;
1697
10
        break;
1698
0
      }
1699
278k
      case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE);  /* FALLTHROUGH */
1700
1.32M
      case Kpaddalign: case Knop:
1701
1.32M
        arg--;  /* undo increment */
1702
1.32M
        break;
1703
1.76M
    }
1704
1.76M
  }
1705
407k
  luaL_pushresult(&b);
1706
407k
  return 1;
1707
432k
}
1708
1709
1710
1.90k
static int str_packsize (lua_State *L) {
1711
1.90k
  Header h;
1712
1.90k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1713
1.90k
  size_t totalsize = 0;  /* accumulate total size of result */
1714
1.90k
  initheader(L, &h);
1715
53.5k
  while (*fmt != '\0') {
1716
51.6k
    unsigned ntoalign;
1717
51.6k
    size_t size;
1718
51.6k
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1719
51.6k
    luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
1720
51.6k
                     "variable-length format");
1721
51.6k
    size += ntoalign;  /* total space used by option */
1722
51.6k
    luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,
1723
51.6k
                     1, "format result too large");
1724
51.6k
    totalsize += size;
1725
51.6k
  }
1726
1.90k
  lua_pushinteger(L, cast_st2S(totalsize));
1727
1.90k
  return 1;
1728
1.90k
}
1729
1730
1731
/*
1732
** Unpack an integer with 'size' bytes and 'islittle' endianness.
1733
** If size is smaller than the size of a Lua integer and integer
1734
** is signed, must do sign extension (propagating the sign to the
1735
** higher bits); if size is larger than the size of a Lua integer,
1736
** it must check the unread bytes to see whether they do not cause an
1737
** overflow.
1738
*/
1739
static lua_Integer unpackint (lua_State *L, const char *str,
1740
181k
                              int islittle, int size, int issigned) {
1741
181k
  lua_Unsigned res = 0;
1742
181k
  int i;
1743
181k
  int limit = (size  <= SZINT) ? size : SZINT;
1744
1.51M
  for (i = limit - 1; i >= 0; i--) {
1745
1.33M
    res <<= NB;
1746
1.33M
    res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
1747
1.33M
  }
1748
181k
  if (size < SZINT) {  /* real size smaller than lua_Integer? */
1749
19.7k
    if (issigned) {  /* needs sign extension? */
1750
6.22k
      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1751
6.22k
      res = ((res ^ mask) - mask);  /* do sign extension */
1752
6.22k
    }
1753
19.7k
  }
1754
161k
  else if (size > SZINT) {  /* must check unread bytes */
1755
14.9k
    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1756
71.3k
    for (i = limit; i < size; i++) {
1757
56.4k
      if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
1758
11.3k
        luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
1759
56.4k
    }
1760
14.9k
  }
1761
181k
  return (lua_Integer)res;
1762
181k
}
1763
1764
1765
30.9k
static int str_unpack (lua_State *L) {
1766
30.9k
  Header h;
1767
30.9k
  const char *fmt = luaL_checkstring(L, 1);
1768
30.9k
  size_t ld;
1769
30.9k
  const char *data = luaL_checklstring(L, 2, &ld);
1770
30.9k
  size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
1771
30.9k
  int n = 0;  /* number of results */
1772
30.9k
  luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1773
30.9k
  initheader(L, &h);
1774
237k
  while (*fmt != '\0') {
1775
232k
    unsigned ntoalign;
1776
232k
    size_t size;
1777
232k
    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1778
232k
    luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
1779
232k
                    "data string too short");
1780
232k
    pos += ntoalign;  /* skip alignment */
1781
    /* stack space for item + next position */
1782
232k
    luaL_checkstack(L, 2, "too many results");
1783
232k
    n++;
1784
232k
    switch (opt) {
1785
152k
      case Kint:
1786
163k
      case Kuint: {
1787
163k
        lua_Integer res = unpackint(L, data + pos, h.islittle,
1788
163k
                                       cast_int(size), (opt == Kint));
1789
163k
        lua_pushinteger(L, res);
1790
163k
        break;
1791
152k
      }
1792
3.52k
      case Kfloat: {
1793
3.52k
        float f;
1794
3.52k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1795
3.52k
        lua_pushnumber(L, (lua_Number)f);
1796
3.52k
        break;
1797
152k
      }
1798
3.73k
      case Knumber: {
1799
3.73k
        lua_Number f;
1800
3.73k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1801
3.73k
        lua_pushnumber(L, f);
1802
3.73k
        break;
1803
152k
      }
1804
3.24k
      case Kdouble: {
1805
3.24k
        double f;
1806
3.24k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1807
3.24k
        lua_pushnumber(L, (lua_Number)f);
1808
3.24k
        break;
1809
152k
      }
1810
1.27k
      case Kchar: {
1811
1.27k
        lua_pushlstring(L, data + pos, size);
1812
1.27k
        break;
1813
152k
      }
1814
18.5k
      case Kstring: {
1815
18.5k
        lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
1816
18.5k
                                          h.islittle, cast_int(size), 0);
1817
18.5k
        luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
1818
18.5k
        lua_pushlstring(L, data + pos + size, cast_sizet(len));
1819
18.5k
        pos += cast_sizet(len);  /* skip string */
1820
18.5k
        break;
1821
152k
      }
1822
929
      case Kzstr: {
1823
929
        size_t len = strlen(data + pos);
1824
929
        luaL_argcheck(L, pos + len < ld, 2,
1825
929
                         "unfinished string for format 'z'");
1826
929
        lua_pushlstring(L, data + pos, len);
1827
929
        pos += len + 1;  /* skip string plus final '\0' */
1828
929
        break;
1829
152k
      }
1830
29.0k
      case Kpaddalign: case Kpadding: case Knop:
1831
29.0k
        n--;  /* undo increment */
1832
29.0k
        break;
1833
232k
    }
1834
206k
    pos += size;
1835
206k
  }
1836
4.29k
  lua_pushinteger(L, cast_st2S(pos) + 1);  /* next position */
1837
4.29k
  return n + 1;
1838
30.9k
}
1839
1840
/* }====================================================== */
1841
1842
1843
static const luaL_Reg strlib[] = {
1844
  {"byte", str_byte},
1845
  {"char", str_char},
1846
  {"dump", str_dump},
1847
  {"find", str_find},
1848
  {"format", str_format},
1849
  {"gmatch", gmatch},
1850
  {"gsub", str_gsub},
1851
  {"len", str_len},
1852
  {"lower", str_lower},
1853
  {"match", str_match},
1854
  {"rep", str_rep},
1855
  {"reverse", str_reverse},
1856
  {"sub", str_sub},
1857
  {"upper", str_upper},
1858
  {"pack", str_pack},
1859
  {"packsize", str_packsize},
1860
  {"unpack", str_unpack},
1861
  {NULL, NULL}
1862
};
1863
1864
1865
25.3k
static void createmetatable (lua_State *L) {
1866
  /* table to be metatable for strings */
1867
25.3k
  luaL_newlibtable(L, stringmetamethods);
1868
25.3k
  luaL_setfuncs(L, stringmetamethods, 0);
1869
25.3k
  lua_pushliteral(L, "");  /* dummy string */
1870
25.3k
  lua_pushvalue(L, -2);  /* copy table */
1871
25.3k
  lua_setmetatable(L, -2);  /* set table as metatable for strings */
1872
25.3k
  lua_pop(L, 1);  /* pop dummy string */
1873
25.3k
  lua_pushvalue(L, -2);  /* get string library */
1874
25.3k
  lua_setfield(L, -2, "__index");  /* metatable.__index = string */
1875
25.3k
  lua_pop(L, 1);  /* pop metatable */
1876
25.3k
}
1877
1878
1879
/*
1880
** Open string library
1881
*/
1882
25.3k
LUAMOD_API int luaopen_string (lua_State *L) {
1883
25.3k
  luaL_newlib(L, strlib);
1884
25.3k
  createmetatable(L);
1885
25.3k
  return 1;
1886
25.3k
}
1887