Coverage Report

Created: 2025-11-11 06:55

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