Coverage Report

Created: 2026-04-11 06:45

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