Coverage Report

Created: 2025-11-24 06:29

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