1 /* $NetBSD: lstrlib.c,v 1.12 2016/03/25 08:15:20 mbalmer Exp $ */ 2 3 /* 4 ** Id: lstrlib.c,v 1.239 2015/11/25 16:28:17 roberto Exp 5 ** Standard library for string operations and pattern-matching 6 ** See Copyright Notice in lua.h 7 */ 8 9 #define lstrlib_c 10 #define LUA_LIB 11 12 #include "lprefix.h" 13 14 15 #ifndef _KERNEL 16 #include <ctype.h> 17 #include <float.h> 18 #include <limits.h> 19 #include <stddef.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #endif /* _KERNEL */ 24 25 #include "lua.h" 26 27 #include "lauxlib.h" 28 #include "lualib.h" 29 30 31 /* 32 ** maximum number of captures that a pattern can do during 33 ** pattern-matching. This limit is arbitrary. 34 */ 35 #if !defined(LUA_MAXCAPTURES) 36 #define LUA_MAXCAPTURES 32 37 #endif 38 39 40 /* macro to 'unsign' a character */ 41 #define uchar(c) ((unsigned char)(c)) 42 43 44 /* 45 ** Some sizes are better limited to fit in 'int', but must also fit in 46 ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) 47 */ 48 #define MAX_SIZET ((size_t)(~(size_t)0)) 49 50 #define MAXSIZE \ 51 (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) 52 53 54 55 56 static int str_len (lua_State *L) { 57 size_t l; 58 luaL_checklstring(L, 1, &l); 59 lua_pushinteger(L, (lua_Integer)l); 60 return 1; 61 } 62 63 64 /* translate a relative string position: negative means back from end */ 65 static lua_Integer posrelat (lua_Integer pos, size_t len) { 66 if (pos >= 0) return pos; 67 else if (0u - (size_t)pos > len) return 0; 68 else return (lua_Integer)len + pos + 1; 69 } 70 71 72 static int str_sub (lua_State *L) { 73 size_t l; 74 const char *s = luaL_checklstring(L, 1, &l); 75 lua_Integer start = posrelat(luaL_checkinteger(L, 2), l); 76 lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l); 77 if (start < 1) start = 1; 78 if (end > (lua_Integer)l) end = l; 79 if (start <= end) 80 lua_pushlstring(L, s + start - 1, (size_t)(end - start) + 1); 81 else lua_pushliteral(L, ""); 82 return 1; 83 } 84 85 86 static int str_reverse (lua_State *L) { 87 size_t l, i; 88 luaL_Buffer b; 89 const char *s = luaL_checklstring(L, 1, &l); 90 char *p = luaL_buffinitsize(L, &b, l); 91 for (i = 0; i < l; i++) 92 p[i] = s[l - i - 1]; 93 luaL_pushresultsize(&b, l); 94 return 1; 95 } 96 97 98 static int str_lower (lua_State *L) { 99 size_t l; 100 size_t i; 101 luaL_Buffer b; 102 const char *s = luaL_checklstring(L, 1, &l); 103 char *p = luaL_buffinitsize(L, &b, l); 104 for (i=0; i<l; i++) 105 p[i] = tolower(uchar(s[i])); 106 luaL_pushresultsize(&b, l); 107 return 1; 108 } 109 110 111 static int str_upper (lua_State *L) { 112 size_t l; 113 size_t i; 114 luaL_Buffer b; 115 const char *s = luaL_checklstring(L, 1, &l); 116 char *p = luaL_buffinitsize(L, &b, l); 117 for (i=0; i<l; i++) 118 p[i] = toupper(uchar(s[i])); 119 luaL_pushresultsize(&b, l); 120 return 1; 121 } 122 123 124 static int str_rep (lua_State *L) { 125 size_t l, lsep; 126 const char *s = luaL_checklstring(L, 1, &l); 127 lua_Integer n = luaL_checkinteger(L, 2); 128 const char *sep = luaL_optlstring(L, 3, "", &lsep); 129 if (n <= 0) lua_pushliteral(L, ""); 130 else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */ 131 return luaL_error(L, "resulting string too large"); 132 else { 133 size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; 134 luaL_Buffer b; 135 char *p = luaL_buffinitsize(L, &b, totallen); 136 while (n-- > 1) { /* first n-1 copies (followed by separator) */ 137 memcpy(p, s, l * sizeof(char)); p += l; 138 if (lsep > 0) { /* empty 'memcpy' is not that cheap */ 139 memcpy(p, sep, lsep * sizeof(char)); 140 p += lsep; 141 } 142 } 143 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ 144 luaL_pushresultsize(&b, totallen); 145 } 146 return 1; 147 } 148 149 150 static int str_byte (lua_State *L) { 151 size_t l; 152 const char *s = luaL_checklstring(L, 1, &l); 153 lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l); 154 lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l); 155 int n, i; 156 if (posi < 1) posi = 1; 157 if (pose > (lua_Integer)l) pose = l; 158 if (posi > pose) return 0; /* empty interval; return no values */ 159 if (pose - posi >= INT_MAX) /* arithmetic overflow? */ 160 return luaL_error(L, "string slice too long"); 161 n = (int)(pose - posi) + 1; 162 luaL_checkstack(L, n, "string slice too long"); 163 for (i=0; i<n; i++) 164 lua_pushinteger(L, uchar(s[posi+i-1])); 165 return n; 166 } 167 168 169 static int str_char (lua_State *L) { 170 int n = lua_gettop(L); /* number of arguments */ 171 int i; 172 luaL_Buffer b; 173 char *p = luaL_buffinitsize(L, &b, n); 174 for (i=1; i<=n; i++) { 175 lua_Integer c = luaL_checkinteger(L, i); 176 luaL_argcheck(L, uchar(c) == c, i, "value out of range"); 177 p[i - 1] = uchar(c); 178 } 179 luaL_pushresultsize(&b, n); 180 return 1; 181 } 182 183 184 static int writer (lua_State *L, const void *b, size_t size, void *B) { 185 (void)L; 186 luaL_addlstring((luaL_Buffer *) B, (const char *)b, size); 187 return 0; 188 } 189 190 191 static int str_dump (lua_State *L) { 192 luaL_Buffer b; 193 int strip = lua_toboolean(L, 2); 194 luaL_checktype(L, 1, LUA_TFUNCTION); 195 lua_settop(L, 1); 196 luaL_buffinit(L,&b); 197 if (lua_dump(L, writer, &b, strip) != 0) 198 return luaL_error(L, "unable to dump given function"); 199 luaL_pushresult(&b); 200 return 1; 201 } 202 203 204 205 /* 206 ** {====================================================== 207 ** PATTERN MATCHING 208 ** ======================================================= 209 */ 210 211 212 #define CAP_UNFINISHED (-1) 213 #define CAP_POSITION (-2) 214 215 216 typedef struct MatchState { 217 const char *src_init; /* init of source string */ 218 const char *src_end; /* end ('\0') of source string */ 219 const char *p_end; /* end ('\0') of pattern */ 220 lua_State *L; 221 size_t nrep; /* limit to avoid non-linear complexity */ 222 int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ 223 int level; /* total number of captures (finished or unfinished) */ 224 struct { 225 const char *init; 226 ptrdiff_t len; 227 } capture[LUA_MAXCAPTURES]; 228 } MatchState; 229 230 231 /* recursive function */ 232 static const char *match (MatchState *ms, const char *s, const char *p); 233 234 235 /* maximum recursion depth for 'match' */ 236 #if !defined(MAXCCALLS) 237 #define MAXCCALLS 200 238 #endif 239 240 241 /* 242 ** parameters to control the maximum number of operators handled in 243 ** a match (to avoid non-linear complexity). The maximum will be: 244 ** (subject length) * A_REPS + B_REPS 245 */ 246 #if !defined(A_REPS) 247 #define A_REPS 4 248 #define B_REPS 100000 249 #endif 250 251 252 #define L_ESC '%' 253 #define SPECIALS "^$*+?.([%-" 254 255 256 static int check_capture (MatchState *ms, int l) { 257 l -= '1'; 258 if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED) 259 return luaL_error(ms->L, "invalid capture index %%%d", l + 1); 260 return l; 261 } 262 263 264 static int capture_to_close (MatchState *ms) { 265 int level = ms->level; 266 for (level--; level>=0; level--) 267 if (ms->capture[level].len == CAP_UNFINISHED) return level; 268 return luaL_error(ms->L, "invalid pattern capture"); 269 } 270 271 272 static const char *classend (MatchState *ms, const char *p) { 273 switch (*p++) { 274 case L_ESC: { 275 if (p == ms->p_end) 276 luaL_error(ms->L, "malformed pattern (ends with '%%')"); 277 return p+1; 278 } 279 case '[': { 280 if (*p == '^') p++; 281 do { /* look for a ']' */ 282 if (p == ms->p_end) 283 luaL_error(ms->L, "malformed pattern (missing ']')"); 284 if (*(p++) == L_ESC && p < ms->p_end) 285 p++; /* skip escapes (e.g. '%]') */ 286 } while (*p != ']'); 287 return p+1; 288 } 289 default: { 290 return p; 291 } 292 } 293 } 294 295 296 static int match_class (int c, int cl) { 297 int res; 298 switch (tolower(cl)) { 299 case 'a' : res = isalpha(c); break; 300 case 'c' : res = iscntrl(c); break; 301 case 'd' : res = isdigit(c); break; 302 case 'g' : res = isgraph(c); break; 303 case 'l' : res = islower(c); break; 304 case 'p' : res = ispunct(c); break; 305 case 's' : res = isspace(c); break; 306 case 'u' : res = isupper(c); break; 307 case 'w' : res = isalnum(c); break; 308 case 'x' : res = isxdigit(c); break; 309 case 'z' : res = (c == 0); break; /* deprecated option */ 310 default: return (cl == c); 311 } 312 return (islower(cl) ? res : !res); 313 } 314 315 316 static int matchbracketclass (int c, const char *p, const char *ec) { 317 int sig = 1; 318 if (*(p+1) == '^') { 319 sig = 0; 320 p++; /* skip the '^' */ 321 } 322 while (++p < ec) { 323 if (*p == L_ESC) { 324 p++; 325 if (match_class(c, uchar(*p))) 326 return sig; 327 } 328 else if ((*(p+1) == '-') && (p+2 < ec)) { 329 p+=2; 330 if (uchar(*(p-2)) <= c && c <= uchar(*p)) 331 return sig; 332 } 333 else if (uchar(*p) == c) return sig; 334 } 335 return !sig; 336 } 337 338 339 static int singlematch (MatchState *ms, const char *s, const char *p, 340 const char *ep) { 341 if (s >= ms->src_end) 342 return 0; 343 else { 344 int c = uchar(*s); 345 switch (*p) { 346 case '.': return 1; /* matches any char */ 347 case L_ESC: return match_class(c, uchar(*(p+1))); 348 case '[': return matchbracketclass(c, p, ep-1); 349 default: return (uchar(*p) == c); 350 } 351 } 352 } 353 354 355 static const char *matchbalance (MatchState *ms, const char *s, 356 const char *p) { 357 if (p >= ms->p_end - 1) 358 luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); 359 if (*s != *p) return NULL; 360 else { 361 int b = *p; 362 int e = *(p+1); 363 int cont = 1; 364 while (++s < ms->src_end) { 365 if (*s == e) { 366 if (--cont == 0) return s+1; 367 } 368 else if (*s == b) cont++; 369 } 370 } 371 return NULL; /* string ends out of balance */ 372 } 373 374 375 static const char *max_expand (MatchState *ms, const char *s, 376 const char *p, const char *ep) { 377 ptrdiff_t i = 0; /* counts maximum expand for item */ 378 while (singlematch(ms, s + i, p, ep)) 379 i++; 380 /* keeps trying to match with the maximum repetitions */ 381 while (i>=0) { 382 const char *res = match(ms, (s+i), ep+1); 383 if (res) return res; 384 i--; /* else didn't match; reduce 1 repetition to try again */ 385 } 386 return NULL; 387 } 388 389 390 static const char *min_expand (MatchState *ms, const char *s, 391 const char *p, const char *ep) { 392 for (;;) { 393 const char *res = match(ms, s, ep+1); 394 if (res != NULL) 395 return res; 396 else if (singlematch(ms, s, p, ep)) 397 s++; /* try with one more repetition */ 398 else return NULL; 399 } 400 } 401 402 403 static const char *start_capture (MatchState *ms, const char *s, 404 const char *p, int what) { 405 const char *res; 406 int level = ms->level; 407 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); 408 ms->capture[level].init = s; 409 ms->capture[level].len = what; 410 ms->level = level+1; 411 if ((res=match(ms, s, p)) == NULL) /* match failed? */ 412 ms->level--; /* undo capture */ 413 return res; 414 } 415 416 417 static const char *end_capture (MatchState *ms, const char *s, 418 const char *p) { 419 int l = capture_to_close(ms); 420 const char *res; 421 ms->capture[l].len = s - ms->capture[l].init; /* close capture */ 422 if ((res = match(ms, s, p)) == NULL) /* match failed? */ 423 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ 424 return res; 425 } 426 427 428 static const char *match_capture (MatchState *ms, const char *s, int l) { 429 size_t len; 430 l = check_capture(ms, l); 431 len = ms->capture[l].len; 432 if ((size_t)(ms->src_end-s) >= len && 433 memcmp(ms->capture[l].init, s, len) == 0) 434 return s+len; 435 else return NULL; 436 } 437 438 439 static const char *match (MatchState *ms, const char *s, const char *p) { 440 if (ms->matchdepth-- == 0) 441 luaL_error(ms->L, "pattern too complex"); 442 init: /* using goto's to optimize tail recursion */ 443 if (p != ms->p_end) { /* end of pattern? */ 444 switch (*p) { 445 case '(': { /* start capture */ 446 if (*(p + 1) == ')') /* position capture? */ 447 s = start_capture(ms, s, p + 2, CAP_POSITION); 448 else 449 s = start_capture(ms, s, p + 1, CAP_UNFINISHED); 450 break; 451 } 452 case ')': { /* end capture */ 453 s = end_capture(ms, s, p + 1); 454 break; 455 } 456 case '$': { 457 if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ 458 goto dflt; /* no; go to default */ 459 s = (s == ms->src_end) ? s : NULL; /* check end of string */ 460 break; 461 } 462 case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ 463 switch (*(p + 1)) { 464 case 'b': { /* balanced string? */ 465 s = matchbalance(ms, s, p + 2); 466 if (s != NULL) { 467 p += 4; goto init; /* return match(ms, s, p + 4); */ 468 } /* else fail (s == NULL) */ 469 break; 470 } 471 case 'f': { /* frontier? */ 472 const char *ep; char previous; 473 p += 2; 474 if (*p != '[') 475 luaL_error(ms->L, "missing '[' after '%%f' in pattern"); 476 ep = classend(ms, p); /* points to what is next */ 477 previous = (s == ms->src_init) ? '\0' : *(s - 1); 478 if (!matchbracketclass(uchar(previous), p, ep - 1) && 479 matchbracketclass(uchar(*s), p, ep - 1)) { 480 p = ep; goto init; /* return match(ms, s, ep); */ 481 } 482 s = NULL; /* match failed */ 483 break; 484 } 485 case '0': case '1': case '2': case '3': 486 case '4': case '5': case '6': case '7': 487 case '8': case '9': { /* capture results (%0-%9)? */ 488 s = match_capture(ms, s, uchar(*(p + 1))); 489 if (s != NULL) { 490 p += 2; goto init; /* return match(ms, s, p + 2) */ 491 } 492 break; 493 } 494 default: goto dflt; 495 } 496 break; 497 } 498 default: dflt: { /* pattern class plus optional suffix */ 499 const char *ep = classend(ms, p); /* points to optional suffix */ 500 /* does not match at least once? */ 501 if (!singlematch(ms, s, p, ep)) { 502 if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ 503 p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ 504 } 505 else /* '+' or no suffix */ 506 s = NULL; /* fail */ 507 } 508 else { /* matched once */ 509 if (ms->nrep-- == 0) 510 luaL_error(ms->L, "pattern too complex"); 511 switch (*ep) { /* handle optional suffix */ 512 case '?': { /* optional */ 513 const char *res; 514 if ((res = match(ms, s + 1, ep + 1)) != NULL) 515 s = res; 516 else { 517 p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ 518 } 519 break; 520 } 521 case '+': /* 1 or more repetitions */ 522 s++; /* 1 match already done */ 523 /* FALLTHROUGH */ 524 case '*': /* 0 or more repetitions */ 525 s = max_expand(ms, s, p, ep); 526 break; 527 case '-': /* 0 or more repetitions (minimum) */ 528 s = min_expand(ms, s, p, ep); 529 break; 530 default: /* no suffix */ 531 s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ 532 } 533 } 534 break; 535 } 536 } 537 } 538 ms->matchdepth++; 539 return s; 540 } 541 542 543 544 static const char *lmemfind (const char *s1, size_t l1, 545 const char *s2, size_t l2) { 546 if (l2 == 0) return s1; /* empty strings are everywhere */ 547 else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ 548 else { 549 const char *init; /* to search for a '*s2' inside 's1' */ 550 l2--; /* 1st char will be checked by 'memchr' */ 551 l1 = l1-l2; /* 's2' cannot be found after that */ 552 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { 553 init++; /* 1st char is already checked */ 554 if (memcmp(init, s2+1, l2) == 0) 555 return init-1; 556 else { /* correct 'l1' and 's1' to try again */ 557 l1 -= init-s1; 558 s1 = init; 559 } 560 } 561 return NULL; /* not found */ 562 } 563 } 564 565 566 static void push_onecapture (MatchState *ms, int i, const char *s, 567 const char *e) { 568 if (i >= ms->level) { 569 if (i == 0) /* ms->level == 0, too */ 570 lua_pushlstring(ms->L, s, e - s); /* add whole match */ 571 else 572 luaL_error(ms->L, "invalid capture index %%%d", i + 1); 573 } 574 else { 575 ptrdiff_t l = ms->capture[i].len; 576 if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); 577 if (l == CAP_POSITION) 578 lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1); 579 else 580 lua_pushlstring(ms->L, ms->capture[i].init, l); 581 } 582 } 583 584 585 static int push_captures (MatchState *ms, const char *s, const char *e) { 586 int i; 587 int nlevels = (ms->level == 0 && s) ? 1 : ms->level; 588 luaL_checkstack(ms->L, nlevels, "too many captures"); 589 for (i = 0; i < nlevels; i++) 590 push_onecapture(ms, i, s, e); 591 return nlevels; /* number of strings pushed */ 592 } 593 594 595 /* check whether pattern has no special characters */ 596 static int nospecials (const char *p, size_t l) { 597 size_t upto = 0; 598 do { 599 if (strpbrk(p + upto, SPECIALS)) 600 return 0; /* pattern has a special character */ 601 upto += strlen(p + upto) + 1; /* may have more after \0 */ 602 } while (upto <= l); 603 return 1; /* no special chars found */ 604 } 605 606 607 static void prepstate (MatchState *ms, lua_State *L, 608 const char *s, size_t ls, const char *p, size_t lp) { 609 ms->L = L; 610 ms->matchdepth = MAXCCALLS; 611 ms->src_init = s; 612 ms->src_end = s + ls; 613 ms->p_end = p + lp; 614 if (ls < (MAX_SIZET - B_REPS) / A_REPS) 615 ms->nrep = A_REPS * ls + B_REPS; 616 else /* overflow (very long subject) */ 617 ms->nrep = MAX_SIZET; /* no limit */ 618 } 619 620 621 static void reprepstate (MatchState *ms) { 622 ms->level = 0; 623 lua_assert(ms->matchdepth == MAXCCALLS); 624 } 625 626 627 static int str_find_aux (lua_State *L, int find) { 628 size_t ls, lp; 629 const char *s = luaL_checklstring(L, 1, &ls); 630 const char *p = luaL_checklstring(L, 2, &lp); 631 lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls); 632 if (init < 1) init = 1; 633 else if (init > (lua_Integer)ls + 1) { /* start after string's end? */ 634 lua_pushnil(L); /* cannot find anything */ 635 return 1; 636 } 637 /* explicit request or no special characters? */ 638 if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { 639 /* do a plain search */ 640 const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp); 641 if (s2) { 642 lua_pushinteger(L, (s2 - s) + 1); 643 lua_pushinteger(L, (s2 - s) + lp); 644 return 2; 645 } 646 } 647 else { 648 MatchState ms; 649 const char *s1 = s + init - 1; 650 int anchor = (*p == '^'); 651 if (anchor) { 652 p++; lp--; /* skip anchor character */ 653 } 654 prepstate(&ms, L, s, ls, p, lp); 655 do { 656 const char *res; 657 reprepstate(&ms); 658 if ((res=match(&ms, s1, p)) != NULL) { 659 if (find) { 660 lua_pushinteger(L, (s1 - s) + 1); /* start */ 661 lua_pushinteger(L, res - s); /* end */ 662 return push_captures(&ms, NULL, 0) + 2; 663 } 664 else 665 return push_captures(&ms, s1, res); 666 } 667 } while (s1++ < ms.src_end && !anchor); 668 } 669 lua_pushnil(L); /* not found */ 670 return 1; 671 } 672 673 674 static int str_find (lua_State *L) { 675 return str_find_aux(L, 1); 676 } 677 678 679 static int str_match (lua_State *L) { 680 return str_find_aux(L, 0); 681 } 682 683 684 /* state for 'gmatch' */ 685 typedef struct GMatchState { 686 const char *src; /* current position */ 687 const char *p; /* pattern */ 688 MatchState ms; /* match state */ 689 } GMatchState; 690 691 692 static int gmatch_aux (lua_State *L) { 693 GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); 694 const char *src; 695 gm->ms.L = L; 696 for (src = gm->src; src <= gm->ms.src_end; src++) { 697 const char *e; 698 reprepstate(&gm->ms); 699 if ((e = match(&gm->ms, src, gm->p)) != NULL) { 700 if (e == src) /* empty match? */ 701 gm->src =src + 1; /* go at least one position */ 702 else 703 gm->src = e; 704 return push_captures(&gm->ms, src, e); 705 } 706 } 707 return 0; /* not found */ 708 } 709 710 711 static int gmatch (lua_State *L) { 712 size_t ls, lp; 713 const char *s = luaL_checklstring(L, 1, &ls); 714 const char *p = luaL_checklstring(L, 2, &lp); 715 GMatchState *gm; 716 lua_settop(L, 2); /* keep them on closure to avoid being collected */ 717 gm = (GMatchState *)lua_newuserdata(L, sizeof(GMatchState)); 718 prepstate(&gm->ms, L, s, ls, p, lp); 719 gm->src = s; gm->p = p; 720 lua_pushcclosure(L, gmatch_aux, 3); 721 return 1; 722 } 723 724 725 static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, 726 const char *e) { 727 size_t l, i; 728 lua_State *L = ms->L; 729 const char *news = lua_tolstring(L, 3, &l); 730 for (i = 0; i < l; i++) { 731 if (news[i] != L_ESC) 732 luaL_addchar(b, news[i]); 733 else { 734 i++; /* skip ESC */ 735 if (!isdigit(uchar(news[i]))) { 736 if (news[i] != L_ESC) 737 luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); 738 luaL_addchar(b, news[i]); 739 } 740 else if (news[i] == '0') 741 luaL_addlstring(b, s, e - s); 742 else { 743 push_onecapture(ms, news[i] - '1', s, e); 744 luaL_tolstring(L, -1, NULL); /* if number, convert it to string */ 745 lua_remove(L, -2); /* remove original value */ 746 luaL_addvalue(b); /* add capture to accumulated result */ 747 } 748 } 749 } 750 } 751 752 753 static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, 754 const char *e, int tr) { 755 lua_State *L = ms->L; 756 switch (tr) { 757 case LUA_TFUNCTION: { 758 int n; 759 lua_pushvalue(L, 3); 760 n = push_captures(ms, s, e); 761 lua_call(L, n, 1); 762 break; 763 } 764 case LUA_TTABLE: { 765 push_onecapture(ms, 0, s, e); 766 lua_gettable(L, 3); 767 break; 768 } 769 default: { /* LUA_TNUMBER or LUA_TSTRING */ 770 add_s(ms, b, s, e); 771 return; 772 } 773 } 774 if (!lua_toboolean(L, -1)) { /* nil or false? */ 775 lua_pop(L, 1); 776 lua_pushlstring(L, s, e - s); /* keep original text */ 777 } 778 else if (!lua_isstring(L, -1)) 779 luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); 780 luaL_addvalue(b); /* add result to accumulator */ 781 } 782 783 784 static int str_gsub (lua_State *L) { 785 size_t srcl, lp; 786 const char *src = luaL_checklstring(L, 1, &srcl); 787 const char *p = luaL_checklstring(L, 2, &lp); 788 int tr = lua_type(L, 3); 789 lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); 790 int anchor = (*p == '^'); 791 lua_Integer n = 0; 792 MatchState ms; 793 luaL_Buffer b; 794 luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || 795 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, 796 "string/function/table expected"); 797 luaL_buffinit(L, &b); 798 if (anchor) { 799 p++; lp--; /* skip anchor character */ 800 } 801 prepstate(&ms, L, src, srcl, p, lp); 802 while (n < max_s) { 803 const char *e; 804 reprepstate(&ms); 805 if ((e = match(&ms, src, p)) != NULL) { 806 n++; 807 add_value(&ms, &b, src, e, tr); 808 } 809 if (e && e>src) /* non empty match? */ 810 src = e; /* skip it */ 811 else if (src < ms.src_end) 812 luaL_addchar(&b, *src++); 813 else break; 814 if (anchor) break; 815 } 816 luaL_addlstring(&b, src, ms.src_end-src); 817 luaL_pushresult(&b); 818 lua_pushinteger(L, n); /* number of substitutions */ 819 return 2; 820 } 821 822 /* }====================================================== */ 823 824 825 826 /* 827 ** {====================================================== 828 ** STRING FORMAT 829 ** ======================================================= 830 */ 831 832 #if !defined(lua_number2strx) /* { */ 833 834 /* 835 ** Hexadecimal floating-point formatter 836 */ 837 838 #include <locale.h> 839 #include <math.h> 840 841 #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) 842 843 844 /* 845 ** Number of bits that goes into the first digit. It can be any value 846 ** between 1 and 4; the following definition tries to align the number 847 ** to nibble boundaries by making what is left after that first digit a 848 ** multiple of 4. 849 */ 850 #define L_NBFD ((l_mathlim(MANT_DIG) - 1)%4 + 1) 851 852 853 /* 854 ** Add integer part of 'x' to buffer and return new 'x' 855 */ 856 static lua_Number adddigit (char *buff, int n, lua_Number x) { 857 lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ 858 int d = (int)dd; 859 buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ 860 return x - dd; /* return what is left */ 861 } 862 863 864 static int num2straux (char *buff, int sz, lua_Number x) { 865 if (x != x || x == HUGE_VAL || x == -HUGE_VAL) /* inf or NaN? */ 866 return l_sprintf(buff, sz, LUA_NUMBER_FMT, x); /* equal to '%g' */ 867 else if (x == 0) { /* can be -0... */ 868 /* create "0" or "-0" followed by exponent */ 869 return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", x); 870 } 871 else { 872 int e; 873 lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ 874 int n = 0; /* character count */ 875 if (m < 0) { /* is number negative? */ 876 buff[n++] = '-'; /* add signal */ 877 m = -m; /* make it positive */ 878 } 879 buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ 880 m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ 881 e -= L_NBFD; /* this digit goes before the radix point */ 882 if (m > 0) { /* more digits? */ 883 buff[n++] = lua_getlocaledecpoint(); /* add radix point */ 884 do { /* add as many digits as needed */ 885 m = adddigit(buff, n++, m * 16); 886 } while (m > 0); 887 } 888 n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */ 889 lua_assert(n < sz); 890 return n; 891 } 892 } 893 894 895 static int lua_number2strx (lua_State *L, char *buff, int sz, 896 const char *fmt, lua_Number x) { 897 int n = num2straux(buff, sz, x); 898 if (fmt[SIZELENMOD] == 'A') { 899 int i; 900 for (i = 0; i < n; i++) 901 buff[i] = toupper(uchar(buff[i])); 902 } 903 else if (fmt[SIZELENMOD] != 'a') 904 luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); 905 return n; 906 } 907 908 #endif /* } */ 909 910 911 /* 912 ** Maximum size of each formatted item. This maximum size is produced 913 ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.', 914 ** and '\0') + number of decimal digits to represent maxfloat (which 915 ** is maximum exponent + 1). (99+3+1 then rounded to 120 for "extra 916 ** expenses", such as locale-dependent stuff) 917 */ 918 #define MAX_ITEM (120 + l_mathlim(MAX_10_EXP)) 919 920 921 /* valid flags in a format specification */ 922 #define FLAGS "-+ #0" 923 924 /* 925 ** maximum size of each format specification (such as "%-099.99d") 926 */ 927 #define MAX_FORMAT 32 928 929 930 static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { 931 size_t l; 932 const char *s = luaL_checklstring(L, arg, &l); 933 luaL_addchar(b, '"'); 934 while (l--) { 935 if (*s == '"' || *s == '\\' || *s == '\n') { 936 luaL_addchar(b, '\\'); 937 luaL_addchar(b, *s); 938 } 939 else if (*s == '\0' || iscntrl(uchar(*s))) { 940 char buff[10]; 941 if (!isdigit(uchar(*(s+1)))) 942 l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s)); 943 else 944 l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s)); 945 luaL_addstring(b, buff); 946 } 947 else 948 luaL_addchar(b, *s); 949 s++; 950 } 951 luaL_addchar(b, '"'); 952 } 953 954 static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { 955 const char *p = strfrmt; 956 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ 957 if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char)) 958 luaL_error(L, "invalid format (repeated flags)"); 959 if (isdigit(uchar(*p))) p++; /* skip width */ 960 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ 961 if (*p == '.') { 962 p++; 963 if (isdigit(uchar(*p))) p++; /* skip precision */ 964 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ 965 } 966 if (isdigit(uchar(*p))) 967 luaL_error(L, "invalid format (width or precision too long)"); 968 *(form++) = '%'; 969 memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char)); 970 form += (p - strfrmt) + 1; 971 *form = '\0'; 972 return p; 973 } 974 975 976 /* 977 ** add length modifier into formats 978 */ 979 static void addlenmod (char *form, const char *lenmod) { 980 size_t l = strlen(form); 981 size_t lm = strlen(lenmod); 982 char spec = form[l - 1]; 983 strcpy(form + l - 1, lenmod); 984 form[l + lm - 1] = spec; 985 form[l + lm] = '\0'; 986 } 987 988 989 static int str_format (lua_State *L) { 990 int top = lua_gettop(L); 991 int arg = 1; 992 size_t sfl; 993 const char *strfrmt = luaL_checklstring(L, arg, &sfl); 994 const char *strfrmt_end = strfrmt+sfl; 995 luaL_Buffer b; 996 luaL_buffinit(L, &b); 997 while (strfrmt < strfrmt_end) { 998 if (*strfrmt != L_ESC) 999 luaL_addchar(&b, *strfrmt++); 1000 else if (*++strfrmt == L_ESC) 1001 luaL_addchar(&b, *strfrmt++); /* %% */ 1002 else { /* format item */ 1003 char form[MAX_FORMAT]; /* to store the format ('%...') */ 1004 char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ 1005 int nb = 0; /* number of bytes in added item */ 1006 if (++arg > top) 1007 luaL_argerror(L, arg, "no value"); 1008 strfrmt = scanformat(L, strfrmt, form); 1009 switch (*strfrmt++) { 1010 case 'c': { 1011 nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg)); 1012 break; 1013 } 1014 case 'd': case 'i': 1015 case 'o': case 'u': case 'x': case 'X': { 1016 lua_Integer n = luaL_checkinteger(L, arg); 1017 addlenmod(form, LUA_INTEGER_FRMLEN); 1018 nb = l_sprintf(buff, MAX_ITEM, form, n); 1019 break; 1020 } 1021 #ifndef _KERNEL 1022 case 'a': case 'A': 1023 addlenmod(form, LUA_NUMBER_FRMLEN); 1024 nb = lua_number2strx(L, buff, MAX_ITEM, form, 1025 luaL_checknumber(L, arg)); 1026 break; 1027 case 'e': case 'E': case 'f': 1028 case 'g': case 'G': { 1029 addlenmod(form, LUA_NUMBER_FRMLEN); 1030 nb = l_sprintf(buff, MAX_ITEM, form, luaL_checknumber(L, arg)); 1031 break; 1032 } 1033 #endif /* _KERNEL */ 1034 case 'q': { 1035 addquoted(L, &b, arg); 1036 break; 1037 } 1038 case 's': { 1039 size_t l; 1040 const char *s = luaL_tolstring(L, arg, &l); 1041 if (form[2] == '\0') /* no modifiers? */ 1042 luaL_addvalue(&b); /* keep entire string */ 1043 else { 1044 luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); 1045 if (!strchr(form, '.') && l >= 100) { 1046 /* no precision and string is too long to be formatted */ 1047 luaL_addvalue(&b); /* keep entire string */ 1048 } 1049 else { /* format the string into 'buff' */ 1050 nb = l_sprintf(buff, MAX_ITEM, form, s); 1051 lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ 1052 } 1053 } 1054 break; 1055 } 1056 default: { /* also treat cases 'pnLlh' */ 1057 return luaL_error(L, "invalid option '%%%c' to 'format'", 1058 *(strfrmt - 1)); 1059 } 1060 } 1061 lua_assert(nb < MAX_ITEM); 1062 luaL_addsize(&b, nb); 1063 } 1064 } 1065 luaL_pushresult(&b); 1066 return 1; 1067 } 1068 1069 /* }====================================================== */ 1070 1071 1072 /* 1073 ** {====================================================== 1074 ** PACK/UNPACK 1075 ** ======================================================= 1076 */ 1077 1078 1079 /* value used for padding */ 1080 #if !defined(LUA_PACKPADBYTE) 1081 #define LUA_PACKPADBYTE 0x00 1082 #endif 1083 1084 /* maximum size for the binary representation of an integer */ 1085 #define MAXINTSIZE 16 1086 1087 /* number of bits in a character */ 1088 #define NB CHAR_BIT 1089 1090 /* mask for one character (NB 1's) */ 1091 #define MC ((1 << NB) - 1) 1092 1093 /* size of a lua_Integer */ 1094 #define SZINT ((int)sizeof(lua_Integer)) 1095 1096 1097 /* dummy union to get native endianness */ 1098 static const union { 1099 int dummy; 1100 char little; /* true iff machine is little endian */ 1101 } nativeendian = {1}; 1102 1103 1104 /* dummy structure to get native alignment requirements */ 1105 struct cD { 1106 char c; 1107 #ifndef _KERNEL 1108 union { double d; void *p; lua_Integer i; lua_Number n; } u; 1109 #else /* _KERNEL */ 1110 union { void *p; lua_Integer i; lua_Number n; } u; 1111 #endif /* _KERNEL */ 1112 }; 1113 1114 #define MAXALIGN (offsetof(struct cD, u)) 1115 1116 1117 #ifndef _KERNEL 1118 /* 1119 ** Union for serializing floats 1120 */ 1121 typedef union Ftypes { 1122 float f; 1123 double d; 1124 lua_Number n; 1125 char buff[5 * sizeof(lua_Number)]; /* enough for any float type */ 1126 } Ftypes; 1127 #endif /* _KERNEL */ 1128 1129 1130 /* 1131 ** information to pack/unpack stuff 1132 */ 1133 typedef struct Header { 1134 lua_State *L; 1135 int islittle; 1136 int maxalign; 1137 } Header; 1138 1139 1140 /* 1141 ** options for pack/unpack 1142 */ 1143 typedef enum KOption { 1144 Kint, /* signed integers */ 1145 Kuint, /* unsigned integers */ 1146 #ifndef _KERNEL 1147 Kfloat, /* floating-point numbers */ 1148 #endif /* _KERNEL */ 1149 Kchar, /* fixed-length strings */ 1150 Kstring, /* strings with prefixed length */ 1151 Kzstr, /* zero-terminated strings */ 1152 Kpadding, /* padding */ 1153 Kpaddalign, /* padding for alignment */ 1154 Knop /* no-op (configuration or spaces) */ 1155 } KOption; 1156 1157 1158 /* 1159 ** Read an integer numeral from string 'fmt' or return 'df' if 1160 ** there is no numeral 1161 */ 1162 static int digit (int c) { return '0' <= c && c <= '9'; } 1163 1164 static int getnum (const char **fmt, int df) { 1165 if (!digit(**fmt)) /* no number? */ 1166 return df; /* return default value */ 1167 else { 1168 int a = 0; 1169 do { 1170 a = a*10 + (*((*fmt)++) - '0'); 1171 } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); 1172 return a; 1173 } 1174 } 1175 1176 1177 /* 1178 ** Read an integer numeral and raises an error if it is larger 1179 ** than the maximum size for integers. 1180 */ 1181 static int getnumlimit (Header *h, const char **fmt, int df) { 1182 int sz = getnum(fmt, df); 1183 if (sz > MAXINTSIZE || sz <= 0) 1184 luaL_error(h->L, "integral size (%d) out of limits [1,%d]", 1185 sz, MAXINTSIZE); 1186 return sz; 1187 } 1188 1189 1190 /* 1191 ** Initialize Header 1192 */ 1193 static void initheader (lua_State *L, Header *h) { 1194 h->L = L; 1195 h->islittle = nativeendian.little; 1196 h->maxalign = 1; 1197 } 1198 1199 1200 /* 1201 ** Read and classify next option. 'size' is filled with option's size. 1202 */ 1203 static KOption getoption (Header *h, const char **fmt, int *size) { 1204 int opt = *((*fmt)++); 1205 *size = 0; /* default */ 1206 switch (opt) { 1207 case 'b': *size = sizeof(char); return Kint; 1208 case 'B': *size = sizeof(char); return Kuint; 1209 case 'h': *size = sizeof(short); return Kint; 1210 case 'H': *size = sizeof(short); return Kuint; 1211 case 'l': *size = sizeof(long); return Kint; 1212 case 'L': *size = sizeof(long); return Kuint; 1213 case 'j': *size = sizeof(lua_Integer); return Kint; 1214 case 'J': *size = sizeof(lua_Integer); return Kuint; 1215 case 'T': *size = sizeof(size_t); return Kuint; 1216 #ifndef _KERNEL 1217 case 'f': *size = sizeof(float); return Kfloat; 1218 case 'd': *size = sizeof(double); return Kfloat; 1219 case 'n': *size = sizeof(lua_Number); return Kfloat; 1220 #else /* _KERNEL */ 1221 case 'n': *size = sizeof(lua_Number); return Kint; 1222 #endif /* _KERNEL */ 1223 case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; 1224 case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; 1225 case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; 1226 case 'c': 1227 *size = getnum(fmt, -1); 1228 if (*size == -1) 1229 luaL_error(h->L, "missing size for format option 'c'"); 1230 return Kchar; 1231 case 'z': return Kzstr; 1232 case 'x': *size = 1; return Kpadding; 1233 case 'X': return Kpaddalign; 1234 case ' ': break; 1235 case '<': h->islittle = 1; break; 1236 case '>': h->islittle = 0; break; 1237 case '=': h->islittle = nativeendian.little; break; 1238 case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break; 1239 default: luaL_error(h->L, "invalid format option '%c'", opt); 1240 } 1241 return Knop; 1242 } 1243 1244 1245 /* 1246 ** Read, classify, and fill other details about the next option. 1247 ** 'psize' is filled with option's size, 'notoalign' with its 1248 ** alignment requirements. 1249 ** Local variable 'size' gets the size to be aligned. (Kpadal option 1250 ** always gets its full alignment, other options are limited by 1251 ** the maximum alignment ('maxalign'). Kchar option needs no alignment 1252 ** despite its size. 1253 */ 1254 static KOption getdetails (Header *h, size_t totalsize, 1255 const char **fmt, int *psize, int *ntoalign) { 1256 KOption opt = getoption(h, fmt, psize); 1257 int align = *psize; /* usually, alignment follows size */ 1258 if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ 1259 if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) 1260 luaL_argerror(h->L, 1, "invalid next option for option 'X'"); 1261 } 1262 if (align <= 1 || opt == Kchar) /* need no alignment? */ 1263 *ntoalign = 0; 1264 else { 1265 if (align > h->maxalign) /* enforce maximum alignment */ 1266 align = h->maxalign; 1267 if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */ 1268 luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); 1269 *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); 1270 } 1271 return opt; 1272 } 1273 1274 1275 /* 1276 ** Pack integer 'n' with 'size' bytes and 'islittle' endianness. 1277 ** The final 'if' handles the case when 'size' is larger than 1278 ** the size of a Lua integer, correcting the extra sign-extension 1279 ** bytes if necessary (by default they would be zeros). 1280 */ 1281 static void packint (luaL_Buffer *b, lua_Unsigned n, 1282 int islittle, int size, int neg) { 1283 char *buff = luaL_prepbuffsize(b, size); 1284 int i; 1285 buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ 1286 for (i = 1; i < size; i++) { 1287 n >>= NB; 1288 buff[islittle ? i : size - 1 - i] = (char)(n & MC); 1289 } 1290 if (neg && size > SZINT) { /* negative number need sign extension? */ 1291 for (i = SZINT; i < size; i++) /* correct extra bytes */ 1292 buff[islittle ? i : size - 1 - i] = (char)MC; 1293 } 1294 luaL_addsize(b, size); /* add result to buffer */ 1295 } 1296 1297 1298 #ifndef _KERNEL 1299 /* 1300 ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if 1301 ** given 'islittle' is different from native endianness. 1302 */ 1303 static void copywithendian (volatile char *dest, volatile const char *src, 1304 int size, int islittle) { 1305 if (islittle == nativeendian.little) { 1306 while (size-- != 0) 1307 *(dest++) = *(src++); 1308 } 1309 else { 1310 dest += size - 1; 1311 while (size-- != 0) 1312 *(dest--) = *(src++); 1313 } 1314 } 1315 #endif /* _KERNEL */ 1316 1317 1318 static int str_pack (lua_State *L) { 1319 luaL_Buffer b; 1320 Header h; 1321 const char *fmt = luaL_checkstring(L, 1); /* format string */ 1322 int arg = 1; /* current argument to pack */ 1323 size_t totalsize = 0; /* accumulate total size of result */ 1324 initheader(L, &h); 1325 lua_pushnil(L); /* mark to separate arguments from string buffer */ 1326 luaL_buffinit(L, &b); 1327 while (*fmt != '\0') { 1328 int size, ntoalign; 1329 KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); 1330 totalsize += ntoalign + size; 1331 while (ntoalign-- > 0) 1332 luaL_addchar(&b, LUA_PACKPADBYTE); /* fill alignment */ 1333 arg++; 1334 switch (opt) { 1335 case Kint: { /* signed integers */ 1336 lua_Integer n = luaL_checkinteger(L, arg); 1337 if (size < SZINT) { /* need overflow check? */ 1338 lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); 1339 luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); 1340 } 1341 packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); 1342 break; 1343 } 1344 case Kuint: { /* unsigned integers */ 1345 lua_Integer n = luaL_checkinteger(L, arg); 1346 if (size < SZINT) /* need overflow check? */ 1347 luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), 1348 arg, "unsigned overflow"); 1349 packint(&b, (lua_Unsigned)n, h.islittle, size, 0); 1350 break; 1351 } 1352 #ifndef _KERNEL 1353 case Kfloat: { /* floating-point options */ 1354 volatile Ftypes u; 1355 char *buff = luaL_prepbuffsize(&b, size); 1356 lua_Number n = luaL_checknumber(L, arg); /* get argument */ 1357 if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */ 1358 else if (size == sizeof(u.d)) u.d = (double)n; 1359 else u.n = n; 1360 /* move 'u' to final result, correcting endianness if needed */ 1361 copywithendian(buff, u.buff, size, h.islittle); 1362 luaL_addsize(&b, size); 1363 break; 1364 } 1365 #endif /* _KERNEL */ 1366 case Kchar: { /* fixed-size string */ 1367 size_t len; 1368 const char *s = luaL_checklstring(L, arg, &len); 1369 if ((size_t)size <= len) /* string larger than (or equal to) needed? */ 1370 luaL_addlstring(&b, s, size); /* truncate string to asked size */ 1371 else { /* string smaller than needed */ 1372 luaL_addlstring(&b, s, len); /* add it all */ 1373 while (len++ < (size_t)size) /* pad extra space */ 1374 luaL_addchar(&b, LUA_PACKPADBYTE); 1375 } 1376 break; 1377 } 1378 case Kstring: { /* strings with length count */ 1379 size_t len; 1380 const char *s = luaL_checklstring(L, arg, &len); 1381 luaL_argcheck(L, size >= (int)sizeof(size_t) || 1382 len < ((size_t)1 << (size * NB)), 1383 arg, "string length does not fit in given size"); 1384 packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ 1385 luaL_addlstring(&b, s, len); 1386 totalsize += len; 1387 break; 1388 } 1389 case Kzstr: { /* zero-terminated string */ 1390 size_t len; 1391 const char *s = luaL_checklstring(L, arg, &len); 1392 luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); 1393 luaL_addlstring(&b, s, len); 1394 luaL_addchar(&b, '\0'); /* add zero at the end */ 1395 totalsize += len + 1; 1396 break; 1397 } 1398 case Kpadding: luaL_addchar(&b, LUA_PACKPADBYTE); /* FALLTHROUGH */ 1399 case Kpaddalign: case Knop: 1400 arg--; /* undo increment */ 1401 break; 1402 } 1403 } 1404 luaL_pushresult(&b); 1405 return 1; 1406 } 1407 1408 1409 static int str_packsize (lua_State *L) { 1410 Header h; 1411 const char *fmt = luaL_checkstring(L, 1); /* format string */ 1412 size_t totalsize = 0; /* accumulate total size of result */ 1413 initheader(L, &h); 1414 while (*fmt != '\0') { 1415 int size, ntoalign; 1416 KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); 1417 size += ntoalign; /* total space used by option */ 1418 luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, 1419 "format result too large"); 1420 totalsize += size; 1421 switch (opt) { 1422 case Kstring: /* strings with length count */ 1423 case Kzstr: /* zero-terminated string */ 1424 luaL_argerror(L, 1, "variable-length format"); 1425 /* call never return, but to avoid warnings: *//* FALLTHROUGH */ 1426 default: break; 1427 } 1428 } 1429 lua_pushinteger(L, (lua_Integer)totalsize); 1430 return 1; 1431 } 1432 1433 1434 /* 1435 ** Unpack an integer with 'size' bytes and 'islittle' endianness. 1436 ** If size is smaller than the size of a Lua integer and integer 1437 ** is signed, must do sign extension (propagating the sign to the 1438 ** higher bits); if size is larger than the size of a Lua integer, 1439 ** it must check the unread bytes to see whether they do not cause an 1440 ** overflow. 1441 */ 1442 static lua_Integer unpackint (lua_State *L, const char *str, 1443 int islittle, int size, int issigned) { 1444 lua_Unsigned res = 0; 1445 int i; 1446 int limit = (size <= SZINT) ? size : SZINT; 1447 for (i = limit - 1; i >= 0; i--) { 1448 res <<= NB; 1449 res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; 1450 } 1451 if (size < SZINT) { /* real size smaller than lua_Integer? */ 1452 if (issigned) { /* needs sign extension? */ 1453 lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); 1454 res = ((res ^ mask) - mask); /* do sign extension */ 1455 } 1456 } 1457 else if (size > SZINT) { /* must check unread bytes */ 1458 int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; 1459 for (i = limit; i < size; i++) { 1460 if ((unsigned char)str[islittle ? i : size - 1 - i] != mask) 1461 luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); 1462 } 1463 } 1464 return (lua_Integer)res; 1465 } 1466 1467 1468 static int str_unpack (lua_State *L) { 1469 Header h; 1470 const char *fmt = luaL_checkstring(L, 1); 1471 size_t ld; 1472 const char *data = luaL_checklstring(L, 2, &ld); 1473 size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1; 1474 int n = 0; /* number of results */ 1475 luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); 1476 initheader(L, &h); 1477 while (*fmt != '\0') { 1478 int size, ntoalign; 1479 KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); 1480 if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld) 1481 luaL_argerror(L, 2, "data string too short"); 1482 pos += ntoalign; /* skip alignment */ 1483 /* stack space for item + next position */ 1484 luaL_checkstack(L, 2, "too many results"); 1485 n++; 1486 switch (opt) { 1487 case Kint: 1488 case Kuint: { 1489 lua_Integer res = unpackint(L, data + pos, h.islittle, size, 1490 (opt == Kint)); 1491 lua_pushinteger(L, res); 1492 break; 1493 } 1494 #ifndef _KERNEL 1495 case Kfloat: { 1496 volatile Ftypes u; 1497 lua_Number num; 1498 copywithendian(u.buff, data + pos, size, h.islittle); 1499 if (size == sizeof(u.f)) num = (lua_Number)u.f; 1500 else if (size == sizeof(u.d)) num = (lua_Number)u.d; 1501 else num = u.n; 1502 lua_pushnumber(L, num); 1503 break; 1504 } 1505 #endif /* _KERNEL */ 1506 case Kchar: { 1507 lua_pushlstring(L, data + pos, size); 1508 break; 1509 } 1510 case Kstring: { 1511 size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); 1512 luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short"); 1513 lua_pushlstring(L, data + pos + size, len); 1514 pos += len; /* skip string */ 1515 break; 1516 } 1517 case Kzstr: { 1518 size_t len = (int)strlen(data + pos); 1519 lua_pushlstring(L, data + pos, len); 1520 pos += len + 1; /* skip string plus final '\0' */ 1521 break; 1522 } 1523 case Kpaddalign: case Kpadding: case Knop: 1524 n--; /* undo increment */ 1525 break; 1526 } 1527 pos += size; 1528 } 1529 lua_pushinteger(L, pos + 1); /* next position */ 1530 return n + 1; 1531 } 1532 1533 /* }====================================================== */ 1534 1535 1536 static const luaL_Reg strlib[] = { 1537 {"byte", str_byte}, 1538 {"char", str_char}, 1539 {"dump", str_dump}, 1540 {"find", str_find}, 1541 {"format", str_format}, 1542 {"gmatch", gmatch}, 1543 {"gsub", str_gsub}, 1544 {"len", str_len}, 1545 {"lower", str_lower}, 1546 {"match", str_match}, 1547 {"rep", str_rep}, 1548 {"reverse", str_reverse}, 1549 {"sub", str_sub}, 1550 {"upper", str_upper}, 1551 {"pack", str_pack}, 1552 {"packsize", str_packsize}, 1553 {"unpack", str_unpack}, 1554 {NULL, NULL} 1555 }; 1556 1557 1558 static void createmetatable (lua_State *L) { 1559 lua_createtable(L, 0, 1); /* table to be metatable for strings */ 1560 lua_pushliteral(L, ""); /* dummy string */ 1561 lua_pushvalue(L, -2); /* copy table */ 1562 lua_setmetatable(L, -2); /* set table as metatable for strings */ 1563 lua_pop(L, 1); /* pop dummy string */ 1564 lua_pushvalue(L, -2); /* get string library */ 1565 lua_setfield(L, -2, "__index"); /* metatable.__index = string */ 1566 lua_pop(L, 1); /* pop metatable */ 1567 } 1568 1569 1570 /* 1571 ** Open string library 1572 */ 1573 LUAMOD_API int luaopen_string (lua_State *L) { 1574 luaL_newlib(L, strlib); 1575 createmetatable(L); 1576 return 1; 1577 } 1578 1579