Coverage Report

Created: 2025-08-29 06:37

/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
92.8M
#define LUA_MAXCAPTURES   32
37
#endif
38
39
40
9.53k
static int str_len (lua_State *L) {
41
9.53k
  size_t l;
42
9.53k
  luaL_checklstring(L, 1, &l);
43
9.53k
  lua_pushinteger(L, (lua_Integer)l);
44
9.53k
  return 1;
45
9.53k
}
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.53M
static size_t posrelatI (lua_Integer pos, size_t len) {
57
5.53M
  if (pos > 0)
58
5.23M
    return (size_t)pos;
59
296k
  else if (pos == 0)
60
109k
    return 1;
61
186k
  else if (pos < -(lua_Integer)len)  /* inverted comparison */
62
17.9k
    return 1;  /* clip to 1 */
63
168k
  else return len + (size_t)pos + 1;
64
5.53M
}
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.71M
                         size_t len) {
74
4.71M
  lua_Integer pos = luaL_optinteger(L, arg, def);
75
4.71M
  if (pos > (lua_Integer)len)
76
5.04k
    return len;
77
4.71M
  else if (pos >= 0)
78
4.45M
    return (size_t)pos;
79
251k
  else if (pos < -(lua_Integer)len)
80
2.35k
    return 0;
81
249k
  else return len + (size_t)pos + 1;
82
4.71M
}
83
84
85
4.61M
static int str_sub (lua_State *L) {
86
4.61M
  size_t l;
87
4.61M
  const char *s = luaL_checklstring(L, 1, &l);
88
4.61M
  size_t start = posrelatI(luaL_checkinteger(L, 2), l);
89
4.61M
  size_t end = getendpos(L, 3, -1, l);
90
4.61M
  if (start <= end)
91
4.42M
    lua_pushlstring(L, s + start - 1, (end - start) + 1);
92
184k
  else lua_pushliteral(L, "");
93
4.61M
  return 1;
94
4.61M
}
95
96
97
141k
static int str_reverse (lua_State *L) {
98
141k
  size_t l, i;
99
141k
  luaL_Buffer b;
100
141k
  const char *s = luaL_checklstring(L, 1, &l);
101
141k
  char *p = luaL_buffinitsize(L, &b, l);
102
1.76G
  for (i = 0; i < l; i++)
103
1.76G
    p[i] = s[l - i - 1];
104
141k
  luaL_pushresultsize(&b, l);
105
141k
  return 1;
106
141k
}
107
108
109
3.87k
static int str_lower (lua_State *L) {
110
3.87k
  size_t l;
111
3.87k
  size_t i;
112
3.87k
  luaL_Buffer b;
113
3.87k
  const char *s = luaL_checklstring(L, 1, &l);
114
3.87k
  char *p = luaL_buffinitsize(L, &b, l);
115
193k
  for (i=0; i<l; i++)
116
189k
    p[i] = cast_char(tolower(cast_uchar(s[i])));
117
3.87k
  luaL_pushresultsize(&b, l);
118
3.87k
  return 1;
119
3.87k
}
120
121
122
878k
static int str_upper (lua_State *L) {
123
878k
  size_t l;
124
878k
  size_t i;
125
878k
  luaL_Buffer b;
126
878k
  const char *s = luaL_checklstring(L, 1, &l);
127
878k
  char *p = luaL_buffinitsize(L, &b, l);
128
4.85M
  for (i=0; i<l; i++)
129
3.97M
    p[i] = cast_char(toupper(cast_uchar(s[i])));
130
878k
  luaL_pushresultsize(&b, l);
131
878k
  return 1;
132
878k
}
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
159k
static int str_rep (lua_State *L) {
140
159k
  size_t len, lsep;
141
159k
  const char *s = luaL_checklstring(L, 1, &len);
142
159k
  lua_Integer n = luaL_checkinteger(L, 2);
143
159k
  const char *sep = luaL_optlstring(L, 3, "", &lsep);
144
159k
  if (n <= 0)
145
3.61k
    lua_pushliteral(L, "");
146
155k
  else if (l_unlikely(len > MAX_SIZE - lsep ||
147
155k
               cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))
148
705
    return luaL_error(L, "resulting string too large");
149
155k
  else {
150
155k
    size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;
151
155k
    luaL_Buffer b;
152
155k
    char *p = luaL_buffinitsize(L, &b, totallen);
153
93.4M
    while (n-- > 1) {  /* first n-1 copies (followed by separator) */
154
93.3M
      memcpy(p, s, len * sizeof(char)); p += len;
155
93.3M
      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
156
357k
        memcpy(p, sep, lsep * sizeof(char)); p += lsep;
157
357k
      }
158
93.3M
    }
159
155k
    memcpy(p, s, len * sizeof(char));  /* last copy without separator */
160
155k
    luaL_pushresultsize(&b, totallen);
161
155k
  }
162
158k
  return 1;
163
159k
}
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
294k
  for (i=0; i<n; i++)
179
177k
    lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));
180
117k
  return n;
181
117k
}
182
183
184
33.9k
static int str_char (lua_State *L) {
185
33.9k
  int n = lua_gettop(L);  /* number of arguments */
186
33.9k
  int i;
187
33.9k
  luaL_Buffer b;
188
33.9k
  char *p = luaL_buffinitsize(L, &b, cast_uint(n));
189
132k
  for (i=1; i<=n; i++) {
190
98.5k
    lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
191
98.5k
    luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
192
98.5k
    p[i - 1] = cast_char(cast_uchar(c));
193
98.5k
  }
194
33.9k
  luaL_pushresultsize(&b, cast_uint(n));
195
33.9k
  return 1;
196
33.9k
}
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.93M
static int writer (lua_State *L, const void *b, size_t size, void *ud) {
212
1.93M
  struct str_Writer *state = (struct str_Writer *)ud;
213
1.93M
  if (!state->init) {
214
10.1k
    state->init = 1;
215
10.1k
    luaL_buffinit(L, &state->B);
216
10.1k
  }
217
1.93M
  if (b == NULL) {  /* finishing dump? */
218
10.1k
    luaL_pushresult(&state->B);  /* push result */
219
10.1k
    lua_replace(L, 1);  /* move it to reserved slot */
220
10.1k
  }
221
1.92M
  else
222
1.92M
    luaL_addlstring(&state->B, (const char *)b, size);
223
1.93M
  return 0;
224
1.93M
}
225
226
227
10.3k
static int str_dump (lua_State *L) {
228
10.3k
  struct str_Writer state;
229
10.3k
  int strip = lua_toboolean(L, 2);
230
10.3k
  luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
231
10.3k
                   1, "Lua function expected");
232
  /* ensure function is on the top of the stack and vacate slot 1 */
233
10.3k
  lua_pushvalue(L, 1);
234
10.3k
  state.init = 0;
235
10.3k
  lua_dump(L, writer, &state, strip);
236
10.3k
  lua_settop(L, 1);  /* leave final result on top */
237
10.3k
  return 1;
238
10.3k
}
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
1.14M
static int tonum (lua_State *L, int arg) {
260
1.14M
  if (lua_type(L, arg) == LUA_TNUMBER) {  /* already a number? */
261
452k
    lua_pushvalue(L, arg);
262
452k
    return 1;
263
452k
  }
264
690k
  else {  /* check whether it is a numerical string */
265
690k
    size_t len;
266
690k
    const char *s = lua_tolstring(L, arg, &len);
267
690k
    return (s != NULL && lua_stringtonumber(L, s) == len + 1);
268
690k
  }
269
1.14M
}
270
271
272
12.3k
static void trymt (lua_State *L, const char *mtname) {
273
12.3k
  lua_settop(L, 2);  /* back to the original arguments */
274
12.3k
  if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
275
12.3k
                 !luaL_getmetafield(L, 2, mtname)))
276
12.3k
    luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
277
12.3k
                  luaL_typename(L, -2), luaL_typename(L, -1));
278
12.3k
  lua_insert(L, -3);  /* put metamethod before arguments */
279
12.3k
  lua_call(L, 2, 1);  /* call metamethod */
280
12.3k
}
281
282
283
574k
static int arith (lua_State *L, int op, const char *mtname) {
284
574k
  if (tonum(L, 1) && tonum(L, 2))
285
562k
    lua_arith(L, op);  /* result will be on the top */
286
12.3k
  else
287
12.3k
    trymt(L, mtname);
288
574k
  return 1;
289
574k
}
290
291
292
170k
static int arith_add (lua_State *L) {
293
170k
  return arith(L, LUA_OPADD, "__add");
294
170k
}
295
296
124k
static int arith_sub (lua_State *L) {
297
124k
  return arith(L, LUA_OPSUB, "__sub");
298
124k
}
299
300
100k
static int arith_mul (lua_State *L) {
301
100k
  return arith(L, LUA_OPMUL, "__mul");
302
100k
}
303
304
78.1k
static int arith_mod (lua_State *L) {
305
78.1k
  return arith(L, LUA_OPMOD, "__mod");
306
78.1k
}
307
308
9.67k
static int arith_pow (lua_State *L) {
309
9.67k
  return arith(L, LUA_OPPOW, "__pow");
310
9.67k
}
311
312
25.7k
static int arith_div (lua_State *L) {
313
25.7k
  return arith(L, LUA_OPDIV, "__div");
314
25.7k
}
315
316
18.8k
static int arith_idiv (lua_State *L) {
317
18.8k
  return arith(L, LUA_OPIDIV, "__idiv");
318
18.8k
}
319
320
46.9k
static int arith_unm (lua_State *L) {
321
46.9k
  return arith(L, LUA_OPUNM, "__unm");
322
46.9k
}
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
300M
#define CAP_UNFINISHED  (-1)
350
10.6M
#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.22M
#define MAXCCALLS 200
374
#endif
375
376
377
282M
#define L_ESC   '%'
378
379k
#define SPECIALS  "^$*+?.([%-"
379
380
381
76.6M
static int check_capture (MatchState *ms, int l) {
382
76.6M
  l -= '1';
383
76.6M
  if (l_unlikely(l < 0 || l >= ms->level ||
384
76.6M
                 ms->capture[l].len == CAP_UNFINISHED))
385
16.8k
    return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
386
76.6M
  return l;
387
76.6M
}
388
389
390
83.4M
static int capture_to_close (MatchState *ms) {
391
83.4M
  int level = ms->level;
392
132M
  for (level--; level>=0; level--)
393
132M
    if (ms->capture[level].len == CAP_UNFINISHED) return level;
394
2.92k
  return luaL_error(ms->L, "invalid pattern capture");
395
83.4M
}
396
397
398
291M
static const char *classend (MatchState *ms, const char *p) {
399
291M
  switch (*p++) {
400
13.3M
    case L_ESC: {
401
13.3M
      if (l_unlikely(p == ms->p_end))
402
659
        luaL_error(ms->L, "malformed pattern (ends with '%%')");
403
13.3M
      return p+1;
404
0
    }
405
4.92M
    case '[': {
406
4.92M
      if (*p == '^') p++;
407
50.3M
      do {  /* look for a ']' */
408
50.3M
        if (l_unlikely(p == ms->p_end))
409
13.6k
          luaL_error(ms->L, "malformed pattern (missing ']')");
410
50.3M
        if (*(p++) == L_ESC && p < ms->p_end)
411
5.08M
          p++;  /* skip escapes (e.g. '%]') */
412
50.3M
      } while (*p != ']');
413
4.92M
      return p+1;
414
0
    }
415
273M
    default: {
416
273M
      return p;
417
0
    }
418
291M
  }
419
291M
}
420
421
422
20.9M
static int match_class (int c, int cl) {
423
20.9M
  int res;
424
20.9M
  switch (tolower(cl)) {
425
1.29M
    case 'a' : res = isalpha(c); break;
426
358
    case 'c' : res = iscntrl(c); break;
427
9.40M
    case 'd' : res = isdigit(c); break;
428
8.04k
    case 'g' : res = isgraph(c); break;
429
257
    case 'l' : res = islower(c); break;
430
3
    case 'p' : res = ispunct(c); break;
431
4.54M
    case 's' : res = isspace(c); break;
432
23
    case 'u' : res = isupper(c); break;
433
82.0k
    case 'w' : res = isalnum(c); break;
434
3.83k
    case 'x' : res = isxdigit(c); break;
435
126k
    case 'z' : res = (c == 0); break;  /* deprecated option */
436
5.50M
    default: return (cl == c);
437
20.9M
  }
438
15.4M
  return (islower(cl) ? res : !res);
439
20.9M
}
440
441
442
6.38M
static int matchbracketclass (int c, const char *p, const char *ec) {
443
6.38M
  int sig = 1;
444
6.38M
  if (*(p+1) == '^') {
445
1.44M
    sig = 0;
446
1.44M
    p++;  /* skip the '^' */
447
1.44M
  }
448
34.3M
  while (++p < ec) {
449
28.4M
    if (*p == L_ESC) {
450
4.78M
      p++;
451
4.78M
      if (match_class(c, cast_uchar(*p)))
452
52.4k
        return sig;
453
4.78M
    }
454
23.6M
    else if ((*(p+1) == '-') && (p+2 < ec)) {
455
169k
      p+=2;
456
169k
      if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
457
14.5k
        return sig;
458
169k
    }
459
23.5M
    else if (cast_uchar(*p) == c) return sig;
460
28.4M
  }
461
5.86M
  return !sig;
462
6.38M
}
463
464
465
static int singlematch (MatchState *ms, const char *s, const char *p,
466
518M
                        const char *ep) {
467
518M
  if (s >= ms->src_end)
468
2.18M
    return 0;
469
516M
  else {
470
516M
    int c = cast_uchar(*s);
471
516M
    switch (*p) {
472
173M
      case '.': return 1;  /* matches any char */
473
16.1M
      case L_ESC: return match_class(c, cast_uchar(*(p+1)));
474
6.01M
      case '[': return matchbracketclass(c, p, ep-1);
475
320M
      default:  return (cast_uchar(*p) == c);
476
516M
    }
477
516M
  }
478
518M
}
479
480
481
static const char *matchbalance (MatchState *ms, const char *s,
482
89.2k
                                   const char *p) {
483
89.2k
  if (l_unlikely(p >= ms->p_end - 1))
484
1.60k
    luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
485
89.2k
  if (*s != *p) return NULL;
486
4.96k
  else {
487
4.96k
    int b = *p;
488
4.96k
    int e = *(p+1);
489
4.96k
    int cont = 1;
490
17.5M
    while (++s < ms->src_end) {
491
17.5M
      if (*s == e) {
492
702k
        if (--cont == 0) return s+1;
493
702k
      }
494
16.8M
      else if (*s == b) cont++;
495
17.5M
    }
496
4.96k
  }
497
3.70k
  return NULL;  /* string ends out of balance */
498
89.2k
}
499
500
501
static const char *max_expand (MatchState *ms, const char *s,
502
1.32M
                                 const char *p, const char *ep) {
503
1.32M
  ptrdiff_t i = 0;  /* counts maximum expand for item */
504
166M
  while (singlematch(ms, s + i, p, ep))
505
165M
    i++;
506
  /* keeps trying to match with the maximum repetitions */
507
113M
  while (i>=0) {
508
112M
    const char *res = match(ms, (s+i), ep+1);
509
112M
    if (res) return res;
510
111M
    i--;  /* else didn't match; reduce 1 repetition to try again */
511
111M
  }
512
356k
  return NULL;
513
1.32M
}
514
515
516
static const char *min_expand (MatchState *ms, const char *s,
517
37.9k
                                 const char *p, const char *ep) {
518
60.8M
  for (;;) {
519
60.8M
    const char *res = match(ms, s, ep+1);
520
60.8M
    if (res != NULL)
521
7.37k
      return res;
522
60.8M
    else if (singlematch(ms, s, p, ep))
523
60.8M
      s++;  /* try with one more repetition */
524
30.5k
    else return NULL;
525
60.8M
  }
526
37.9k
}
527
528
529
static const char *start_capture (MatchState *ms, const char *s,
530
92.8M
                                    const char *p, int what) {
531
92.8M
  const char *res;
532
92.8M
  int level = ms->level;
533
92.8M
  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
534
92.8M
  ms->capture[level].init = s;
535
92.8M
  ms->capture[level].len = what;
536
92.8M
  ms->level = level+1;
537
92.8M
  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
538
91.3M
    ms->level--;  /* undo capture */
539
92.8M
  return res;
540
92.8M
}
541
542
543
static const char *end_capture (MatchState *ms, const char *s,
544
83.4M
                                  const char *p) {
545
83.4M
  int l = capture_to_close(ms);
546
83.4M
  const char *res;
547
83.4M
  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
548
83.4M
  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
549
82.5M
    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
550
83.4M
  return res;
551
83.4M
}
552
553
554
76.6M
static const char *match_capture (MatchState *ms, const char *s, int l) {
555
76.6M
  size_t len;
556
76.6M
  l = check_capture(ms, l);
557
76.6M
  len = cast_sizet(ms->capture[l].len);
558
76.6M
  if ((size_t)(ms->src_end-s) >= len &&
559
76.6M
      memcmp(ms->capture[l].init, s, len) == 0)
560
3.46M
    return s+len;
561
73.2M
  else return NULL;
562
76.6M
}
563
564
565
483M
static const char *match (MatchState *ms, const char *s, const char *p) {
566
483M
  if (l_unlikely(ms->matchdepth-- == 0))
567
0
    luaL_error(ms->L, "pattern too complex");
568
646M
  init: /* using goto to optimize tail recursion */
569
646M
  if (p != ms->p_end) {  /* end of pattern? */
570
642M
    switch (*p) {
571
92.8M
      case '(': {  /* start capture */
572
92.8M
        if (*(p + 1) == ')')  /* position capture? */
573
6.86M
          s = start_capture(ms, s, p + 2, CAP_POSITION);
574
86.0M
        else
575
86.0M
          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
576
92.8M
        break;
577
0
      }
578
83.4M
      case ')': {  /* end capture */
579
83.4M
        s = end_capture(ms, s, p + 1);
580
83.4M
        break;
581
0
      }
582
97.8M
      case '$': {
583
97.8M
        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
584
30.5k
          goto dflt;  /* no; go to default */
585
97.7M
        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
586
97.7M
        break;
587
97.8M
      }
588
90.4M
      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
589
90.4M
        switch (*(p + 1)) {
590
89.2k
          case 'b': {  /* balanced string? */
591
89.2k
            s = matchbalance(ms, s, p + 2);
592
89.2k
            if (s != NULL) {
593
1.26k
              p += 4; goto init;  /* return match(ms, s, p + 4); */
594
1.26k
            }  /* else fail (s == NULL) */
595
87.9k
            break;
596
89.2k
          }
597
325k
          case 'f': {  /* frontier? */
598
325k
            const char *ep; char previous;
599
325k
            p += 2;
600
325k
            if (l_unlikely(*p != '['))
601
1.09k
              luaL_error(ms->L, "missing '[' after '%%f' in pattern");
602
325k
            ep = classend(ms, p);  /* points to what is next */
603
325k
            previous = (s == ms->src_init) ? '\0' : *(s - 1);
604
325k
            if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
605
325k
               matchbracketclass(cast_uchar(*s), p, ep - 1)) {
606
21.1k
              p = ep; goto init;  /* return match(ms, s, ep); */
607
21.1k
            }
608
304k
            s = NULL;  /* match failed */
609
304k
            break;
610
325k
          }
611
48.7M
          case '0': case '1': case '2': case '3':
612
76.6M
          case '4': case '5': case '6': case '7':
613
76.6M
          case '8': case '9': {  /* capture results (%0-%9)? */
614
76.6M
            s = match_capture(ms, s, cast_uchar(*(p + 1)));
615
76.6M
            if (s != NULL) {
616
3.46M
              p += 2; goto init;  /* return match(ms, s, p + 2) */
617
3.46M
            }
618
73.2M
            break;
619
76.6M
          }
620
73.2M
          default: goto dflt;
621
90.4M
        }
622
73.5M
        break;
623
90.4M
      }
624
291M
      default: dflt: {  /* pattern class plus optional suffix */
625
291M
        const char *ep = classend(ms, p);  /* points to optional suffix */
626
        /* does not match at least once? */
627
291M
        if (!singlematch(ms, s, p, ep)) {
628
191M
          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
629
61.2M
            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
630
61.2M
          }
631
130M
          else  /* '+' or no suffix */
632
130M
            s = NULL;  /* fail */
633
191M
        }
634
99.9M
        else {  /* matched once */
635
99.9M
          switch (*ep) {  /* handle optional suffix */
636
92.7M
            case '?': {  /* optional */
637
92.7M
              const char *res;
638
92.7M
              if ((res = match(ms, s + 1, ep + 1)) != NULL)
639
6.58k
                s = res;
640
92.7M
              else {
641
92.7M
                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
642
92.7M
              }
643
6.58k
              break;
644
92.7M
            }
645
98.6k
            case '+':  /* 1 or more repetitions */
646
98.6k
              s++;  /* 1 match already done */
647
              /* FALLTHROUGH */
648
1.32M
            case '*':  /* 0 or more repetitions */
649
1.32M
              s = max_expand(ms, s, p, ep);
650
1.32M
              break;
651
37.9k
            case '-':  /* 0 or more repetitions (minimum) */
652
37.9k
              s = min_expand(ms, s, p, ep);
653
37.9k
              break;
654
5.80M
            default:  /* no suffix */
655
5.80M
              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
656
99.9M
          }
657
99.9M
        }
658
131M
        break;
659
291M
      }
660
642M
    }
661
642M
  }
662
483M
  ms->matchdepth++;
663
483M
  return s;
664
646M
}
665
666
667
668
static const char *lmemfind (const char *s1, size_t l1,
669
74.9k
                               const char *s2, size_t l2) {
670
74.9k
  if (l2 == 0) return s1;  /* empty strings are everywhere */
671
73.8k
  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
672
73.7k
  else {
673
73.7k
    const char *init;  /* to search for a '*s2' inside 's1' */
674
73.7k
    l2--;  /* 1st char will be checked by 'memchr' */
675
73.7k
    l1 = l1-l2;  /* 's2' cannot be found after that */
676
107k
    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
677
94.0k
      init++;   /* 1st char is already checked */
678
94.0k
      if (memcmp(init, s2+1, l2) == 0)
679
60.3k
        return init-1;
680
33.6k
      else {  /* correct 'l1' and 's1' to try again */
681
33.6k
        l1 -= ct_diff2sz(init - s1);
682
33.6k
        s1 = init;
683
33.6k
      }
684
94.0k
    }
685
13.3k
    return NULL;  /* not found */
686
73.7k
  }
687
74.9k
}
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
2.54M
                              const char *e, const char **cap) {
699
2.54M
  if (i >= ms->level) {
700
1.34M
    if (l_unlikely(i != 0))
701
3.10k
      luaL_error(ms->L, "invalid capture index %%%d", i + 1);
702
1.34M
    *cap = s;
703
1.34M
    return (e - s);
704
1.34M
  }
705
1.19M
  else {
706
1.19M
    ptrdiff_t capl = ms->capture[i].len;
707
1.19M
    *cap = ms->capture[i].init;
708
1.19M
    if (l_unlikely(capl == CAP_UNFINISHED))
709
1.56k
      luaL_error(ms->L, "unfinished capture");
710
1.19M
    else if (capl == CAP_POSITION)
711
286k
      lua_pushinteger(ms->L,
712
286k
          ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
713
1.19M
    return capl;
714
1.19M
  }
715
2.54M
}
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.18M
                                                    const char *e) {
723
1.18M
  const char *cap;
724
1.18M
  ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
725
1.18M
  if (l != CAP_POSITION)
726
1.17M
    lua_pushlstring(ms->L, cap, cast_sizet(l));
727
  /* else position was already pushed */
728
1.18M
}
729
730
731
1.16M
static int push_captures (MatchState *ms, const char *s, const char *e) {
732
1.16M
  int i;
733
1.16M
  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
734
1.16M
  luaL_checkstack(ms->L, nlevels, "too many captures");
735
2.34M
  for (i = 0; i < nlevels; i++)
736
1.18M
    push_onecapture(ms, i, s, e);
737
1.16M
  return nlevels;  /* number of strings pushed */
738
1.16M
}
739
740
741
/* check whether pattern has no special characters */
742
327k
static int nospecials (const char *p, size_t l) {
743
327k
  size_t upto = 0;
744
379k
  do {
745
379k
    if (strpbrk(p + upto, SPECIALS))
746
252k
      return 0;  /* pattern has a special character */
747
127k
    upto += strlen(p + upto) + 1;  /* may have more after \0 */
748
127k
  } while (upto <= l);
749
74.9k
  return 1;  /* no special chars found */
750
327k
}
751
752
753
static void prepstate (MatchState *ms, lua_State *L,
754
2.22M
                       const char *s, size_t ls, const char *p, size_t lp) {
755
2.22M
  ms->L = L;
756
2.22M
  ms->matchdepth = MAXCCALLS;
757
2.22M
  ms->src_init = s;
758
2.22M
  ms->src_end = s + ls;
759
2.22M
  ms->p_end = p + lp;
760
2.22M
}
761
762
763
40.4M
static void reprepstate (MatchState *ms) {
764
40.4M
  ms->level = 0;
765
40.4M
  lua_assert(ms->matchdepth == MAXCCALLS);
766
40.4M
}
767
768
769
531k
static int str_find_aux (lua_State *L, int find) {
770
531k
  size_t ls, lp;
771
531k
  const char *s = luaL_checklstring(L, 1, &ls);
772
531k
  const char *p = luaL_checklstring(L, 2, &lp);
773
531k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
774
531k
  if (init > ls) {  /* start after string's end? */
775
169k
    luaL_pushfail(L);  /* cannot find anything */
776
169k
    return 1;
777
169k
  }
778
  /* explicit request or no special characters? */
779
361k
  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
780
    /* do a plain search */
781
74.9k
    const char *s2 = lmemfind(s + init, ls - init, p, lp);
782
74.9k
    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
74.9k
  }
788
286k
  else {
789
286k
    MatchState ms;
790
286k
    const char *s1 = s + init;
791
286k
    int anchor = (*p == '^');
792
286k
    if (anchor) {
793
5.62k
      p++; lp--;  /* skip anchor character */
794
5.62k
    }
795
286k
    prepstate(&ms, L, s, ls, p, lp);
796
18.4M
    do {
797
18.4M
      const char *res;
798
18.4M
      reprepstate(&ms);
799
18.4M
      if ((res=match(&ms, s1, p)) != NULL) {
800
12.4k
        if (find) {
801
3.37k
          lua_pushinteger(L, ct_diff2S(s1 - s) + 1);  /* start */
802
3.37k
          lua_pushinteger(L, ct_diff2S(res - s));   /* end */
803
3.37k
          return push_captures(&ms, NULL, 0) + 2;
804
3.37k
        }
805
9.05k
        else
806
9.05k
          return push_captures(&ms, s1, res);
807
12.4k
      }
808
18.4M
    } while (s1++ < ms.src_end && !anchor);
809
286k
  }
810
287k
  luaL_pushfail(L);  /* not found */
811
287k
  return 1;
812
361k
}
813
814
815
350k
static int str_find (lua_State *L) {
816
350k
  return str_find_aux(L, 1);
817
350k
}
818
819
820
181k
static int str_match (lua_State *L) {
821
181k
  return str_find_aux(L, 0);
822
181k
}
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
182k
static int gmatch_aux (lua_State *L) {
835
182k
  GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
836
182k
  const char *src;
837
182k
  gm->ms.L = L;
838
3.73M
  for (src = gm->src; src <= gm->ms.src_end; src++) {
839
3.56M
    const char *e;
840
3.56M
    reprepstate(&gm->ms);
841
3.56M
    if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
842
14.9k
      gm->src = gm->lastmatch = e;
843
14.9k
      return push_captures(&gm->ms, src, e);
844
14.9k
    }
845
3.56M
  }
846
167k
  return 0;  /* not found */
847
182k
}
848
849
850
258k
static int gmatch (lua_State *L) {
851
258k
  size_t ls, lp;
852
258k
  const char *s = luaL_checklstring(L, 1, &ls);
853
258k
  const char *p = luaL_checklstring(L, 2, &lp);
854
258k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
855
258k
  GMatchState *gm;
856
258k
  lua_settop(L, 2);  /* keep strings on closure to avoid being collected */
857
258k
  gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
858
258k
  if (init > ls)  /* start after string's end? */
859
4.07k
    init = ls + 1;  /* avoid overflows in 's + init' */
860
258k
  prepstate(&gm->ms, L, s, ls, p, lp);
861
258k
  gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
862
258k
  lua_pushcclosure(L, gmatch_aux, 3);
863
258k
  return 1;
864
258k
}
865
866
867
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
868
1.37M
                                                   const char *e) {
869
1.37M
  size_t l;
870
1.37M
  lua_State *L = ms->L;
871
1.37M
  const char *news = lua_tolstring(L, 3, &l);
872
1.37M
  const char *p;
873
5.29M
  while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
874
3.91M
    luaL_addlstring(b, news, ct_diff2sz(p - news));
875
3.91M
    p++;  /* skip ESC */
876
3.91M
    if (*p == L_ESC)  /* '%%' */
877
1.52M
      luaL_addchar(b, *p);
878
2.39M
    else if (*p == '0')  /* '%0' */
879
1.02M
        luaL_addlstring(b, s, ct_diff2sz(e - s));
880
1.36M
    else if (isdigit(cast_uchar(*p))) {  /* '%n' */
881
1.35M
      const char *cap;
882
1.35M
      ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
883
1.35M
      if (resl == CAP_POSITION)
884
273k
        luaL_addvalue(b);  /* add position to accumulated result */
885
1.08M
      else
886
1.08M
        luaL_addlstring(b, cap, cast_sizet(resl));
887
1.35M
    }
888
1.25k
    else
889
1.25k
      luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
890
3.91M
    l -= ct_diff2sz(p + 1 - news);
891
3.91M
    news = p + 1;
892
3.91M
  }
893
1.37M
  luaL_addlstring(b, news, l);
894
1.37M
}
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.51M
                                      const char *e, int tr) {
904
2.51M
  lua_State *L = ms->L;
905
2.51M
  switch (tr) {
906
1.13M
    case LUA_TFUNCTION: {  /* call the function */
907
1.13M
      int n;
908
1.13M
      lua_pushvalue(L, 3);  /* push the function */
909
1.13M
      n = push_captures(ms, s, e);  /* all captures as arguments */
910
1.13M
      lua_call(L, n, 1);  /* call it */
911
1.13M
      break;
912
0
    }
913
3.25k
    case LUA_TTABLE: {  /* index the table */
914
3.25k
      push_onecapture(ms, 0, s, e);  /* first capture is the index */
915
3.25k
      lua_gettable(L, 3);
916
3.25k
      break;
917
0
    }
918
1.37M
    default: {  /* LUA_TNUMBER or LUA_TSTRING */
919
1.37M
      add_s(ms, b, s, e);  /* add value to the buffer */
920
1.37M
      return 1;  /* something changed */
921
0
    }
922
2.51M
  }
923
1.14M
  if (!lua_toboolean(L, -1)) {  /* nil or false? */
924
12.1k
    lua_pop(L, 1);  /* remove value */
925
12.1k
    luaL_addlstring(b, s, ct_diff2sz(e - s));  /* keep original text */
926
12.1k
    return 0;  /* no changes */
927
12.1k
  }
928
1.12M
  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.12M
  else {
932
1.12M
    luaL_addvalue(b);  /* add result to accumulator */
933
1.12M
    return 1;  /* something changed */
934
1.12M
  }
935
1.14M
}
936
937
938
1.68M
static int str_gsub (lua_State *L) {
939
1.68M
  size_t srcl, lp;
940
1.68M
  const char *src = luaL_checklstring(L, 1, &srcl);  /* subject */
941
1.68M
  const char *p = luaL_checklstring(L, 2, &lp);  /* pattern */
942
1.68M
  const char *lastmatch = NULL;  /* end of last match */
943
1.68M
  int tr = lua_type(L, 3);  /* replacement type */
944
  /* max replacements */
945
1.68M
  lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
946
1.68M
  int anchor = (*p == '^');
947
1.68M
  lua_Integer n = 0;  /* replacement count */
948
1.68M
  int changed = 0;  /* change flag */
949
1.68M
  MatchState ms;
950
1.68M
  luaL_Buffer b;
951
1.68M
  luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
952
1.68M
                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
953
1.68M
                      "string/function/table");
954
1.68M
  luaL_buffinit(L, &b);
955
1.68M
  if (anchor) {
956
6.23k
    p++; lp--;  /* skip anchor character */
957
6.23k
  }
958
1.68M
  prepstate(&ms, L, src, srcl, p, lp);
959
18.3M
  while (n < max_s) {
960
18.3M
    const char *e;
961
18.3M
    reprepstate(&ms);  /* (re)prepare state for new match */
962
18.3M
    if ((e = match(&ms, src, p)) != NULL && e != lastmatch) {  /* match? */
963
2.51M
      n++;
964
2.51M
      changed = add_value(&ms, &b, src, e, tr) | changed;
965
2.51M
      src = lastmatch = e;
966
2.51M
    }
967
15.8M
    else if (src < ms.src_end)  /* otherwise, skip one character */
968
14.1M
      luaL_addchar(&b, *src++);
969
1.66M
    else break;  /* end of subject */
970
16.7M
    if (anchor) break;
971
16.7M
  }
972
1.68M
  if (!changed)  /* no changes? */
973
744k
    lua_pushvalue(L, 1);  /* return original string */
974
942k
  else {  /* something changed */
975
942k
    luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));
976
942k
    luaL_pushresult(&b);  /* create and return new string */
977
942k
  }
978
1.68M
  lua_pushinteger(L, n);  /* number of substitutions */
979
1.68M
  return 2;
980
1.68M
}
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.48k
#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
1.16M
#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.91M
#define L_FMTFLAGSF "-+#0 "
1094
1095
/* valid flags for o, x, and X conversions */
1096
11.6k
#define L_FMTFLAGSX "-#0"
1097
1098
/* valid flags for d and i conversions */
1099
19.4k
#define L_FMTFLAGSI "-+0 "
1100
1101
/* valid flags for u conversions */
1102
7.81k
#define L_FMTFLAGSU "-0"
1103
1104
/* valid flags for c, p, and s conversions */
1105
61.9k
#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
1.12M
#define MAX_FORMAT  32
1117
1118
1119
15.9k
static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
1120
15.9k
  luaL_addchar(b, '"');
1121
35.0M
  while (len--) {
1122
35.0M
    if (*s == '"' || *s == '\\' || *s == '\n') {
1123
1.69M
      luaL_addchar(b, '\\');
1124
1.69M
      luaL_addchar(b, *s);
1125
1.69M
    }
1126
33.3M
    else if (iscntrl(cast_uchar(*s))) {
1127
2.28M
      char buff[10];
1128
2.28M
      if (!isdigit(cast_uchar(*(s+1))))
1129
2.27M
        l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
1130
11.7k
      else
1131
11.7k
        l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s));
1132
2.28M
      luaL_addstring(b, buff);
1133
2.28M
    }
1134
31.0M
    else
1135
31.0M
      luaL_addchar(b, *s);
1136
35.0M
    s++;
1137
35.0M
  }
1138
15.9k
  luaL_addchar(b, '"');
1139
15.9k
}
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
16.8k
static int quotefloat (lua_State *L, char *buff, lua_Number n) {
1149
16.8k
  const char *s;  /* for the fixed representations */
1150
16.8k
  if (n == (lua_Number)HUGE_VAL)  /* inf? */
1151
9.16k
    s = "1e9999";
1152
7.72k
  else if (n == -(lua_Number)HUGE_VAL)  /* -inf? */
1153
318
    s = "-1e9999";
1154
7.40k
  else if (n != n)  /* NaN? */
1155
3.45k
    s = "(0/0)";
1156
3.94k
  else {  /* format number as hexadecimal */
1157
3.94k
    int  nb = lua_number2strx(L, buff, MAX_ITEM,
1158
3.94k
                                 "%" LUA_NUMBER_FRMLEN "a", n);
1159
    /* ensures that 'buff' string uses a dot as the radix character */
1160
3.94k
    if (memchr(buff, '.', cast_uint(nb)) == NULL) {  /* no dot? */
1161
3.79k
      char point = lua_getlocaledecpoint();  /* try locale point */
1162
3.79k
      char *ppoint = (char *)memchr(buff, point, cast_uint(nb));
1163
3.79k
      if (ppoint) *ppoint = '.';  /* change it to a dot */
1164
3.79k
    }
1165
3.94k
    return nb;
1166
3.94k
  }
1167
  /* for the fixed representations */
1168
12.9k
  return l_sprintf(buff, MAX_ITEM, "%s", s);
1169
16.8k
}
1170
1171
1172
35.4k
static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
1173
35.4k
  switch (lua_type(L, arg)) {
1174
15.9k
    case LUA_TSTRING: {
1175
15.9k
      size_t len;
1176
15.9k
      const char *s = lua_tolstring(L, arg, &len);
1177
15.9k
      addquoted(b, s, len);
1178
15.9k
      break;
1179
0
    }
1180
17.0k
    case LUA_TNUMBER: {
1181
17.0k
      char *buff = luaL_prepbuffsize(b, MAX_ITEM);
1182
17.0k
      int nb;
1183
17.0k
      if (!lua_isinteger(L, arg))  /* float? */
1184
16.8k
        nb = quotefloat(L, buff, lua_tonumber(L, arg));
1185
195
      else {  /* integers */
1186
195
        lua_Integer n = lua_tointeger(L, arg);
1187
195
        const char *format = (n == LUA_MININTEGER)  /* corner case? */
1188
195
                           ? "0x%" LUA_INTEGER_FRMLEN "x"  /* use hex */
1189
195
                           : LUA_INTEGER_FMT;  /* else use default format */
1190
195
        nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
1191
195
      }
1192
17.0k
      luaL_addsize(b, cast_uint(nb));
1193
17.0k
      break;
1194
0
    }
1195
2.36k
    case LUA_TNIL: case LUA_TBOOLEAN: {
1196
2.36k
      luaL_tolstring(L, arg, NULL);
1197
2.36k
      luaL_addvalue(b);
1198
2.36k
      break;
1199
839
    }
1200
0
    default: {
1201
0
      luaL_argerror(L, arg, "value has no literal form");
1202
0
    }
1203
35.4k
  }
1204
35.4k
}
1205
1206
1207
1.49M
static const char *get2digits (const char *s) {
1208
1.49M
  if (isdigit(cast_uchar(*s))) {
1209
672k
    s++;
1210
672k
    if (isdigit(cast_uchar(*s))) s++;  /* (2 digits at most) */
1211
672k
  }
1212
1.49M
  return s;
1213
1.49M
}
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
866k
                                       int precision) {
1224
866k
  const char *spec = form + 1;  /* skip '%' */
1225
866k
  spec += strspn(spec, flags);  /* skip flags */
1226
866k
  if (*spec != '0') {  /* a width cannot start with '0' */
1227
855k
    spec = get2digits(spec);  /* skip width */
1228
855k
    if (*spec == '.' && precision) {
1229
636k
      spec++;
1230
636k
      spec = get2digits(spec);  /* skip precision */
1231
636k
    }
1232
855k
  }
1233
866k
  if (!isalpha(cast_uchar(*spec)))  /* did not go to the end? */
1234
17.4k
    luaL_error(L, "invalid conversion specification: '%s'", form);
1235
866k
}
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
1.12M
                                            char *form) {
1244
  /* spans flags, width, and precision ('0' is included as a flag) */
1245
1.12M
  size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
1246
1.12M
  len++;  /* adds following character (should be the specifier) */
1247
  /* still needs space for '%', '\0', plus a length modifier */
1248
1.12M
  if (len >= MAX_FORMAT - 10)
1249
12.5k
    luaL_error(L, "invalid format (too long)");
1250
1.12M
  *(form++) = '%';
1251
1.12M
  memcpy(form, strfrmt, len * sizeof(char));
1252
1.12M
  *(form + len) = '\0';
1253
1.12M
  return strfrmt + len - 1;
1254
1.12M
}
1255
1256
1257
/*
1258
** add length modifier into formats
1259
*/
1260
804k
static void addlenmod (char *form, const char *lenmod) {
1261
804k
  size_t l = strlen(form);
1262
804k
  size_t lm = strlen(lenmod);
1263
804k
  char spec = form[l - 1];
1264
804k
  strcpy(form + l - 1, lenmod);
1265
804k
  form[l + lm - 1] = spec;
1266
804k
  form[l + lm] = '\0';
1267
804k
}
1268
1269
1270
1.26M
static int str_format (lua_State *L) {
1271
1.26M
  int top = lua_gettop(L);
1272
1.26M
  int arg = 1;
1273
1.26M
  size_t sfl;
1274
1.26M
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
1275
1.26M
  const char *strfrmt_end = strfrmt+sfl;
1276
1.26M
  const char *flags;
1277
1.26M
  luaL_Buffer b;
1278
1.26M
  luaL_buffinit(L, &b);
1279
24.0M
  while (strfrmt < strfrmt_end) {
1280
22.9M
    if (*strfrmt != L_ESC)
1281
21.6M
      luaL_addchar(&b, *strfrmt++);
1282
1.31M
    else if (*++strfrmt == L_ESC)
1283
164k
      luaL_addchar(&b, *strfrmt++);  /* %% */
1284
1.14M
    else { /* format item */
1285
1.14M
      char form[MAX_FORMAT];  /* to store the format ('%...') */
1286
1.14M
      unsigned maxitem = MAX_ITEM;  /* maximum length for the result */
1287
1.14M
      char *buff = luaL_prepbuffsize(&b, maxitem);  /* to put result */
1288
1.14M
      int nb = 0;  /* number of bytes in result */
1289
1.14M
      if (++arg > top)
1290
27.8k
        return luaL_argerror(L, arg, "no value");
1291
1.12M
      strfrmt = getformat(L, strfrmt, form);
1292
1.12M
      switch (*strfrmt++) {
1293
17.9k
        case 'c': {
1294
17.9k
          checkformat(L, form, L_FMTFLAGSC, 0);
1295
17.9k
          nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
1296
17.9k
          break;
1297
0
        }
1298
19.4k
        case 'd': case 'i':
1299
19.4k
          flags = L_FMTFLAGSI;
1300
19.4k
          goto intcase;
1301
7.81k
        case 'u':
1302
7.81k
          flags = L_FMTFLAGSU;
1303
7.81k
          goto intcase;
1304
11.6k
        case 'o': case 'x': case 'X':
1305
11.6k
          flags = L_FMTFLAGSX;
1306
38.9k
         intcase: {
1307
38.9k
          lua_Integer n = luaL_checkinteger(L, arg);
1308
38.9k
          checkformat(L, form, flags, 1);
1309
38.9k
          addlenmod(form, LUA_INTEGER_FRMLEN);
1310
38.9k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
1311
38.9k
          break;
1312
11.6k
        }
1313
153k
        case 'a': case 'A':
1314
153k
          checkformat(L, form, L_FMTFLAGSF, 1);
1315
153k
          addlenmod(form, LUA_NUMBER_FRMLEN);
1316
153k
          nb = lua_number2strx(L, buff, maxitem, form,
1317
153k
                                  luaL_checknumber(L, arg));
1318
153k
          break;
1319
3.48k
        case 'f':
1320
3.48k
          maxitem = MAX_ITEMF;  /* extra space for '%f' */
1321
3.48k
          buff = luaL_prepbuffsize(&b, maxitem);
1322
          /* FALLTHROUGH */
1323
637k
        case 'e': case 'E': case 'g': case 'G': {
1324
637k
          lua_Number n = luaL_checknumber(L, arg);
1325
637k
          checkformat(L, form, L_FMTFLAGSF, 1);
1326
637k
          addlenmod(form, LUA_NUMBER_FRMLEN);
1327
637k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
1328
637k
          break;
1329
636k
        }
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
367
            p = "(null)";  /* result */
1335
367
            form[strlen(form) - 1] = 's';  /* format it as a string */
1336
367
          }
1337
11.8k
          nb = l_sprintf(buff, maxitem, form, p);
1338
11.8k
          break;
1339
636k
        }
1340
35.4k
        case 'q': {
1341
35.4k
          if (form[2] != '\0')  /* modifiers? */
1342
36
            return luaL_error(L, "specifier '%%q' cannot have modifiers");
1343
35.4k
          addliteral(L, &b, arg);
1344
35.4k
          break;
1345
35.4k
        }
1346
204k
        case 's': {
1347
204k
          size_t l;
1348
204k
          const char *s = luaL_tolstring(L, arg, &l);
1349
204k
          if (form[2] == '\0')  /* no modifiers? */
1350
171k
            luaL_addvalue(&b);  /* keep entire string */
1351
32.1k
          else {
1352
32.1k
            luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
1353
32.1k
            checkformat(L, form, L_FMTFLAGSC, 1);
1354
32.1k
            if (strchr(form, '.') == NULL && l >= 100) {
1355
              /* no precision and string is too long to be formatted */
1356
7.49k
              luaL_addvalue(&b);  /* keep entire string */
1357
7.49k
            }
1358
24.6k
            else {  /* format the string into 'buff' */
1359
24.6k
              nb = l_sprintf(buff, maxitem, form, s);
1360
24.6k
              lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
1361
24.6k
            }
1362
32.1k
          }
1363
204k
          break;
1364
35.4k
        }
1365
10.3k
        default: {  /* also treat cases 'pnLlh' */
1366
10.3k
          return luaL_error(L, "invalid conversion '%s' to 'format'", form);
1367
35.4k
        }
1368
1.12M
      }
1369
1.03M
      lua_assert(cast_uint(nb) < maxitem);
1370
1.03M
      luaL_addsize(&b, cast_uint(nb));
1371
1.03M
    }
1372
22.9M
  }
1373
1.15M
  luaL_pushresult(&b);
1374
1.15M
  return 1;
1375
1.26M
}
1376
1377
/* }====================================================== */
1378
1379
1380
/*
1381
** {======================================================
1382
** PACK/UNPACK
1383
** =======================================================
1384
*/
1385
1386
1387
/* value used for padding */
1388
#if !defined(LUAL_PACKPADBYTE)
1389
186k
#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.01M
#define NB  CHAR_BIT
1397
1398
/* mask for one character (NB 1's) */
1399
1.43M
#define MC  ((1 << NB) - 1)
1400
1401
/* size of a lua_Integer */
1402
601k
#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.51M
static int digit (int c) { return '0' <= c && c <= '9'; }
1445
1446
609k
static size_t getnum (const char **fmt, size_t df) {
1447
609k
  if (!digit(**fmt))  /* no number? */
1448
387k
    return df;  /* return default value */
1449
222k
  else {
1450
222k
    size_t a = 0;
1451
906k
    do {
1452
906k
      a = a*10 + cast_uint(*((*fmt)++) - '0');
1453
906k
    } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);
1454
222k
    return a;
1455
222k
  }
1456
609k
}
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
420k
static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
1464
420k
  size_t sz = getnum(fmt, df);
1465
420k
  if (l_unlikely((sz - 1u) >= MAXINTSIZE))
1466
7.64k
    return cast_uint(luaL_error(h->L,
1467
413k
               "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
1468
413k
  return cast_uint(sz);
1469
420k
}
1470
1471
1472
/*
1473
** Initialize Header
1474
*/
1475
478k
static void initheader (lua_State *L, Header *h) {
1476
478k
  h->L = L;
1477
478k
  h->islittle = nativeendian.little;
1478
478k
  h->maxalign = 1;
1479
478k
}
1480
1481
1482
/*
1483
** Read and classify next option. 'size' is filled with option's size.
1484
*/
1485
2.24M
static KOption getoption (Header *h, const char **fmt, size_t *size) {
1486
  /* dummy structure to get native alignment requirements */
1487
2.24M
  struct cD { char c; union { LUAI_MAXALIGN; } u; };
1488
2.24M
  int opt = *((*fmt)++);
1489
2.24M
  *size = 0;  /* default */
1490
2.24M
  switch (opt) {
1491
3.19k
    case 'b': *size = sizeof(char); return Kint;
1492
8.28k
    case 'B': *size = sizeof(char); return Kuint;
1493
60.7k
    case 'h': *size = sizeof(short); return Kint;
1494
1.12k
    case 'H': *size = sizeof(short); return Kuint;
1495
151k
    case 'l': *size = sizeof(long); return Kint;
1496
15.9k
    case 'L': *size = sizeof(long); return Kuint;
1497
202k
    case 'j': *size = sizeof(lua_Integer); return Kint;
1498
466
    case 'J': *size = sizeof(lua_Integer); return Kuint;
1499
1
    case 'T': *size = sizeof(size_t); return Kuint;
1500
5.58k
    case 'f': *size = sizeof(float); return Kfloat;
1501
6.81k
    case 'n': *size = sizeof(lua_Number); return Knumber;
1502
5.40k
    case 'd': *size = sizeof(double); return Kdouble;
1503
19.7k
    case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1504
5.37k
    case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1505
179k
    case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1506
189k
    case 'c':
1507
189k
      *size = getnum(fmt, cast_sizet(-1));
1508
189k
      if (l_unlikely(*size == cast_sizet(-1)))
1509
145
        luaL_error(h->L, "missing size for format option 'c'");
1510
189k
      return Kchar;
1511
952
    case 'z': return Kzstr;
1512
277k
    case 'x': *size = 1; return Kpadding;
1513
186k
    case 'X': return Kpaddalign;
1514
26.9k
    case ' ': break;
1515
81.4k
    case '<': h->islittle = 1; break;
1516
582k
    case '>': h->islittle = 0; break;
1517
5.39k
    case '=': h->islittle = nativeendian.little; break;
1518
215k
    case '!': {
1519
215k
      const size_t maxalign = offsetof(struct cD, u);
1520
215k
      h->maxalign = getnumlimit(h, fmt, maxalign);
1521
215k
      break;
1522
0
    }
1523
10.1k
    default: luaL_error(h->L, "invalid format option '%c'", opt);
1524
2.24M
  }
1525
911k
  return Knop;
1526
2.24M
}
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.05M
                           size_t *psize, unsigned *ntoalign) {
1540
2.05M
  KOption opt = getoption(h, fmt, psize);
1541
2.05M
  size_t align = *psize;  /* usually, alignment follows size */
1542
2.05M
  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
1543
186k
    if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1544
1.32k
      luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1545
186k
  }
1546
2.05M
  if (align <= 1 || opt == Kchar)  /* need no alignment? */
1547
1.39M
    *ntoalign = 0;
1548
664k
  else {
1549
664k
    if (align > h->maxalign)  /* enforce maximum alignment */
1550
309k
      align = h->maxalign;
1551
664k
    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
663k
    else {
1556
      /* 'szmoda' = totalsize % align */
1557
663k
      unsigned szmoda = cast_uint(totalsize & (align - 1));
1558
663k
      *ntoalign = cast_uint((align - szmoda) & (align - 1));
1559
663k
    }
1560
664k
  }
1561
2.05M
  return opt;
1562
2.05M
}
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
225k
                     int islittle, unsigned size, int neg) {
1573
225k
  char *buff = luaL_prepbuffsize(b, size);
1574
225k
  unsigned i;
1575
225k
  buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */
1576
1.43M
  for (i = 1; i < size; i++) {
1577
1.20M
    n >>= NB;
1578
1.20M
    buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1579
1.20M
  }
1580
225k
  if (neg && size > SZINT) {  /* negative number need sign extension? */
1581
325
    for (i = SZINT; i < size; i++)  /* correct extra bytes */
1582
257
      buff[islittle ? i : size - 1 - i] = (char)MC;
1583
68
  }
1584
225k
  luaL_addsize(b, size);  /* add result to buffer */
1585
225k
}
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
13.0k
                            unsigned size, int islittle) {
1594
13.0k
  if (islittle == nativeendian.little)
1595
4.96k
    memcpy(dest, src, size);
1596
8.10k
  else {
1597
8.10k
    dest += size - 1;
1598
55.2k
    while (size-- != 0)
1599
47.1k
      *(dest--) = *(src++);
1600
8.10k
  }
1601
13.0k
}
1602
1603
1604
447k
static int str_pack (lua_State *L) {
1605
447k
  luaL_Buffer b;
1606
447k
  Header h;
1607
447k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1608
447k
  int arg = 1;  /* current argument to pack */
1609
447k
  size_t totalsize = 0;  /* accumulate total size of result */
1610
447k
  initheader(L, &h);
1611
447k
  lua_pushnil(L);  /* mark to separate arguments from string buffer */
1612
447k
  luaL_buffinit(L, &b);
1613
2.19M
  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.67M
    while (ntoalign-- > 0)
1621
1.90M
     luaL_addchar(&b, LUAL_PACKPADBYTE);  /* fill alignment */
1622
1.76M
    arg++;
1623
1.76M
    switch (opt) {
1624
67.7k
      case Kint: {  /* signed integers */
1625
67.7k
        lua_Integer n = luaL_checkinteger(L, arg);
1626
67.7k
        if (size < SZINT) {  /* need overflow check? */
1627
62.3k
          lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1628
62.3k
          luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1629
62.3k
        }
1630
67.7k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
1631
67.7k
        break;
1632
0
      }
1633
2.41k
      case Kuint: {  /* unsigned integers */
1634
2.41k
        lua_Integer n = luaL_checkinteger(L, arg);
1635
2.41k
        if (size < SZINT)  /* need overflow check? */
1636
1.66k
          luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1637
2.41k
                           arg, "unsigned overflow");
1638
2.41k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
1639
2.41k
        break;
1640
0
      }
1641
1.56k
      case Kfloat: {  /* C float */
1642
1.56k
        float f = (float)luaL_checknumber(L, arg);  /* get argument */
1643
1.56k
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1644
        /* move 'f' to final result, correcting endianness if needed */
1645
1.56k
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1646
1.56k
        luaL_addsize(&b, size);
1647
1.56k
        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
273
      case Kdouble: {  /* C double */
1658
273
        double f = (double)luaL_checknumber(L, arg);  /* get argument */
1659
273
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1660
        /* move 'f' to final result, correcting endianness if needed */
1661
273
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1662
273
        luaL_addsize(&b, size);
1663
273
        break;
1664
0
      }
1665
187k
      case Kchar: {  /* fixed-size string */
1666
187k
        size_t len;
1667
187k
        const char *s = luaL_checklstring(L, arg, &len);
1668
187k
        luaL_argcheck(L, len <= size, arg, "string longer than given size");
1669
187k
        luaL_addlstring(&b, s, len);  /* add string */
1670
187k
        if (len < size) {  /* does it need padding? */
1671
186k
          size_t psize = size - len;  /* pad size */
1672
186k
          char *buff = luaL_prepbuffsize(&b, psize);
1673
186k
          memset(buff, LUAL_PACKPADBYTE, psize);
1674
186k
          luaL_addsize(&b, psize);
1675
186k
        }
1676
187k
        break;
1677
0
      }
1678
160k
      case Kstring: {  /* strings with length count */
1679
160k
        size_t len;
1680
160k
        const char *s = luaL_checklstring(L, arg, &len);
1681
160k
        luaL_argcheck(L, size >= sizeof(lua_Unsigned) ||
1682
160k
                         len < ((lua_Unsigned)1 << (size * NB)),
1683
160k
                         arg, "string length does not fit in given size");
1684
        /* pack length */
1685
160k
        packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0);
1686
160k
        luaL_addlstring(&b, s, len);
1687
160k
        totalsize += len;
1688
160k
        break;
1689
0
      }
1690
13
      case Kzstr: {  /* zero-terminated string */
1691
13
        size_t len;
1692
13
        const char *s = luaL_checklstring(L, arg, &len);
1693
13
        luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1694
13
        luaL_addlstring(&b, s, len);
1695
13
        luaL_addchar(&b, '\0');  /* add zero at the end */
1696
13
        totalsize += len + 1;
1697
13
        break;
1698
0
      }
1699
275k
      case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE);  /* FALLTHROUGH */
1700
1.33M
      case Kpaddalign: case Knop:
1701
1.33M
        arg--;  /* undo increment */
1702
1.33M
        break;
1703
1.76M
    }
1704
1.76M
  }
1705
430k
  luaL_pushresult(&b);
1706
430k
  return 1;
1707
447k
}
1708
1709
1710
2.43k
static int str_packsize (lua_State *L) {
1711
2.43k
  Header h;
1712
2.43k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1713
2.43k
  size_t totalsize = 0;  /* accumulate total size of result */
1714
2.43k
  initheader(L, &h);
1715
58.5k
  while (*fmt != '\0') {
1716
56.0k
    unsigned ntoalign;
1717
56.0k
    size_t size;
1718
56.0k
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1719
56.0k
    luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
1720
56.0k
                     "variable-length format");
1721
56.0k
    size += ntoalign;  /* total space used by option */
1722
56.0k
    luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,
1723
56.0k
                     1, "format result too large");
1724
56.0k
    totalsize += size;
1725
56.0k
  }
1726
2.43k
  lua_pushinteger(L, cast_st2S(totalsize));
1727
2.43k
  return 1;
1728
2.43k
}
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
179k
                              int islittle, int size, int issigned) {
1741
179k
  lua_Unsigned res = 0;
1742
179k
  int i;
1743
179k
  int limit = (size  <= SZINT) ? size : SZINT;
1744
1.49M
  for (i = limit - 1; i >= 0; i--) {
1745
1.31M
    res <<= NB;
1746
1.31M
    res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
1747
1.31M
  }
1748
179k
  if (size < SZINT) {  /* real size smaller than lua_Integer? */
1749
19.7k
    if (issigned) {  /* needs sign extension? */
1750
6.92k
      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1751
6.92k
      res = ((res ^ mask) - mask);  /* do sign extension */
1752
6.92k
    }
1753
19.7k
  }
1754
159k
  else if (size > SZINT) {  /* must check unread bytes */
1755
13.0k
    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1756
59.0k
    for (i = limit; i < size; i++) {
1757
45.9k
      if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
1758
10.4k
        luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
1759
45.9k
    }
1760
13.0k
  }
1761
179k
  return (lua_Integer)res;
1762
179k
}
1763
1764
1765
29.4k
static int str_unpack (lua_State *L) {
1766
29.4k
  Header h;
1767
29.4k
  const char *fmt = luaL_checkstring(L, 1);
1768
29.4k
  size_t ld;
1769
29.4k
  const char *data = luaL_checklstring(L, 2, &ld);
1770
29.4k
  size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
1771
29.4k
  int n = 0;  /* number of results */
1772
29.4k
  luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1773
29.4k
  initheader(L, &h);
1774
238k
  while (*fmt != '\0') {
1775
233k
    unsigned ntoalign;
1776
233k
    size_t size;
1777
233k
    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1778
233k
    luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
1779
233k
                    "data string too short");
1780
233k
    pos += ntoalign;  /* skip alignment */
1781
    /* stack space for item + next position */
1782
233k
    luaL_checkstack(L, 2, "too many results");
1783
233k
    n++;
1784
233k
    switch (opt) {
1785
153k
      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
153k
      }
1792
3.74k
      case Kfloat: {
1793
3.74k
        float f;
1794
3.74k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1795
3.74k
        lua_pushnumber(L, (lua_Number)f);
1796
3.74k
        break;
1797
153k
      }
1798
3.82k
      case Knumber: {
1799
3.82k
        lua_Number f;
1800
3.82k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1801
3.82k
        lua_pushnumber(L, f);
1802
3.82k
        break;
1803
153k
      }
1804
3.26k
      case Kdouble: {
1805
3.26k
        double f;
1806
3.26k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1807
3.26k
        lua_pushnumber(L, (lua_Number)f);
1808
3.26k
        break;
1809
153k
      }
1810
1.29k
      case Kchar: {
1811
1.29k
        lua_pushlstring(L, data + pos, size);
1812
1.29k
        break;
1813
153k
      }
1814
15.3k
      case Kstring: {
1815
15.3k
        lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
1816
15.3k
                                          h.islittle, cast_int(size), 0);
1817
15.3k
        luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
1818
15.3k
        lua_pushlstring(L, data + pos + size, cast_sizet(len));
1819
15.3k
        pos += cast_sizet(len);  /* skip string */
1820
15.3k
        break;
1821
153k
      }
1822
937
      case Kzstr: {
1823
937
        size_t len = strlen(data + pos);
1824
937
        luaL_argcheck(L, pos + len < ld, 2,
1825
937
                         "unfinished string for format 'z'");
1826
937
        lua_pushlstring(L, data + pos, len);
1827
937
        pos += len + 1;  /* skip string plus final '\0' */
1828
937
        break;
1829
153k
      }
1830
31.0k
      case Kpaddalign: case Kpadding: case Knop:
1831
31.0k
        n--;  /* undo increment */
1832
31.0k
        break;
1833
233k
    }
1834
208k
    pos += size;
1835
208k
  }
1836
4.64k
  lua_pushinteger(L, cast_st2S(pos) + 1);  /* next position */
1837
4.64k
  return n + 1;
1838
29.4k
}
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
26.2k
static void createmetatable (lua_State *L) {
1866
  /* table to be metatable for strings */
1867
26.2k
  luaL_newlibtable(L, stringmetamethods);
1868
26.2k
  luaL_setfuncs(L, stringmetamethods, 0);
1869
26.2k
  lua_pushliteral(L, "");  /* dummy string */
1870
26.2k
  lua_pushvalue(L, -2);  /* copy table */
1871
26.2k
  lua_setmetatable(L, -2);  /* set table as metatable for strings */
1872
26.2k
  lua_pop(L, 1);  /* pop dummy string */
1873
26.2k
  lua_pushvalue(L, -2);  /* get string library */
1874
26.2k
  lua_setfield(L, -2, "__index");  /* metatable.__index = string */
1875
26.2k
  lua_pop(L, 1);  /* pop metatable */
1876
26.2k
}
1877
1878
1879
/*
1880
** Open string library
1881
*/
1882
26.2k
LUAMOD_API int luaopen_string (lua_State *L) {
1883
26.2k
  luaL_newlib(L, strlib);
1884
26.2k
  createmetatable(L);
1885
26.2k
  return 1;
1886
26.2k
}
1887