Coverage Report

Created: 2025-07-18 07:03

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