Coverage Report

Created: 2025-08-25 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
93.6M
#define LUA_MAXCAPTURES   32
37
#endif
38
39
40
9.48k
static int str_len (lua_State *L) {
41
9.48k
  size_t l;
42
9.48k
  luaL_checklstring(L, 1, &l);
43
9.48k
  lua_pushinteger(L, (lua_Integer)l);
44
9.48k
  return 1;
45
9.48k
}
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.07M
static size_t posrelatI (lua_Integer pos, size_t len) {
57
5.07M
  if (pos > 0)
58
4.76M
    return (size_t)pos;
59
307k
  else if (pos == 0)
60
128k
    return 1;
61
179k
  else if (pos < -(lua_Integer)len)  /* inverted comparison */
62
11.4k
    return 1;  /* clip to 1 */
63
167k
  else return len + (size_t)pos + 1;
64
5.07M
}
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.18M
                         size_t len) {
74
4.18M
  lua_Integer pos = luaL_optinteger(L, arg, def);
75
4.18M
  if (pos > (lua_Integer)len)
76
2.58k
    return len;
77
4.18M
  else if (pos >= 0)
78
3.93M
    return (size_t)pos;
79
251k
  else if (pos < -(lua_Integer)len)
80
2.34k
    return 0;
81
249k
  else return len + (size_t)pos + 1;
82
4.18M
}
83
84
85
4.08M
static int str_sub (lua_State *L) {
86
4.08M
  size_t l;
87
4.08M
  const char *s = luaL_checklstring(L, 1, &l);
88
4.08M
  size_t start = posrelatI(luaL_checkinteger(L, 2), l);
89
4.08M
  size_t end = getendpos(L, 3, -1, l);
90
4.08M
  if (start <= end)
91
3.91M
    lua_pushlstring(L, s + start - 1, (end - start) + 1);
92
176k
  else lua_pushliteral(L, "");
93
4.08M
  return 1;
94
4.08M
}
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
2.44k
static int str_lower (lua_State *L) {
110
2.44k
  size_t l;
111
2.44k
  size_t i;
112
2.44k
  luaL_Buffer b;
113
2.44k
  const char *s = luaL_checklstring(L, 1, &l);
114
2.44k
  char *p = luaL_buffinitsize(L, &b, l);
115
83.8k
  for (i=0; i<l; i++)
116
81.3k
    p[i] = cast_char(tolower(cast_uchar(s[i])));
117
2.44k
  luaL_pushresultsize(&b, l);
118
2.44k
  return 1;
119
2.44k
}
120
121
122
873k
static int str_upper (lua_State *L) {
123
873k
  size_t l;
124
873k
  size_t i;
125
873k
  luaL_Buffer b;
126
873k
  const char *s = luaL_checklstring(L, 1, &l);
127
873k
  char *p = luaL_buffinitsize(L, &b, l);
128
4.84M
  for (i=0; i<l; i++)
129
3.97M
    p[i] = cast_char(toupper(cast_uchar(s[i])));
130
873k
  luaL_pushresultsize(&b, l);
131
873k
  return 1;
132
873k
}
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
182k
static int str_rep (lua_State *L) {
140
182k
  size_t len, lsep;
141
182k
  const char *s = luaL_checklstring(L, 1, &len);
142
182k
  lua_Integer n = luaL_checkinteger(L, 2);
143
182k
  const char *sep = luaL_optlstring(L, 3, "", &lsep);
144
182k
  if (n <= 0)
145
3.61k
    lua_pushliteral(L, "");
146
178k
  else if (l_unlikely(len > MAX_SIZE - lsep ||
147
178k
               cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))
148
707
    return luaL_error(L, "resulting string too large");
149
178k
  else {
150
178k
    size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;
151
178k
    luaL_Buffer b;
152
178k
    char *p = luaL_buffinitsize(L, &b, totallen);
153
156M
    while (n-- > 1) {  /* first n-1 copies (followed by separator) */
154
156M
      memcpy(p, s, len * sizeof(char)); p += len;
155
156M
      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
156
244k
        memcpy(p, sep, lsep * sizeof(char)); p += lsep;
157
244k
      }
158
156M
    }
159
178k
    memcpy(p, s, len * sizeof(char));  /* last copy without separator */
160
178k
    luaL_pushresultsize(&b, totallen);
161
178k
  }
162
181k
  return 1;
163
182k
}
164
165
166
125k
static int str_byte (lua_State *L) {
167
125k
  size_t l;
168
125k
  const char *s = luaL_checklstring(L, 1, &l);
169
125k
  lua_Integer pi = luaL_optinteger(L, 2, 1);
170
125k
  size_t posi = posrelatI(pi, l);
171
125k
  size_t pose = getendpos(L, 3, pi, l);
172
125k
  int n, i;
173
125k
  if (posi > pose) return 0;  /* empty interval; return no values */
174
124k
  if (l_unlikely(pose - posi >= (size_t)INT_MAX))  /* arithmetic overflow? */
175
0
    return luaL_error(L, "string slice too long");
176
124k
  n = (int)(pose -  posi) + 1;
177
124k
  luaL_checkstack(L, n, "string slice too long");
178
288k
  for (i=0; i<n; i++)
179
163k
    lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));
180
124k
  return n;
181
124k
}
182
183
184
33.2k
static int str_char (lua_State *L) {
185
33.2k
  int n = lua_gettop(L);  /* number of arguments */
186
33.2k
  int i;
187
33.2k
  luaL_Buffer b;
188
33.2k
  char *p = luaL_buffinitsize(L, &b, cast_uint(n));
189
131k
  for (i=1; i<=n; i++) {
190
97.8k
    lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
191
97.8k
    luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
192
97.8k
    p[i - 1] = cast_char(cast_uchar(c));
193
97.8k
  }
194
33.2k
  luaL_pushresultsize(&b, cast_uint(n));
195
33.2k
  return 1;
196
33.2k
}
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
2.03M
static int writer (lua_State *L, const void *b, size_t size, void *ud) {
212
2.03M
  struct str_Writer *state = (struct str_Writer *)ud;
213
2.03M
  if (!state->init) {
214
10.1k
    state->init = 1;
215
10.1k
    luaL_buffinit(L, &state->B);
216
10.1k
  }
217
2.03M
  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
2.02M
  else
222
2.02M
    luaL_addlstring(&state->B, (const char *)b, size);
223
2.03M
  return 0;
224
2.03M
}
225
226
227
10.4k
static int str_dump (lua_State *L) {
228
10.4k
  struct str_Writer state;
229
10.4k
  int strip = lua_toboolean(L, 2);
230
10.4k
  luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
231
10.4k
                   1, "Lua function expected");
232
  /* ensure function is on the top of the stack and vacate slot 1 */
233
10.4k
  lua_pushvalue(L, 1);
234
10.4k
  state.init = 0;
235
10.4k
  lua_dump(L, writer, &state, strip);
236
10.4k
  lua_settop(L, 1);  /* leave final result on top */
237
10.4k
  return 1;
238
10.4k
}
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.09M
static int tonum (lua_State *L, int arg) {
260
1.09M
  if (lua_type(L, arg) == LUA_TNUMBER) {  /* already a number? */
261
430k
    lua_pushvalue(L, arg);
262
430k
    return 1;
263
430k
  }
264
668k
  else {  /* check whether it is a numerical string */
265
668k
    size_t len;
266
668k
    const char *s = lua_tolstring(L, arg, &len);
267
668k
    return (s != NULL && lua_stringtonumber(L, s) == len + 1);
268
668k
  }
269
1.09M
}
270
271
272
11.6k
static void trymt (lua_State *L, const char *mtname) {
273
11.6k
  lua_settop(L, 2);  /* back to the original arguments */
274
11.6k
  if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
275
11.6k
                 !luaL_getmetafield(L, 2, mtname)))
276
11.5k
    luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
277
11.5k
                  luaL_typename(L, -2), luaL_typename(L, -1));
278
11.6k
  lua_insert(L, -3);  /* put metamethod before arguments */
279
11.6k
  lua_call(L, 2, 1);  /* call metamethod */
280
11.6k
}
281
282
283
553k
static int arith (lua_State *L, int op, const char *mtname) {
284
553k
  if (tonum(L, 1) && tonum(L, 2))
285
541k
    lua_arith(L, op);  /* result will be on the top */
286
11.6k
  else
287
11.6k
    trymt(L, mtname);
288
553k
  return 1;
289
553k
}
290
291
292
172k
static int arith_add (lua_State *L) {
293
172k
  return arith(L, LUA_OPADD, "__add");
294
172k
}
295
296
122k
static int arith_sub (lua_State *L) {
297
122k
  return arith(L, LUA_OPSUB, "__sub");
298
122k
}
299
300
130k
static int arith_mul (lua_State *L) {
301
130k
  return arith(L, LUA_OPMUL, "__mul");
302
130k
}
303
304
20.3k
static int arith_mod (lua_State *L) {
305
20.3k
  return arith(L, LUA_OPMOD, "__mod");
306
20.3k
}
307
308
9.66k
static int arith_pow (lua_State *L) {
309
9.66k
  return arith(L, LUA_OPPOW, "__pow");
310
9.66k
}
311
312
25.3k
static int arith_div (lua_State *L) {
313
25.3k
  return arith(L, LUA_OPDIV, "__div");
314
25.3k
}
315
316
26.0k
static int arith_idiv (lua_State *L) {
317
26.0k
  return arith(L, LUA_OPIDIV, "__idiv");
318
26.0k
}
319
320
46.8k
static int arith_unm (lua_State *L) {
321
46.8k
  return arith(L, LUA_OPUNM, "__unm");
322
46.8k
}
323
324
325
static const luaL_Reg stringmetamethods[] = {
326
  {"__add", arith_add},
327
  {"__sub", arith_sub},
328
  {"__mul", arith_mul},
329
  {"__mod", arith_mod},
330
  {"__pow", arith_pow},
331
  {"__div", arith_div},
332
  {"__idiv", arith_idiv},
333
  {"__unm", arith_unm},
334
  {"__index", NULL},  /* placeholder */
335
  {NULL, NULL}
336
};
337
338
#endif    /* } */
339
340
/* }====================================================== */
341
342
/*
343
** {======================================================
344
** PATTERN MATCHING
345
** =======================================================
346
*/
347
348
349
301M
#define CAP_UNFINISHED  (-1)
350
11.2M
#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.27M
#define MAXCCALLS 200
374
#endif
375
376
377
280M
#define L_ESC   '%'
378
444k
#define SPECIALS  "^$*+?.([%-"
379
380
381
76.9M
static int check_capture (MatchState *ms, int l) {
382
76.9M
  l -= '1';
383
76.9M
  if (l_unlikely(l < 0 || l >= ms->level ||
384
76.9M
                 ms->capture[l].len == CAP_UNFINISHED))
385
58.6k
    return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
386
76.8M
  return l;
387
76.9M
}
388
389
390
83.6M
static int capture_to_close (MatchState *ms) {
391
83.6M
  int level = ms->level;
392
132M
  for (level--; level>=0; level--)
393
132M
    if (ms->capture[level].len == CAP_UNFINISHED) return level;
394
2.91k
  return luaL_error(ms->L, "invalid pattern capture");
395
83.6M
}
396
397
398
371M
static const char *classend (MatchState *ms, const char *p) {
399
371M
  switch (*p++) {
400
13.4M
    case L_ESC: {
401
13.4M
      if (l_unlikely(p == ms->p_end))
402
662
        luaL_error(ms->L, "malformed pattern (ends with '%%')");
403
13.4M
      return p+1;
404
0
    }
405
4.97M
    case '[': {
406
4.97M
      if (*p == '^') p++;
407
50.1M
      do {  /* look for a ']' */
408
50.1M
        if (l_unlikely(p == ms->p_end))
409
20.5k
          luaL_error(ms->L, "malformed pattern (missing ']')");
410
50.1M
        if (*(p++) == L_ESC && p < ms->p_end)
411
5.13M
          p++;  /* skip escapes (e.g. '%]') */
412
50.1M
      } while (*p != ']');
413
4.97M
      return p+1;
414
0
    }
415
353M
    default: {
416
353M
      return p;
417
0
    }
418
371M
  }
419
371M
}
420
421
422
20.8M
static int match_class (int c, int cl) {
423
20.8M
  int res;
424
20.8M
  switch (tolower(cl)) {
425
1.02M
    case 'a' : res = isalpha(c); break;
426
351
    case 'c' : res = iscntrl(c); break;
427
9.36M
    case 'd' : res = isdigit(c); break;
428
8.04k
    case 'g' : res = isgraph(c); break;
429
136
    case 'l' : res = islower(c); break;
430
2
    case 'p' : res = ispunct(c); break;
431
4.67M
    case 's' : res = isspace(c); break;
432
31
    case 'u' : res = isupper(c); break;
433
113k
    case 'w' : res = isalnum(c); break;
434
3.62k
    case 'x' : res = isxdigit(c); break;
435
163k
    case 'z' : res = (c == 0); break;  /* deprecated option */
436
5.53M
    default: return (cl == c);
437
20.8M
  }
438
15.3M
  return (islower(cl) ? res : !res);
439
20.8M
}
440
441
442
6.67M
static int matchbracketclass (int c, const char *p, const char *ec) {
443
6.67M
  int sig = 1;
444
6.67M
  if (*(p+1) == '^') {
445
1.68M
    sig = 0;
446
1.68M
    p++;  /* skip the '^' */
447
1.68M
  }
448
34.3M
  while (++p < ec) {
449
28.2M
    if (*p == L_ESC) {
450
4.84M
      p++;
451
4.84M
      if (match_class(c, cast_uchar(*p)))
452
72.6k
        return sig;
453
4.84M
    }
454
23.3M
    else if ((*(p+1) == '-') && (p+2 < ec)) {
455
204k
      p+=2;
456
204k
      if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
457
13.8k
        return sig;
458
204k
    }
459
23.1M
    else if (cast_uchar(*p) == c) return sig;
460
28.2M
  }
461
6.14M
  return !sig;
462
6.67M
}
463
464
465
static int singlematch (MatchState *ms, const char *s, const char *p,
466
658M
                        const char *ep) {
467
658M
  if (s >= ms->src_end)
468
2.19M
    return 0;
469
656M
  else {
470
656M
    int c = cast_uchar(*s);
471
656M
    switch (*p) {
472
213M
      case '.': return 1;  /* matches any char */
473
16.0M
      case L_ESC: return match_class(c, cast_uchar(*(p+1)));
474
6.28M
      case '[': return matchbracketclass(c, p, ep-1);
475
420M
      default:  return (cast_uchar(*p) == c);
476
656M
    }
477
656M
  }
478
658M
}
479
480
481
static const char *matchbalance (MatchState *ms, const char *s,
482
136k
                                   const char *p) {
483
136k
  if (l_unlikely(p >= ms->p_end - 1))
484
1.58k
    luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
485
136k
  if (*s != *p) return NULL;
486
1.60k
  else {
487
1.60k
    int b = *p;
488
1.60k
    int e = *(p+1);
489
1.60k
    int cont = 1;
490
65.6k
    while (++s < ms->src_end) {
491
64.1k
      if (*s == e) {
492
286
        if (--cont == 0) return s+1;
493
286
      }
494
63.8k
      else if (*s == b) cont++;
495
64.1k
    }
496
1.60k
  }
497
1.58k
  return NULL;  /* string ends out of balance */
498
136k
}
499
500
501
static const char *max_expand (MatchState *ms, const char *s,
502
1.28M
                                 const char *p, const char *ep) {
503
1.28M
  ptrdiff_t i = 0;  /* counts maximum expand for item */
504
206M
  while (singlematch(ms, s + i, p, ep))
505
205M
    i++;
506
  /* keeps trying to match with the maximum repetitions */
507
132M
  while (i>=0) {
508
132M
    const char *res = match(ms, (s+i), ep+1);
509
132M
    if (res) return res;
510
131M
    i--;  /* else didn't match; reduce 1 repetition to try again */
511
131M
  }
512
317k
  return NULL;
513
1.28M
}
514
515
516
static const char *min_expand (MatchState *ms, const char *s,
517
38.9k
                                 const char *p, const char *ep) {
518
80.7M
  for (;;) {
519
80.7M
    const char *res = match(ms, s, ep+1);
520
80.7M
    if (res != NULL)
521
8.36k
      return res;
522
80.7M
    else if (singlematch(ms, s, p, ep))
523
80.6M
      s++;  /* try with one more repetition */
524
30.5k
    else return NULL;
525
80.7M
  }
526
38.9k
}
527
528
529
static const char *start_capture (MatchState *ms, const char *s,
530
93.6M
                                    const char *p, int what) {
531
93.6M
  const char *res;
532
93.6M
  int level = ms->level;
533
93.6M
  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
534
93.6M
  ms->capture[level].init = s;
535
93.6M
  ms->capture[level].len = what;
536
93.6M
  ms->level = level+1;
537
93.6M
  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
538
91.7M
    ms->level--;  /* undo capture */
539
93.6M
  return res;
540
93.6M
}
541
542
543
static const char *end_capture (MatchState *ms, const char *s,
544
83.6M
                                  const char *p) {
545
83.6M
  int l = capture_to_close(ms);
546
83.6M
  const char *res;
547
83.6M
  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
548
83.6M
  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
549
82.6M
    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
550
83.6M
  return res;
551
83.6M
}
552
553
554
76.9M
static const char *match_capture (MatchState *ms, const char *s, int l) {
555
76.9M
  size_t len;
556
76.9M
  l = check_capture(ms, l);
557
76.9M
  len = cast_sizet(ms->capture[l].len);
558
76.9M
  if ((size_t)(ms->src_end-s) >= len &&
559
76.9M
      memcmp(ms->capture[l].init, s, len) == 0)
560
3.45M
    return s+len;
561
73.4M
  else return NULL;
562
76.9M
}
563
564
565
564M
static const char *match (MatchState *ms, const char *s, const char *p) {
566
564M
  if (l_unlikely(ms->matchdepth-- == 0))
567
0
    luaL_error(ms->L, "pattern too complex");
568
767M
  init: /* using goto to optimize tail recursion */
569
767M
  if (p != ms->p_end) {  /* end of pattern? */
570
763M
    switch (*p) {
571
93.6M
      case '(': {  /* start capture */
572
93.6M
        if (*(p + 1) == ')')  /* position capture? */
573
7.41M
          s = start_capture(ms, s, p + 2, CAP_POSITION);
574
86.1M
        else
575
86.1M
          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
576
93.6M
        break;
577
0
      }
578
83.6M
      case ')': {  /* end capture */
579
83.6M
        s = end_capture(ms, s, p + 1);
580
83.6M
        break;
581
0
      }
582
137M
      case '$': {
583
137M
        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
584
26.3k
          goto dflt;  /* no; go to default */
585
137M
        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
586
137M
        break;
587
137M
      }
588
90.8M
      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
589
90.8M
        switch (*(p + 1)) {
590
136k
          case 'b': {  /* balanced string? */
591
136k
            s = matchbalance(ms, s, p + 2);
592
136k
            if (s != NULL) {
593
12
              p += 4; goto init;  /* return match(ms, s, p + 4); */
594
12
            }  /* else fail (s == NULL) */
595
136k
            break;
596
136k
          }
597
336k
          case 'f': {  /* frontier? */
598
336k
            const char *ep; char previous;
599
336k
            p += 2;
600
336k
            if (l_unlikely(*p != '['))
601
1.09k
              luaL_error(ms->L, "missing '[' after '%%f' in pattern");
602
336k
            ep = classend(ms, p);  /* points to what is next */
603
336k
            previous = (s == ms->src_init) ? '\0' : *(s - 1);
604
336k
            if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
605
336k
               matchbracketclass(cast_uchar(*s), p, ep - 1)) {
606
28.3k
              p = ep; goto init;  /* return match(ms, s, ep); */
607
28.3k
            }
608
308k
            s = NULL;  /* match failed */
609
308k
            break;
610
336k
          }
611
48.9M
          case '0': case '1': case '2': case '3':
612
76.9M
          case '4': case '5': case '6': case '7':
613
76.9M
          case '8': case '9': {  /* capture results (%0-%9)? */
614
76.9M
            s = match_capture(ms, s, cast_uchar(*(p + 1)));
615
76.9M
            if (s != NULL) {
616
3.45M
              p += 2; goto init;  /* return match(ms, s, p + 2) */
617
3.45M
            }
618
73.4M
            break;
619
76.9M
          }
620
73.4M
          default: goto dflt;
621
90.8M
        }
622
73.8M
        break;
623
90.8M
      }
624
371M
      default: dflt: {  /* pattern class plus optional suffix */
625
371M
        const char *ep = classend(ms, p);  /* points to optional suffix */
626
        /* does not match at least once? */
627
371M
        if (!singlematch(ms, s, p, ep)) {
628
232M
          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
629
61.6M
            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
630
61.6M
          }
631
170M
          else  /* '+' or no suffix */
632
170M
            s = NULL;  /* fail */
633
232M
        }
634
139M
        else {  /* matched once */
635
139M
          switch (*ep) {  /* handle optional suffix */
636
132M
            case '?': {  /* optional */
637
132M
              const char *res;
638
132M
              if ((res = match(ms, s + 1, ep + 1)) != NULL)
639
6.34k
                s = res;
640
132M
              else {
641
132M
                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
642
132M
              }
643
6.34k
              break;
644
132M
            }
645
99.0k
            case '+':  /* 1 or more repetitions */
646
99.0k
              s++;  /* 1 match already done */
647
              /* FALLTHROUGH */
648
1.28M
            case '*':  /* 0 or more repetitions */
649
1.28M
              s = max_expand(ms, s, p, ep);
650
1.28M
              break;
651
38.9k
            case '-':  /* 0 or more repetitions (minimum) */
652
38.9k
              s = min_expand(ms, s, p, ep);
653
38.9k
              break;
654
5.65M
            default:  /* no suffix */
655
5.65M
              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
656
139M
          }
657
139M
        }
658
171M
        break;
659
371M
      }
660
763M
    }
661
763M
  }
662
563M
  ms->matchdepth++;
663
563M
  return s;
664
767M
}
665
666
667
668
static const char *lmemfind (const char *s1, size_t l1,
669
116k
                               const char *s2, size_t l2) {
670
116k
  if (l2 == 0) return s1;  /* empty strings are everywhere */
671
115k
  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
672
115k
  else {
673
115k
    const char *init;  /* to search for a '*s2' inside 's1' */
674
115k
    l2--;  /* 1st char will be checked by 'memchr' */
675
115k
    l1 = l1-l2;  /* 's2' cannot be found after that */
676
150k
    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
677
137k
      init++;   /* 1st char is already checked */
678
137k
      if (memcmp(init, s2+1, l2) == 0)
679
102k
        return init-1;
680
35.3k
      else {  /* correct 'l1' and 's1' to try again */
681
35.3k
        l1 -= ct_diff2sz(init - s1);
682
35.3k
        s1 = init;
683
35.3k
      }
684
137k
    }
685
13.3k
    return NULL;  /* not found */
686
115k
  }
687
116k
}
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.50M
                              const char *e, const char **cap) {
699
2.50M
  if (i >= ms->level) {
700
1.16M
    if (l_unlikely(i != 0))
701
3.20k
      luaL_error(ms->L, "invalid capture index %%%d", i + 1);
702
1.16M
    *cap = s;
703
1.16M
    return (e - s);
704
1.16M
  }
705
1.34M
  else {
706
1.34M
    ptrdiff_t capl = ms->capture[i].len;
707
1.34M
    *cap = ms->capture[i].init;
708
1.34M
    if (l_unlikely(capl == CAP_UNFINISHED))
709
1.99k
      luaL_error(ms->L, "unfinished capture");
710
1.34M
    else if (capl == CAP_POSITION)
711
430k
      lua_pushinteger(ms->L,
712
430k
          ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
713
1.34M
    return capl;
714
1.34M
  }
715
2.50M
}
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.19M
                                                    const char *e) {
723
1.19M
  const char *cap;
724
1.19M
  ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
725
1.19M
  if (l != CAP_POSITION)
726
1.17M
    lua_pushlstring(ms->L, cap, cast_sizet(l));
727
  /* else position was already pushed */
728
1.19M
}
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
372k
static int nospecials (const char *p, size_t l) {
743
372k
  size_t upto = 0;
744
444k
  do {
745
444k
    if (strpbrk(p + upto, SPECIALS))
746
255k
      return 0;  /* pattern has a special character */
747
188k
    upto += strlen(p + upto) + 1;  /* may have more after \0 */
748
188k
  } while (upto <= l);
749
116k
  return 1;  /* no special chars found */
750
372k
}
751
752
753
static void prepstate (MatchState *ms, lua_State *L,
754
2.27M
                       const char *s, size_t ls, const char *p, size_t lp) {
755
2.27M
  ms->L = L;
756
2.27M
  ms->matchdepth = MAXCCALLS;
757
2.27M
  ms->src_init = s;
758
2.27M
  ms->src_end = s + ls;
759
2.27M
  ms->p_end = p + lp;
760
2.27M
}
761
762
763
41.3M
static void reprepstate (MatchState *ms) {
764
41.3M
  ms->level = 0;
765
41.3M
  lua_assert(ms->matchdepth == MAXCCALLS);
766
41.3M
}
767
768
769
597k
static int str_find_aux (lua_State *L, int find) {
770
597k
  size_t ls, lp;
771
597k
  const char *s = luaL_checklstring(L, 1, &ls);
772
597k
  const char *p = luaL_checklstring(L, 2, &lp);
773
597k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
774
597k
  if (init > ls) {  /* start after string's end? */
775
190k
    luaL_pushfail(L);  /* cannot find anything */
776
190k
    return 1;
777
190k
  }
778
  /* explicit request or no special characters? */
779
407k
  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
780
    /* do a plain search */
781
116k
    const char *s2 = lmemfind(s + init, ls - init, p, lp);
782
116k
    if (s2) {
783
103k
      lua_pushinteger(L, ct_diff2S(s2 - s) + 1);
784
103k
      lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));
785
103k
      return 2;
786
103k
    }
787
116k
  }
788
290k
  else {
789
290k
    MatchState ms;
790
290k
    const char *s1 = s + init;
791
290k
    int anchor = (*p == '^');
792
290k
    if (anchor) {
793
7.24k
      p++; lp--;  /* skip anchor character */
794
7.24k
    }
795
290k
    prepstate(&ms, L, s, ls, p, lp);
796
18.9M
    do {
797
18.9M
      const char *res;
798
18.9M
      reprepstate(&ms);
799
18.9M
      if ((res=match(&ms, s1, p)) != NULL) {
800
15.4k
        if (find) {
801
3.44k
          lua_pushinteger(L, ct_diff2S(s1 - s) + 1);  /* start */
802
3.44k
          lua_pushinteger(L, ct_diff2S(res - s));   /* end */
803
3.44k
          return push_captures(&ms, NULL, 0) + 2;
804
3.44k
        }
805
11.9k
        else
806
11.9k
          return push_captures(&ms, s1, res);
807
15.4k
      }
808
18.9M
    } while (s1++ < ms.src_end && !anchor);
809
290k
  }
810
288k
  luaL_pushfail(L);  /* not found */
811
288k
  return 1;
812
407k
}
813
814
815
416k
static int str_find (lua_State *L) {
816
416k
  return str_find_aux(L, 1);
817
416k
}
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
187k
static int gmatch_aux (lua_State *L) {
835
187k
  GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
836
187k
  const char *src;
837
187k
  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
172k
  return 0;  /* not found */
847
187k
}
848
849
850
259k
static int gmatch (lua_State *L) {
851
259k
  size_t ls, lp;
852
259k
  const char *s = luaL_checklstring(L, 1, &ls);
853
259k
  const char *p = luaL_checklstring(L, 2, &lp);
854
259k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
855
259k
  GMatchState *gm;
856
259k
  lua_settop(L, 2);  /* keep strings on closure to avoid being collected */
857
259k
  gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
858
259k
  if (init > ls)  /* start after string's end? */
859
6.90k
    init = ls + 1;  /* avoid overflows in 's + init' */
860
259k
  prepstate(&gm->ms, L, s, ls, p, lp);
861
259k
  gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
862
259k
  lua_pushcclosure(L, gmatch_aux, 3);
863
259k
  return 1;
864
259k
}
865
866
867
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
868
1.33M
                                                   const char *e) {
869
1.33M
  size_t l;
870
1.33M
  lua_State *L = ms->L;
871
1.33M
  const char *news = lua_tolstring(L, 3, &l);
872
1.33M
  const char *p;
873
5.04M
  while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
874
3.70M
    luaL_addlstring(b, news, ct_diff2sz(p - news));
875
3.70M
    p++;  /* skip ESC */
876
3.70M
    if (*p == L_ESC)  /* '%%' */
877
1.55M
      luaL_addchar(b, *p);
878
2.14M
    else if (*p == '0')  /* '%0' */
879
829k
        luaL_addlstring(b, s, ct_diff2sz(e - s));
880
1.31M
    else if (isdigit(cast_uchar(*p))) {  /* '%n' */
881
1.31M
      const char *cap;
882
1.31M
      ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
883
1.31M
      if (resl == CAP_POSITION)
884
411k
        luaL_addvalue(b);  /* add position to accumulated result */
885
906k
      else
886
906k
        luaL_addlstring(b, cap, cast_sizet(resl));
887
1.31M
    }
888
1.25k
    else
889
1.25k
      luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
890
3.70M
    l -= ct_diff2sz(p + 1 - news);
891
3.70M
    news = p + 1;
892
3.70M
  }
893
1.33M
  luaL_addlstring(b, news, l);
894
1.33M
}
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.47M
                                      const char *e, int tr) {
904
2.47M
  lua_State *L = ms->L;
905
2.47M
  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
4.49k
    case LUA_TTABLE: {  /* index the table */
914
4.49k
      push_onecapture(ms, 0, s, e);  /* first capture is the index */
915
4.49k
      lua_gettable(L, 3);
916
4.49k
      break;
917
0
    }
918
1.33M
    default: {  /* LUA_TNUMBER or LUA_TSTRING */
919
1.33M
      add_s(ms, b, s, e);  /* add value to the buffer */
920
1.33M
      return 1;  /* something changed */
921
0
    }
922
2.47M
  }
923
1.13M
  if (!lua_toboolean(L, -1)) {  /* nil or false? */
924
12.3k
    lua_pop(L, 1);  /* remove value */
925
12.3k
    luaL_addlstring(b, s, ct_diff2sz(e - s));  /* keep original text */
926
12.3k
    return 0;  /* no changes */
927
12.3k
  }
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.13M
}
936
937
938
1.74M
static int str_gsub (lua_State *L) {
939
1.74M
  size_t srcl, lp;
940
1.74M
  const char *src = luaL_checklstring(L, 1, &srcl);  /* subject */
941
1.74M
  const char *p = luaL_checklstring(L, 2, &lp);  /* pattern */
942
1.74M
  const char *lastmatch = NULL;  /* end of last match */
943
1.74M
  int tr = lua_type(L, 3);  /* replacement type */
944
  /* max replacements */
945
1.74M
  lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
946
1.74M
  int anchor = (*p == '^');
947
1.74M
  lua_Integer n = 0;  /* replacement count */
948
1.74M
  int changed = 0;  /* change flag */
949
1.74M
  MatchState ms;
950
1.74M
  luaL_Buffer b;
951
1.74M
  luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
952
1.74M
                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
953
1.74M
                      "string/function/table");
954
1.74M
  luaL_buffinit(L, &b);
955
1.74M
  if (anchor) {
956
7.18k
    p++; lp--;  /* skip anchor character */
957
7.18k
  }
958
1.74M
  prepstate(&ms, L, src, srcl, p, lp);
959
18.8M
  while (n < max_s) {
960
18.8M
    const char *e;
961
18.8M
    reprepstate(&ms);  /* (re)prepare state for new match */
962
18.8M
    if ((e = match(&ms, src, p)) != NULL && e != lastmatch) {  /* match? */
963
2.47M
      n++;
964
2.47M
      changed = add_value(&ms, &b, src, e, tr) | changed;
965
2.47M
      src = lastmatch = e;
966
2.47M
    }
967
16.3M
    else if (src < ms.src_end)  /* otherwise, skip one character */
968
14.6M
      luaL_addchar(&b, *src++);
969
1.71M
    else break;  /* end of subject */
970
17.1M
    if (anchor) break;
971
17.1M
  }
972
1.74M
  if (!changed)  /* no changes? */
973
747k
    lua_pushvalue(L, 1);  /* return original string */
974
997k
  else {  /* something changed */
975
997k
    luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));
976
997k
    luaL_pushresult(&b);  /* create and return new string */
977
997k
  }
978
1.74M
  lua_pushinteger(L, n);  /* number of substitutions */
979
1.74M
  return 2;
980
1.74M
}
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.44k
#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.15M
#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
18.4k
#define L_FMTFLAGSI "-+0 "
1100
1101
/* valid flags for u conversions */
1102
7.68k
#define L_FMTFLAGSU "-0"
1103
1104
/* valid flags for c, p, and s conversions */
1105
72.2k
#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
23.5k
static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
1120
23.5k
  luaL_addchar(b, '"');
1121
55.8M
  while (len--) {
1122
55.8M
    if (*s == '"' || *s == '\\' || *s == '\n') {
1123
1.67M
      luaL_addchar(b, '\\');
1124
1.67M
      luaL_addchar(b, *s);
1125
1.67M
    }
1126
54.1M
    else if (iscntrl(cast_uchar(*s))) {
1127
2.29M
      char buff[10];
1128
2.29M
      if (!isdigit(cast_uchar(*(s+1))))
1129
2.28M
        l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
1130
10.4k
      else
1131
10.4k
        l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s));
1132
2.29M
      luaL_addstring(b, buff);
1133
2.29M
    }
1134
51.8M
    else
1135
51.8M
      luaL_addchar(b, *s);
1136
55.8M
    s++;
1137
55.8M
  }
1138
23.5k
  luaL_addchar(b, '"');
1139
23.5k
}
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
3.87k
static int quotefloat (lua_State *L, char *buff, lua_Number n) {
1149
3.87k
  const char *s;  /* for the fixed representations */
1150
3.87k
  if (n == (lua_Number)HUGE_VAL)  /* inf? */
1151
1.99k
    s = "1e9999";
1152
1.88k
  else if (n == -(lua_Number)HUGE_VAL)  /* -inf? */
1153
302
    s = "-1e9999";
1154
1.57k
  else if (n != n)  /* NaN? */
1155
620
    s = "(0/0)";
1156
958
  else {  /* format number as hexadecimal */
1157
958
    int  nb = lua_number2strx(L, buff, MAX_ITEM,
1158
958
                                 "%" LUA_NUMBER_FRMLEN "a", n);
1159
    /* ensures that 'buff' string uses a dot as the radix character */
1160
958
    if (memchr(buff, '.', cast_uint(nb)) == NULL) {  /* no dot? */
1161
804
      char point = lua_getlocaledecpoint();  /* try locale point */
1162
804
      char *ppoint = (char *)memchr(buff, point, cast_uint(nb));
1163
804
      if (ppoint) *ppoint = '.';  /* change it to a dot */
1164
804
    }
1165
958
    return nb;
1166
958
  }
1167
  /* for the fixed representations */
1168
2.92k
  return l_sprintf(buff, MAX_ITEM, "%s", s);
1169
3.87k
}
1170
1171
1172
28.7k
static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
1173
28.7k
  switch (lua_type(L, arg)) {
1174
23.5k
    case LUA_TSTRING: {
1175
23.5k
      size_t len;
1176
23.5k
      const char *s = lua_tolstring(L, arg, &len);
1177
23.5k
      addquoted(b, s, len);
1178
23.5k
      break;
1179
0
    }
1180
4.07k
    case LUA_TNUMBER: {
1181
4.07k
      char *buff = luaL_prepbuffsize(b, MAX_ITEM);
1182
4.07k
      int nb;
1183
4.07k
      if (!lua_isinteger(L, arg))  /* float? */
1184
3.87k
        nb = quotefloat(L, buff, lua_tonumber(L, arg));
1185
194
      else {  /* integers */
1186
194
        lua_Integer n = lua_tointeger(L, arg);
1187
194
        const char *format = (n == LUA_MININTEGER)  /* corner case? */
1188
194
                           ? "0x%" LUA_INTEGER_FRMLEN "x"  /* use hex */
1189
194
                           : LUA_INTEGER_FMT;  /* else use default format */
1190
194
        nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
1191
194
      }
1192
4.07k
      luaL_addsize(b, cast_uint(nb));
1193
4.07k
      break;
1194
0
    }
1195
1.11k
    case LUA_TNIL: case LUA_TBOOLEAN: {
1196
1.11k
      luaL_tolstring(L, arg, NULL);
1197
1.11k
      luaL_addvalue(b);
1198
1.11k
      break;
1199
896
    }
1200
0
    default: {
1201
0
      luaL_argerror(L, arg, "value has no literal form");
1202
0
    }
1203
28.7k
  }
1204
28.7k
}
1205
1206
1207
1.50M
static const char *get2digits (const char *s) {
1208
1.50M
  if (isdigit(cast_uchar(*s))) {
1209
683k
    s++;
1210
683k
    if (isdigit(cast_uchar(*s))) s++;  /* (2 digits at most) */
1211
683k
  }
1212
1.50M
  return s;
1213
1.50M
}
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
873k
                                       int precision) {
1224
873k
  const char *spec = form + 1;  /* skip '%' */
1225
873k
  spec += strspn(spec, flags);  /* skip flags */
1226
873k
  if (*spec != '0') {  /* a width cannot start with '0' */
1227
863k
    spec = get2digits(spec);  /* skip width */
1228
863k
    if (*spec == '.' && precision) {
1229
637k
      spec++;
1230
637k
      spec = get2digits(spec);  /* skip precision */
1231
637k
    }
1232
863k
  }
1233
873k
  if (!isalpha(cast_uchar(*spec)))  /* did not go to the end? */
1234
18.2k
    luaL_error(L, "invalid conversion specification: '%s'", form);
1235
873k
}
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
9.26k
    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
798k
static void addlenmod (char *form, const char *lenmod) {
1261
798k
  size_t l = strlen(form);
1262
798k
  size_t lm = strlen(lenmod);
1263
798k
  char spec = form[l - 1];
1264
798k
  strcpy(form + l - 1, lenmod);
1265
798k
  form[l + lm - 1] = spec;
1266
798k
  form[l + lm] = '\0';
1267
798k
}
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
23.2M
  while (strfrmt < strfrmt_end) {
1280
22.0M
    if (*strfrmt != L_ESC)
1281
20.7M
      luaL_addchar(&b, *strfrmt++);
1282
1.31M
    else if (*++strfrmt == L_ESC)
1283
166k
      luaL_addchar(&b, *strfrmt++);  /* %% */
1284
1.15M
    else { /* format item */
1285
1.15M
      char form[MAX_FORMAT];  /* to store the format ('%...') */
1286
1.15M
      unsigned maxitem = MAX_ITEM;  /* maximum length for the result */
1287
1.15M
      char *buff = luaL_prepbuffsize(&b, maxitem);  /* to put result */
1288
1.15M
      int nb = 0;  /* number of bytes in result */
1289
1.15M
      if (++arg > top)
1290
29.7k
        return luaL_argerror(L, arg, "no value");
1291
1.12M
      strfrmt = getformat(L, strfrmt, form);
1292
1.12M
      switch (*strfrmt++) {
1293
17.8k
        case 'c': {
1294
17.8k
          checkformat(L, form, L_FMTFLAGSC, 0);
1295
17.8k
          nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
1296
17.8k
          break;
1297
0
        }
1298
18.4k
        case 'd': case 'i':
1299
18.4k
          flags = L_FMTFLAGSI;
1300
18.4k
          goto intcase;
1301
7.68k
        case 'u':
1302
7.68k
          flags = L_FMTFLAGSU;
1303
7.68k
          goto intcase;
1304
11.6k
        case 'o': case 'x': case 'X':
1305
11.6k
          flags = L_FMTFLAGSX;
1306
37.7k
         intcase: {
1307
37.7k
          lua_Integer n = luaL_checkinteger(L, arg);
1308
37.7k
          checkformat(L, form, flags, 1);
1309
37.7k
          addlenmod(form, LUA_INTEGER_FRMLEN);
1310
37.7k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
1311
37.7k
          break;
1312
11.6k
        }
1313
152k
        case 'a': case 'A':
1314
152k
          checkformat(L, form, L_FMTFLAGSF, 1);
1315
152k
          addlenmod(form, LUA_NUMBER_FRMLEN);
1316
152k
          nb = lua_number2strx(L, buff, maxitem, form,
1317
152k
                                  luaL_checknumber(L, arg));
1318
152k
          break;
1319
3.44k
        case 'f':
1320
3.44k
          maxitem = MAX_ITEMF;  /* extra space for '%f' */
1321
3.44k
          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
364
            p = "(null)";  /* result */
1335
364
            form[strlen(form) - 1] = 's';  /* format it as a string */
1336
364
          }
1337
11.8k
          nb = l_sprintf(buff, maxitem, form, p);
1338
11.8k
          break;
1339
636k
        }
1340
28.8k
        case 'q': {
1341
28.8k
          if (form[2] != '\0')  /* modifiers? */
1342
36
            return luaL_error(L, "specifier '%%q' cannot have modifiers");
1343
28.7k
          addliteral(L, &b, arg);
1344
28.7k
          break;
1345
28.8k
        }
1346
217k
        case 's': {
1347
217k
          size_t l;
1348
217k
          const char *s = luaL_tolstring(L, arg, &l);
1349
217k
          if (form[2] == '\0')  /* no modifiers? */
1350
174k
            luaL_addvalue(&b);  /* keep entire string */
1351
42.5k
          else {
1352
42.5k
            luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
1353
42.5k
            checkformat(L, form, L_FMTFLAGSC, 1);
1354
42.5k
            if (strchr(form, '.') == NULL && l >= 100) {
1355
              /* no precision and string is too long to be formatted */
1356
17.6k
              luaL_addvalue(&b);  /* keep entire string */
1357
17.6k
            }
1358
24.8k
            else {  /* format the string into 'buff' */
1359
24.8k
              nb = l_sprintf(buff, maxitem, form, s);
1360
24.8k
              lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
1361
24.8k
            }
1362
42.5k
          }
1363
217k
          break;
1364
28.8k
        }
1365
10.3k
        default: {  /* also treat cases 'pnLlh' */
1366
10.3k
          return luaL_error(L, "invalid conversion '%s' to 'format'", form);
1367
28.8k
        }
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.0M
  }
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
192k
#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.02M
#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.57M
static int digit (int c) { return '0' <= c && c <= '9'; }
1445
1446
626k
static size_t getnum (const char **fmt, size_t df) {
1447
626k
  if (!digit(**fmt))  /* no number? */
1448
398k
    return df;  /* return default value */
1449
227k
  else {
1450
227k
    size_t a = 0;
1451
943k
    do {
1452
943k
      a = a*10 + cast_uint(*((*fmt)++) - '0');
1453
943k
    } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);
1454
227k
    return a;
1455
227k
  }
1456
626k
}
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
431k
static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
1464
431k
  size_t sz = getnum(fmt, df);
1465
431k
  if (l_unlikely((sz - 1u) >= MAXINTSIZE))
1466
7.64k
    return cast_uint(luaL_error(h->L,
1467
424k
               "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
1468
424k
  return cast_uint(sz);
1469
431k
}
1470
1471
1472
/*
1473
** Initialize Header
1474
*/
1475
488k
static void initheader (lua_State *L, Header *h) {
1476
488k
  h->L = L;
1477
488k
  h->islittle = nativeendian.little;
1478
488k
  h->maxalign = 1;
1479
488k
}
1480
1481
1482
/*
1483
** Read and classify next option. 'size' is filled with option's size.
1484
*/
1485
2.27M
static KOption getoption (Header *h, const char **fmt, size_t *size) {
1486
  /* dummy structure to get native alignment requirements */
1487
2.27M
  struct cD { char c; union { LUAI_MAXALIGN; } u; };
1488
2.27M
  int opt = *((*fmt)++);
1489
2.27M
  *size = 0;  /* default */
1490
2.27M
  switch (opt) {
1491
3.18k
    case 'b': *size = sizeof(char); return Kint;
1492
8.26k
    case 'B': *size = sizeof(char); return Kuint;
1493
59.8k
    case 'h': *size = sizeof(short); return Kint;
1494
1.11k
    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
201k
    case 'j': *size = sizeof(lua_Integer); return Kint;
1498
430
    case 'J': *size = sizeof(lua_Integer); return Kuint;
1499
925
    case 'T': *size = sizeof(size_t); return Kuint;
1500
5.40k
    case 'f': *size = sizeof(float); return Kfloat;
1501
6.63k
    case 'n': *size = sizeof(lua_Number); return Knumber;
1502
5.37k
    case 'd': *size = sizeof(double); return Kdouble;
1503
21.2k
    case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1504
5.36k
    case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1505
179k
    case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1506
194k
    case 'c':
1507
194k
      *size = getnum(fmt, cast_sizet(-1));
1508
194k
      if (l_unlikely(*size == cast_sizet(-1)))
1509
145
        luaL_error(h->L, "missing size for format option 'c'");
1510
194k
      return Kchar;
1511
969
    case 'z': return Kzstr;
1512
293k
    case 'x': *size = 1; return Kpadding;
1513
188k
    case 'X': return Kpaddalign;
1514
27.8k
    case ' ': break;
1515
81.4k
    case '<': h->islittle = 1; break;
1516
582k
    case '>': h->islittle = 0; break;
1517
4.45k
    case '=': h->islittle = nativeendian.little; break;
1518
225k
    case '!': {
1519
225k
      const size_t maxalign = offsetof(struct cD, u);
1520
225k
      h->maxalign = getnumlimit(h, fmt, maxalign);
1521
225k
      break;
1522
0
    }
1523
12.5k
    default: luaL_error(h->L, "invalid format option '%c'", opt);
1524
2.27M
  }
1525
920k
  return Knop;
1526
2.27M
}
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.09M
                           size_t *psize, unsigned *ntoalign) {
1540
2.09M
  KOption opt = getoption(h, fmt, psize);
1541
2.09M
  size_t align = *psize;  /* usually, alignment follows size */
1542
2.09M
  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
1543
188k
    if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1544
553
      luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1545
188k
  }
1546
2.09M
  if (align <= 1 || opt == Kchar)  /* need no alignment? */
1547
1.42M
    *ntoalign = 0;
1548
667k
  else {
1549
667k
    if (align > h->maxalign)  /* enforce maximum alignment */
1550
311k
      align = h->maxalign;
1551
667k
    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
666k
    else {
1556
      /* 'szmoda' = totalsize % align */
1557
666k
      unsigned szmoda = cast_uint(totalsize & (align - 1));
1558
666k
      *ntoalign = cast_uint((align - szmoda) & (align - 1));
1559
666k
    }
1560
667k
  }
1561
2.09M
  return opt;
1562
2.09M
}
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
227k
                     int islittle, unsigned size, int neg) {
1573
227k
  char *buff = luaL_prepbuffsize(b, size);
1574
227k
  unsigned i;
1575
227k
  buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */
1576
1.43M
  for (i = 1; i < size; i++) {
1577
1.21M
    n >>= NB;
1578
1.21M
    buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1579
1.21M
  }
1580
227k
  if (neg && size > SZINT) {  /* negative number need sign extension? */
1581
319
    for (i = SZINT; i < size; i++)  /* correct extra bytes */
1582
254
      buff[islittle ? i : size - 1 - i] = (char)MC;
1583
65
  }
1584
227k
  luaL_addsize(b, size);  /* add result to buffer */
1585
227k
}
1586
1587
1588
/*
1589
** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
1590
** given 'islittle' is different from native endianness.
1591
*/
1592
static void copywithendian (char *dest, const char *src,
1593
12.7k
                            unsigned size, int islittle) {
1594
12.7k
  if (islittle == nativeendian.little)
1595
4.78k
    memcpy(dest, src, size);
1596
7.95k
  else {
1597
7.95k
    dest += size - 1;
1598
53.9k
    while (size-- != 0)
1599
46.0k
      *(dest--) = *(src++);
1600
7.95k
  }
1601
12.7k
}
1602
1603
1604
457k
static int str_pack (lua_State *L) {
1605
457k
  luaL_Buffer b;
1606
457k
  Header h;
1607
457k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1608
457k
  int arg = 1;  /* current argument to pack */
1609
457k
  size_t totalsize = 0;  /* accumulate total size of result */
1610
457k
  initheader(L, &h);
1611
457k
  lua_pushnil(L);  /* mark to separate arguments from string buffer */
1612
457k
  luaL_buffinit(L, &b);
1613
2.24M
  while (*fmt != '\0') {
1614
1.80M
    unsigned ntoalign;
1615
1.80M
    size_t size;
1616
1.80M
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1617
1.80M
    luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,
1618
1.80M
                     "result too long");
1619
1.80M
    totalsize += ntoalign + size;
1620
3.71M
    while (ntoalign-- > 0)
1621
1.91M
     luaL_addchar(&b, LUAL_PACKPADBYTE);  /* fill alignment */
1622
1.80M
    arg++;
1623
1.80M
    switch (opt) {
1624
69.2k
      case Kint: {  /* signed integers */
1625
69.2k
        lua_Integer n = luaL_checkinteger(L, arg);
1626
69.2k
        if (size < SZINT) {  /* need overflow check? */
1627
63.8k
          lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1628
63.8k
          luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1629
63.8k
        }
1630
69.2k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
1631
69.2k
        break;
1632
0
      }
1633
3.33k
      case Kuint: {  /* unsigned integers */
1634
3.33k
        lua_Integer n = luaL_checkinteger(L, arg);
1635
3.33k
        if (size < SZINT)  /* need overflow check? */
1636
1.66k
          luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1637
3.33k
                           arg, "unsigned overflow");
1638
3.33k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
1639
3.33k
        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
192k
      case Kchar: {  /* fixed-size string */
1666
192k
        size_t len;
1667
192k
        const char *s = luaL_checklstring(L, arg, &len);
1668
192k
        luaL_argcheck(L, len <= size, arg, "string longer than given size");
1669
192k
        luaL_addlstring(&b, s, len);  /* add string */
1670
192k
        if (len < size) {  /* does it need padding? */
1671
192k
          size_t psize = size - len;  /* pad size */
1672
192k
          char *buff = luaL_prepbuffsize(&b, psize);
1673
192k
          memset(buff, LUAL_PACKPADBYTE, psize);
1674
192k
          luaL_addsize(&b, psize);
1675
192k
        }
1676
192k
        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
29
      case Kzstr: {  /* zero-terminated string */
1691
29
        size_t len;
1692
29
        const char *s = luaL_checklstring(L, arg, &len);
1693
29
        luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1694
29
        luaL_addlstring(&b, s, len);
1695
29
        luaL_addchar(&b, '\0');  /* add zero at the end */
1696
29
        totalsize += len + 1;
1697
29
        break;
1698
0
      }
1699
292k
      case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE);  /* FALLTHROUGH */
1700
1.36M
      case Kpaddalign: case Knop:
1701
1.36M
        arg--;  /* undo increment */
1702
1.36M
        break;
1703
1.80M
    }
1704
1.80M
  }
1705
437k
  luaL_pushresult(&b);
1706
437k
  return 1;
1707
457k
}
1708
1709
1710
2.35k
static int str_packsize (lua_State *L) {
1711
2.35k
  Header h;
1712
2.35k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1713
2.35k
  size_t totalsize = 0;  /* accumulate total size of result */
1714
2.35k
  initheader(L, &h);
1715
58.0k
  while (*fmt != '\0') {
1716
55.6k
    unsigned ntoalign;
1717
55.6k
    size_t size;
1718
55.6k
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1719
55.6k
    luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
1720
55.6k
                     "variable-length format");
1721
55.6k
    size += ntoalign;  /* total space used by option */
1722
55.6k
    luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,
1723
55.6k
                     1, "format result too large");
1724
55.6k
    totalsize += size;
1725
55.6k
  }
1726
2.35k
  lua_pushinteger(L, cast_st2S(totalsize));
1727
2.35k
  return 1;
1728
2.35k
}
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
177k
                              int islittle, int size, int issigned) {
1741
177k
  lua_Unsigned res = 0;
1742
177k
  int i;
1743
177k
  int limit = (size  <= SZINT) ? size : SZINT;
1744
1.48M
  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
177k
  if (size < SZINT) {  /* real size smaller than lua_Integer? */
1749
18.5k
    if (issigned) {  /* needs sign extension? */
1750
5.98k
      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1751
5.98k
      res = ((res ^ mask) - mask);  /* do sign extension */
1752
5.98k
    }
1753
18.5k
  }
1754
159k
  else if (size > SZINT) {  /* must check unread bytes */
1755
13.0k
    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1756
59.1k
    for (i = limit; i < size; i++) {
1757
46.0k
      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
46.0k
    }
1760
13.0k
  }
1761
177k
  return (lua_Integer)res;
1762
177k
}
1763
1764
1765
28.3k
static int str_unpack (lua_State *L) {
1766
28.3k
  Header h;
1767
28.3k
  const char *fmt = luaL_checkstring(L, 1);
1768
28.3k
  size_t ld;
1769
28.3k
  const char *data = luaL_checklstring(L, 2, &ld);
1770
28.3k
  size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
1771
28.3k
  int n = 0;  /* number of results */
1772
28.3k
  luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1773
28.3k
  initheader(L, &h);
1774
233k
  while (*fmt != '\0') {
1775
229k
    unsigned ntoalign;
1776
229k
    size_t size;
1777
229k
    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1778
229k
    luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
1779
229k
                    "data string too short");
1780
229k
    pos += ntoalign;  /* skip alignment */
1781
    /* stack space for item + next position */
1782
229k
    luaL_checkstack(L, 2, "too many results");
1783
229k
    n++;
1784
229k
    switch (opt) {
1785
152k
      case Kint:
1786
162k
      case Kuint: {
1787
162k
        lua_Integer res = unpackint(L, data + pos, h.islittle,
1788
162k
                                       cast_int(size), (opt == Kint));
1789
162k
        lua_pushinteger(L, res);
1790
162k
        break;
1791
152k
      }
1792
3.56k
      case Kfloat: {
1793
3.56k
        float f;
1794
3.56k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1795
3.56k
        lua_pushnumber(L, (lua_Number)f);
1796
3.56k
        break;
1797
152k
      }
1798
3.69k
      case Knumber: {
1799
3.69k
        lua_Number f;
1800
3.69k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1801
3.69k
        lua_pushnumber(L, f);
1802
3.69k
        break;
1803
152k
      }
1804
3.24k
      case Kdouble: {
1805
3.24k
        double f;
1806
3.24k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1807
3.24k
        lua_pushnumber(L, (lua_Number)f);
1808
3.24k
        break;
1809
152k
      }
1810
1.29k
      case Kchar: {
1811
1.29k
        lua_pushlstring(L, data + pos, size);
1812
1.29k
        break;
1813
152k
      }
1814
15.1k
      case Kstring: {
1815
15.1k
        lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
1816
15.1k
                                          h.islittle, cast_int(size), 0);
1817
15.1k
        luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
1818
15.1k
        lua_pushlstring(L, data + pos + size, cast_sizet(len));
1819
15.1k
        pos += cast_sizet(len);  /* skip string */
1820
15.1k
        break;
1821
152k
      }
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
152k
      }
1830
29.0k
      case Kpaddalign: case Kpadding: case Knop:
1831
29.0k
        n--;  /* undo increment */
1832
29.0k
        break;
1833
229k
    }
1834
205k
    pos += size;
1835
205k
  }
1836
4.52k
  lua_pushinteger(L, cast_st2S(pos) + 1);  /* next position */
1837
4.52k
  return n + 1;
1838
28.3k
}
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.8k
static void createmetatable (lua_State *L) {
1866
  /* table to be metatable for strings */
1867
26.8k
  luaL_newlibtable(L, stringmetamethods);
1868
26.8k
  luaL_setfuncs(L, stringmetamethods, 0);
1869
26.8k
  lua_pushliteral(L, "");  /* dummy string */
1870
26.8k
  lua_pushvalue(L, -2);  /* copy table */
1871
26.8k
  lua_setmetatable(L, -2);  /* set table as metatable for strings */
1872
26.8k
  lua_pop(L, 1);  /* pop dummy string */
1873
26.8k
  lua_pushvalue(L, -2);  /* get string library */
1874
26.8k
  lua_setfield(L, -2, "__index");  /* metatable.__index = string */
1875
26.8k
  lua_pop(L, 1);  /* pop metatable */
1876
26.8k
}
1877
1878
1879
/*
1880
** Open string library
1881
*/
1882
26.8k
LUAMOD_API int luaopen_string (lua_State *L) {
1883
26.8k
  luaL_newlib(L, strlib);
1884
26.8k
  createmetatable(L);
1885
26.8k
  return 1;
1886
26.8k
}
1887