Coverage Report

Created: 2025-10-27 06:39

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
84.4M
#define LUA_MAXCAPTURES   32
37
#endif
38
39
40
9.91k
static int str_len (lua_State *L) {
41
9.91k
  size_t l;
42
9.91k
  luaL_checklstring(L, 1, &l);
43
9.91k
  lua_pushinteger(L, (lua_Integer)l);
44
9.91k
  return 1;
45
9.91k
}
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.52M
static size_t posrelatI (lua_Integer pos, size_t len) {
57
2.52M
  if (pos > 0)
58
2.22M
    return (size_t)pos;
59
304k
  else if (pos == 0)
60
109k
    return 1;
61
194k
  else if (pos < -(lua_Integer)len)  /* inverted comparison */
62
23.9k
    return 1;  /* clip to 1 */
63
170k
  else return len + (size_t)pos + 1;
64
2.52M
}
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.77M
                         size_t len) {
74
1.77M
  lua_Integer pos = luaL_optinteger(L, arg, def);
75
1.77M
  if (pos > (lua_Integer)len)
76
5.91k
    return len;
77
1.76M
  else if (pos >= 0)
78
1.50M
    return (size_t)pos;
79
261k
  else if (pos < -(lua_Integer)len)
80
4.78k
    return 0;
81
256k
  else return len + (size_t)pos + 1;
82
1.77M
}
83
84
85
1.70M
static int str_sub (lua_State *L) {
86
1.70M
  size_t l;
87
1.70M
  const char *s = luaL_checklstring(L, 1, &l);
88
1.70M
  size_t start = posrelatI(luaL_checkinteger(L, 2), l);
89
1.70M
  size_t end = getendpos(L, 3, -1, l);
90
1.70M
  if (start <= end)
91
1.52M
    lua_pushlstring(L, s + start - 1, (end - start) + 1);
92
179k
  else lua_pushliteral(L, "");
93
1.70M
  return 1;
94
1.70M
}
95
96
97
92.7k
static int str_reverse (lua_State *L) {
98
92.7k
  size_t l, i;
99
92.7k
  luaL_Buffer b;
100
92.7k
  const char *s = luaL_checklstring(L, 1, &l);
101
92.7k
  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.7k
  luaL_pushresultsize(&b, l);
105
92.7k
  return 1;
106
92.7k
}
107
108
109
3.34k
static int str_lower (lua_State *L) {
110
3.34k
  size_t l;
111
3.34k
  size_t i;
112
3.34k
  luaL_Buffer b;
113
3.34k
  const char *s = luaL_checklstring(L, 1, &l);
114
3.34k
  char *p = luaL_buffinitsize(L, &b, l);
115
191k
  for (i=0; i<l; i++)
116
188k
    p[i] = cast_char(tolower(cast_uchar(s[i])));
117
3.34k
  luaL_pushresultsize(&b, l);
118
3.34k
  return 1;
119
3.34k
}
120
121
122
521k
static int str_upper (lua_State *L) {
123
521k
  size_t l;
124
521k
  size_t i;
125
521k
  luaL_Buffer b;
126
521k
  const char *s = luaL_checklstring(L, 1, &l);
127
521k
  char *p = luaL_buffinitsize(L, &b, l);
128
3.44M
  for (i=0; i<l; i++)
129
2.92M
    p[i] = cast_char(toupper(cast_uchar(s[i])));
130
521k
  luaL_pushresultsize(&b, l);
131
521k
  return 1;
132
521k
}
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
98.2k
static int str_rep (lua_State *L) {
140
98.2k
  size_t len, lsep;
141
98.2k
  const char *s = luaL_checklstring(L, 1, &len);
142
98.2k
  lua_Integer n = luaL_checkinteger(L, 2);
143
98.2k
  const char *sep = luaL_optlstring(L, 3, "", &lsep);
144
98.2k
  if (n <= 0)
145
2.64k
    lua_pushliteral(L, "");
146
95.6k
  else if (l_unlikely(len > MAX_SIZE - lsep ||
147
95.6k
               cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))
148
1.03k
    return luaL_error(L, "resulting string too large");
149
94.5k
  else {
150
94.5k
    size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;
151
94.5k
    luaL_Buffer b;
152
94.5k
    char *p = luaL_buffinitsize(L, &b, totallen);
153
33.9M
    while (n-- > 1) {  /* first n-1 copies (followed by separator) */
154
33.8M
      memcpy(p, s, len * sizeof(char)); p += len;
155
33.8M
      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
156
1.18M
        memcpy(p, sep, lsep * sizeof(char)); p += lsep;
157
1.18M
      }
158
33.8M
    }
159
94.5k
    memcpy(p, s, len * sizeof(char));  /* last copy without separator */
160
94.5k
    luaL_pushresultsize(&b, totallen);
161
94.5k
  }
162
97.2k
  return 1;
163
98.2k
}
164
165
166
82.3k
static int str_byte (lua_State *L) {
167
82.3k
  size_t l;
168
82.3k
  const char *s = luaL_checklstring(L, 1, &l);
169
82.3k
  lua_Integer pi = luaL_optinteger(L, 2, 1);
170
82.3k
  size_t posi = posrelatI(pi, l);
171
82.3k
  size_t pose = getendpos(L, 3, pi, l);
172
82.3k
  int n, i;
173
82.3k
  if (posi > pose) return 0;  /* empty interval; return no values */
174
80.7k
  if (l_unlikely(pose - posi >= (size_t)INT_MAX))  /* arithmetic overflow? */
175
0
    return luaL_error(L, "string slice too long");
176
80.7k
  n = (int)(pose -  posi) + 1;
177
80.7k
  luaL_checkstack(L, n, "string slice too long");
178
336k
  for (i=0; i<n; i++)
179
255k
    lua_pushinteger(L, cast_uchar(s[posi + cast_uint(i) - 1]));
180
80.7k
  return n;
181
80.7k
}
182
183
184
29.2k
static int str_char (lua_State *L) {
185
29.2k
  int n = lua_gettop(L);  /* number of arguments */
186
29.2k
  int i;
187
29.2k
  luaL_Buffer b;
188
29.2k
  char *p = luaL_buffinitsize(L, &b, cast_uint(n));
189
115k
  for (i=1; i<=n; i++) {
190
86.5k
    lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
191
86.5k
    luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
192
86.5k
    p[i - 1] = cast_char(cast_uchar(c));
193
86.5k
  }
194
29.2k
  luaL_pushresultsize(&b, cast_uint(n));
195
29.2k
  return 1;
196
29.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.84M
static int writer (lua_State *L, const void *b, size_t size, void *ud) {
212
2.84M
  struct str_Writer *state = (struct str_Writer *)ud;
213
2.84M
  if (!state->init) {
214
17.5k
    state->init = 1;
215
17.5k
    luaL_buffinit(L, &state->B);
216
17.5k
  }
217
2.84M
  if (b == NULL) {  /* finishing dump? */
218
17.5k
    luaL_pushresult(&state->B);  /* push result */
219
17.5k
    lua_replace(L, 1);  /* move it to reserved slot */
220
17.5k
  }
221
2.83M
  else
222
2.83M
    luaL_addlstring(&state->B, (const char *)b, size);
223
2.84M
  return 0;
224
2.84M
}
225
226
227
17.8k
static int str_dump (lua_State *L) {
228
17.8k
  struct str_Writer state;
229
17.8k
  int strip = lua_toboolean(L, 2);
230
17.8k
  luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
231
17.8k
                   1, "Lua function expected");
232
  /* ensure function is on the top of the stack and vacate slot 1 */
233
17.8k
  lua_pushvalue(L, 1);
234
17.8k
  state.init = 0;
235
17.8k
  lua_dump(L, writer, &state, strip);
236
17.8k
  lua_settop(L, 1);  /* leave final result on top */
237
17.8k
  return 1;
238
17.8k
}
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.42M
static int tonum (lua_State *L, int arg) {
260
1.42M
  if (lua_type(L, arg) == LUA_TNUMBER) {  /* already a number? */
261
624k
    lua_pushvalue(L, arg);
262
624k
    return 1;
263
624k
  }
264
800k
  else {  /* check whether it is a numerical string */
265
800k
    size_t len;
266
800k
    const char *s = lua_tolstring(L, arg, &len);
267
800k
    return (s != NULL && lua_stringtonumber(L, s) == len + 1);
268
800k
  }
269
1.42M
}
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
18.9k
static void trymt (lua_State *L, const char *mtkey, const char *opname) {
280
18.9k
  lua_settop(L, 2);  /* back to the original arguments */
281
18.9k
  if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
282
18.9k
                 !luaL_getmetafield(L, 2, mtkey)))
283
18.7k
    luaL_error(L, "attempt to %s a '%s' with a '%s'", opname,
284
18.7k
                  luaL_typename(L, -2), luaL_typename(L, -1));
285
18.9k
  lua_insert(L, -3);  /* put metamethod before arguments */
286
18.9k
  lua_call(L, 2, 1);  /* call metamethod */
287
18.9k
}
288
289
290
719k
static int arith (lua_State *L, int op, const char *mtname) {
291
719k
  if (tonum(L, 1) && tonum(L, 2))
292
700k
    lua_arith(L, op);  /* result will be on the top */
293
18.9k
  else
294
18.9k
    trymt(L, mtname, mtname + 2);
295
719k
  return 1;
296
719k
}
297
298
299
202k
static int arith_add (lua_State *L) {
300
202k
  return arith(L, LUA_OPADD, "__add");
301
202k
}
302
303
132k
static int arith_sub (lua_State *L) {
304
132k
  return arith(L, LUA_OPSUB, "__sub");
305
132k
}
306
307
118k
static int arith_mul (lua_State *L) {
308
118k
  return arith(L, LUA_OPMUL, "__mul");
309
118k
}
310
311
87.2k
static int arith_mod (lua_State *L) {
312
87.2k
  return arith(L, LUA_OPMOD, "__mod");
313
87.2k
}
314
315
22.3k
static int arith_pow (lua_State *L) {
316
22.3k
  return arith(L, LUA_OPPOW, "__pow");
317
22.3k
}
318
319
29.8k
static int arith_div (lua_State *L) {
320
29.8k
  return arith(L, LUA_OPDIV, "__div");
321
29.8k
}
322
323
100k
static int arith_idiv (lua_State *L) {
324
100k
  return arith(L, LUA_OPIDIV, "__idiv");
325
100k
}
326
327
25.8k
static int arith_unm (lua_State *L) {
328
25.8k
  return arith(L, LUA_OPUNM, "__unm");
329
25.8k
}
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
282M
#define CAP_UNFINISHED  (-1)
357
9.07M
#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.52M
#define MAXCCALLS 200
381
#endif
382
383
384
203M
#define L_ESC   '%'
385
337k
#define SPECIALS  "^$*+?.([%-"
386
387
388
78.5M
static int check_capture (MatchState *ms, int l) {
389
78.5M
  l -= '1';
390
78.5M
  if (l_unlikely(l < 0 || l >= ms->level ||
391
78.5M
                 ms->capture[l].len == CAP_UNFINISHED))
392
35.1k
    return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
393
78.5M
  return l;
394
78.5M
}
395
396
397
77.1M
static int capture_to_close (MatchState *ms) {
398
77.1M
  int level = ms->level;
399
127M
  for (level--; level>=0; level--)
400
127M
    if (ms->capture[level].len == CAP_UNFINISHED) return level;
401
3.32k
  return luaL_error(ms->L, "invalid pattern capture");
402
77.1M
}
403
404
405
157M
static const char *classend (MatchState *ms, const char *p) {
406
157M
  switch (*p++) {
407
8.40M
    case L_ESC: {
408
8.40M
      if (l_unlikely(p == ms->p_end))
409
688
        luaL_error(ms->L, "malformed pattern (ends with '%%')");
410
8.40M
      return p+1;
411
0
    }
412
8.11M
    case '[': {
413
8.11M
      if (*p == '^') p++;
414
16.8M
      do {  /* look for a ']' */
415
16.8M
        if (l_unlikely(p == ms->p_end))
416
3.00k
          luaL_error(ms->L, "malformed pattern (missing ']')");
417
16.8M
        if (*(p++) == L_ESC && p < ms->p_end)
418
4.55M
          p++;  /* skip escapes (e.g. '%]') */
419
16.8M
      } while (*p != ']');
420
8.11M
      return p+1;
421
0
    }
422
140M
    default: {
423
140M
      return p;
424
0
    }
425
157M
  }
426
157M
}
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
1.69M
    case 'a' : res = isalpha(c); break;
433
356
    case 'c' : res = iscntrl(c); break;
434
5.26M
    case 'd' : res = isdigit(c); break;
435
8.04k
    case 'g' : res = isgraph(c); break;
436
192
    case 'l' : res = islower(c); break;
437
5
    case 'p' : res = ispunct(c); break;
438
3.27M
    case 's' : res = isspace(c); break;
439
44
    case 'u' : res = isupper(c); break;
440
42.4k
    case 'w' : res = isalnum(c); break;
441
3.92k
    case 'x' : res = isxdigit(c); break;
442
94.2k
    case 'z' : res = (c == 0); break;  /* deprecated option */
443
4.90M
    default: return (cl == c);
444
15.2M
  }
445
10.3M
  return (islower(cl) ? res : !res);
446
15.2M
}
447
448
449
9.45M
static int matchbracketclass (int c, const char *p, const char *ec) {
450
9.45M
  int sig = 1;
451
9.45M
  if (*(p+1) == '^') {
452
5.14M
    sig = 0;
453
5.14M
    p++;  /* skip the '^' */
454
5.14M
  }
455
26.1M
  while (++p < ec) {
456
16.8M
    if (*p == L_ESC) {
457
4.30M
      p++;
458
4.30M
      if (match_class(c, cast_uchar(*p)))
459
24.5k
        return sig;
460
4.30M
    }
461
12.4M
    else if ((*(p+1) == '-') && (p+2 < ec)) {
462
152k
      p+=2;
463
152k
      if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
464
15.7k
        return sig;
465
152k
    }
466
12.3M
    else if (cast_uchar(*p) == c) return sig;
467
16.8M
  }
468
9.35M
  return !sig;
469
9.45M
}
470
471
472
static int singlematch (MatchState *ms, const char *s, const char *p,
473
284M
                        const char *ep) {
474
284M
  if (s >= ms->src_end)
475
1.45M
    return 0;
476
283M
  else {
477
283M
    int c = cast_uchar(*s);
478
283M
    switch (*p) {
479
109M
      case '.': return 1;  /* matches any char */
480
10.9M
      case L_ESC: return match_class(c, cast_uchar(*(p+1)));
481
9.42M
      case '[': return matchbracketclass(c, p, ep-1);
482
153M
      default:  return (cast_uchar(*p) == c);
483
283M
    }
484
283M
  }
485
284M
}
486
487
488
static const char *matchbalance (MatchState *ms, const char *s,
489
153k
                                   const char *p) {
490
153k
  if (l_unlikely(p >= ms->p_end - 1))
491
644
    luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
492
153k
  if (*s != *p) return NULL;
493
1.05k
  else {
494
1.05k
    int b = *p;
495
1.05k
    int e = *(p+1);
496
1.05k
    int cont = 1;
497
14.9M
    while (++s < ms->src_end) {
498
14.9M
      if (*s == e) {
499
22.6k
        if (--cont == 0) return s+1;
500
22.6k
      }
501
14.9M
      else if (*s == b) cont++;
502
14.9M
    }
503
1.05k
  }
504
1.00k
  return NULL;  /* string ends out of balance */
505
153k
}
506
507
508
static const char *max_expand (MatchState *ms, const char *s,
509
1.27M
                                 const char *p, const char *ep) {
510
1.27M
  ptrdiff_t i = 0;  /* counts maximum expand for item */
511
91.7M
  while (singlematch(ms, s + i, p, ep))
512
90.4M
    i++;
513
  /* keeps trying to match with the maximum repetitions */
514
74.4M
  while (i>=0) {
515
73.7M
    const char *res = match(ms, (s+i), ep+1);
516
73.7M
    if (res) return res;
517
73.1M
    i--;  /* else didn't match; reduce 1 repetition to try again */
518
73.1M
  }
519
665k
  return NULL;
520
1.27M
}
521
522
523
static const char *min_expand (MatchState *ms, const char *s,
524
19.6k
                                 const char *p, const char *ep) {
525
36.0M
  for (;;) {
526
36.0M
    const char *res = match(ms, s, ep+1);
527
36.0M
    if (res != NULL)
528
8.90k
      return res;
529
36.0M
    else if (singlematch(ms, s, p, ep))
530
36.0M
      s++;  /* try with one more repetition */
531
10.7k
    else return NULL;
532
36.0M
  }
533
19.6k
}
534
535
536
static const char *start_capture (MatchState *ms, const char *s,
537
84.4M
                                    const char *p, int what) {
538
84.4M
  const char *res;
539
84.4M
  int level = ms->level;
540
84.4M
  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
541
84.4M
  ms->capture[level].init = s;
542
84.4M
  ms->capture[level].len = what;
543
84.4M
  ms->level = level+1;
544
84.4M
  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
545
83.2M
    ms->level--;  /* undo capture */
546
84.4M
  return res;
547
84.4M
}
548
549
550
static const char *end_capture (MatchState *ms, const char *s,
551
77.1M
                                  const char *p) {
552
77.1M
  int l = capture_to_close(ms);
553
77.1M
  const char *res;
554
77.1M
  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
555
77.1M
  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
556
76.5M
    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
557
77.1M
  return res;
558
77.1M
}
559
560
561
78.5M
static const char *match_capture (MatchState *ms, const char *s, int l) {
562
78.5M
  size_t len;
563
78.5M
  l = check_capture(ms, l);
564
78.5M
  len = cast_sizet(ms->capture[l].len);
565
78.5M
  if ((size_t)(ms->src_end-s) >= len &&
566
48.4M
      memcmp(ms->capture[l].init, s, len) == 0)
567
3.06M
    return s+len;
568
75.4M
  else return NULL;
569
78.5M
}
570
571
572
321M
static const char *match (MatchState *ms, const char *s, const char *p) {
573
321M
  if (l_unlikely(ms->matchdepth-- == 0))
574
1
    luaL_error(ms->L, "pattern too complex");
575
427M
  init: /* using goto to optimize tail recursion */
576
427M
  if (p != ms->p_end) {  /* end of pattern? */
577
425M
    switch (*p) {
578
84.4M
      case '(': {  /* start capture */
579
84.4M
        if (*(p + 1) == ')')  /* position capture? */
580
6.82M
          s = start_capture(ms, s, p + 2, CAP_POSITION);
581
77.6M
        else
582
77.6M
          s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
583
84.4M
        break;
584
0
      }
585
77.1M
      case ')': {  /* end capture */
586
77.1M
        s = end_capture(ms, s, p + 1);
587
77.1M
        break;
588
0
      }
589
28.6M
      case '$': {
590
28.6M
        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
591
58.3k
          goto dflt;  /* no; go to default */
592
28.5M
        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
593
28.5M
        break;
594
28.6M
      }
595
87.1M
      case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
596
87.1M
        switch (*(p + 1)) {
597
153k
          case 'b': {  /* balanced string? */
598
153k
            s = matchbalance(ms, s, p + 2);
599
153k
            if (s != NULL) {
600
52
              p += 4; goto init;  /* return match(ms, s, p + 4); */
601
52
            }  /* else fail (s == NULL) */
602
153k
            break;
603
153k
          }
604
153k
          case 'f': {  /* frontier? */
605
19.7k
            const char *ep; char previous;
606
19.7k
            p += 2;
607
19.7k
            if (l_unlikely(*p != '['))
608
303
              luaL_error(ms->L, "missing '[' after '%%f' in pattern");
609
19.7k
            ep = classend(ms, p);  /* points to what is next */
610
19.7k
            previous = (s == ms->src_init) ? '\0' : *(s - 1);
611
19.7k
            if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
612
9.89k
               matchbracketclass(cast_uchar(*s), p, ep - 1)) {
613
3.30k
              p = ep; goto init;  /* return match(ms, s, ep); */
614
3.30k
            }
615
16.4k
            s = NULL;  /* match failed */
616
16.4k
            break;
617
19.7k
          }
618
50.0M
          case '0': case '1': case '2': case '3':
619
78.5M
          case '4': case '5': case '6': case '7':
620
78.5M
          case '8': case '9': {  /* capture results (%0-%9)? */
621
78.5M
            s = match_capture(ms, s, cast_uchar(*(p + 1)));
622
78.5M
            if (s != NULL) {
623
3.06M
              p += 2; goto init;  /* return match(ms, s, p + 2) */
624
3.06M
            }
625
75.4M
            break;
626
78.5M
          }
627
75.4M
          default: goto dflt;
628
87.1M
        }
629
75.6M
        break;
630
87.1M
      }
631
157M
      default: dflt: {  /* pattern class plus optional suffix */
632
157M
        const char *ep = classend(ms, p);  /* points to optional suffix */
633
        /* does not match at least once? */
634
157M
        if (!singlematch(ms, s, p, ep)) {
635
121M
          if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
636
68.3M
            p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
637
68.3M
          }
638
52.8M
          else  /* '+' or no suffix */
639
52.8M
            s = NULL;  /* fail */
640
121M
        }
641
35.8M
        else {  /* matched once */
642
35.8M
          switch (*ep) {  /* handle optional suffix */
643
26.5M
            case '?': {  /* optional */
644
26.5M
              const char *res;
645
26.5M
              if ((res = match(ms, s + 1, ep + 1)) != NULL)
646
9.01k
                s = res;
647
26.5M
              else {
648
26.5M
                p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
649
26.5M
              }
650
9.01k
              break;
651
26.5M
            }
652
107k
            case '+':  /* 1 or more repetitions */
653
107k
              s++;  /* 1 match already done */
654
              /* FALLTHROUGH */
655
1.27M
            case '*':  /* 0 or more repetitions */
656
1.27M
              s = max_expand(ms, s, p, ep);
657
1.27M
              break;
658
19.6k
            case '-':  /* 0 or more repetitions (minimum) */
659
19.6k
              s = min_expand(ms, s, p, ep);
660
19.6k
              break;
661
7.93M
            default:  /* no suffix */
662
7.93M
              s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
663
35.8M
          }
664
35.8M
        }
665
54.1M
        break;
666
157M
      }
667
425M
    }
668
425M
  }
669
321M
  ms->matchdepth++;
670
321M
  return s;
671
427M
}
672
673
674
675
static const char *lmemfind (const char *s1, size_t l1,
676
56.6k
                               const char *s2, size_t l2) {
677
56.6k
  if (l2 == 0) return s1;  /* empty strings are everywhere */
678
56.0k
  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
679
55.6k
  else {
680
55.6k
    const char *init;  /* to search for a '*s2' inside 's1' */
681
55.6k
    l2--;  /* 1st char will be checked by 'memchr' */
682
55.6k
    l1 = l1-l2;  /* 's2' cannot be found after that */
683
79.1k
    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
684
72.3k
      init++;   /* 1st char is already checked */
685
72.3k
      if (memcmp(init, s2+1, l2) == 0)
686
48.8k
        return init-1;
687
23.4k
      else {  /* correct 'l1' and 's1' to try again */
688
23.4k
        l1 -= ct_diff2sz(init - s1);
689
23.4k
        s1 = init;
690
23.4k
      }
691
72.3k
    }
692
6.79k
    return NULL;  /* not found */
693
55.6k
  }
694
56.6k
}
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.41M
                              const char *e, const char **cap) {
706
1.41M
  if (i >= ms->level) {
707
558k
    if (l_unlikely(i != 0))
708
14.3k
      luaL_error(ms->L, "invalid capture index %%%d", i + 1);
709
558k
    *cap = s;
710
558k
    return (e - s);
711
558k
  }
712
853k
  else {
713
853k
    ptrdiff_t capl = ms->capture[i].len;
714
853k
    *cap = ms->capture[i].init;
715
853k
    if (l_unlikely(capl == CAP_UNFINISHED))
716
11.6k
      luaL_error(ms->L, "unfinished capture");
717
842k
    else if (capl == CAP_POSITION)
718
285k
      lua_pushinteger(ms->L,
719
285k
          ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
720
853k
    return capl;
721
853k
  }
722
1.41M
}
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
745k
                                                    const char *e) {
730
745k
  const char *cap;
731
745k
  ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
732
745k
  if (l != CAP_POSITION)
733
723k
    lua_pushlstring(ms->L, cap, cast_sizet(l));
734
  /* else position was already pushed */
735
745k
}
736
737
738
709k
static int push_captures (MatchState *ms, const char *s, const char *e) {
739
709k
  int i;
740
709k
  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
741
709k
  luaL_checkstack(ms->L, nlevels, "too many captures");
742
1.43M
  for (i = 0; i < nlevels; i++)
743
727k
    push_onecapture(ms, i, s, e);
744
709k
  return nlevels;  /* number of strings pushed */
745
709k
}
746
747
748
/* check whether pattern has no special characters */
749
292k
static int nospecials (const char *p, size_t l) {
750
292k
  size_t upto = 0;
751
337k
  do {
752
337k
    if (strpbrk(p + upto, SPECIALS))
753
236k
      return 0;  /* pattern has a special character */
754
101k
    upto += strlen(p + upto) + 1;  /* may have more after \0 */
755
101k
  } while (upto <= l);
756
56.0k
  return 1;  /* no special chars found */
757
292k
}
758
759
760
static void prepstate (MatchState *ms, lua_State *L,
761
1.52M
                       const char *s, size_t ls, const char *p, size_t lp) {
762
1.52M
  ms->L = L;
763
1.52M
  ms->matchdepth = MAXCCALLS;
764
1.52M
  ms->src_init = s;
765
1.52M
  ms->src_end = s + ls;
766
1.52M
  ms->p_end = p + lp;
767
1.52M
}
768
769
770
23.8M
static void reprepstate (MatchState *ms) {
771
23.8M
  ms->level = 0;
772
23.8M
  lua_assert(ms->matchdepth == MAXCCALLS);
773
23.8M
}
774
775
776
439k
static int str_find_aux (lua_State *L, int find) {
777
439k
  size_t ls, lp;
778
439k
  const char *s = luaL_checklstring(L, 1, &ls);
779
439k
  const char *p = luaL_checklstring(L, 2, &lp);
780
439k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
781
439k
  if (init > ls) {  /* start after string's end? */
782
124k
    luaL_pushfail(L);  /* cannot find anything */
783
124k
    return 1;
784
124k
  }
785
  /* explicit request or no special characters? */
786
314k
  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
787
    /* do a plain search */
788
56.6k
    const char *s2 = lmemfind(s + init, ls - init, p, lp);
789
56.6k
    if (s2) {
790
49.3k
      lua_pushinteger(L, ct_diff2S(s2 - s) + 1);
791
49.3k
      lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));
792
49.3k
      return 2;
793
49.3k
    }
794
56.6k
  }
795
258k
  else {
796
258k
    MatchState ms;
797
258k
    const char *s1 = s + init;
798
258k
    int anchor = (*p == '^');
799
258k
    if (anchor) {
800
5.11k
      p++; lp--;  /* skip anchor character */
801
5.11k
    }
802
258k
    prepstate(&ms, L, s, ls, p, lp);
803
12.3M
    do {
804
12.3M
      const char *res;
805
12.3M
      reprepstate(&ms);
806
12.3M
      if ((res=match(&ms, s1, p)) != NULL) {
807
12.2k
        if (find) {
808
1.95k
          lua_pushinteger(L, ct_diff2S(s1 - s) + 1);  /* start */
809
1.95k
          lua_pushinteger(L, ct_diff2S(res - s));   /* end */
810
1.95k
          return push_captures(&ms, NULL, 0) + 2;
811
1.95k
        }
812
10.2k
        else
813
10.2k
          return push_captures(&ms, s1, res);
814
12.2k
      }
815
12.3M
    } while (s1++ < ms.src_end && !anchor);
816
258k
  }
817
253k
  luaL_pushfail(L);  /* not found */
818
253k
  return 1;
819
314k
}
820
821
822
316k
static int str_find (lua_State *L) {
823
316k
  return str_find_aux(L, 1);
824
316k
}
825
826
827
122k
static int str_match (lua_State *L) {
828
122k
  return str_find_aux(L, 0);
829
122k
}
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
177k
static int gmatch_aux (lua_State *L) {
842
177k
  GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
843
177k
  const char *src;
844
177k
  gm->ms.L = L;
845
3.80M
  for (src = gm->src; src <= gm->ms.src_end; src++) {
846
3.63M
    const char *e;
847
3.63M
    reprepstate(&gm->ms);
848
3.63M
    if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
849
7.35k
      gm->src = gm->lastmatch = e;
850
7.35k
      return push_captures(&gm->ms, src, e);
851
7.35k
    }
852
3.63M
  }
853
170k
  return 0;  /* not found */
854
177k
}
855
856
857
276k
static int gmatch (lua_State *L) {
858
276k
  size_t ls, lp;
859
276k
  const char *s = luaL_checklstring(L, 1, &ls);
860
276k
  const char *p = luaL_checklstring(L, 2, &lp);
861
276k
  size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
862
276k
  GMatchState *gm;
863
276k
  lua_settop(L, 2);  /* keep strings on closure to avoid being collected */
864
276k
  gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
865
276k
  if (init > ls)  /* start after string's end? */
866
20.7k
    init = ls + 1;  /* avoid overflows in 's + init' */
867
276k
  prepstate(&gm->ms, L, s, ls, p, lp);
868
276k
  gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
869
276k
  lua_pushcclosure(L, gmatch_aux, 3);
870
276k
  return 1;
871
276k
}
872
873
874
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
875
600k
                                                   const char *e) {
876
600k
  size_t l;
877
600k
  lua_State *L = ms->L;
878
600k
  const char *news = lua_tolstring(L, 3, &l);
879
600k
  const char *p;
880
8.41M
  while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
881
7.81M
    luaL_addlstring(b, news, ct_diff2sz(p - news));
882
7.81M
    p++;  /* skip ESC */
883
7.81M
    if (*p == L_ESC)  /* '%%' */
884
7.01M
      luaL_addchar(b, *p);
885
798k
    else if (*p == '0')  /* '%0' */
886
130k
        luaL_addlstring(b, s, ct_diff2sz(e - s));
887
668k
    else if (isdigit(cast_uchar(*p))) {  /* '%n' */
888
666k
      const char *cap;
889
666k
      ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
890
666k
      if (resl == CAP_POSITION)
891
274k
        luaL_addvalue(b);  /* add position to accumulated result */
892
391k
      else
893
391k
        luaL_addlstring(b, cap, cast_sizet(resl));
894
666k
    }
895
1.89k
    else
896
1.89k
      luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
897
7.81M
    l -= ct_diff2sz(p + 1 - news);
898
7.81M
    news = p + 1;
899
7.81M
  }
900
600k
  luaL_addlstring(b, news, l);
901
600k
}
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.30M
                                      const char *e, int tr) {
911
1.30M
  lua_State *L = ms->L;
912
1.30M
  switch (tr) {
913
689k
    case LUA_TFUNCTION: {  /* call the function */
914
689k
      int n;
915
689k
      lua_pushvalue(L, 3);  /* push the function */
916
689k
      n = push_captures(ms, s, e);  /* all captures as arguments */
917
689k
      lua_call(L, n, 1);  /* call it */
918
689k
      break;
919
0
    }
920
18.0k
    case LUA_TTABLE: {  /* index the table */
921
18.0k
      push_onecapture(ms, 0, s, e);  /* first capture is the index */
922
18.0k
      lua_gettable(L, 3);
923
18.0k
      break;
924
0
    }
925
600k
    default: {  /* LUA_TNUMBER or LUA_TSTRING */
926
600k
      add_s(ms, b, s, e);  /* add value to the buffer */
927
600k
      return 1;  /* something changed */
928
0
    }
929
1.30M
  }
930
696k
  if (!lua_toboolean(L, -1)) {  /* nil or false? */
931
13.5k
    lua_pop(L, 1);  /* remove value */
932
13.5k
    luaL_addlstring(b, s, ct_diff2sz(e - s));  /* keep original text */
933
13.5k
    return 0;  /* no changes */
934
13.5k
  }
935
682k
  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
682k
  else {
939
682k
    luaL_addvalue(b);  /* add result to accumulator */
940
682k
    return 1;  /* something changed */
941
682k
  }
942
696k
}
943
944
945
1.00M
static int str_gsub (lua_State *L) {
946
1.00M
  size_t srcl, lp;
947
1.00M
  const char *src = luaL_checklstring(L, 1, &srcl);  /* subject */
948
1.00M
  const char *p = luaL_checklstring(L, 2, &lp);  /* pattern */
949
1.00M
  const char *lastmatch = NULL;  /* end of last match */
950
1.00M
  int tr = lua_type(L, 3);  /* replacement type */
951
  /* max replacements */
952
1.00M
  lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
953
1.00M
  int anchor = (*p == '^');
954
1.00M
  lua_Integer n = 0;  /* replacement count */
955
1.00M
  int changed = 0;  /* change flag */
956
1.00M
  MatchState ms;
957
1.00M
  luaL_Buffer b;
958
1.00M
  luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
959
1.00M
                   tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
960
1.00M
                      "string/function/table");
961
1.00M
  luaL_buffinit(L, &b);
962
1.00M
  if (anchor) {
963
8.57k
    p++; lp--;  /* skip anchor character */
964
8.57k
  }
965
1.00M
  prepstate(&ms, L, src, srcl, p, lp);
966
7.91M
  while (n < max_s) {
967
7.86M
    const char *e;
968
7.86M
    reprepstate(&ms);  /* (re)prepare state for new match */
969
7.86M
    if ((e = match(&ms, src, p)) != NULL && e != lastmatch) {  /* match? */
970
1.30M
      n++;
971
1.30M
      changed = add_value(&ms, &b, src, e, tr) | changed;
972
1.30M
      src = lastmatch = e;
973
1.30M
    }
974
6.56M
    else if (src < ms.src_end)  /* otherwise, skip one character */
975
5.60M
      luaL_addchar(&b, *src++);
976
955k
    else break;  /* end of subject */
977
6.91M
    if (anchor) break;
978
6.91M
  }
979
1.00M
  if (!changed)  /* no changes? */
980
377k
    lua_pushvalue(L, 1);  /* return original string */
981
629k
  else {  /* something changed */
982
629k
    luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));
983
629k
    luaL_pushresult(&b);  /* create and return new string */
984
629k
  }
985
1.00M
  lua_pushinteger(L, n);  /* number of substitutions */
986
1.00M
  return 2;
987
1.00M
}
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
3.30k
#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
876k
#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.30M
#define L_FMTFLAGSF "-+#0 "
1101
1102
/* valid flags for o, x, and X conversions */
1103
39.8k
#define L_FMTFLAGSX "-#0"
1104
1105
/* valid flags for d and i conversions */
1106
21.8k
#define L_FMTFLAGSI "-+0 "
1107
1108
/* valid flags for u conversions */
1109
6.85k
#define L_FMTFLAGSU "-0"
1110
1111
/* valid flags for c, p, and s conversions */
1112
71.5k
#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
843k
#define MAX_FORMAT  32
1124
1125
1126
15.4k
static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
1127
15.4k
  luaL_addchar(b, '"');
1128
617M
  while (len--) {
1129
617M
    if (*s == '"' || *s == '\\' || *s == '\n') {
1130
1.86M
      luaL_addchar(b, '\\');
1131
1.86M
      luaL_addchar(b, *s);
1132
1.86M
    }
1133
616M
    else if (iscntrl(cast_uchar(*s))) {
1134
3.54M
      char buff[10];
1135
3.54M
      if (!isdigit(cast_uchar(*(s+1))))
1136
3.52M
        l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
1137
15.6k
      else
1138
15.6k
        l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s));
1139
3.54M
      luaL_addstring(b, buff);
1140
3.54M
    }
1141
612M
    else
1142
612M
      luaL_addchar(b, *s);
1143
617M
    s++;
1144
617M
  }
1145
15.4k
  luaL_addchar(b, '"');
1146
15.4k
}
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
7.53k
static int quotefloat (lua_State *L, char *buff, lua_Number n) {
1156
7.53k
  const char *s;  /* for the fixed representations */
1157
7.53k
  if (n == (lua_Number)HUGE_VAL)  /* inf? */
1158
3.66k
    s = "1e9999";
1159
3.87k
  else if (n == -(lua_Number)HUGE_VAL)  /* -inf? */
1160
955
    s = "-1e9999";
1161
2.92k
  else if (n != n)  /* NaN? */
1162
1.27k
    s = "(0/0)";
1163
1.64k
  else {  /* format number as hexadecimal */
1164
1.64k
    int  nb = lua_number2strx(L, buff, MAX_ITEM,
1165
1.64k
                                 "%" LUA_NUMBER_FRMLEN "a", n);
1166
    /* ensures that 'buff' string uses a dot as the radix character */
1167
1.64k
    if (memchr(buff, '.', cast_uint(nb)) == NULL) {  /* no dot? */
1168
1.26k
      char point = lua_getlocaledecpoint();  /* try locale point */
1169
1.26k
      char *ppoint = (char *)memchr(buff, point, cast_uint(nb));
1170
1.26k
      if (ppoint) *ppoint = '.';  /* change it to a dot */
1171
1.26k
    }
1172
1.64k
    return nb;
1173
1.64k
  }
1174
  /* for the fixed representations */
1175
5.89k
  return l_sprintf(buff, MAX_ITEM, "%s", s);
1176
7.53k
}
1177
1178
1179
24.1k
static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
1180
24.1k
  switch (lua_type(L, arg)) {
1181
15.4k
    case LUA_TSTRING: {
1182
15.4k
      size_t len;
1183
15.4k
      const char *s = lua_tolstring(L, arg, &len);
1184
15.4k
      addquoted(b, s, len);
1185
15.4k
      break;
1186
0
    }
1187
7.83k
    case LUA_TNUMBER: {
1188
7.83k
      char *buff = luaL_prepbuffsize(b, MAX_ITEM);
1189
7.83k
      int nb;
1190
7.83k
      if (!lua_isinteger(L, arg))  /* float? */
1191
7.53k
        nb = quotefloat(L, buff, lua_tonumber(L, arg));
1192
298
      else {  /* integers */
1193
298
        lua_Integer n = lua_tointeger(L, arg);
1194
298
        const char *format = (n == LUA_MININTEGER)  /* corner case? */
1195
298
                           ? "0x%" LUA_INTEGER_FRMLEN "x"  /* use hex */
1196
298
                           : LUA_INTEGER_FMT;  /* else use default format */
1197
298
        nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
1198
298
      }
1199
7.83k
      luaL_addsize(b, cast_uint(nb));
1200
7.83k
      break;
1201
0
    }
1202
910
    case LUA_TNIL: case LUA_TBOOLEAN: {
1203
910
      luaL_tolstring(L, arg, NULL);
1204
910
      luaL_addvalue(b);
1205
910
      break;
1206
691
    }
1207
0
    default: {
1208
0
      luaL_argerror(L, arg, "value has no literal form");
1209
0
    }
1210
24.1k
  }
1211
24.1k
}
1212
1213
1214
806k
static const char *get2digits (const char *s) {
1215
806k
  if (isdigit(cast_uchar(*s))) {
1216
326k
    s++;
1217
326k
    if (isdigit(cast_uchar(*s))) s++;  /* (2 digits at most) */
1218
326k
  }
1219
806k
  return s;
1220
806k
}
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
519k
                                       int precision) {
1231
519k
  const char *spec = form + 1;  /* skip '%' */
1232
519k
  spec += strspn(spec, flags);  /* skip flags */
1233
519k
  if (*spec != '0') {  /* a width cannot start with '0' */
1234
508k
    spec = get2digits(spec);  /* skip width */
1235
508k
    if (*spec == '.' && precision) {
1236
298k
      spec++;
1237
298k
      spec = get2digits(spec);  /* skip precision */
1238
298k
    }
1239
508k
  }
1240
519k
  if (!isalpha(cast_uchar(*spec)))  /* did not go to the end? */
1241
16.7k
    luaL_error(L, "invalid conversion specification: '%s'", form);
1242
519k
}
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
843k
                                            char *form) {
1251
  /* spans flags, width, and precision ('0' is included as a flag) */
1252
843k
  size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
1253
843k
  len++;  /* adds following character (should be the specifier) */
1254
  /* still needs space for '%', '\0', plus a length modifier */
1255
843k
  if (len >= MAX_FORMAT - 10)
1256
9.04k
    luaL_error(L, "invalid format (too long)");
1257
843k
  *(form++) = '%';
1258
843k
  memcpy(form, strfrmt, len * sizeof(char));
1259
843k
  *(form + len) = '\0';
1260
843k
  return strfrmt + len - 1;
1261
843k
}
1262
1263
1264
/*
1265
** add length modifier into formats
1266
*/
1267
467k
static void addlenmod (char *form, const char *lenmod) {
1268
467k
  size_t l = strlen(form);
1269
467k
  size_t lm = strlen(lenmod);
1270
467k
  char spec = form[l - 1];
1271
467k
  strcpy(form + l - 1, lenmod);
1272
467k
  form[l + lm - 1] = spec;
1273
467k
  form[l + lm] = '\0';
1274
467k
}
1275
1276
1277
1.67M
static int str_format (lua_State *L) {
1278
1.67M
  int top = lua_gettop(L);
1279
1.67M
  int arg = 1;
1280
1.67M
  size_t sfl;
1281
1.67M
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
1282
1.67M
  const char *strfrmt_end = strfrmt+sfl;
1283
1.67M
  const char *flags;
1284
1.67M
  luaL_Buffer b;
1285
1.67M
  luaL_buffinit(L, &b);
1286
30.1M
  while (strfrmt < strfrmt_end) {
1287
28.7M
    if (*strfrmt != L_ESC)
1288
27.7M
      luaL_addchar(&b, *strfrmt++);
1289
1.00M
    else if (*++strfrmt == L_ESC)
1290
136k
      luaL_addchar(&b, *strfrmt++);  /* %% */
1291
868k
    else { /* format item */
1292
868k
      char form[MAX_FORMAT];  /* to store the format ('%...') */
1293
868k
      unsigned maxitem = MAX_ITEM;  /* maximum length for the result */
1294
868k
      char *buff = luaL_prepbuffsize(&b, maxitem);  /* to put result */
1295
868k
      int nb = 0;  /* number of bytes in result */
1296
868k
      if (++arg > top)
1297
24.7k
        return luaL_argerror(L, arg, "no value");
1298
843k
      strfrmt = getformat(L, strfrmt, form);
1299
843k
      switch (*strfrmt++) {
1300
21.4k
        case 'c': {
1301
21.4k
          checkformat(L, form, L_FMTFLAGSC, 0);
1302
21.4k
          nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
1303
21.4k
          break;
1304
0
        }
1305
21.8k
        case 'd': case 'i':
1306
21.8k
          flags = L_FMTFLAGSI;
1307
21.8k
          goto intcase;
1308
6.85k
        case 'u':
1309
6.85k
          flags = L_FMTFLAGSU;
1310
6.85k
          goto intcase;
1311
39.8k
        case 'o': case 'x': case 'X':
1312
39.8k
          flags = L_FMTFLAGSX;
1313
68.5k
         intcase: {
1314
68.5k
          lua_Integer n = luaL_checkinteger(L, arg);
1315
68.5k
          checkformat(L, form, flags, 1);
1316
68.5k
          addlenmod(form, LUA_INTEGER_FRMLEN);
1317
68.5k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
1318
68.5k
          break;
1319
39.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
3.30k
        case 'f':
1327
3.30k
          maxitem = MAX_ITEMF;  /* extra space for '%f' */
1328
3.30k
          buff = luaL_prepbuffsize(&b, maxitem);
1329
          /* FALLTHROUGH */
1330
308k
        case 'e': case 'E': case 'g': case 'G': {
1331
308k
          lua_Number n = luaL_checknumber(L, arg);
1332
308k
          checkformat(L, form, L_FMTFLAGSF, 1);
1333
308k
          addlenmod(form, LUA_NUMBER_FRMLEN);
1334
308k
          nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
1335
308k
          break;
1336
304k
        }
1337
9.80k
        case 'p': {
1338
9.80k
          const void *p = lua_topointer(L, arg);
1339
9.80k
          checkformat(L, form, L_FMTFLAGSC, 0);
1340
9.80k
          if (p == NULL) {  /* avoid calling 'printf' with argument NULL */
1341
657
            p = "(null)";  /* result */
1342
657
            form[strlen(form) - 1] = 's';  /* format it as a string */
1343
657
          }
1344
9.80k
          nb = l_sprintf(buff, maxitem, form, p);
1345
9.80k
          break;
1346
304k
        }
1347
24.1k
        case 'q': {
1348
24.1k
          if (form[2] != '\0')  /* modifiers? */
1349
36
            return luaL_error(L, "specifier '%%q' cannot have modifiers");
1350
24.1k
          addliteral(L, &b, arg);
1351
24.1k
          break;
1352
24.1k
        }
1353
145k
        case 's': {
1354
145k
          size_t l;
1355
145k
          const char *s = luaL_tolstring(L, arg, &l);
1356
145k
          if (form[2] == '\0')  /* no modifiers? */
1357
104k
            luaL_addvalue(&b);  /* keep entire string */
1358
40.3k
          else {
1359
40.3k
            luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
1360
40.3k
            checkformat(L, form, L_FMTFLAGSC, 1);
1361
40.3k
            if (strchr(form, '.') == NULL && l >= 100) {
1362
              /* no precision and string is too long to be formatted */
1363
3.69k
              luaL_addvalue(&b);  /* keep entire string */
1364
3.69k
            }
1365
36.6k
            else {  /* format the string into 'buff' */
1366
36.6k
              nb = l_sprintf(buff, maxitem, form, s);
1367
36.6k
              lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
1368
36.6k
            }
1369
40.3k
          }
1370
145k
          break;
1371
24.1k
        }
1372
101k
        default: {  /* also treat cases 'pnLlh' */
1373
101k
          return luaL_error(L, "invalid conversion '%s' to 'format'", form);
1374
24.1k
        }
1375
843k
      }
1376
606k
      lua_assert(cast_uint(nb) < maxitem);
1377
606k
      luaL_addsize(&b, cast_uint(nb));
1378
606k
    }
1379
28.7M
  }
1380
1.41M
  luaL_pushresult(&b);
1381
1.41M
  return 1;
1382
1.67M
}
1383
1384
/* }====================================================== */
1385
1386
1387
/*
1388
** {======================================================
1389
** PACK/UNPACK
1390
** =======================================================
1391
*/
1392
1393
1394
/* value used for padding */
1395
#if !defined(LUAL_PACKPADBYTE)
1396
347k
#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.43M
#define NB  CHAR_BIT
1404
1405
/* mask for one character (NB 1's) */
1406
1.63M
#define MC  ((1 << NB) - 1)
1407
1408
/* size of a lua_Integer */
1409
664k
#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
2.52M
static int digit (int c) { return '0' <= c && c <= '9'; }
1452
1453
878k
static size_t getnum (const char **fmt, size_t df) {
1454
878k
  if (!digit(**fmt))  /* no number? */
1455
470k
    return df;  /* return default value */
1456
408k
  else {
1457
408k
    size_t a = 0;
1458
1.64M
    do {
1459
1.64M
      a = a*10 + cast_uint(*((*fmt)++) - '0');
1460
1.64M
    } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);
1461
408k
    return a;
1462
408k
  }
1463
878k
}
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
524k
static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
1471
524k
  size_t sz = getnum(fmt, df);
1472
524k
  if (l_unlikely((sz - 1u) >= MAXINTSIZE))
1473
5.82k
    return cast_uint(luaL_error(h->L,
1474
518k
               "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
1475
518k
  return cast_uint(sz);
1476
524k
}
1477
1478
1479
/*
1480
** Initialize Header
1481
*/
1482
705k
static void initheader (lua_State *L, Header *h) {
1483
705k
  h->L = L;
1484
705k
  h->islittle = nativeendian.little;
1485
705k
  h->maxalign = 1;
1486
705k
}
1487
1488
1489
/*
1490
** Read and classify next option. 'size' is filled with option's size.
1491
*/
1492
2.89M
static KOption getoption (Header *h, const char **fmt, size_t *size) {
1493
  /* dummy structure to get native alignment requirements */
1494
2.89M
  struct cD { char c; union { LUAI_MAXALIGN; } u; };
1495
2.89M
  int opt = *((*fmt)++);
1496
2.89M
  *size = 0;  /* default */
1497
2.89M
  switch (opt) {
1498
2.57k
    case 'b': *size = sizeof(char); return Kint;
1499
6.16k
    case 'B': *size = sizeof(char); return Kuint;
1500
59.8k
    case 'h': *size = sizeof(short); return Kint;
1501
8.53k
    case 'H': *size = sizeof(short); return Kuint;
1502
148k
    case 'l': *size = sizeof(long); return Kint;
1503
15.1k
    case 'L': *size = sizeof(long); return Kuint;
1504
201k
    case 'j': *size = sizeof(lua_Integer); return Kint;
1505
573
    case 'J': *size = sizeof(lua_Integer); return Kuint;
1506
264
    case 'T': *size = sizeof(size_t); return Kuint;
1507
12.1k
    case 'f': *size = sizeof(float); return Kfloat;
1508
11.1k
    case 'n': *size = sizeof(lua_Number); return Knumber;
1509
6.62k
    case 'd': *size = sizeof(double); return Kdouble;
1510
46.9k
    case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1511
7.34k
    case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1512
175k
    case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1513
354k
    case 'c':
1514
354k
      *size = getnum(fmt, cast_sizet(-1));
1515
354k
      if (l_unlikely(*size == cast_sizet(-1)))
1516
169
        luaL_error(h->L, "missing size for format option 'c'");
1517
354k
      return Kchar;
1518
991
    case 'z': return Kzstr;
1519
583k
    case 'x': *size = 1; return Kpadding;
1520
216k
    case 'X': return Kpaddalign;
1521
35.0k
    case ' ': break;
1522
80.7k
    case '<': h->islittle = 1; break;
1523
597k
    case '>': h->islittle = 0; break;
1524
5.20k
    case '=': h->islittle = nativeendian.little; break;
1525
294k
    case '!': {
1526
294k
      const size_t maxalign = offsetof(struct cD, u);
1527
294k
      h->maxalign = getnumlimit(h, fmt, maxalign);
1528
294k
      break;
1529
0
    }
1530
24.7k
    default: luaL_error(h->L, "invalid format option '%c'", opt);
1531
2.89M
  }
1532
1.01M
  return Knop;
1533
2.89M
}
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
2.68M
                           size_t *psize, unsigned *ntoalign) {
1547
2.68M
  KOption opt = getoption(h, fmt, psize);
1548
2.68M
  size_t align = *psize;  /* usually, alignment follows size */
1549
2.68M
  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
1550
216k
    if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1551
1.63k
      luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1552
216k
  }
1553
2.68M
  if (align <= 1 || opt == Kchar)  /* need no alignment? */
1554
1.96M
    *ntoalign = 0;
1555
714k
  else {
1556
714k
    if (align > h->maxalign)  /* enforce maximum alignment */
1557
341k
      align = h->maxalign;
1558
714k
    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
713k
    else {
1563
      /* 'szmoda' = totalsize % align */
1564
713k
      unsigned szmoda = cast_uint(totalsize & (align - 1));
1565
713k
      *ntoalign = cast_uint((align - szmoda) & (align - 1));
1566
713k
    }
1567
714k
  }
1568
2.68M
  return opt;
1569
2.68M
}
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
238k
                     int islittle, unsigned size, int neg) {
1580
238k
  char *buff = luaL_prepbuffsize(b, size);
1581
238k
  unsigned i;
1582
238k
  buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */
1583
1.58M
  for (i = 1; i < size; i++) {
1584
1.34M
    n >>= NB;
1585
1.34M
    buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1586
1.34M
  }
1587
238k
  if (neg && size > SZINT) {  /* negative number need sign extension? */
1588
64.7k
    for (i = SZINT; i < size; i++)  /* correct extra bytes */
1589
53.9k
      buff[islittle ? i : size - 1 - i] = (char)MC;
1590
10.7k
  }
1591
238k
  luaL_addsize(b, size);  /* add result to buffer */
1592
238k
}
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
21.5k
                            unsigned size, int islittle) {
1601
21.5k
  if (islittle == nativeendian.little)
1602
11.8k
    memcpy(dest, src, size);
1603
9.77k
  else {
1604
9.77k
    dest += size - 1;
1605
74.8k
    while (size-- != 0)
1606
65.1k
      *(dest--) = *(src++);
1607
9.77k
  }
1608
21.5k
}
1609
1610
1611
668k
static int str_pack (lua_State *L) {
1612
668k
  luaL_Buffer b;
1613
668k
  Header h;
1614
668k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1615
668k
  int arg = 1;  /* current argument to pack */
1616
668k
  size_t totalsize = 0;  /* accumulate total size of result */
1617
668k
  initheader(L, &h);
1618
668k
  lua_pushnil(L);  /* mark to separate arguments from string buffer */
1619
668k
  luaL_buffinit(L, &b);
1620
2.99M
  while (*fmt != '\0') {
1621
2.36M
    unsigned ntoalign;
1622
2.36M
    size_t size;
1623
2.36M
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1624
2.36M
    luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,
1625
2.36M
                     "result too long");
1626
2.36M
    totalsize += ntoalign + size;
1627
4.19M
    while (ntoalign-- > 0)
1628
1.83M
     luaL_addchar(&b, LUAL_PACKPADBYTE);  /* fill alignment */
1629
2.36M
    arg++;
1630
2.36M
    switch (opt) {
1631
78.7k
      case Kint: {  /* signed integers */
1632
78.7k
        lua_Integer n = luaL_checkinteger(L, arg);
1633
78.7k
        if (size < SZINT) {  /* need overflow check? */
1634
62.5k
          lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1635
62.5k
          luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1636
62.5k
        }
1637
78.7k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
1638
78.7k
        break;
1639
0
      }
1640
3.90k
      case Kuint: {  /* unsigned integers */
1641
3.90k
        lua_Integer n = luaL_checkinteger(L, arg);
1642
3.90k
        if (size < SZINT)  /* need overflow check? */
1643
2.48k
          luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1644
3.90k
                           arg, "unsigned overflow");
1645
3.90k
        packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
1646
3.90k
        break;
1647
0
      }
1648
886
      case Kfloat: {  /* C float */
1649
886
        float f = (float)luaL_checknumber(L, arg);  /* get argument */
1650
886
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1651
        /* move 'f' to final result, correcting endianness if needed */
1652
886
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1653
886
        luaL_addsize(&b, size);
1654
886
        break;
1655
0
      }
1656
3.30k
      case Knumber: {  /* Lua float */
1657
3.30k
        lua_Number f = luaL_checknumber(L, arg);  /* get argument */
1658
3.30k
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1659
        /* move 'f' to final result, correcting endianness if needed */
1660
3.30k
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1661
3.30k
        luaL_addsize(&b, size);
1662
3.30k
        break;
1663
0
      }
1664
429
      case Kdouble: {  /* C double */
1665
429
        double f = (double)luaL_checknumber(L, arg);  /* get argument */
1666
429
        char *buff = luaL_prepbuffsize(&b, sizeof(f));
1667
        /* move 'f' to final result, correcting endianness if needed */
1668
429
        copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
1669
429
        luaL_addsize(&b, size);
1670
429
        break;
1671
0
      }
1672
348k
      case Kchar: {  /* fixed-size string */
1673
348k
        size_t len;
1674
348k
        const char *s = luaL_checklstring(L, arg, &len);
1675
348k
        luaL_argcheck(L, len <= size, arg, "string longer than given size");
1676
348k
        luaL_addlstring(&b, s, len);  /* add string */
1677
348k
        if (len < size) {  /* does it need padding? */
1678
347k
          size_t psize = size - len;  /* pad size */
1679
347k
          char *buff = luaL_prepbuffsize(&b, psize);
1680
347k
          memset(buff, LUAL_PACKPADBYTE, psize);
1681
347k
          luaL_addsize(&b, psize);
1682
347k
        }
1683
348k
        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
242
      case Kzstr: {  /* zero-terminated string */
1698
242
        size_t len;
1699
242
        const char *s = luaL_checklstring(L, arg, &len);
1700
242
        luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1701
242
        luaL_addlstring(&b, s, len);
1702
242
        luaL_addchar(&b, '\0');  /* add zero at the end */
1703
242
        totalsize += len + 1;
1704
242
        break;
1705
0
      }
1706
578k
      case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE);  /* FALLTHROUGH */
1707
1.73M
      case Kpaddalign: case Knop:
1708
1.73M
        arg--;  /* undo increment */
1709
1.73M
        break;
1710
2.36M
    }
1711
2.36M
  }
1712
635k
  luaL_pushresult(&b);
1713
635k
  return 1;
1714
668k
}
1715
1716
1717
1.85k
static int str_packsize (lua_State *L) {
1718
1.85k
  Header h;
1719
1.85k
  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1720
1.85k
  size_t totalsize = 0;  /* accumulate total size of result */
1721
1.85k
  initheader(L, &h);
1722
58.5k
  while (*fmt != '\0') {
1723
56.7k
    unsigned ntoalign;
1724
56.7k
    size_t size;
1725
56.7k
    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1726
56.7k
    luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
1727
56.7k
                     "variable-length format");
1728
56.7k
    size += ntoalign;  /* total space used by option */
1729
56.7k
    luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size,
1730
56.7k
                     1, "format result too large");
1731
56.7k
    totalsize += size;
1732
56.7k
  }
1733
1.85k
  lua_pushinteger(L, cast_st2S(totalsize));
1734
1.85k
  return 1;
1735
1.85k
}
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
186k
                              int islittle, int size, int issigned) {
1748
186k
  lua_Unsigned res = 0;
1749
186k
  int i;
1750
186k
  int limit = (size  <= SZINT) ? size : SZINT;
1751
1.56M
  for (i = limit - 1; i >= 0; i--) {
1752
1.38M
    res <<= NB;
1753
1.38M
    res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
1754
1.38M
  }
1755
186k
  if (size < SZINT) {  /* real size smaller than lua_Integer? */
1756
18.5k
    if (issigned) {  /* needs sign extension? */
1757
11.9k
      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1758
11.9k
      res = ((res ^ mask) - mask);  /* do sign extension */
1759
11.9k
    }
1760
18.5k
  }
1761
168k
  else if (size > SZINT) {  /* must check unread bytes */
1762
17.6k
    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1763
90.0k
    for (i = limit; i < size; i++) {
1764
72.4k
      if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
1765
5.71k
        luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
1766
72.4k
    }
1767
17.6k
  }
1768
186k
  return (lua_Integer)res;
1769
186k
}
1770
1771
1772
34.9k
static int str_unpack (lua_State *L) {
1773
34.9k
  Header h;
1774
34.9k
  const char *fmt = luaL_checkstring(L, 1);
1775
34.9k
  size_t ld;
1776
34.9k
  const char *data = luaL_checklstring(L, 2, &ld);
1777
34.9k
  size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
1778
34.9k
  int n = 0;  /* number of results */
1779
34.9k
  luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1780
34.9k
  initheader(L, &h);
1781
277k
  while (*fmt != '\0') {
1782
260k
    unsigned ntoalign;
1783
260k
    size_t size;
1784
260k
    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1785
260k
    luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
1786
260k
                    "data string too short");
1787
260k
    pos += ntoalign;  /* skip alignment */
1788
    /* stack space for item + next position */
1789
260k
    luaL_checkstack(L, 2, "too many results");
1790
260k
    n++;
1791
260k
    switch (opt) {
1792
166k
      case Kint:
1793
176k
      case Kuint: {
1794
176k
        lua_Integer res = unpackint(L, data + pos, h.islittle,
1795
176k
                                       cast_int(size), (opt == Kint));
1796
176k
        lua_pushinteger(L, res);
1797
176k
        break;
1798
166k
      }
1799
10.9k
      case Kfloat: {
1800
10.9k
        float f;
1801
10.9k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1802
10.9k
        lua_pushnumber(L, (lua_Number)f);
1803
10.9k
        break;
1804
166k
      }
1805
2.92k
      case Knumber: {
1806
2.92k
        lua_Number f;
1807
2.92k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1808
2.92k
        lua_pushnumber(L, f);
1809
2.92k
        break;
1810
166k
      }
1811
3.15k
      case Kdouble: {
1812
3.15k
        double f;
1813
3.15k
        copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
1814
3.15k
        lua_pushnumber(L, (lua_Number)f);
1815
3.15k
        break;
1816
166k
      }
1817
5.14k
      case Kchar: {
1818
5.14k
        lua_pushlstring(L, data + pos, size);
1819
5.14k
        break;
1820
166k
      }
1821
10.6k
      case Kstring: {
1822
10.6k
        lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
1823
10.6k
                                          h.islittle, cast_int(size), 0);
1824
10.6k
        luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
1825
10.6k
        lua_pushlstring(L, data + pos + size, cast_sizet(len));
1826
10.6k
        pos += cast_sizet(len);  /* skip string */
1827
10.6k
        break;
1828
166k
      }
1829
746
      case Kzstr: {
1830
746
        size_t len = strlen(data + pos);
1831
746
        luaL_argcheck(L, pos + len < ld, 2,
1832
746
                         "unfinished string for format 'z'");
1833
746
        lua_pushlstring(L, data + pos, len);
1834
746
        pos += len + 1;  /* skip string plus final '\0' */
1835
746
        break;
1836
166k
      }
1837
42.6k
      case Kpaddalign: case Kpadding: case Knop:
1838
42.6k
        n--;  /* undo increment */
1839
42.6k
        break;
1840
260k
    }
1841
243k
    pos += size;
1842
243k
  }
1843
17.7k
  lua_pushinteger(L, cast_st2S(pos) + 1);  /* next position */
1844
17.7k
  return n + 1;
1845
34.9k
}
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.6k
static void createmetatable (lua_State *L) {
1873
  /* table to be metatable for strings */
1874
29.6k
  luaL_newlibtable(L, stringmetamethods);
1875
29.6k
  luaL_setfuncs(L, stringmetamethods, 0);
1876
29.6k
  lua_pushliteral(L, "");  /* dummy string */
1877
29.6k
  lua_pushvalue(L, -2);  /* copy table */
1878
29.6k
  lua_setmetatable(L, -2);  /* set table as metatable for strings */
1879
29.6k
  lua_pop(L, 1);  /* pop dummy string */
1880
29.6k
  lua_pushvalue(L, -2);  /* get string library */
1881
29.6k
  lua_setfield(L, -2, "__index");  /* metatable.__index = string */
1882
29.6k
  lua_pop(L, 1);  /* pop metatable */
1883
29.6k
}
1884
1885
1886
/*
1887
** Open string library
1888
*/
1889
29.6k
LUAMOD_API int luaopen_string (lua_State *L) {
1890
29.6k
  luaL_newlib(L, strlib);
1891
29.6k
  createmetatable(L);
1892
29.6k
  return 1;
1893
29.6k
}
1894