Coverage Report

Created: 2025-10-10 06:41

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