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