1 /* 2 * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io> 3 * 4 * Permission to use, copy, modify, and/or distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 /** 18 * # Builtin functions 19 * 20 * The core namespace is not an actual module but refers to the set of 21 * builtin functions and properties available to `ucode` scripts. 22 * 23 * @module core 24 */ 25 26 #include <stdio.h> 27 #include <stdlib.h> 28 #include <stdarg.h> 29 #include <string.h> 30 #include <signal.h> 31 #include <ctype.h> 32 #include <errno.h> 33 #include <math.h> 34 #include <time.h> 35 #include <dlfcn.h> 36 #include <libgen.h> 37 #include <unistd.h> 38 #include <arpa/inet.h> 39 #include <sys/stat.h> 40 #include <sys/types.h> 41 #include <sys/wait.h> 42 #include <fnmatch.h> 43 #include <assert.h> 44 45 46 #include "ucode/internal/vm.h" /* ISA: I_* opcodes */ 47 #include "ucode/internal/types.h" 48 #include "ucode/internal/lexer.h" /* utf8enc() */ 49 #include "ucode/internal/lib.h" 50 #include "ucode/internal/source.h" 51 #include "ucode/internal/program.h" 52 #include "ucode/internal/platform.h" 53 #include "ucode/internal/json-c-compat.h" 54 55 /* Appends the printed form of `line`, followed by a marker underlining the 56 * byte range [sbegin, send) of the enclosing statement within it. When no 57 * statement span is known, `sbegin` and `send` are equal and a caret labelled 58 * "Near here" is placed at the byte index `off` instead. */ 59 static void 60 format_context_line(uc_stringbuf_t *buf, const char *line, size_t off, 61 size_t sbegin, size_t send, bool compact) 62 { 63 unsigned padlen, begcol = 0, endcol = 0, width, i; 64 size_t n; 65 const char *p; 66 67 for (p = line, padlen = 0; *p != '\n' && *p != '\0'; p++) { 68 n = (size_t) (p - line); 69 70 if (compact && n == off) 71 ucv_stringbuf_append(buf, "\033[22m"); 72 73 switch (*p) { 74 case '\t': 75 ucv_stringbuf_append(buf, " "); 76 width = 4; 77 break; 78 79 case '\r': 80 case '\v': 81 ucv_stringbuf_append(buf, " "); 82 width = 1; 83 break; 84 85 default: 86 ucv_stringbuf_addstr(buf, p, 1); 87 width = 1; 88 } 89 90 /* the marker columns are the printed widths up to each position, with 91 * tabs and control characters expanded to their printable equivalent */ 92 if (n < sbegin) 93 begcol += width; 94 95 if (n < send) 96 endcol += width; 97 98 if (n < off) 99 padlen += width; 100 } 101 102 if (compact) { 103 ucv_stringbuf_append(buf, "\033[m\n"); 104 105 return; 106 } 107 108 ucv_stringbuf_append(buf, "`\n "); 109 110 if (send > sbegin) { 111 /* the caret always marks the failing position, even if the statement 112 * extent resolved to something which does not contain it */ 113 if (begcol > padlen) 114 begcol = padlen; 115 116 if (endcol < padlen + 1) 117 endcol = padlen + 1; 118 119 for (i = 0; i < endcol; i++) 120 ucv_stringbuf_addstr(buf, i < begcol ? " " : (i == padlen ? "^" : "~"), 1); 121 122 ucv_stringbuf_append(buf, "\n"); 123 124 return; 125 } 126 127 /* without a resolvable statement span all we can do is point at the 128 * failing position itself */ 129 if (padlen < strlen("Near here ^")) { 130 for (i = 0; i < padlen; i++) 131 ucv_stringbuf_append(buf, " "); 132 133 ucv_stringbuf_append(buf, "^-- Near here\n"); 134 } 135 else { 136 ucv_stringbuf_append(buf, "Near here "); 137 138 for (i = strlen("Near here "); i < padlen; i++) 139 ucv_stringbuf_append(buf, "-"); 140 141 ucv_stringbuf_append(buf, "^\n"); 142 } 143 } 144 145 static char * 146 source_filename(uc_source_t *src, uint32_t line) 147 { 148 const char *name = src->filename ? basename(src->filename) : "[?]"; 149 static char buf[sizeof("xxxxxxxxx.uc:0000000000")]; 150 size_t len = strlen(name); 151 152 if (len > 12) 153 snprintf(buf, sizeof(buf), "...%s:%u", name + (len - 9), line); 154 else 155 snprintf(buf, sizeof(buf), "%12s:%u", name, line); 156 157 return buf; 158 } 159 160 /* Shared body of uc_source_context_format() and uc_error_context_format(). */ 161 static bool 162 format_context_range(uc_stringbuf_t *buf, uc_source_t *src, size_t off, 163 size_t startoff, size_t endoff, bool compact) 164 { 165 size_t len, lpos, eoff, sbegin, send, shift; 166 bool truncated; 167 char line[256]; 168 int eline; 169 170 eline = uc_source_read_line(src, off, line, sizeof(line), &lpos, &truncated); 171 172 if (!eline) 173 return false; 174 175 if (compact) 176 ucv_stringbuf_printf(buf, "\033[2;40;97m%17s %s", 177 source_filename(src, eline), 178 truncated ? "..." : ""); 179 else 180 ucv_stringbuf_printf(buf, "\n `%s", 181 truncated ? "..." : ""); 182 183 /* the index of the failing byte within the line and the columns gained by 184 * prefixing an overlong line with "..." */ 185 eoff = off - lpos; 186 shift = truncated ? 3 : 0; 187 188 sbegin = send = eoff; 189 190 /* clip the statement's extent to the part of it on this line */ 191 len = strlen(line); 192 193 if (endoff > startoff && endoff > lpos && startoff < lpos + len) { 194 sbegin = startoff > lpos ? startoff - lpos : 0; 195 send = endoff < lpos + len ? endoff - lpos : len; 196 } 197 198 format_context_line(buf, line, eoff + shift, sbegin + shift, send + shift, compact); 199 200 return true; 201 } 202 203 bool 204 uc_source_context_format(uc_stringbuf_t *buf, uc_source_t *src, size_t off, bool compact) 205 { 206 return format_context_range(buf, src, off, 0, 0, compact); 207 } 208 209 /* Renders the stacktrace of an error followed by the source context at `off`, 210 * underlining the extent delimited by `startoff` and `endoff` when the statement 211 * it covers is known, rather than just marking the failing position. Pass equal 212 * values for the two when it is not. */ 213 bool 214 uc_error_context_format(uc_stringbuf_t *buf, uc_source_t *src, uc_value_t *stacktrace, 215 size_t startoff, size_t endoff, size_t off) 216 { 217 uc_value_t *e, *fn, *file, *line, *byte, *tco; 218 const char *path; 219 size_t idx; 220 221 for (idx = 0; idx < (stacktrace ? ucv_array_length(stacktrace) : 0); idx++) { 222 e = ucv_array_get(stacktrace, idx); 223 fn = ucv_object_get(e, "function", NULL); 224 file = ucv_object_get(e, "filename", NULL); 225 tco = ucv_object_get(e, "tco", NULL); 226 227 if (idx == 0) { 228 path = (file && strcmp(ucv_string_get(file), "[stdin]")) 229 ? ucv_string_get(file) : NULL; 230 231 if (path && fn) 232 ucv_stringbuf_printf(buf, "In %s(), file %s, ", ucv_string_get(fn), path); 233 else if (fn) 234 ucv_stringbuf_printf(buf, "In %s(), ", ucv_string_get(fn)); 235 else if (path) 236 ucv_stringbuf_printf(buf, "In %s, ", path); 237 else 238 ucv_stringbuf_append(buf, "In "); 239 240 ucv_stringbuf_printf(buf, "line %" PRId64 ", byte %" PRId64 ":\n", 241 ucv_int64_get(ucv_object_get(e, "line", NULL)), 242 ucv_int64_get(ucv_object_get(e, "byte", NULL))); 243 } 244 else { 245 line = ucv_object_get(e, "line", NULL); 246 byte = ucv_object_get(e, "byte", NULL); 247 248 ucv_stringbuf_printf(buf, " called from %s%s (%s", 249 fn ? "function " : "anonymous function", 250 fn ? ucv_string_get(fn) : "", 251 file ? ucv_string_get(file) : ""); 252 253 if (line && byte) 254 ucv_stringbuf_printf(buf, ":%" PRId64 ":%" PRId64 ")\n", 255 ucv_int64_get(line), 256 ucv_int64_get(byte)); 257 else 258 ucv_stringbuf_append(buf, "[C])\n"); 259 } 260 261 /* indicate the call frames collapsed into this one by tail call 262 * optimization, which are absent from the trace */ 263 if (tco) 264 ucv_stringbuf_printf(buf, 265 " (%" PRId64 " tail call frames omitted)\n", 266 ucv_int64_get(tco)); 267 } 268 269 return format_context_range(buf, src, off, startoff, endoff, false); 270 } 271 272 void 273 uc_error_message_indent(char **msg) { 274 uc_stringbuf_t *buf; 275 char *s, *p, *nl; 276 size_t len; 277 278 if (!msg || !*msg) 279 return; 280 281 buf = xprintbuf_new(); 282 s = *msg; 283 len = strlen(s); 284 285 while (len > 0 && s[len-1] == '\n') 286 s[--len] = 0; 287 288 for (p = s, nl = strchr(p, '\n'); p != NULL; 289 p = nl ? nl + 1 : NULL, nl = p ? strchr(p, '\n') : NULL) 290 { 291 if (!nl) 292 ucv_stringbuf_printf(buf, " | %s", p); 293 else if (nl != p) 294 ucv_stringbuf_printf(buf, " | %.*s\n", (int)(nl - p), p); 295 else 296 ucv_stringbuf_append(buf, " |\n"); 297 } 298 299 ucv_stringbuf_append(buf, "\n"); 300 301 *msg = buf->buf; 302 303 free(buf); 304 free(s); 305 } 306 307 static char *uc_cast_string(uc_vm_t *vm, uc_value_t **v, bool *freeable) { 308 if (ucv_type(*v) == UC_STRING) { 309 *freeable = false; 310 311 return _ucv_string_get(v); 312 } 313 314 *freeable = true; 315 316 return ucv_to_string(vm, *v); 317 } 318 319 static void 320 uc_vm_ctx_push(uc_vm_t *vm) 321 { 322 uc_value_t *ctx = NULL; 323 324 if (vm->callframes.count >= 2) 325 ctx = vm->callframes.entries[vm->callframes.count - 2].ctx; 326 327 uc_vm_stack_push(vm, ucv_get(ctx)); 328 } 329 330 static uc_value_t * 331 uc_print_common(uc_vm_t *vm, size_t nargs, FILE *fh) 332 { 333 uc_value_t *item; 334 size_t reslen = 0; 335 size_t len = 0; 336 size_t arridx; 337 char *p; 338 339 for (arridx = 0; arridx < nargs; arridx++) { 340 item = uc_fn_arg(arridx); 341 342 if (ucv_type(item) == UC_STRING) { 343 len = ucv_string_length(item); 344 reslen += fwrite(ucv_string_get(item), 1, len, fh); 345 } 346 else if (item != NULL) { 347 p = ucv_to_string(vm, item); 348 len = strlen(p); 349 reslen += fwrite(p, 1, len, fh); 350 free(p); 351 } 352 } 353 354 return ucv_int64_new(reslen); 355 } 356 357 358 /** 359 * Print any of the given values to stdout. 360 * 361 * The `print()` function writes a string representation of each given argument 362 * to stdout and returns the amount of bytes written. 363 * 364 * String values are printed as-is, integer and double values are printed in 365 * decimal notation, boolean values are printed as `true` or `false` while 366 * arrays and objects are converted to their JSON representation before being 367 * written to the standard output. The `null` value is represented by an empty 368 * string so `print(null)` would print nothing. Resource values are printed in 369 * the form `<type address>`, e.g. `<fs.file 0x7f60f0981760>`. 370 * 371 * If resource, array or object values contain a `tostring()` function in their 372 * prototypes, then this function is invoked to obtain an alternative string 373 * representation of the value. 374 * 375 * Examples: 376 * 377 * ```javascript 378 * print(1 != 2); // Will print 'true' 379 * print(0xff); // Will print '255' 380 * print(2e3); // Will print '2000' 381 * print(null); // Will print nothing 382 * print({ hello: true, world: 123 }); // Will print '{ "hello": true, "world": 123 }' 383 * print([1,2,3]); // Will print '[ 1, 2, 3 ]' 384 * 385 * print(proto({ foo: "bar" }, // Will print 'MyObj' 386 * { tostring: () => "MyObj" })); // instead of '{ "foo": "bar" }' 387 * 388 * ``` 389 * 390 * Returns the amount of bytes printed. 391 * 392 * @function module:core#print 393 * 394 * @param {...*} values 395 * Arbitrary values to print 396 * 397 * @returns {number} 398 */ 399 static uc_value_t * 400 uc_print(uc_vm_t *vm, size_t nargs) 401 { 402 return uc_print_common(vm, nargs, vm->output); 403 } 404 405 /** 406 * Determine the length of the given object, array or string. 407 * 408 * Returns the length of the given value. 409 * 410 * - For strings, the length is the amount of bytes within the string 411 * - For arrays, the length is the amount of array elements 412 * - For objects, the length is defined as the amount of keys 413 * 414 * Returns `null` if the given argument is not an object, array or string. 415 * 416 * @function module:core#length 417 * 418 * @param {Object|Array|string} x - The input object, array, or string. 419 * 420 * @returns {?number} - The length of the input. 421 * 422 * @example 423 * length("test") // 4 424 * length([true, false, null, 123, "test"]) // 5 425 * length({foo: true, bar: 123, baz: "test"}) // 3 426 * length({}) // 0 427 * length(true) // null 428 * length(10.0) // null 429 */ 430 static uc_value_t * 431 uc_length(uc_vm_t *vm, size_t nargs) 432 { 433 uc_value_t *arg = uc_fn_arg(0); 434 435 switch (ucv_type(arg)) { 436 case UC_OBJECT: 437 return ucv_int64_new(ucv_object_length(arg)); 438 439 case UC_ARRAY: 440 return ucv_int64_new(ucv_array_length(arg)); 441 442 case UC_STRING: 443 return ucv_int64_new(ucv_string_length(arg)); 444 445 default: 446 return NULL; 447 } 448 } 449 450 static int 451 uc_uniq_ucv_equal(const void *k1, const void *k2); 452 453 static uc_value_t * 454 uc_index(uc_vm_t *vm, size_t nargs, bool right) 455 { 456 uc_value_t *stack = uc_fn_arg(0); 457 uc_value_t *needle = uc_fn_arg(1); 458 uc_value_t *offset = nargs > 2 ? uc_fn_arg(2) : NULL; 459 const char *sstr, *nstr, *p; 460 size_t arridx, slen, nlen, high; 461 ssize_t ret = -1, start = 0; 462 bool bounded = false; 463 464 /* An optional third argument constrains where the search begins (or, for 465 * rindex(), the highest index a match may have). Negative offsets are 466 * relative to the end, mirroring substr(); out-of-range offsets are 467 * clamped rather than rejected. */ 468 if (offset != NULL && ucv_type(offset) != UC_NULL) { 469 switch (ucv_type(offset)) { 470 case UC_INTEGER: 471 start = (ssize_t)ucv_int64_get(offset); 472 bounded = true; 473 break; 474 475 case UC_DOUBLE: 476 start = (ssize_t)ucv_double_get(offset); 477 bounded = true; 478 break; 479 480 default: 481 return NULL; 482 } 483 } 484 485 switch (ucv_type(stack)) { 486 case UC_ARRAY: 487 slen = ucv_array_length(stack); 488 489 if (bounded) { 490 if (start < 0) 491 start += (ssize_t)slen; 492 493 if (start < 0) 494 start = 0; 495 else if (start > (ssize_t)slen) 496 start = (ssize_t)slen; 497 } 498 499 if (right) { 500 arridx = !bounded || (size_t)start + 1 > slen ? slen : (size_t)start + 1; 501 502 while (arridx > 0) { 503 arridx--; 504 505 if (uc_uniq_ucv_equal(ucv_array_get(stack, arridx), needle)) { 506 ret = (ssize_t)arridx; 507 break; 508 } 509 } 510 } 511 else { 512 for (arridx = bounded ? (size_t)start : 0; arridx < slen; arridx++) { 513 if (uc_uniq_ucv_equal(ucv_array_get(stack, arridx), needle)) { 514 ret = (ssize_t)arridx; 515 break; 516 } 517 } 518 } 519 520 return ucv_int64_new(ret); 521 522 case UC_STRING: 523 if (ucv_type(needle) != UC_STRING) 524 return ucv_int64_new(ret); 525 526 sstr = ucv_string_get(stack); 527 slen = ucv_string_length(stack); 528 nstr = ucv_string_get(needle); 529 nlen = ucv_string_length(needle); 530 531 if (bounded) { 532 if (start < 0) 533 start += (ssize_t)slen; 534 535 if (start < 0) 536 start = 0; 537 else if (start > (ssize_t)slen) 538 start = (ssize_t)slen; 539 } 540 541 if (!right) { 542 if (nlen <= slen && (size_t)start <= slen - nlen) { 543 p = (const char *)memmem(sstr + start, slen - (size_t)start, nstr, nlen); 544 545 if (p) 546 ret = (ssize_t)(p - sstr); 547 } 548 } 549 else if (nlen <= slen) { 550 high = slen - nlen; 551 552 if (bounded && (size_t)start < high) 553 high = (size_t)start; 554 555 p = sstr + high; 556 557 for (;;) { 558 if (memcmp(p, nstr, nlen) == 0) { 559 ret = (ssize_t)(p - sstr); 560 break; 561 } 562 563 if (p == sstr) 564 break; 565 566 p--; 567 } 568 } 569 570 return ucv_int64_new(ret); 571 572 default: 573 return NULL; 574 } 575 } 576 577 /** 578 * Finds the given value passed as the second argument within the array or 579 * string specified in the first argument. 580 * 581 * Returns the first matching array index or first matching string offset or 582 * `-1` if the value was not found. 583 * 584 * Returns `null` if the first argument was neither an array nor a string. 585 * 586 * @function module:core#index 587 * 588 * @param {Array|string} arr_or_str 589 * The array or string to search for the value. 590 * 591 * @param {*} needle 592 * The value to find within the array or string. 593 * 594 * @param {?number} [offset=0] 595 * Optional index to begin the search at, counted in bytes for strings and in 596 * elements for arrays. A negative offset is relative to the end and an 597 * out-of-range offset is clamped rather than treated as a failure. 598 * 599 * @returns {?number} 600 * 601 * @example 602 * index("hello world", "o") // 4 603 * index("hello world", "o", 5) // 7 604 * index("hello world", "l", -3) // 9 605 * index("Hello hello hello", "ll") // 2 606 * index([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2) // 1 607 * index("foo", "bar") // -1 608 * index(["Red", "Blue", "Green"], "Brown") // -1 609 * index(123, 2) // null 610 */ 611 static uc_value_t * 612 uc_lindex(uc_vm_t *vm, size_t nargs) 613 { 614 return uc_index(vm, nargs, false); 615 } 616 617 /** 618 * Finds the given value passed as the second argument within the array or 619 * string specified in the first argument. 620 * 621 * Returns the last matching array index or last matching string offset or 622 * `-1` if the value was not found. 623 * 624 * Returns `null` if the first argument was neither an array nor a string. 625 * 626 * @function module:core#rindex 627 * 628 * @param {Array|string} arr_or_str 629 * The array or string to search for the value. 630 * 631 * @param {*} needle 632 * The value to find within the array or string. 633 * 634 * @param {?number} [offset] 635 * Optional upper bound: only indices less than or equal to it are considered. 636 * A negative offset is relative to the end and an out-of-range offset is 637 * clamped rather than treated as a failure. 638 * 639 * @returns {?number} 640 * 641 * @example 642 * rindex("hello world", "o") // 7 643 * rindex("hello world", "o", 5) // 4 644 * rindex("Hello hello hello", "ll") // 14 645 * rindex([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2) // 7 646 * rindex("foo", "bar") // -1 647 * rindex(["Red", "Blue", "Green"], "Brown") // -1 648 * rindex(123, 2) // null 649 */ 650 static uc_value_t * 651 uc_rindex(uc_vm_t *vm, size_t nargs) 652 { 653 return uc_index(vm, nargs, true); 654 } 655 656 static bool 657 assert_mutable(uc_vm_t *vm, uc_value_t *val) 658 { 659 if (ucv_is_constant(val)) { 660 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 661 "%s value is immutable", 662 ucv_typename(val)); 663 664 return false; 665 } 666 667 return true; 668 } 669 670 static bool 671 assert_mutable_array(uc_vm_t *vm, uc_value_t *val) 672 { 673 if (ucv_type(val) != UC_ARRAY) 674 return false; 675 676 return assert_mutable(vm, val); 677 } 678 679 /** 680 * Pushes the given argument(s) to the given array. 681 * 682 * Returns the last pushed value. 683 * 684 * @function module:core#push 685 * 686 * @param {Array} arr 687 * The array to push values to. 688 * 689 * @param {...*} [values] 690 * The values to push. 691 * 692 * @returns {*} 693 * 694 * @example 695 * let x = [ 1, 2, 3 ]; 696 * push(x, 4, 5, 6); // 6 697 * print(x, "\n"); // [ 1, 2, 3, 4, 5, 6 ] 698 */ 699 static uc_value_t * 700 uc_push(uc_vm_t *vm, size_t nargs) 701 { 702 uc_value_t *arr = uc_fn_arg(0); 703 uc_value_t *item = NULL; 704 size_t arridx; 705 706 if (!assert_mutable_array(vm, arr)) 707 return NULL; 708 709 for (arridx = 1; arridx < nargs; arridx++) { 710 item = uc_fn_arg(arridx); 711 ucv_array_push(arr, ucv_get(item)); 712 } 713 714 return ucv_get(item); 715 } 716 717 /** 718 * Pops the last item from the given array and returns it. 719 * 720 * Returns `null` if the array was empty or if a non-array argument was passed. 721 * 722 * @function module:core#pop 723 * 724 * @param {Array} arr 725 * The input array. 726 * 727 * @returns {*} 728 * 729 * @example 730 * let x = [ 1, 2, 3 ]; 731 * pop(x); // 3 732 * print(x, "\n"); // [ 1, 2 ] 733 */ 734 static uc_value_t * 735 uc_pop(uc_vm_t *vm, size_t nargs) 736 { 737 uc_value_t *arr = uc_fn_arg(0); 738 739 if (!assert_mutable_array(vm, arr)) 740 return NULL; 741 742 return ucv_array_pop(arr); 743 } 744 745 /** 746 * Pops the first item from the given array and returns it. 747 * 748 * Returns `null` if the array was empty or if a non-array argument was passed. 749 * 750 * @function module:core#shift 751 * 752 * @param {Array} arr 753 * The array from which to pop the first item. 754 * 755 * @returns {*} 756 * 757 * @example 758 * let x = [ 1, 2, 3 ]; 759 * shift(x); // 1 760 * print(x, "\n"); // [ 2, 3 ] 761 */ 762 static uc_value_t * 763 uc_shift(uc_vm_t *vm, size_t nargs) 764 { 765 uc_value_t *arr = uc_fn_arg(0); 766 767 if (!assert_mutable_array(vm, arr)) 768 return NULL; 769 770 return ucv_array_shift(arr); 771 } 772 773 /** 774 * Add the given values to the beginning of the array passed via first argument. 775 * 776 * Returns the last value added to the array. 777 * 778 * @function module:core#unshift 779 * 780 * @param {Array} arr 781 * The array to which the values will be added. 782 * 783 * @param {...*} 784 * Values to add. 785 * 786 * @returns {*} 787 * 788 * @example 789 * let x = [ 3, 4, 5 ]; 790 * unshift(x, 1, 2); // 2 791 * print(x, "\n"); // [ 1, 2, 3, 4, 5 ] 792 */ 793 static uc_value_t * 794 uc_unshift(uc_vm_t *vm, size_t nargs) 795 { 796 uc_value_t *arr = uc_fn_arg(0); 797 uc_value_t *item; 798 size_t i; 799 800 if (!assert_mutable_array(vm, arr)) 801 return NULL; 802 803 for (i = 1; i < nargs; i++) { 804 item = uc_fn_arg(nargs - i); 805 ucv_array_unshift(arr, ucv_get(item)); 806 } 807 808 return (nargs > 1) ? ucv_get(uc_fn_arg(nargs - 1)) : NULL; 809 } 810 811 /** 812 * Converts each given numeric value to a byte and return the resulting string. 813 * Invalid numeric values or values < 0 result in `\0` bytes, values larger than 814 * 255 are truncated to 255. 815 * 816 * Returns a new strings consisting of the given byte values. 817 * 818 * @function module:core#chr 819 * 820 * @param {...number} n1 821 * The numeric values. 822 * 823 * @returns {string} 824 * 825 * @example 826 * chr(65, 98, 99); // "Abc" 827 * chr(-1, 300); // string consisting of an `0x0` and a `0xff` byte 828 */ 829 static uc_value_t * 830 uc_chr(uc_vm_t *vm, size_t nargs) 831 { 832 uc_value_t *rv = NULL; 833 size_t idx; 834 int64_t n; 835 char *str; 836 837 if (!nargs) 838 return ucv_string_new_length("", 0); 839 840 str = xalloc(nargs); 841 842 for (idx = 0; idx < nargs; idx++) { 843 n = ucv_to_integer(uc_fn_arg(idx)); 844 845 if (n < 0) 846 n = 0; 847 else if (n > 255) 848 n = 255; 849 850 str[idx] = (char)n; 851 } 852 853 rv = ucv_string_new_length(str, nargs); 854 free(str); 855 856 return rv; 857 } 858 859 static uc_exception_type_t 860 check_exception_object(uc_value_t *obj) 861 { 862 uc_value_t *trace, *entry, *type; 863 uc_exception_type_t i; 864 const char *typestr; 865 size_t len; 866 867 if (ucv_type(obj) != UC_OBJECT) 868 return EXCEPTION_NONE; 869 870 trace = ucv_object_get(obj, "stacktrace", NULL); 871 872 if (ucv_type(trace) != UC_ARRAY) 873 return EXCEPTION_NONE; 874 875 len = ucv_array_length(trace); 876 877 if (len == 0) 878 return EXCEPTION_NONE; 879 880 entry = ucv_array_get(trace, 0); 881 882 if (ucv_type(entry) != UC_OBJECT || ucv_object_get(entry, "line", NULL) == NULL) 883 return EXCEPTION_NONE; 884 885 type = ucv_object_get(obj, "type", NULL); 886 887 if (ucv_type(type) != UC_STRING) 888 return EXCEPTION_USER; 889 890 typestr = ucv_string_get(type); 891 892 for (i = EXCEPTION_SYNTAX; i < EXCEPTION_MAX; i++) 893 if (exception_type_strings[i] && strcmp(typestr, exception_type_strings[i]) == 0) 894 return i; 895 896 return EXCEPTION_USER; 897 } 898 899 /** 900 * Raise an exception with the given message and abort execution. 901 * 902 * When passed an exception object (an object with `message` and/or 903 * `stacktrace` properties matching the shape of a caught exception), 904 * `die()` preserves the original message and stacktrace instead of 905 * creating new ones — enabling clean re-throw semantics. 906 * 907 * @function module:core#die 908 * 909 * @param {string|Object} msg 910 * The error message, or an exception-like object with `message` and 911 * `stacktrace` properties. 912 * 913 * @throws {Error} 914 * The error with the given message. 915 * 916 * @example 917 * die(msg); 918 * 919 * @example 920 * try { 921 * inner(); 922 * } catch (e) { 923 * die(e); // re-throw preserving original message and stacktrace 924 * } 925 */ 926 static uc_value_t * 927 uc_die(uc_vm_t *vm, size_t nargs) 928 { 929 uc_value_t *arg = uc_fn_arg(0); 930 uc_exception_type_t etype; 931 bool freeable = false; 932 char *s; 933 934 /* If arg is an exception object with a valid stacktrace, use it 935 * directly to avoid the cost of capturing a new one. */ 936 etype = check_exception_object(arg); 937 938 if (etype != EXCEPTION_NONE) 939 { 940 uc_value_t *msg = ucv_object_get(arg, "message", NULL); 941 942 s = msg ? uc_cast_string(vm, &msg, &freeable) : "Died"; 943 944 vm->exception.type = etype; 945 free(vm->exception.message); 946 vm->exception.message = strdup(s); 947 948 ucv_put(vm->exception.stacktrace); 949 vm->exception.stacktrace = ucv_get(ucv_object_get(arg, "stacktrace", NULL)); 950 } 951 else 952 { 953 s = arg ? uc_cast_string(vm, &arg, &freeable) : "Died"; 954 uc_vm_raise_exception(vm, EXCEPTION_USER, "%s", s); 955 } 956 957 if (freeable) 958 free(s); 959 960 return NULL; 961 } 962 963 /** 964 * Check whether the given key exists within the given object value. 965 * 966 * Returns `true` if the given key is present within the object passed as the 967 * first argument, otherwise `false`. 968 * 969 * @function module:core#exists 970 * 971 * @param {Object} obj 972 * The input object. 973 * 974 * @param {string} key 975 * The key to check for existence. 976 * 977 * @returns {boolean} 978 * 979 * @example 980 * let x = { foo: true, bar: false, qrx: null }; 981 * exists(x, 'foo'); // true 982 * exists(x, 'qrx'); // true 983 * exists(x, 'baz'); // false 984 */ 985 static uc_value_t * 986 uc_exists(uc_vm_t *vm, size_t nargs) 987 { 988 uc_value_t *obj = uc_fn_arg(0); 989 uc_value_t *key = uc_fn_arg(1); 990 bool found, freeable; 991 char *k; 992 993 if (ucv_type(obj) != UC_OBJECT) 994 return ucv_boolean_new(false); 995 996 k = uc_cast_string(vm, &key, &freeable); 997 998 ucv_object_get(obj, k, &found); 999 1000 if (freeable) 1001 free(k); 1002 1003 return ucv_boolean_new(found); 1004 } 1005 1006 /** 1007 * Raw property read: the non-metamethod counterpart of `obj[key]`. 1008 * 1009 * Reads the property the way the VM would if `obj` had no `__get__` in its 1010 * prototype chain (array index / resource type-proto / object own key + 1011 * prototype chain), without dispatching `__get__`. This is the escape hatch a 1012 * `__get__` uses to read the underlying storage without re-dispatching itself 1013 * (a `__get__` that did `return this[key]` would otherwise recurse). 1014 * 1015 * @example 1016 * let o = proto({}, { __get__: function(k) { return rawget(this, k) || 'x'; } }); 1017 * 1018 * @param {object|array|resource} obj The value to read from. 1019 * @param {string|number} key The property key. 1020 * @return {*} The property value, or null if not present. 1021 */ 1022 static uc_value_t * 1023 uc_rawget(uc_vm_t *vm, size_t nargs) 1024 { 1025 uc_value_t *obj = uc_fn_arg(0); 1026 uc_value_t *key = uc_fn_arg(1); 1027 1028 return ucv_key_rawget(vm, obj, key); 1029 } 1030 1031 /** 1032 * Raw property write: the non-metamethod counterpart of `obj[key] = val`. 1033 * 1034 * Stores the property the way the VM would if `obj` had no `__set__` in its 1035 * prototype chain (own-key store for objects, index store for arrays), without 1036 * dispatching `__set__`. Escape hatch for a `__set__` that needs to write the 1037 * underlying storage without re-dispatching itself. 1038 * 1039 * @example 1040 * let o = proto({}, { __set__: function(k, v) { rawset(this, k, v); } }); 1041 * 1042 * @param {object|array} obj The value to write to. 1043 * @param {string|number} key The property key. 1044 * @param {*} val The value to store. 1045 * @return {*} The stored value (null on failure, e.g. non-container). 1046 */ 1047 static uc_value_t * 1048 uc_rawset(uc_vm_t *vm, size_t nargs) 1049 { 1050 uc_value_t *obj = uc_fn_arg(0); 1051 uc_value_t *key = uc_fn_arg(1); 1052 uc_value_t *val = uc_fn_arg(2); 1053 1054 return ucv_key_rawset(vm, obj, key, val); 1055 } 1056 1057 /** 1058 * Raw property delete: the non-metamethod counterpart of `delete obj[key]`. 1059 * 1060 * Deletes the own property the way the VM would if `obj` had no `__delete__` 1061 * in its prototype chain, without dispatching `__delete__`. Escape hatch for a 1062 * `__delete__` that needs to remove the underlying storage without 1063 * re-dispatching itself. 1064 * 1065 * @example 1066 * let o = proto({}, { __delete__: function(k) { return rawdelete(this, k); } }); 1067 * 1068 * @param {object} obj The value to delete from. 1069 * @param {string|number} key The property key. 1070 * @return {boolean} true if a property was deleted, false otherwise. 1071 */ 1072 static uc_value_t * 1073 uc_rawdelete(uc_vm_t *vm, size_t nargs) 1074 { 1075 uc_value_t *obj = uc_fn_arg(0); 1076 uc_value_t *key = uc_fn_arg(1); 1077 1078 return ucv_boolean_new(ucv_key_rawdelete(vm, obj, key)); 1079 } 1080 1081 /** 1082 * Terminate the interpreter with the given exit code. 1083 * 1084 * This function does not return. 1085 * 1086 * @function module:core#exit 1087 * 1088 * @param {number} n 1089 * The exit code. 1090 * 1091 * @example 1092 * exit(); 1093 * exit(5); 1094 */ 1095 static uc_value_t * 1096 uc_exit(uc_vm_t *vm, size_t nargs) 1097 { 1098 int64_t n = ucv_to_integer(uc_fn_arg(0)); 1099 1100 vm->arg.s32 = (int32_t)n; 1101 uc_vm_raise_exception(vm, EXCEPTION_EXIT, "Terminated"); 1102 1103 return NULL; 1104 } 1105 1106 /** 1107 * Query an environment variable or then entire environment. 1108 * 1109 * Returns the value of the given environment variable, or - if omitted - a 1110 * dictionary containing all environment variables. 1111 * 1112 * @function module:core#getenv 1113 * 1114 * @param {string} [name] 1115 * The name of the environment variable. 1116 * 1117 * @returns {string|Object<string, string>} 1118 */ 1119 static uc_value_t * 1120 uc_getenv(uc_vm_t *vm, size_t nargs) 1121 { 1122 uc_value_t *key = uc_fn_arg(0), *rv = NULL; 1123 extern char **environ; 1124 char **env = environ; 1125 char *k, *v; 1126 1127 if (!key) { 1128 rv = ucv_object_new(vm); 1129 1130 while (*env) { 1131 v = strchr(*env, '='); 1132 1133 if (v) { 1134 xasprintf(&k, "%.*s", (int)(v - *env), *env); 1135 ucv_object_add(rv, k, ucv_string_new(v + 1)); 1136 free(k); 1137 } 1138 1139 env++; 1140 } 1141 } 1142 else if (ucv_type(key) == UC_STRING) { 1143 k = ucv_string_get(key); 1144 v = getenv(k); 1145 1146 if (v) 1147 rv = ucv_string_new(v); 1148 } 1149 1150 return rv; 1151 } 1152 1153 /** 1154 * Filter the array passed as the first argument by invoking the function 1155 * specified in the second argument for each array item. 1156 * 1157 * If the invoked function returns a truthy result, the item is retained, 1158 * otherwise, it is dropped. The filter function is invoked with three 1159 * arguments: 1160 * 1161 * 1. The array value 1162 * 2. The current index 1163 * 3. The array being filtered 1164 * 1165 * (Note that the `map` function behaves similarly to `filter` with respect 1166 * to its `fn` parameters.) 1167 * 1168 * Returns a new array containing only retained items, in the same order as 1169 * the input array. 1170 * 1171 * @function module:core#filter 1172 * 1173 * @param {Array} arr 1174 * The input array. 1175 * 1176 * @param {Function} fn 1177 * The filter function. 1178 * 1179 * @returns {Array} 1180 * 1181 * @example 1182 * // filter out any empty string: 1183 * a = filter(["foo", "", "bar", "", "baz"], length) 1184 * // a = ["foo", "bar", "baz"] 1185 * 1186 * // filter out any non-number type: 1187 * a = filter(["foo", 1, true, null, 2.2], function(v) { 1188 * return (type(v) == "int" || type(v) == "double"); 1189 * }); 1190 * // a = [1, 2.2] 1191 */ 1192 static uc_value_t * 1193 uc_filter(uc_vm_t *vm, size_t nargs) 1194 { 1195 uc_value_t *obj = uc_fn_arg(0); 1196 uc_value_t *func = uc_fn_arg(1); 1197 uc_value_t *rv, *arr; 1198 size_t arridx, arrlen; 1199 1200 if (ucv_type(obj) != UC_ARRAY) 1201 return NULL; 1202 1203 arr = ucv_array_new(vm); 1204 uc_vm_stack_push(vm, ucv_get(arr)); 1205 1206 for (arrlen = ucv_array_length(obj), arridx = 0; arridx < arrlen; arridx++) { 1207 uc_vm_ctx_push(vm); 1208 uc_vm_stack_push(vm, ucv_get(func)); 1209 uc_vm_stack_push(vm, ucv_get(ucv_array_get(obj, arridx))); 1210 uc_vm_stack_push(vm, ucv_int64_new(arridx)); 1211 uc_vm_stack_push(vm, ucv_get(obj)); 1212 1213 if (uc_vm_call(vm, true, 3)) { 1214 ucv_put(arr); 1215 1216 return NULL; 1217 } 1218 1219 rv = uc_vm_stack_pop(vm); 1220 1221 if (ucv_is_truish(rv)) 1222 ucv_array_push(arr, ucv_get(ucv_array_get(obj, arridx))); 1223 1224 ucv_put(rv); 1225 } 1226 1227 ucv_put(uc_vm_stack_pop(vm)); 1228 1229 return arr; 1230 } 1231 1232 /** 1233 * Converts the given hexadecimal string into a number. 1234 * 1235 * Returns the resulting integer value or `NaN` if the input value cannot be 1236 * interpreted as hexadecimal number. 1237 * 1238 * @function module:core#hex 1239 * 1240 * @param {*} x 1241 * The hexadecimal string to be converted. 1242 * 1243 * @returns {number} 1244 */ 1245 static uc_value_t * 1246 uc_hex(uc_vm_t *vm, size_t nargs) 1247 { 1248 uc_value_t *val = uc_fn_arg(0); 1249 char *e, *v; 1250 int64_t n; 1251 1252 v = ucv_string_get(val); 1253 1254 if (!v || !isxdigit((unsigned char)*v)) 1255 return ucv_double_new(NAN); 1256 1257 n = strtoll(v, &e, 16); 1258 1259 if (e == v || *e) 1260 return ucv_double_new(NAN); 1261 1262 return ucv_int64_new(n); 1263 } 1264 1265 /** 1266 * Converts the given value to an integer, using an optional base. 1267 * 1268 * Returns `NaN` if the value is not convertible. 1269 * 1270 * @function module:core#int 1271 * 1272 * @param {*} x 1273 * The value to be converted to an integer. 1274 * 1275 * @param {int} [base] 1276 * The base into which the value is to be converted, the default is 10. 1277 * Note that the base parameter is ignored if the `x` value is already numeric. 1278 * 1279 * @returns {number} 1280 * 1281 * @example 1282 * int("123") // Returns 123 1283 * int("123", 10) // 123 1284 * int("10 or more") // 10 1285 * int("12.3") // 12 1286 * int("123", 7) // 66 1287 * int("abc", 16) // 2748 1288 * int("xyz", 36) // 44027 1289 * int(10.10, "2") // 10, the invalid base is ignored 1290 * int("xyz", 16) // NaN, bad value 1291 * int("1010", "2") // NaN, bad base 1292 */ 1293 static uc_value_t * 1294 uc_int(uc_vm_t *vm, size_t nargs) 1295 { 1296 uc_value_t *val = uc_fn_arg(0); 1297 uc_value_t *base = uc_fn_arg(1); 1298 char *e, *v; 1299 int64_t n; 1300 1301 if (ucv_type(val) == UC_STRING) { 1302 errno = 0; 1303 v = ucv_string_get(val); 1304 n = strtoll(v, &e, base ? ucv_int64_get(base) : 10); 1305 1306 if (e == v) 1307 return ucv_double_new(NAN); 1308 } 1309 else { 1310 n = ucv_to_integer(val); 1311 } 1312 1313 if (errno == EINVAL || errno == ERANGE) 1314 return ucv_double_new(NAN); 1315 1316 return ucv_int64_new(n); 1317 } 1318 1319 /** 1320 * Joins the array passed as the second argument into a string, using the 1321 * separator passed in the first argument as glue. 1322 * 1323 * Returns `null` if the second argument is not an array. 1324 * 1325 * @function module:core#join 1326 * 1327 * @param {string} sep 1328 * The separator to be used in joining the array elements. 1329 * 1330 * @param {Array} arr 1331 * The array to be joined into a string. 1332 * 1333 * @returns {?string} 1334 */ 1335 static uc_value_t * 1336 uc_join(uc_vm_t *vm, size_t nargs) 1337 { 1338 uc_value_t *sep = uc_fn_arg(0); 1339 uc_value_t *arr = uc_fn_arg(1); 1340 size_t arrlen, arridx; 1341 uc_stringbuf_t *buf; 1342 1343 if (ucv_type(arr) != UC_ARRAY) 1344 return NULL; 1345 1346 buf = ucv_stringbuf_new(); 1347 1348 for (arrlen = ucv_array_length(arr), arridx = 0; arridx < arrlen; arridx++) { 1349 if (arridx > 0) 1350 ucv_to_stringbuf(vm, buf, sep, false); 1351 1352 ucv_to_stringbuf(vm, buf, ucv_array_get(arr, arridx), false); 1353 } 1354 1355 return ucv_stringbuf_finish(buf); 1356 } 1357 1358 /** 1359 * Enumerates all object key names. 1360 * 1361 * Returns an array of all key names present in the passed object. 1362 * Returns `null` if the given argument is not an object. 1363 * 1364 * @function module:core#keys 1365 * 1366 * @param {object} obj 1367 * The object from which to retrieve the key names. 1368 * 1369 * @returns {?Array} 1370 */ 1371 static uc_value_t * 1372 uc_keys(uc_vm_t *vm, size_t nargs) 1373 { 1374 uc_value_t *obj = uc_fn_arg(0); 1375 uc_value_t *arr = NULL; 1376 1377 if (ucv_type(obj) != UC_OBJECT) 1378 return NULL; 1379 1380 arr = ucv_array_new(vm); 1381 1382 ucv_object_foreach(obj, key, val) { 1383 (void)val; 1384 ucv_array_push(arr, ucv_string_new(key)); 1385 } 1386 1387 return arr; 1388 } 1389 1390 /** 1391 * Convert the given string to lowercase and return the resulting string. 1392 * 1393 * Returns `null` if the given argument could not be converted to a string. 1394 * 1395 * @function module:core#lc 1396 * 1397 * @param {string} s 1398 * The input string. 1399 * 1400 * @returns {?string} 1401 * The lowercase string. 1402 * 1403 * @example 1404 * lc("HeLLo WoRLd!"); // "hello world!" 1405 */ 1406 static uc_value_t * 1407 uc_lc(uc_vm_t *vm, size_t nargs) 1408 { 1409 uc_stringbuf_t *buf = xprintbuf_new(); 1410 uc_value_t *rv; 1411 size_t i, len; 1412 char *s; 1413 1414 ucv_to_stringbuf(vm, buf, uc_fn_arg(0), false); 1415 1416 s = buf->buf; 1417 len = printbuf_length(buf); 1418 1419 for (i = 0; i < len; i++) 1420 if (s[i] >= 'A' && s[i] <= 'Z') 1421 s[i] |= 32; 1422 1423 rv = ucv_string_new_length(s, len); 1424 1425 printbuf_free(buf); 1426 1427 return rv; 1428 } 1429 1430 /** 1431 * Transform the array passed as the first argument by invoking the function 1432 * specified in the second argument for each array item. 1433 * 1434 * The mapping function is invoked with three arguments (see examples, below, 1435 * for some possibly counterintuitive usage): 1436 * 1437 * 1. The array value 1438 * 2. The current index 1439 * 3. The array being filtered 1440 * 1441 * (Note that the `filter` function behaves similarly to `map` with respect 1442 * to its `fn` parameters.) 1443 * 1444 * Returns a new array of the same length as the input array containing the 1445 * transformed values. 1446 * 1447 * @function module:core#map 1448 * 1449 * @param {Array} arr 1450 * The input array. 1451 * 1452 * @param {Function} fn 1453 * The mapping function. 1454 * 1455 * @returns {Array} 1456 * 1457 * @example 1458 * // turn into an array of string lengths: 1459 * a = map(["Apple", "Banana", "Bean"], length); 1460 * // a = [5, 6, 4] 1461 * 1462 * // map to type names: 1463 * a = map(["foo", 1, true, null, 2.2], type); 1464 * // a = ["string", "int", "bool", null, "double"] 1465 * 1466 * // attempt to naively use built-in 'int' to map an array: 1467 * a = map(["x", "2", "11", "7"], int) 1468 * // a = [NaN, NaN, 3, NaN] 1469 * // 1470 * // This is a direct result of 'int' being provided the second, index parameter 1471 * // for its base value in the conversion. 1472 * // 1473 * // The resulting calls to 'int' are as follows: 1474 * // int("x", 0, [...]) - convert "x" to base 0, 'int' ignores the third value 1475 * // int("2", 1, [...]) - convert "2" to base 1, digit out of range, so NaN 1476 * // int("11", 2, [...]) - convert "11" to base 2, produced unexpected 3 1477 * // int("7", 3, [...]) - convert "7" to base 3, digit out of range, NaN again 1478 * 1479 * // remedy this by using an arrow function to ensure the proper base value 1480 * // (in this case, the default of 10) is passed to 'int': 1481 * a = map(["x", "2", "1", "7"], (x) => int(x)) 1482 * // a = [NaN, 2, 1, 7] 1483 * 1484 * // convert base-2 values: 1485 * a = map(["22", "1010", "0001", "0101"], (x) => int(x, 2)) 1486 * // a = [NaN, 10, 1, 5] 1487 */ 1488 static uc_value_t * 1489 uc_map(uc_vm_t *vm, size_t nargs) 1490 { 1491 uc_value_t *obj = uc_fn_arg(0); 1492 uc_value_t *func = uc_fn_arg(1); 1493 uc_value_t *arr, *rv; 1494 size_t arridx, arrlen; 1495 1496 if (ucv_type(obj) != UC_ARRAY) 1497 return NULL; 1498 1499 arr = ucv_array_new(vm); 1500 uc_vm_stack_push(vm, ucv_get(arr)); 1501 1502 for (arrlen = ucv_array_length(obj), arridx = 0; arridx < arrlen; arridx++) { 1503 uc_vm_ctx_push(vm); 1504 uc_vm_stack_push(vm, ucv_get(func)); 1505 uc_vm_stack_push(vm, ucv_get(ucv_array_get(obj, arridx))); 1506 uc_vm_stack_push(vm, ucv_int64_new(arridx)); 1507 uc_vm_stack_push(vm, ucv_get(obj)); 1508 1509 if (uc_vm_call(vm, true, 3)) { 1510 ucv_put(arr); 1511 1512 return NULL; 1513 } 1514 1515 rv = uc_vm_stack_pop(vm); 1516 1517 ucv_array_push(arr, rv); 1518 } 1519 1520 ucv_put(uc_vm_stack_pop(vm)); 1521 1522 return arr; 1523 } 1524 1525 /** 1526 * Without further arguments, this function returns the byte value of the first 1527 * character in the given string. 1528 * 1529 * If an offset argument is supplied, the byte value of the character at this 1530 * position is returned. If an invalid index is supplied, the function will 1531 * return `null`. Negative index entries are counted towards the end of the 1532 * string, e.g. `-2` will return the value of the second last character. 1533 * 1534 * Returns the byte value of the character. 1535 * Returns `null` if the offset is invalid or if the input is not a string. 1536 * 1537 * @function module:core#ord 1538 * 1539 * @param {string} s 1540 * The input string. 1541 * 1542 * @param {number} [offset] 1543 * The offset of the character. 1544 * 1545 * @returns {?number} 1546 * 1547 * @example 1548 * ord("Abc"); // 65 1549 * ord("Abc", 0); // 65 1550 * ord("Abc", 1); // 98 1551 * ord("Abc", 2); // 99 1552 * ord("Abc", 10); // null 1553 * ord("Abc", -10); // null 1554 * ord("Abc", "nan"); // null 1555 */ 1556 static uc_value_t * 1557 uc_ord(uc_vm_t *vm, size_t nargs) 1558 { 1559 uc_value_t *obj = uc_fn_arg(0); 1560 const char *str; 1561 int64_t n = 0; 1562 size_t len; 1563 1564 if (ucv_type(obj) != UC_STRING) 1565 return NULL; 1566 1567 str = ucv_string_get(obj); 1568 len = ucv_string_length(obj); 1569 1570 if (nargs > 1) { 1571 n = ucv_int64_get(uc_fn_arg(1)); 1572 1573 if (errno == EINVAL) 1574 return NULL; 1575 1576 if (n < 0) 1577 n += len; 1578 } 1579 1580 if (n < 0 || (uint64_t)n >= len) 1581 return NULL; 1582 1583 return ucv_int64_new((uint8_t)str[n]); 1584 } 1585 1586 /** 1587 * Query the type of the given value. 1588 * 1589 * Returns the type of the given value as a string which might be one of 1590 * `"function"`, `"object"`, `"array"`, `"double"`, `"int"`, or `"bool"`. 1591 * 1592 * Returns `null` when no value or `null` is passed. 1593 * 1594 * @function module:core#type 1595 * 1596 * @param {*} x 1597 * The value to determine the type of. 1598 * 1599 * @returns {?string} 1600 */ 1601 static uc_value_t * 1602 uc_type(uc_vm_t *vm, size_t nargs) 1603 { 1604 uc_value_t *v = uc_fn_arg(0); 1605 uc_type_t t = ucv_type(v); 1606 1607 switch (t) { 1608 case UC_CFUNCTION: 1609 case UC_CLOSURE: 1610 return ucv_string_new("function"); 1611 1612 case UC_INTEGER: 1613 return ucv_string_new("int"); 1614 1615 case UC_BOOLEAN: 1616 return ucv_string_new("bool"); 1617 1618 case UC_NULL: 1619 return NULL; 1620 1621 default: 1622 return ucv_string_new(ucv_typename(v)); 1623 } 1624 } 1625 1626 /** 1627 * Reverse the order of the given input array or string. 1628 * 1629 * If an array is passed, returns the array in reverse order. 1630 * If a string is passed, returns the string with the sequence of the characters 1631 * reversed. 1632 * 1633 * Returns the reversed array or string. 1634 * Returns `null` if neither an array nor a string were passed. 1635 * 1636 * @function module:core#reverse 1637 * 1638 * @param {Array|string} arr_or_str 1639 * The input array or string. 1640 * 1641 * @returns {?(Array|string)} 1642 * 1643 * @example 1644 * reverse([1, 2, 3]); // [ 3, 2, 1 ] 1645 * reverse("Abc"); // "cbA" 1646 */ 1647 static uc_value_t * 1648 uc_reverse(uc_vm_t *vm, size_t nargs) 1649 { 1650 uc_value_t *obj = uc_fn_arg(0); 1651 uc_value_t *rv = NULL; 1652 size_t len, arridx; 1653 const char *str; 1654 char *dup, *p; 1655 1656 if (ucv_type(obj) == UC_ARRAY) { 1657 if (!assert_mutable_array(vm, obj)) 1658 return NULL; 1659 1660 rv = ucv_array_new(vm); 1661 1662 for (arridx = ucv_array_length(obj); arridx > 0; arridx--) 1663 ucv_array_push(rv, ucv_get(ucv_array_get(obj, arridx - 1))); 1664 } 1665 else if (ucv_type(obj) == UC_STRING) { 1666 len = ucv_string_length(obj); 1667 str = ucv_string_get(obj); 1668 p = dup = xalloc(len + 1); 1669 1670 while (len > 0) 1671 *p++ = str[--len]; 1672 1673 rv = ucv_string_new_length(dup, ucv_string_length(obj)); 1674 1675 free(dup); 1676 } 1677 1678 return rv; 1679 } 1680 1681 1682 typedef struct { 1683 uc_vm_t *vm; 1684 bool ex; 1685 uc_value_t *fn; 1686 } sort_ctx_t; 1687 1688 static int 1689 default_cmp(uc_value_t *v1, uc_value_t *v2, sort_ctx_t *ctx) 1690 { 1691 char *s1 = NULL, *s2 = NULL; 1692 bool f1 = false, f2 = false; 1693 int res = 0; 1694 1695 /* when both operands are numeric then compare numerically */ 1696 if ((ucv_type(v1) == UC_INTEGER || ucv_type(v1) == UC_DOUBLE) && 1697 (ucv_type(v2) == UC_INTEGER || ucv_type(v2) == UC_DOUBLE)) { 1698 ucv_compare(0, v1, v2, &res); 1699 1700 return res; 1701 } 1702 1703 /* otherwise convert both operands to strings and compare lexically */ 1704 s1 = uc_cast_string(ctx->vm, &v1, &f1); 1705 1706 if (ctx->vm->exception.type != EXCEPTION_NONE) 1707 goto out; 1708 1709 s2 = uc_cast_string(ctx->vm, &v2, &f2); 1710 1711 if (ctx->vm->exception.type != EXCEPTION_NONE) 1712 goto out; 1713 1714 res = strcmp(s1, s2); 1715 1716 out: 1717 ctx->ex = (ctx->vm->exception.type != EXCEPTION_NONE); 1718 1719 if (f1) free(s1); 1720 if (f2) free(s2); 1721 1722 return res; 1723 } 1724 1725 static int 1726 array_sort_fn(uc_value_t *v1, uc_value_t *v2, void *ud) 1727 { 1728 uc_value_t *rv, *null = ucv_int64_new(0); 1729 sort_ctx_t *ctx = ud; 1730 int res; 1731 1732 if (ctx->ex) 1733 return 0; 1734 1735 if (!ctx->fn) 1736 return default_cmp(v1, v2, ctx); 1737 1738 uc_vm_ctx_push(ctx->vm); 1739 uc_vm_stack_push(ctx->vm, ucv_get(ctx->fn)); 1740 uc_vm_stack_push(ctx->vm, ucv_get(v1)); 1741 uc_vm_stack_push(ctx->vm, ucv_get(v2)); 1742 1743 if (uc_vm_call(ctx->vm, true, 2)) { 1744 ctx->ex = true; 1745 1746 return 0; 1747 } 1748 1749 rv = uc_vm_stack_pop(ctx->vm); 1750 1751 ucv_compare(0, rv, null, &res); 1752 1753 ucv_put(null); 1754 ucv_put(rv); 1755 1756 return res; 1757 } 1758 1759 static int 1760 object_sort_fn(const char *k1, uc_value_t *v1, const char *k2, uc_value_t *v2, 1761 void *ud) 1762 { 1763 uc_value_t *rv, *null = ucv_int64_new(0); 1764 sort_ctx_t *ctx = ud; 1765 int res; 1766 1767 if (ctx->ex) 1768 return 0; 1769 1770 if (!ctx->fn) 1771 return strcmp(k1, k2); 1772 1773 uc_vm_ctx_push(ctx->vm); 1774 uc_vm_stack_push(ctx->vm, ucv_get(ctx->fn)); 1775 uc_vm_stack_push(ctx->vm, ucv_string_new(k1)); 1776 uc_vm_stack_push(ctx->vm, ucv_string_new(k2)); 1777 uc_vm_stack_push(ctx->vm, ucv_get(v1)); 1778 uc_vm_stack_push(ctx->vm, ucv_get(v2)); 1779 1780 if (uc_vm_call(ctx->vm, true, 4)) { 1781 ctx->ex = true; 1782 1783 return 0; 1784 } 1785 1786 rv = uc_vm_stack_pop(ctx->vm); 1787 1788 ucv_compare(0, rv, null, &res); 1789 1790 ucv_put(null); 1791 ucv_put(rv); 1792 1793 return res; 1794 } 1795 1796 /** 1797 * Sort the given array according to the given sort function. 1798 * If no sort function is provided, a default ascending sort order is applied. 1799 * 1800 * The input array is sorted in-place, no copy is made. 1801 * The input is temporarily immutable while sorting. Attempts to modify it 1802 * from the comparator or a string conversion method raise an exception. 1803 * 1804 * The custom sort function is repeatedly called until the entire array is 1805 * sorted. It will receive two values as arguments and should return a value 1806 * lower than, larger than or equal to zero depending on whether the first 1807 * argument is smaller, larger or equal to the second argument respectively. 1808 * 1809 * Returns the sorted input array. 1810 * 1811 * @function module:core#sort 1812 * 1813 * @param {Array} arr 1814 * The input array to be sorted. 1815 * 1816 * @param {Function} [fn] 1817 * The sort function. 1818 * 1819 * @returns {Array} 1820 * 1821 * @example 1822 * sort([8, 1, 5, 9]) // [1, 5, 8, 9] 1823 * sort(["Bean", "Orange", "Apple"], function(a, b) { 1824 * return length(a) - length(b); 1825 * }) // ["Bean", "Apple", "Orange"] 1826 */ 1827 static uc_value_t * 1828 uc_sort(uc_vm_t *vm, size_t nargs) 1829 { 1830 uc_value_t *val = uc_fn_arg(0); 1831 uc_value_t *fn = uc_fn_arg(1); 1832 sort_ctx_t ctx = { 1833 .vm = vm, 1834 .fn = fn, 1835 .ex = false 1836 }; 1837 1838 if (!assert_mutable(vm, val)) 1839 return NULL; 1840 1841 switch (ucv_type(val)) { 1842 case UC_ARRAY: 1843 ucv_array_sort_r(val, array_sort_fn, &ctx); 1844 break; 1845 1846 case UC_OBJECT: 1847 ucv_object_sort_r(val, object_sort_fn, &ctx); 1848 break; 1849 1850 default: 1851 return NULL; 1852 } 1853 1854 return ctx.ex ? NULL : ucv_get(val); 1855 } 1856 1857 /** 1858 * Removes the elements designated by `off` and `len` from the given array, 1859 * and replaces them with the additional arguments passed, if any. 1860 * 1861 * The array grows or shrinks as necessary. 1862 * 1863 * Returns the modified input array. 1864 * 1865 * @function module:core#splice 1866 * 1867 * @param {Array} arr 1868 * The input array to be modified. 1869 * 1870 * @param {number} off 1871 * The index to start removing elements. 1872 * 1873 * @param {number} [len] 1874 * The number of elements to remove. 1875 * 1876 * @param {...*} [elements] 1877 * The elements to insert. 1878 * 1879 * @returns {*} 1880 * 1881 * @example 1882 * let x = [ 1, 2, 3, 4 ]; 1883 * splice(x, 1, 2, "a", "b", "c"); // [ 1, "a", "b", "c", 4 ] 1884 * print(x, "\n"); // [ 1, "a", "b", "c", 4 ] 1885 */ 1886 static uc_value_t * 1887 uc_splice(uc_vm_t *vm, size_t nargs) 1888 { 1889 uc_value_t *arr = uc_fn_arg(0); 1890 int64_t ofs = ucv_to_integer(uc_fn_arg(1)); 1891 int64_t remlen = ucv_to_integer(uc_fn_arg(2)); 1892 size_t arrlen, addlen, idx; 1893 1894 if (!assert_mutable_array(vm, arr)) 1895 return NULL; 1896 1897 arrlen = ucv_array_length(arr); 1898 addlen = nargs; 1899 1900 if (addlen == 1) { 1901 ofs = 0; 1902 addlen = 0; 1903 remlen = arrlen; 1904 } 1905 else if (addlen == 2) { 1906 if (ofs < 0) { 1907 ofs = arrlen + ofs; 1908 1909 if (ofs < 0) 1910 ofs = 0; 1911 } 1912 else if ((uint64_t)ofs > arrlen) { 1913 ofs = arrlen; 1914 } 1915 1916 addlen = 0; 1917 remlen = arrlen - ofs; 1918 } 1919 else { 1920 if (ofs < 0) { 1921 ofs = arrlen + ofs; 1922 1923 if (ofs < 0) 1924 ofs = 0; 1925 } 1926 else if ((uint64_t)ofs > arrlen) { 1927 ofs = arrlen; 1928 } 1929 1930 if (remlen < 0) { 1931 remlen = arrlen - ofs + remlen; 1932 1933 if (remlen < 0) 1934 remlen = 0; 1935 } 1936 else if ((uint64_t)remlen > arrlen - (uint64_t)ofs) { 1937 remlen = arrlen - ofs; 1938 } 1939 1940 addlen -= 3; 1941 } 1942 1943 if (addlen < (uint64_t)remlen) { 1944 ucv_array_delete(arr, ofs, remlen - addlen); 1945 } 1946 else if (addlen > (uint64_t)remlen) { 1947 for (idx = arrlen; idx > (uint64_t)ofs; idx--) 1948 ucv_array_set(arr, idx + addlen - remlen - 1, 1949 ucv_get(ucv_array_get(arr, idx - 1))); 1950 } 1951 1952 for (idx = 0; idx < addlen; idx++) 1953 ucv_array_set(arr, ofs + idx, 1954 ucv_get(uc_fn_arg(3 + idx))); 1955 1956 return ucv_get(arr); 1957 } 1958 1959 /** 1960 * Performs a shallow copy of a portion of the source array, as specified by 1961 * the start and end offsets. The original array is not modified. 1962 * 1963 * Returns a new array containing the copied elements, if any. 1964 * Returns `null` if the given source argument is not an array value. 1965 * 1966 * @function module:core#slice 1967 * 1968 * @param {Array} arr 1969 * The source array to be copied. 1970 * 1971 * @param {number} [off] 1972 * The index of the first element to copy. 1973 * 1974 * @param {number} [end] 1975 * The index of the first element to exclude from the returned array. 1976 * 1977 * @returns {Array} 1978 * 1979 * @example 1980 * slice([1, 2, 3]) // [1, 2, 3] 1981 * slice([1, 2, 3], 1) // [2, 3] 1982 * slice([1, 2, 3], -1) // [3] 1983 * slice([1, 2, 3], -3, -1) // [1, 2] 1984 * slice([1, 2, 3], 10) // [] 1985 * slice([1, 2, 3], 2, 1) // [] 1986 * slice("invalid", 1, 2) // null 1987 */ 1988 static uc_value_t * 1989 uc_slice(uc_vm_t *vm, size_t nargs) 1990 { 1991 uc_value_t *arr = uc_fn_arg(0); 1992 uc_value_t *sv = uc_fn_arg(1); 1993 uc_value_t *ev = uc_fn_arg(2); 1994 uc_value_t *res = NULL; 1995 int64_t off, end; 1996 size_t len; 1997 1998 if (ucv_type(arr) != UC_ARRAY) 1999 return NULL; 2000 2001 len = ucv_array_length(arr); 2002 off = sv ? ucv_to_integer(sv) : 0; 2003 end = ev ? ucv_to_integer(ev) : (int64_t)len; 2004 2005 if (off < 0) { 2006 off = len + off; 2007 2008 if (off < 0) 2009 off = 0; 2010 } 2011 else if ((uint64_t)off > len) { 2012 off = len; 2013 } 2014 2015 if (end < 0) { 2016 end = len + end; 2017 2018 if (end < 0) 2019 end = 0; 2020 } 2021 else if ((uint64_t)end > len) { 2022 end = len; 2023 } 2024 2025 res = ucv_array_new(vm); 2026 2027 while (off < end) 2028 ucv_array_push(res, ucv_get(ucv_array_get(arr, off++))); 2029 2030 return res; 2031 } 2032 2033 /** 2034 * Split the given string using the separator passed as the second argument 2035 * and return an array containing the resulting pieces. 2036 * 2037 * If a limit argument is supplied, the resulting array contains no more than 2038 * the given amount of entries, that means the string is split at most 2039 * `limit - 1` times total. 2040 * 2041 * The separator may either be a plain string or a regular expression. 2042 * 2043 * Returns a new array containing the resulting pieces. 2044 * 2045 * @function module:core#split 2046 * 2047 * @param {string} str 2048 * The input string to be split. 2049 * 2050 * @param {string|RegExp} sep 2051 * The separator. 2052 * 2053 * @param {number} [limit] 2054 * The limit on the number of splits. 2055 * 2056 * @returns {Array} 2057 * 2058 * @example 2059 * split("foo,bar,baz", ",") // ["foo", "bar", "baz"] 2060 * split("foobar", "") // ["f", "o", "o", "b", "a", "r"] 2061 * split("foo,bar,baz", /[ao]/) // ["f", "", ",b", "r,b", "z"] 2062 * split("foo=bar=baz", "=", 2) // ["foo", "bar=baz"] 2063 */ 2064 static uc_value_t * 2065 uc_split(uc_vm_t *vm, size_t nargs) 2066 { 2067 uc_value_t *str = uc_fn_arg(0); 2068 uc_value_t *sep = uc_fn_arg(1); 2069 uc_value_t *lim = uc_fn_arg(2); 2070 uc_value_t *arr = NULL; 2071 const char *p, *sepstr, *splitstr; 2072 size_t seplen, splitlen, limit; 2073 int eflags = 0, res; 2074 regmatch_t pmatch; 2075 uc_regexp_t *re; 2076 2077 if (!sep || ucv_type(str) != UC_STRING) 2078 return NULL; 2079 2080 arr = ucv_array_new(vm); 2081 splitlen = ucv_string_length(str); 2082 p = splitstr = ucv_string_get(str); 2083 limit = lim ? ucv_uint64_get(lim) : SIZE_MAX; 2084 2085 if (limit == 0) 2086 goto out; 2087 2088 if (ucv_type(sep) == UC_REGEXP) { 2089 re = ucv_as_regexp(sep); 2090 2091 while (limit > 1) { 2092 res = regexec(&re->regexp, splitstr, 1, &pmatch, eflags); 2093 2094 if (res == REG_NOMATCH) 2095 break; 2096 2097 if (pmatch.rm_so != pmatch.rm_eo) { 2098 ucv_array_push(arr, ucv_string_new_length(splitstr, pmatch.rm_so)); 2099 splitstr += pmatch.rm_eo; 2100 } 2101 else if (*splitstr) { 2102 ucv_array_push(arr, ucv_string_new_length(splitstr, 1)); 2103 splitstr++; 2104 } 2105 else { 2106 goto out; 2107 } 2108 2109 eflags |= REG_NOTBOL; 2110 limit--; 2111 } 2112 2113 ucv_array_push(arr, ucv_string_new(splitstr)); 2114 } 2115 else if (ucv_type(sep) == UC_STRING) { 2116 sepstr = ucv_string_get(sep); 2117 seplen = ucv_string_length(sep); 2118 2119 if (splitlen == 0) { 2120 ucv_array_push(arr, ucv_string_new_length("", 0)); 2121 } 2122 else if (seplen == 0) { 2123 while (limit > 1 && splitlen > 0) { 2124 ucv_array_push(arr, ucv_string_new_length(p, 1)); 2125 2126 limit--; 2127 splitlen--; 2128 p++; 2129 } 2130 2131 if (splitlen > 0) 2132 ucv_array_push(arr, ucv_string_new_length(p, splitlen)); 2133 } 2134 else { 2135 while (limit > 1 && splitlen >= seplen) { 2136 if (!memcmp(p, sepstr, seplen)) { 2137 ucv_array_push(arr, ucv_string_new_length(splitstr, p - splitstr)); 2138 2139 p = splitstr = p + seplen; 2140 splitlen -= seplen; 2141 limit--; 2142 continue; 2143 } 2144 2145 splitlen--; 2146 p++; 2147 } 2148 2149 ucv_array_push(arr, ucv_string_new_length(splitstr, p - splitstr + splitlen)); 2150 } 2151 } 2152 else { 2153 ucv_put(arr); 2154 2155 return NULL; 2156 } 2157 2158 out: 2159 return arr; 2160 } 2161 2162 /** 2163 * Extracts a substring out of `str` and returns it. First character is at 2164 * offset zero. 2165 * 2166 * - If `off` is negative, starts that far back from the end of the string. 2167 * - If `len` is omitted, returns everything through the end of the string. 2168 * - If `len` is negative, leaves that many characters off the string end. 2169 * 2170 * Returns the extracted substring. 2171 * 2172 * @function module:core#substr 2173 * 2174 * @param {string} str 2175 * The input string. 2176 * 2177 * @param {number} off 2178 * The starting offset. 2179 * 2180 * @param {number} [len] 2181 * The length of the substring. 2182 * 2183 * @returns {string} 2184 * 2185 * @example 2186 * s = "The black cat climbed the green tree"; 2187 * substr(s, 4, 5); // black 2188 * substr(s, 4, -11); // black cat climbed the 2189 * substr(s, 14); // climbed the green tree 2190 * substr(s, -4); // tree 2191 * substr(s, -4, 2); // tr 2192 */ 2193 static uc_value_t * 2194 uc_substr(uc_vm_t *vm, size_t nargs) 2195 { 2196 uc_value_t *str = uc_fn_arg(0); 2197 int64_t ofs = ucv_to_integer(uc_fn_arg(1)); 2198 int64_t sublen = ucv_to_integer(uc_fn_arg(2)); 2199 const char *p; 2200 size_t len; 2201 2202 if (ucv_type(str) != UC_STRING) 2203 return NULL; 2204 2205 p = ucv_string_get(str); 2206 len = ucv_string_length(str); 2207 2208 switch (nargs) { 2209 case 1: 2210 ofs = 0; 2211 sublen = len; 2212 2213 break; 2214 2215 case 2: 2216 if (ofs < 0) { 2217 ofs = len + ofs; 2218 2219 if (ofs < 0) 2220 ofs = 0; 2221 } 2222 else if ((uint64_t)ofs > len) { 2223 ofs = len; 2224 } 2225 2226 sublen = len - ofs; 2227 2228 break; 2229 2230 default: 2231 if (ofs < 0) { 2232 ofs = len + ofs; 2233 2234 if (ofs < 0) 2235 ofs = 0; 2236 } 2237 else if ((uint64_t)ofs > len) { 2238 ofs = len; 2239 } 2240 2241 if (sublen < 0) { 2242 sublen = len - ofs + sublen; 2243 2244 if (sublen < 0) 2245 sublen = 0; 2246 } 2247 else if ((uint64_t)sublen > len - (uint64_t)ofs) { 2248 sublen = len - ofs; 2249 } 2250 2251 break; 2252 } 2253 2254 return ucv_string_new_length(p + ofs, sublen); 2255 } 2256 2257 /** 2258 * Returns the current UNIX epoch. 2259 * 2260 * @function module:core#time 2261 * 2262 * @returns {number} 2263 * 2264 * @example 2265 * time(); // 1598043054 2266 */ 2267 static uc_value_t * 2268 uc_time(uc_vm_t *vm, size_t nargs) 2269 { 2270 time_t t = time(NULL); 2271 2272 return ucv_int64_new((int64_t)t); 2273 } 2274 2275 /** 2276 * Converts the given string to uppercase and returns the resulting string. 2277 * 2278 * Returns null if the given argument could not be converted to a string. 2279 * 2280 * @function module:core#uc 2281 * 2282 * @param {*} str 2283 * The string to be converted to uppercase. 2284 * 2285 * @returns {?string} 2286 * 2287 * @example 2288 * uc("hello"); // "HELLO" 2289 * uc(123); // null 2290 */ 2291 2292 static uc_value_t * 2293 uc_uc(uc_vm_t *vm, size_t nargs) 2294 { 2295 uc_stringbuf_t *buf = xprintbuf_new(); 2296 uc_value_t *rv; 2297 size_t i, len; 2298 char *s; 2299 2300 ucv_to_stringbuf(vm, buf, uc_fn_arg(0), false); 2301 2302 s = buf->buf; 2303 len = printbuf_length(buf); 2304 2305 for (i = 0; i < len; i++) 2306 if (s[i] >= 'a' && s[i] <= 'z') 2307 s[i] &= ~32; 2308 2309 rv = ucv_string_new_length(s, len); 2310 2311 printbuf_free(buf); 2312 2313 return rv; 2314 } 2315 2316 /** 2317 * Converts each given numeric value to an UTF-8 multibyte sequence and returns 2318 * the resulting string. 2319 * 2320 * Invalid numeric values or values outside the range `0`..`0x10FFFF` are 2321 * represented by the unicode replacement character `0xFFFD`. 2322 * 2323 * Returns a new UTF-8 encoded string consisting of unicode characters 2324 * corresponding to the given numeric codepoints. 2325 * 2326 * @function module:core#uchr 2327 * 2328 * @param {...number} 2329 * Numeric values to convert. 2330 * 2331 * @returns {string} 2332 * 2333 * @example 2334 * uchr(0x2600, 0x26C6, 0x2601); // "☀⛆☁" 2335 * uchr(-1, 0x20ffff, "foo"); // "���" 2336 */ 2337 static uc_value_t * 2338 uc_uchr(uc_vm_t *vm, size_t nargs) 2339 { 2340 uc_value_t *rv = NULL; 2341 size_t idx, ulen; 2342 char *p, *str; 2343 int64_t n; 2344 int rem; 2345 2346 for (idx = 0, ulen = 0; idx < nargs; idx++) { 2347 n = ucv_to_integer(uc_fn_arg(idx)); 2348 2349 if (errno == EINVAL || errno == ERANGE || n < 0 || n > 0x10FFFF) 2350 ulen += 3; 2351 else if (n <= 0x7F) 2352 ulen++; 2353 else if (n <= 0x7FF) 2354 ulen += 2; 2355 else if (n <= 0xFFFF) 2356 ulen += 3; 2357 else 2358 ulen += 4; 2359 } 2360 2361 str = xalloc(ulen); 2362 2363 for (idx = 0, p = str, rem = ulen; idx < nargs; idx++) { 2364 n = ucv_to_integer(uc_fn_arg(idx)); 2365 2366 if (errno == EINVAL || errno == ERANGE || n < 0 || n > 0x10FFFF) 2367 n = 0xFFFD; 2368 2369 if (!utf8enc(&p, &rem, n)) 2370 break; 2371 } 2372 2373 rv = ucv_string_new_length(str, ulen); 2374 2375 free(str); 2376 2377 return rv; 2378 } 2379 2380 /** 2381 * Returns an array containing all values of the given object. 2382 * 2383 * Returns null if no object was passed. 2384 * 2385 * @function module:core#values 2386 * 2387 * @param {*} obj 2388 * The object from which to extract values. 2389 * 2390 * @returns {?Array} 2391 * 2392 * @example 2393 * values({ foo: true, bar: false }); // [true, false] 2394 */ 2395 static uc_value_t * 2396 uc_values(uc_vm_t *vm, size_t nargs) 2397 { 2398 uc_value_t *obj = uc_fn_arg(0); 2399 uc_value_t *arr; 2400 2401 if (ucv_type(obj) != UC_OBJECT) 2402 return NULL; 2403 2404 arr = ucv_array_new(vm); 2405 2406 ucv_object_foreach(obj, key, val) { 2407 (void)key; 2408 ucv_array_push(arr, ucv_get(val)); 2409 } 2410 2411 return arr; 2412 } 2413 2414 static uc_value_t * 2415 uc_trim_common(uc_vm_t *vm, size_t nargs, bool start, bool end) 2416 { 2417 uc_value_t *str = uc_fn_arg(0); 2418 uc_value_t *chr = uc_fn_arg(1); 2419 const char *o, *p, *c; 2420 size_t olen, len; 2421 2422 if (ucv_type(str) != UC_STRING || 2423 (chr != NULL && ucv_type(chr) != UC_STRING)) 2424 return NULL; 2425 2426 c = ucv_string_get(chr); 2427 c = c ? c : " \t\r\n"; 2428 2429 o = p = ucv_string_get(str); 2430 olen = len = ucv_string_length(str); 2431 2432 if (start) { 2433 while (*p) { 2434 if (!strchr(c, *p)) 2435 break; 2436 2437 p++; 2438 len--; 2439 } 2440 } 2441 2442 if (end) { 2443 while (len > 0) { 2444 if (!strchr(c, p[len - 1])) 2445 break; 2446 2447 len--; 2448 } 2449 } 2450 2451 if (o == p && olen == len) 2452 return ucv_get(str); 2453 2454 return ucv_string_new_length(p, len); 2455 } 2456 2457 /** 2458 * Trim any of the specified characters in `c` from the start and end of `str`. 2459 * If the second argument is omitted, trims the characters, ` ` (space), `\t`, 2460 * `\r`, and `\n`. 2461 * 2462 * Returns the trimmed string. 2463 * 2464 * @function module:core#trim 2465 * 2466 * @param {string} str 2467 * The string to be trimmed. 2468 * 2469 * @param {string} [c] 2470 * The characters to be trimmed from the start and end of the string. 2471 * 2472 * @returns {string} 2473 */ 2474 static uc_value_t * 2475 uc_trim(uc_vm_t *vm, size_t nargs) 2476 { 2477 return uc_trim_common(vm, nargs, true, true); 2478 } 2479 2480 /** 2481 * Trim any of the specified characters from the start of the string. 2482 * If the second argument is omitted, trims the characters ` ` (space), '\t', 2483 * '\r', and '\n'. 2484 * 2485 * Returns the left trimmed string. 2486 * 2487 * @function module:core#ltrim 2488 * 2489 * @param {string} s 2490 * The input string. 2491 * 2492 * @param {string} [c] 2493 * The characters to trim. 2494 * 2495 * @returns {string} 2496 * 2497 * @example 2498 * ltrim(" foo \n") // "foo \n" 2499 * ltrim("--bar--", "-") // "bar--" 2500 */ 2501 static uc_value_t * 2502 uc_ltrim(uc_vm_t *vm, size_t nargs) 2503 { 2504 return uc_trim_common(vm, nargs, true, false); 2505 } 2506 2507 /** 2508 * Trim any of the specified characters from the end of the string. 2509 * If the second argument is omitted, trims the characters ` ` (space), '\t', 2510 * '\r', and '\n'. 2511 * 2512 * Returns the right trimmed string. 2513 * 2514 * @function module:core#rtrim 2515 * 2516 * @param {string} str 2517 * The input string. 2518 * 2519 * @param {string} [c] 2520 * The characters to trim. 2521 * 2522 * @returns {string} 2523 * 2524 * @example 2525 * rtrim(" foo \n") // " foo" 2526 * rtrim("--bar--", "-") // "--bar" 2527 */ 2528 static uc_value_t * 2529 uc_rtrim(uc_vm_t *vm, size_t nargs) 2530 { 2531 return uc_trim_common(vm, nargs, false, true); 2532 } 2533 2534 enum { 2535 FMT_F_ALT = (1 << 0), 2536 FMT_F_ZERO = (1 << 1), 2537 FMT_F_LEFT = (1 << 2), 2538 FMT_F_SPACE = (1 << 3), 2539 FMT_F_SIGN = (1 << 4), 2540 FMT_F_WIDTH = (1 << 5), 2541 FMT_F_PREC = (1 << 6), 2542 }; 2543 2544 enum { 2545 FMT_C_NONE = (1 << 0), 2546 FMT_C_INT = (1 << 1), 2547 FMT_C_UINT = (1 << 2), 2548 FMT_C_DBL = (1 << 3), 2549 FMT_C_CHR = (1 << 4), 2550 FMT_C_STR = (1 << 5), 2551 FMT_C_JSON = (1 << 6), 2552 }; 2553 2554 static void 2555 uc_printf_common(uc_vm_t *vm, size_t nargs, uc_stringbuf_t *buf) 2556 { 2557 char *s, sfmt[sizeof("%#0- +0123456789.0123456789%")]; 2558 uint32_t conv, flags, width, precision; 2559 uc_value_t *fmt = uc_fn_arg(0), *arg; 2560 const char *fstr, *last, *p, *cfmt; 2561 size_t argidx = 1, argpos, sfmtlen; 2562 uint64_t u; 2563 int64_t n; 2564 double d; 2565 2566 if (ucv_type(fmt) == UC_STRING) 2567 fstr = ucv_string_get(fmt); 2568 else 2569 fstr = ""; 2570 2571 for (last = p = fstr; *p; p++) { 2572 if (*p == '%') { 2573 ucv_stringbuf_addstr(buf, last, p - last); 2574 2575 last = p++; 2576 2577 flags = 0; 2578 width = 0; 2579 precision = 0; 2580 2581 argpos = argidx; 2582 2583 if (*p >= '1' && *p <= '9') { 2584 while (isdigit(*p)) 2585 width = width * 10 + (*p++ - ''); 2586 2587 /* if a dollar sign follows, this is an argument index */ 2588 if (*p == '$') { 2589 argpos = width; 2590 width = 0; 2591 p++; 2592 } 2593 2594 /* otherwise skip to parsing precision, flags can't possibly follow */ 2595 else { 2596 flags |= FMT_F_WIDTH; 2597 goto parse_precision; 2598 } 2599 } 2600 2601 while (*p != '\0' && strchr("#0- +", *p)) { 2602 switch (*p++) { 2603 case '#': flags |= FMT_F_ALT; break; 2604 case '': flags |= FMT_F_ZERO; break; 2605 case '-': flags |= FMT_F_LEFT; break; 2606 case ' ': flags |= FMT_F_SPACE; break; 2607 case '+': flags |= FMT_F_SIGN; break; 2608 } 2609 } 2610 2611 if (*p >= '1' && *p <= '9') { 2612 while (isdigit(*p)) 2613 width = width * 10 + (*p++ - ''); 2614 2615 flags |= FMT_F_WIDTH; 2616 } 2617 2618 parse_precision: 2619 if (*p == '.') { 2620 p++; 2621 2622 if (*p == '-') { 2623 p++; 2624 2625 while (isdigit(*p)) 2626 p++; 2627 } 2628 else { 2629 while (isdigit(*p)) 2630 precision = precision * 10 + (*p++ - ''); 2631 } 2632 2633 flags |= FMT_F_PREC; 2634 } 2635 2636 switch (*p) { 2637 case 'd': 2638 case 'i': 2639 conv = FMT_C_INT; 2640 flags &= ~FMT_F_PREC; 2641 cfmt = PRId64; 2642 break; 2643 2644 case 'o': 2645 conv = FMT_C_UINT; 2646 flags &= ~FMT_F_PREC; 2647 cfmt = PRIo64; 2648 break; 2649 2650 case 'u': 2651 conv = FMT_C_UINT; 2652 flags &= ~FMT_F_PREC; 2653 cfmt = PRIu64; 2654 break; 2655 2656 case 'x': 2657 conv = FMT_C_UINT; 2658 flags &= ~FMT_F_PREC; 2659 cfmt = PRIx64; 2660 break; 2661 2662 case 'X': 2663 conv = FMT_C_UINT; 2664 flags &= ~FMT_F_PREC; 2665 cfmt = PRIX64; 2666 break; 2667 2668 case 'e': 2669 conv = FMT_C_DBL; 2670 cfmt = "e"; 2671 break; 2672 2673 case 'E': 2674 conv = FMT_C_DBL; 2675 cfmt = "E"; 2676 break; 2677 2678 case 'f': 2679 conv = FMT_C_DBL; 2680 cfmt = "f"; 2681 break; 2682 2683 case 'F': 2684 conv = FMT_C_DBL; 2685 cfmt = "F"; 2686 break; 2687 2688 case 'g': 2689 conv = FMT_C_DBL; 2690 cfmt = "g"; 2691 break; 2692 2693 case 'G': 2694 conv = FMT_C_DBL; 2695 cfmt = "G"; 2696 break; 2697 2698 case 'c': 2699 conv = FMT_C_CHR; 2700 flags &= ~FMT_F_PREC; 2701 cfmt = "c"; 2702 break; 2703 2704 case 's': 2705 conv = FMT_C_STR; 2706 flags &= ~FMT_F_ZERO; 2707 cfmt = "s"; 2708 break; 2709 2710 case 'J': 2711 conv = FMT_C_JSON; 2712 2713 if (flags & FMT_F_PREC) { 2714 flags &= ~FMT_F_PREC; 2715 precision++; 2716 } 2717 2718 cfmt = "s"; 2719 break; 2720 2721 case '%': 2722 conv = FMT_C_NONE; 2723 flags = 0; 2724 cfmt = "%"; 2725 break; 2726 2727 case '\0': 2728 p--; 2729 /* fall through */ 2730 2731 default: 2732 continue; 2733 } 2734 2735 sfmtlen = 0; 2736 sfmt[sfmtlen++] = '%'; 2737 2738 if (flags & FMT_F_ALT) sfmt[sfmtlen++] = '#'; 2739 if (flags & FMT_F_ZERO) sfmt[sfmtlen++] = ''; 2740 if (flags & FMT_F_LEFT) sfmt[sfmtlen++] = '-'; 2741 if (flags & FMT_F_SPACE) sfmt[sfmtlen++] = ' '; 2742 if (flags & FMT_F_SIGN) sfmt[sfmtlen++] = '+'; 2743 2744 if (flags & FMT_F_WIDTH) 2745 sfmtlen += snprintf(&sfmt[sfmtlen], sizeof(sfmt) - sfmtlen, "%" PRIu32, width); 2746 2747 if (flags & FMT_F_PREC) 2748 sfmtlen += snprintf(&sfmt[sfmtlen], sizeof(sfmt) - sfmtlen, ".%" PRIu32, precision); 2749 2750 snprintf(&sfmt[sfmtlen], sizeof(sfmt) - sfmtlen, "%s", cfmt); 2751 2752 switch (conv) { 2753 case FMT_C_NONE: 2754 ucv_stringbuf_addstr(buf, cfmt, strlen(cfmt)); 2755 break; 2756 2757 case FMT_C_INT: 2758 argidx++; 2759 arg = uc_fn_arg(argpos); 2760 n = ucv_to_integer(arg); 2761 2762 if (errno == ERANGE) 2763 n = (int64_t)ucv_to_unsigned(arg); 2764 2765 ucv_stringbuf_printf(buf, sfmt, n); 2766 break; 2767 2768 case FMT_C_UINT: 2769 argidx++; 2770 arg = uc_fn_arg(argpos); 2771 u = ucv_to_unsigned(arg); 2772 2773 if (errno == ERANGE) 2774 u = (uint64_t)ucv_to_integer(arg); 2775 2776 ucv_stringbuf_printf(buf, sfmt, u); 2777 break; 2778 2779 case FMT_C_DBL: 2780 argidx++; 2781 d = ucv_to_double(uc_fn_arg(argpos)); 2782 ucv_stringbuf_printf(buf, sfmt, d); 2783 break; 2784 2785 case FMT_C_CHR: 2786 argidx++; 2787 n = ucv_to_integer(uc_fn_arg(argpos)); 2788 ucv_stringbuf_printf(buf, sfmt, (int)n); 2789 break; 2790 2791 case FMT_C_STR: 2792 argidx++; 2793 arg = uc_fn_arg(argpos); 2794 2795 switch (ucv_type(arg)) { 2796 case UC_STRING: 2797 ucv_stringbuf_printf(buf, sfmt, ucv_string_get(arg)); 2798 break; 2799 2800 case UC_NULL: 2801 ucv_stringbuf_append(buf, "(null)"); 2802 break; 2803 2804 default: 2805 s = ucv_to_string(vm, arg); 2806 ucv_stringbuf_printf(buf, sfmt, s ? s : "(null)"); 2807 free(s); 2808 } 2809 2810 break; 2811 2812 case FMT_C_JSON: 2813 argidx++; 2814 s = ucv_to_jsonstring_formatted(vm, 2815 uc_fn_arg(argpos), 2816 precision > 0 ? (precision > 1 ? ' ' : '\t') : '\0', 2817 precision > 0 ? (precision > 1 ? precision - 1 : 1) : 0); 2818 2819 ucv_stringbuf_printf(buf, sfmt, s ? s : "null"); 2820 free(s); 2821 break; 2822 } 2823 2824 last = p + 1; 2825 } 2826 } 2827 2828 ucv_stringbuf_addstr(buf, last, p - last); 2829 } 2830 2831 /** 2832 * Formats the given arguments according to the given format string. 2833 * 2834 * See `printf()` for details. 2835 * 2836 * Returns the formatted string. 2837 * 2838 * @function module:core#sprintf 2839 * 2840 * @param {string} fmt 2841 * The format string. 2842 * 2843 * @param {...*} 2844 * Arguments to be formatted. 2845 * 2846 * @returns {string} 2847 * 2848 * @example 2849 * sprintf("Hello %s", "world"); // "Hello world" 2850 * sprintf("%08x", 123); // "0000007b" 2851 * sprintf("%c%c%c", 65, 98, 99); // "Abc" 2852 * sprintf("%g", 10 / 3.0); // "3.33333" 2853 * sprintf("%2$d %1$d", 12, 34); // "34 12" 2854 * sprintf("%J", [1,2,3]); // "[1,2,3]" 2855 */ 2856 static uc_value_t * 2857 uc_sprintf(uc_vm_t *vm, size_t nargs) 2858 { 2859 uc_stringbuf_t *buf = ucv_stringbuf_new(); 2860 2861 uc_printf_common(vm, nargs, buf); 2862 2863 return ucv_stringbuf_finish(buf); 2864 } 2865 2866 /** 2867 * Formats the given arguments according to the given format string and outputs 2868 * the result to stdout. 2869 * 2870 * Ucode supports a restricted subset of the formats allowed by the underlying 2871 * libc's `printf()` implementation, namely it allows the `d`, `i`, `o`, `u`, 2872 * `x`, `X`, `e`, `E`, `f`, `F`, `g`, `G`, `c` and `s` conversions. 2873 * 2874 * Additionally, an ucode specific `J` format is implemented, which causes the 2875 * corresponding value to be formatted as JSON string. By prefixing the `J` 2876 * format letter with a precision specifier, the resulting JSON output will be 2877 * pretty printed. A precision of `0` will use tabs for indentation, any other 2878 * positive precision will use that many spaces for indentation while a negative 2879 * or omitted precision specifier will turn off pretty printing. 2880 * 2881 * Other format specifiers such as `n` or `z` are not accepted and returned 2882 * verbatim. Format specifiers including `*` directives are rejected as well. 2883 * 2884 * Returns the number of bytes written to the standard output. 2885 * 2886 * @function module:core#printf 2887 * 2888 * @param {string} fmt 2889 * The format string. 2890 * 2891 * @param {...*} 2892 * Arguments to be formatted. 2893 * 2894 * @returns {number} 2895 * 2896 * @example 2897 * {% 2898 * printf("Hello %s\n", "world"); // Hello world 2899 * printf("%08x\n", 123); // 0000007b 2900 * printf("%c%c%c\n", 65, 98, 99); // Abc 2901 * printf("%g\n", 10 / 3.0); // 3.33333 2902 * printf("%2$d %1$d\n", 12, 34); // 34 12 2903 * printf("%J", [1,2,3]); // [ 1, 2, 3 ] 2904 * 2905 * printf("%.J", [1,2,3]); 2906 * // [ 2907 * // 1, 2908 * // 2, 2909 * // 3 2910 * // ] 2911 * 2912 * printf("%.2J", [1,2,3]); 2913 * // [ 2914 * // 1, 2915 * // 2, 2916 * // 3 2917 * // ] 2918 * %} 2919 */ 2920 static uc_value_t * 2921 uc_printf(uc_vm_t *vm, size_t nargs) 2922 { 2923 uc_stringbuf_t *buf = xprintbuf_new(); 2924 size_t len; 2925 2926 uc_printf_common(vm, nargs, buf); 2927 2928 len = fwrite(buf->buf, 1, printbuf_length(buf), vm->output); 2929 2930 printbuf_free(buf); 2931 2932 return ucv_int64_new(len); 2933 } 2934 2935 static bool 2936 uc_require_so(uc_vm_t *vm, const char *path, uc_value_t **res) 2937 { 2938 void (*init)(uc_vm_t *, uc_value_t *); 2939 uc_value_t *scope; 2940 struct stat st; 2941 void *dlh; 2942 2943 if (stat(path, &st)) 2944 return false; 2945 2946 dlerror(); 2947 dlh = dlopen(path, RTLD_LAZY|RTLD_LOCAL); 2948 2949 if (!dlh) { 2950 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 2951 "Unable to dlopen file '%s': %s", path, dlerror()); 2952 2953 return true; 2954 } 2955 2956 *(void **)(&init) = dlsym(dlh, "uc_module_entry"); 2957 2958 if (!init) { 2959 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 2960 "Module '%s' provides no 'uc_module_entry' function", path); 2961 2962 return true; 2963 } 2964 2965 scope = ucv_object_new(vm); 2966 2967 init(vm, scope); 2968 2969 *res = scope; 2970 2971 return true; 2972 } 2973 2974 static uc_value_t * 2975 uc_loadfile(uc_vm_t *vm, size_t nargs); 2976 2977 static uc_value_t * 2978 uc_callfunc(uc_vm_t *vm, size_t nargs); 2979 2980 static uc_value_t * 2981 uc_require_imports(uc_vm_t *vm, uc_value_t *closure) 2982 { 2983 uc_function_t *fn = ucv_as_closure(closure)->function; 2984 uc_source_t *src = uc_program_function_source(fn); 2985 uc_export_instance_t *instance = 2986 uc_program_instance_get(fn->program, ucv_as_closure(closure), false); 2987 uc_value_t *ns = ucv_object_new(vm); 2988 size_t own = 0, i = 0; 2989 2990 /* The module exports its own symbols last, after those of the modules 2991 * that it links. A precompiled module does not record their offset. */ 2992 uc_vector_foreach(&src->exports, sym) 2993 if (ucv_type(*sym) == UC_STRING || ucv_type(*sym) == UC_NULL) 2994 own++; 2995 2996 if (instance && instance->exports.count > own) 2997 i = instance->exports.count - own; 2998 2999 uc_vector_foreach(&src->exports, sym) { 3000 if (!instance || i >= instance->exports.count) 3001 break; 3002 3003 if (ucv_type(*sym) == UC_STRING) 3004 ucv_object_add(ns, ucv_string_get(*sym), 3005 ucv_get(&instance->exports.entries[i++]->header)); 3006 else if (ucv_type(*sym) == UC_NULL) 3007 ucv_object_add(ns, "default", 3008 ucv_get(&instance->exports.entries[i++]->header)); 3009 } 3010 3011 ucv_set_constant(ns, true); 3012 3013 return ns; 3014 } 3015 3016 static bool 3017 uc_require_ucode(uc_vm_t *vm, const char *path, uc_value_t *scope, uc_value_t **res, bool raw_mode, bool module_mode) 3018 { 3019 uc_parse_config_t config = *vm->config, *prev_config = vm->config; 3020 uc_value_t *closure; 3021 struct stat st; 3022 3023 if (stat(path, &st)) 3024 return false; 3025 3026 config.raw_mode = raw_mode; 3027 config.compile_module = module_mode; 3028 vm->config = &config; 3029 3030 uc_vm_stack_push(vm, ucv_string_new(path)); 3031 3032 closure = uc_loadfile(vm, 1); 3033 3034 /* the module body runs with this configuration; a file that it loads is 3035 * not a module */ 3036 config.compile_module = prev_config->compile_module; 3037 3038 ucv_put(uc_vm_stack_pop(vm)); 3039 3040 if (closure) { 3041 uc_vm_stack_push(vm, closure); 3042 uc_vm_stack_push(vm, NULL); 3043 uc_vm_stack_push(vm, scope); 3044 3045 *res = uc_callfunc(vm, 3); 3046 3047 if (vm->exception.type != EXCEPTION_EXIT) { 3048 if (module_mode) { 3049 ucv_put(*res); 3050 *res = uc_require_imports(vm, closure); 3051 } 3052 3053 if (vm->stack.count >= 3) { 3054 uc_vm_stack_pop(vm); 3055 uc_vm_stack_pop(vm); 3056 uc_vm_stack_pop(vm); 3057 ucv_put(closure); 3058 } 3059 } 3060 } 3061 3062 vm->config = prev_config; 3063 3064 return true; 3065 } 3066 3067 static bool 3068 uc_require_path(uc_vm_t *vm, const char *path_template, const char *name, 3069 uc_value_t **res, bool module_mode) 3070 { 3071 uc_stringbuf_t *buf = xprintbuf_new(); 3072 const char *p, *q, *last; 3073 uc_value_t *modtable; 3074 bool rv; 3075 3076 modtable = ucv_property_get(uc_vm_scope_get(vm), "modules"); 3077 *res = ucv_get(ucv_object_get(modtable, name, &rv)); 3078 3079 if (rv) 3080 goto out; 3081 3082 p = strchr(path_template, '*'); 3083 3084 if (!p) 3085 goto out; 3086 3087 ucv_stringbuf_addstr(buf, path_template, p - path_template); 3088 3089 for (q = last = name;; q++) { 3090 if (*q == '.' || *q == '\0') { 3091 ucv_stringbuf_addstr(buf, last, q - last); 3092 3093 if (*q) 3094 ucv_stringbuf_append(buf, "/"); 3095 else 3096 ucv_stringbuf_addstr(buf, p + 1, strlen(p + 1)); 3097 3098 if (*q == '\0') 3099 break; 3100 3101 last = q + 1; 3102 } 3103 else if (!isalnum(*q) && *q != '_') { 3104 goto out; 3105 } 3106 } 3107 3108 if (!strcmp(p + 1, ".so")) 3109 rv = uc_require_so(vm, buf->buf, res); 3110 else if (!strcmp(p + 1, ".uc")) 3111 rv = uc_require_ucode(vm, buf->buf, NULL, res, true, module_mode); 3112 3113 if (rv && vm->exception.type == EXCEPTION_NONE) 3114 ucv_object_add(modtable, name, ucv_get(*res)); 3115 3116 out: 3117 printbuf_free(buf); 3118 3119 return rv; 3120 } 3121 3122 uc_value_t * 3123 uc_require_library(uc_vm_t *vm, uc_value_t *nameval, bool module_mode) 3124 { 3125 uc_value_t *search, *se, *res; 3126 size_t arridx, arrlen; 3127 const char *name; 3128 3129 if (ucv_type(nameval) != UC_STRING) 3130 return NULL; 3131 3132 name = ucv_string_get(nameval); 3133 search = ucv_property_get(uc_vm_scope_get(vm), "REQUIRE_SEARCH_PATH"); 3134 3135 if (ucv_type(search) != UC_ARRAY) { 3136 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 3137 "Global require search path not set"); 3138 3139 return NULL; 3140 } 3141 3142 for (arridx = 0, arrlen = ucv_array_length(search); arridx < arrlen; arridx++) { 3143 se = ucv_array_get(search, arridx); 3144 3145 if (ucv_type(se) != UC_STRING) 3146 continue; 3147 3148 if (uc_require_path(vm, ucv_string_get(se), name, &res, module_mode)) 3149 return res; 3150 } 3151 3152 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 3153 "No module named '%s' could be found", name); 3154 3155 return NULL; 3156 } 3157 3158 /** 3159 * Load and evaluate ucode scripts or shared library extensions. 3160 * 3161 * The `require()` function expands each member of the global 3162 * `REQUIRE_SEARCH_PATH` array to a filesystem path by replacing the `*` 3163 * placeholder with a slash-separated version of the given dotted module name 3164 * and subsequently tries to load a file at the resulting location. 3165 * 3166 * If a file is found at one of the search path locations, it is compiled and 3167 * evaluated or loaded via the C runtime's `dlopen()` function, depending on 3168 * whether the found file is a ucode script or a compiled dynamic library. 3169 * 3170 * The resulting program function of the compiled/loaded module is then 3171 * subsequently executed with the current global environment, without a `this` 3172 * context and without arguments. 3173 * 3174 * Finally, the return value of the invoked program function is returned back 3175 * by `require()` to the caller. 3176 * 3177 * By default, modules are cached in the global `modules` dictionary and 3178 * subsequent attempts to require the same module will return the cached module 3179 * dictionary entry without re-evaluating the module. 3180 * 3181 * To force reloading a module, the corresponding entry from the global 3182 * `modules` dictionary can be deleted. 3183 * 3184 * To preload a module or to provide a "virtual" module without a corresponding 3185 * filesystem resource, an entry can be manually added to the global `modules` 3186 * dictionary. 3187 * 3188 * Summarized, the `require()` function can be roughly described by the 3189 * following code: 3190 * 3191 * ``` 3192 * function require(name) { 3193 * if (exists(modules, name)) 3194 * return modules[name]; 3195 * 3196 * for (const item in REQUIRE_SEARCH_PATH) { 3197 * const modpath = replace(item, '*', replace(name, '.', '/')); 3198 * const entryfunc = loadfile(modpath, { raw_mode: true }); 3199 * 3200 * if (entryfunc) { 3201 * const modval = entryfunc(); 3202 * modules[name] = modval; 3203 * 3204 * return modval; 3205 * } 3206 * } 3207 * 3208 * die(`Module ${name} not found`); 3209 * } 3210 * ``` 3211 * 3212 * Due to the fact that `require()` is a runtime operation, module source code 3213 * is only lazily evaluated/loaded upon invoking the first require invocation, 3214 * which might lead to situations where errors in module sources are only 3215 * reported much later throughout the program execution. Unless runtime loading 3216 * of modules is absolutely required, e.g. to conditionally load extensions, the 3217 * compile time 3218 * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import|`import` syntax} 3219 * should be preferred. 3220 * 3221 * Returns the module value (typically an object) on success. 3222 * 3223 * Throws an exception if the module function threw an exception. 3224 * 3225 * Throws an exception if no matching module could be found, if the module 3226 * contains syntax errors or upon other I/O related problems. 3227 * 3228 * @function module:core#require 3229 * 3230 * @param {string} name 3231 * The name of the module to require in dotted notation. 3232 * 3233 * @returns {*} 3234 * 3235 * @example 3236 * // Require the `example/acme.uc` or `example/acme.so` module 3237 * const acme = require('example.acme'); 3238 * 3239 * // Requiring the same name again will yield the cached instance 3240 * const acme2 = require('example.acme'); 3241 * assert(acme === acme2); 3242 * 3243 * // Deleting the module dictionary entry will force a reload 3244 * delete modules['example.acme']; 3245 * const acme3 = require('example.acme'); 3246 * assert(acme !== acme3); 3247 * 3248 * // Preloading a "virtual" module 3249 * modules['example.test'] = { 3250 * hello: function() { print("This is the example module\n"); } 3251 * }; 3252 * 3253 * const test = require('example.test'); 3254 * test.hello(); // will print "This is the example module" 3255 */ 3256 static uc_value_t * 3257 uc_require(uc_vm_t *vm, size_t nargs) 3258 { 3259 return uc_require_library(vm, uc_fn_arg(0), false); 3260 } 3261 3262 /** 3263 * Convert the given IP address string to an array of byte values. 3264 * 3265 * IPv4 addresses result in arrays of 4 integers while IPv6 ones in arrays 3266 * containing 16 integers. The resulting array can be turned back into IP 3267 * address strings using the inverse `arrtoip()` function. 3268 * 3269 * Returns an array containing the address byte values. 3270 * Returns `null` if the given argument is not a string or an invalid IP. 3271 * 3272 * @function module:core#iptoarr 3273 * 3274 * @param {string} address 3275 * The IP address string to convert. 3276 * 3277 * @returns {?number[]} 3278 * 3279 * @example 3280 * iptoarr("192.168.1.1") // [ 192, 168, 1, 1 ] 3281 * iptoarr("fe80::fc54:ff:fe82:abbd") // [ 254, 128, 0, 0, 0, 0, 0, 0, 252, 84, 3282 * // 0, 255, 254, 130, 171, 189 ]) 3283 * iptoarr("foo") // null (invalid address) 3284 * iptoarr(123) // null (not a string) 3285 */ 3286 static uc_value_t * 3287 uc_iptoarr(uc_vm_t *vm, size_t nargs) 3288 { 3289 uc_value_t *ip = uc_fn_arg(0); 3290 uc_value_t *res; 3291 union { 3292 uint8_t u8[4]; 3293 struct in_addr in; 3294 struct in6_addr in6; 3295 } a; 3296 int i; 3297 3298 if (ucv_type(ip) != UC_STRING) 3299 return NULL; 3300 3301 if (inet_pton(AF_INET6, ucv_string_get(ip), &a)) { 3302 res = ucv_array_new(vm); 3303 3304 for (i = 0; i < 16; i++) 3305 ucv_array_push(res, ucv_int64_new(a.in6.s6_addr[i])); 3306 3307 return res; 3308 } 3309 else if (inet_pton(AF_INET, ucv_string_get(ip), &a)) { 3310 res = ucv_array_new(vm); 3311 3312 ucv_array_push(res, ucv_int64_new(a.u8[0])); 3313 ucv_array_push(res, ucv_int64_new(a.u8[1])); 3314 ucv_array_push(res, ucv_int64_new(a.u8[2])); 3315 ucv_array_push(res, ucv_int64_new(a.u8[3])); 3316 3317 return res; 3318 } 3319 3320 return NULL; 3321 } 3322 3323 static int 3324 check_byte(uc_value_t *v) 3325 { 3326 int n; 3327 3328 if (ucv_type(v) != UC_INTEGER) 3329 return -1; 3330 3331 n = ucv_int64_get(v); 3332 3333 if (n < 0 || n > 255) 3334 return -1; 3335 3336 return n; 3337 } 3338 3339 /** 3340 * Convert the given input array of byte values to an IP address string. 3341 * 3342 * Input arrays of length 4 are converted to IPv4 addresses, arrays of length 16 3343 * to IPv6 ones. All other lengths are rejected. If any array element is not an 3344 * integer or exceeds the range 0..255 (inclusive), the array is rejected. 3345 * 3346 * Returns a string containing the formatted IP address. 3347 * Returns `null` if the input array was invalid. 3348 * 3349 * @function module:core#arrtoip 3350 * 3351 * @param {number[]} arr 3352 * The byte array to convert into an IP address string. 3353 * 3354 * @returns {?string} 3355 * 3356 * @example 3357 * arrtoip([ 192, 168, 1, 1 ]) // "192.168.1.1" 3358 * arrtoip([ 254, 128, 0, 0, 0, 0, 0, 0, 252, 84, 0, 255, 254, 130, 171, 189 ]) 3359 * // "fe80::fc54:ff:fe82:abbd" 3360 * arrtoip([ 1, 2, 3]) // null (invalid length) 3361 * arrtoip([ 1, "2", -5, 300 ]) // null (invalid values) 3362 * arrtoip("123") // null (not an array) 3363 */ 3364 static uc_value_t * 3365 uc_arrtoip(uc_vm_t *vm, size_t nargs) 3366 { 3367 uc_value_t *arr = uc_fn_arg(0); 3368 union { 3369 uint8_t u8[4]; 3370 struct in6_addr in6; 3371 } a; 3372 char buf[INET6_ADDRSTRLEN]; 3373 int i, n; 3374 3375 if (ucv_type(arr) != UC_ARRAY) 3376 return NULL; 3377 3378 switch (ucv_array_length(arr)) { 3379 case 4: 3380 for (i = 0; i < 4; i++) { 3381 n = check_byte(ucv_array_get(arr, i)); 3382 3383 if (n < 0) 3384 return NULL; 3385 3386 a.u8[i] = n; 3387 } 3388 3389 inet_ntop(AF_INET, &a, buf, sizeof(buf)); 3390 3391 return ucv_string_new(buf); 3392 3393 case 16: 3394 for (i = 0; i < 16; i++) { 3395 n = check_byte(ucv_array_get(arr, i)); 3396 3397 if (n < 0) 3398 return NULL; 3399 3400 a.in6.s6_addr[i] = n; 3401 } 3402 3403 inet_ntop(AF_INET6, &a, buf, sizeof(buf)); 3404 3405 return ucv_string_new(buf); 3406 3407 default: 3408 return NULL; 3409 } 3410 } 3411 3412 /** 3413 * Match the given string against the regular expression pattern specified as 3414 * the second argument. 3415 * 3416 * If the passed regular expression uses the `g` flag, the return value will be 3417 * an array of arrays describing all found occurrences within the string. 3418 * 3419 * Without the `g` modifier, an array describing the first match is returned. 3420 * 3421 * Returns `null` if the pattern was not found within the given string. 3422 * 3423 * @function module:core#match 3424 * 3425 * @param {string} str 3426 * The string to be matched against the pattern. 3427 * 3428 * @param {RegExp} pattern 3429 * The regular expression pattern. 3430 * 3431 * @returns {?Array} 3432 * 3433 * @example 3434 * match("foobarbaz", /b.(.)/) // ["bar", "r"] 3435 * match("foobarbaz", /b.(.)/g) // [["bar", "r"], ["baz", "z"]] 3436 */ 3437 static uc_value_t * 3438 uc_match(uc_vm_t *vm, size_t nargs) 3439 { 3440 uc_value_t *subject = uc_fn_arg(0); 3441 uc_value_t *pattern = uc_fn_arg(1); 3442 uc_value_t *rv = NULL, *m; 3443 regmatch_t *pmatch = NULL; 3444 int eflags = 0, res; 3445 uc_regexp_t *re; 3446 bool freeable; 3447 char *str, *p; 3448 size_t i; 3449 3450 if (ucv_type(pattern) != UC_REGEXP || !subject) 3451 return NULL; 3452 3453 re = ucv_as_regexp(pattern); 3454 3455 pmatch = calloc(1 + re->regexp.re_nsub, sizeof(regmatch_t)); 3456 3457 if (!pmatch) 3458 return NULL; 3459 3460 str = p = uc_cast_string(vm, &subject, &freeable); 3461 3462 while (true) { 3463 res = regexec(&re->regexp, p, 1 + re->regexp.re_nsub, pmatch, eflags); 3464 3465 if (res == REG_NOMATCH) 3466 break; 3467 3468 m = ucv_array_new(vm); 3469 3470 for (i = 0; i < 1 + re->regexp.re_nsub; i++) { 3471 if (pmatch[i].rm_so != -1) 3472 ucv_array_push(m, 3473 ucv_string_new_length(p + pmatch[i].rm_so, 3474 pmatch[i].rm_eo - pmatch[i].rm_so)); 3475 else 3476 ucv_array_push(m, NULL); 3477 } 3478 3479 if (re->global) { 3480 if (!rv) 3481 rv = ucv_array_new(vm); 3482 3483 ucv_array_push(rv, m); 3484 3485 if (pmatch[0].rm_so != pmatch[0].rm_eo) 3486 p += pmatch[0].rm_eo; 3487 else if (*p) 3488 p++; 3489 else 3490 break; 3491 3492 eflags |= REG_NOTBOL; 3493 } 3494 else { 3495 rv = m; 3496 break; 3497 } 3498 } 3499 3500 free(pmatch); 3501 3502 if (freeable) 3503 free(str); 3504 3505 return rv; 3506 } 3507 3508 static void 3509 uc_replace_cb(uc_vm_t *vm, uc_value_t *func, 3510 const char *subject, regmatch_t *pmatch, size_t plen, 3511 uc_stringbuf_t *resbuf) 3512 { 3513 uc_value_t *rv; 3514 size_t i; 3515 3516 uc_vm_ctx_push(vm); 3517 uc_vm_stack_push(vm, ucv_get(func)); 3518 3519 for (i = 0; i < plen; i++) { 3520 if (pmatch[i].rm_so != -1) 3521 uc_vm_stack_push(vm, 3522 ucv_string_new_length(subject + pmatch[i].rm_so, 3523 pmatch[i].rm_eo - pmatch[i].rm_so)); 3524 else 3525 uc_vm_stack_push(vm, NULL); 3526 } 3527 3528 if (uc_vm_call(vm, true, i) == EXCEPTION_NONE) { 3529 rv = uc_vm_stack_pop(vm); 3530 3531 ucv_to_stringbuf(vm, resbuf, rv, false); 3532 3533 ucv_put(rv); 3534 } 3535 } 3536 3537 static void 3538 uc_replace_str(uc_vm_t *vm, uc_value_t *str, 3539 const char *subject, regmatch_t *pmatch, size_t plen, 3540 uc_stringbuf_t *resbuf) 3541 { 3542 bool esc = false; 3543 char *p, *r; 3544 uint8_t i; 3545 3546 for (p = r = ucv_to_string(vm, str); *p; p++) { 3547 if (esc) { 3548 switch (*p) { 3549 case '&': 3550 if (pmatch[0].rm_so != -1) 3551 ucv_stringbuf_addstr(resbuf, 3552 subject + pmatch[0].rm_so, 3553 pmatch[0].rm_eo - pmatch[0].rm_so); 3554 break; 3555 3556 case '`': 3557 if (pmatch[0].rm_so != -1) 3558 ucv_stringbuf_addstr(resbuf, subject, pmatch[0].rm_so); 3559 break; 3560 3561 case '\'': 3562 if (pmatch[0].rm_so != -1) 3563 ucv_stringbuf_addstr(resbuf, 3564 subject + pmatch[0].rm_eo, 3565 strlen(subject + pmatch[0].rm_eo)); 3566 break; 3567 3568 case '1': 3569 case '2': 3570 case '3': 3571 case '4': 3572 case '5': 3573 case '6': 3574 case '7': 3575 case '8': 3576 case '9': 3577 i = *p - ''; 3578 if (i < plen && pmatch[i].rm_so != -1) { 3579 ucv_stringbuf_addstr(resbuf, 3580 subject + pmatch[i].rm_so, 3581 pmatch[i].rm_eo - pmatch[i].rm_so); 3582 } 3583 else { 3584 ucv_stringbuf_append(resbuf, "$"); 3585 ucv_stringbuf_addstr(resbuf, p, 1); 3586 } 3587 break; 3588 3589 case '$': 3590 ucv_stringbuf_append(resbuf, "$"); 3591 break; 3592 3593 default: 3594 ucv_stringbuf_append(resbuf, "$"); 3595 ucv_stringbuf_addstr(resbuf, p, 1); 3596 } 3597 3598 esc = false; 3599 } 3600 else if (*p == '$') { 3601 esc = true; 3602 } 3603 else { 3604 ucv_stringbuf_addstr(resbuf, p, 1); 3605 } 3606 } 3607 3608 free(r); 3609 } 3610 3611 /** 3612 * Replace occurrences of the specified pattern in the string passed as the 3613 * first argument. 3614 * 3615 * - The pattern value may be either a regular expression or a plain string. 3616 * - The replace value may be a function which is invoked for each found pattern 3617 * or any other value which is converted into a plain string and used as 3618 * replacement. 3619 * - When an optional limit is specified, substitutions are performed only that 3620 * many times. 3621 * - If the pattern is a regular expression and not using the `g` flag, then 3622 * only the first occurrence in the string is replaced. 3623 * - If the `g` flag is used or if the pattern is not a regular expression, all 3624 * occurrences are replaced. 3625 * - If the replace value is a callback function, it is invoked with the found 3626 * substring as the first and any capture group values as subsequent 3627 * parameters. 3628 * - If the replace value is a string, specific substrings are substituted 3629 * before it is inserted into the result. 3630 * 3631 * Returns a new string with the pattern replaced. 3632 * 3633 * @function module:core#replace 3634 * 3635 * @param {string} str 3636 * The string in which to replace occurrences. 3637 * 3638 * @param {RegExp|string} pattern 3639 * The pattern to be replaced. 3640 * 3641 * @param {Function|string} replace 3642 * The replacement value. 3643 * 3644 * @param {number} [limit] 3645 * The optional limit of substitutions. 3646 * 3647 * @returns {string} 3648 * 3649 * @example 3650 * replace("barfoobaz", /(f)(o+)/g, "[$$|$`|$&|$'|$1|$2|$3]") // bar[$|bar|foo|baz|f|oo|$3]baz 3651 * replace("barfoobaz", /(f)(o+)/g, uc) // barFOObaz 3652 * replace("barfoobaz", "a", "X") // bXrfoobXz 3653 * replace("barfoobaz", /(.)(.)(.)/g, function(m, c1, c2, c3) { 3654 * return c3 + c2 + c1; 3655 * }) // raboofzab 3656 * replace("aaaaa", "a", "x", 3) // xxxaa 3657 * replace("foo bar baz", /[ao]/g, "x", 3) // fxx bxr baz 3658 */ 3659 static uc_value_t * 3660 uc_replace(uc_vm_t *vm, size_t nargs) 3661 { 3662 char *sb = NULL, *pt = NULL, *p, *l; 3663 uc_value_t *subject = uc_fn_arg(0); 3664 uc_value_t *pattern = uc_fn_arg(1); 3665 uc_value_t *replace = uc_fn_arg(2); 3666 uc_value_t *limitval = uc_fn_arg(3); 3667 bool sb_freeable, pt_freeable; 3668 regmatch_t *pmatch = NULL; 3669 size_t pl, nmatch, limit; 3670 uc_regexp_t *re = NULL; 3671 uc_stringbuf_t *resbuf; 3672 int eflags = 0, res; 3673 3674 if (!pattern || !subject || !replace) 3675 return NULL; 3676 3677 nmatch = 1; 3678 3679 if (ucv_type(pattern) == UC_REGEXP) { 3680 re = ucv_as_regexp(pattern); 3681 nmatch += re->regexp.re_nsub; 3682 } 3683 3684 pmatch = calloc(nmatch, sizeof(regmatch_t)); 3685 3686 if (!pmatch) 3687 return NULL; 3688 3689 sb = uc_cast_string(vm, &subject, &sb_freeable); 3690 resbuf = ucv_stringbuf_new(); 3691 limit = limitval ? ucv_uint64_get(limitval) : SIZE_MAX; 3692 3693 if (re) { 3694 p = sb; 3695 3696 while (limit > 0) { 3697 res = regexec(&re->regexp, p, nmatch, pmatch, eflags); 3698 3699 if (res == REG_NOMATCH) 3700 break; 3701 3702 ucv_stringbuf_addstr(resbuf, p, pmatch[0].rm_so); 3703 3704 if (ucv_is_callable(replace)) 3705 uc_replace_cb(vm, replace, p, pmatch, nmatch, resbuf); 3706 else 3707 uc_replace_str(vm, replace, p, pmatch, nmatch, resbuf); 3708 3709 if (pmatch[0].rm_so != pmatch[0].rm_eo) 3710 p += pmatch[0].rm_eo; 3711 else if (*p) 3712 ucv_stringbuf_addstr(resbuf, p++, 1); 3713 else 3714 break; 3715 3716 if (re->global) 3717 eflags |= REG_NOTBOL; 3718 else 3719 break; 3720 3721 limit--; 3722 } 3723 3724 ucv_stringbuf_addstr(resbuf, p, strlen(p)); 3725 } 3726 else { 3727 pt = uc_cast_string(vm, &pattern, &pt_freeable); 3728 pl = strlen(pt); 3729 3730 l = p = sb; 3731 3732 while (limit > 0) { 3733 if (pl == 0 || !strncmp(p, pt, pl)) { 3734 ucv_stringbuf_addstr(resbuf, l, p - l); 3735 3736 pmatch[0].rm_so = p - l; 3737 pmatch[0].rm_eo = pmatch[0].rm_so + pl; 3738 3739 if (ucv_is_callable(replace)) 3740 uc_replace_cb(vm, replace, l, pmatch, 1, resbuf); 3741 else 3742 uc_replace_str(vm, replace, l, pmatch, 1, resbuf); 3743 3744 if (pl) { 3745 l = p + pl; 3746 p += pl - 1; 3747 } 3748 else { 3749 l = p; 3750 } 3751 3752 limit--; 3753 } 3754 3755 if (!*p++) 3756 break; 3757 } 3758 3759 ucv_stringbuf_addstr(resbuf, l, strlen(l)); 3760 3761 if (pt_freeable) 3762 free(pt); 3763 } 3764 3765 free(pmatch); 3766 3767 if (sb_freeable) 3768 free(sb); 3769 3770 return ucv_stringbuf_finish(resbuf); 3771 } 3772 3773 static struct json_tokener * 3774 uc_json_from_object(uc_vm_t *vm, uc_value_t *obj, json_object **jso) 3775 { 3776 bool trail = false, eof = false; 3777 enum json_tokener_error err; 3778 struct json_tokener *tok = NULL; 3779 uc_value_t *rfn, *rbuf = NULL; 3780 uc_stringbuf_t *buf; 3781 3782 rfn = ucv_get(ucv_property_get(obj, "read")); 3783 3784 if (!ucv_is_callable(rfn)) { 3785 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 3786 "Input object does not implement read() method"); 3787 3788 goto out; 3789 } 3790 3791 tok = xjs_new_tokener(); 3792 3793 while (true) { 3794 uc_vm_stack_push(vm, ucv_get(obj)); 3795 uc_vm_stack_push(vm, ucv_get(rfn)); 3796 uc_vm_stack_push(vm, ucv_int64_new(1024)); 3797 3798 if (uc_vm_call(vm, true, 1) != EXCEPTION_NONE) 3799 goto fail; 3800 3801 rbuf = uc_vm_stack_pop(vm); 3802 3803 /* check EOF */ 3804 eof = (rbuf == NULL || (ucv_type(rbuf) == UC_STRING && ucv_string_length(rbuf) == 0)); 3805 3806 /* on EOF, stop parsing unless trailing garbage was detected which handled below */ 3807 if (eof && !trail) { 3808 /* Didn't parse a complete object yet, possibly a non-delimited atomic value 3809 such as `null`, `true` etc. - nudge parser by sending final zero byte. 3810 See json-c issue #681 <https://github.com/json-c/json-c/issues/681> */ 3811 if (json_tokener_get_error(tok) == json_tokener_continue) 3812 *jso = json_tokener_parse_ex(tok, "\0", 1); 3813 3814 break; 3815 } 3816 3817 if (trail || *jso) { 3818 uc_vm_raise_exception(vm, EXCEPTION_SYNTAX, 3819 "Trailing garbage after JSON data"); 3820 3821 goto fail; 3822 } 3823 3824 if (ucv_type(rbuf) != UC_STRING) { 3825 buf = xprintbuf_new(); 3826 ucv_to_stringbuf_formatted(vm, buf, rbuf, 0, '\0', 0); 3827 3828 *jso = json_tokener_parse_ex(tok, buf->buf, printbuf_length(buf)); 3829 3830 trail = (json_tokener_get_error(tok) == json_tokener_success && 3831 json_tokener_get_parse_end(tok) < (size_t)printbuf_length(buf)); 3832 3833 printbuf_free(buf); 3834 } 3835 else { 3836 *jso = json_tokener_parse_ex(tok, ucv_string_get(rbuf), ucv_string_length(rbuf)); 3837 3838 trail = (json_tokener_get_error(tok) == json_tokener_success && 3839 json_tokener_get_parse_end(tok) < ucv_string_length(rbuf)); 3840 } 3841 3842 ucv_put(rbuf); 3843 rbuf = NULL; 3844 3845 err = json_tokener_get_error(tok); 3846 3847 if (err != json_tokener_success && err != json_tokener_continue) 3848 break; 3849 } 3850 3851 goto out; 3852 3853 fail: 3854 json_tokener_free(tok); 3855 tok = NULL; 3856 3857 out: 3858 ucv_put(rfn); 3859 ucv_put(rbuf); 3860 3861 return tok; 3862 } 3863 3864 static struct json_tokener * 3865 uc_json_from_string(uc_vm_t *vm, uc_value_t *str, json_object **jso) 3866 { 3867 struct json_tokener *tok = xjs_new_tokener(); 3868 size_t i; 3869 char *p; 3870 3871 /* NB: the len + 1 here is intentional to pass the terminating \0 byte 3872 * to the json-c parser. This is required to work-around upstream 3873 * issue #681 <https://github.com/json-c/json-c/issues/681> */ 3874 *jso = json_tokener_parse_ex(tok, ucv_string_get(str), ucv_string_length(str) + 1); 3875 3876 if (json_tokener_get_error(tok) == json_tokener_success) { 3877 p = ucv_string_get(str); 3878 3879 for (i = json_tokener_get_parse_end(tok); i < ucv_string_length(str); i++) { 3880 if (!isspace(p[i])) { 3881 uc_vm_raise_exception(vm, EXCEPTION_SYNTAX, 3882 "Trailing garbage after JSON data"); 3883 3884 3885 json_tokener_free(tok); 3886 3887 return NULL; 3888 } 3889 } 3890 } 3891 3892 return tok; 3893 } 3894 3895 /** 3896 * Parse the given string or resource as JSON and return the resulting value. 3897 * 3898 * If the input argument is a plain string, it is directly parsed as JSON. 3899 * 3900 * If an array, object or resource value is given, this function will attempt to 3901 * invoke a `read()` method on it to read chunks of input text to incrementally 3902 * parse as JSON data. Reading will stop if the object's `read()` method returns 3903 * either `null` or an empty string. 3904 * 3905 * Throws an exception on parse errors, trailing garbage, or premature EOF. 3906 * 3907 * Returns the parsed JSON data. 3908 * 3909 * @function module:core#json 3910 * 3911 * @param {string} str_or_resource 3912 * The string or resource object to be parsed as JSON. 3913 * 3914 * @returns {*} 3915 * 3916 * @example 3917 * json('{"a":true, "b":123}') // { "a": true, "b": 123 } 3918 * json('[1,2,') // Throws an exception 3919 * 3920 * import { open } from 'fs'; 3921 * let fd = open('example.json', 'r'); 3922 * json(fd); // will keep invoking `fd.read()` until EOF and 3923 * // incrementally parse each read chunk. 3924 * 3925 * let x = proto( 3926 * [ '{"foo":', 'true, ', '"bar":', 'false}' ], 3927 * { read: function() { return shift(this) } } 3928 * ); 3929 * json(x); // will keep invoking `x.read()` until array 3930 * // is empty incrementally parse each piece 3931 * 3932 */ 3933 static uc_value_t * 3934 uc_json(uc_vm_t *vm, size_t nargs) 3935 { 3936 uc_value_t *rv = NULL, *src = uc_fn_arg(0); 3937 struct json_tokener *tok = NULL; 3938 enum json_tokener_error err; 3939 json_object *jso = NULL; 3940 3941 switch (ucv_type(src)) { 3942 case UC_STRING: 3943 tok = uc_json_from_string(vm, src, &jso); 3944 break; 3945 3946 case UC_RESOURCE: 3947 case UC_OBJECT: 3948 case UC_ARRAY: 3949 tok = uc_json_from_object(vm, src, &jso); 3950 break; 3951 3952 default: 3953 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 3954 "Passed value is neither a string nor an object"); 3955 } 3956 3957 if (!tok) 3958 goto out; 3959 3960 err = json_tokener_get_error(tok); 3961 3962 if (err == json_tokener_continue) { 3963 uc_vm_raise_exception(vm, EXCEPTION_SYNTAX, 3964 "Unexpected end of string in JSON data"); 3965 3966 goto out; 3967 } 3968 else if (err != json_tokener_success) { 3969 uc_vm_raise_exception(vm, EXCEPTION_SYNTAX, 3970 "Failed to parse JSON string: %s", 3971 json_tokener_error_desc(err)); 3972 3973 goto out; 3974 } 3975 3976 rv = ucv_from_json(vm, jso); 3977 3978 out: 3979 if (tok) 3980 json_tokener_free(tok); 3981 3982 json_object_put(jso); 3983 3984 return rv; 3985 } 3986 3987 static char * 3988 include_path(const char *curpath, const char *incpath) 3989 { 3990 const char *slash; 3991 char *dup, *res; 3992 int len; 3993 3994 if (*incpath == '/') 3995 return realpath(incpath, NULL); 3996 3997 slash = curpath ? strrchr(curpath, '/') : NULL; 3998 3999 if (slash) 4000 len = asprintf(&res, "%.*s/%s", (int)(slash - curpath), curpath, incpath); 4001 else 4002 len = asprintf(&res, "./%s", incpath); 4003 4004 if (len == -1) 4005 return NULL; 4006 4007 dup = realpath(res, NULL); 4008 4009 free(res); 4010 4011 return dup; 4012 } 4013 4014 static uc_value_t * 4015 uc_include_common(uc_vm_t *vm, size_t nargs, bool raw_mode) 4016 { 4017 uc_value_t *path = uc_fn_arg(0); 4018 uc_value_t *scope = uc_fn_arg(1); 4019 uc_value_t *rv = NULL, *sc = NULL; 4020 uc_closure_t *closure = NULL; 4021 size_t i; 4022 char *p; 4023 4024 if (ucv_type(path) != UC_STRING) { 4025 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4026 "Passed filename is not a string"); 4027 4028 return NULL; 4029 } 4030 4031 if (scope && ucv_type(scope) != UC_OBJECT) { 4032 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4033 "Passed scope value is not an object"); 4034 4035 return NULL; 4036 } 4037 4038 /* find calling closure */ 4039 for (i = vm->callframes.count; i > 0; i--) { 4040 closure = vm->callframes.entries[i - 1].closure; 4041 4042 if (closure) 4043 break; 4044 } 4045 4046 if (!closure) 4047 return NULL; 4048 4049 p = include_path(uc_program_function_source(closure->function)->runpath, ucv_string_get(path)); 4050 4051 if (!p) { 4052 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 4053 "Include file not found"); 4054 4055 return NULL; 4056 } 4057 4058 if (ucv_prototype_get(scope)) { 4059 sc = ucv_get(scope); 4060 } 4061 else if (scope) { 4062 sc = ucv_object_new(vm); 4063 4064 ucv_object_foreach(scope, key, val) 4065 ucv_object_add(sc, key, ucv_get(val)); 4066 4067 ucv_prototype_set(sc, ucv_get(uc_vm_scope_get(vm))); 4068 } 4069 else { 4070 sc = ucv_get(uc_vm_scope_get(vm)); 4071 } 4072 4073 if (uc_require_ucode(vm, p, sc, &rv, raw_mode, false)) 4074 ucv_put(rv); 4075 4076 ucv_put(sc); 4077 free(p); 4078 4079 return NULL; 4080 } 4081 4082 /** 4083 * Evaluate and include the file at the given path and optionally override the 4084 * execution scope with the given scope object. 4085 * 4086 * By default, the file is executed within the same scope as the calling 4087 * `include()`, but by passing an object as the second argument, it is possible 4088 * to extend the scope available to the included file. 4089 * 4090 * This is useful to supply additional properties as global variables to the 4091 * included code. To sandbox included code, that is giving it only access to 4092 * explicitly provided properties, the `proto()` function can be used to create 4093 * a scope object with an empty prototype. 4094 * 4095 * @function module:core#include 4096 * 4097 * @param {string} path 4098 * The path to the file to be included. 4099 * 4100 * @param {Object} [scope] 4101 * The optional scope object to override the execution scope. 4102 * 4103 * @example 4104 * // Load and execute "foo.uc" immediately 4105 * include("./foo.uc") 4106 * 4107 * // Execute the "supplemental.ucode" in an extended scope and make the "foo" 4108 * // and "bar" properties available as global variables 4109 * include("./supplemental.uc", { 4110 * foo: true, 4111 * bar: 123 4112 * }) 4113 * 4114 * // Execute the "untrusted.ucode" in a sandboxed scope and make the "foo" and 4115 * // "bar" variables as well as the "print" function available to it. 4116 * // By assigning an empty prototype object to the scope, included code has no 4117 * // access to other global values anymore. 4118 * include("./untrusted.uc", proto({ 4119 * foo: true, 4120 * bar: 123, 4121 * print: print 4122 * }, {})) 4123 */ 4124 static uc_value_t * 4125 uc_include(uc_vm_t *vm, size_t nargs) 4126 { 4127 return uc_include_common(vm, nargs, vm->config && vm->config->raw_mode); 4128 } 4129 4130 /** 4131 * When invoked with a string value as the first argument, the function acts 4132 * like `include()` but captures the output of the included file as a string and 4133 * returns the captured contents. 4134 * 4135 * The second argument is treated as the scope. 4136 * 4137 * When invoked with a function value as the first argument, `render()` calls 4138 * the given function and passes all subsequent arguments to it. 4139 * 4140 * Any output produced by the called function is captured and returned as a 4141 * string. The return value of the called function is discarded. 4142 * 4143 * @function module:core#render 4144 * 4145 * @param {string|Function} path_or_func 4146 * The path to the file or the function to be rendered. 4147 * 4148 * @param {Object|*} [scope_or_fnarg1] 4149 * The optional scope or the first argument for the function. 4150 * 4151 * @param {*} [fnarg2] 4152 * The second argument for the function. 4153 * 4154 * @param {...*} [fnargN] 4155 * Additional arguments for the function. 4156 * 4157 * @returns {string} 4158 * 4159 * @example 4160 * // Renders template file with given scope and captures the output as a string 4161 * const output = render("./template.uc", { foo: "bar" }); 4162 * 4163 * // Calls a function, captures the output, and returns it as a string 4164 * const result = render(function(name) { 4165 * printf("Hello, %s!\n", name); 4166 * }, "Alice"); 4167 */ 4168 static uc_value_t * 4169 uc_render(uc_vm_t *vm, size_t nargs) 4170 { 4171 uc_string_t hdr = { .header = { .type = UC_STRING, .refcount = 1 } }; 4172 uc_string_t *ustr = NULL; 4173 FILE *mem, *prev; 4174 size_t len = 0; 4175 4176 mem = open_memstream((char **)&ustr, &len); 4177 4178 if (!mem) 4179 goto out; 4180 4181 /* reserve space for uc_string_t header... */ 4182 if (fwrite(&hdr, 1, sizeof(hdr), mem) != sizeof(hdr)) 4183 goto out; 4184 4185 /* divert VM output to memory fd */ 4186 prev = vm->output; 4187 vm->output = mem; 4188 4189 /* execute function */ 4190 if (ucv_is_callable(uc_fn_arg(0))) 4191 (void) uc_vm_call(vm, false, nargs - 1); 4192 4193 /* execute include */ 4194 else 4195 (void) uc_include_common(vm, nargs, false); 4196 4197 /* restore previous VM output */ 4198 vm->output = prev; 4199 fclose(mem); 4200 4201 /* update uc_string_t length */ 4202 ustr->length = len - sizeof(*ustr); 4203 4204 return &ustr->header; 4205 4206 out: 4207 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 4208 "Unable to initialize output memory: %s", 4209 strerror(errno)); 4210 4211 if (mem) 4212 fclose(mem); 4213 4214 free(ustr); 4215 4216 return NULL; 4217 } 4218 4219 /** 4220 * Print any of the given values to stderr. Arrays and objects are converted to 4221 * their JSON representation. 4222 * 4223 * Returns the amount of bytes printed. 4224 * 4225 * @function module:core#warn 4226 * 4227 * @param {...*} x 4228 * The values to be printed. 4229 * 4230 * @returns {number} 4231 * 4232 * @example 4233 * warn("Hello", "world"); // Print "Helloworld" to stderr 4234 * warn({ key: "value" }); // Print JSON representation of the object to stderr 4235 */ 4236 static uc_value_t * 4237 uc_warn(uc_vm_t *vm, size_t nargs) 4238 { 4239 return uc_print_common(vm, nargs, stderr); 4240 } 4241 4242 /** 4243 * Executes the given command, waits for completion, and returns the resulting 4244 * exit code. 4245 * 4246 * The command argument may be either a string, in which case it is passed to 4247 * `/bin/sh -c`, or an array, which is directly converted into an `execv()` 4248 * argument vector. 4249 * 4250 * - If the program terminated normally, a positive integer holding the 4251 * program's `exit()` code is returned. 4252 * - If the program was terminated by an uncaught signal, a negative signal 4253 * number is returned. 4254 * - If the optional timeout argument is specified, the program is terminated 4255 * by `SIGKILL` after that many milliseconds if it doesn't complete within 4256 * the timeout. 4257 * 4258 * Omitting the timeout argument or passing `0` disables the command timeout. 4259 * 4260 * Returns the program exit code. 4261 * 4262 * @function module:core#system 4263 * 4264 * @param {string|Array} command 4265 * The command to be executed. 4266 * 4267 * @param {number} [timeout] 4268 * The optional timeout in milliseconds. 4269 * 4270 * @returns {number} 4271 * 4272 * @example 4273 * // Execute through `/bin/sh` 4274 * // prints "Hello world" to stdout and returns 3 4275 * system("echo 'Hello world' && exit 3"); 4276 * 4277 * // Execute argument vector 4278 * // prints the UNIX timestamp to stdout and returns 0 4279 * system(["/usr/bin/date", "+%s"]); 4280 * 4281 * // Apply a timeout 4282 * // returns -9 4283 * system("sleep 3 && echo 'Success'", 1000); 4284 */ 4285 static uc_value_t * 4286 uc_system(uc_vm_t *vm, size_t nargs) 4287 { 4288 uc_value_t *cmdline = uc_fn_arg(0); 4289 uc_value_t *timeout = uc_fn_arg(1); 4290 const char **arglist, *fn; 4291 sigset_t sigmask, sigomask; 4292 struct timespec ts; 4293 size_t i, len; 4294 int64_t tms; 4295 pid_t cld; 4296 int rc; 4297 4298 if (timeout && (ucv_type(timeout) != UC_INTEGER || ucv_int64_get(timeout) < 0)) { 4299 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4300 "Invalid timeout specified"); 4301 4302 return NULL; 4303 } 4304 4305 switch (ucv_type(cmdline)) { 4306 case UC_STRING: 4307 arglist = xalloc(sizeof(*arglist) * 4); 4308 arglist[0] = xstrdup("/bin/sh"); 4309 arglist[1] = xstrdup("-c"); 4310 arglist[2] = ucv_to_string(vm, cmdline); 4311 arglist[3] = NULL; 4312 break; 4313 4314 case UC_ARRAY: 4315 len = ucv_array_length(cmdline); 4316 4317 if (len == 0) { 4318 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4319 "Passed command array is empty"); 4320 4321 return NULL; 4322 } 4323 4324 arglist = xalloc(sizeof(*arglist) * (len + 1)); 4325 4326 for (i = 0; i < len; i++) 4327 arglist[i] = ucv_to_string(vm, ucv_array_get(cmdline, i)); 4328 4329 arglist[i] = NULL; 4330 4331 break; 4332 4333 default: 4334 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4335 "Passed command is neither string nor array"); 4336 4337 return NULL; 4338 } 4339 4340 tms = timeout ? ucv_int64_get(timeout) : 0; 4341 4342 if (tms > 0) { 4343 sigemptyset(&sigmask); 4344 sigaddset(&sigmask, SIGCHLD); 4345 4346 if (sigprocmask(SIG_BLOCK, &sigmask, &sigomask) < 0) { 4347 fn = "sigprocmask"; 4348 goto fail; 4349 } 4350 } 4351 4352 cld = fork(); 4353 4354 switch (cld) { 4355 case -1: 4356 fn = "fork"; 4357 goto fail; 4358 4359 case 0: 4360 if (tms <= 0 || sigprocmask(SIG_SETMASK, &sigomask, NULL) == 0) 4361 execvp(arglist[0], (char * const *)arglist); 4362 4363 exit(-1); 4364 4365 break; 4366 4367 default: 4368 if (tms > 0) { 4369 ts.tv_sec = tms / 1000; 4370 ts.tv_nsec = (tms % 1000) * 1000000; 4371 4372 while (1) { 4373 if (sigtimedwait(&sigmask, NULL, &ts) < 0) { 4374 if (errno == EINTR) 4375 continue; 4376 4377 if (errno != EAGAIN) { 4378 fn = "sigtimedwait"; 4379 goto fail; 4380 } 4381 4382 kill(cld, SIGKILL); 4383 } 4384 4385 break; 4386 } 4387 } 4388 4389 while (waitpid(cld, &rc, 0) < 0) { 4390 if (errno == EINTR) 4391 continue; 4392 4393 fn = "waitpid"; 4394 goto fail; 4395 } 4396 4397 if (tms > 0) 4398 sigprocmask(SIG_SETMASK, &sigomask, NULL); 4399 4400 for (i = 0; arglist[i]; i++) 4401 free((char *)arglist[i]); 4402 4403 free(arglist); 4404 4405 if (WIFEXITED(rc)) 4406 return ucv_int64_new(WEXITSTATUS(rc)); 4407 else if (WIFSIGNALED(rc)) 4408 return ucv_int64_new(-WTERMSIG(rc)); 4409 else if (WIFSTOPPED(rc)) 4410 return ucv_int64_new(-WSTOPSIG(rc)); 4411 4412 return NULL; 4413 } 4414 4415 fail: 4416 if (tms > 0) 4417 sigprocmask(SIG_SETMASK, &sigomask, NULL); 4418 4419 for (i = 0; arglist[i]; i++) 4420 free((char *)arglist[i]); 4421 4422 free(arglist); 4423 4424 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 4425 "%s(): %s", fn, strerror(errno)); 4426 4427 return NULL; 4428 } 4429 4430 /** 4431 * Enables or disables VM opcode tracing. 4432 * 4433 * When invoked with a positive non-zero level, opcode tracing is enabled and 4434 * debug information is printed to stderr as the program is executed. 4435 * 4436 * Invoking `trace()` with zero as an argument turns off opcode tracing. 4437 * 4438 * @function module:core#trace 4439 * 4440 * @param {number} level 4441 * The level of tracing to enable. 4442 * 4443 * @example 4444 * trace(1); // Enables opcode tracing 4445 * trace(0); // Disables opcode tracing 4446 */ 4447 static uc_value_t * 4448 uc_trace(uc_vm_t *vm, size_t nargs) 4449 { 4450 uc_value_t *level = uc_fn_arg(0); 4451 uint8_t prev_level; 4452 4453 if (ucv_type(level) != UC_INTEGER) { 4454 uc_vm_raise_exception(vm, EXCEPTION_TYPE, "Invalid level specified"); 4455 4456 return NULL; 4457 } 4458 4459 prev_level = vm->trace; 4460 vm->trace = ucv_int64_get(level); 4461 4462 return ucv_int64_new(prev_level); 4463 } 4464 4465 /** 4466 * Get or set the prototype of the array or object value `val`. 4467 * 4468 * When invoked without a second argument, the function returns the current 4469 * prototype of the value in `val` or `null` if there is no prototype or if the 4470 * given value is neither an object nor an array. 4471 * 4472 * When invoked with a second prototype argument, the given `proto` value is set 4473 * as the prototype on the array or object in `val`. 4474 * 4475 * Throws an exception if the given prototype value is not an object, if the 4476 * given value does not support prototypes, or if setting the prototype would 4477 * create a circular prototype chain. 4478 * 4479 * @function module:core#proto 4480 * 4481 * @param {Array|Object} val 4482 * The array or object value. 4483 * 4484 * @param {Object} [proto] 4485 * The optional prototype object. 4486 * 4487 * @returns {?Object} 4488 * 4489 * @example 4490 * const arr = [1, 2, 3]; 4491 * proto(arr); // Returns the current prototype of the array (null by default) 4492 * proto(arr, { foo: true }); // Sets the given object as the prototype of the array 4493 */ 4494 static uc_value_t * 4495 uc_proto(uc_vm_t *vm, size_t nargs) 4496 { 4497 uc_value_t *val = uc_fn_arg(0); 4498 uc_value_t *proto = NULL; 4499 4500 if (nargs < 2) 4501 return ucv_get(ucv_prototype_get(val)); 4502 4503 proto = uc_fn_arg(1); 4504 4505 /* Reject a circular prototype chain up front so we can raise a specific 4506 * error without invoking ucv_prototype_set(). */ 4507 if (ucv_type(proto) == UC_OBJECT) { 4508 uc_value_t *p; 4509 4510 for (p = proto; p; p = ucv_prototype_get(p)) { 4511 if (p == val) { 4512 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4513 "Cannot set circular prototype"); 4514 4515 return NULL; 4516 } 4517 } 4518 } 4519 4520 /* ucv_prototype_set() takes ownership of the passed reference, so hand it 4521 * an owned ref (uc_fn_arg() only borrows from the stack). Release the 4522 * extra ref if the set is rejected so it is not leaked. */ 4523 if (!ucv_prototype_set(val, ucv_get(proto))) { 4524 ucv_put(proto); 4525 uc_vm_raise_exception(vm, EXCEPTION_TYPE, 4526 "Passed value is neither a prototype, resource or object"); 4527 4528 return NULL; 4529 } 4530 4531 return ucv_get(val); 4532 } 4533 4534 /** 4535 * Pause execution for the given amount of milliseconds. 4536 * 4537 * @function module:core#sleep 4538 * 4539 * @param {number} milliseconds 4540 * The amount of milliseconds to sleep. 4541 * 4542 * @returns {boolean} 4543 * 4544 * @example 4545 * sleep(1000); // Sleeps for 1 second 4546 */ 4547 static uc_value_t * 4548 uc_sleep(uc_vm_t *vm, size_t nargs) 4549 { 4550 uc_value_t *duration = uc_fn_arg(0); 4551 struct timeval tv; 4552 int64_t ms; 4553 4554 ms = ucv_to_integer(duration); 4555 4556 if (errno != 0 || ms <= 0) 4557 return ucv_boolean_new(false); 4558 4559 tv.tv_sec = ms / 1000; 4560 tv.tv_usec = (ms % 1000) * 1000; 4561 4562 select(0, NULL, NULL, NULL, &tv); 4563 4564 return ucv_boolean_new(true); 4565 } 4566 4567 /** 4568 * Raise an exception with the given message parameter when the value in `cond` 4569 * is not truthy. 4570 * 4571 * When `message` is omitted, the default value is `Assertion failed`. 4572 * 4573 * @function module:core#assert 4574 * 4575 * @param {*} cond 4576 * The value to check for truthiness. 4577 * 4578 * @param {string} [message] 4579 * The message to include in the exception. 4580 * 4581 * @throws {Error} When the condition is falsy. 4582 * 4583 * @example 4584 * assert(true, "This is true"); // No exception is raised 4585 * assert(false); // Exception is raised with the default message "Assertion failed" 4586 */ 4587 static uc_value_t * 4588 uc_assert(uc_vm_t *vm, size_t nargs) 4589 { 4590 uc_value_t *cond = uc_fn_arg(0); 4591 uc_value_t *msg = uc_fn_arg(1); 4592 bool freeable = false; 4593 char *s; 4594 4595 if (!ucv_is_truish(cond)) { 4596 s = msg ? uc_cast_string(vm, &msg, &freeable) : "Assertion failed"; 4597 4598 uc_vm_raise_exception(vm, EXCEPTION_USER, "%s", s); 4599 4600 if (freeable) 4601 free(s); 4602 4603 return NULL; 4604 } 4605 4606 return ucv_get(cond); 4607 } 4608 4609 /** 4610 * Construct a regular expression instance from the given `source` pattern 4611 * string and any flags optionally specified by the `flags` argument. 4612 * 4613 * Supported flags: 4614 * - `i`: Case-insensitive matching 4615 * - `s`: DotAll - makes `.` match newline characters (default: `.` does not match newlines) 4616 * - `g`: Global matching (for match() function) 4617 * 4618 * - Throws a type error exception if `flags` is not a string or if the string 4619 * in `flags` contains unrecognized regular expression flag characters. 4620 * - Throws a syntax error when the pattern in `source` cannot be compiled into 4621 * a valid regular expression. 4622 * 4623 * Returns the compiled regular expression value. 4624 * 4625 * @function module:core#regexp 4626 * 4627 * @param {string} source 4628 * The pattern string. 4629 * 4630 * @param {string} [flags] 4631 * The optional regular expression flags (i=ignore case, s=dotAll, g=global). 4632 * 4633 * @returns {RegExp} 4634 * 4635 * @example 4636 * regexp('foo.*bar', 'is'); // equivalent to /foo.*bar/is 4637 * regexp('foo.*bar', 'x'); // throws a "Type error: Unrecognized flag character 'x'" exception 4638 * regexp('foo.*('); // throws a "Syntax error: Unmatched ( or \( exception" 4639 * 4640 * @example 4641 * // Without 's' flag, . does not match newlines 4642 * match("hello\nworld", /hello.world/); // null 4643 * 4644 * @example 4645 * // With 's' flag, . matches newlines (dotAll behavior) 4646 * match("hello\nworld", /hello.world/s); // matches 4647 */ 4648 static uc_value_t * 4649 uc_regexp(uc_vm_t *vm, size_t nargs) 4650 { 4651 bool icase = false, newline = false, global = false, freeable; 4652 uc_value_t *source = uc_fn_arg(0); 4653 uc_value_t *flags = uc_fn_arg(1); 4654 uc_value_t *regex = NULL; 4655 char *p, *err = NULL; 4656 4657 if (flags) { 4658 if (ucv_type(flags) != UC_STRING) { 4659 uc_vm_raise_exception(vm, EXCEPTION_TYPE, "Given flags argument is not a string"); 4660 4661 return NULL; 4662 } 4663 4664 for (p = ucv_string_get(flags); *p; p++) { 4665 switch (*p) { 4666 case 'i': 4667 icase = true; 4668 break; 4669 4670 case 's': 4671 newline = true; 4672 break; 4673 4674 case 'g': 4675 global = true; 4676 break; 4677 4678 default: 4679 uc_vm_raise_exception(vm, EXCEPTION_TYPE, "Unrecognized flag character '%c'", *p); 4680 4681 return NULL; 4682 } 4683 } 4684 } 4685 4686 p = uc_cast_string(vm, &source, &freeable); 4687 regex = ucv_regexp_new(p, icase, newline, global, &err); 4688 4689 if (freeable) 4690 free(p); 4691 4692 if (err) { 4693 uc_vm_raise_exception(vm, EXCEPTION_SYNTAX, "%s", err); 4694 ucv_put(regex); 4695 free(err); 4696 4697 return NULL; 4698 } 4699 4700 return regex; 4701 } 4702 4703 /** 4704 * Match the given subject against the supplied wildcard (file glob) pattern. 4705 * 4706 * - If a truthy value is supplied as the third argument, case-insensitive 4707 * matching is performed. 4708 * - If a non-string value is supplied as the subject, it is converted into a 4709 * string before being matched. 4710 * 4711 * Returns `true` when the value matched the given pattern, otherwise `false`. 4712 * 4713 * @function module:core#wildcard 4714 * 4715 * @param {*} subject 4716 * The subject to match against the wildcard pattern. 4717 * 4718 * @param {string} pattern 4719 * The wildcard pattern. 4720 * 4721 * @param {boolean} [nocase] 4722 * Whether to perform case-insensitive matching. 4723 * 4724 * @returns {boolean} 4725 * 4726 * @example 4727 * wildcard("file.txt", "*.txt"); // Returns true 4728 * wildcard("file.txt", "*.TXT", true); // Returns true (case-insensitive match) 4729 * wildcard("file.txt", "*.jpg"); // Returns false 4730 */ 4731 static uc_value_t * 4732 uc_wildcard(uc_vm_t *vm, size_t nargs) 4733 { 4734 uc_value_t *subject = uc_fn_arg(0); 4735 uc_value_t *pattern = uc_fn_arg(1); 4736 uc_value_t *icase = uc_fn_arg(2); 4737 int flags = 0, rv; 4738 bool freeable; 4739 char *s; 4740 4741 if (!subject || ucv_type(pattern) != UC_STRING) 4742 return NULL; 4743 4744 if (ucv_is_truish(icase)) 4745 flags |= FNM_CASEFOLD; 4746 4747 s = uc_cast_string(vm, &subject, &freeable); 4748 rv = fnmatch(ucv_string_get(pattern), s, flags); 4749 4750 if (freeable) 4751 free(s); 4752 4753 return ucv_boolean_new(rv == 0); 4754 } 4755 4756 /** 4757 * Determine the path of the source file currently being executed by ucode. 4758 * 4759 * @function module:core#sourcepath 4760 * 4761 * @param {number} [depth=0] 4762 * The depth to walk up the call stack. 4763 * 4764 * @param {boolean} [dironly] 4765 * Whether to return only the directory portion of the source file path. 4766 * 4767 * @returns {?string} 4768 * 4769 * @example 4770 * sourcepath(); // Returns the path of the currently executed file 4771 * sourcepath(1); // Returns the path of the parent source file 4772 * sourcepath(2, true); // Returns the directory portion of the grandparent source file path 4773 */ 4774 static uc_value_t * 4775 uc_sourcepath(uc_vm_t *vm, size_t nargs) 4776 { 4777 uc_value_t *calldepth = uc_fn_arg(0); 4778 uc_value_t *dironly = uc_fn_arg(1); 4779 uc_value_t *rv = NULL; 4780 uc_callframe_t *frame; 4781 char *path = NULL; 4782 int64_t depth; 4783 size_t i; 4784 4785 depth = ucv_to_integer(calldepth); 4786 4787 if (errno) 4788 depth = 0; 4789 4790 for (i = vm->callframes.count; i > 0; i--) { 4791 frame = &vm->callframes.entries[i - 1]; 4792 4793 if (!frame->closure) 4794 continue; 4795 4796 if (depth > 0) { 4797 depth--; 4798 continue; 4799 } 4800 4801 path = realpath(uc_program_function_source(frame->closure->function)->runpath, NULL); 4802 break; 4803 } 4804 4805 if (path) { 4806 if (ucv_is_truish(dironly)) 4807 rv = ucv_string_new(dirname(path)); 4808 else 4809 rv = ucv_string_new(path); 4810 4811 free(path); 4812 } 4813 4814 return rv; 4815 } 4816 4817 static uc_value_t * 4818 uc_min_max(uc_vm_t *vm, size_t nargs, int cmp) 4819 { 4820 uc_value_t *rv = NULL, *val; 4821 bool set = false; 4822 size_t i; 4823 4824 for (i = 0; i < nargs; i++) { 4825 val = uc_fn_arg(i); 4826 4827 if (!set || ucv_compare(cmp, val, rv, NULL)) { 4828 set = true; 4829 rv = val; 4830 } 4831 } 4832 4833 return ucv_get(rv); 4834 } 4835 4836 /** 4837 * Return the smallest value among all parameters passed to the function. 4838 * 4839 * @function module:core#min 4840 * 4841 * @param {...*} [val] 4842 * The values to compare. 4843 * 4844 * @returns {*} 4845 * 4846 * @example 4847 * min(5, 2.1, 3, "abc", 0.3); // Returns 0.3 4848 * min(1, "abc"); // Returns 1 4849 * min("1", "abc"); // Returns "1" 4850 * min("def", "abc", "ghi"); // Returns "abc" 4851 * min(true, false); // Returns false 4852 */ 4853 static uc_value_t * 4854 uc_min(uc_vm_t *vm, size_t nargs) 4855 { 4856 return uc_min_max(vm, nargs, I_LT); 4857 } 4858 4859 /** 4860 * Return the largest value among all parameters passed to the function. 4861 * 4862 * @function module:core#max 4863 * 4864 * @param {...*} [val] 4865 * The values to compare. 4866 * 4867 * @returns {*} 4868 * 4869 * @example 4870 * max(5, 2.1, 3, "abc", 0.3); // Returns 5 4871 * max(1, "abc"); // Returns 1 (!) 4872 * max("1", "abc"); // Returns "abc" 4873 * max("def", "abc", "ghi"); // Returns "ghi" 4874 * max(true, false); // Returns true 4875 */ 4876 static uc_value_t * 4877 uc_max(uc_vm_t *vm, size_t nargs) 4878 { 4879 return uc_min_max(vm, nargs, I_GT); 4880 } 4881 4882 4883 /* ------------------------------------------------------------------------- 4884 * The following base64 encoding and decoding routines are taken from 4885 * https://git.openwrt.org/?p=project/libubox.git;a=blob;f=base64.c 4886 * and modified for use in ucode. 4887 * 4888 * Original copyright and license statements below. 4889 */ 4890 4891 /* 4892 * base64 - libubox base64 functions 4893 * 4894 * Copyright (C) 2015 Felix Fietkau <nbd@openwrt.org> 4895 * 4896 * Permission to use, copy, modify, and/or distribute this software for any 4897 * purpose with or without fee is hereby granted, provided that the above 4898 * copyright notice and this permission notice appear in all copies. 4899 * 4900 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 4901 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 4902 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 4903 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 4904 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 4905 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 4906 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 4907 */ 4908 4909 /* $OpenBSD: base64.c,v 1.7 2013/12/31 02:32:56 tedu Exp $ */ 4910 4911 /* 4912 * Copyright (c) 1996 by Internet Software Consortium. 4913 * 4914 * Permission to use, copy, modify, and distribute this software for any 4915 * purpose with or without fee is hereby granted, provided that the above 4916 * copyright notice and this permission notice appear in all copies. 4917 * 4918 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS 4919 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES 4920 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE 4921 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL 4922 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR 4923 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS 4924 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS 4925 * SOFTWARE. 4926 */ 4927 4928 /* 4929 * Portions Copyright (c) 1995 by International Business Machines, Inc. 4930 * 4931 * International Business Machines, Inc. (hereinafter called IBM) grants 4932 * permission under its copyrights to use, copy, modify, and distribute this 4933 * Software with or without fee, provided that the above copyright notice and 4934 * all paragraphs of this notice appear in all copies, and that the name of IBM 4935 * not be used in connection with the marketing of any product incorporating 4936 * the Software or modifications thereof, without specific, written prior 4937 * permission. 4938 * 4939 * To the extent it has a right to do so, IBM grants an immunity from suit 4940 * under its patents, if any, for the use, sale or manufacture of products to 4941 * the extent that such products are used for performing Domain Name System 4942 * dynamic updates in TCP/IP networks by means of the Software. No immunity is 4943 * granted for any product per se or for any other function of any product. 4944 * 4945 * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, 4946 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 4947 * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, 4948 * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING 4949 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN 4950 * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. 4951 */ 4952 4953 /* skips all whitespace anywhere. 4954 converts characters, four at a time, starting at (or after) 4955 src from base - 64 numbers into three 8 bit bytes in the target area. 4956 it returns the number of data bytes stored at the target, or -1 on error. 4957 */ 4958 4959 /** 4960 * Decodes the given base64 encoded string and returns the decoded result. 4961 * 4962 * - If non-whitespace, non-base64 characters are encountered, if invalid 4963 * padding or trailing garbage is found, the function returns `null`. 4964 * - If a non-string argument is given, the function returns `null`. 4965 * 4966 * @function module:core#b64dec 4967 * 4968 * @param {string} str 4969 * The base64 encoded string to decode. 4970 * 4971 * @returns {?string} 4972 * 4973 * @example 4974 * b64dec("VGhpcyBpcyBhIHRlc3Q="); // Returns "This is a test" 4975 * b64dec(123); // Returns null 4976 * b64dec("XXX"); // Returns null 4977 */ 4978 static uc_value_t * 4979 uc_b64dec(uc_vm_t *vm, size_t nargs) 4980 { 4981 enum { BYTE1, BYTE2, BYTE3, BYTE4 } state; 4982 uc_value_t *str = uc_fn_arg(0); 4983 uc_stringbuf_t *buf; 4984 const char *src; 4985 unsigned int ch; 4986 uint8_t val; 4987 size_t off; 4988 4989 if (ucv_type(str) != UC_STRING) 4990 return NULL; 4991 4992 buf = ucv_stringbuf_new(); 4993 src = ucv_string_get(str); 4994 off = printbuf_length(buf); 4995 4996 state = BYTE1; 4997 4998 /* memset the last expected output char to pre-grow the output buffer */ 4999 if (printbuf_memset(buf, off + ((ucv_string_length(str) + 3) / 4) * 3, 0, 1)) { 5000 printbuf_free(buf); 5001 5002 return NULL; 5003 } 5004 5005 while ((ch = (unsigned char)*src++) != '\0') { 5006 if (isspace(ch)) /* Skip whitespace anywhere. */ 5007 continue; 5008 5009 if (ch == '=') 5010 break; 5011 5012 if (ch >= 'A' && ch <= 'Z') 5013 val = ch - 'A'; 5014 else if (ch >= 'a' && ch <= 'z') 5015 val = ch - 'a' + 26; 5016 else if (ch >= '' && ch <= '9') 5017 val = ch - '' + 52; 5018 else if (ch == '+') 5019 val = 62; 5020 else if (ch == '/') 5021 val = 63; 5022 else 5023 goto err; 5024 5025 switch (state) { 5026 case BYTE1: 5027 buf->buf[off] = val << 2; 5028 state = BYTE2; 5029 break; 5030 5031 case BYTE2: 5032 buf->buf[off++] |= val >> 4; 5033 buf->buf[off] = (val & 0x0f) << 4; 5034 state = BYTE3; 5035 break; 5036 5037 case BYTE3: 5038 buf->buf[off++] |= val >> 2; 5039 buf->buf[off] = (val & 0x03) << 6; 5040 state = BYTE4; 5041 break; 5042 5043 case BYTE4: 5044 buf->buf[off++] |= val; 5045 state = BYTE1; 5046 break; 5047 } 5048 } 5049 5050 /* 5051 * We are done decoding Base-64 chars. Let's see if we ended 5052 * on a byte boundary, and/or with erroneous trailing characters. 5053 */ 5054 5055 if (ch == '=') { /* We got a pad char. */ 5056 ch = (unsigned char)*src++; /* Skip it, get next. */ 5057 switch (state) { 5058 case BYTE1: /* Invalid = in first position */ 5059 case BYTE2: /* Invalid = in second position */ 5060 goto err; 5061 5062 case BYTE3: /* Valid, means one byte of info */ 5063 /* Skip any number of spaces. */ 5064 for (; ch != '\0'; ch = (unsigned char)*src++) 5065 if (!isspace(ch)) 5066 break; 5067 /* Make sure there is another trailing = sign. */ 5068 if (ch != '=') 5069 goto err; 5070 ch = (unsigned char)*src++; /* Skip the = */ 5071 /* Fall through to "single trailing =" case. */ 5072 /* FALLTHROUGH */ 5073 5074 case BYTE4: /* Valid, means two bytes of info */ 5075 /* 5076 * We know this char is an =. Is there anything but 5077 * whitespace after it? 5078 */ 5079 for (; ch != '\0'; ch = (unsigned char)*src++) 5080 if (!isspace(ch)) 5081 goto err; 5082 5083 /* 5084 * Now make sure for cases BYTE3 and BYTE4 that the "extra" 5085 * bits that slopped past the last full byte were 5086 * zeros. If we don't check them, they become a 5087 * subliminal channel. 5088 */ 5089 if (buf->buf[off] != 0) 5090 goto err; 5091 } 5092 } else { 5093 /* 5094 * We ended by seeing the end of the string. Make sure we 5095 * have no partial bytes lying around. 5096 */ 5097 if (state != BYTE1) 5098 goto err; 5099 } 5100 5101 /* Truncate buffer length to actual output length */ 5102 buf->bpos = off; 5103 5104 return ucv_stringbuf_finish(buf); 5105 5106 err: 5107 printbuf_free(buf); 5108 5109 return NULL; 5110 } 5111 5112 static const char Base64[] = 5113 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 5114 5115 /** 5116 * Encodes the given string into base64 and returns the resulting string. 5117 * 5118 * - If a non-string argument is given, the function returns `null`. 5119 * 5120 * @function module:core#b64enc 5121 * 5122 * @param {string} str 5123 * The string to encode. 5124 * 5125 * @returns {?string} 5126 * 5127 * @example 5128 * b64enc("This is a test"); // Returns "VGhpcyBpcyBhIHRlc3Q=" 5129 * b64enc(123); // Returns null 5130 */ 5131 static uc_value_t * 5132 uc_b64enc(uc_vm_t *vm, size_t nargs) 5133 { 5134 uc_value_t *str = uc_fn_arg(0); 5135 unsigned char input[3] = {0}; 5136 uc_stringbuf_t *buf; 5137 const char *src; 5138 char output[4]; 5139 size_t len, i; 5140 5141 if (ucv_type(str) != UC_STRING) 5142 return NULL; 5143 5144 buf = ucv_stringbuf_new(); 5145 src = ucv_string_get(str); 5146 len = ucv_string_length(str); 5147 5148 while (2 < len) { 5149 input[0] = (unsigned char)*src++; 5150 input[1] = (unsigned char)*src++; 5151 input[2] = (unsigned char)*src++; 5152 len -= 3; 5153 5154 output[0] = Base64[input[0] >> 2]; 5155 output[1] = Base64[((input[0] & 0x03) << 4) + (input[1] >> 4)]; 5156 output[2] = Base64[((input[1] & 0x0f) << 2) + (input[2] >> 6)]; 5157 output[3] = Base64[input[2] & 0x3f]; 5158 5159 ucv_stringbuf_addstr(buf, output, sizeof(output)); 5160 } 5161 5162 /* Now we worry about padding. */ 5163 if (0 != len) { 5164 /* Get what's left. */ 5165 input[0] = input[1] = input[2] = '\0'; 5166 for (i = 0; i < len; i++) 5167 input[i] = *src++; 5168 5169 output[0] = Base64[input[0] >> 2]; 5170 output[1] = Base64[((input[0] & 0x03) << 4) + (input[1] >> 4)]; 5171 output[2] = (len == 1) ? '=' : Base64[((input[1] & 0x0f) << 2) + (input[2] >> 6)]; 5172 output[3] = '='; 5173 5174 ucv_stringbuf_addstr(buf, output, sizeof(output)); 5175 } 5176 5177 return ucv_stringbuf_finish(buf); 5178 } 5179 5180 /* End of base64 code. 5181 * ------------------------------------------------------------------------- 5182 */ 5183 5184 static unsigned long 5185 uc_uniq_ucv_hash(const void *k) 5186 { 5187 union { double d; int64_t i; uint64_t u; } conv; 5188 uc_value_t *uv = (uc_value_t *)k; 5189 unsigned int h; 5190 uint8_t *u8; 5191 size_t len; 5192 5193 h = ucv_type(uv); 5194 5195 switch (h) { 5196 case UC_STRING: 5197 u8 = (uint8_t *)ucv_string_get(uv); 5198 len = ucv_string_length(uv); 5199 break; 5200 5201 case UC_INTEGER: 5202 conv.i = ucv_int64_get(uv); 5203 5204 if (errno == ERANGE) { 5205 h *= 2; 5206 conv.u = ucv_uint64_get(uv); 5207 } 5208 5209 u8 = (uint8_t *)&conv.u; 5210 len = sizeof(conv.u); 5211 break; 5212 5213 case UC_DOUBLE: 5214 conv.d = ucv_double_get(uv); 5215 5216 u8 = (uint8_t *)&conv.u; 5217 len = sizeof(conv.u); 5218 break; 5219 5220 default: 5221 u8 = (uint8_t *)&uv; 5222 len = sizeof(uv); 5223 break; 5224 } 5225 5226 while (len > 0) { 5227 h = h * 129 + (*u8++) + LH_PRIME; 5228 len--; 5229 } 5230 5231 return h; 5232 } 5233 5234 static int 5235 uc_uniq_ucv_equal(const void *k1, const void *k2) 5236 { 5237 uc_value_t *uv1 = (uc_value_t *)k1; 5238 uc_value_t *uv2 = (uc_value_t *)k2; 5239 5240 if (!ucv_is_scalar(uv1) && !ucv_is_scalar(uv2)) 5241 return (uv1 == uv2); 5242 5243 /* for the sake of array item uniqueness, treat two NaNs as equal */ 5244 if (ucv_type(uv1) == UC_DOUBLE && ucv_type(uv2) == UC_DOUBLE && 5245 isnan(ucv_double_get(uv1)) && isnan(ucv_double_get(uv2))) 5246 return true; 5247 5248 return ucv_is_equal(uv1, uv2); 5249 } 5250 5251 /** 5252 * Returns a new array containing all unique values of the given input array. 5253 * 5254 * - The order is preserved, and subsequent duplicate values are skipped. 5255 * - If a non-array argument is given, the function returns `null`. 5256 * 5257 * @function module:core#uniq 5258 * 5259 * @param {Array} array 5260 * The input array. 5261 * 5262 * @returns {?Array} 5263 * 5264 * @example 5265 * uniq([1, true, "foo", 2, true, "bar", "foo"]); // Returns [1, true, "foo", 2, "bar"] 5266 * uniq("test"); // Returns null 5267 */ 5268 static uc_value_t * 5269 uc_uniq(uc_vm_t *vm, size_t nargs) 5270 { 5271 uc_value_t *list = uc_fn_arg(0); 5272 uc_value_t *uniq = NULL; 5273 struct lh_table *seen; 5274 unsigned long hash; 5275 uc_value_t *item; 5276 size_t i, len; 5277 5278 if (ucv_type(list) != UC_ARRAY) 5279 return NULL; 5280 5281 seen = lh_table_new(16, NULL, uc_uniq_ucv_hash, uc_uniq_ucv_equal); 5282 uniq = ucv_array_new(vm); 5283 5284 assert(seen && uniq); 5285 5286 for (i = 0, len = ucv_array_length(list); i < len; i++) { 5287 item = ucv_array_get(list, i); 5288 hash = lh_get_hash(seen, item); 5289 5290 if (!lh_table_lookup_entry_w_hash(seen, item, hash)) { 5291 lh_table_insert_w_hash(seen, item, NULL, hash, 0); 5292 ucv_array_push(uniq, ucv_get(item)); 5293 } 5294 } 5295 5296 lh_table_free(seen); 5297 5298 return uniq; 5299 } 5300 5301 /** 5302 * A time spec is a plain object describing a point in time, it is returned by 5303 * the {@link module:core#gmtime|gmtime()} and 5304 * {@link module:core#localtime|localtime()} functions and expected as parameter 5305 * by the complementary {@link module:core#timegm|timegm()} and 5306 * {@link module:core#timelocal|timelocal()} functions. 5307 * 5308 * When returned by `gmtime()` or `localtime()`, all members of the object will 5309 * be initialized, when passed as argument to `timegm()` or `timelocal()`, most 5310 * member values are optional. 5311 * 5312 * @typedef {Object} module:core.TimeSpec 5313 * @property {number} sec - Seconds (0..60) 5314 * @property {number} min - Minutes (0..59) 5315 * @property {number} hour - Hours (0..23) 5316 * @property {number} mday - Day of month (1..31) 5317 * @property {number} mon - Month (1..12) 5318 * @property {number} year - Year (>= 1900) 5319 * @property {number} wday - Day of week (1..7, Sunday = 7) 5320 * @property {number} yday - Day of year (1-366, Jan 1st = 1) 5321 * @property {number} isdst - Daylight saving time in effect (yes = 1) 5322 */ 5323 static uc_value_t * 5324 uc_gettime_common(uc_vm_t *vm, size_t nargs, bool local) 5325 { 5326 uc_value_t *ts = uc_fn_arg(0), *res; 5327 time_t t = ts ? (time_t)ucv_to_integer(ts) : time(NULL); 5328 struct tm *tm = (local ? localtime : gmtime)(&t); 5329 5330 if (!tm) 5331 return NULL; 5332 5333 res = ucv_object_new(vm); 5334 5335 ucv_object_add(res, "sec", ucv_int64_new(tm->tm_sec)); 5336 ucv_object_add(res, "min", ucv_int64_new(tm->tm_min)); 5337 ucv_object_add(res, "hour", ucv_int64_new(tm->tm_hour)); 5338 ucv_object_add(res, "mday", ucv_int64_new(tm->tm_mday)); 5339 ucv_object_add(res, "mon", ucv_int64_new(tm->tm_mon + 1)); 5340 ucv_object_add(res, "year", ucv_int64_new(tm->tm_year + 1900)); 5341 ucv_object_add(res, "wday", ucv_int64_new(tm->tm_wday ? tm->tm_wday : 7)); 5342 ucv_object_add(res, "yday", ucv_int64_new(tm->tm_yday + 1)); 5343 ucv_object_add(res, "isdst", ucv_int64_new(tm->tm_isdst)); 5344 5345 return res; 5346 } 5347 5348 /** 5349 * Return the given epoch timestamp (or now, if omitted) as a dictionary 5350 * containing broken-down date and time information according to the local 5351 * system timezone. 5352 * 5353 * See {@link module:core.TimeSpec|TimeSpec} for a description of the fields. 5354 * 5355 * Note that in contrast to the underlying `localtime(3)` C library function, 5356 * the values for `mon`, `wday`, and `yday` are 1-based, and the `year` is 5357 * 1900-based. 5358 * 5359 * @function module:core#localtime 5360 * 5361 * @param {number} [epoch] 5362 * The epoch timestamp. 5363 * 5364 * @returns {module:core.TimeSpec} 5365 * 5366 * @example 5367 * localtime(1647953502); 5368 * // Returns: 5369 * // { 5370 * // sec: 42, 5371 * // min: 51, 5372 * // hour: 13, 5373 * // mday: 22, 5374 * // mon: 3, 5375 * // year: 2022, 5376 * // wday: 2, 5377 * // yday: 81, 5378 * // isdst: 0 5379 * // } 5380 */ 5381 static uc_value_t * 5382 uc_localtime(uc_vm_t *vm, size_t nargs) 5383 { 5384 return uc_gettime_common(vm, nargs, true); 5385 } 5386 5387 /** 5388 * Like `localtime()` but interpreting the given epoch value as UTC time. 5389 * 5390 * See {@link module:core#localtime|localtime()} for details on the return value. 5391 * 5392 * @function module:core#gmtime 5393 * 5394 * @param {number} [epoch] 5395 * The epoch timestamp. 5396 * 5397 * @returns {module:core.TimeSpec} 5398 * 5399 * @example 5400 * gmtime(1647953502); 5401 * // Returns: 5402 * // { 5403 * // sec: 42, 5404 * // min: 51, 5405 * // hour: 13, 5406 * // mday: 22, 5407 * // mon: 3, 5408 * // year: 2022, 5409 * // wday: 2, 5410 * // yday: 81, 5411 * // isdst: 0 5412 * // } 5413 */ 5414 static uc_value_t * 5415 uc_gmtime(uc_vm_t *vm, size_t nargs) 5416 { 5417 return uc_gettime_common(vm, nargs, false); 5418 } 5419 5420 static uc_value_t * 5421 uc_mktime_common(uc_vm_t *vm, size_t nargs, bool local) 5422 { 5423 #define FIELD(name, required) \ 5424 { #name, required, offsetof(struct tm, tm_##name) } 5425 5426 const struct { 5427 const char *name; 5428 bool required; 5429 size_t off; 5430 } fields[] = { 5431 FIELD(sec, false), 5432 FIELD(min, false), 5433 FIELD(hour, false), 5434 FIELD(mday, true), 5435 FIELD(mon, true), 5436 FIELD(year, true), 5437 FIELD(isdst, false) 5438 }; 5439 5440 uc_value_t *to = uc_fn_arg(0), *v; 5441 struct tm tm = { 0 }; 5442 bool exists; 5443 time_t t; 5444 size_t i; 5445 5446 if (ucv_type(to) != UC_OBJECT) 5447 return NULL; 5448 5449 for (i = 0; i < ARRAY_SIZE(fields); i++) { 5450 v = ucv_object_get(to, fields[i].name, &exists); 5451 5452 if (!exists && fields[i].required) 5453 return NULL; 5454 5455 *(int *)((char *)&tm + fields[i].off) = (int)ucv_to_integer(v); 5456 } 5457 5458 if (tm.tm_mon > 0) 5459 tm.tm_mon--; 5460 5461 if (tm.tm_year >= 1900) 5462 tm.tm_year -= 1900; 5463 5464 t = (local ? mktime : timegm)(&tm); 5465 5466 return (t != (time_t)-1) ? ucv_int64_new((int64_t)t) : NULL; 5467 } 5468 5469 /** 5470 * Performs the inverse operation of {@link module:core#localtime|localtime()} 5471 * by taking a broken-down date and time dictionary and transforming it into an 5472 * epoch value according to the local system timezone. 5473 * 5474 * The `wday` and `yday` fields of the given date time specification are 5475 * ignored. Field values outside of their valid range are internally normalized, 5476 * e.g. October 40th is interpreted as November 9th. 5477 * 5478 * Returns the resulting epoch value or null if the input date time dictionary 5479 * was invalid or if the date time specification cannot be represented as epoch 5480 * value. 5481 * 5482 * @function module:core#timelocal 5483 * 5484 * @param {module:core.TimeSpec} datetimespec 5485 * The broken-down date and time dictionary. 5486 * 5487 * @returns {?number} 5488 * 5489 * @example 5490 * timelocal({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 }); 5491 * // Returns 1647953502 5492 */ 5493 static uc_value_t * 5494 uc_timelocal(uc_vm_t *vm, size_t nargs) 5495 { 5496 return uc_mktime_common(vm, nargs, true); 5497 } 5498 5499 /** 5500 * Like `timelocal()` but interpreting the given date time specification as UTC 5501 * time. 5502 * 5503 * See {@link module:core#timelocal|timelocal()} for details. 5504 * 5505 * @function module:core#timegm 5506 * 5507 * @param {module:core.TimeSpec} datetimespec 5508 * The broken-down date and time dictionary. 5509 * 5510 * @returns {?number} 5511 * 5512 * @example 5513 * timegm({ "sec": 42, "min": 51, "hour": 13, "mday": 22, "mon": 3, "year": 2022, "isdst": 0 }); 5514 * // Returns 1647953502 5515 */ 5516 static uc_value_t * 5517 uc_timegm(uc_vm_t *vm, size_t nargs) 5518 { 5519 return uc_mktime_common(vm, nargs, false); 5520 } 5521 5522 /** 5523 * Reads the current second and microsecond value of the system clock. 5524 * 5525 * By default, the realtime clock is queried which might skew forwards or 5526 * backwards due to NTP changes, system sleep modes etc. If a truthy value is 5527 * passed as argument, the monotonic system clock is queried instead, which will 5528 * return the monotonically increasing time since some arbitrary point in the 5529 * past (usually the system boot time). 5530 * 5531 * Returns a two element array containing the full seconds as the first element 5532 * and the nanosecond fraction as the second element. 5533 * 5534 * Returns `null` if a monotonic clock value is requested and the system does 5535 * not implement this clock type. 5536 * 5537 * @function module:core#clock 5538 * 5539 * @param {boolean} [monotonic] 5540 * Whether to query the monotonic system clock. 5541 * 5542 * @returns {?number[]} 5543 * 5544 * @example 5545 * clock(); // [ 1647954926, 798269464 ] 5546 * clock(true); // [ 474751, 527959975 ] 5547 */ 5548 static uc_value_t * 5549 uc_clock(uc_vm_t *vm, size_t nargs) 5550 { 5551 clockid_t id = ucv_is_truish(uc_fn_arg(0)) ? CLOCK_MONOTONIC : CLOCK_REALTIME; 5552 struct timespec ts; 5553 uc_value_t *res; 5554 5555 if (clock_gettime(id, &ts) == -1) 5556 return NULL; 5557 5558 res = ucv_array_new(vm); 5559 5560 ucv_array_set(res, 0, ucv_int64_new((int64_t)ts.tv_sec)); 5561 ucv_array_set(res, 1, ucv_int64_new((int64_t)ts.tv_nsec)); 5562 5563 return res; 5564 } 5565 5566 /** 5567 * Encodes the given byte string into a hexadecimal digit string, converting 5568 * the input value to a string if needed. 5569 * 5570 * @function module:core#hexenc 5571 * 5572 * @param {string} val 5573 * The byte string to encode. 5574 * 5575 * @returns {string} 5576 * 5577 * @example 5578 * hexenc("Hello world!\n"); // "48656c6c6f20776f726c64210a" 5579 */ 5580 static uc_value_t * 5581 uc_hexenc(uc_vm_t *vm, size_t nargs) 5582 { 5583 const char *hex = "0123456789abcdef"; 5584 uc_value_t *input = uc_fn_arg(0); 5585 uc_stringbuf_t *buf; 5586 size_t off, len; 5587 uint8_t byte; 5588 5589 if (!input) 5590 return NULL; 5591 5592 buf = ucv_stringbuf_new(); 5593 off = printbuf_length(buf); 5594 5595 ucv_to_stringbuf(vm, buf, input, false); 5596 5597 len = printbuf_length(buf) - off; 5598 5599 /* memset the last expected output char to grow the output buffer */ 5600 printbuf_memset(buf, off + len * 2, 0, 1); 5601 5602 /* translate string into hex back to front to reuse the same buffer */ 5603 while (len > 0) { 5604 byte = buf->buf[--len + off]; 5605 buf->buf[off + len * 2 + 0] = hex[byte / 16]; 5606 buf->buf[off + len * 2 + 1] = hex[byte % 16]; 5607 } 5608 5609 /* do not include sentinel `\0` in string length */ 5610 buf->bpos--; 5611 5612 return ucv_stringbuf_finish(buf); 5613 } 5614 5615 static inline uint8_t 5616 hexval(unsigned char c, bool lo) 5617 { 5618 return ((c > '9') ? (c - 'a') + 10 : c - '') << (lo ? 0 : 4); 5619 } 5620 5621 /** 5622 * Decodes the given hexadecimal digit string into a byte string, optionally 5623 * skipping specified characters. 5624 * 5625 * If the characters to skip are not specified, a default of `" \t\n"` is used. 5626 * 5627 * Returns null if the input string contains invalid characters or an uneven 5628 * amount of hex digits. 5629 * 5630 * Returns the decoded byte string on success. 5631 * 5632 * @function module:core#hexdec 5633 * 5634 * @param {string} hexstring 5635 * The hexadecimal digit string to decode. 5636 * 5637 * @param {string} [skipchars] 5638 * The characters to skip during decoding. 5639 * 5640 * @returns {?string} 5641 * 5642 * @example 5643 * hexdec("48656c6c6f20776f726c64210a"); // "Hello world!\n" 5644 * hexdec("44:55:66:77:33:44", ":"); // "DUfw3D" 5645 */ 5646 static uc_value_t * 5647 uc_hexdec(uc_vm_t *vm, size_t nargs) 5648 { 5649 uc_value_t *input = uc_fn_arg(0); 5650 uc_value_t *skip = uc_fn_arg(1); 5651 size_t len, off, n, i; 5652 uc_stringbuf_t *buf; 5653 unsigned char *p; 5654 const char *s; 5655 5656 if (ucv_type(input) != UC_STRING) 5657 return NULL; 5658 5659 if (skip && ucv_type(skip) != UC_STRING) 5660 return NULL; 5661 5662 p = (unsigned char *)ucv_string_get(input); 5663 len = ucv_string_length(input); 5664 5665 s = skip ? (const char *)ucv_string_get(skip) : " \t\n"; 5666 5667 for (i = 0, n = 0; i < len; i++) { 5668 if (isxdigit(p[i])) 5669 n++; 5670 else if (!s || !strchr(s, p[i])) 5671 return NULL; 5672 } 5673 5674 if (n & 1) 5675 return NULL; 5676 5677 buf = ucv_stringbuf_new(); 5678 off = printbuf_length(buf); 5679 5680 /* preallocate the output buffer */ 5681 printbuf_memset(buf, off, 0, n / 2 + 1); 5682 5683 for (i = 0, n = 0; i < len; i++) { 5684 if (!isxdigit(p[i])) 5685 continue; 5686 5687 buf->buf[off + (n >> 1)] |= hexval(p[i] | 32, n & 1); 5688 n++; 5689 } 5690 5691 /* do not include sentinel `\0` in string length */ 5692 buf->bpos--; 5693 5694 return ucv_stringbuf_finish(buf); 5695 } 5696 5697 /** 5698 * Interacts with the mark and sweep garbage collector of the running ucode 5699 * virtual machine. 5700 * 5701 * Depending on the given `operation` string argument, the meaning of `argument` 5702 * and the function return value differs. 5703 * 5704 * The following operations are defined: 5705 * 5706 * - `collect` - Perform a complete garbage collection cycle, returns `true`. 5707 * - `start` - (Re-)start periodic garbage collection, `argument` is an optional 5708 * integer in the range `1..65535` specifying the interval. 5709 * Defaults to `1000` if omitted. Returns `true` if the periodic GC 5710 * was previously stopped and is now started or if the interval 5711 * changed. Returns `false` otherwise. 5712 * - `stop` - Stop periodic garbage collection. Returns `true` if the periodic 5713 * GC was previously started and is now stopped, `false` otherwise. 5714 * - `count` - Count the amount of active complex object references in the VM 5715 * context, returns the counted amount. 5716 * 5717 * If the `operation` argument is omitted, the default is `collect`. 5718 * 5719 * @function module:core#gc 5720 * 5721 * @param {string} [operation] 5722 * The operation to perform. 5723 * 5724 * @param {*} [argument] 5725 * The argument for the operation. 5726 * 5727 * @returns {?(boolean|number)} 5728 * 5729 * @example 5730 * gc(); // true 5731 * gc("start"); // true 5732 * gc("count"); // 42 5733 */ 5734 static uc_value_t * 5735 uc_gc(uc_vm_t *vm, size_t nargs) 5736 { 5737 uc_value_t *operation = uc_fn_arg(0); 5738 uc_value_t *argument = uc_fn_arg(1); 5739 const char *op = NULL; 5740 uc_weakref_t *ref; 5741 int64_t n; 5742 5743 if (operation != NULL && ucv_type(operation) != UC_STRING) 5744 return NULL; 5745 5746 op = ucv_string_get(operation); 5747 5748 if (!op || !strcmp(op, "collect")) { 5749 ucv_gc(vm); 5750 5751 return ucv_boolean_new(true); 5752 } 5753 else if (!strcmp(op, "start")) { 5754 n = argument ? ucv_int64_get(argument) : 0; 5755 5756 if (errno || n < 0 || n > 0xFFFF) 5757 return NULL; 5758 5759 if (n == 0) 5760 n = UC_GC_DEFAULT_INTERVAL; 5761 5762 return ucv_boolean_new(uc_vm_gc_start(vm, n)); 5763 } 5764 else if (!strcmp(op, "stop")) { 5765 return ucv_boolean_new(uc_vm_gc_stop(vm)); 5766 } 5767 else if (!strcmp(op, "count")) { 5768 for (n = 0, ref = vm->values.next; ref != &vm->values; ref = ref->next) 5769 n++; 5770 5771 return ucv_uint64_new(n); 5772 } 5773 5774 return NULL; 5775 } 5776 5777 /** 5778 * A parse configuration is a plain object describing options to use when 5779 * compiling ucode at runtime. It is expected as parameter by the 5780 * {@link module:core#loadfile|loadfile()} and 5781 * {@link module:core#loadstring|loadstring()} functions. 5782 * 5783 * All members of the parse configuration object are optional and will default 5784 * to the state of the running ucode file if omitted. 5785 * 5786 * @typedef {Object} module:core.ParseConfig 5787 * 5788 * @property {boolean} lstrip_blocks 5789 * Whether to strip whitespace preceding template directives. 5790 * See {@link https://ucode-lang.org/manual/#h-16-templates-5|whitespace handling in the manual}. 5791 * 5792 * @property {boolean} trim_blocks 5793 * Whether to trim trailing newlines following template directives. 5794 * See {@link https://ucode-lang.org/manual/#h-16-templates-5|whitespace handling in the manual}. 5795 * 5796 * @property {boolean} strict_declarations 5797 * Whether to compile the code in strict mode (`true`) or not (`false`). 5798 * 5799 * @property {boolean} raw_mode 5800 * Whether to compile the code in plain script mode (`true`) or not (`false`). 5801 * 5802 * @property {string[]} module_search_path 5803 * Override the module search path for compile time imports while compiling the 5804 * ucode source. 5805 * 5806 * @property {string[]} force_dynlink_list 5807 * List of module names assumed to be dynamic library extensions, allows 5808 * compiling ucode source with import statements referring to `*.so` extensions 5809 * not present at compile time. 5810 */ 5811 static void 5812 uc_compile_parse_config(uc_parse_config_t *config, uc_value_t *spec) 5813 { 5814 uc_value_t *v, *p; 5815 size_t i, j; 5816 bool found; 5817 5818 struct { 5819 const char *key; 5820 bool *flag; 5821 uc_search_path_t *path; 5822 } fields[] = { 5823 { "lstrip_blocks", &config->lstrip_blocks, NULL }, 5824 { "trim_blocks", &config->trim_blocks, NULL }, 5825 { "strict_declarations", &config->strict_declarations, NULL }, 5826 { "raw_mode", &config->raw_mode, NULL }, 5827 { "module_search_path", NULL, &config->module_search_path }, 5828 { "force_dynlink_list", NULL, &config->force_dynlink_list } 5829 }; 5830 5831 for (i = 0; i < ARRAY_SIZE(fields); i++) { 5832 v = ucv_object_get(spec, fields[i].key, &found); 5833 5834 if (!found) 5835 continue; 5836 5837 if (fields[i].flag) { 5838 *fields[i].flag = ucv_is_truish(v); 5839 } 5840 else if (fields[i].path) { 5841 fields[i].path->count = 0; 5842 fields[i].path->entries = NULL; 5843 5844 for (j = 0; j < ucv_array_length(v); j++) { 5845 p = ucv_array_get(v, j); 5846 5847 if (ucv_type(p) != UC_STRING) 5848 continue; 5849 5850 /* short strings are stored inline in the pointer, so take the 5851 * address of the array slot rather than of the local copy */ 5852 uc_vector_push(fields[i].path, 5853 ucv_string_get(ucv_as_array(v)->entries[j])); 5854 } 5855 } 5856 } 5857 } 5858 5859 static uc_value_t * 5860 uc_load_common(uc_vm_t *vm, size_t nargs, uc_source_t *source, bool is_file) 5861 { 5862 uc_parse_config_t conf = *vm->config; 5863 uc_program_t *program; 5864 uc_value_t *closure; 5865 char *err = NULL; 5866 5867 uc_compile_parse_config(&conf, uc_fn_arg(1)); 5868 5869 program = uc_compile(&conf, source, &err); 5870 closure = program ? uc_program_main(vm, program) : NULL; 5871 5872 uc_program_put(program); 5873 5874 if (!vm->config || conf.module_search_path.entries != vm->config->module_search_path.entries) 5875 uc_vector_clear(&conf.module_search_path); 5876 5877 if (!vm->config || conf.force_dynlink_list.entries != vm->config->force_dynlink_list.entries) 5878 uc_vector_clear(&conf.force_dynlink_list); 5879 5880 if (!closure) { 5881 uc_error_message_indent(&err); 5882 5883 if (!is_file) 5884 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 5885 "Unable to compile source string:\n\n%s", err); 5886 else 5887 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 5888 "Unable to compile source file '%s':\n\n%s", source->filename, err); 5889 } 5890 5891 uc_source_put(source); 5892 free(err); 5893 5894 return closure; 5895 } 5896 5897 /** 5898 * Compiles the given code string into a ucode program and returns the resulting 5899 * program entry function. 5900 * 5901 * The optional `options` dictionary overrides parse and compile options. 5902 * 5903 * - If a non-string `code` argument is given, it is implicitly converted to a 5904 * string value first. 5905 * - If `options` is omitted or a non-object value, the compile options of the 5906 * running ucode program are reused. 5907 * 5908 * See {@link module:core.ParseConfig|ParseConfig} for known keys within the 5909 * `options` object. Unrecognized keys are ignored, unspecified options default 5910 * to those of the running program. 5911 * 5912 * Returns the compiled program entry function. 5913 * 5914 * Throws an exception on compilation errors. 5915 * 5916 * @function module:core#loadstring 5917 * 5918 * @param {string} code 5919 * The code string to compile. 5920 * 5921 * @param {module:core.ParseConfig} [options] 5922 * The options for compilation. 5923 * 5924 * @returns {Function} 5925 * 5926 * @example 5927 * let fn1 = loadstring("Hello, {{ name }}", { raw_mode: false }); 5928 * 5929 * global.name = "Alice"; 5930 * fn1(); // prints `Hello, Alice` 5931 * 5932 * 5933 * let fn2 = loadstring("return 1 + 2;", { raw_mode: true }); 5934 * fn2(); // 3 5935 */ 5936 static uc_value_t * 5937 uc_loadstring(uc_vm_t *vm, size_t nargs) 5938 { 5939 uc_value_t *code = uc_fn_arg(0); 5940 uc_source_t *source; 5941 size_t len; 5942 char *s; 5943 5944 if (ucv_type(code) == UC_STRING) { 5945 len = ucv_string_length(code); 5946 s = xalloc(len); 5947 memcpy(s, ucv_string_get(code), len); 5948 } 5949 else { 5950 s = ucv_to_string(vm, code); 5951 len = strlen(s); 5952 } 5953 5954 source = uc_source_new_buffer("[loadstring argument]", s, len); 5955 5956 if (!source) { 5957 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 5958 "Unable to allocate source buffer: %s", 5959 strerror(errno)); 5960 5961 return NULL; 5962 } 5963 5964 return uc_load_common(vm, nargs, source, false); 5965 } 5966 5967 /** 5968 * Compiles the given file into a ucode program and returns the resulting 5969 * program entry function. 5970 * 5971 * See {@link module:core#loadstring|`loadstring()`} for details. 5972 * 5973 * Returns the compiled program entry function. 5974 * 5975 * Throws an exception on compilation or file I/O errors. 5976 * 5977 * @function module:core#loadfile 5978 * 5979 * @param {string} path 5980 * The path of the file to compile. 5981 * 5982 * @param {module:core.ParseConfig} [options] 5983 * The options for compilation. 5984 * 5985 * @returns {Function} 5986 * 5987 * @example 5988 * loadfile("./templates/example.uc"); // function main() { ... } 5989 */ 5990 static uc_value_t * 5991 uc_loadfile(uc_vm_t *vm, size_t nargs) 5992 { 5993 uc_value_t *path = uc_fn_arg(0); 5994 uc_source_t *source; 5995 5996 if (ucv_type(path) != UC_STRING) 5997 return NULL; 5998 5999 source = uc_source_new_file(ucv_string_get(path)); 6000 6001 if (!source) { 6002 uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, 6003 "Unable to open source file %s: %s", 6004 ucv_string_get(path), strerror(errno)); 6005 6006 return NULL; 6007 } 6008 6009 return uc_load_common(vm, nargs, source, true); 6010 } 6011 6012 /** 6013 * Calls the given function value with a modified environment. 6014 * 6015 * The given `ctx` argument is used as `this` context for the invoked function 6016 * and the given `scope` value as global environment. Any further arguments are 6017 * passed to the invoked function as-is. 6018 * 6019 * When `ctx` is omitted or `null`, the function will get invoked with `this` 6020 * being `null`. 6021 * 6022 * When `scope` is omitted or `null`, the function will get executed with the 6023 * current global environment of the running program. When `scope` is set to a 6024 * dictionary, the dictionary is used as global function environment. 6025 * 6026 * When the `scope` dictionary has no prototype, the current global environment 6027 * will be set as prototype, means the scope will inherit from it. 6028 * 6029 * When a scope prototype is set, it is kept. This allows passing an isolated 6030 * (sandboxed) function scope without access to the global environment. 6031 * 6032 * Any further argument is forwarded as-is to the invoked function as function 6033 * call argument. 6034 * 6035 * Returns `null` if the given function value `fn` is not callable. 6036 * 6037 * Returns the return value of the invoked function in all other cases. 6038 * 6039 * Forwards exceptions thrown by the invoked function. 6040 * 6041 * @function module:core#call 6042 * 6043 * @param {Function} fn 6044 * Function value to call. 6045 * 6046 * @param {*} [ctx=null] 6047 * `this` context for the invoked function. 6048 * 6049 * @param {Object} [scope=null] 6050 * Global environment for the invoked function. 6051 * 6052 * @param {...*} [arg] 6053 * Additional arguments to pass to the invoked function. 6054 * 6055 * @returns {*} 6056 * 6057 * @example 6058 * // Override this context 6059 * call(function() { printf("%J\n", this) }); // null 6060 * call(function() { printf("%J\n", this) }, null); // null 6061 * call(function() { printf("%J\n", this) }, { x: 1 }); // { "x": 1 } 6062 * call(function() { printf("%J\n", this) }, { x: 2 }); // { "x": 2 } 6063 * 6064 * // Run with default scope 6065 * global.a = 1; 6066 * call(function() { printf("%J\n", a) }); // 1 6067 * 6068 * // Override scope, inherit from current global scope (implicit) 6069 * call(function() { printf("%J\n", a) }, null, { a: 2 }); // 2 6070 * 6071 * // Override scope, inherit from current global scope (explicit) 6072 * call(function() { printf("%J\n", a) }, null, 6073 * proto({ a: 2 }, global)); // 2 6074 * 6075 * // Override scope, don't inherit (pass `printf()` but not `a`) 6076 * call(function() { printf("%J\n", a) }, null, 6077 * proto({}, { printf })); // null 6078 * 6079 * // Forward arguments 6080 * x = call((x, y, z) => x * y * z, null, null, 2, 3, 4); // x = 24 6081 */ 6082 static uc_value_t * 6083 uc_callfunc(uc_vm_t *vm, size_t nargs) 6084 { 6085 size_t argoff = vm->stack.count - nargs, i; 6086 uc_value_t *fn_scope, *prev_scope = NULL, *res; 6087 uc_value_t *fn = uc_fn_arg(0); 6088 uc_value_t *this = uc_fn_arg(1); 6089 uc_value_t *scope = uc_fn_arg(2); 6090 6091 if (!ucv_is_callable(fn)) 6092 return NULL; 6093 6094 if (scope && ucv_type(scope) != UC_OBJECT) 6095 return NULL; 6096 6097 if (ucv_prototype_get(scope)) { 6098 fn_scope = ucv_get(scope); 6099 } 6100 else if (scope) { 6101 fn_scope = ucv_object_new(vm); 6102 6103 ucv_object_foreach(scope, k, v) 6104 ucv_object_add(fn_scope, k, ucv_get(v)); 6105 6106 ucv_prototype_set(fn_scope, ucv_get(uc_vm_scope_get(vm))); 6107 } 6108 else { 6109 fn_scope = NULL; 6110 } 6111 6112 if (fn_scope) { 6113 prev_scope = ucv_get(uc_vm_scope_get(vm)); 6114 uc_vm_stack_push(vm, ucv_get(prev_scope)); 6115 uc_vm_scope_set(vm, fn_scope); 6116 } 6117 6118 uc_vm_stack_push(vm, ucv_get(this)); 6119 uc_vm_stack_push(vm, ucv_get(fn)); 6120 6121 for (i = 3; i < nargs; i++) 6122 uc_vm_stack_push(vm, ucv_get(vm->stack.entries[3 + argoff++])); 6123 6124 if (uc_vm_call(vm, true, i - 3) == EXCEPTION_NONE) 6125 res = uc_vm_stack_pop(vm); 6126 else 6127 res = NULL; 6128 6129 if (fn_scope) { 6130 uc_vm_scope_set(vm, prev_scope); 6131 ucv_put(uc_vm_stack_pop(vm)); 6132 } 6133 6134 return res; 6135 } 6136 6137 /** 6138 * Set or query process signal handler function. 6139 * 6140 * When invoked with two arguments, a signal specification and a signal handler 6141 * value, this function configures a new process signal handler. 6142 * 6143 * When invoked with one argument, a signal specification, this function returns 6144 * the currently configured handler for the given signal. 6145 * 6146 * The signal specification might either be an integer signal number or a string 6147 * value containing a signal name (with or without "SIG" prefix). Signal names 6148 * are treated case-insensitively. 6149 * 6150 * The signal handler might be either a callable function value or one of the 6151 * two special string values `"ignore"` and `"default"`. Passing `"ignore"` will 6152 * mask the given process signal while `"default"` will restore the operating 6153 * systems default behaviour for the given signal. 6154 * 6155 * In case a callable handler function is provided, it is invoked at the 6156 * earliest opportunity after receiving the corresponding signal from the 6157 * operating system. The invoked function will receive a single argument, the 6158 * number of the signal it is invoked for. 6159 * 6160 * Note that within the ucode VM, process signals are not immediately delivered, 6161 * instead the VM keeps track of received signals and delivers them to the ucode 6162 * script environment at the next opportunity, usually before executing the next 6163 * byte code instruction. This means that if a signal is received while 6164 * performing a computationally expensive operation in C mode, such as a complex 6165 * regexp match, the corresponding ucode signal handler will only be invoked 6166 * after that operation concluded and control flow returns to the VM. 6167 * 6168 * Returns the signal handler function or one of the special values `"ignore"` 6169 * or `"default"` corresponding to the given signal specification. 6170 * 6171 * Returns `null` if an invalid signal spec or signal handler was provided. 6172 * 6173 * Returns `null` if changing the signal action failed, e.g. due to insufficient 6174 * permission, or when attempting to ignore a non-ignorable signal. 6175 * 6176 * @function module:core#signal 6177 * 6178 * @param {number|string} signal 6179 * The signal to query/set handler for. 6180 * 6181 * @param {Function|string} [handler] 6182 * The signal handler to install for the given signal. 6183 * 6184 * @returns {Function|string} 6185 * 6186 * @example 6187 * // Ignore signals 6188 * signal('INT', 'ignore'); // "ignore" 6189 * signal('SIGINT', 'ignore'); // "ignore" (equivalent to 'INT') 6190 * signal('sigterm', 'ignore'); // "ignore" (signal names are case insensitive) 6191 * signal(9, 'ignore'); // null (SIGKILL cannot be ignored) 6192 * 6193 * // Restore signal default behavior 6194 * signal('INT', 'default'); // "default" 6195 * signal('foobar', 'default'); // null (unknown signal name) 6196 * signal(-313, 'default'); // null (invalid signal number) 6197 * 6198 * // Set custom handler function 6199 * function intexit(signo) { 6200 * printf("I received signal number %d\n", signo); 6201 * exit(1); 6202 * } 6203 * 6204 * signal('SIGINT', intexit); // returns intexit 6205 * signal('SIGINT') == intexit; // true 6206 */ 6207 static uc_value_t * 6208 uc_signal(uc_vm_t *vm, size_t nargs) 6209 { 6210 uc_value_t *signame = uc_fn_arg(0); 6211 uc_value_t *sighandler = uc_fn_arg(1); 6212 struct sigaction sa = { 0 }; 6213 char *sigstr; 6214 int sig; 6215 6216 if (ucv_type(signame) == UC_INTEGER) { 6217 sig = (int)ucv_int64_get(signame); 6218 6219 if (errno || sig < 0 || sig >= UC_SYSTEM_SIGNAL_COUNT) 6220 return NULL; 6221 6222 if (!uc_system_signal_names[sig]) 6223 return NULL; 6224 } 6225 else if (ucv_type(signame) == UC_STRING) { 6226 sigstr = ucv_string_get(signame); 6227 6228 if (!strncasecmp(sigstr, "SIG", 3)) 6229 sigstr += 3; 6230 6231 for (sig = 0; sig < UC_SYSTEM_SIGNAL_COUNT; sig++) 6232 if (uc_system_signal_names[sig] && 6233 !strcasecmp(uc_system_signal_names[sig], sigstr)) 6234 break; 6235 6236 if (sig == UC_SYSTEM_SIGNAL_COUNT) 6237 return NULL; 6238 } 6239 else { 6240 return NULL; 6241 } 6242 6243 /* Query current signal handler state */ 6244 if (nargs < 2) { 6245 if (sigaction(sig, NULL, &sa) != 0) 6246 return NULL; 6247 6248 if (sa.sa_handler == SIG_IGN) 6249 return ucv_string_new("ignore"); 6250 6251 if (sa.sa_handler == SIG_DFL) 6252 return ucv_string_new("default"); 6253 6254 return ucv_get(ucv_array_get(vm->signal.handler, sig)); 6255 } 6256 6257 /* Install new signal handler */ 6258 if (ucv_type(sighandler) == UC_STRING) { 6259 sigstr = ucv_string_get(sighandler); 6260 6261 sa.sa_flags = SA_ONSTACK | SA_RESTART; 6262 sigemptyset(&sa.sa_mask); 6263 6264 if (!strcmp(sigstr, "ignore")) 6265 sa.sa_handler = SIG_IGN; 6266 else if (!strcmp(sigstr, "default")) 6267 sa.sa_handler = SIG_DFL; 6268 else 6269 return NULL; 6270 6271 if (sigaction(sig, &sa, NULL) != 0) 6272 return NULL; 6273 6274 ucv_array_set(vm->signal.handler, sig, NULL); 6275 } 6276 else if (ucv_is_callable(sighandler)) { 6277 if (sigaction(sig, &vm->signal.sa, NULL) != 0) 6278 return NULL; 6279 6280 ucv_array_set(vm->signal.handler, sig, ucv_get(sighandler)); 6281 } 6282 else { 6283 return NULL; 6284 } 6285 6286 return ucv_get(sighandler); 6287 } 6288 6289 6290 /* The slot of every entry is pinned by its designated initializer, see 6291 * uc_stdlib_fn_t, so the layout of this table does not depend on the order the 6292 * entries are written in: adding a function appends a slot at the end, retiring 6293 * one drops its initializer and leaves that slot empty. 6294 * 6295 * Slots are baked into compiled bytecode; one beyond the table or an empty one 6296 * is reported by the VM rather than silently invoking another function. */ 6297 const uc_function_list_t uc_stdlib_functions[] = { 6298 [UC_FN_CHR ] = { "chr", uc_chr }, 6299 [UC_FN_DIE ] = { "die", uc_die }, 6300 [UC_FN_EXISTS ] = { "exists", uc_exists }, 6301 [UC_FN_RAWGET ] = { "rawget", uc_rawget }, 6302 [UC_FN_RAWSET ] = { "rawset", uc_rawset }, 6303 [UC_FN_RAWDELETE ] = { "rawdelete", uc_rawdelete }, 6304 [UC_FN_EXIT ] = { "exit", uc_exit }, 6305 [UC_FN_FILTER ] = { "filter", uc_filter }, 6306 [UC_FN_GETENV ] = { "getenv", uc_getenv }, 6307 [UC_FN_HEX ] = { "hex", uc_hex }, 6308 [UC_FN_INDEX ] = { "index", uc_lindex }, 6309 [UC_FN_INT ] = { "int", uc_int }, 6310 [UC_FN_JOIN ] = { "join", uc_join }, 6311 [UC_FN_KEYS ] = { "keys", uc_keys }, 6312 [UC_FN_LC ] = { "lc", uc_lc }, 6313 [UC_FN_LENGTH ] = { "length", uc_length }, 6314 [UC_FN_LTRIM ] = { "ltrim", uc_ltrim }, 6315 [UC_FN_MAP ] = { "map", uc_map }, 6316 [UC_FN_ORD ] = { "ord", uc_ord }, 6317 [UC_FN_POP ] = { "pop", uc_pop }, 6318 [UC_FN_PRINT ] = { "print", uc_print }, 6319 [UC_FN_PUSH ] = { "push", uc_push }, 6320 [UC_FN_REVERSE ] = { "reverse", uc_reverse }, 6321 [UC_FN_RINDEX ] = { "rindex", uc_rindex }, 6322 [UC_FN_RTRIM ] = { "rtrim", uc_rtrim }, 6323 [UC_FN_SHIFT ] = { "shift", uc_shift }, 6324 [UC_FN_SORT ] = { "sort", uc_sort }, 6325 [UC_FN_SPLICE ] = { "splice", uc_splice }, 6326 [UC_FN_SLICE ] = { "slice", uc_slice }, 6327 [UC_FN_SPLIT ] = { "split", uc_split }, 6328 [UC_FN_SUBSTR ] = { "substr", uc_substr }, 6329 [UC_FN_TIME ] = { "time", uc_time }, 6330 [UC_FN_TRIM ] = { "trim", uc_trim }, 6331 [UC_FN_TYPE ] = { "type", uc_type }, 6332 [UC_FN_UCHR ] = { "uchr", uc_uchr }, 6333 [UC_FN_UC ] = { "uc", uc_uc }, 6334 [UC_FN_UNSHIFT ] = { "unshift", uc_unshift }, 6335 [UC_FN_VALUES ] = { "values", uc_values }, 6336 [UC_FN_SPRINTF ] = { "sprintf", uc_sprintf }, 6337 [UC_FN_PRINTF ] = { "printf", uc_printf }, 6338 [UC_FN_REQUIRE ] = { "require", uc_require }, 6339 [UC_FN_IPTOARR ] = { "iptoarr", uc_iptoarr }, 6340 [UC_FN_ARRTOIP ] = { "arrtoip", uc_arrtoip }, 6341 [UC_FN_MATCH ] = { "match", uc_match }, 6342 [UC_FN_REPLACE ] = { "replace", uc_replace }, 6343 [UC_FN_JSON ] = { "json", uc_json }, 6344 [UC_FN_INCLUDE ] = { "include", uc_include }, 6345 [UC_FN_WARN ] = { "warn", uc_warn }, 6346 [UC_FN_SYSTEM ] = { "system", uc_system }, 6347 [UC_FN_TRACE ] = { "trace", uc_trace }, 6348 [UC_FN_PROTO ] = { "proto", uc_proto }, 6349 [UC_FN_SLEEP ] = { "sleep", uc_sleep }, 6350 [UC_FN_ASSERT ] = { "assert", uc_assert }, 6351 [UC_FN_RENDER ] = { "render", uc_render }, 6352 [UC_FN_REGEXP ] = { "regexp", uc_regexp }, 6353 [UC_FN_WILDCARD ] = { "wildcard", uc_wildcard }, 6354 [UC_FN_SOURCEPATH] = { "sourcepath", uc_sourcepath }, 6355 [UC_FN_MIN ] = { "min", uc_min }, 6356 [UC_FN_MAX ] = { "max", uc_max }, 6357 [UC_FN_B64DEC ] = { "b64dec", uc_b64dec }, 6358 [UC_FN_B64ENC ] = { "b64enc", uc_b64enc }, 6359 [UC_FN_UNIQ ] = { "uniq", uc_uniq }, 6360 [UC_FN_LOCALTIME ] = { "localtime", uc_localtime }, 6361 [UC_FN_GMTIME ] = { "gmtime", uc_gmtime }, 6362 [UC_FN_TIMELOCAL ] = { "timelocal", uc_timelocal }, 6363 [UC_FN_TIMEGM ] = { "timegm", uc_timegm }, 6364 [UC_FN_CLOCK ] = { "clock", uc_clock }, 6365 [UC_FN_HEXDEC ] = { "hexdec", uc_hexdec }, 6366 [UC_FN_HEXENC ] = { "hexenc", uc_hexenc }, 6367 [UC_FN_GC ] = { "gc", uc_gc }, 6368 [UC_FN_LOADSTRING] = { "loadstring", uc_loadstring }, 6369 [UC_FN_LOADFILE ] = { "loadfile", uc_loadfile }, 6370 [UC_FN_CALL ] = { "call", uc_callfunc }, 6371 [UC_FN_SIGNAL ] = { "signal", uc_signal }, 6372 }; 6373 6374 6375 /* The table holds exactly the slots the enum enumerates. */ 6376 _Static_assert(ARRAY_SIZE(uc_stdlib_functions) == UC_FN_COUNT, 6377 "uc_stdlib_functions[] and uc_stdlib_fn_t are out of step"); 6378 6379 6380 6381 void 6382 uc_stdlib_load(uc_value_t *scope) 6383 { 6384 uc_function_list_register(scope, uc_stdlib_functions); 6385 } 6386 6387 uc_cfn_ptr_t 6388 uc_stdlib_function(const char *name) 6389 { 6390 size_t i; 6391 6392 for (i = 0; i < ARRAY_SIZE(uc_stdlib_functions); i++) 6393 if (uc_stdlib_functions[i].name && 6394 !strcmp(uc_stdlib_functions[i].name, name)) 6395 return uc_stdlib_functions[i].func; 6396 6397 return NULL; 6398 } 6399 6400 /* Resolve a bytecode slot to the C function, for the VM; returns NULL for 6401 * slots out of range, i.e. for bytecode built against another table order. */ 6402 uc_cfn_ptr_t 6403 uc_stdlib_function_by_slot(size_t slot) 6404 { 6405 if (slot >= ARRAY_SIZE(uc_stdlib_functions)) 6406 return NULL; 6407 6408 return uc_stdlib_functions[slot].func; 6409 } 6410 6411 /* Resolve a bytecode slot to the name of its function, for the trace output 6412 * and the debugger's disassembly; returns NULL for slots out of range and for 6413 * empty ones, i.e. functions retired since the bytecode was compiled. */ 6414 const char * 6415 uc_stdlib_function_name_by_slot(size_t slot) 6416 { 6417 if (slot >= ARRAY_SIZE(uc_stdlib_functions)) 6418 return NULL; 6419 6420 return uc_stdlib_functions[slot].name; 6421 } 6422
This page was automatically generated by LXR 0.3.1. • OpenWrt