QuickJSR/0000755000176200001440000000000015135354472011716 5ustar liggesusersQuickJSR/tests/0000755000176200001440000000000015122664674013064 5ustar liggesusersQuickJSR/tests/tinytest.R0000644000176200001440000000007715122664674015076 0ustar liggesuserslibrary(QuickJSR) library(tinytest) test_package("QuickJSR") QuickJSR/MD50000644000176200001440000001232315135354472012227 0ustar liggesusers262ffca64726751c573b70234fa2ef89 *DESCRIPTION f29ab4c037b9b5744c35044282f622ba *LICENSE a3cc65aaaf4273be05b237616f458ee0 *NAMESPACE 4ebb576d5743e61f3ddc74c43e9ea19c *NEWS.md ca74e92e0a387359d3f2021b77991726 *R/JSContext.R f447f2e841bd83b4b432f7204f47cba1 *R/qjs.R f10f1910f65938f9d24db769a9268f19 *R/quickjsr-package.R 45d369987be0f222d8e6bb77d55e2dae *R/zzz.R 5c90eea19f8048d73491b8a2cd793a6b *README.md ce66024b1eccd2b5da306c2b065e6484 *build/vignette.rds fb48a01a3bca2fea3bb8ea0ae6991a0f *inst/doc/working_with_js_types.R 9a56f2155c98c72800c17a34512ef31e *inst/doc/working_with_js_types.Rmd a607709023d871a66638699ec92b22ce *inst/doc/working_with_js_types.html 5f5e8bda75bbc24d0bb41aa85c91337d *inst/tinytest/test_JSContext.R 7ab298428bfbe98ac7a7ff285841e7f5 *inst/tinytest/test_data_conversion.R 11c942e40a7f1c632194ebb7dd41c422 *inst/tinytest/test_qjs_eval.R 4b816d167b6bc876fe321613f8a5a442 *inst/tinytest/test_to_json_asis.R 8aa94f260b4114a192b388e2f4d3b7b0 *inst/tinytest/test_to_json_dataframe.R 0ba9d2d0ae011de367835975ed0d80f9 *inst/tinytest/test_to_json_date.R 43a407fa35b86461ef406f8c649be36c *inst/tinytest/test_to_json_factor.R 327184a78119fd54b079b7154cc4dc6f *inst/tinytest/test_to_json_matrix.R ea6de7a5870eaf7fe6bfca93e92ac049 *man/JSContext-method-assign.Rd e24fa08fdc370229109eccfe571cf014 *man/JSContext-method-call.Rd ddf5a2b0625e36b4fb6e01b5cc9ebe14 *man/JSContext-method-get.Rd d4982ecbd86a1ce5939634cfc86e6a64 *man/JSContext-method-source.Rd 81543a45d4f279e1fa46114a7786efc8 *man/JSContext-method-validate.Rd 7f79334a1b18d5b2254f9856d20a268c *man/JSContext.Rd fc18b5b233f62c88dd40e02674528ff0 *man/QuickJSR-package.Rd 362bc38ae3cad23f09de655a9c0431c3 *man/from_json.Rd 6d4b8bfb872a8b860d8343ad332ee4f2 *man/qjs_eval.Rd a753931e4fa9c1be839b6c122cfe064e *man/quickjs_version.Rd 2b3a5adc32539392c22dafee20054401 *man/to_json.Rd cfa7e60f3c935be3c8bd7f2c2f9aade4 *src/Makevars b56de332e35095618753f222d83b2a1b *src/include/cpp11.hpp 734e3820b036557fb463941bb8181ff0 *src/include/cpp11/R.hpp 9a79c29ef17b31f942e4524daa3c567a *src/include/cpp11/altrep.hpp 582a3ef513152a0d9b2d7fd645ab9946 *src/include/cpp11/as.hpp 33fea6ce3d8e419e3b39edbad929debd *src/include/cpp11/attribute_proxy.hpp fd2e4e415d8d86514a6838aba41db1da *src/include/cpp11/data_frame.hpp e269e0ae86768bf648df277c0df27cda *src/include/cpp11/declarations.hpp eb92c84370b25e2c7d97afae9544dd68 *src/include/cpp11/doubles.hpp ddcd2f3fff750cbe90d0627e702b7b3f *src/include/cpp11/environment.hpp 331f8c0efca0806f14b3a0bbb1092488 *src/include/cpp11/external_pointer.hpp 095e53bfef9ee433616ebb5ce535ee47 *src/include/cpp11/function.hpp 92a920417bb7f8c1bbd8847a3fc59ee9 *src/include/cpp11/integers.hpp d21de309e70aae249aea0bee2e2fe474 *src/include/cpp11/list.hpp 26585fec819060d3fccf1c02ee7fc4a8 *src/include/cpp11/list_of.hpp 9736add601cc8f942d06fda5539b0d6a *src/include/cpp11/logicals.hpp 02d19af5542af6c4c5719738456690e7 *src/include/cpp11/matrix.hpp 1b93c8f871fcb4709daf948c636134bb *src/include/cpp11/named_arg.hpp c95a85448df8f197db19e15e9ee06ac4 *src/include/cpp11/protect.hpp 8c0c27a9d1515bd999e6ef61da1c8b47 *src/include/cpp11/r_bool.hpp 3fc390174af4a3b7877c5ab6f082b7d8 *src/include/cpp11/r_string.hpp 92205cc55f585d56137ef34ef27d15e4 *src/include/cpp11/r_vector.hpp f5fe61ca41e78b435c59d7f549566d77 *src/include/cpp11/raws.hpp 04c39e6e707d1f00c627cc94d0d03104 *src/include/cpp11/sexp.hpp e2049f00df55293784bb93fbc1ec7c0c *src/include/cpp11/strings.hpp b2e7c20e41f44a3d731113d1e29b7813 *src/include/quickjs_helpers.hpp 6c6169a01c040a168f2c892fcb3f3388 *src/include/quickjsr.hpp b306e2d748cc4e3e1c9ea0d2a121cacd *src/include/quickjsr/JSValue_to_SEXP.hpp 0fb33adea37899328a4b765a006b5a88 *src/include/quickjsr/JS_PropertyRecursive.hpp d42327c064b8ed8475757929603e3d29 *src/include/quickjsr/JS_SEXP.hpp c703ccf2e560d1c68d112c9aeea3de8f *src/include/quickjsr/SEXP_to_JSValue.hpp a7521674b0f9f555f8d072cbbc2e089a *src/include/quickjsr/type_traits.hpp 0ea4b6fe1a2b7b73a58b7e8d017d4896 *src/init.cpp 6682b4362372bbf72e53c3965ba9db8d *src/libquickjs.c 3e9b6955e717474a8b2899949397b26b *src/quickjs/builtin-array-fromasync.h 476a4ccd3ab6e6562a5d113abac41176 *src/quickjs/cutils.c c393102b035605df487c2c90a6e9d764 *src/quickjs/cutils.h 4a86a0a58603dc53d6214c34799cf334 *src/quickjs/dtoa.c 0653db195810c1cbb75068ef9e710e04 *src/quickjs/dtoa.h 94c363501d12bcb70d6a165e3a2c22b8 *src/quickjs/libregexp-opcode.h c3491ff205f767cd5859fffbffd24633 *src/quickjs/libregexp.c cc938155f27366f6f86a5427b48f5d11 *src/quickjs/libregexp.h e84967ae9aa74c24333b2bdfa193f32d *src/quickjs/libunicode-table.h cdc8f69c278c4c4c0b66898a4eee7950 *src/quickjs/libunicode.c 0cbe91ef76f92b9bf9ac0992146db818 *src/quickjs/libunicode.h 31c01ed5a76bb037ee839d9ff634203b *src/quickjs/list.h 085ba4da45ed83cb473a390799c28257 *src/quickjs/quickjs-atom.h a50162c5a29b02575cc515499a0bc6da *src/quickjs/quickjs-c-atomics.h d7cf53a3e4ed2075af392804960dbea2 *src/quickjs/quickjs-libc.c 1175a8e86e5b4f05f12667235e4e64e1 *src/quickjs/quickjs-libc.h fe1bbd5b86062adba35ea87c32ccf435 *src/quickjs/quickjs-opcode.h 8614ec88851520e84db6e085516d632d *src/quickjs/quickjs.c 829d061ef584255460d917732b8959d2 *src/quickjs/quickjs.h d4adcf2681493f80e0217ecbdec510e5 *src/quickjsr.cpp ac8612347958caa9b35bc4dbfe52e670 *tests/tinytest.R 9a56f2155c98c72800c17a34512ef31e *vignettes/working_with_js_types.Rmd QuickJSR/R/0000755000176200001440000000000015122664674012123 5ustar liggesusersQuickJSR/R/JSContext.R0000644000176200001440000001054015122664674014127 0ustar liggesusers#' Assess validity of JS code without evaluating #' #' @name JSContext-method-validate #' @aliases validate #' #' @usage validate(code_string) #' #' @description #' Checks whether JS code string is valid code in the current context #' #' @param code_string The JS code to check #' @return A boolean indicating whether code is valid #' #' @examples #' \dontrun{ #' ctx <- JSContext$new() #' ctx$validate("1 + 2") #' } validate <- NULL #' Evaluate JS string or file in the current context #' #' @name JSContext-method-source #' @aliases source #' #' @usage source(file = NULL, code = NULL) #' #' @description #' Evaluate a provided JavaScript file or string within the initialised context. #' Note that this method should only be used for initialising functions or values #' within the context, no values are returned from this function. See the `$call()` #' method for returning values. #' #' @param file A path to the JavaScript file to load #' @param code A single string of JavaScript to evaluate #' @return No return value, called for side effects #' #' @examples #' \dontrun{ #' ctx <- JSContext$new() #' ctx$source(file = "path/to/file.js") #' ctx$source(code = "1 + 2") #' } source <- NULL #' Call a JS function in the current context #' #' @name JSContext-method-call #' @aliases call #' #' @usage call(function_name, ...) #' #' @description Call a specified function in the JavaScript context with the #' provided arguments. #' #' @param function_name The function to be called #' @param ... The arguments to be passed to the function #' @return The result of calling the specified function #' #' @examples #' \dontrun{ #' ctx <- JSContext$new() #' ctx$source(code = "function add(a, b) { return a + b; }") #' ctx$call("add", 1, 2) #' } call <- NULL #' Get a variable from the current context #' #' @name JSContext-method-get #' @aliases get #' #' @usage get(var_name) #' #' @description #' Get the value of a variable from the current context #' #' @param var_name The name of the variable to retrieve #' @return The value of the variable #' #' @examples #' \dontrun{ #' ctx <- JSContext$new() #' ctx$source(code = "var a = 1;") #' ctx$get("a") #' } get <- NULL #' Assign a value to a variable in the current context #' #' @name JSContext-method-assign #' @aliases assign #' #' @usage assign(var_name, value) #' #' @description #' Assign a value to a variable in the current context #' #' @param var_name The name of the variable to assign #' @param value The value to assign to the variable #' @return No return value, called for side effects #' #' @examples #' \dontrun{ #' ctx <- JSContext$new() #' ctx$assign("a", 1) #' ctx$get("a") #' } assign <- NULL new_JSContext <- function(stack_size = NULL) { stack_size_int <- ifelse(is.null(stack_size), -1, stack_size) rt_and_ctx <- qjs_context(stack_size_int) ContextList <- list( runtime = rt_and_ctx$runtime_ptr, context = rt_and_ctx$context_ptr ) ContextList$validate <- function(code_string) { qjs_validate(ContextList$context, code_string) } ContextList$source <- function(file = NULL, code = NULL) { eval_success <- TRUE if (!is.null(file)) { if (!is.null(code)) { warning("Both a filepath and code string cannot be provided,", " code will be ignored!", call. = FALSE) } eval_success <- qjs_source(ContextList$context, input = normalizePath(file), is_file = TRUE) } else if (!is.null(code)) { eval_success <- qjs_source(ContextList$context, input = code, is_file = FALSE) } else { stop("No JS code provided!", call. = FALSE) } if (!eval_success) { stop("Evaluating JS code failed, see message above!", call. = FALSE) } invisible(NULL) } ContextList$call <- function(function_name, ...) { qjs_call(ContextList$context, function_name, ...) } ContextList$get <- function(var_name) { qjs_get(ContextList$context, var_name) } ContextList$assign <- function(var_name, value) { qjs_assign(ContextList$context, var_name, value) } structure( class = "JSContext", ContextList ) } #' @title JSContext object #' #' @description #' An initialised context within which to evaluate Javascript #' scripts or commands. #' #' @return A JSContext object containing an initialised JavaScript #' context for evaluating scripts/commands #' #' @export JSContext <- list( new = new_JSContext ) QuickJSR/R/qjs.R0000644000176200001440000000343015122664674013043 0ustar liggesusers#' qjs_eval #' #' Evaluate a single Javascript expression. #' #' @param eval_string A single string of the expression to evaluate #' @return The result of the provided expression #' #' @examples #' # Return the sum of two numbers: #' qjs_eval("1 + 2") #' #' # Concatenate strings: #' qjs_eval("'1' + '2'") #' #' # Create lists from objects: #' qjs_eval("var t = {'a' : 1, 'b' : 2}; t") #' #' @export qjs_eval <- function(eval_string) { .Call(`qjs_eval_`, eval_string) } qjs_context <- function(stack_size) { .Call(`qjs_context_`, stack_size) } qjs_source <- function(ctx_ptr, input, is_file) { .Call(`qjs_source_`, ctx_ptr, input, is_file) } qjs_call <- function(ctx_ptr, function_name, ...) { .Call(`qjs_call_`, ctx_ptr, function_name, list(...)) } qjs_validate <- function(ctx_ptr, function_name) { .Call(`qjs_validate_`, ctx_ptr, function_name) } qjs_get <- function(ctx_ptr, var_name) { .Call(`qjs_get_`, ctx_ptr, var_name) } qjs_assign <- function(ctx_ptr, var_name, value) { res <- .Call(`qjs_assign_`, ctx_ptr, var_name, value) invisible(NULL) } #' to_json #' #' Use the QuickJS C API to convert an R object to a JSON string #' #' @param arg Argument to convert to JSON #' @param auto_unbox Automatically unbox single element vectors #' @return JSON string #' #' @export to_json <- function(arg, auto_unbox = FALSE) { .Call(`to_json_`, arg, auto_unbox) } #' from_json #' #' Use the QuickJS C API to convert a JSON string to an R object #' #' @param json JSON string to convert to an R object #' @return R object #' #' @export from_json <- function(json) { .Call(`from_json_`, json) } #' Get the version of the bundled QuickJS library #' #' @return Character string of the version of the bundled QuickJS library #' @export quickjs_version <- function() { .Call(`qjs_version_`) } QuickJSR/R/quickjsr-package.R0000644000176200001440000000032615122664674015473 0ustar liggesusers#' The QuickJSR package. #' #' @description An interface to the QuickJS lightweight Javascript engine #' #' @name QuickJSR-package #' @aliases QuickJSR #' @useDynLib QuickJSR, .registration = TRUE #' #' "_PACKAGE" QuickJSR/R/zzz.R0000644000176200001440000000016015122664674013100 0ustar liggesusers.onUnload <- function(libpath) { # unload the package library library.dynam.unload("QuickJSR", libpath) } QuickJSR/vignettes/0000755000176200001440000000000015135347454013730 5ustar liggesusersQuickJSR/vignettes/working_with_js_types.Rmd0000644000176200001440000000676115122664674021043 0ustar liggesusers--- title: "Working with R and JS Types" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with R and JS Types} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(QuickJSR) ``` ## Mappings and Conversions Between R and JS Types `QuickJSR` uses the respective `C` APIs of `R` and `QuickJS` in order to pass values between the two. This allows for increased efficiency in passing and returning values (as no serialisation or de-serialisation is required) and also allows for greater flexibility in working with R closures, functions, and environments in JS code. `QuickJSR` aims to broadly follow the conventions of `jsonlite` in terms of how R types are converted to JS types and vice-versa. ### Primitive & Scalar Types The following table outlines the basic mappings of primitive types between R and JS types: | R Type | JS Type | |--------|---------| | NULL | null | | logical| boolean | | integer| number | | double | number | | character| string| | date | date | | POSIXct| date | | factor | string | Note that the handling of `Date`/`POSIXct` types differs from `jsonlite`, where they are converted to strings. In `QuickJSR`, they are treated directly as `Date` objects in JS. ### Container Types The following table outlines the basic mappings of container types between R and JS types: | R Type | JS Type | |--------|---------| | named list | object | | unnamed list | array | | vector | array | | array | array | | matrix | 2D number array | | data.frame | array of objects | Examples of the `matrix` and `data.frame` conversions are shown below: ```{r} m <- matrix(1:6, nrow = 2) cat(to_json(m)) ``` ```{r} df <- data.frame(a = 1:3, b = c("x", "y", "z")) cat(to_json(df)) ``` Note that the `to_json()` function operates by converting R objects to their JS equivalents, and then calling `JSON.stringify()` on the result. This allows you to explore how different types are being converted to JS. ### Functions and Closures Functions and closures can be passed between R and JS code. In JS, functions are represented as `Function` objects, and can be called directly from JS code. ```{r} ctx <- JSContext$new() ctx$source(code = "function callRFunction(f, x, y) { return f(x, y); }") ctx$call("callRFunction", function(x, y) x + y, 1, 2) ctx$call("callRFunction", function(x, y) paste0(x, ",", y), "a", "b") ``` ## Working with R Environments R environments are represented in JS as a custom class: `REnv`. The `REnv` class simply wraps the pointer to the R environment, and provides methods for getting and setting values - this means that there is only a 'cost' for conversion when values or accessed or updated. Environment values can be accessed using either `env.value` or `env["value"]` syntax: ```{r} ctx$source(code = 'function env_test(env) { return env.a + env["b"]; }') env <- new.env() env$a <- 1 env$b <- 2 ctx$call("env_test", env) ``` Values in the environment can also be updated from JS code: ```{r} ctx$source(code = "function env_update(env) { env.a = 10; env.b = 20; }") ctx$call("env_update", env) env$a env$b ``` ## Accessing Package Namespaces & Functions `QuickJSR` automatically adds a global object `R` to each context, which can be used to access the namespaces of installed packages - and subsequently extract and use functions and objects from them. ```{r} qjs_eval('R.package("base").getwd()') ```QuickJSR/src/0000755000176200001440000000000015135347454012507 5ustar liggesusersQuickJSR/src/include/0000755000176200001440000000000015122664674014134 5ustar liggesusersQuickJSR/src/include/quickjs_helpers.hpp0000644000176200001440000000651015122664674020042 0ustar liggesusers#ifndef QUICKJS_HELPERS_HPP #define QUICKJS_HELPERS_HPP #include #include #include /** * These functions were adapted from the qjs.c file in the QuickJS source code. */ extern "C" int js__has_suffix(const char *str, const char *suffix); #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif namespace quickjsr { static int eval_buf(JSContext *ctx, const char* buf, int buf_len, const char *filename, int eval_flags) { JSValue val; int ret; if ((eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_MODULE) { /* for the modules, we compile then run to be able to set import.meta */ val = JS_Eval(ctx, buf, buf_len, filename, eval_flags | JS_EVAL_FLAG_COMPILE_ONLY); if (!JS_IsException(val)) { js_module_set_import_meta(ctx, val, TRUE, TRUE); val = JS_EvalFunction(ctx, val); } } else { val = JS_Eval(ctx, buf, buf_len, filename, eval_flags); } if (JS_IsException(val)) { js_std_dump_error(ctx); ret = -1; } else { ret = 0; } JS_FreeValue(ctx, val); return ret; } static int eval_file(JSContext *ctx, const char *filename, int module) { const char* buf; int ret, eval_flags; size_t buf_len; buf = (const char*)js_load_file(ctx, &buf_len, filename); if (!buf) { cpp11::stop("Could not load '%s'\n", filename); } if (module < 0) { module = js__has_suffix(filename, ".mjs"); } if (module) { eval_flags = JS_EVAL_TYPE_MODULE; } else { eval_flags = JS_EVAL_TYPE_GLOBAL; } ret = eval_buf(ctx, buf, buf_len, "", eval_flags); js_free(ctx, (void*)buf); return ret; } /* also used to initialize the worker context */ static JSContext* JS_NewCustomContext(JSRuntime *rt) { JSContext *ctx; ctx = JS_NewContext(rt); if (!ctx){ return NULL; } /* system modules */ js_init_module_std(ctx, "std"); js_init_module_os(ctx, "os"); JSValue proto = JS_NewObject(ctx); JS_SetClassProto(ctx, quickjsr::js_renv_class_id, proto); JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL); js_init_module_os(ctx, "os"); js_init_module_std(ctx, "std"); js_std_add_helpers(ctx, 0, (char**)""); const char *str = "import * as std from 'std';\n" "import * as os from 'os';\n" "globalThis.std = std;\n" "globalThis.os = os;\n"; eval_buf(ctx, str, strlen(str), "", JS_EVAL_TYPE_MODULE); JSValue global_obj = JS_GetGlobalObject(ctx); JSValue r_obj = quickjsr::create_r_object(ctx); JS_SetPropertyStr(ctx, global_obj, "R", r_obj); JS_FreeValue(ctx, global_obj); return ctx; } JSRuntime* JS_NewCustomRuntime(int stack_size) { JSRuntime *rt; rt = JS_NewRuntime(); if (!rt){ return NULL; } if (stack_size != -1) { JS_SetMaxStackSize(rt, stack_size); } js_std_set_worker_new_context_func(JS_NewCustomContext); js_std_init_handlers(rt); // Initialise a class which can be used for passing SEXP objects to JS // without needing conversion JS_NewClass(rt, quickjsr::js_sexp_class_id, &quickjsr::js_sexp_class_def); JS_NewClass(rt, quickjsr::js_renv_class_id, &quickjsr::js_renv_class_def); return rt; } } #endif QuickJSR/src/include/cpp11/0000755000176200001440000000000015135354472015054 5ustar liggesusersQuickJSR/src/include/cpp11/R.hpp0000644000176200001440000000641115122664674015774 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #ifdef R_INTERNALS_H_ #if !(defined(R_NO_REMAP) && defined(STRICT_R_HEADERS)) #error R headers were included before cpp11 headers \ and at least one of R_NO_REMAP or STRICT_R_HEADERS \ was not defined. #endif #endif #ifndef R_NO_REMAP #define R_NO_REMAP #endif #ifndef STRICT_R_HEADERS #define STRICT_R_HEADERS #endif #include "R_ext/Boolean.h" #include "Rinternals.h" #include "Rversion.h" // clang-format off #ifdef __clang__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wattributes" #endif #ifdef __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wattributes" #endif // clang-format on #include #if defined(R_VERSION) && R_VERSION >= R_Version(4, 4, 0) // Use R's new macro #define CPP11_PRIdXLEN_T R_PRIdXLEN_T #else // Recreate what new R does #ifdef LONG_VECTOR_SUPPORT #define CPP11_PRIdXLEN_T "td" #else #define CPP11_PRIdXLEN_T "d" #endif #endif namespace cpp11 { namespace literals { constexpr R_xlen_t operator""_xl(unsigned long long int value) { return value; } } // namespace literals namespace traits { template struct get_underlying_type { using type = T; }; } // namespace traits namespace detail { // Annoyingly, `TYPEOF()` returns an `int` rather than a `SEXPTYPE`, // which can throw warnings with `-Wsign-compare` on Windows. inline SEXPTYPE r_typeof(SEXP x) { return static_cast(TYPEOF(x)); } /// Get an object from an environment /// /// SAFETY: Keep as a pure C function. Call like an R API function, i.e. wrap in `safe[]` /// as required. inline SEXP r_env_get(SEXP env, SEXP sym) { #if defined(R_VERSION) && R_VERSION >= R_Version(4, 5, 0) const Rboolean inherits = FALSE; return R_getVar(sym, env, inherits); #else SEXP out = Rf_findVarInFrame3(env, sym, TRUE); // Replicate the 3 checks from `R_getVar()` (along with exact error message): // - Object must be found in the `env` // - `R_MissingArg` can't leak from an `env` anymore // - Promises can't leak from an `env` anymore if (out == R_MissingArg) { Rf_errorcall(R_NilValue, "argument \"%s\" is missing, with no default", CHAR(PRINTNAME(sym))); } if (out == R_UnboundValue) { Rf_errorcall(R_NilValue, "object '%s' not found", CHAR(PRINTNAME(sym))); } if (r_typeof(out) == PROMSXP) { PROTECT(out); out = Rf_eval(out, env); UNPROTECT(1); } return out; #endif } /// Check if an object exists in an environment /// /// SAFETY: Keep as a pure C function. Call like an R API function, i.e. wrap in `safe[]` /// as required. inline bool r_env_has(SEXP env, SEXP sym) { #if R_VERSION >= R_Version(4, 2, 0) return R_existsVarInFrame(env, sym); #else return Rf_findVarInFrame3(env, sym, FALSE) != R_UnboundValue; #endif } } // namespace detail template inline T na(); template inline typename std::enable_if::type, double>::value, bool>::type is_na(const T& value) { return value == na(); } template inline typename std::enable_if::type, double>::value, bool>::type is_na(const T& value) { return ISNA(value); } } // namespace cpp11 QuickJSR/src/include/cpp11/integers.hpp0000644000176200001440000000552315122664674017416 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for min #include // for array #include // for initializer_list #include "R_ext/Arith.h" // for NA_INTEGER #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_allocVector #include "cpp11/as.hpp" // for as_sexp #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/protect.hpp" // for safe #include "cpp11/r_vector.hpp" // for r_vector, r_vector<>::proxy #include "cpp11/sexp.hpp" // for sexp // Specializations for integers namespace cpp11 { template <> inline SEXPTYPE r_vector::get_sexptype() { return INTSXP; } template <> inline typename r_vector::underlying_type r_vector::get_elt(SEXP x, R_xlen_t i) { // NOPROTECT: likely too costly to unwind protect every elt return INTEGER_ELT(x, i); } template <> inline typename r_vector::underlying_type* r_vector::get_p(bool is_altrep, SEXP data) { if (is_altrep) { return nullptr; } else { return INTEGER(data); } } template <> inline typename r_vector::underlying_type const* r_vector::get_const_p( bool is_altrep, SEXP data) { return INTEGER_OR_NULL(data); } template <> inline void r_vector::get_region(SEXP x, R_xlen_t i, R_xlen_t n, typename r_vector::underlying_type* buf) { // NOPROTECT: likely too costly to unwind protect here INTEGER_GET_REGION(x, i, n, buf); } template <> inline bool r_vector::const_iterator::use_buf(bool is_altrep) { return is_altrep; } typedef r_vector integers; namespace writable { template <> inline void r_vector::set_elt(SEXP x, R_xlen_t i, typename r_vector::underlying_type value) { // NOPROTECT: Likely too costly to unwind protect every set elt SET_INTEGER_ELT(x, i, value); } typedef r_vector integers; } // namespace writable template <> inline int na() { return NA_INTEGER; } // forward declaration typedef r_vector doubles; inline integers as_integers(SEXP x) { if (detail::r_typeof(x) == INTSXP) { return integers(x); } else if (detail::r_typeof(x) == REALSXP) { doubles xn(x); writable::integers ret(xn.size()); std::transform(xn.begin(), xn.end(), ret.begin(), [](double value) { if (ISNA(value)) { return NA_INTEGER; } if (!is_convertible_without_loss_to_integer(value)) { throw std::runtime_error("All elements must be integer-like"); } return static_cast(value); }); return ret; } throw type_error(INTSXP, detail::r_typeof(x)); } } // namespace cpp11 QuickJSR/src/include/cpp11/named_arg.hpp0000644000176200001440000000207015122664674017505 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for size_t #include // for initializer_list #include "cpp11/R.hpp" // for SEXP, SEXPREC, literals #include "cpp11/as.hpp" // for as_sexp #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { class named_arg { public: explicit named_arg(const char* name) : name_(name), value_(R_NilValue) {} named_arg& operator=(std::initializer_list il) { value_ = as_sexp(il); return *this; } template named_arg& operator=(T rhs) { value_ = as_sexp(rhs); return *this; } template named_arg& operator=(std::initializer_list rhs) { value_ = as_sexp(rhs); return *this; } const char* name() const { return name_; } SEXP value() const { return value_; } private: const char* name_; sexp value_; }; namespace literals { inline named_arg operator""_nm(const char* name, std::size_t) { return named_arg(name); } } // namespace literals using namespace literals; } // namespace cpp11 QuickJSR/src/include/cpp11/list.hpp0000644000176200001440000000601615122664674016547 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for initializer_list #include "cpp11/R.hpp" // for SEXP, SEXPREC, SET_VECTOR_ELT #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/protect.hpp" // for safe #include "cpp11/r_string.hpp" // for r_string #include "cpp11/r_vector.hpp" // for r_vector, r_vector<>::proxy #include "cpp11/sexp.hpp" // for sexp // Specializations for list namespace cpp11 { template <> inline SEXPTYPE r_vector::get_sexptype() { return VECSXP; } template <> inline typename r_vector::underlying_type r_vector::get_elt(SEXP x, R_xlen_t i) { // NOPROTECT: likely too costly to unwind protect every elt return VECTOR_ELT(x, i); } template <> inline typename r_vector::underlying_type* r_vector::get_p(bool, SEXP) { return nullptr; } template <> inline typename r_vector::underlying_type const* r_vector::get_const_p( bool is_altrep, SEXP data) { // No `VECTOR_PTR_OR_NULL()` if (is_altrep) { return nullptr; } else { // TODO: Use `VECTOR_PTR_RO()` conditionally once R 4.5.0 is officially released return static_cast(DATAPTR_RO(data)); } } /// Specialization for lists, where `x["oob"]` returns `R_NilValue`, like at the R level template <> inline SEXP r_vector::get_oob() { return R_NilValue; } template <> inline void r_vector::get_region(SEXP x, R_xlen_t i, R_xlen_t n, typename r_vector::underlying_type* buf) { cpp11::stop("Unreachable!"); } template <> inline bool r_vector::const_iterator::use_buf(bool is_altrep) { return false; } typedef r_vector list; namespace writable { template <> inline void r_vector::set_elt(SEXP x, R_xlen_t i, typename r_vector::underlying_type value) { // NOPROTECT: Likely too costly to unwind protect every set elt SET_VECTOR_ELT(x, i, value); } // Requires specialization to handle the fact that, for lists, each element of the // initializer list is considered the scalar "element", i.e. we don't expect that // each `named_arg` contains a list of length 1, like we do for the other vector types. // This means we don't need type checks, length 1 checks, or `get_elt()` for lists. template <> inline r_vector::r_vector(std::initializer_list il) : cpp11::r_vector(safe[Rf_allocVector](VECSXP, il.size())), capacity_(il.size()) { unwind_protect([&] { SEXP names = Rf_allocVector(STRSXP, capacity_); Rf_setAttrib(data_, R_NamesSymbol, names); auto it = il.begin(); for (R_xlen_t i = 0; i < capacity_; ++i, ++it) { SEXP elt = it->value(); set_elt(data_, i, elt); SEXP name = Rf_mkCharCE(it->name(), CE_UTF8); SET_STRING_ELT(names, i, name); } }); } typedef r_vector list; } // namespace writable } // namespace cpp11 QuickJSR/src/include/cpp11/data_frame.hpp0000644000176200001440000000640515122664674017661 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for abs #include #include // for initializer_list #include // for string, basic_string #include // for move #include "R_ext/Arith.h" // for NA_INTEGER #include "cpp11/R.hpp" // for Rf_xlength, SEXP, SEXPREC, INTEGER #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/list.hpp" // for list, r_vector<>::r_vector, r_v... #include "cpp11/r_vector.hpp" // for r_vector namespace cpp11 { class named_arg; namespace writable { class data_frame; } // namespace writable class data_frame : public list { using list::list; friend class writable::data_frame; /* we cannot use Rf_getAttrib because it has a special case for c(NA, -n) and creates * the full vector */ static SEXP get_attrib0(SEXP x, SEXP sym) { for (SEXP attr = ATTRIB(x); attr != R_NilValue; attr = CDR(attr)) { if (TAG(attr) == sym) { return CAR(attr); } } return R_NilValue; } static R_xlen_t calc_nrow(SEXP x) { auto nms = get_attrib0(x, R_RowNamesSymbol); bool has_short_rownames = (Rf_isInteger(nms) && Rf_xlength(nms) == 2 && INTEGER(nms)[0] == NA_INTEGER); if (has_short_rownames) { return static_cast(abs(INTEGER(nms)[1])); } if (!Rf_isNull(nms)) { return Rf_xlength(nms); } if (Rf_xlength(x) == 0) { return 0; } return Rf_xlength(VECTOR_ELT(x, 0)); } public: /* Adapted from * https://github.com/wch/r-source/blob/f2a0dfab3e26fb42b8b296fcba40cbdbdbec767d/src/main/attrib.c#L198-L207 */ R_xlen_t nrow() const { return calc_nrow(*this); } R_xlen_t ncol() const { return size(); } }; namespace writable { class data_frame : public cpp11::data_frame { private: writable::list set_data_frame_attributes(writable::list&& x) { return set_data_frame_attributes(std::move(x), calc_nrow(x)); } writable::list set_data_frame_attributes(writable::list&& x, R_xlen_t nrow) { x.attr(R_RowNamesSymbol) = {NA_INTEGER, -static_cast(nrow)}; x.attr(R_ClassSymbol) = "data.frame"; return std::move(x); } public: data_frame(const SEXP data) : cpp11::data_frame(set_data_frame_attributes(data)) {} data_frame(const SEXP data, bool is_altrep) : cpp11::data_frame(set_data_frame_attributes(data), is_altrep) {} data_frame(const SEXP data, bool is_altrep, R_xlen_t nrow) : cpp11::data_frame(set_data_frame_attributes(data, nrow), is_altrep) {} data_frame(std::initializer_list il) : cpp11::data_frame(set_data_frame_attributes(writable::list(il))) {} data_frame(std::initializer_list il) : cpp11::data_frame(set_data_frame_attributes(writable::list(il))) {} using cpp11::data_frame::ncol; using cpp11::data_frame::nrow; attribute_proxy attr(const char* name) const { return {*this, name}; } attribute_proxy attr(const std::string& name) const { return {*this, name.c_str()}; } attribute_proxy attr(SEXP name) const { return {*this, name}; } attribute_proxy names() const { return {*this, R_NamesSymbol}; } }; } // namespace writable } // namespace cpp11 QuickJSR/src/include/cpp11/logicals.hpp0000644000176200001440000000440415122664674017370 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for min #include // for array #include // for initializer_list #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_all... #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/protect.hpp" // for safe #include "cpp11/r_bool.hpp" // for r_bool #include "cpp11/r_vector.hpp" // for r_vector, r_vector<>::proxy #include "cpp11/sexp.hpp" // for sexp // Specializations for logicals namespace cpp11 { template <> inline SEXPTYPE r_vector::get_sexptype() { return LGLSXP; } template <> inline typename r_vector::underlying_type r_vector::get_elt(SEXP x, R_xlen_t i) { // NOPROTECT: likely too costly to unwind protect every elt return LOGICAL_ELT(x, i); } template <> inline typename r_vector::underlying_type* r_vector::get_p(bool is_altrep, SEXP data) { if (is_altrep) { return nullptr; } else { return LOGICAL(data); } } template <> inline typename r_vector::underlying_type const* r_vector::get_const_p( bool is_altrep, SEXP data) { return LOGICAL_OR_NULL(data); } template <> inline void r_vector::get_region(SEXP x, R_xlen_t i, R_xlen_t n, typename r_vector::underlying_type* buf) { // NOPROTECT: likely too costly to unwind protect here LOGICAL_GET_REGION(x, i, n, buf); } template <> inline bool r_vector::const_iterator::use_buf(bool is_altrep) { return is_altrep; } typedef r_vector logicals; namespace writable { template <> inline void r_vector::set_elt(SEXP x, R_xlen_t i, typename r_vector::underlying_type value) { // NOPROTECT: Likely too costly to unwind protect every set elt SET_LOGICAL_ELT(x, i, value); } inline bool operator==(const r_vector::proxy& lhs, r_bool rhs) { return static_cast(lhs).operator==(rhs); } typedef r_vector logicals; } // namespace writable } // namespace cpp11 QuickJSR/src/include/cpp11/function.hpp0000644000176200001440000000761015122664674017422 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for strcmp #include // for snprintf #include // for string, basic_string #include // for forward #include "cpp11/R.hpp" // for SEXP, SEXPREC, CDR, Rf_install, SETCAR #include "cpp11/as.hpp" // for as_sexp #include "cpp11/named_arg.hpp" // for named_arg #include "cpp11/protect.hpp" // for protect, protect::function, safe #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { class function { public: function(SEXP data) : data_(data) {} template sexp operator()(Args&&... args) const { // Size of the arguments plus one for the function name itself R_xlen_t num_args = sizeof...(args) + 1; sexp call(safe[Rf_allocVector](LANGSXP, num_args)); construct_call(call, data_, std::forward(args)...); return safe[Rf_eval](call, R_GlobalEnv); } private: sexp data_; template void construct_call(SEXP val, const named_arg& arg, Args&&... args) const { SETCAR(val, arg.value()); SET_TAG(val, safe[Rf_install](arg.name())); val = CDR(val); construct_call(val, std::forward(args)...); } // Construct the call recursively, each iteration adds an Arg to the pairlist. template void construct_call(SEXP val, const T& arg, Args&&... args) const { SETCAR(val, as_sexp(arg)); val = CDR(val); construct_call(val, std::forward(args)...); } // Base case, just return void construct_call(SEXP val) const {} }; class package { public: package(const char* name) : data_(get_namespace(name)) {} package(const std::string& name) : data_(get_namespace(name.c_str())) {} function operator[](const char* name) { return safe[Rf_findFun](safe[Rf_install](name), data_); } function operator[](const std::string& name) { return operator[](name.c_str()); } private: static SEXP get_namespace(const char* name) { if (strcmp(name, "base") == 0) { return R_BaseEnv; } sexp name_sexp = safe[Rf_install](name); return safe[detail::r_env_get](R_NamespaceRegistry, name_sexp); } // Either base env or in namespace registry, so no protection needed SEXP data_; }; namespace detail { // Special internal way to call `base::message()` // // - Pure C, so call with `safe[]` // - Holds a `static SEXP` for the `base::message` function protected with // `R_PreserveObject()` // // We don't use a `static cpp11::function` because that will infinitely retain a cell in // our preserve list, which can throw off our counts in the preserve list tests. inline void r_message(const char* x) { static SEXP fn = NULL; if (fn == NULL) { fn = Rf_findFun(Rf_install("message"), R_BaseEnv); R_PreserveObject(fn); } SEXP x_char = PROTECT(Rf_mkCharCE(x, CE_UTF8)); SEXP x_string = PROTECT(Rf_ScalarString(x_char)); SEXP call = PROTECT(Rf_lang2(fn, x_string)); Rf_eval(call, R_GlobalEnv); UNPROTECT(3); } } // namespace detail inline void message(const char* fmt_arg) { #ifdef CPP11_USE_FMT std::string msg = fmt::format(fmt_arg); safe[detail::r_message](msg.c_str()); #else char buff[1024]; int msg; msg = std::snprintf(buff, 1024, "%s", fmt_arg); if (msg >= 0 && msg < 1024) { safe[detail::r_message](buff); } #endif } template void message(const char* fmt_arg, Args... args) { #ifdef CPP11_USE_FMT std::string msg = fmt::format(fmt_arg, args...); safe[detail::r_message](msg.c_str()); #else char buff[1024]; int msg; msg = std::snprintf(buff, 1024, fmt_arg, args...); if (msg >= 0 && msg < 1024) { safe[detail::r_message](buff); } #endif } inline void message(const std::string& fmt_arg) { message(fmt_arg.c_str()); } template void message(const std::string& fmt_arg, Args... args) { message(fmt_arg.c_str(), args...); } } // namespace cpp11 QuickJSR/src/include/cpp11/list_of.hpp0000644000176200001440000000402115122664674017225 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for string, basic_string #include "cpp11/R.hpp" // for R_xlen_t, SEXP, SEXPREC, LONG_VECTOR_SUPPORT #include "cpp11/list.hpp" // for list namespace cpp11 { template class list_of : public list { public: list_of(const list& data) : list(data) {} #ifdef LONG_VECTOR_SUPPORT T operator[](const int pos) const { return operator[](static_cast(pos)); } #endif T operator[](const R_xlen_t pos) const { return list::operator[](pos); } T operator[](const char* pos) const { return list::operator[](pos); } T operator[](const std::string& pos) const { return list::operator[](pos.c_str()); } }; namespace writable { template class list_of : public writable::list { public: list_of(const list& data) : writable::list(data) {} list_of(R_xlen_t n) : writable::list(n) {} class proxy { private: writable::list::proxy data_; public: proxy(const writable::list::proxy& data) : data_(data) {} operator T() const { return static_cast(*this); } operator SEXP() const { return static_cast(data_); } #ifdef LONG_VECTOR_SUPPORT typename T::proxy operator[](int pos) { return static_cast(data_)[pos]; } #endif typename T::proxy operator[](R_xlen_t pos) { return static_cast(data_)[pos]; } proxy operator[](const char* pos) { static_cast(data_)[pos]; } proxy operator[](const std::string& pos) { return static_cast(data_)[pos]; } proxy& operator=(const T& rhs) { data_ = rhs; return *this; } }; #ifdef LONG_VECTOR_SUPPORT proxy operator[](int pos) { return {writable::list::operator[](static_cast(pos))}; } #endif proxy operator[](R_xlen_t pos) { return writable::list::operator[](pos); } proxy operator[](const char* pos) { return {writable::list::operator[](pos)}; } proxy operator[](const std::string& pos) { return writable::list::operator[](pos.c_str()); } }; } // namespace writable } // namespace cpp11 QuickJSR/src/include/cpp11/r_string.hpp0000644000176200001440000000515115122664674017422 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for string, basic_string, operator== #include // for is_convertible, enable_if #include "R_ext/Memory.h" // for vmaxget, vmaxset #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_mkCharCE, Rf_translat... #include "cpp11/as.hpp" // for as_sexp #include "cpp11/protect.hpp" // for unwind_protect, protect, protect::function #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { class r_string { public: r_string() = default; r_string(SEXP data) : data_(data) {} r_string(const char* data) : data_(safe[Rf_mkCharCE](data, CE_UTF8)) {} r_string(const std::string& data) : data_(safe[Rf_mkCharLenCE](data.c_str(), data.size(), CE_UTF8)) {} operator SEXP() const { return data_; } operator sexp() const { return data_; } operator std::string() const { std::string res; res.reserve(size()); void* vmax = vmaxget(); unwind_protect([&] { res.assign(Rf_translateCharUTF8(data_)); }); vmaxset(vmax); return res; } bool operator==(const r_string& rhs) const { return data_.data() == rhs.data_.data(); } bool operator==(const SEXP rhs) const { return data_.data() == rhs; } bool operator==(const char* rhs) const { return static_cast(*this) == rhs; } bool operator==(const std::string& rhs) const { return static_cast(*this) == rhs; } R_xlen_t size() const { return Rf_xlength(data_); } private: sexp data_ = R_NilValue; }; inline SEXP as_sexp(std::initializer_list il) { R_xlen_t size = il.size(); sexp data; unwind_protect([&] { data = Rf_allocVector(STRSXP, size); auto it = il.begin(); for (R_xlen_t i = 0; i < size; ++i, ++it) { if (*it == NA_STRING) { SET_STRING_ELT(data, i, *it); } else { SET_STRING_ELT(data, i, Rf_mkCharCE(Rf_translateCharUTF8(*it), CE_UTF8)); } } }); return data; } template using enable_if_r_string = enable_if_t::value, R>; template enable_if_r_string as_sexp(T from) { r_string str(from); sexp res; unwind_protect([&] { res = Rf_allocVector(STRSXP, 1); if (str == NA_STRING) { SET_STRING_ELT(res, 0, str); } else { SET_STRING_ELT(res, 0, Rf_mkCharCE(Rf_translateCharUTF8(str), CE_UTF8)); } }); return res; } template <> inline r_string na() { return NA_STRING; } namespace traits { template <> struct get_underlying_type { using type = SEXP; }; } // namespace traits } // namespace cpp11 QuickJSR/src/include/cpp11/attribute_proxy.hpp0000644000176200001440000000251115122664674021034 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for initializer_list #include // for string, basic_string #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_install, PROTECT, Rf_... #include "cpp11/as.hpp" // for as_sexp #include "cpp11/protect.hpp" // for protect, safe, protect::function namespace cpp11 { class sexp; template class attribute_proxy { private: const T& parent_; SEXP symbol_; public: attribute_proxy(const T& parent, const char* index) : parent_(parent), symbol_(safe[Rf_install](index)) {} attribute_proxy(const T& parent, const std::string& index) : parent_(parent), symbol_(safe[Rf_install](index.c_str())) {} attribute_proxy(const T& parent, SEXP index) : parent_(parent), symbol_(index) {} template attribute_proxy& operator=(C rhs) { SEXP value = PROTECT(as_sexp(rhs)); Rf_setAttrib(parent_.data(), symbol_, value); UNPROTECT(1); return *this; } template attribute_proxy& operator=(std::initializer_list rhs) { SEXP value = PROTECT(as_sexp(rhs)); Rf_setAttrib(parent_.data(), symbol_, value); UNPROTECT(1); return *this; } operator SEXP() const { return safe[Rf_getAttrib](parent_.data(), symbol_); } }; } // namespace cpp11 QuickJSR/src/include/cpp11/doubles.hpp0000644000176200001440000000517415122664674017235 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for min, tranform #include // for array #include // for initializer_list #include "R_ext/Arith.h" // for ISNA #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_allocVector, REAL #include "cpp11/as.hpp" // for as_sexp #include "cpp11/protect.hpp" // for safe #include "cpp11/r_vector.hpp" // for vector, vector<>::proxy, vector<>::... #include "cpp11/sexp.hpp" // for sexp // Specializations for doubles namespace cpp11 { template <> inline SEXPTYPE r_vector::get_sexptype() { return REALSXP; } template <> inline typename r_vector::underlying_type r_vector::get_elt(SEXP x, R_xlen_t i) { // NOPROTECT: likely too costly to unwind protect every elt return REAL_ELT(x, i); } template <> inline typename r_vector::underlying_type* r_vector::get_p(bool is_altrep, SEXP data) { if (is_altrep) { return nullptr; } else { return REAL(data); } } template <> inline typename r_vector::underlying_type const* r_vector::get_const_p( bool is_altrep, SEXP data) { return REAL_OR_NULL(data); } template <> inline void r_vector::get_region(SEXP x, R_xlen_t i, R_xlen_t n, typename r_vector::underlying_type* buf) { // NOPROTECT: likely too costly to unwind protect here REAL_GET_REGION(x, i, n, buf); } template <> inline bool r_vector::const_iterator::use_buf(bool is_altrep) { return is_altrep; } typedef r_vector doubles; namespace writable { template <> inline void r_vector::set_elt(SEXP x, R_xlen_t i, typename r_vector::underlying_type value) { // NOPROTECT: Likely too costly to unwind protect every set elt SET_REAL_ELT(x, i, value); } typedef r_vector doubles; } // namespace writable typedef r_vector integers; inline doubles as_doubles(SEXP x) { if (detail::r_typeof(x) == REALSXP) { return doubles(x); } else if (detail::r_typeof(x) == INTSXP) { integers xn(x); size_t len = xn.size(); writable::doubles ret(len); std::transform(xn.begin(), xn.end(), ret.begin(), [](int value) { return value == NA_INTEGER ? NA_REAL : static_cast(value); }); return ret; } throw type_error(REALSXP, detail::r_typeof(x)); } template <> inline double na() { return NA_REAL; } } // namespace cpp11 QuickJSR/src/include/cpp11/external_pointer.hpp0000644000176200001440000001027115122664674021154 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for nullptr_t, NULL #include // for bad_weak_ptr #include // for add_lvalue_reference #include "cpp11/R.hpp" // for SEXP, SEXPREC, R_NilValue #include "cpp11/protect.hpp" // for protect, safe, protect::function #include "cpp11/r_bool.hpp" // for r_bool #include "cpp11/r_vector.hpp" // for type_error #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { template void default_deleter(T* obj) { delete obj; } template > class external_pointer { private: sexp data_ = R_NilValue; static SEXP valid_type(SEXP data) { if (data == nullptr) { throw type_error(EXTPTRSXP, NILSXP); } if (detail::r_typeof(data) != EXTPTRSXP) { throw type_error(EXTPTRSXP, detail::r_typeof(data)); } return data; } static void r_deleter(SEXP p) { if (detail::r_typeof(p) != EXTPTRSXP) return; T* ptr = static_cast(R_ExternalPtrAddr(p)); if (ptr == NULL) { return; } R_ClearExternalPtr(p); Deleter(ptr); } public: using pointer = T*; external_pointer() noexcept {} external_pointer(std::nullptr_t) noexcept {} external_pointer(SEXP data) : data_(valid_type(data)) {} external_pointer(pointer p, bool use_deleter = true, bool finalize_on_exit = true) : data_(safe[R_MakeExternalPtr]((void*)p, R_NilValue, R_NilValue)) { if (use_deleter) { R_RegisterCFinalizerEx(data_, r_deleter, static_cast(finalize_on_exit)); } } external_pointer(const external_pointer& rhs) { data_ = safe[Rf_shallow_duplicate](rhs.data_); } external_pointer(external_pointer&& rhs) { reset(rhs.release()); } external_pointer& operator=(external_pointer&& rhs) noexcept { reset(rhs.release()); } external_pointer& operator=(std::nullptr_t) noexcept { reset(); }; operator SEXP() const noexcept { return data_; } pointer get() const noexcept { pointer addr = static_cast(R_ExternalPtrAddr(data_)); if (addr == nullptr) { return nullptr; } return addr; } typename std::add_lvalue_reference::type operator*() { pointer addr = get(); if (addr == nullptr) { throw std::bad_weak_ptr(); } return *get(); } pointer operator->() const { pointer addr = get(); if (addr == nullptr) { throw std::bad_weak_ptr(); } return get(); } pointer release() noexcept { if (get() == nullptr) { return nullptr; } pointer ptr = get(); R_ClearExternalPtr(data_); return ptr; } void reset(pointer ptr = pointer()) { SEXP old_data = data_; data_ = safe[R_MakeExternalPtr]((void*)ptr, R_NilValue, R_NilValue); r_deleter(old_data); } void swap(external_pointer& other) noexcept { SEXP tmp = other.data_; other.data_ = data_; data_ = tmp; } operator bool() noexcept { return data_ != nullptr; } }; template void swap(external_pointer& lhs, external_pointer& rhs) noexcept { lhs.swap(rhs); } template bool operator==(const external_pointer& x, const external_pointer& y) { return x.data_ == y.data_; } template bool operator!=(const external_pointer& x, const external_pointer& y) { return x.data_ != y.data_; } template bool operator<(const external_pointer& x, const external_pointer& y) { return x.data_ < y.data_; } template bool operator<=(const external_pointer& x, const external_pointer& y) { return x.data_ <= y.data_; } template bool operator>(const external_pointer& x, const external_pointer& y) { return x.data_ > y.data_; } template bool operator>=(const external_pointer& x, const external_pointer& y) { return x.data_ >= y.data_; } } // namespace cpp11 QuickJSR/src/include/cpp11/protect.hpp0000644000176200001440000002512315122664674017254 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for longjmp, setjmp, jmp_buf #include // for exception #include // for std::runtime_error #include // for string, basic_string #include // for tuple, make_tuple // NB: cpp11/R.hpp must precede R_ext/Error.h to ensure R_NO_REMAP is defined #include "cpp11/R.hpp" // for SEXP, SEXPREC, CDR, R_NilValue, CAR, R_Pres... #include "R_ext/Boolean.h" // for Rboolean #include "R_ext/Error.h" // for Rf_error, Rf_warning #include "R_ext/Print.h" // for REprintf #include "R_ext/Utils.h" // for R_CheckUserInterrupt // We would like to remove this, since all supported versions of R now support proper // unwind protect, but some groups rely on it existing, like arrow and systemfonts // https://github.com/r-lib/cpp11/issues/412 #define HAS_UNWIND_PROTECT #ifdef CPP11_USE_FMT #define FMT_HEADER_ONLY #include "fmt/core.h" #endif namespace cpp11 { class unwind_exception : public std::exception { public: SEXP token; unwind_exception(SEXP token_) : token(token_) {} }; /// Unwind Protection from C longjmp's, like those used in R error handling /// /// @param code The code to which needs to be protected, as a nullary callable template ()()), SEXP>::value>::type> SEXP unwind_protect(Fun&& code) { static SEXP token = [] { SEXP res = R_MakeUnwindCont(); R_PreserveObject(res); return res; }(); std::jmp_buf jmpbuf; if (setjmp(jmpbuf)) { throw unwind_exception(token); } SEXP res = R_UnwindProtect( [](void* data) -> SEXP { auto callback = static_cast(data); return static_cast(*callback)(); }, &code, [](void* jmpbuf, Rboolean jump) { if (jump == TRUE) { // We need to first jump back into the C++ stacks because you can't safely // throw exceptions from C stack frames. longjmp(*static_cast(jmpbuf), 1); } }, &jmpbuf, token); // R_UnwindProtect adds the result to the CAR of the continuation token, // which implicitly protects the result. However if there is no error and // R_UwindProtect does a normal exit the memory shouldn't be protected, so we // unset it here before returning the value ourselves. SETCAR(token, R_NilValue); return res; } template ()()), void>::value>::type> void unwind_protect(Fun&& code) { (void)unwind_protect([&] { std::forward(code)(); return R_NilValue; }); } template ()())> typename std::enable_if::value && !std::is_same::value, R>::type unwind_protect(Fun&& code) { R out; (void)unwind_protect([&] { out = std::forward(code)(); return R_NilValue; }); return out; } namespace detail { template struct index_sequence { using type = index_sequence; }; template struct appended_sequence; template struct appended_sequence, J> : index_sequence {}; template struct make_index_sequence : appended_sequence::type, N - 1> {}; template <> struct make_index_sequence<0> : index_sequence<> {}; template decltype(std::declval()(std::declval()...)) apply( F&& f, std::tuple&& a, const index_sequence&) { return std::forward(f)(std::get(std::move(a))...); } template decltype(std::declval()(std::declval()...)) apply(F&& f, std::tuple&& a) { return apply(std::forward(f), std::move(a), make_index_sequence{}); } // overload to silence a compiler warning that the (empty) tuple parameter is set but // unused template decltype(std::declval()()) apply(F&& f, std::tuple<>&&) { return std::forward(f)(); } template struct closure { decltype(std::declval()(std::declval()...)) operator()() && { return apply(ptr_, std::move(arefs_)); } F* ptr_; std::tuple arefs_; }; } // namespace detail struct protect { template struct function { template decltype(std::declval()(std::declval()...)) operator()(A&&... a) const { // workaround to support gcc4.8, which can't capture a parameter pack return unwind_protect( detail::closure{ptr_, std::forward_as_tuple(std::forward(a)...)}); } F* ptr_; }; /// May not be applied to a function bearing attributes, which interfere with linkage on /// some compilers; use an appropriately attributed alternative. (For example, Rf_error /// bears the [[noreturn]] attribute and must be protected with safe.noreturn rather /// than safe.operator[]). template constexpr function operator[](F* raw) const { return {raw}; } template struct noreturn_function { template void operator() [[noreturn]] (A&&... a) const { // workaround to support gcc4.8, which can't capture a parameter pack unwind_protect( detail::closure{ptr_, std::forward_as_tuple(std::forward(a)...)}); // Compiler hint to allow [[noreturn]] attribute; this is never executed since // the above call will not return. throw std::runtime_error("[[noreturn]]"); } F* ptr_; }; template constexpr noreturn_function noreturn(F* raw) const { return {raw}; } }; constexpr struct protect safe = {}; inline void check_user_interrupt() { safe[R_CheckUserInterrupt](); } #ifdef CPP11_USE_FMT template void stop [[noreturn]] (const char* fmt_arg, Args&&... args) { std::string msg = fmt::format(fmt_arg, std::forward(args)...); safe.noreturn(Rf_errorcall)(R_NilValue, "%s", msg.c_str()); } template void stop [[noreturn]] (const std::string& fmt_arg, Args&&... args) { std::string msg = fmt::format(fmt_arg, std::forward(args)...); safe.noreturn(Rf_errorcall)(R_NilValue, "%s", msg.c_str()); } template void warning(const char* fmt_arg, Args&&... args) { std::string msg = fmt::format(fmt_arg, std::forward(args)...); safe[Rf_warningcall](R_NilValue, "%s", msg.c_str()); } template void warning(const std::string& fmt_arg, Args&&... args) { std::string msg = fmt::format(fmt_arg, std::forward(args)...); safe[Rf_warningcall](R_NilValue, "%s", msg.c_str()); } #else template void stop [[noreturn]] (const char* fmt, Args... args) { safe.noreturn(Rf_errorcall)(R_NilValue, fmt, args...); } template void stop [[noreturn]] (const std::string& fmt, Args... args) { safe.noreturn(Rf_errorcall)(R_NilValue, fmt.c_str(), args...); } template void warning(const char* fmt, Args... args) { safe[Rf_warningcall](R_NilValue, fmt, args...); } template void warning(const std::string& fmt, Args... args) { safe[Rf_warningcall](R_NilValue, fmt.c_str(), args...); } #endif namespace detail { // A doubly-linked list of preserved objects, allowing O(1) insertion/release of objects // compared to O(N preserved) with `R_PreserveObject()` and `R_ReleaseObject()`. // // We let R manage the memory of the list itself by calling `R_PreserveObject()` on it. // // cpp11 being a header only library makes creating a "global" preserve list a bit tricky. // The trick we use here is that static local variables in inline extern functions are // guaranteed by the standard to be unique across the whole program. Inline functions are // extern by default, but `static inline` functions are not, so do not change these // functions to `static`. If we did that, we would end up having one preserve list per // compilation unit instead. As it stands today, we are fairly confident that we have 1 // preserve list per package, which seems to work nicely. // https://stackoverflow.com/questions/185624/what-happens-to-static-variables-in-inline-functions // https://stackoverflow.com/questions/51612866/global-variables-in-header-only-library // https://github.com/r-lib/cpp11/issues/330 // // > A static local variable in an extern inline function always refers to the // same object. 7.1.2/4 - C++98/C++14 (n3797) namespace store { inline SEXP init() { SEXP out = Rf_cons(R_NilValue, Rf_cons(R_NilValue, R_NilValue)); R_PreserveObject(out); return out; } inline SEXP get() { // Note the `static` local variable in the inline extern function here! Guarantees we // have 1 unique preserve list across all compilation units in the package. static SEXP out = init(); return out; } inline R_xlen_t count() { const R_xlen_t head = 1; const R_xlen_t tail = 1; SEXP list = get(); return Rf_xlength(list) - head - tail; } inline SEXP insert(SEXP x) { if (x == R_NilValue) { return R_NilValue; } PROTECT(x); SEXP list = get(); // Get references to the head of the preserve list and the next element // after the head SEXP head = list; SEXP next = CDR(list); // Add a new cell that points to the current head + next. SEXP cell = PROTECT(Rf_cons(head, next)); SET_TAG(cell, x); // Update the head + next to point at the newly-created cell, // effectively inserting that cell between the current head + next. SETCDR(head, cell); SETCAR(next, cell); UNPROTECT(2); return cell; } inline void release(SEXP cell) { if (cell == R_NilValue) { return; } // Get a reference to the cells before and after the token. SEXP lhs = CAR(cell); SEXP rhs = CDR(cell); // Remove the cell from the preserve list -- effectively, we do this // by updating the 'lhs' and 'rhs' references to point at each-other, // effectively removing any references to the cell in the pairlist. SETCDR(lhs, rhs); SETCAR(rhs, lhs); } inline void print() { SEXP list = get(); for (SEXP cell = list; cell != R_NilValue; cell = CDR(cell)) { REprintf("%p CAR: %p CDR: %p TAG: %p\n", reinterpret_cast(cell), reinterpret_cast(CAR(cell)), reinterpret_cast(CDR(cell)), reinterpret_cast(TAG(cell))); } REprintf("---\n"); } } // namespace store } // namespace detail } // namespace cpp11 QuickJSR/src/include/cpp11/altrep.hpp0000644000176200001440000000046015122664674017060 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once // It would be nice to remove this since all supported versions of R have ALTREP, but // some groups rely on both this `#define` and `altrep.hpp` itself existing, like arrow: // https://github.com/r-lib/cpp11/issues/413 #define HAS_ALTREP QuickJSR/src/include/cpp11/sexp.hpp0000644000176200001440000000417215122664674016554 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for size_t #include // for string, basic_string #include "cpp11/R.hpp" // for SEXP, SEXPREC, REAL_ELT, R_NilV... #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/protect.hpp" // for store namespace cpp11 { /// Converting to SEXP class sexp { private: SEXP data_ = R_NilValue; SEXP preserve_token_ = R_NilValue; public: sexp() = default; sexp(SEXP data) : data_(data), preserve_token_(detail::store::insert(data_)) {} // We maintain our own new `preserve_token_` sexp(const sexp& rhs) { data_ = rhs.data_; preserve_token_ = detail::store::insert(data_); } // We take ownership over the `rhs.preserve_token_`. // Importantly we clear it in the `rhs` so it can't release the object upon destruction. sexp(sexp&& rhs) { data_ = rhs.data_; preserve_token_ = rhs.preserve_token_; rhs.data_ = R_NilValue; rhs.preserve_token_ = R_NilValue; } sexp& operator=(const sexp& rhs) { detail::store::release(preserve_token_); data_ = rhs.data_; preserve_token_ = detail::store::insert(data_); return *this; } ~sexp() { detail::store::release(preserve_token_); } attribute_proxy attr(const char* name) const { return attribute_proxy(*this, name); } attribute_proxy attr(const std::string& name) const { return attribute_proxy(*this, name.c_str()); } attribute_proxy attr(SEXP name) const { return attribute_proxy(*this, name); } attribute_proxy names() const { return attribute_proxy(*this, R_NamesSymbol); } operator SEXP() const { return data_; } SEXP data() const { return data_; } /// DEPRECATED: Do not use this, it will be removed soon. operator double() const { return REAL_ELT(data_, 0); } /// DEPRECATED: Do not use this, it will be removed soon. operator size_t() const { return REAL_ELT(data_, 0); } /// DEPRECATED: Do not use this, it will be removed soon. operator bool() const { return LOGICAL_ELT(data_, 0); } }; } // namespace cpp11 QuickJSR/src/include/cpp11/declarations.hpp0000644000176200001440000000514415122664674020245 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include #include #include // Davis: From what I can tell, you'd only ever define this if you need to include // `declarations.hpp` manually in a file, i.e. to possibly use `BEGIN_CPP11` with a // custom `END_CPP11`, as textshaping does do. Otherwise, `declarations.hpp` is included // in `code.cpp` and should contain all of the cpp11 type definitions that the generated // function signatures need to link against. #ifndef CPP11_PARTIAL #include "cpp11.hpp" namespace writable = ::cpp11::writable; using namespace ::cpp11; #endif #include namespace cpp11 { // No longer used, but was previously used in `code.cpp` code generation in cpp11 0.1.0. // `code.cpp` could be generated with cpp11 0.1.0, but the package could be compiled with // cpp11 >0.1.0, so `unmove()` must exist in newer cpp11 too. Eventually remove this once // we decide enough time has gone by since `unmove()` was removed. // https://github.com/r-lib/cpp11/issues/88 // https://github.com/r-lib/cpp11/pull/75 template T& unmove(T&& t) { return t; } } // namespace cpp11 // We would like to remove this, since all supported versions of R now support proper // unwind protect, but some groups rely on it existing, like textshaping: // https://github.com/r-lib/cpp11/issues/414 #define CPP11_UNWIND R_ContinueUnwind(err); #define CPP11_ERROR_BUFSIZE 8192 #define BEGIN_CPP11 \ SEXP err = R_NilValue; \ char buf[CPP11_ERROR_BUFSIZE] = ""; \ try { #define END_CPP11 \ } \ catch (cpp11::unwind_exception & e) { \ err = e.token; \ } \ catch (std::exception & e) { \ strncpy(buf, e.what(), sizeof(buf) - 1); \ } \ catch (...) { \ strncpy(buf, "C++ error (unknown cause)", sizeof(buf) - 1); \ } \ if (buf[0] != '\0') { \ Rf_errorcall(R_NilValue, "%s", buf); \ } else if (err != R_NilValue) { \ R_ContinueUnwind(err); \ } \ return R_NilValue; QuickJSR/src/include/cpp11/environment.hpp0000644000176200001440000000375415122664674020146 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for string, basic_string #include "Rversion.h" // for R_VERSION, R_Version #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_install, r_env_get... #include "cpp11/as.hpp" // for as_sexp #include "cpp11/protect.hpp" // for protect, protect::function, safe, unwin... #include "cpp11/sexp.hpp" // for sexp #if R_VERSION >= R_Version(4, 0, 0) #define HAS_REMOVE_VAR_FROM_FRAME #endif #ifndef HAS_REMOVE_VAR_FROM_FRAME #include "cpp11/function.hpp" #endif namespace cpp11 { class environment { private: sexp env_; class proxy { SEXP parent_; SEXP name_; public: proxy(SEXP parent, SEXP name) : parent_(parent), name_(name) {} template proxy& operator=(T value) { safe[Rf_defineVar](name_, as_sexp(value), parent_); return *this; } operator SEXP() const { return safe[detail::r_env_get](parent_, name_); }; operator sexp() const { return SEXP(); }; }; public: environment(SEXP env) : env_(env) {} environment(sexp env) : env_(env) {} proxy operator[](const SEXP name) const { return {env_, name}; } proxy operator[](const char* name) const { return operator[](safe[Rf_install](name)); } proxy operator[](const std::string& name) const { return operator[](name.c_str()); } bool exists(SEXP name) const { return safe[detail::r_env_has](env_, name); } bool exists(const char* name) const { return exists(safe[Rf_install](name)); } bool exists(const std::string& name) const { return exists(name.c_str()); } void remove(SEXP name) { PROTECT(name); #ifdef HAS_REMOVE_VAR_FROM_FRAME R_removeVarFromFrame(name, env_); #else auto remove = package("base")["remove"]; remove(name, "envir"_nm = env_); #endif UNPROTECT(1); } void remove(const char* name) { remove(safe[Rf_install](name)); } R_xlen_t size() const { return Rf_xlength(env_); } operator SEXP() const { return env_; } }; } // namespace cpp11 QuickJSR/src/include/cpp11/r_vector.hpp0000644000176200001440000012127315122664674017422 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for ptrdiff_t, size_t #include // for max #include // for array #include // for snprintf #include // for memcpy #include // for exception #include // for initializer_list #include // for forward_iterator_tag, random_ac... #include // for out_of_range #include // for string, basic_string #include // for decay, is_same, enable_if, is_c... #include // for declval #include "cpp11/R.hpp" // for R_xlen_t, SEXP, SEXPREC, Rf_xle... #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/named_arg.hpp" // for named_arg #include "cpp11/protect.hpp" // for store #include "cpp11/r_string.hpp" // for r_string #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { using namespace cpp11::literals; namespace writable { template class r_vector; } // namespace writable // Declarations template class r_vector { public: // Forward declare class const_iterator; using underlying_type = typename traits::get_underlying_type::type; private: SEXP data_ = R_NilValue; SEXP protect_ = R_NilValue; bool is_altrep_ = false; underlying_type* data_p_ = nullptr; R_xlen_t length_ = 0; public: typedef ptrdiff_t difference_type; typedef size_t size_type; typedef T value_type; typedef T* pointer; typedef T& reference; ~r_vector(); r_vector() noexcept = default; r_vector(SEXP data); r_vector(SEXP data, bool is_altrep); r_vector(const r_vector& x); r_vector(r_vector&& x); r_vector(const writable::r_vector& x); r_vector(named_arg) = delete; r_vector& operator=(const r_vector& rhs); r_vector& operator=(r_vector&& rhs); operator SEXP() const; operator sexp() const; #ifdef LONG_VECTOR_SUPPORT T operator[](const int pos) const; #endif T operator[](const R_xlen_t pos) const; T operator[](const size_type pos) const; T operator[](const r_string& name) const; #ifdef LONG_VECTOR_SUPPORT T at(const int pos) const; #endif T at(const R_xlen_t pos) const; T at(const size_type pos) const; T at(const r_string& name) const; bool contains(const r_string& name) const; bool is_altrep() const; bool named() const; R_xlen_t size() const; bool empty() const; SEXP data() const; const sexp attr(const char* name) const; const sexp attr(const std::string& name) const; const sexp attr(SEXP name) const; r_vector names() const; const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; const_iterator find(const r_string& name) const; class const_iterator { // Iterator references: // https://cplusplus.com/reference/iterator/ // https://stackoverflow.com/questions/8054273/how-to-implement-an-stl-style-iterator-and-avoid-common-pitfalls // It seems like our iterator doesn't fully implement everything for // `random_access_iterator_tag` (like an `[]` operator, for example). If we discover // issues with it, we probably need to add more methods. private: const r_vector* data_; R_xlen_t pos_; std::array buf_; R_xlen_t block_start_ = 0; R_xlen_t length_ = 0; public: using difference_type = ptrdiff_t; using value_type = T; using pointer = T*; using reference = T&; using iterator_category = std::random_access_iterator_tag; const_iterator(const r_vector* data, R_xlen_t pos); const_iterator operator+(R_xlen_t pos); ptrdiff_t operator-(const const_iterator& other) const; const_iterator& operator++(); const_iterator& operator--(); const_iterator& operator+=(R_xlen_t pos); const_iterator& operator-=(R_xlen_t pos); bool operator!=(const const_iterator& other) const; bool operator==(const const_iterator& other) const; T operator*() const; friend class writable::r_vector::iterator; private: /// Implemented in specialization static bool use_buf(bool is_altrep); void fill_buf(R_xlen_t pos); }; private: /// Implemented in specialization static underlying_type get_elt(SEXP x, R_xlen_t i); /// Implemented in specialization static underlying_type* get_p(bool is_altrep, SEXP data); /// Implemented in specialization static underlying_type const* get_const_p(bool is_altrep, SEXP data); /// Implemented in specialization static void get_region(SEXP x, R_xlen_t i, R_xlen_t n, underlying_type* buf); /// Implemented in specialization static SEXPTYPE get_sexptype(); /// Implemented in specialization (throws by default, specialization in list type) static T get_oob(); static SEXP valid_type(SEXP x); static SEXP valid_length(SEXP x, R_xlen_t n); friend class writable::r_vector; }; namespace writable { template using has_begin_fun = std::decay()))>; /// Read/write access to new or copied r_vectors template class r_vector : public cpp11::r_vector { public: // Forward declare class proxy; class iterator; private: R_xlen_t capacity_ = 0; using cpp11::r_vector::data_; using cpp11::r_vector::data_p_; using cpp11::r_vector::is_altrep_; using cpp11::r_vector::length_; using cpp11::r_vector::protect_; using typename cpp11::r_vector::underlying_type; public: typedef ptrdiff_t difference_type; typedef size_t size_type; typedef proxy value_type; typedef proxy* pointer; typedef proxy& reference; r_vector() noexcept = default; r_vector(const SEXP& data); r_vector(SEXP&& data); r_vector(const SEXP& data, bool is_altrep); r_vector(SEXP&& data, bool is_altrep); r_vector(const r_vector& rhs); r_vector(r_vector&& rhs); r_vector(const cpp11::r_vector& rhs); r_vector(std::initializer_list il); r_vector(std::initializer_list il); explicit r_vector(const R_xlen_t size); template r_vector(Iter first, Iter last); template > r_vector(const V& obj); r_vector& operator=(const r_vector& rhs); r_vector& operator=(r_vector&& rhs); operator SEXP() const; #ifdef LONG_VECTOR_SUPPORT proxy operator[](const int pos) const; #endif proxy operator[](const R_xlen_t pos) const; proxy operator[](const size_type pos) const; proxy operator[](const r_string& name) const; #ifdef LONG_VECTOR_SUPPORT proxy at(const int pos) const; #endif proxy at(const R_xlen_t pos) const; proxy at(const size_type pos) const; proxy at(const r_string& name) const; void push_back(T value); /// Implemented in `strings.hpp` void push_back(const named_arg& value); void pop_back(); void resize(R_xlen_t count); void reserve(R_xlen_t new_capacity); iterator insert(R_xlen_t pos, T value); iterator erase(R_xlen_t pos); void clear(); iterator begin() const; iterator end() const; using cpp11::r_vector::cbegin; using cpp11::r_vector::cend; using cpp11::r_vector::size; iterator find(const r_string& name) const; attribute_proxy> attr(const char* name) const; attribute_proxy> attr(const std::string& name) const; attribute_proxy> attr(SEXP name) const; attribute_proxy> names() const; class proxy { private: const SEXP data_; const R_xlen_t index_; underlying_type* const p_; bool is_altrep_; public: proxy(SEXP data, const R_xlen_t index, underlying_type* const p, bool is_altrep); proxy& operator=(const proxy& rhs); proxy& operator=(const T& rhs); proxy& operator+=(const T& rhs); proxy& operator-=(const T& rhs); proxy& operator*=(const T& rhs); proxy& operator/=(const T& rhs); proxy& operator++(int); proxy& operator--(int); void operator++(); void operator--(); operator T() const; private: underlying_type get() const; void set(underlying_type x); }; class iterator : public cpp11::r_vector::const_iterator { private: using cpp11::r_vector::const_iterator::data_; using cpp11::r_vector::const_iterator::block_start_; using cpp11::r_vector::const_iterator::pos_; using cpp11::r_vector::const_iterator::buf_; using cpp11::r_vector::const_iterator::length_; using cpp11::r_vector::const_iterator::use_buf; using cpp11::r_vector::const_iterator::fill_buf; public: using difference_type = ptrdiff_t; using value_type = proxy; using pointer = proxy*; using reference = proxy&; using iterator_category = std::forward_iterator_tag; iterator(const r_vector* data, R_xlen_t pos); iterator& operator++(); proxy operator*() const; using cpp11::r_vector::const_iterator::operator!=; iterator& operator+=(R_xlen_t rhs); iterator operator+(R_xlen_t rhs); }; private: /// Implemented in specialization static void set_elt(SEXP x, R_xlen_t i, underlying_type value); static SEXP reserve_data(SEXP x, bool is_altrep, R_xlen_t size); static SEXP resize_data(SEXP x, bool is_altrep, R_xlen_t size); static SEXP resize_names(SEXP x, R_xlen_t size); using cpp11::r_vector::get_elt; using cpp11::r_vector::get_p; using cpp11::r_vector::get_const_p; using cpp11::r_vector::get_sexptype; using cpp11::r_vector::valid_type; using cpp11::r_vector::valid_length; }; } // namespace writable // Implementations below template inline r_vector::~r_vector() { detail::store::release(protect_); } template inline r_vector::r_vector(const SEXP data) : data_(valid_type(data)), protect_(detail::store::insert(data)), is_altrep_(ALTREP(data)), data_p_(get_p(ALTREP(data), data)), length_(Rf_xlength(data)) {} template inline r_vector::r_vector(const SEXP data, bool is_altrep) : data_(valid_type(data)), protect_(detail::store::insert(data)), is_altrep_(is_altrep), data_p_(get_p(is_altrep, data)), length_(Rf_xlength(data)) {} // We are in read-only space so we can just copy over all properties except for // `protect_`, which we need to manage on our own. `x` persists after this call, so we // don't clear anything. template inline r_vector::r_vector(const r_vector& x) { data_ = x.data_; protect_ = detail::store::insert(data_); is_altrep_ = x.is_altrep_; data_p_ = x.data_p_; length_ = x.length_; } // `x` here is a temporary value, it is going to be destructed right after this. // Take ownership over all `x` details, including `protect_`. // Importantly, set `x.protect_` to `R_NilValue` to prevent the `x` destructor from // releasing the object that we now own. template inline r_vector::r_vector(r_vector&& x) { data_ = x.data_; protect_ = x.protect_; is_altrep_ = x.is_altrep_; data_p_ = x.data_p_; length_ = x.length_; // Important for `x.protect_`, extra check for everything else x.data_ = R_NilValue; x.protect_ = R_NilValue; x.is_altrep_ = false; x.data_p_ = nullptr; x.length_ = 0; } // `x` here is writable, meaning the underlying `SEXP` could have more `capacity` than // a read only equivalent would expect. This means we have to go through `SEXP` first, // to truncate the writable data, and then we can wrap it in a read only `r_vector`. // // It would be the same scenario if we came from a writable temporary, i.e. // `writable::r_vector&& x`, so we let this method handle both scenarios. template inline r_vector::r_vector(const writable::r_vector& x) : r_vector(static_cast(x)) {} // Same reasoning as `r_vector(const r_vector& x)` constructor template inline r_vector& r_vector::operator=(const r_vector& rhs) { if (data_ == rhs.data_) { return *this; } // Release existing object that we protect detail::store::release(protect_); data_ = rhs.data_; protect_ = detail::store::insert(data_); is_altrep_ = rhs.is_altrep_; data_p_ = rhs.data_p_; length_ = rhs.length_; return *this; } // Same reasoning as `r_vector(r_vector&& x)` constructor template inline r_vector& r_vector::operator=(r_vector&& rhs) { if (data_ == rhs.data_) { return *this; } // Release existing object that we protect detail::store::release(protect_); data_ = rhs.data_; protect_ = rhs.protect_; is_altrep_ = rhs.is_altrep_; data_p_ = rhs.data_p_; length_ = rhs.length_; // Important for `rhs.protect_`, extra check for everything else rhs.data_ = R_NilValue; rhs.protect_ = R_NilValue; rhs.is_altrep_ = false; rhs.data_p_ = nullptr; rhs.length_ = 0; return *this; } template inline r_vector::operator SEXP() const { return data_; } template inline r_vector::operator sexp() const { return data_; } #ifdef LONG_VECTOR_SUPPORT template inline T r_vector::operator[](const int pos) const { return operator[](static_cast(pos)); } #endif template inline T r_vector::operator[](const R_xlen_t pos) const { // Handles ALTREP, VECSXP, and STRSXP cases through `get_elt()` const underlying_type elt = (data_p_ != nullptr) ? data_p_[pos] : get_elt(data_, pos); return static_cast(elt); } template inline T r_vector::operator[](const size_type pos) const { return operator[](static_cast(pos)); } template inline T r_vector::operator[](const r_string& name) const { SEXP names = this->names(); R_xlen_t size = Rf_xlength(names); for (R_xlen_t pos = 0; pos < size; ++pos) { auto cur = Rf_translateCharUTF8(STRING_ELT(names, pos)); if (name == cur) { return operator[](pos); } } return get_oob(); } #ifdef LONG_VECTOR_SUPPORT template inline T r_vector::at(const int pos) const { return at(static_cast(pos)); } #endif template inline T r_vector::at(const R_xlen_t pos) const { if (pos < 0 || pos >= length_) { throw std::out_of_range("r_vector"); } return operator[](pos); } template inline T r_vector::at(const size_type pos) const { return at(static_cast(pos)); } template inline T r_vector::at(const r_string& name) const { return operator[](name); } template inline bool r_vector::contains(const r_string& name) const { SEXP names = this->names(); R_xlen_t size = Rf_xlength(names); for (R_xlen_t pos = 0; pos < size; ++pos) { auto cur = Rf_translateCharUTF8(STRING_ELT(names, pos)); if (name == cur) { return true; } } return false; } template inline bool r_vector::is_altrep() const { return is_altrep_; } template inline bool r_vector::named() const { return Rf_getAttrib(data_, R_NamesSymbol) != R_NilValue; } template inline R_xlen_t r_vector::size() const { return length_; } template inline bool r_vector::empty() const { return (!(this->size() > 0)); } /// Provide access to the underlying data, mainly for interface /// compatibility with std::vector template inline SEXP r_vector::data() const { return data_; } template inline const sexp r_vector::attr(const char* name) const { return SEXP(attribute_proxy>(*this, name)); } template inline const sexp r_vector::attr(const std::string& name) const { return SEXP(attribute_proxy>(*this, name.c_str())); } template inline const sexp r_vector::attr(SEXP name) const { return SEXP(attribute_proxy>(*this, name)); } template inline r_vector r_vector::names() const { SEXP nms = Rf_getAttrib(data_, R_NamesSymbol); if (nms == R_NilValue) { return r_vector(); } else { return r_vector(nms); } } template inline T r_vector::get_oob() { throw std::out_of_range("r_vector"); } class type_error : public std::exception { public: type_error(SEXPTYPE expected, SEXPTYPE actual) : expected_(expected), actual_(actual) {} virtual const char* what() const noexcept override { snprintf(str_, 64, "Invalid input type, expected '%s' actual '%s'", Rf_type2char(expected_), Rf_type2char(actual_)); return str_; } private: SEXPTYPE expected_; SEXPTYPE actual_; mutable char str_[64]; }; template inline SEXP r_vector::valid_type(SEXP x) { const SEXPTYPE type = get_sexptype(); if (x == nullptr) { throw type_error(type, NILSXP); } if (detail::r_typeof(x) != type) { throw type_error(type, detail::r_typeof(x)); } return x; } template inline SEXP r_vector::valid_length(SEXP x, R_xlen_t n) { R_xlen_t x_n = Rf_xlength(x); if (x_n == n) { return x; } char message[128]; snprintf(message, 128, "Invalid input length, expected '%" CPP11_PRIdXLEN_T "' actual '%" CPP11_PRIdXLEN_T "'.", n, x_n); throw std::length_error(message); } template inline typename r_vector::const_iterator r_vector::begin() const { return const_iterator(this, 0); } template inline typename r_vector::const_iterator r_vector::end() const { return const_iterator(this, length_); } template inline typename r_vector::const_iterator r_vector::cbegin() const { return const_iterator(this, 0); } template inline typename r_vector::const_iterator r_vector::cend() const { return const_iterator(this, length_); } template r_vector::const_iterator::const_iterator(const r_vector* data, R_xlen_t pos) : data_(data), pos_(pos), buf_() { if (use_buf(data_->is_altrep())) { fill_buf(pos); } } template inline typename r_vector::const_iterator& r_vector::const_iterator::operator++() { ++pos_; if (use_buf(data_->is_altrep()) && pos_ >= block_start_ + length_) { fill_buf(pos_); } return *this; } template inline typename r_vector::const_iterator& r_vector::const_iterator::operator--() { --pos_; if (use_buf(data_->is_altrep()) && pos_ > 0 && pos_ < block_start_) { fill_buf(std::max(0_xl, pos_ - 64)); } return *this; } template inline typename r_vector::const_iterator& r_vector::const_iterator::operator+=( R_xlen_t i) { pos_ += i; if (use_buf(data_->is_altrep()) && pos_ >= block_start_ + length_) { fill_buf(pos_); } return *this; } template inline typename r_vector::const_iterator& r_vector::const_iterator::operator-=( R_xlen_t i) { pos_ -= i; if (use_buf(data_->is_altrep()) && pos_ >= block_start_ + length_) { fill_buf(std::max(0_xl, pos_ - 64)); } return *this; } template inline bool r_vector::const_iterator::operator!=( const r_vector::const_iterator& other) const { return pos_ != other.pos_; } template inline bool r_vector::const_iterator::operator==( const r_vector::const_iterator& other) const { return pos_ == other.pos_; } template inline ptrdiff_t r_vector::const_iterator::operator-( const r_vector::const_iterator& other) const { return pos_ - other.pos_; } template inline typename r_vector::const_iterator r_vector::const_iterator::operator+( R_xlen_t rhs) { auto it = *this; it += rhs; return it; } template inline typename r_vector::const_iterator r_vector::find( const r_string& name) const { SEXP names = this->names(); R_xlen_t size = Rf_xlength(names); for (R_xlen_t pos = 0; pos < size; ++pos) { auto cur = Rf_translateCharUTF8(STRING_ELT(names, pos)); if (name == cur) { return begin() + pos; } } return end(); } template inline T r_vector::const_iterator::operator*() const { if (use_buf(data_->is_altrep())) { // Use pre-loaded buffer for compatible ALTREP types return static_cast(buf_[pos_ - block_start_]); } else { // Otherwise pass through to normal retrieval method return data_->operator[](pos_); } } template inline void r_vector::const_iterator::fill_buf(R_xlen_t pos) { using namespace cpp11::literals; length_ = std::min(64_xl, data_->size() - pos); get_region(data_->data_, pos, length_, buf_.data()); block_start_ = pos; } namespace writable { template inline r_vector::r_vector(const SEXP& data) : cpp11::r_vector(safe[Rf_shallow_duplicate](data)), capacity_(length_) {} template inline r_vector::r_vector(SEXP&& data) : cpp11::r_vector(data), capacity_(length_) {} template inline r_vector::r_vector(const SEXP& data, bool is_altrep) : cpp11::r_vector(safe[Rf_shallow_duplicate](data), is_altrep), capacity_(length_) {} template inline r_vector::r_vector(SEXP&& data, bool is_altrep) : cpp11::r_vector(data, is_altrep), capacity_(length_) {} template inline r_vector::r_vector(const r_vector& rhs) { // We don't want to just pass through to the read-only constructor because we'd // have to convert to `SEXP` first, which could truncate, and then we'd still have // to shallow duplicate after that to really ensure we have a duplicate, which can // result in too many copies (#369). // // Instead we take control of setting all fields to try and only duplicate 1 time. // If there is extra capacity in the `rhs`, that is also copied over. Resist the urge // to try and trim the extra capacity during the duplication. We really do want to do a // shallow duplicate to ensure that ALL attributes are copied over, including `dim` and // `dimnames`, which would be lost if we instead used `reserve_data()` to do a combined // duplicate + possible truncate. This is important for the `matrix` class. data_ = safe[Rf_shallow_duplicate](rhs.data_); protect_ = detail::store::insert(data_); is_altrep_ = ALTREP(data_); data_p_ = (data_ == R_NilValue) ? nullptr : get_p(is_altrep_, data_); length_ = rhs.length_; capacity_ = rhs.capacity_; } template inline r_vector::r_vector(r_vector&& rhs) { // We don't want to pass through to the read-only constructor from a // `writable::r_vector&& rhs` as that forces a truncation to be able to generate // a well-formed read-only vector. Instead, we take advantage of the fact that we // are going from writable input to writable output and just move everything over. // // This ends up looking very similar to the equivalent read-only constructor from a // read-only `r_vector&& rhs`, with the addition of moving the capacity. data_ = rhs.data_; protect_ = rhs.protect_; is_altrep_ = rhs.is_altrep_; data_p_ = rhs.data_p_; length_ = rhs.length_; capacity_ = rhs.capacity_; // Important for `rhs.protect_`, extra check for everything else rhs.data_ = R_NilValue; rhs.protect_ = R_NilValue; rhs.is_altrep_ = false; rhs.data_p_ = nullptr; rhs.length_ = 0; rhs.capacity_ = 0; } template inline r_vector::r_vector(const cpp11::r_vector& rhs) : cpp11::r_vector(safe[Rf_shallow_duplicate](rhs.data_)), capacity_(rhs.length_) {} template inline r_vector::r_vector(std::initializer_list il) : cpp11::r_vector(safe[Rf_allocVector](get_sexptype(), il.size())), capacity_(il.size()) { auto it = il.begin(); if (data_p_ != nullptr) { for (R_xlen_t i = 0; i < capacity_; ++i, ++it) { data_p_[i] = static_cast(*it); } } else { // Handles both the ALTREP and VECSXP cases for (R_xlen_t i = 0; i < capacity_; ++i, ++it) { set_elt(data_, i, static_cast(*it)); } } } template inline r_vector::r_vector(std::initializer_list il) : cpp11::r_vector(safe[Rf_allocVector](get_sexptype(), il.size())), capacity_(il.size()) { auto it = il.begin(); // SAFETY: Loop through once outside the `unwind_protect()` to perform the // validation that might `throw`. for (R_xlen_t i = 0; i < capacity_; ++i, ++it) { SEXP value = it->value(); valid_type(value); valid_length(value, 1); } unwind_protect([&] { SEXP names = Rf_allocVector(STRSXP, capacity_); Rf_setAttrib(data_, R_NamesSymbol, names); auto it = il.begin(); for (R_xlen_t i = 0; i < capacity_; ++i, ++it) { SEXP value = it->value(); // SAFETY: We've validated type and length ahead of this. const underlying_type elt = get_elt(value, 0); // TODO: The equivalent ctor from `initializer_list` has a specialization // for `` to translate `elt` to UTF-8 before assigning. Should we have // that here too? `named_arg` doesn't do any checking here. if (data_p_ != nullptr) { data_p_[i] = elt; } else { // Handles STRSXP case. VECSXP case has its own specialization. // We don't expect any ALTREP cases since we just freshly allocated `data_`. set_elt(data_, i, elt); } SEXP name = Rf_mkCharCE(it->name(), CE_UTF8); SET_STRING_ELT(names, i, name); } }); } template inline r_vector::r_vector(const R_xlen_t size) : r_vector() { resize(size); } template template inline r_vector::r_vector(Iter first, Iter last) : r_vector() { reserve(last - first); while (first != last) { push_back(*first); ++first; } } template template inline r_vector::r_vector(const V& obj) : r_vector() { auto first = obj.begin(); auto last = obj.end(); reserve(last - first); while (first != last) { push_back(*first); ++first; } } template inline r_vector& r_vector::operator=(const r_vector& rhs) { if (data_ == rhs.data_) { return *this; } // We don't release the old object until the end in case we throw an exception // during the duplicate. SEXP old_protect = protect_; // Unlike with move assignment operator, we can't just call the read only parent method. // We are in writable mode, so we must duplicate the `rhs` (since it isn't a temporary // we can just take ownership of) and recompute the properties from the duplicate. data_ = safe[Rf_shallow_duplicate](rhs.data_); protect_ = detail::store::insert(data_); is_altrep_ = ALTREP(data_); data_p_ = (data_ == R_NilValue) ? nullptr : get_p(is_altrep_, data_); length_ = rhs.length_; capacity_ = rhs.capacity_; detail::store::release(old_protect); return *this; } template inline r_vector& r_vector::operator=(r_vector&& rhs) { if (data_ == rhs.data_) { return *this; } // Call parent read only move assignment operator to move // all other properties, including protection handling cpp11::r_vector::operator=(std::move(rhs)); // Handle fields specific to writable capacity_ = rhs.capacity_; rhs.capacity_ = 0; return *this; } template inline r_vector::operator SEXP() const { // Throwing away the const-ness is a bit gross, but we only modify // internal details here, and updating the internal data after we resize allows // statements like `Rf_setAttrib(, name, value)` to make sense, where // people expect that the SEXP inside the `` gets the updated attribute. auto* p = const_cast*>(this); if (data_ == R_NilValue) { // Specially call out the `NULL` case, which can occur if immediately // returning a default constructed writable `r_vector` as a `SEXP`. p->resize(0); return data_; } if (length_ < capacity_) { // Truncate the vector to its `length_`. This unfortunately typically forces // an allocation if the user has called `push_back()` on a writable // `r_vector`. Importantly, going through `resize()` updates: `data_` and // protection of it, `data_p_`, and `capacity_`. p->resize(length_); return data_; } return data_; } #ifdef LONG_VECTOR_SUPPORT template inline typename r_vector::proxy r_vector::operator[](const int pos) const { return operator[](static_cast(pos)); } #endif template inline typename r_vector::proxy r_vector::operator[](const R_xlen_t pos) const { if (is_altrep_) { return {data_, pos, nullptr, true}; } return {data_, pos, data_p_ != nullptr ? &data_p_[pos] : nullptr, false}; } template inline typename r_vector::proxy r_vector::operator[](const size_type pos) const { return operator[](static_cast(pos)); } template inline typename r_vector::proxy r_vector::operator[](const r_string& name) const { SEXP names = PROTECT(this->names()); R_xlen_t size = Rf_xlength(names); for (R_xlen_t pos = 0; pos < size; ++pos) { auto cur = Rf_translateCharUTF8(STRING_ELT(names, pos)); if (name == cur) { UNPROTECT(1); return operator[](pos); } } UNPROTECT(1); throw std::out_of_range("r_vector"); } #ifdef LONG_VECTOR_SUPPORT template inline typename r_vector::proxy r_vector::at(const int pos) const { return at(static_cast(pos)); } #endif template inline typename r_vector::proxy r_vector::at(const R_xlen_t pos) const { if (pos < 0 || pos >= length_) { throw std::out_of_range("r_vector"); } return operator[](static_cast(pos)); } template inline typename r_vector::proxy r_vector::at(const size_type pos) const { return at(static_cast(pos)); } template inline typename r_vector::proxy r_vector::at(const r_string& name) const { return operator[](name); } template inline void r_vector::push_back(T value) { while (length_ >= capacity_) { reserve(capacity_ == 0 ? 1 : capacity_ *= 2); } if (data_p_ != nullptr) { data_p_[length_] = static_cast(value); } else { set_elt(data_, length_, static_cast(value)); } ++length_; } template inline void r_vector::pop_back() { --length_; } template inline void r_vector::resize(R_xlen_t count) { reserve(count); length_ = count; } /// Reserve a new capacity and copy all elements over /// /// SAFETY: The new capacity is allowed to be smaller than the current capacity, which /// is used in the `SEXP` conversion operator during truncation, but if that occurs then /// we also need to update the `length_`, so if you need to truncate then you should call /// `resize()` instead. template inline void r_vector::reserve(R_xlen_t new_capacity) { SEXP old_protect = protect_; data_ = (data_ == R_NilValue) ? safe[Rf_allocVector](get_sexptype(), new_capacity) : reserve_data(data_, is_altrep_, new_capacity); protect_ = detail::store::insert(data_); is_altrep_ = ALTREP(data_); data_p_ = get_p(is_altrep_, data_); capacity_ = new_capacity; detail::store::release(old_protect); } template inline typename r_vector::iterator r_vector::insert(R_xlen_t pos, T value) { push_back(value); R_xlen_t i = length_ - 1; while (i > pos) { operator[](i) = (T) operator[](i - 1); --i; }; operator[](pos) = value; return begin() + pos; } template inline typename r_vector::iterator r_vector::erase(R_xlen_t pos) { R_xlen_t i = pos; while (i < length_ - 1) { operator[](i) = (T) operator[](i + 1); ++i; } pop_back(); return begin() + pos; } template inline void r_vector::clear() { length_ = 0; } template inline typename r_vector::iterator r_vector::begin() const { return iterator(this, 0); } template inline typename r_vector::iterator r_vector::end() const { return iterator(this, length_); } template inline typename r_vector::iterator r_vector::find(const r_string& name) const { SEXP names = PROTECT(this->names()); R_xlen_t size = Rf_xlength(names); for (R_xlen_t pos = 0; pos < size; ++pos) { auto cur = Rf_translateCharUTF8(STRING_ELT(names, pos)); if (name == cur) { UNPROTECT(1); return begin() + pos; } } UNPROTECT(1); return end(); } template inline attribute_proxy> r_vector::attr(const char* name) const { return attribute_proxy>(*this, name); } template inline attribute_proxy> r_vector::attr(const std::string& name) const { return attribute_proxy>(*this, name.c_str()); } template inline attribute_proxy> r_vector::attr(SEXP name) const { return attribute_proxy>(*this, name); } template inline attribute_proxy> r_vector::names() const { return attribute_proxy>(*this, R_NamesSymbol); } template r_vector::proxy::proxy(SEXP data, const R_xlen_t index, typename r_vector::underlying_type* const p, bool is_altrep) : data_(data), index_(index), p_(p), is_altrep_(is_altrep) {} template inline typename r_vector::proxy& r_vector::proxy::operator=(const proxy& rhs) { const underlying_type elt = rhs.get(); set(elt); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator=(const T& rhs) { const underlying_type elt = static_cast(rhs); set(elt); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator+=(const T& rhs) { operator=(static_cast(*this) + rhs); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator-=(const T& rhs) { operator=(static_cast(*this) - rhs); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator*=(const T& rhs) { operator=(static_cast(*this) * rhs); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator/=(const T& rhs) { operator=(static_cast(*this) / rhs); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator++(int) { operator=(static_cast(*this) + 1); return *this; } template inline typename r_vector::proxy& r_vector::proxy::operator--(int) { operator=(static_cast(*this) - 1); return *this; } template inline void r_vector::proxy::operator++() { operator=(static_cast(*this) + 1); } template inline void r_vector::proxy::operator--() { operator=(static_cast(*this) - 1); } template inline r_vector::proxy::operator T() const { const underlying_type elt = get(); return static_cast(elt); } template inline typename r_vector::underlying_type r_vector::proxy::get() const { if (p_ != nullptr) { return *p_; } else { // Handles ALTREP, VECSXP, and STRSXP cases return r_vector::get_elt(data_, index_); } } template inline void r_vector::proxy::set(typename r_vector::underlying_type x) { if (p_ != nullptr) { *p_ = x; } else { // Handles ALTREP, VECSXP, and STRSXP cases set_elt(data_, index_, x); } } template r_vector::iterator::iterator(const r_vector* data, R_xlen_t pos) : r_vector::const_iterator(data, pos) {} template inline typename r_vector::iterator& r_vector::iterator::operator++() { ++pos_; if (use_buf(data_->is_altrep()) && pos_ >= block_start_ + length_) { fill_buf(pos_); } return *this; } template inline typename r_vector::proxy r_vector::iterator::operator*() const { if (use_buf(data_->is_altrep())) { return proxy( data_->data(), pos_, const_cast(&buf_[pos_ - block_start_]), true); } else { return proxy(data_->data(), pos_, data_->data_p_ != nullptr ? &data_->data_p_[pos_] : nullptr, false); } } template inline typename r_vector::iterator& r_vector::iterator::operator+=(R_xlen_t rhs) { pos_ += rhs; if (use_buf(data_->is_altrep()) && pos_ >= block_start_ + length_) { fill_buf(pos_); } return *this; } template inline typename r_vector::iterator r_vector::iterator::operator+(R_xlen_t rhs) { auto it = *this; it += rhs; return it; } /// Compared to `Rf_xlengthgets()`: /// - This copies over attributes with `Rf_copyMostAttrib()`, which is important when we /// truncate right before returning from the `SEXP` operator. /// - This always allocates, even if it is the same size. /// - This is more friendly to ALTREP `x`. /// /// SAFETY: For use only by `reserve()`! This won't retain the `dim` or `dimnames` /// attributes (which doesn't make much sense anyways). template inline SEXP r_vector::reserve_data(SEXP x, bool is_altrep, R_xlen_t size) { // Resize core data SEXP out = PROTECT(resize_data(x, is_altrep, size)); // Resize names, if required // Protection seems needed to make rchk happy SEXP names = PROTECT(Rf_getAttrib(x, R_NamesSymbol)); if (names != R_NilValue) { if (Rf_xlength(names) != size) { names = resize_names(names, size); } Rf_setAttrib(out, R_NamesSymbol, names); } // Copy over "most" attributes, and set OBJECT bit and S4 bit as needed. // Does not copy over names, dim, or dim names. // Names are handled already. Dim and dim names should not be applicable, // as this is a vector. // Does not look like it would ever error in our use cases, so no `safe[]`. Rf_copyMostAttrib(x, out); UNPROTECT(2); return out; } template inline SEXP r_vector::resize_data(SEXP x, bool is_altrep, R_xlen_t size) { underlying_type const* v_x = get_const_p(is_altrep, x); SEXP out = PROTECT(safe[Rf_allocVector](get_sexptype(), size)); underlying_type* v_out = get_p(ALTREP(out), out); const R_xlen_t x_size = Rf_xlength(x); const R_xlen_t copy_size = (x_size > size) ? size : x_size; // Copy over data from `x` up to `copy_size` (we could be truncating so don't blindly // copy everything from `x`) if (v_x != nullptr && v_out != nullptr) { std::memcpy(v_out, v_x, copy_size * sizeof(underlying_type)); } else { // Handles ALTREP `x` with no const pointer, VECSXP, STRSXP for (R_xlen_t i = 0; i < copy_size; ++i) { set_elt(out, i, get_elt(x, i)); } } UNPROTECT(1); return out; } template inline SEXP r_vector::resize_names(SEXP x, R_xlen_t size) { const SEXP* v_x = STRING_PTR_RO(x); SEXP out = PROTECT(safe[Rf_allocVector](STRSXP, size)); const R_xlen_t x_size = Rf_xlength(x); const R_xlen_t copy_size = (x_size > size) ? size : x_size; for (R_xlen_t i = 0; i < copy_size; ++i) { SET_STRING_ELT(out, i, v_x[i]); } // Ensure remaining names are initialized to `""` for (R_xlen_t i = copy_size; i < size; ++i) { SET_STRING_ELT(out, i, R_BlankString); } UNPROTECT(1); return out; } } // namespace writable // TODO: is there a better condition we could use, e.g. assert something true // rather than three things false? template using is_container_but_not_sexp_or_string = typename std::enable_if< !std::is_constructible::value && !std::is_same::type, std::string>::value && !std::is_same::type, std::string>::value, typename std::decay::type>::type; template ::type::value_type> // typename T = typename C::value_type> is_container_but_not_sexp_or_string as_cpp(SEXP from) { auto obj = cpp11::r_vector(from); return {obj.begin(), obj.end()}; } // TODO: could we make this generalize outside of std::string? template using is_vector_of_strings = typename std::enable_if< std::is_same::type, std::string>::value, typename std::decay::type>::type; template ::type::value_type> // typename T = typename C::value_type> is_vector_of_strings as_cpp(SEXP from) { auto obj = cpp11::r_vector(from); typename std::decay::type res; auto it = obj.begin(); while (it != obj.end()) { r_string s = *it; res.emplace_back(static_cast(s)); ++it; } return res; } template bool operator==(const r_vector& lhs, const r_vector& rhs) { if (lhs.size() != rhs.size()) { return false; } auto lhs_it = lhs.begin(); auto rhs_it = rhs.begin(); auto end = lhs.end(); while (lhs_it != end) { if (!(*lhs_it == *rhs_it)) { return false; } ++lhs_it; ++rhs_it; } return true; } template bool operator!=(const r_vector& lhs, const r_vector& rhs) { return !(lhs == rhs); } } // namespace cpp11 QuickJSR/src/include/cpp11/matrix.hpp0000644000176200001440000001537215122664674017105 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include #include // for string #include "cpp11/R.hpp" // for SEXP, SEXPREC, R_xlen_t, INT... #include "cpp11/r_bool.hpp" // for r_bool #include "cpp11/r_string.hpp" // for r_string #include "cpp11/r_vector.hpp" // for r_vector #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { // matrix dimensions struct matrix_dims { protected: const int nrow_; const int ncol_; public: matrix_dims(SEXP data) : nrow_(Rf_nrows(data)), ncol_(Rf_ncols(data)) {} matrix_dims(int nrow, int ncol) : nrow_(nrow), ncol_(ncol) {} int nrow() const { return nrow_; } int ncol() const { return ncol_; } }; // base type for dimension-wise matrix access specialization struct matrix_slice {}; struct by_row : public matrix_slice {}; struct by_column : public matrix_slice {}; // basic properties of matrix slices template struct matrix_slices : public matrix_dims { public: using matrix_dims::matrix_dims; using matrix_dims::ncol; using matrix_dims::nrow; int nslices() const; int slice_size() const; int slice_stride() const; int slice_offset(int pos) const; }; // basic properties of matrix row slices template <> struct matrix_slices : public matrix_dims { public: using matrix_dims::matrix_dims; using matrix_dims::ncol; using matrix_dims::nrow; int nslices() const { return nrow(); } int slice_size() const { return ncol(); } int slice_stride() const { return nrow(); } int slice_offset(int pos) const { return pos; } }; // basic properties of matrix column slices template <> struct matrix_slices : public matrix_dims { public: using matrix_dims::matrix_dims; using matrix_dims::ncol; using matrix_dims::nrow; int nslices() const { return ncol(); } int slice_size() const { return nrow(); } int slice_stride() const { return 1; } int slice_offset(int pos) const { return pos * nrow(); } }; template class matrix : public matrix_slices { private: V vector_; public: // matrix slice: row (if S=by_row) or a column (if S=by_column) class slice { private: const matrix& parent_; int index_; // slice index int offset_; // index of the first slice element in parent_.vector_ public: slice(const matrix& parent, int index) : parent_(parent), index_(index), offset_(parent.slice_offset(index)) {} R_xlen_t stride() const { return parent_.slice_stride(); } R_xlen_t size() const { return parent_.slice_size(); } bool operator==(const slice& rhs) const { return (index_ == rhs.index_) && (parent_.data() == rhs.parent_.data()); } bool operator!=(const slice& rhs) const { return !operator==(rhs); } T operator[](int pos) const { return parent_.vector_[offset_ + stride() * pos]; } // iterates elements of a slice class iterator { private: const slice& slice_; int pos_; public: using difference_type = std::ptrdiff_t; using value_type = T; using pointer = T*; using reference = T&; using iterator_category = std::forward_iterator_tag; iterator(const slice& slice, R_xlen_t pos) : slice_(slice), pos_(pos) {} iterator& operator++() { ++pos_; return *this; } bool operator==(const iterator& rhs) const { return (pos_ == rhs.pos_) && (slice_ == rhs.slice_); } bool operator!=(const iterator& rhs) const { return !operator==(rhs); } T operator*() const { return slice_[pos_]; }; }; iterator begin() const { return {*this, 0}; } iterator end() const { return {*this, size()}; } }; friend slice; // iterates slices (rows or columns -- depending on S template param) of a matrix class slice_iterator { private: const matrix& parent_; int pos_; public: using difference_type = std::ptrdiff_t; using value_type = slice; using pointer = slice*; using reference = slice&; using iterator_category = std::forward_iterator_tag; slice_iterator(const matrix& parent, R_xlen_t pos) : parent_(parent), pos_(pos) {} slice_iterator& operator++() { ++pos_; return *this; } bool operator==(const slice_iterator& rhs) const { return (pos_ == rhs.pos_) && (parent_.data() == rhs.parent_.data()); } bool operator!=(const slice_iterator& rhs) const { return !operator==(rhs); } slice operator*() { return parent_[pos_]; }; }; public: matrix(SEXP data) : matrix_slices(data), vector_(data) {} template matrix(const cpp11::matrix& rhs) : matrix_slices(rhs.nrow(), rhs.ncol()), vector_(rhs.vector()) {} matrix(int nrow, int ncol) : matrix_slices(nrow, ncol), vector_(R_xlen_t(nrow * ncol)) { vector_.attr(R_DimSymbol) = {nrow, ncol}; } using matrix_slices::nrow; using matrix_slices::ncol; using matrix_slices::nslices; using matrix_slices::slice_size; using matrix_slices::slice_stride; using matrix_slices::slice_offset; V vector() const { return vector_; } SEXP data() const { return vector_.data(); } R_xlen_t size() const { return vector_.size(); } operator SEXP() const { return SEXP(vector_); } // operator sexp() { return sexp(vector_); } sexp attr(const char* name) const { return SEXP(vector_.attr(name)); } sexp attr(const std::string& name) const { return SEXP(vector_.attr(name)); } sexp attr(SEXP name) const { return SEXP(vector_.attr(name)); } r_vector names() const { return r_vector(vector_.names()); } T operator()(int row, int col) const { return vector_[row + (col * nrow())]; } slice operator[](int index) const { return {*this, index}; } slice_iterator begin() const { return {*this, 0}; } slice_iterator end() const { return {*this, nslices()}; } }; template using doubles_matrix = matrix, double, S>; template using integers_matrix = matrix, int, S>; template using logicals_matrix = matrix, r_bool, S>; template using strings_matrix = matrix, r_string, S>; namespace writable { template using doubles_matrix = matrix, r_vector::proxy, S>; template using integers_matrix = matrix, r_vector::proxy, S>; template using logicals_matrix = matrix, r_vector::proxy, S>; template using strings_matrix = matrix, r_vector::proxy, S>; } // namespace writable // TODO: Add tests for Matrix class } // namespace cpp11 QuickJSR/src/include/cpp11/raws.hpp0000644000176200001440000000427215122664674016552 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for min #include // for array #include // for uint8_t #include // for initializer_list #include "Rversion.h" #include "cpp11/R.hpp" // for RAW, SEXP, SEXPREC, Rf_allocVector #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/protect.hpp" // for safe #include "cpp11/r_vector.hpp" // for r_vector, r_vector<>::proxy #include "cpp11/sexp.hpp" // for sexp // Specializations for raws namespace cpp11 { namespace traits { template <> struct get_underlying_type { using type = Rbyte; }; } // namespace traits template <> inline SEXPTYPE r_vector::get_sexptype() { return RAWSXP; } template <> inline typename r_vector::underlying_type r_vector::get_elt( SEXP x, R_xlen_t i) { // NOPROTECT: likely too costly to unwind protect every elt return RAW_ELT(x, i); } template <> inline typename r_vector::underlying_type const* r_vector::get_const_p( bool is_altrep, SEXP data) { return RAW_OR_NULL(data); } template <> inline typename r_vector::underlying_type* r_vector::get_p( bool is_altrep, SEXP data) { if (is_altrep) { return nullptr; } else { return RAW(data); } } template <> inline void r_vector::get_region(SEXP x, R_xlen_t i, R_xlen_t n, typename r_vector::underlying_type* buf) { // NOPROTECT: likely too costly to unwind protect here RAW_GET_REGION(x, i, n, buf); } template <> inline bool r_vector::const_iterator::use_buf(bool is_altrep) { return is_altrep; } typedef r_vector raws; namespace writable { template <> inline void r_vector::set_elt(SEXP x, R_xlen_t i, typename r_vector::underlying_type value) { // NOPROTECT: Likely too costly to unwind protect every set elt #if R_VERSION >= R_Version(4, 2, 0) SET_RAW_ELT(x, i, value); #else RAW(x)[i] = value; #endif } typedef r_vector raws; } // namespace writable } // namespace cpp11 QuickJSR/src/include/cpp11/strings.hpp0000644000176200001440000001031415122664674017261 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for initializer_list #include // for string, basic_string #include "cpp11/R.hpp" // for SEXP, SEXPREC, SET_STRI... #include "cpp11/as.hpp" // for as_sexp #include "cpp11/attribute_proxy.hpp" // for attribute_proxy #include "cpp11/named_arg.hpp" // for named_arg #include "cpp11/protect.hpp" // for safe #include "cpp11/r_string.hpp" // for r_string #include "cpp11/r_vector.hpp" // for r_vector, r_vector<>::proxy #include "cpp11/sexp.hpp" // for sexp // Specializations for strings namespace cpp11 { template <> inline SEXPTYPE r_vector::get_sexptype() { return STRSXP; } template <> inline typename r_vector::underlying_type r_vector::get_elt( SEXP x, R_xlen_t i) { // NOPROTECT: likely too costly to unwind protect every elt return STRING_ELT(x, i); } template <> inline typename r_vector::underlying_type* r_vector::get_p(bool, SEXP) { return nullptr; } template <> inline typename r_vector::underlying_type const* r_vector::get_const_p(bool is_altrep, SEXP data) { // No `STRING_PTR_OR_NULL()` if (is_altrep) { return nullptr; } else { return STRING_PTR_RO(data); } } template <> inline void r_vector::get_region(SEXP x, R_xlen_t i, R_xlen_t n, typename r_vector::underlying_type* buf) { cpp11::stop("Unreachable!"); } template <> inline bool r_vector::const_iterator::use_buf(bool is_altrep) { return false; } typedef r_vector strings; namespace writable { template <> inline void r_vector::set_elt(SEXP x, R_xlen_t i, typename r_vector::underlying_type value) { // NOPROTECT: Likely too costly to unwind protect every set elt SET_STRING_ELT(x, i, value); } inline bool operator==(const r_vector::proxy& lhs, r_string rhs) { return static_cast(lhs).operator==(static_cast(rhs).c_str()); } inline SEXP alloc_or_copy(const SEXP data) { switch (detail::r_typeof(data)) { case CHARSXP: return cpp11::r_vector(safe[Rf_allocVector](STRSXP, 1)); case STRSXP: return safe[Rf_shallow_duplicate](data); default: throw type_error(STRSXP, detail::r_typeof(data)); } } inline SEXP alloc_if_charsxp(const SEXP data) { switch (detail::r_typeof(data)) { case CHARSXP: return cpp11::r_vector(safe[Rf_allocVector](STRSXP, 1)); case STRSXP: return data; default: throw type_error(STRSXP, detail::r_typeof(data)); } } template <> inline r_vector::r_vector(const SEXP& data) : cpp11::r_vector(alloc_or_copy(data)), capacity_(length_) { if (detail::r_typeof(data) == CHARSXP) { SET_STRING_ELT(data_, 0, data); } } template <> inline r_vector::r_vector(SEXP&& data) : cpp11::r_vector(alloc_if_charsxp(data)), capacity_(length_) { if (detail::r_typeof(data) == CHARSXP) { SET_STRING_ELT(data_, 0, data); } } // Requires specialization to handle `NA_STRING` and UTF-8 translation template <> inline r_vector::r_vector(std::initializer_list il) : cpp11::r_vector(safe[Rf_allocVector](STRSXP, il.size())), capacity_(il.size()) { unwind_protect([&] { auto it = il.begin(); for (R_xlen_t i = 0; i < capacity_; ++i, ++it) { // i.e. to `SEXP` underlying_type elt = static_cast(*it); if (elt == NA_STRING) { set_elt(data_, i, elt); } else { set_elt(data_, i, Rf_mkCharCE(Rf_translateCharUTF8(elt), CE_UTF8)); } } }); } typedef r_vector strings; template inline void r_vector::push_back(const named_arg& value) { push_back(value.value()); if (Rf_xlength(names()) == 0) { cpp11::writable::strings new_nms(size()); names() = new_nms; } cpp11::writable::strings nms(names()); nms[size() - 1] = value.name(); } } // namespace writable } // namespace cpp11 QuickJSR/src/include/cpp11/as.hpp0000644000176200001440000002326015122664674016177 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for modf #include // for initializer_list #include // for std::shared_ptr, std::weak_ptr, std::unique_ptr #include #include // for string, basic_string #include // for decay, enable_if, is_same, is_convertible #include "cpp11/R.hpp" // for SEXP, SEXPREC, Rf_xlength, R_xlen_t #include "cpp11/protect.hpp" // for stop, protect, safe, protect::function namespace cpp11 { template using enable_if_t = typename std::enable_if::type; template using decay_t = typename std::decay::type; template struct is_smart_ptr : std::false_type {}; template struct is_smart_ptr> : std::true_type {}; template struct is_smart_ptr> : std::true_type {}; template struct is_smart_ptr> : std::true_type {}; template using enable_if_constructible_from_sexp = enable_if_t::value && // workaround for gcc 4.8 std::is_class::value && std::is_constructible::value, R>; template using enable_if_is_sexp = enable_if_t::value, R>; template using enable_if_convertible_to_sexp = enable_if_t::value, R>; template using disable_if_convertible_to_sexp = enable_if_t::value, R>; template using enable_if_integral = enable_if_t::value && !std::is_same::value && !std::is_same::value, R>; template using enable_if_floating_point = typename std::enable_if::value, R>::type; template using enable_if_enum = enable_if_t::value, R>; template using enable_if_bool = enable_if_t::value, R>; template using enable_if_char = enable_if_t::value, R>; template using enable_if_std_string = enable_if_t::value, R>; template using enable_if_c_string = enable_if_t::value, R>; // https://stackoverflow.com/a/1521682/2055486 // inline bool is_convertible_without_loss_to_integer(double value) { double int_part; return std::modf(value, &int_part) == 0.0; } template enable_if_constructible_from_sexp as_cpp(SEXP from) { return T(from); } template enable_if_is_sexp as_cpp(SEXP from) { return from; } template enable_if_integral as_cpp(SEXP from) { if (Rf_isInteger(from)) { if (Rf_xlength(from) == 1) { return INTEGER_ELT(from, 0); } } else if (Rf_isReal(from)) { if (Rf_xlength(from) == 1) { if (ISNA(REAL_ELT(from, 0))) { return NA_INTEGER; } double value = REAL_ELT(from, 0); if (is_convertible_without_loss_to_integer(value)) { return value; } } } else if (Rf_isLogical(from)) { if (Rf_xlength(from) == 1) { if (LOGICAL_ELT(from, 0) == NA_LOGICAL) { return NA_INTEGER; } } } throw std::length_error("Expected single integer value"); } template enable_if_enum as_cpp(SEXP from) { if (Rf_isInteger(from)) { using underlying_type = typename std::underlying_type::type; using int_type = typename std::conditional::value, int, // as_cpp would trigger // undesired string conversions underlying_type>::type; return static_cast(as_cpp(from)); } throw std::length_error("Expected single integer value"); } template enable_if_bool as_cpp(SEXP from) { if (Rf_isLogical(from)) { if (Rf_xlength(from) == 1) { return LOGICAL_ELT(from, 0) == 1; } } throw std::length_error("Expected single logical value"); } template enable_if_floating_point as_cpp(SEXP from) { if (Rf_isReal(from)) { if (Rf_xlength(from) == 1) { return REAL_ELT(from, 0); } } // All 32 bit integers can be coerced to doubles, so we just convert them. if (Rf_isInteger(from)) { if (Rf_xlength(from) == 1) { if (INTEGER_ELT(from, 0) == NA_INTEGER) { return NA_REAL; } return INTEGER_ELT(from, 0); } } // Also allow NA values if (Rf_isLogical(from)) { if (Rf_xlength(from) == 1) { if (LOGICAL_ELT(from, 0) == NA_LOGICAL) { return NA_REAL; } } } throw std::length_error("Expected single double value"); } template enable_if_char as_cpp(SEXP from) { if (Rf_isString(from)) { if (Rf_xlength(from) == 1) { return unwind_protect([&] { return Rf_translateCharUTF8(STRING_ELT(from, 0))[0]; }); } } throw std::length_error("Expected string vector of length 1"); } template enable_if_c_string as_cpp(SEXP from) { if (Rf_isString(from)) { if (Rf_xlength(from) == 1) { // TODO: use vmaxget / vmaxset here? return {unwind_protect([&] { return Rf_translateCharUTF8(STRING_ELT(from, 0)); })}; } } throw std::length_error("Expected string vector of length 1"); } template enable_if_std_string as_cpp(SEXP from) { return {as_cpp(from)}; } /// Temporary workaround for compatibility with cpp11 0.1.0 template enable_if_t, T>::value, decay_t> as_cpp(SEXP from) { return as_cpp>(from); } template enable_if_integral as_sexp(T from) { return safe[Rf_ScalarInteger](from); } template enable_if_floating_point as_sexp(T from) { return safe[Rf_ScalarReal](from); } template enable_if_bool as_sexp(T from) { return safe[Rf_ScalarLogical](from); } template enable_if_c_string as_sexp(T from) { return unwind_protect([&] { return Rf_ScalarString(Rf_mkCharCE(from, CE_UTF8)); }); } template enable_if_std_string as_sexp(const T& from) { return as_sexp(from.c_str()); } template > enable_if_integral as_sexp(const Container& from) { R_xlen_t size = from.size(); SEXP data = safe[Rf_allocVector](INTSXP, size); auto it = from.begin(); int* data_p = INTEGER(data); for (R_xlen_t i = 0; i < size; ++i, ++it) { data_p[i] = *it; } return data; } inline SEXP as_sexp(std::initializer_list from) { return as_sexp>(from); } template > enable_if_floating_point as_sexp(const Container& from) { R_xlen_t size = from.size(); SEXP data = safe[Rf_allocVector](REALSXP, size); auto it = from.begin(); double* data_p = REAL(data); for (R_xlen_t i = 0; i < size; ++i, ++it) { data_p[i] = *it; } return data; } inline SEXP as_sexp(std::initializer_list from) { return as_sexp>(from); } template > enable_if_bool as_sexp(const Container& from) { R_xlen_t size = from.size(); SEXP data = safe[Rf_allocVector](LGLSXP, size); auto it = from.begin(); int* data_p = LOGICAL(data); for (R_xlen_t i = 0; i < size; ++i, ++it) { data_p[i] = *it; } return data; } inline SEXP as_sexp(std::initializer_list from) { return as_sexp>(from); } namespace detail { template SEXP as_sexp_strings(const Container& from, AsCstring&& c_str) { R_xlen_t size = from.size(); SEXP data; try { data = PROTECT(safe[Rf_allocVector](STRSXP, size)); auto it = from.begin(); for (R_xlen_t i = 0; i < size; ++i, ++it) { SET_STRING_ELT(data, i, safe[Rf_mkCharCE](c_str(*it), CE_UTF8)); } } catch (const unwind_exception& e) { UNPROTECT(1); throw e; } UNPROTECT(1); return data; } } // namespace detail class r_string; template using disable_if_r_string = enable_if_t::value, R>; template > enable_if_t::value && !std::is_convertible::value, SEXP> as_sexp(const Container& from) { return detail::as_sexp_strings(from, [](const std::string& s) { return s.c_str(); }); } template enable_if_c_string as_sexp(const Container& from) { return detail::as_sexp_strings(from, [](const char* s) { return s; }); } inline SEXP as_sexp(std::initializer_list from) { return as_sexp>(from); } template > enable_if_convertible_to_sexp as_sexp(const T& from) { return from; } } // namespace cpp11 QuickJSR/src/include/cpp11/r_bool.hpp0000644000176200001440000000425515122664674017053 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include // for numeric_limits #include #include // for is_convertible, enable_if #include "R_ext/Boolean.h" // for Rboolean #include "cpp11/R.hpp" // for SEXP, SEXPREC, ... #include "cpp11/as.hpp" // for as_sexp #include "cpp11/protect.hpp" // for unwind_protect #include "cpp11/r_vector.hpp" #include "cpp11/sexp.hpp" // for sexp namespace cpp11 { class r_bool { public: r_bool() = default; r_bool(SEXP data) { if (Rf_isLogical(data)) { if (Rf_xlength(data) == 1) { value_ = static_cast(LOGICAL_ELT(data, 0)); } } throw std::invalid_argument("Invalid r_bool value"); } r_bool(bool value) : value_(value ? TRUE : FALSE) {} r_bool(Rboolean value) : value_(value) {} r_bool(int value) : value_(from_int(value)) {} operator bool() const { return value_ == TRUE; } operator int() const { return value_; } operator Rboolean() const { return value_ ? TRUE : FALSE; } bool operator==(r_bool rhs) const { return value_ == rhs.value_; } bool operator==(bool rhs) const { return operator==(r_bool(rhs)); } bool operator==(Rboolean rhs) const { return operator==(r_bool(rhs)); } bool operator==(int rhs) const { return operator==(r_bool(rhs)); } private: static constexpr int na = std::numeric_limits::min(); static int from_int(int value) { if (value == static_cast(FALSE)) return FALSE; if (value == static_cast(na)) return na; return TRUE; } int value_ = na; }; inline std::ostream& operator<<(std::ostream& os, r_bool const& value) { os << ((value == TRUE) ? "TRUE" : "FALSE"); return os; } template using enable_if_r_bool = enable_if_t::value, R>; template enable_if_r_bool as_sexp(T from) { sexp res = Rf_allocVector(LGLSXP, 1); unwind_protect([&] { SET_LOGICAL_ELT(res.data(), 0, from); }); return res; } template <> inline r_bool na() { return NA_LOGICAL; } namespace traits { template <> struct get_underlying_type { using type = int; }; } // namespace traits } // namespace cpp11 QuickJSR/src/include/quickjsr/0000755000176200001440000000000015135354472015763 5ustar liggesusersQuickJSR/src/include/quickjsr/SEXP_to_JSValue.hpp0000644000176200001440000002233115122664674021353 0ustar liggesusers#ifndef QUICKJSR_SEXP_TO_JSVALUE_HPP #define QUICKJSR_SEXP_TO_JSVALUE_HPP #include #include #include #include #if R_VERSION < R_Version(4, 5, 0) # define R_ClosureFormals(x) FORMALS(x) # define Rf_isDataFrame(x) Rf_isFrame(x) #endif namespace quickjsr { // Forward declaration to allow for recursive calls inline JSValue SEXP_to_JSValue(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr); inline JSValue SEXP_to_JSValue(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr, int64_t index); inline JSValue SEXP_to_JSValue_array(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr) { JSValue arr = JS_NewArray(ctx); for (int64_t i = 0; i < Rf_xlength(x); i++) { JSValue val = SEXP_to_JSValue(ctx, x, auto_unbox, auto_unbox_curr, i); JS_SetPropertyInt64(ctx, arr, i, val); } return arr; } inline JSValue SEXP_to_JSValue_object(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr) { JSValue obj = JS_NewObject(ctx); SEXP names = Rf_getAttrib(x, R_NamesSymbol); PROTECT(names); for (int64_t i = 0; i < Rf_xlength(x); i++) { JSValue val = SEXP_to_JSValue(ctx, x, auto_unbox, auto_unbox_curr, i); JS_SetPropertyStr(ctx, obj, Rf_translateCharUTF8(STRING_ELT(names, i)), val); } UNPROTECT(1); return obj; } inline JSValue SEXP_to_JSValue_list(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr) { // Following jsonlite conventions: // - R list with names is an object, otherwise an array if (Rf_getAttrib(x, R_NamesSymbol) != R_NilValue) { return SEXP_to_JSValue_object(ctx, x, auto_unbox, auto_unbox_curr); } else { return SEXP_to_JSValue_array(ctx, x, auto_unbox, auto_unbox_curr); } } inline JSValue SEXP_to_JSValue_df(JSContext* ctx, const SEXP& x, bool auto_unbox_inp = false, bool auto_unbox = false) { SEXP col_names = Rf_getAttrib(x, R_NamesSymbol); PROTECT(col_names); SEXP row_names = Rf_getAttrib(x, R_RowNamesSymbol); PROTECT(row_names); JSValue arr = JS_NewArray(ctx); for (int64_t i = 0; i < Rf_xlength(VECTOR_ELT(x, 0)); i++) { JSValue obj = JS_NewObject(ctx); for (int64_t j = 0; j < Rf_xlength(x); j++) { SEXP col = VECTOR_ELT(x, j); if (Rf_isDataFrame(col)) { JSValue df_obj = JS_NewObject(ctx); SEXP df_names = Rf_getAttrib(col, R_NamesSymbol); PROTECT(df_names); for (int64_t k = 0; k < Rf_xlength(col); k++) { JSValue val = SEXP_to_JSValue(ctx, VECTOR_ELT(col, k), auto_unbox_inp, auto_unbox, i); JS_SetPropertyStr(ctx, df_obj, Rf_translateCharUTF8(STRING_ELT(df_names, k)), val); } UNPROTECT(1); JS_SetPropertyStr(ctx, obj, Rf_translateCharUTF8(STRING_ELT(col_names, j)), df_obj); } else { JSValue val = SEXP_to_JSValue(ctx, col, auto_unbox_inp, auto_unbox, i); JS_SetPropertyStr(ctx, obj, Rf_translateCharUTF8(STRING_ELT(col_names, j)), val); } } // If row names are present and a character vector, add them to the object if (Rf_isString(row_names)) { JSValue row_name = JS_NewString(ctx, Rf_translateCharUTF8(STRING_ELT(row_names, i))); JS_SetPropertyStr(ctx, obj, "_row", row_name); } JS_SetPropertyInt64(ctx, arr, i, obj); } UNPROTECT(2); return arr; } static JSValue js_fun_static(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic, JSValue* data) { JSValue data_val = data[0]; SEXP x = reinterpret_cast(JS_GetOpaque(data_val, js_sexp_class_id)); JS_FreeValue(ctx, data_val); if (argc == 0) { return SEXP_to_JSValue(ctx, cpp11::function(x)(), true, true); } cpp11::writable::list args(argc); for (int i = 0; i < argc; i++) { args[i] = JSValue_to_SEXP(ctx, argv[i]); } cpp11::function do_call = cpp11::package("base")["do.call"]; return SEXP_to_JSValue(ctx, do_call(x, args), true, true); } inline JSValue SEXP_to_JSValue_function(JSContext* ctx, const SEXP& x, bool auto_unbox_inp = false, bool auto_unbox = false) { JSValue obj = JS_NewObjectClass(ctx, js_sexp_class_id); JS_SetOpaque(obj, reinterpret_cast(x)); return JS_NewCFunctionData(ctx, js_fun_static, Rf_xlength(R_ClosureFormals(x)), JS_CFUNC_generic, 1, &obj); } inline JSValue SEXP_to_JSValue_env(JSContext* ctx, const SEXP& x) { JSValue obj = JS_NewObjectClass(ctx, js_renv_class_id); JS_SetOpaque(obj, reinterpret_cast(x)); return obj; } inline JSValue SEXP_to_JSValue_matrix(JSContext* ctx, const SEXP& x, bool auto_unbox_inp = false, bool auto_unbox = false) { int64_t nrow = Rf_nrows(x); int64_t ncol = Rf_ncols(x); JSValue arr = JS_NewArray(ctx); for (int64_t i = 0; i < nrow; i++) { JSValue row = JS_NewArray(ctx); for (int64_t j = 0; j < ncol; j++) { JSValue val = SEXP_to_JSValue(ctx, x, auto_unbox_inp, auto_unbox, i + j * nrow); JS_SetPropertyInt64(ctx, row, j, val); } JS_SetPropertyInt64(ctx, arr, i, row); } return arr; } inline JSValue SEXP_to_JSValue(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr, int64_t index) { if (Rf_isDataFrame(x)) { return SEXP_to_JSValue_df(ctx, VECTOR_ELT(x, index), auto_unbox, auto_unbox_curr); } if (Rf_isNewList(x)) { return SEXP_to_JSValue(ctx, VECTOR_ELT(x, index), auto_unbox, auto_unbox_curr); } switch (TYPEOF(x)) { case NILSXP: return JS_NULL; case LGLSXP: { if (LOGICAL_ELT(x, index) == NA_LOGICAL) { return JS_NULL; } return JS_NewBool(ctx, LOGICAL_ELT(x, index)); } case INTSXP: { if (INTEGER_ELT(x, index) == NA_INTEGER) { return JS_NULL; } else if (Rf_inherits(x, "factor")) { SEXP levels = Rf_getAttrib(x, R_LevelsSymbol); return JS_NewString(ctx, Rf_translateCharUTF8(STRING_ELT(levels, INTEGER_ELT(x, index) - 1))); } else { return JS_NewInt32(ctx, INTEGER_ELT(x, index)); } } case REALSXP: { if (ISNA(REAL_ELT(x, index))) { return JS_NULL; } else if (Rf_inherits(x, "POSIXct") || Rf_inherits(x, "POSIXt") || Rf_inherits(x, "Date")) { cpp11::writable::doubles x_index(1); x_index[0] = REAL_ELT(x, index); // Match input classes x_index.attr("class") = Rf_getAttrib(x, R_ClassSymbol); cpp11::function format = cpp11::package("base")["format"]; std::string formatted = cpp11::as_cpp(format(x_index, "format"_nm = "%Y-%m-%dT%H:%M:%OSZ", "tz"_nm = "UTC")); // Create new Date from ISO string using JS_CallConstructor JSValue global = JS_GetGlobalObject(ctx); JSValue date_ctor = JS_GetPropertyStr(ctx, global, "Date"); JSValue iso_str = JS_NewString(ctx, formatted.c_str()); JSValue date_obj = JS_CallConstructor(ctx, date_ctor, 1, &iso_str); JS_FreeValue(ctx, iso_str); JS_FreeValue(ctx, date_ctor); JS_FreeValue(ctx, global); return date_obj; } else { return JS_NewFloat64(ctx, REAL_ELT(x, index)); } } case STRSXP: { if (STRING_ELT(x, index) == NA_STRING) { return JS_NULL; } return JS_NewString(ctx, Rf_translateCharUTF8(STRING_ELT(x, index))); } case VECSXP: return SEXP_to_JSValue(ctx, VECTOR_ELT(x, index), auto_unbox, auto_unbox_curr); case CLOSXP: return SEXP_to_JSValue_function(ctx, x, auto_unbox, auto_unbox_curr); case ENVSXP: return SEXP_to_JSValue_env(ctx, x); default: cpp11::stop("Conversions for type %s to JSValue are not yet implemented", Rf_type2char(TYPEOF(x))); } } inline JSValue SEXP_to_JSValue_null(JSContext* ctx, bool auto_unbox) { if (auto_unbox) { return JS_NULL; } else { JSValue arr = JS_NewArray(ctx); JS_SetPropertyInt64(ctx, arr, 0, JS_NULL); return arr; } } inline JSValue SEXP_to_JSValue(JSContext* ctx, const SEXP& x, bool auto_unbox_inp = false, bool auto_unbox = false) { bool auto_unbox_curr = static_cast(Rf_inherits(x, "AsIs")) ? false : auto_unbox_inp; if (Rf_isNull(x)) { return SEXP_to_JSValue_null(ctx, auto_unbox_curr); } if (Rf_isDataFrame(x)) { return SEXP_to_JSValue_df(ctx, x, auto_unbox_inp, auto_unbox_curr); } if (Rf_isNewList(x)) { return SEXP_to_JSValue_list(ctx, x, auto_unbox_inp, auto_unbox_curr); } if (Rf_isMatrix(x)) { return SEXP_to_JSValue_matrix(ctx, x, auto_unbox_inp, auto_unbox_curr); } if (Rf_isVectorAtomic(x) || Rf_isArray(x)) { if (Rf_xlength(x) > 1 || !auto_unbox_curr || Rf_isArray(x)) { return SEXP_to_JSValue_array(ctx, x, auto_unbox_inp, auto_unbox_curr); } } return SEXP_to_JSValue(ctx, x, auto_unbox_inp, auto_unbox_curr, 0); } } // namespace quickjsr #endif QuickJSR/src/include/quickjsr/JSValue_to_SEXP.hpp0000644000176200001440000002252515122664674021360 0ustar liggesusers#ifndef QUICKJSR_JSVALUE_TO_SEXP_HPP #define QUICKJSR_JSVALUE_TO_SEXP_HPP #include #include namespace quickjsr { enum BaseType { Number, String, Boolean, DateNew, Null, Array, ObjectNew, Mixed, Error }; BaseType value_to_base_type(const JSValue& value) { if (JS_IsException(value)) { return Error; } if (JS_IsNull(value) || JS_IsUndefined(value) || JS_IsUninitialized(value)) { return Null; } if (JS_IsBool(value)) { return Boolean; } if (JS_IsString(value)) { return String; } if (JS_IsDate(value)) { return DateNew; } if (JS_IsNumber(value)) { return Number; } if (JS_IsArray(value)) { return Array; } if (JS_IsObject(value)) { return ObjectNew; } return Mixed; } BaseType combine_array_types(BaseType a, BaseType b) { if (a == Mixed || b == Mixed) { return Mixed; } if (a == ObjectNew || b == ObjectNew) { return Mixed; } if (a == Array || b == Array) { return Mixed; } if (a == Null) { return b; } if (b == Null) { return a; } if (a == b) { return a; } if ((a == Number && b == Boolean) || (a == Boolean && b == Number)) { return Number; } if ((a == String && b == Number) || (a == Number && b == String)) { return String; } if ((a == String && b == Boolean) || (a == Boolean && b == String)) { return String; } return Mixed; } SEXP JSValue_to_SEXP(JSContext* ctx, const JSValue& val); SEXP date_sexp(JSContext* ctx, const JSValue& val) { // Extract getIsoString from the Date object JSValue iso_str_func = JS_GetPropertyStr(ctx, val, "toISOString"); if (JS_IsException(iso_str_func) || !JS_IsFunction(ctx, iso_str_func)) { JS_FreeValue(ctx, iso_str_func); return R_NilValue; } JSValue iso_str_val = JS_Call(ctx, iso_str_func, val, 0, NULL); JS_FreeValue(ctx, iso_str_func); if (JS_IsException(iso_str_val) || !JS_IsString(iso_str_val)) { JS_FreeValue(ctx, iso_str_val); return R_NilValue; } const char* res = JS_ToCString(ctx, iso_str_val); cpp11::function as_posix = cpp11::package("base")["as.POSIXct"]; SEXP out = as_posix(res, "tz"_nm = "UTC", "format"_nm = "%Y-%m-%dT%H:%M:%OSZ"); JS_FreeValue(ctx, iso_str_val); JS_FreeCString(ctx, res); return out; } SEXP array_sexp(JSContext* ctx, const JSValue& val) { // Handle as array int64_t len; JS_GetLength(ctx, val, &len); JSValue base_val = JS_GetPropertyInt64(ctx, val, 0); BaseType prev_type = value_to_base_type(base_val); JS_FreeValue(ctx, base_val); for (int64_t i = 1; i < len; i++) { base_val = JS_GetPropertyInt64(ctx, val, i); BaseType curr_type = value_to_base_type(base_val); JS_FreeValue(ctx, base_val); prev_type = combine_array_types(prev_type, curr_type); if (prev_type == Mixed) { // No need to continue checking types, we know it's mixed break; } } if (prev_type == Number) { cpp11::writable::doubles out(len); for (int64_t i = 0; i < len; i++) { base_val = JS_GetPropertyInt64(ctx, val, i); if (JS_IsNull(base_val) || JS_IsUndefined(base_val)) { out[static_cast(i)] = NA_REAL; } else { double res; JS_ToFloat64(ctx, &res, base_val); out[static_cast(i)] = res; } JS_FreeValue(ctx, base_val); } return out; } else if (prev_type == String) { cpp11::writable::strings out(len); for (int64_t i = 0; i < len; i++) { base_val = JS_GetPropertyInt64(ctx, val, i); if (JS_IsNull(base_val) || JS_IsUndefined(base_val)) { out[static_cast(i)] = NA_STRING; } else if (JS_IsBool(base_val)) { out[static_cast(i)] = JS_ToBool(ctx, base_val) ? "TRUE" : "FALSE"; } else if (JS_VALUE_GET_TAG(base_val) == JS_TAG_INT) { int32_t res = JS_VALUE_GET_INT(base_val); out[static_cast(i)] = std::to_string(res); } else if (JS_VALUE_GET_TAG(base_val) == JS_TAG_BIG_INT) { int64_t res; JS_ToBigInt64(ctx, &res, base_val); out[static_cast(i)] = std::to_string(res); } else if (JS_VALUE_GET_TAG(base_val) == JS_TAG_SHORT_BIG_INT) { int64_t res = JS_VALUE_GET_SHORT_BIG_INT(base_val); out[static_cast(i)] = std::to_string(res); } else if (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(base_val))) { double res; JS_ToFloat64(ctx, &res, base_val); std::string str_res; if (std::isnan(res)) { str_res = "NaN"; } else if (std::isinf(res)) { str_res = (res > 0) ? "Inf" : "-Inf"; } else { str_res = std::to_string(res); // Remove trailing zeros str_res.erase(str_res.find_last_not_of('0') + 1, std::string::npos); // If the last character is a decimal point, remove it if (str_res.back() == '.') { str_res.pop_back(); } } out[static_cast(i)] = str_res; } else { const char* res = JS_ToCString(ctx, base_val); out[static_cast(i)] = res; JS_FreeCString(ctx, res); } JS_FreeValue(ctx, base_val); } return out; } else if (prev_type == Boolean || prev_type == Null) { cpp11::writable::logicals out(len); for (int64_t i = 0; i < len; i++) { base_val = JS_GetPropertyInt64(ctx, val, i); if (JS_IsNull(base_val) || JS_IsUndefined(base_val)) { out[static_cast(i)] = NA_LOGICAL; } else { out[static_cast(i)] = static_cast(JS_ToBool(ctx, base_val)); } JS_FreeValue(ctx, base_val); } return out; } else { // Mixed types, return as list cpp11::writable::list out(len); bool all_double = true; bool all_same_size = true; int64_t first_size = -1; for (int64_t i = 0; i < len; i++) { JSValue elem = JS_GetPropertyInt64(ctx, val, i); SEXP elem_sexp = JSValue_to_SEXP(ctx, elem); if (all_double && all_same_size) { if (TYPEOF(elem_sexp) != REALSXP) { all_double = false; } R_xlen_t elem_size = Rf_xlength(elem_sexp); if (first_size == -1) { first_size = elem_size; } else if (elem_size != first_size) { all_same_size = false; } } out[static_cast(i)] = elem_sexp; JS_FreeValue(ctx, elem); } if (all_double && all_same_size) { cpp11::function unlist = cpp11::package("base")["unlist"]; cpp11::function matrix = cpp11::package("base")["matrix"]; return matrix(unlist(out), len, first_size, true); } else { return out; } } } SEXP object_sexp(JSContext* ctx, const JSValue& val) { // Handle as object // Get the keys of the object JSPropertyEnum* tab = NULL; uint32_t len = 0; JS_GetOwnPropertyNames(ctx, &tab, &len, val, JS_GPN_STRING_MASK); cpp11::writable::strings keys(len); cpp11::writable::list out(len); for (uint32_t i = 0; i < len; i++) { JSValue elem = JS_GetProperty(ctx, val, tab[i].atom); out[static_cast(i)] = JSValue_to_SEXP(ctx, elem); const char* key = JS_AtomToCString(ctx, tab[i].atom); keys[static_cast(i)] = key; JS_FreeValue(ctx, elem); JS_FreeCString(ctx, key); } JS_FreePropertyEnum(ctx, tab, len); out.attr("names") = keys; return out; } SEXP JSValue_to_SEXP(JSContext* ctx, const JSValue& val) { switch (JS_VALUE_GET_TAG(val)) { case JS_TAG_EXCEPTION: { JSValue exc = JS_GetException(ctx); const char* res_str = JS_ToCString(ctx, val); std::string msg = res_str; JS_FreeCString(ctx, res_str); JS_FreeValue(ctx, exc); cpp11::stop("JavaScript Exception: " + msg); } case JS_TAG_NULL: { return R_NilValue; } case JS_TAG_UNDEFINED: { return R_NilValue; } case JS_TAG_UNINITIALIZED: { return R_NilValue; } case JS_TAG_BOOL: { return cpp11::as_sexp(static_cast(JS_ToBool(ctx, val))); } case JS_TAG_INT: { return cpp11::as_sexp(JS_VALUE_GET_INT(val)); } case JS_TAG_SHORT_BIG_INT: { return cpp11::as_sexp(JS_VALUE_GET_SHORT_BIG_INT(val)); } case JS_TAG_BIG_INT: { int64_t res; JS_ToBigInt64(ctx, &res, val); return cpp11::as_sexp(res); } case JS_TAG_FLOAT64: { if (JS_VALUE_IS_NAN(val)) { return cpp11::as_sexp(R_NaN); } return cpp11::as_sexp(JS_VALUE_GET_FLOAT64(val)); } case JS_TAG_STRING: { const char* res = JS_ToCString(ctx, val); std::string res_str = res ? res : ""; JS_FreeCString(ctx, res); return cpp11::as_sexp(res_str); } case JS_TAG_OBJECT: { if (JS_IsDate(val)) { return date_sexp(ctx, val); } else if (JS_IsArray(val)) { return array_sexp(ctx, val); } else { return object_sexp(ctx, val); } } default: { return R_NilValue; } } return R_NilValue; // Fallback for unhandled types } } // namespace quickjsr #endif QuickJSR/src/include/quickjsr/type_traits.hpp0000644000176200001440000000145415122664674021053 0ustar liggesusers#ifndef QUICKJSR_TYPE_TRAITS_HPP #define QUICKJSR_TYPE_TRAITS_HPP #include #include namespace quickjsr { template struct is_std_vector : std::false_type {}; template struct is_std_vector> : std::true_type {}; template struct value_type { using type = typename std::decay::type; }; template struct value_type::value>::type> { using type = typename std::decay::type::value_type; }; template using value_type_t = typename value_type::type; template using enable_if_type_t = typename std::enable_if::value>::type; } // namespace quickjsr #endif QuickJSR/src/include/quickjsr/JS_PropertyRecursive.hpp0000644000176200001440000000304415122664674022611 0ustar liggesusers#ifndef QUICKJSR_JS_GET_PROPERTY_RECURSIVE_HPP #define QUICKJSR_JS_GET_PROPERTY_RECURSIVE_HPP #include #include #include namespace quickjsr { JSValue JS_GetPropertyRecursive(JSContext* ctx, JSValue obj, const char* name) { const char* dot = strchr(name, '.'); if (dot) { // The name contains a ".", so we extract the first property and recurse on the rest of the name std::string first_property_name(name, dot - name); JSValue first_property = JS_GetPropertyStr(ctx, obj, first_property_name.c_str()); JSValue result = JS_GetPropertyRecursive(ctx, first_property, dot + 1); JS_FreeValue(ctx, first_property); return result; } else { // The name does not contain a ".", so we get the property from the object return JS_GetPropertyStr(ctx, obj, name); } } int JS_SetPropertyRecursive(JSContext* ctx, JSValue obj, const char* name, JSValue value) { const char* dot = strchr(name, '.'); if (dot) { // The name contains a ".", so we extract the first property and recurse on the rest of the name std::string first_property_name(name, dot - name); JSValue first_property = JS_GetPropertyStr(ctx, obj, first_property_name.c_str()); int result = JS_SetPropertyRecursive(ctx, first_property, dot + 1, value); JS_FreeValue(ctx, first_property); return result; } else { // The name does not contain a ".", so we set the property on the object return JS_SetPropertyStr(ctx, obj, name, value); } } } #endif QuickJSR/src/include/quickjsr/JS_SEXP.hpp0000644000176200001440000000573415122664674017664 0ustar liggesusers#ifndef QUICKJSR_JS_SEXP_HPP #define QUICKJSR_JS_SEXP_HPP #include #include #include // Need to redefine the JS_CFUNC_DEF macro as it uses C features // (designated initializers) which are not supported in C++ (until C++20) #define JS_CFUNC_DEF_CPP(name, length, func1) { \ name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, \ { { length, JS_CFUNC_generic, { func1 } } } \ } #ifndef countof #define countof(x) (sizeof(x) / sizeof((x)[0])) #endif namespace quickjsr { inline JSValue SEXP_to_JSValue(JSContext* ctx, const SEXP& x, bool auto_unbox, bool auto_unbox_curr); JSClassID js_sexp_class_id = 100; JSClassID js_renv_class_id = 101; JSClassDef js_sexp_class_def = { "SEXP", nullptr // finalized }; static JSValue js_renv_get_property(JSContext *ctx, JSValueConst this_val, JSAtom atom, JSValueConst receiver) { const char *property_name = JS_AtomToCString(ctx, atom); JS_FreeCString(ctx, property_name); SEXP x = reinterpret_cast(JS_GetOpaque(this_val, js_renv_class_id)); cpp11::environment env(x); SEXP fun = env[property_name]; if (TYPEOF(fun) == PROMSXP) { fun = Rf_eval(fun, env); } return SEXP_to_JSValue(ctx, fun, true, true); } static int js_renv_set_property(JSContext *ctx, JSValueConst this_val, JSAtom atom, JSValueConst value, JSValueConst receiver, int flags) { const char *property_name = JS_AtomToCString(ctx, atom); JS_FreeCString(ctx, property_name); SEXP x = reinterpret_cast(JS_GetOpaque(this_val, js_renv_class_id)); cpp11::environment env(x); env[property_name] = JSValue_to_SEXP(ctx, value); return 0; } JSClassExoticMethods js_renv_exotic_methods = { nullptr, nullptr, nullptr, nullptr, nullptr, js_renv_get_property, js_renv_set_property }; JSClassDef js_renv_class_def = { "REnv", nullptr, nullptr, nullptr, &js_renv_exotic_methods }; static JSValue js_r_package(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { if (argc != 1) { return JS_ThrowTypeError(ctx, "R.package requires one argument"); } const char *package_name = JS_ToCString(ctx, argv[0]); JS_FreeCString(ctx, package_name); if (!package_name) { return JS_EXCEPTION; } SEXP pkg_ns; if (strcmp(package_name, "base") == 0) { pkg_ns = R_BaseEnv; } else { SEXP pkg_name_sexp = Rf_mkString(package_name); pkg_ns = R_FindNamespace(pkg_name_sexp); } return SEXP_to_JSValue(ctx, pkg_ns, true, true); } static const JSCFunctionListEntry js_r_funcs[] = { JS_CFUNC_DEF_CPP("package", 1, js_r_package), }; static JSValue create_r_object(JSContext *ctx) { JSValue r_obj = JS_NewObject(ctx); if (JS_IsException(r_obj)) { return r_obj; } JS_SetPropertyFunctionList(ctx, r_obj, js_r_funcs, countof(js_r_funcs)); return r_obj; } } #endif QuickJSR/src/include/quickjsr.hpp0000644000176200001440000000036415122664674016503 0ustar liggesusers#ifndef QUICKJSR_HPP #define QUICKJSR_HPP #include #include #include #include #include #endif QuickJSR/src/include/cpp11.hpp0000644000176200001440000000130715122664674015572 0ustar liggesusers// cpp11 version: 0.5.1 // vendored on: 2024-12-26 #pragma once #include "cpp11/R.hpp" #include "cpp11/altrep.hpp" #include "cpp11/as.hpp" #include "cpp11/attribute_proxy.hpp" #include "cpp11/data_frame.hpp" #include "cpp11/doubles.hpp" #include "cpp11/environment.hpp" #include "cpp11/external_pointer.hpp" #include "cpp11/function.hpp" #include "cpp11/integers.hpp" #include "cpp11/list.hpp" #include "cpp11/list_of.hpp" #include "cpp11/logicals.hpp" #include "cpp11/matrix.hpp" #include "cpp11/named_arg.hpp" #include "cpp11/protect.hpp" #include "cpp11/r_bool.hpp" #include "cpp11/r_string.hpp" #include "cpp11/r_vector.hpp" #include "cpp11/raws.hpp" #include "cpp11/sexp.hpp" #include "cpp11/strings.hpp" QuickJSR/src/init.cpp0000644000176200001440000000247115122664674014164 0ustar liggesusers#include #include extern "C" { SEXP qjs_context_(SEXP stack_size_); SEXP qjs_source_(SEXP ctx_ptr_, SEXP input_, SEXP is_file_); SEXP qjs_validate_(SEXP ctx_ptr_, SEXP code_string_); SEXP qjs_call_(SEXP ctx_ptr_, SEXP function_name_, SEXP args_json_); SEXP qjs_get_(SEXP ctx_ptr_, SEXP js_obj_name); SEXP qjs_assign_(SEXP ctx_ptr_, SEXP js_obj_name_, SEXP value_); SEXP qjs_eval_(SEXP eval_string_); SEXP to_json_(SEXP arg_, SEXP auto_unbox_); SEXP from_json_(SEXP json_); SEXP qjs_version_(); static const R_CallMethodDef CallEntries[] = { {"qjs_call_", (DL_FUNC) &qjs_call_, 3}, {"qjs_context_", (DL_FUNC) &qjs_context_, 1}, {"qjs_eval_", (DL_FUNC) &qjs_eval_, 1}, {"qjs_source_", (DL_FUNC) &qjs_source_, 3}, {"qjs_validate_", (DL_FUNC) &qjs_validate_, 2}, {"qjs_get_", (DL_FUNC) &qjs_get_, 2}, {"qjs_assign_", (DL_FUNC) &qjs_assign_, 3}, {"to_json_", (DL_FUNC) &to_json_, 2}, {"from_json_", (DL_FUNC) &from_json_, 1}, {"qjs_version_", (DL_FUNC) &qjs_version_, 0}, {NULL, NULL, 0} }; attribute_visible void R_init_QuickJSR(DllInfo* dll){ R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); R_forceSymbols(dll, TRUE); } } QuickJSR/src/libquickjs.c0000644000176200001440000000026415122664674015017 0ustar liggesusers#include "quickjs/cutils.c" #include "quickjs/dtoa.c" #include "quickjs/libregexp.c" #include "quickjs/libunicode.c" #include "quickjs/quickjs.c" #include "quickjs/quickjs-libc.c" QuickJSR/src/Makevars0000644000176200001440000000234615122664674014212 0ustar liggesusersPKG_CPPFLAGS = -I"include" -I"quickjs" -D_GNU_SOURCE PKG_LIBS = libquickjs.o ifeq ($(OS),Windows_NT) DLL := .dll else DLL := .so endif ifdef R_HOME R_CC := $(shell $(R_HOME)/bin$(R_ARCH_BIN)/R CMD config CC) R_CXX := $(shell $(R_HOME)/bin$(R_ARCH_BIN)/R CMD config CXX) else R_CC := $(CC) R_CXX := $(CXX) endif CLANG_CHECK := $(shell echo | $(R_CC) -dM -E - | grep -i __clang__) ifneq (,$(CLANG_CHECK)) # Clang on armel needs libatomic ifeq ($(shell uname -m), armv7l) CC_TARGET := $(shell $(R_CXX) -v 2>&1 | grep Target | cut -d ' ' -f 2) ifeq ($(findstring gnueabihf,$(CC_TARGET)),) PKG_LIBS += -latomic endif endif else # Explicit -latomic is needed for 32-bit builds only on GCC ifeq ($(shell getconf LONG_BIT), 32) PKG_LIBS += -latomic endif endif SOURCES = quickjsr.cpp init.cpp OBJECTS = $(SOURCES:.cpp=.o) $(SHLIB): $(OBJECTS) $(OBJECTS): build-static build-static: # @mkdir -p ../inst/include/quickjs # @cp $(wildcard quickjs/*.h) ../inst/include/quickjs $(R_CC) $(ALL_CPPFLAGS) $(ALL_CFLAGS) -funsigned-char -std=gnu11 -c libquickjs.c # @mkdir -p ../inst/lib/$(R_ARCH) # $(AR) -rs ../inst/lib/$(R_ARCH)/libquickjs.a libquickjs.o clean: $(RM) libquickjs.o $(OBJECTS) $(RM) -r ../inst/lib ../inst/include/quickjs QuickJSR/src/quickjs/0000755000176200001440000000000015135347454014160 5ustar liggesusersQuickJSR/src/quickjs/libunicode.h0000644000176200001440000000730015122664706016444 0ustar liggesusers/* * Unicode utilities * * Copyright (c) 2017-2018 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef LIBUNICODE_H #define LIBUNICODE_H #include #include #include #ifdef __cplusplus extern "C" { #endif #define LRE_CC_RES_LEN_MAX 3 typedef enum { UNICODE_NFC, UNICODE_NFD, UNICODE_NFKC, UNICODE_NFKD, } UnicodeNormalizationEnum; int lre_case_conv(uint32_t *res, uint32_t c, int conv_type); int lre_canonicalize(uint32_t c, bool is_unicode); bool lre_is_cased(uint32_t c); bool lre_is_case_ignorable(uint32_t c); /* char ranges */ typedef struct { int len; /* in points, always even */ int size; uint32_t *points; /* points sorted by increasing value */ void *mem_opaque; void *(*realloc_func)(void *opaque, void *ptr, size_t size); } CharRange; typedef enum { CR_OP_UNION, CR_OP_INTER, CR_OP_XOR, } CharRangeOpEnum; void cr_init(CharRange *cr, void *mem_opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); void cr_free(CharRange *cr); int cr_realloc(CharRange *cr, int size); int cr_copy(CharRange *cr, const CharRange *cr1); static inline int cr_add_point(CharRange *cr, uint32_t v) { if (cr->len >= cr->size) { if (cr_realloc(cr, cr->len + 1)) return -1; } cr->points[cr->len++] = v; return 0; } static inline int cr_add_interval(CharRange *cr, uint32_t c1, uint32_t c2) { if ((cr->len + 2) > cr->size) { if (cr_realloc(cr, cr->len + 2)) return -1; } cr->points[cr->len++] = c1; cr->points[cr->len++] = c2; return 0; } int cr_union1(CharRange *cr, const uint32_t *b_pt, int b_len); static inline int cr_union_interval(CharRange *cr, uint32_t c1, uint32_t c2) { uint32_t b_pt[2]; b_pt[0] = c1; b_pt[1] = c2 + 1; return cr_union1(cr, b_pt, 2); } int cr_op(CharRange *cr, const uint32_t *a_pt, int a_len, const uint32_t *b_pt, int b_len, int op); int cr_invert(CharRange *cr); int cr_regexp_canonicalize(CharRange *cr, bool is_unicode); bool lre_is_id_start(uint32_t c); bool lre_is_id_continue(uint32_t c); bool lre_is_white_space(uint32_t c); int unicode_normalize(uint32_t **pdst, const uint32_t *src, int src_len, UnicodeNormalizationEnum n_type, void *opaque, void *(*realloc_func)(void *opaque, void *ptr, size_t size)); /* Unicode character range functions */ int unicode_script(CharRange *cr, const char *script_name, bool is_ext); int unicode_general_category(CharRange *cr, const char *gc_name); int unicode_prop(CharRange *cr, const char *prop_name); #ifdef __cplusplus } /* extern "C" { */ #endif #endif /* LIBUNICODE_H */ QuickJSR/src/quickjs/dtoa.c0000644000176200001440000012753415122664706015265 0ustar liggesusers/* * Tiny float64 printing and parsing library * * Copyright (c) 2024 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include #include #include #include #include #include #include // #include #include // #include #include "cutils.h" #include "dtoa.h" /* TODO: - test n_digits=101 instead of 100 - simplify subnormal handling - reduce max memory usage - free format: could add shortcut if exact result - use 64 bit limb_t when possible - use another algorithm for free format dtoa in base 10 (ryu ?) */ #define USE_POW5_TABLE /* use fast path to print small integers in free format */ #define USE_FAST_INT #define LIMB_LOG2_BITS 5 #define LIMB_BITS (1 << LIMB_LOG2_BITS) typedef int32_t slimb_t; typedef uint32_t limb_t; typedef uint64_t dlimb_t; #define LIMB_DIGITS 9 #define JS_RADIX_MAX 36 #define DBIGNUM_LEN_MAX 52 /* ~ 2^(1072+53)*36^100 (dtoa) */ #define MANT_LEN_MAX 18 /* < 36^100 */ typedef intptr_t mp_size_t; /* the represented number is sum(i, tab[i]*2^(LIMB_BITS * i)) */ typedef struct { int len; /* >= 1 */ limb_t tab[]; } mpb_t; static limb_t mp_add_ui(limb_t *tab, limb_t b, size_t n) { size_t i; limb_t k, a; k=b; for(i=0;i> LIMB_BITS; } return l; } /* WARNING: d must be >= 2^(LIMB_BITS-1) */ static inline limb_t udiv1norm_init(limb_t d) { limb_t a0, a1; a1 = -d - 1; a0 = -1; return (((dlimb_t)a1 << LIMB_BITS) | a0) / d; } /* return the quotient and the remainder in '*pr'of 'a1*2^LIMB_BITS+a0 / d' with 0 <= a1 < d. */ static inline limb_t udiv1norm(limb_t *pr, limb_t a1, limb_t a0, limb_t d, limb_t d_inv) { limb_t n1m, n_adj, q, r, ah; dlimb_t a; n1m = ((slimb_t)a0 >> (LIMB_BITS - 1)); n_adj = a0 + (n1m & d); a = (dlimb_t)d_inv * (a1 - n1m) + n_adj; q = (a >> LIMB_BITS) + a1; /* compute a - q * r and update q so that the remainder is between 0 and d - 1 */ a = ((dlimb_t)a1 << LIMB_BITS) | a0; a = a - (dlimb_t)q * d - d; ah = a >> LIMB_BITS; q += 1 + ah; r = (limb_t)a + (ah & d); *pr = r; return q; } static limb_t mp_div1(limb_t *tabr, const limb_t *taba, limb_t n, limb_t b, limb_t r) { slimb_t i; dlimb_t a1; for(i = n - 1; i >= 0; i--) { a1 = ((dlimb_t)r << LIMB_BITS) | taba[i]; tabr[i] = a1 / b; r = a1 % b; } return r; } /* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift). 1 <= shift <= LIMB_BITS - 1 */ static limb_t mp_shr(limb_t *tab_r, const limb_t *tab, mp_size_t n, int shift, limb_t high) { mp_size_t i; limb_t l, a; assert(shift >= 1 && shift < LIMB_BITS); l = high; for(i = n - 1; i >= 0; i--) { a = tab[i]; tab_r[i] = (a >> shift) | (l << (LIMB_BITS - shift)); l = a; } return l & (((limb_t)1 << shift) - 1); } /* r = (a << shift) + low. 1 <= shift <= LIMB_BITS - 1, 0 <= low < 2^shift. */ static limb_t mp_shl(limb_t *tab_r, const limb_t *tab, mp_size_t n, int shift, limb_t low) { mp_size_t i; limb_t l, a; assert(shift >= 1 && shift < LIMB_BITS); l = low; for(i = 0; i < n; i++) { a = tab[i]; tab_r[i] = (a << shift) | l; l = (a >> (LIMB_BITS - shift)); } return l; } static no_inline limb_t mp_div1norm(limb_t *tabr, const limb_t *taba, limb_t n, limb_t b, limb_t r, limb_t b_inv, int shift) { slimb_t i; if (shift != 0) { r = (r << shift) | mp_shl(tabr, taba, n, shift, 0); } for(i = n - 1; i >= 0; i--) { tabr[i] = udiv1norm(&r, r, taba[i], b, b_inv); } r >>= shift; return r; } static __maybe_unused void mpb_dump(const char *str, const mpb_t *a) { int i; printf("%s= 0x", str); for(i = a->len - 1; i >= 0; i--) { printf("%08x", a->tab[i]); if (i != 0) printf("_"); } printf("\n"); } static void mpb_renorm(mpb_t *r) { while (r->len > 1 && r->tab[r->len - 1] == 0) r->len--; } #ifdef USE_POW5_TABLE static const uint32_t pow5_table[17] = { 0x00000005, 0x00000019, 0x0000007d, 0x00000271, 0x00000c35, 0x00003d09, 0x0001312d, 0x0005f5e1, 0x001dcd65, 0x009502f9, 0x02e90edd, 0x0e8d4a51, 0x48c27395, 0x6bcc41e9, 0x1afd498d, 0x86f26fc1, 0xa2bc2ec5, }; static const uint8_t pow5h_table[4] = { 0x00000001, 0x00000007, 0x00000023, 0x000000b1, }; static const uint32_t pow5_inv_table[13] = { 0x99999999, 0x47ae147a, 0x0624dd2f, 0xa36e2eb1, 0x4f8b588e, 0x0c6f7a0b, 0xad7f29ab, 0x5798ee23, 0x12e0be82, 0xb7cdfd9d, 0x5fd7fe17, 0x19799812, 0xc25c2684, }; #endif /* return a^b */ static uint64_t pow_ui(uint32_t a, uint32_t b) { int i, n_bits; uint64_t r; if (b == 0) return 1; if (b == 1) return a; #ifdef USE_POW5_TABLE if ((a == 5 || a == 10) && b <= 17) { r = pow5_table[b - 1]; if (b >= 14) { r |= (uint64_t)pow5h_table[b - 14] << 32; } if (a == 10) r <<= b; return r; } #endif r = a; n_bits = 32 - clz32(b); for(i = n_bits - 2; i >= 0; i--) { r *= r; if ((b >> i) & 1) r *= a; } return r; } static uint32_t pow_ui_inv(uint32_t *pr_inv, int *pshift, uint32_t a, uint32_t b) { uint32_t r_inv, r; int shift; #ifdef USE_POW5_TABLE if (a == 5 && b >= 1 && b <= 13) { r = pow5_table[b - 1]; shift = clz32(r); r <<= shift; r_inv = pow5_inv_table[b - 1]; } else #endif { r = pow_ui(a, b); shift = clz32(r); r <<= shift; r_inv = udiv1norm_init(r); } *pshift = shift; *pr_inv = r_inv; return r; } enum { JS_RNDN, /* round to nearest, ties to even */ JS_RNDNA, /* round to nearest, ties away from zero */ JS_RNDZ, }; static int mpb_get_bit(const mpb_t *r, int k) { int l; l = (unsigned)k / LIMB_BITS; k = k & (LIMB_BITS - 1); if (l >= r->len) return 0; else return (r->tab[l] >> k) & 1; } /* compute round(r / 2^shift). 'shift' can be negative */ static void mpb_shr_round(mpb_t *r, int shift, int rnd_mode) { int l, i; if (shift == 0) return; if (shift < 0) { shift = -shift; l = (unsigned)shift / LIMB_BITS; shift = shift & (LIMB_BITS - 1); if (shift != 0) { r->tab[r->len] = mp_shl(r->tab, r->tab, r->len, shift, 0); r->len++; mpb_renorm(r); } if (l > 0) { for(i = r->len - 1; i >= 0; i--) r->tab[i + l] = r->tab[i]; for(i = 0; i < l; i++) r->tab[i] = 0; r->len += l; } } else { limb_t bit1, bit2; int k, add_one; switch(rnd_mode) { default: case JS_RNDZ: add_one = 0; break; case JS_RNDN: case JS_RNDNA: bit1 = mpb_get_bit(r, shift - 1); if (bit1) { if (rnd_mode == JS_RNDNA) { bit2 = 1; } else { /* bit2 = oring of all the bits after bit1 */ bit2 = 0; if (shift >= 2) { k = shift - 1; l = (unsigned)k / LIMB_BITS; k = k & (LIMB_BITS - 1); for(i = 0; i < min_int(l, r->len); i++) bit2 |= r->tab[i]; if (l < r->len) bit2 |= r->tab[l] & (((limb_t)1 << k) - 1); } } if (bit2) { add_one = 1; } else { /* round to even */ add_one = mpb_get_bit(r, shift); } } else { add_one = 0; } break; } l = (unsigned)shift / LIMB_BITS; shift = shift & (LIMB_BITS - 1); if (l >= r->len) { r->len = 1; r->tab[0] = add_one; } else { if (l > 0) { r->len -= l; for(i = 0; i < r->len; i++) r->tab[i] = r->tab[i + l]; } if (shift != 0) { mp_shr(r->tab, r->tab, r->len, shift, 0); mpb_renorm(r); } if (add_one) { limb_t a; a = mp_add_ui(r->tab, 1, r->len); if (a) r->tab[r->len++] = a; } } } } /* return -1, 0 or 1 */ static int mpb_cmp(const mpb_t *a, const mpb_t *b) { mp_size_t i; if (a->len < b->len) return -1; else if (a->len > b->len) return 1; for(i = a->len - 1; i >= 0; i--) { if (a->tab[i] != b->tab[i]) { if (a->tab[i] < b->tab[i]) return -1; else return 1; } } return 0; } static void mpb_set_u64(mpb_t *r, uint64_t m) { #if LIMB_BITS == 64 r->tab[0] = m; r->len = 1; #else r->tab[0] = m; r->tab[1] = m >> LIMB_BITS; if (r->tab[1] == 0) r->len = 1; else r->len = 2; #endif } static uint64_t mpb_get_u64(mpb_t *r) { #if LIMB_BITS == 64 return r->tab[0]; #else if (r->len == 1) { return r->tab[0]; } else { return r->tab[0] | ((uint64_t)r->tab[1] << LIMB_BITS); } #endif } /* floor_log2() = position of the first non zero bit or -1 if zero. */ static int mpb_floor_log2(mpb_t *a) { limb_t v; v = a->tab[a->len - 1]; if (v == 0) return -1; else return a->len * LIMB_BITS - 1 - clz32(v); } #define MUL_LOG2_RADIX_BASE_LOG2 24 /* round((1 << MUL_LOG2_RADIX_BASE_LOG2)/log2(i + 2)) */ static const uint32_t mul_log2_radix_table[JS_RADIX_MAX - 1] = { 0x000000, 0xa1849d, 0x000000, 0x6e40d2, 0x6308c9, 0x5b3065, 0x000000, 0x50c24e, 0x4d104d, 0x4a0027, 0x4768ce, 0x452e54, 0x433d00, 0x418677, 0x000000, 0x3ea16b, 0x3d645a, 0x3c43c2, 0x3b3b9a, 0x3a4899, 0x39680b, 0x3897b3, 0x37d5af, 0x372069, 0x367686, 0x35d6df, 0x354072, 0x34b261, 0x342bea, 0x33ac62, 0x000000, 0x32bfd9, 0x3251dd, 0x31e8d6, 0x318465, }; /* return floor(a / log2(radix)) for -2048 <= a <= 2047 */ static int mul_log2_radix(int a, int radix) { int radix_bits, mult; if ((radix & (radix - 1)) == 0) { /* if the radix is a power of two better to do it exactly */ radix_bits = 31 - clz32(radix); if (a < 0) a -= radix_bits - 1; return a / radix_bits; } else { mult = mul_log2_radix_table[radix - 2]; return ((int64_t)a * mult) >> MUL_LOG2_RADIX_BASE_LOG2; } } #if 0 static void build_mul_log2_radix_table(void) { int base, radix, mult, col, base_log2; base_log2 = 24; base = 1 << base_log2; col = 0; for(radix = 2; radix <= 36; radix++) { if ((radix & (radix - 1)) == 0) mult = 0; else mult = lrint((double)base / log2(radix)); printf("0x%06x, ", mult); if (++col == 4) { printf("\n"); col = 0; } } printf("\n"); } static void mul_log2_radix_test(void) { int radix, i, ref, r; for(radix = 2; radix <= 36; radix++) { for(i = -2048; i <= 2047; i++) { ref = (int)floor((double)i / log2(radix)); r = mul_log2_radix(i, radix); if (ref != r) { printf("ERROR: radix=%d i=%d r=%d ref=%d\n", radix, i, r, ref); exit(1); } } } if (0) build_mul_log2_radix_table(); } #endif static void u32toa_len(char *buf, uint32_t n, size_t len) { int digit, i; for(i = len - 1; i >= 0; i--) { digit = n % 10; n = n / 10; buf[i] = digit + '0'; } } /* for power of 2 radixes. len >= 1 */ static void u64toa_bin_len(char *buf, uint64_t n, unsigned int radix_bits, int len) { int digit, i; unsigned int mask; mask = (1 << radix_bits) - 1; for(i = len - 1; i >= 0; i--) { digit = n & mask; n >>= radix_bits; if (digit < 10) digit += '0'; else digit += 'a' - 10; buf[i] = digit; } } /* len >= 1. 2 <= radix <= 36 */ static void limb_to_a(char *buf, limb_t n, unsigned int radix, int len) { int digit, i; if (radix == 10) { /* specific case with constant divisor */ #if LIMB_BITS == 32 u32toa_len(buf, n, len); #else /* XXX: optimize */ for(i = len - 1; i >= 0; i--) { digit = (limb_t)n % 10; n = (limb_t)n / 10; buf[i] = digit + '0'; } #endif } else { for(i = len - 1; i >= 0; i--) { digit = (limb_t)n % radix; n = (limb_t)n / radix; if (digit < 10) digit += '0'; else digit += 'a' - 10; buf[i] = digit; } } } size_t u32toa(char *buf, uint32_t n) { char buf1[10], *q; size_t len; q = buf1 + sizeof(buf1); do { *--q = n % 10 + '0'; n /= 10; } while (n != 0); len = buf1 + sizeof(buf1) - q; memcpy(buf, q, len); return len; } size_t i32toa(char *buf, int32_t n) { if (n >= 0) { return u32toa(buf, n); } else { buf[0] = '-'; return u32toa(buf + 1, -(uint32_t)n) + 1; } } #ifdef USE_FAST_INT size_t u64toa(char *buf, uint64_t n) { if (n < 0x100000000) { return u32toa(buf, n); } else { uint64_t n1; char *q = buf; uint32_t n2; n1 = n / 1000000000; n %= 1000000000; if (n1 >= 0x100000000) { n2 = n1 / 1000000000; n1 = n1 % 1000000000; /* at most two digits */ if (n2 >= 10) { *q++ = n2 / 10 + '0'; n2 %= 10; } *q++ = n2 + '0'; u32toa_len(q, n1, 9); q += 9; } else { q += u32toa(q, n1); } u32toa_len(q, n, 9); q += 9; return q - buf; } } size_t i64toa(char *buf, int64_t n) { if (n >= 0) { return u64toa(buf, n); } else { buf[0] = '-'; return u64toa(buf + 1, -(uint64_t)n) + 1; } } /* XXX: only tested for 1 <= n < 2^53 */ size_t u64toa_radix(char *buf, uint64_t n, unsigned int radix) { int radix_bits, l; if (likely(radix == 10)) return u64toa(buf, n); if ((radix & (radix - 1)) == 0) { radix_bits = 31 - clz32(radix); if (n == 0) l = 1; else l = (64 - clz64(n) + radix_bits - 1) / radix_bits; u64toa_bin_len(buf, n, radix_bits, l); return l; } else { char buf1[41], *q; /* maximum length for radix = 3 */ size_t len; int digit; q = buf1 + sizeof(buf1); do { digit = n % radix; n /= radix; if (digit < 10) digit += '0'; else digit += 'a' - 10; *--q = digit; } while (n != 0); len = buf1 + sizeof(buf1) - q; memcpy(buf, q, len); return len; } } size_t i64toa_radix(char *buf, int64_t n, unsigned int radix) { if (n >= 0) { return u64toa_radix(buf, n, radix); } else { buf[0] = '-'; return u64toa_radix(buf + 1, -(uint64_t)n, radix) + 1; } } #endif /* USE_FAST_INT */ static const uint8_t digits_per_limb_table[JS_RADIX_MAX - 1] = { #if LIMB_BITS == 32 32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, #else 64,40,32,27,24,22,21,20,19,18,17,17,16,16,16,15,15,15,14,14,14,14,13,13,13,13,13,13,13,12,12,12,12,12,12, #endif }; static const uint32_t radix_base_table[JS_RADIX_MAX - 1] = { 0x00000000, 0xcfd41b91, 0x00000000, 0x48c27395, 0x81bf1000, 0x75db9c97, 0x40000000, 0xcfd41b91, 0x3b9aca00, 0x8c8b6d2b, 0x19a10000, 0x309f1021, 0x57f6c100, 0x98c29b81, 0x00000000, 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, 0x94ace180, 0xcaf18367, 0x0b640000, 0x0e8d4a51, 0x1269ae40, 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x81bf1000, }; /* XXX: remove the table ? */ static uint8_t dtoa_max_digits_table[JS_RADIX_MAX - 1] = { 54, 35, 28, 24, 22, 20, 19, 18, 17, 17, 16, 16, 15, 15, 15, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, }; /* we limit the maximum number of significant digits for atod to about 128 bits of precision for non power of two bases. The only requirement for Javascript is at least 20 digits in base 10. For power of two bases, we do an exact rounding in all the cases. */ static uint8_t atod_max_digits_table[JS_RADIX_MAX - 1] = { 64, 80, 32, 55, 49, 45, 21, 40, 38, 37, 35, 34, 33, 32, 16, 31, 30, 30, 29, 29, 28, 28, 27, 27, 27, 26, 26, 26, 26, 25, 12, 25, 25, 24, 24, }; /* if abs(d) >= B^max_exponent, it is an overflow */ static const int16_t max_exponent[JS_RADIX_MAX - 1] = { 1024, 647, 512, 442, 397, 365, 342, 324, 309, 297, 286, 277, 269, 263, 256, 251, 246, 242, 237, 234, 230, 227, 224, 221, 218, 216, 214, 211, 209, 207, 205, 203, 202, 200, 199, }; /* if abs(d) <= B^min_exponent, it is an underflow */ static const int16_t min_exponent[JS_RADIX_MAX - 1] = { -1075, -679, -538, -463, -416, -383, -359, -340, -324, -311, -300, -291, -283, -276, -269, -263, -258, -254, -249, -245, -242, -238, -235, -232, -229, -227, -224, -222, -220, -217, -215, -214, -212, -210, -208, }; #if 0 void build_tables(void) { int r, j, radix, n, col, i; /* radix_base_table */ for(radix = 2; radix <= 36; radix++) { r = 1; for(j = 0; j < digits_per_limb_table[radix - 2]; j++) { r *= radix; } printf(" 0x%08x,", r); if ((radix % 4) == 1) printf("\n"); } printf("\n"); /* dtoa_max_digits_table */ for(radix = 2; radix <= 36; radix++) { /* Note: over estimated when the radix is a power of two */ printf(" %d,", 1 + (int)ceil(53.0 / log2(radix))); } printf("\n"); /* atod_max_digits_table */ for(radix = 2; radix <= 36; radix++) { if ((radix & (radix - 1)) == 0) { /* 64 bits is more than enough */ n = (int)floor(64.0 / log2(radix)); } else { n = (int)floor(128.0 / log2(radix)); } printf(" %d,", n); } printf("\n"); printf("static const int16_t max_exponent[JS_RADIX_MAX - 1] = {\n"); col = 0; for(radix = 2; radix <= 36; radix++) { printf("%5d, ", (int)ceil(1024 / log2(radix))); if (++col == 8) { col = 0; printf("\n"); } } printf("\n};\n\n"); printf("static const int16_t min_exponent[JS_RADIX_MAX - 1] = {\n"); col = 0; for(radix = 2; radix <= 36; radix++) { printf("%5d, ", (int)floor(-1075 / log2(radix))); if (++col == 8) { col = 0; printf("\n"); } } printf("\n};\n\n"); printf("static const uint32_t pow5_table[16] = {\n"); col = 0; for(i = 2; i <= 17; i++) { r = 1; for(j = 0; j < i; j++) { r *= 5; } printf("0x%08x, ", r); if (++col == 4) { col = 0; printf("\n"); } } printf("\n};\n\n"); /* high part */ printf("static const uint8_t pow5h_table[4] = {\n"); col = 0; for(i = 14; i <= 17; i++) { uint64_t r1; r1 = 1; for(j = 0; j < i; j++) { r1 *= 5; } printf("0x%08x, ", (uint32_t)(r1 >> 32)); if (++col == 4) { col = 0; printf("\n"); } } printf("\n};\n\n"); } #endif /* n_digits >= 1. 0 <= dot_pos <= n_digits. If dot_pos == n_digits, the dot is not displayed. 'a' is modified. */ static int output_digits(char *buf, mpb_t *a, int radix, int n_digits1, int dot_pos) { int n_digits, digits_per_limb, radix_bits, n, len; n_digits = n_digits1; if ((radix & (radix - 1)) == 0) { /* radix = 2^radix_bits */ radix_bits = 31 - clz32(radix); } else { radix_bits = 0; } digits_per_limb = digits_per_limb_table[radix - 2]; if (radix_bits != 0) { for(;;) { n = min_int(n_digits, digits_per_limb); n_digits -= n; u64toa_bin_len(buf + n_digits, a->tab[0], radix_bits, n); if (n_digits == 0) break; mpb_shr_round(a, digits_per_limb * radix_bits, JS_RNDZ); } } else { limb_t r; while (n_digits != 0) { n = min_int(n_digits, digits_per_limb); n_digits -= n; r = mp_div1(a->tab, a->tab, a->len, radix_base_table[radix - 2], 0); mpb_renorm(a); limb_to_a(buf + n_digits, r, radix, n); } } /* add the dot */ len = n_digits1; if (dot_pos != n_digits1) { memmove(buf + dot_pos + 1, buf + dot_pos, n_digits1 - dot_pos); buf[dot_pos] = '.'; len++; } return len; } /* return (a, e_offset) such that a = a * (radix1*2^radix_shift)^f * 2^-e_offset. 'f' can be negative. */ static int mul_pow(mpb_t *a, int radix1, int radix_shift, int f, bool is_int, int e) { int e_offset, d, n, n0; e_offset = -f * radix_shift; if (radix1 != 1) { d = digits_per_limb_table[radix1 - 2]; if (f >= 0) { limb_t h, b; b = 0; n0 = 0; while (f != 0) { n = min_int(f, d); if (n != n0) { b = pow_ui(radix1, n); n0 = n; } h = mp_mul1(a->tab, a->tab, a->len, b, 0); if (h != 0) { a->tab[a->len++] = h; } f -= n; } } else { int extra_bits, l, shift; limb_t r, rem, b, b_inv; f = -f; l = (f + d - 1) / d; /* high bound for the number of limbs (XXX: make it better) */ e_offset += l * LIMB_BITS; if (!is_int) { /* at least 'e' bits are needed in the final result for rounding */ extra_bits = max_int(e - mpb_floor_log2(a), 0); } else { /* at least two extra bits are needed in the final result for rounding */ extra_bits = max_int(2 + e - e_offset, 0); } e_offset += extra_bits; mpb_shr_round(a, -(l * LIMB_BITS + extra_bits), JS_RNDZ); b = 0; b_inv = 0; shift = 0; n0 = 0; rem = 0; while (f != 0) { n = min_int(f, d); if (n != n0) { b = pow_ui_inv(&b_inv, &shift, radix1, n); n0 = n; } r = mp_div1norm(a->tab, a->tab, a->len, b, 0, b_inv, shift); rem |= r; mpb_renorm(a); f -= n; } /* if the remainder is non zero, use it for rounding */ a->tab[0] |= (rem != 0); } } return e_offset; } /* tmp1 = round(m*2^e*radix^f). 'tmp0' is a temporary storage */ static void mul_pow_round(mpb_t *tmp1, uint64_t m, int e, int radix1, int radix_shift, int f, int rnd_mode) { int e_offset; mpb_set_u64(tmp1, m); e_offset = mul_pow(tmp1, radix1, radix_shift, f, true, e); mpb_shr_round(tmp1, -e + e_offset, rnd_mode); } /* return round(a*2^e_offset) rounded as a float64. 'a' is modified */ static uint64_t round_to_d(int *pe, mpb_t *a, int e_offset, int rnd_mode) { int e; uint64_t m; if (a->tab[0] == 0 && a->len == 1) { /* zero result */ m = 0; e = 0; /* don't care */ } else { int prec, prec1, e_min; e = mpb_floor_log2(a) + 1 - e_offset; prec1 = 53; e_min = -1021; if (e < e_min) { /* subnormal result or zero */ prec = prec1 - (e_min - e); } else { prec = prec1; } mpb_shr_round(a, e + e_offset - prec, rnd_mode); m = mpb_get_u64(a); m <<= (53 - prec); /* mantissa overflow due to rounding */ if (m >= (uint64_t)1 << 53) { m >>= 1; e++; } } *pe = e; return m; } /* return (m, e) such that m*2^(e-53) = round(a * radix^f) with 2^52 <= m < 2^53 or m = 0. 'a' is modified. */ static uint64_t mul_pow_round_to_d(int *pe, mpb_t *a, int radix1, int radix_shift, int f, int rnd_mode) { int e_offset; e_offset = mul_pow(a, radix1, radix_shift, f, false, 55); return round_to_d(pe, a, e_offset, rnd_mode); } #ifdef JS_DTOA_DUMP_STATS static int out_len_count[17]; void js_dtoa_dump_stats(void) { int i, sum; sum = 0; for(i = 0; i < 17; i++) sum += out_len_count[i]; for(i = 0; i < 17; i++) { printf("%2d %8d %5.2f%%\n", i + 1, out_len_count[i], (double)out_len_count[i] / sum * 100); } } #endif /* return a maximum bound of the string length. The bound depends on 'd' only if format = JS_DTOA_FORMAT_FRAC or if JS_DTOA_EXP_DISABLED is enabled. */ int js_dtoa_max_len(double d, int radix, int n_digits, int flags) { int fmt = flags & JS_DTOA_FORMAT_MASK; int n, e; uint64_t a; if (fmt != JS_DTOA_FORMAT_FRAC) { if (fmt == JS_DTOA_FORMAT_FREE) { n = dtoa_max_digits_table[radix - 2]; } else { n = n_digits; } if ((flags & JS_DTOA_EXP_MASK) == JS_DTOA_EXP_DISABLED) { /* no exponential */ a = float64_as_uint64(d); e = (a >> 52) & 0x7ff; if (e == 0x7ff) { /* NaN, Infinity */ n = 0; } else { e -= 1023; /* XXX: adjust */ n += 10 + abs(mul_log2_radix(e - 1, radix)); } } else { /* extra: sign, 1 dot and exponent "e-1000" */ n += 1 + 1 + 6; } } else { a = float64_as_uint64(d); e = (a >> 52) & 0x7ff; if (e == 0x7ff) { /* NaN, Infinity */ n = 0; } else { /* high bound for the integer part */ e -= 1023; /* x < 2^(e + 1) */ if (e < 0) { n = 1; } else { n = 2 + mul_log2_radix(e - 1, radix); } /* sign, extra digit, 1 dot */ n += 1 + 1 + 1 + n_digits; } } return max_int(n, 9); /* also include NaN and [-]Infinity */ } #if defined(__SANITIZE_ADDRESS__) && 0 static void *dtoa_malloc(uint64_t **pptr, size_t size) { return malloc(size); } static void dtoa_free(void *ptr) { free(ptr); } #else static void *dtoa_malloc(uint64_t **pptr, size_t size) { void *ret; ret = *pptr; *pptr += (size + 7) / 8; return ret; } static void dtoa_free(void *ptr) { } #endif /* return the length */ int js_dtoa(char *buf, double d, int radix, int n_digits, int flags, JSDTOATempMem *tmp_mem) { uint64_t a, m, *mptr = tmp_mem->mem; int e, sgn, l, E, P, i, E_max, radix1, radix_shift; char *q; mpb_t *tmp1, *mant_max; int fmt = flags & JS_DTOA_FORMAT_MASK; tmp1 = dtoa_malloc(&mptr, sizeof(mpb_t) + sizeof(limb_t) * DBIGNUM_LEN_MAX); mant_max = dtoa_malloc(&mptr, sizeof(mpb_t) + sizeof(limb_t) * MANT_LEN_MAX); assert((mptr - tmp_mem->mem) <= sizeof(JSDTOATempMem) / sizeof(mptr[0])); radix_shift = ctz32(radix); radix1 = radix >> radix_shift; a = float64_as_uint64(d); sgn = a >> 63; e = (a >> 52) & 0x7ff; m = a & (((uint64_t)1 << 52) - 1); q = buf; if (e == 0x7ff) { if (m == 0) { if (sgn) *q++ = '-'; memcpy(q, "Infinity", 8); q += 8; } else { memcpy(q, "NaN", 3); q += 3; } goto done; } else if (e == 0) { if (m == 0) { tmp1->len = 1; tmp1->tab[0] = 0; E = 1; if (fmt == JS_DTOA_FORMAT_FREE) P = 1; else if (fmt == JS_DTOA_FORMAT_FRAC) P = n_digits + 1; else P = n_digits; /* "-0" is displayed as "0" if JS_DTOA_MINUS_ZERO is not present */ if (sgn && (flags & JS_DTOA_MINUS_ZERO)) *q++ = '-'; goto output; } /* denormal number: convert to a normal number */ l = clz64(m) - 11; e -= l - 1; m <<= l; } else { m |= (uint64_t)1 << 52; } if (sgn) *q++ = '-'; /* remove the bias */ e -= 1022; /* d = 2^(e-53)*m */ // printf("m=0x%016" PRIx64 " e=%d\n", m, e); #ifdef USE_FAST_INT if (fmt == JS_DTOA_FORMAT_FREE && e >= 1 && e <= 53 && (m & (((uint64_t)1 << (53 - e)) - 1)) == 0 && (flags & JS_DTOA_EXP_MASK) != JS_DTOA_EXP_ENABLED) { m >>= 53 - e; /* 'm' is never zero */ q += u64toa_radix(q, m, radix); goto done; } #endif /* this choice of E implies F=round(x*B^(P-E) is such as: B^(P-1) <= F < 2.B^P. */ E = 1 + mul_log2_radix(e - 1, radix); if (fmt == JS_DTOA_FORMAT_FREE) { int P_max, E0, e1, E_found, P_found; uint64_t m1, mant_found, mant, mant_max1; /* P_max is guarranteed to work by construction */ P_max = dtoa_max_digits_table[radix - 2]; E0 = E; E_found = 0; P_found = 0; mant_found = 0; /* find the minimum number of digits by successive tries */ P = P_max; /* P_max is guarateed to work */ for(;;) { /* mant_max always fits on 64 bits */ mant_max1 = pow_ui(radix, P); /* compute the mantissa in base B */ E = E0; for(;;) { /* XXX: add inexact flag */ mul_pow_round(tmp1, m, e - 53, radix1, radix_shift, P - E, JS_RNDN); mant = mpb_get_u64(tmp1); if (mant < mant_max1) break; E++; /* at most one iteration is possible */ } /* remove useless trailing zero digits */ while ((mant % radix) == 0) { mant /= radix; P--; } /* garanteed to work for P = P_max */ if (P_found == 0) goto prec_found; /* convert back to base 2 */ mpb_set_u64(tmp1, mant); m1 = mul_pow_round_to_d(&e1, tmp1, radix1, radix_shift, E - P, JS_RNDN); // printf("P=%2d: m=0x%016" PRIx64 " e=%d m1=0x%016" PRIx64 " e1=%d\n", P, m, e, m1, e1); /* Note: (m, e) is never zero here, so the exponent for m1 = 0 does not matter */ if (m1 == m && e1 == e) { prec_found: P_found = P; E_found = E; mant_found = mant; if (P == 1) break; P--; /* try lower exponent */ } else { break; } } P = P_found; E = E_found; mpb_set_u64(tmp1, mant_found); #ifdef JS_DTOA_DUMP_STATS if (radix == 10) { out_len_count[P - 1]++; } #endif } else if (fmt == JS_DTOA_FORMAT_FRAC) { int len; assert(n_digits >= 0 && n_digits <= JS_DTOA_MAX_DIGITS); /* P = max_int(E, 1) + n_digits; */ /* frac is rounded using RNDNA */ mul_pow_round(tmp1, m, e - 53, radix1, radix_shift, n_digits, JS_RNDNA); /* we add one extra digit on the left and remove it if needed to avoid testing if the result is < radix^P */ len = output_digits(q, tmp1, radix, max_int(E + 1, 1) + n_digits, max_int(E + 1, 1)); if (q[0] == '0' && len >= 2 && q[1] != '.') { len--; memmove(q, q + 1, len); } q += len; goto done; } else { int pow_shift; assert(n_digits >= 1 && n_digits <= JS_DTOA_MAX_DIGITS); P = n_digits; /* mant_max = radix^P */ mant_max->len = 1; mant_max->tab[0] = 1; pow_shift = mul_pow(mant_max, radix1, radix_shift, P, false, 0); mpb_shr_round(mant_max, pow_shift, JS_RNDZ); for(;;) { /* fixed and frac are rounded using RNDNA */ mul_pow_round(tmp1, m, e - 53, radix1, radix_shift, P - E, JS_RNDNA); if (mpb_cmp(tmp1, mant_max) < 0) break; E++; /* at most one iteration is possible */ } } output: if (fmt == JS_DTOA_FORMAT_FIXED) E_max = n_digits; else E_max = dtoa_max_digits_table[radix - 2] + 4; if ((flags & JS_DTOA_EXP_MASK) == JS_DTOA_EXP_ENABLED || ((flags & JS_DTOA_EXP_MASK) == JS_DTOA_EXP_AUTO && (E <= -6 || E > E_max))) { q += output_digits(q, tmp1, radix, P, 1); E--; if (radix == 10) { *q++ = 'e'; } else if (radix1 == 1 && radix_shift <= 4) { E *= radix_shift; *q++ = 'p'; } else { *q++ = '@'; } if (E < 0) { *q++ = '-'; E = -E; } else { *q++ = '+'; } q += u32toa(q, E); } else if (E <= 0) { *q++ = '0'; *q++ = '.'; for(i = 0; i < -E; i++) *q++ = '0'; q += output_digits(q, tmp1, radix, P, P); } else { q += output_digits(q, tmp1, radix, P, min_int(P, E)); for(i = 0; i < E - P; i++) *q++ = '0'; } done: *q = '\0'; dtoa_free(mant_max); dtoa_free(tmp1); return q - buf; } static inline int to_digit(int c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'Z') return c - 'A' + 10; else if (c >= 'a' && c <= 'z') return c - 'a' + 10; else return 36; } /* r = r * radix_base + a. radix_base = 0 means radix_base = 2^32 */ static void mpb_mul1_base(mpb_t *r, limb_t radix_base, limb_t a) { int i; if (r->tab[0] == 0 && r->len == 1) { r->tab[0] = a; } else { if (radix_base == 0) { for(i = r->len; i >= 0; i--) { r->tab[i + 1] = r->tab[i]; } r->tab[0] = a; } else { r->tab[r->len] = mp_mul1(r->tab, r->tab, r->len, radix_base, a); } r->len++; mpb_renorm(r); } } /* XXX: add fast path for small integers */ double js_atod(const char *str, const char **pnext, int radix, int flags, JSATODTempMem *tmp_mem) { uint64_t *mptr = tmp_mem->mem; const char *p, *p_start; limb_t cur_limb, radix_base, extra_digits; int is_neg, digit_count, limb_digit_count, digits_per_limb, sep, radix1, radix_shift; int radix_bits, expn, e, max_digits, expn_offset, dot_pos, sig_pos, pos; mpb_t *tmp0; double dval; bool is_bin_exp, is_zero, expn_overflow; uint64_t m, a; tmp0 = dtoa_malloc(&mptr, sizeof(mpb_t) + sizeof(limb_t) * DBIGNUM_LEN_MAX); assert((mptr - tmp_mem->mem) <= sizeof(JSATODTempMem) / sizeof(mptr[0])); /* optional separator between digits */ sep = (flags & JS_ATOD_ACCEPT_UNDERSCORES) ? '_' : 256; p = str; is_neg = 0; if (p[0] == '+') { p++; p_start = p; } else if (p[0] == '-') { is_neg = 1; p++; p_start = p; } else { p_start = p; } if (p[0] == '0') { if ((p[1] == 'x' || p[1] == 'X') && (radix == 0 || radix == 16)) { p += 2; radix = 16; } else if ((p[1] == 'o' || p[1] == 'O') && radix == 0 && (flags & JS_ATOD_ACCEPT_BIN_OCT)) { p += 2; radix = 8; } else if ((p[1] == 'b' || p[1] == 'B') && radix == 0 && (flags & JS_ATOD_ACCEPT_BIN_OCT)) { p += 2; radix = 2; } else if ((p[1] >= '0' && p[1] <= '9') && radix == 0 && (flags & JS_ATOD_ACCEPT_LEGACY_OCTAL)) { int i; sep = 256; for (i = 1; (p[i] >= '0' && p[i] <= '7'); i++) continue; if (p[i] == '8' || p[i] == '9') goto no_prefix; p += 1; radix = 8; } else { goto no_prefix; } /* there must be a digit after the prefix */ if (to_digit((uint8_t)*p) >= radix) goto fail; no_prefix: ; } else { if (!(flags & JS_ATOD_INT_ONLY) && js__strstart(p, "Infinity", &p)) goto overflow; } if (radix == 0) radix = 10; cur_limb = 0; expn_offset = 0; digit_count = 0; limb_digit_count = 0; max_digits = atod_max_digits_table[radix - 2]; digits_per_limb = digits_per_limb_table[radix - 2]; radix_base = radix_base_table[radix - 2]; radix_shift = ctz32(radix); radix1 = radix >> radix_shift; if (radix1 == 1) { /* radix = 2^radix_bits */ radix_bits = radix_shift; } else { radix_bits = 0; } tmp0->len = 1; tmp0->tab[0] = 0; extra_digits = 0; pos = 0; dot_pos = -1; /* skip leading zeros */ for(;;) { if (*p == '.' && (p > p_start || to_digit(p[1]) < radix) && !(flags & JS_ATOD_INT_ONLY)) { if (*p == sep) goto fail; if (dot_pos >= 0) break; dot_pos = pos; p++; } if (*p == sep && p > p_start && p[1] == '0') p++; if (*p != '0') break; p++; pos++; } sig_pos = pos; for(;;) { limb_t c; if (*p == '.' && (p > p_start || to_digit(p[1]) < radix) && !(flags & JS_ATOD_INT_ONLY)) { if (*p == sep) goto fail; if (dot_pos >= 0) break; dot_pos = pos; p++; } if (*p == sep && p > p_start && to_digit(p[1]) < radix) p++; c = to_digit(*p); if (c >= radix) break; p++; pos++; if (digit_count < max_digits) { /* XXX: could be faster when radix_bits != 0 */ cur_limb = cur_limb * radix + c; limb_digit_count++; if (limb_digit_count == digits_per_limb) { mpb_mul1_base(tmp0, radix_base, cur_limb); cur_limb = 0; limb_digit_count = 0; } digit_count++; } else { extra_digits |= c; } } if (limb_digit_count != 0) { mpb_mul1_base(tmp0, pow_ui(radix, limb_digit_count), cur_limb); } if (digit_count == 0) { is_zero = true; expn_offset = 0; } else { is_zero = false; if (dot_pos < 0) dot_pos = pos; expn_offset = sig_pos + digit_count - dot_pos; } /* Use the extra digits for rounding if the base is a power of two. Otherwise they are just truncated. */ if (radix_bits != 0 && extra_digits != 0) { tmp0->tab[0] |= 1; } /* parse the exponent, if any */ expn = 0; expn_overflow = false; is_bin_exp = false; if (!(flags & JS_ATOD_INT_ONLY) && ((radix == 10 && (*p == 'e' || *p == 'E')) || (radix != 10 && (*p == '@' || (radix_bits >= 1 && radix_bits <= 4 && (*p == 'p' || *p == 'P'))))) && p > p_start) { bool exp_is_neg; int c; is_bin_exp = (*p == 'p' || *p == 'P'); p++; exp_is_neg = false; if (*p == '+') { p++; } else if (*p == '-') { exp_is_neg = true; p++; } c = to_digit(*p); if (c >= 10) goto fail; /* XXX: could stop before the exponent part */ expn = c; p++; for(;;) { if (*p == sep && to_digit(p[1]) < 10) p++; c = to_digit(*p); if (c >= 10) break; if (!expn_overflow) { if (unlikely(expn > ((INT32_MAX - 2 - 9) / 10))) { expn_overflow = true; } else { expn = expn * 10 + c; } } p++; } if (exp_is_neg) expn = -expn; /* if zero result, the exponent can be arbitrarily large */ if (!is_zero && expn_overflow) { if (exp_is_neg) a = 0; else a = (uint64_t)0x7ff << 52; /* infinity */ goto done; } } if (p == p_start) goto fail; if (is_zero) { a = 0; } else { int expn1; if (radix_bits != 0) { if (!is_bin_exp) expn *= radix_bits; expn -= expn_offset * radix_bits; expn1 = expn + digit_count * radix_bits; if (expn1 >= 1024 + radix_bits) goto overflow; else if (expn1 <= -1075) goto underflow; m = round_to_d(&e, tmp0, -expn, JS_RNDN); } else { expn -= expn_offset; expn1 = expn + digit_count; if (expn1 >= max_exponent[radix - 2] + 1) goto overflow; else if (expn1 <= min_exponent[radix - 2]) goto underflow; m = mul_pow_round_to_d(&e, tmp0, radix1, radix_shift, expn, JS_RNDN); } if (m == 0) { underflow: a = 0; } else if (e > 1024) { overflow: /* overflow */ a = (uint64_t)0x7ff << 52; } else if (e < -1073) { /* underflow */ /* XXX: check rounding */ a = 0; } else if (e < -1021) { /* subnormal */ a = m >> (-e - 1021); } else { a = ((uint64_t)(e + 1022) << 52) | (m & (((uint64_t)1 << 52) - 1)); } } done: a |= (uint64_t)is_neg << 63; dval = uint64_as_float64(a); done1: if (pnext) *pnext = p; dtoa_free(tmp0); return dval; fail: dval = NAN; goto done1; } QuickJSR/src/quickjs/quickjs-libc.c0000644000176200001440000040321315122664706016705 0ustar liggesusers/* * QuickJS C library * * Copyright (c) 2017-2021 Fabrice Bellard * Copyright (c) 2017-2021 Charlie Gordon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "quickjs.h" #include #include #include #include #include #include #include #include #if !defined(_MSC_VER) #include #include #endif #include #include #include #include #if !defined(_MSC_VER) #include #endif #if defined(_WIN32) #include #include #include #include #include #include #include #define popen _popen #define pclose _pclose #define rmdir _rmdir #define getcwd _getcwd #define chdir _chdir #else #include #include #if !defined(__wasi__) #include #include #include #include #include #endif #if defined(__APPLE__) typedef sig_t sighandler_t; #include #define environ (*_NSGetEnviron()) #endif #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) typedef sig_t sighandler_t; extern char **environ; #endif #endif /* _WIN32 */ #include "cutils.h" #include "list.h" #include "quickjs-libc.h" #if JS_HAVE_THREADS #include "quickjs-c-atomics.h" #define USE_WORKER // enable os.Worker #endif #ifndef S_IFBLK #define S_IFBLK 0 #endif #ifndef S_IFIFO #define S_IFIFO 0 #endif #ifndef MAX_SAFE_INTEGER // already defined in amalgamation builds #define MAX_SAFE_INTEGER (((int64_t) 1 << 53) - 1) #endif #ifndef QJS_NATIVE_MODULE_SUFFIX #ifdef _WIN32 #define QJS_NATIVE_MODULE_SUFFIX ".dll" #else #define QJS_NATIVE_MODULE_SUFFIX ".so" #endif #endif /* TODO: - add socket calls */ typedef struct { struct list_head link; int fd; JSValue rw_func[2]; } JSOSRWHandler; typedef struct { struct list_head link; int sig_num; JSValue func; } JSOSSignalHandler; typedef struct { struct list_head link; int64_t timer_id; uint8_t repeats:1; int64_t timeout; int64_t delay; JSValue func; } JSOSTimer; typedef struct { struct list_head link; JSValue promise; JSValue reason; } JSRejectedPromiseEntry; #ifdef USE_WORKER typedef struct { struct list_head link; uint8_t *data; size_t data_len; /* list of SharedArrayBuffers, necessary to free the message */ uint8_t **sab_tab; size_t sab_tab_len; } JSWorkerMessage; typedef struct JSWaker { #ifdef _WIN32 HANDLE handle; #else int read_fd; int write_fd; #endif } JSWaker; typedef struct { int ref_count; js_mutex_t mutex; struct list_head msg_queue; /* list of JSWorkerMessage.link */ JSWaker waker; } JSWorkerMessagePipe; typedef struct { struct list_head link; JSWorkerMessagePipe *recv_pipe; JSValue on_message_func; } JSWorkerMessageHandler; #endif // USE_WORKER typedef struct JSThreadState { struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */ struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */ struct list_head os_timers; /* list of JSOSTimer.link */ struct list_head port_list; /* list of JSWorkerMessageHandler.link */ struct list_head rejected_promise_list; /* list of JSRejectedPromiseEntry.link */ int eval_script_recurse; /* only used in the main thread */ int64_t next_timer_id; /* for setTimeout / setInterval */ bool can_js_os_poll; /* not used in the main thread */ #ifdef USE_WORKER JSWorkerMessagePipe *recv_pipe, *send_pipe; #else void *recv_pipe; #endif // USE_WORKER JSClassID std_file_class_id; JSClassID worker_class_id; } JSThreadState; static uint64_t os_pending_signals; static void *js_std_dbuf_realloc(void *opaque, void *ptr, size_t size) { JSRuntime *rt = opaque; return js_realloc_rt(rt, ptr, size); } static void js_std_dbuf_init(JSContext *ctx, DynBuf *s) { dbuf_init2(s, JS_GetRuntime(ctx), js_std_dbuf_realloc); } static bool my_isdigit(int c) { return (c >= '0' && c <= '9'); } static JSThreadState *js_get_thread_state(JSRuntime *rt) { return (JSThreadState *)js_std_cmd(/*GetOpaque*/0, rt); } static void js_set_thread_state(JSRuntime *rt, JSThreadState *ts) { js_std_cmd(/*SetOpaque*/1, rt, ts); } static JSValue js_printf_internal(JSContext *ctx, int argc, JSValueConst *argv, FILE *fp) { char fmtbuf[32]; uint8_t cbuf[UTF8_CHAR_LEN_MAX+1]; JSValue res; DynBuf dbuf; const char *fmt_str = NULL; const uint8_t *fmt, *fmt_end; const uint8_t *p; char *q; int i, c, len, mod; size_t fmt_len; int32_t int32_arg; int64_t int64_arg; double double_arg; const char *string_arg; js_std_dbuf_init(ctx, &dbuf); if (argc > 0) { fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]); if (!fmt_str) goto fail; i = 1; fmt = (const uint8_t *)fmt_str; fmt_end = fmt + fmt_len; while (fmt < fmt_end) { for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++) continue; dbuf_put(&dbuf, p, fmt - p); if (fmt >= fmt_end) break; q = fmtbuf; *q++ = *fmt++; /* copy '%' */ /* flags */ for(;;) { c = *fmt; if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' || c == '\'') { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = c; fmt++; } else { break; } } /* width */ if (*fmt == '*') { if (i >= argc) goto missing; if (JS_ToInt32(ctx, &int32_arg, argv[i++])) goto fail; q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg); fmt++; } else { while (my_isdigit(*fmt)) { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = *fmt++; } } if (*fmt == '.') { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = *fmt++; if (*fmt == '*') { if (i >= argc) goto missing; if (JS_ToInt32(ctx, &int32_arg, argv[i++])) goto fail; q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg); fmt++; } else { while (my_isdigit(*fmt)) { if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = *fmt++; } } } /* we only support the "l" modifier for 64 bit numbers */ mod = ' '; if (*fmt == 'l') { mod = *fmt++; } /* type */ c = *fmt++; if (q >= fmtbuf + sizeof(fmtbuf) - 1) goto invalid; *q++ = c; *q = '\0'; switch (c) { case 'c': if (i >= argc) goto missing; if (JS_IsString(argv[i])) { // TODO(chqrlie) need an API to wrap charCodeAt and codePointAt */ string_arg = JS_ToCString(ctx, argv[i++]); if (!string_arg) goto fail; int32_arg = utf8_decode((const uint8_t *)string_arg, &p); JS_FreeCString(ctx, string_arg); } else { if (JS_ToInt32(ctx, &int32_arg, argv[i++])) goto fail; } // XXX: throw an exception? if ((unsigned)int32_arg > 0x10FFFF) int32_arg = 0xFFFD; /* ignore conversion flags, width and precision */ len = utf8_encode(cbuf, int32_arg); dbuf_put(&dbuf, cbuf, len); break; case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': if (i >= argc) goto missing; if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++])) goto fail; if (mod == 'l') { /* 64 bit number */ #if defined(_WIN32) if (q >= fmtbuf + sizeof(fmtbuf) - 3) goto invalid; q[2] = q[-1]; q[-1] = 'I'; q[0] = '6'; q[1] = '4'; q[3] = '\0'; dbuf_printf(&dbuf, fmtbuf, (int64_t)int64_arg); #else if (q >= fmtbuf + sizeof(fmtbuf) - 2) goto invalid; q[1] = q[-1]; q[-1] = q[0] = 'l'; q[2] = '\0'; dbuf_printf(&dbuf, fmtbuf, (long long)int64_arg); #endif } else { dbuf_printf(&dbuf, fmtbuf, (int)int64_arg); } break; case 's': if (i >= argc) goto missing; /* XXX: handle strings containing null characters */ string_arg = JS_ToCString(ctx, argv[i++]); if (!string_arg) goto fail; dbuf_printf(&dbuf, fmtbuf, string_arg); JS_FreeCString(ctx, string_arg); break; case 'e': case 'f': case 'g': case 'a': case 'E': case 'F': case 'G': case 'A': if (i >= argc) goto missing; if (JS_ToFloat64(ctx, &double_arg, argv[i++])) goto fail; dbuf_printf(&dbuf, fmtbuf, double_arg); break; case '%': dbuf_putc(&dbuf, '%'); break; default: /* XXX: should support an extension mechanism */ invalid: JS_ThrowTypeError(ctx, "invalid conversion specifier in format string"); goto fail; missing: JS_ThrowReferenceError(ctx, "missing argument for conversion specifier"); goto fail; } } JS_FreeCString(ctx, fmt_str); } if (dbuf.error) { res = JS_ThrowOutOfMemory(ctx); } else { if (fp) { len = fwrite(dbuf.buf, 1, dbuf.size, fp); res = JS_NewInt32(ctx, len); } else { res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size); } } dbuf_free(&dbuf); return res; fail: JS_FreeCString(ctx, fmt_str); dbuf_free(&dbuf); return JS_EXCEPTION; } uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename) { FILE *f; size_t n, len; uint8_t *p, *buf, tmp[8192]; f = fopen(filename, "rb"); if (!f) return NULL; buf = NULL; len = 0; do { n = fread(tmp, 1, sizeof(tmp), f); if (ctx) { p = js_realloc(ctx, buf, len + n + 1); } else { p = realloc(buf, len + n + 1); } if (!p) { if (ctx) { js_free(ctx, buf); } else { free(buf); } fclose(f); return NULL; } memcpy(&p[len], tmp, n); buf = p; len += n; buf[len] = '\0'; } while (n == sizeof(tmp)); fclose(f); *pbuf_len = len; return buf; } /* load and evaluate a file */ static JSValue js_loadScript(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; const char *filename; JSValue ret; size_t buf_len; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; buf = js_load_file(ctx, &buf_len, filename); if (!buf) { JS_ThrowReferenceError(ctx, "could not load '%s'", filename); JS_FreeCString(ctx, filename); return JS_EXCEPTION; } ret = JS_Eval(ctx, (char *)buf, buf_len, filename, JS_EVAL_TYPE_GLOBAL); js_free(ctx, buf); JS_FreeCString(ctx, filename); return ret; } static int get_bool_option(JSContext *ctx, bool *pbool, JSValueConst obj, const char *option) { JSValue val; val = JS_GetPropertyStr(ctx, obj, option); if (JS_IsException(val)) return -1; if (!JS_IsUndefined(val)) { *pbool = JS_ToBool(ctx, val); } JS_FreeValue(ctx, val); return 0; } static void free_buf(JSRuntime *rt, void *opaque, void *ptr) { js_free_rt(rt, ptr); } /* load a file as a UTF-8 encoded string or Uint8Array */ static JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; const char *filename; JSValueConst options_obj; JSValue ret; size_t buf_len; bool binary = false; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &binary, options_obj, "binary")) return JS_EXCEPTION; } filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; buf = js_load_file(ctx, &buf_len, filename); JS_FreeCString(ctx, filename); if (!buf) return JS_NULL; if (binary) { ret = JS_NewUint8Array(ctx, buf, buf_len, free_buf, NULL, false); } else { ret = JS_NewStringLen(ctx, (char *)buf, buf_len); js_free(ctx, buf); } return ret; } static JSValue js_std_writeFile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; const char *mode; const void *buf; size_t len, n; JSValueConst data; JSValue val, ret, unref; bool release; FILE *fp; ret = JS_EXCEPTION; len = 0; buf = ""; mode = "w"; data = argv[1]; unref = JS_UNDEFINED; release = false; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; if (JS_IsObject(data)) { val = JS_GetPropertyStr(ctx, data, "buffer"); if (JS_IsException(val)) goto exception; if (JS_IsArrayBuffer(val)) { data = unref = val; } else { JS_FreeValue(ctx, val); } } if (JS_IsArrayBuffer(data)) { buf = JS_GetArrayBuffer(ctx, &len, data); mode = "wb"; } else if (!JS_IsUndefined(data)) { buf = JS_ToCStringLen(ctx, &len, data); release = true; } if (!buf) goto exception; fp = fopen(filename, mode); if (!fp) { JS_ThrowPlainError(ctx, "error opening %s for writing", filename); goto exception; } n = fwrite(buf, len, 1, fp); fclose(fp); if (n != 1) { JS_ThrowPlainError(ctx, "error writing to %s", filename); goto exception; } ret = JS_UNDEFINED; exception: JS_FreeCString(ctx, filename); if (release) JS_FreeCString(ctx, buf); JS_FreeValue(ctx, unref); return ret; } typedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx, const char *module_name); #if defined(_WIN32) static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JSModuleDef *m; HINSTANCE hd; JSInitModuleFunc *init; char *filename = NULL; size_t len = strlen(module_name); bool is_absolute = len > 2 && ((module_name[0] >= 'A' && module_name[0] <= 'Z') || (module_name[0] >= 'a' && module_name[0] <= 'z')) && module_name[1] == ':'; bool is_relative = len > 2 && module_name[0] == '.' && (module_name[1] == '/' || module_name[1] == '\\'); if (is_absolute || is_relative) { filename = (char *)module_name; } else { filename = js_malloc(ctx, len + 2 + 1); if (!filename) return NULL; strcpy(filename, "./"); strcpy(filename + 2, module_name); } hd = LoadLibraryA(filename); if (filename != module_name) js_free(ctx, filename); if (hd == NULL) { JS_ThrowReferenceError(ctx, "js_load_module '%s' error: %lu", module_name, GetLastError()); goto fail; } init = (JSInitModuleFunc *)(uintptr_t)GetProcAddress(hd, "js_init_module"); if (!init) { JS_ThrowReferenceError(ctx, "js_init_module '%s' not found: %lu", module_name, GetLastError()); goto fail; } m = init(ctx, module_name); if (!m) { JS_ThrowReferenceError(ctx, "js_call_module '%s' initialization error", module_name); fail: if (hd != NULL) FreeLibrary(hd); return NULL; } return m; } #elif defined(__wasi__) static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JS_ThrowReferenceError(ctx, "shared library modules are not supported yet"); return NULL; } #else static JSModuleDef *js_module_loader_so(JSContext *ctx, const char *module_name) { JSModuleDef *m; void *hd; JSInitModuleFunc *init; char *filename; if (!strchr(module_name, '/')) { /* must add a '/' so that the DLL is not searched in the system library paths */ filename = js_malloc(ctx, strlen(module_name) + 2 + 1); if (!filename) return NULL; strcpy(filename, "./"); strcpy(filename + 2, module_name); } else { filename = (char *)module_name; } /* C module */ hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL); if (filename != module_name) js_free(ctx, filename); if (!hd) { JS_ThrowReferenceError(ctx, "could not load module filename '%s' as shared library: %s", module_name, dlerror()); goto fail; } *(void **) (&init) = dlsym(hd, "js_init_module"); if (!init) { JS_ThrowReferenceError(ctx, "could not load module filename '%s': js_init_module not found", module_name); goto fail; } m = init(ctx, module_name); if (!m) { JS_ThrowReferenceError(ctx, "could not load module filename '%s': initialization error", module_name); fail: if (hd) dlclose(hd); return NULL; } return m; } #endif /* !_WIN32 */ int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val, bool use_realpath, bool is_main) { JSModuleDef *m; char buf[JS__PATH_MAX + 16]; JSValue meta_obj; JSAtom module_name_atom; const char *module_name; assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE); m = JS_VALUE_GET_PTR(func_val); module_name_atom = JS_GetModuleName(ctx, m); module_name = JS_AtomToCString(ctx, module_name_atom); JS_FreeAtom(ctx, module_name_atom); if (!module_name) return -1; if (!strchr(module_name, ':')) { strcpy(buf, "file://"); #if !defined(_WIN32) && !defined(__wasi__) /* realpath() cannot be used with modules compiled with qjsc because the corresponding module source code is not necessarily present */ if (use_realpath) { char *res = realpath(module_name, buf + strlen(buf)); if (!res) { JS_ThrowTypeError(ctx, "realpath failure"); JS_FreeCString(ctx, module_name); return -1; } } else #endif { js__pstrcat(buf, sizeof(buf), module_name); } } else { js__pstrcpy(buf, sizeof(buf), module_name); } JS_FreeCString(ctx, module_name); meta_obj = JS_GetImportMeta(ctx, m); if (JS_IsException(meta_obj)) return -1; JS_DefinePropertyValueStr(ctx, meta_obj, "url", JS_NewString(ctx, buf), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, meta_obj, "main", JS_NewBool(ctx, is_main), JS_PROP_C_W_E); JS_FreeValue(ctx, meta_obj); return 0; } JSModuleDef *js_module_loader(JSContext *ctx, const char *module_name, void *opaque) { JSModuleDef *m; if (js__has_suffix(module_name, QJS_NATIVE_MODULE_SUFFIX)) { m = js_module_loader_so(ctx, module_name); } else { size_t buf_len; uint8_t *buf; JSValue func_val; buf = js_load_file(ctx, &buf_len, module_name); if (!buf) { JS_ThrowReferenceError(ctx, "could not load module filename '%s'", module_name); return NULL; } /* compile the module */ func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); js_free(ctx, buf); if (JS_IsException(func_val)) return NULL; if (js_module_set_import_meta(ctx, func_val, true, false) < 0) { JS_FreeValue(ctx, func_val); return NULL; } /* the module is already referenced, so we must free it */ m = JS_VALUE_GET_PTR(func_val); JS_FreeValue(ctx, func_val); } return m; } static JSValue js_std_exit(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int status; if (JS_ToInt32(ctx, &status, argv[0])) status = -1; exit(status); return JS_UNDEFINED; } static JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *name, *str; name = JS_ToCString(ctx, argv[0]); if (!name) return JS_EXCEPTION; str = getenv(name); JS_FreeCString(ctx, name); if (!str) return JS_UNDEFINED; else return JS_NewString(ctx, str); } #if defined(_WIN32) static void setenv(const char *name, const char *value, int overwrite) { char *str; size_t name_len, value_len; name_len = strlen(name); value_len = strlen(value); str = malloc(name_len + 1 + value_len + 1); memcpy(str, name, name_len); str[name_len] = '='; memcpy(str + name_len + 1, value, value_len); str[name_len + 1 + value_len] = '\0'; _putenv(str); free(str); } static void unsetenv(const char *name) { setenv(name, "", true); } #endif /* _WIN32 */ static JSValue js_std_setenv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *name, *value; name = JS_ToCString(ctx, argv[0]); if (!name) return JS_EXCEPTION; value = JS_ToCString(ctx, argv[1]); if (!value) { JS_FreeCString(ctx, name); return JS_EXCEPTION; } setenv(name, value, true); JS_FreeCString(ctx, name); JS_FreeCString(ctx, value); return JS_UNDEFINED; } static JSValue js_std_unsetenv(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *name; name = JS_ToCString(ctx, argv[0]); if (!name) return JS_EXCEPTION; unsetenv(name); JS_FreeCString(ctx, name); return JS_UNDEFINED; } /* return an object containing the list of the available environment variables. */ static JSValue js_std_getenviron(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char **envp; const char *name, *p, *value; JSValue obj; uint32_t idx; size_t name_len; JSAtom atom; int ret; obj = JS_NewObject(ctx); if (JS_IsException(obj)) return JS_EXCEPTION; envp = environ; for(idx = 0; envp[idx] != NULL; idx++) { name = envp[idx]; p = strchr(name, '='); name_len = p - name; if (!p) continue; value = p + 1; atom = JS_NewAtomLen(ctx, name, name_len); if (atom == JS_ATOM_NULL) goto fail; ret = JS_DefinePropertyValue(ctx, obj, atom, JS_NewString(ctx, value), JS_PROP_C_W_E); JS_FreeAtom(ctx, atom); if (ret < 0) goto fail; } return obj; fail: JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_std_gc(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JS_RunGC(JS_GetRuntime(ctx)); return JS_UNDEFINED; } static int interrupt_handler(JSRuntime *rt, void *opaque) { return (os_pending_signals >> SIGINT) & 1; } static JSValue js_evalScript(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); const char *str = NULL; size_t len; JSValue ret, obj; JSValueConst options_obj, arg; bool backtrace_barrier = false; bool eval_function = false; bool eval_module = false; bool compile_only = false; bool compile_module = false; bool is_async = false; int flags; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &backtrace_barrier, options_obj, "backtrace_barrier")) return JS_EXCEPTION; if (get_bool_option(ctx, &eval_function, options_obj, "eval_function")) return JS_EXCEPTION; if (get_bool_option(ctx, &eval_module, options_obj, "eval_module")) return JS_EXCEPTION; if (get_bool_option(ctx, &compile_only, options_obj, "compile_only")) return JS_EXCEPTION; if (get_bool_option(ctx, &compile_module, options_obj, "compile_module")) return JS_EXCEPTION; if (get_bool_option(ctx, &is_async, options_obj, "async")) return JS_EXCEPTION; } if (eval_module) { arg = argv[0]; if (JS_VALUE_GET_TAG(arg) != JS_TAG_MODULE) return JS_ThrowTypeError(ctx, "not a module"); if (JS_ResolveModule(ctx, arg) < 0) return JS_EXCEPTION; if (js_module_set_import_meta(ctx, arg, false, false) < 0) return JS_EXCEPTION; return JS_EvalFunction(ctx, JS_DupValue(ctx, arg)); } if (!eval_function) { str = JS_ToCStringLen(ctx, &len, argv[0]); if (!str) return JS_EXCEPTION; } if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) { /* install the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL); } flags = compile_module ? JS_EVAL_TYPE_MODULE : JS_EVAL_TYPE_GLOBAL; if (backtrace_barrier) flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER; if (compile_only) flags |= JS_EVAL_FLAG_COMPILE_ONLY; if (is_async) flags |= JS_EVAL_FLAG_ASYNC; if (eval_function) { obj = JS_DupValue(ctx, argv[0]); ret = JS_EvalFunction(ctx, obj); // takes ownership of |obj| } else { ret = JS_Eval(ctx, str, len, "", flags); } JS_FreeCString(ctx, str); if (!ts->recv_pipe && --ts->eval_script_recurse == 0) { /* remove the interrupt handler */ JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL); os_pending_signals &= ~((uint64_t)1 << SIGINT); /* convert the uncatchable "interrupted" error into a normal error so that it can be caught by the REPL */ if (JS_IsException(ret)) JS_ResetUncatchableError(ctx); } return ret; } typedef struct { FILE *f; bool is_popen; } JSSTDFile; static bool is_stdio(FILE *f) { return f == stdin || f == stdout || f == stderr; } static void js_std_file_finalizer(JSRuntime *rt, JSValueConst val) { JSThreadState *ts = js_get_thread_state(rt); JSSTDFile *s = JS_GetOpaque(val, ts->std_file_class_id); if (s) { if (s->f && !is_stdio(s->f)) { #if !defined(__wasi__) if (s->is_popen) pclose(s->f); else #endif fclose(s->f); } js_free_rt(rt, s); } } static ssize_t js_get_errno(ssize_t ret) { if (ret == -1) ret = -errno; return ret; } static JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int err; if (JS_ToInt32(ctx, &err, argv[0])) return JS_EXCEPTION; return JS_NewString(ctx, strerror(err)); } static JSValue js_new_std_file(JSContext *ctx, FILE *f, bool is_popen) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSSTDFile *s; JSValue obj; obj = JS_NewObjectClass(ctx, ts->std_file_class_id); if (JS_IsException(obj)) return obj; s = js_mallocz(ctx, sizeof(*s)); if (!s) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } s->is_popen = is_popen; s->f = f; JS_SetOpaque(obj, s); return obj; } static void js_set_error_object(JSContext *ctx, JSValueConst obj, int err) { if (!JS_IsUndefined(obj)) { JS_SetPropertyStr(ctx, obj, "errno", JS_NewInt32(ctx, err)); } } static JSValue js_std_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename, *mode = NULL; FILE *f; int err; filename = JS_ToCString(ctx, argv[0]); if (!filename) goto fail; mode = JS_ToCString(ctx, argv[1]); if (!mode) goto fail; if (mode[strspn(mode, "rwa+bx")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = fopen(filename, mode); if (!f) err = errno; else err = 0; if (argc >= 3) js_set_error_object(ctx, argv[2], err); JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); if (!f) return JS_NULL; return js_new_std_file(ctx, f, false); fail: JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); return JS_EXCEPTION; } #if !defined(__wasi__) static JSValue js_std_popen(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename, *mode = NULL; FILE *f; int err; filename = JS_ToCString(ctx, argv[0]); if (!filename) goto fail; mode = JS_ToCString(ctx, argv[1]); if (!mode) goto fail; if (strcmp(mode, "r") && strcmp(mode, "w")) { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = popen(filename, mode); if (!f) err = errno; else err = 0; if (argc >= 3) js_set_error_object(ctx, argv[2], err); JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); if (!f) return JS_NULL; return js_new_std_file(ctx, f, true); fail: JS_FreeCString(ctx, filename); JS_FreeCString(ctx, mode); return JS_EXCEPTION; } #endif // !defined(__wasi__) static JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *mode; FILE *f; int fd, err; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; mode = JS_ToCString(ctx, argv[1]); if (!mode) goto fail; if (mode[strspn(mode, "rwa+")] != '\0') { JS_ThrowTypeError(ctx, "invalid file mode"); goto fail; } f = fdopen(fd, mode); if (!f) err = errno; else err = 0; if (argc >= 3) js_set_error_object(ctx, argv[2], err); JS_FreeCString(ctx, mode); if (!f) return JS_NULL; return js_new_std_file(ctx, f, false); fail: JS_FreeCString(ctx, mode); return JS_EXCEPTION; } #if !defined(__wasi__) static JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f; f = tmpfile(); if (argc >= 1) js_set_error_object(ctx, argv[0], f ? 0 : errno); if (!f) return JS_NULL; return js_new_std_file(ctx, f, false); } #endif static JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return js_printf_internal(ctx, argc, argv, NULL); } static JSValue js_std_printf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return js_printf_internal(ctx, argc, argv, stdout); } static FILE *js_std_file_get(JSContext *ctx, JSValueConst obj) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSSTDFile *s = JS_GetOpaque2(ctx, obj, ts->std_file_class_id); if (!s) return NULL; if (!s->f) { JS_ThrowTypeError(ctx, "invalid file handle"); return NULL; } return s->f; } static JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f; int i; const char *str; size_t len; if (magic == 0) { f = stdout; } else { f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; } for(i = 0; i < argc; i++) { str = JS_ToCStringLen(ctx, &len, argv[i]); if (!str) return JS_EXCEPTION; fwrite(str, 1, len, f); JS_FreeCString(ctx, str); } return JS_UNDEFINED; } static JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSSTDFile *s = JS_GetOpaque2(ctx, this_val, ts->std_file_class_id); int err; if (!s) return JS_EXCEPTION; if (!s->f) return JS_ThrowTypeError(ctx, "invalid file handle"); if (is_stdio(s->f)) return JS_ThrowTypeError(ctx, "cannot close stdio"); #if !defined(__wasi__) if (s->is_popen) err = js_get_errno(pclose(s->f)); else #endif err = js_get_errno(fclose(s->f)); s->f = NULL; return JS_NewInt32(ctx, err); } static JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return js_printf_internal(ctx, argc, argv, f); } static JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; fflush(f); return JS_UNDEFINED; } static JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int is_bigint) { FILE *f = js_std_file_get(ctx, this_val); int64_t pos; if (!f) return JS_EXCEPTION; #if defined(__linux__) || defined(__GLIBC__) pos = ftello(f); #else pos = ftell(f); #endif if (is_bigint) return JS_NewBigInt64(ctx, pos); else return JS_NewInt64(ctx, pos); } static JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int64_t pos; int whence, ret; if (!f) return JS_EXCEPTION; if (JS_ToInt64Ext(ctx, &pos, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &whence, argv[1])) return JS_EXCEPTION; #if defined(__linux__) || defined(__GLIBC__) ret = fseeko(f, pos, whence); #else ret = fseek(f, pos, whence); #endif if (ret < 0) ret = -errno; return JS_NewInt32(ctx, ret); } static JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewBool(ctx, feof(f)); } static JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewBool(ctx, ferror(f)); } static JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; clearerr(f); return JS_UNDEFINED; } static JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewInt32(ctx, fileno(f)); } static JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f = js_std_file_get(ctx, this_val); uint64_t pos, len; size_t size, ret; uint8_t *buf; if (!f) return JS_EXCEPTION; if (JS_ToIndex(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[2])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[0]); if (!buf) return JS_EXCEPTION; if (pos + len > size) return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); if (magic) ret = fwrite(buf + pos, 1, len, f); else ret = fread(buf + pos, 1, len, f); return JS_NewInt64(ctx, ret); } /* XXX: could use less memory and go faster */ static JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; DynBuf dbuf; JSValue obj; if (!f) return JS_EXCEPTION; js_std_dbuf_init(ctx, &dbuf); for(;;) { c = fgetc(f); if (c == EOF) { if (dbuf.size == 0) { /* EOF */ dbuf_free(&dbuf); return JS_NULL; } else { break; } } if (c == '\n') break; if (dbuf_putc(&dbuf, c)) { dbuf_free(&dbuf); return JS_ThrowOutOfMemory(ctx); } } obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); dbuf_free(&dbuf); return obj; } /* XXX: could use less memory and go faster */ static JSValue js_std_file_readAs(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { FILE *f = js_std_file_get(ctx, this_val); int c; DynBuf dbuf; JSValue obj; uint64_t max_size64; size_t max_size; JSValueConst max_size_val; if (!f) return JS_EXCEPTION; if (argc >= 1) max_size_val = argv[0]; else max_size_val = JS_UNDEFINED; max_size = (size_t)-1; if (!JS_IsUndefined(max_size_val)) { if (JS_ToIndex(ctx, &max_size64, max_size_val)) return JS_EXCEPTION; if (max_size64 < max_size) max_size = max_size64; } js_std_dbuf_init(ctx, &dbuf); while (max_size != 0) { c = fgetc(f); if (c == EOF) break; if (dbuf_putc(&dbuf, c)) { dbuf_free(&dbuf); return JS_EXCEPTION; } max_size--; } if (magic) { obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size); } else { obj = JS_NewArrayBufferCopy(ctx, dbuf.buf, dbuf.size); } dbuf_free(&dbuf); return obj; } static JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); if (!f) return JS_EXCEPTION; return JS_NewInt32(ctx, fgetc(f)); } static JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { FILE *f = js_std_file_get(ctx, this_val); int c; if (!f) return JS_EXCEPTION; if (JS_ToInt32(ctx, &c, argv[0])) return JS_EXCEPTION; c = fputc(c, f); return JS_NewInt32(ctx, c); } /* urlGet */ #if !defined(__wasi__) #define URL_GET_PROGRAM "curl -s -i --" #define URL_GET_BUF_SIZE 4096 static int http_get_header_line(FILE *f, char *buf, size_t buf_size, DynBuf *dbuf) { int c; char *p; p = buf; for(;;) { c = fgetc(f); if (c < 0) return -1; if ((p - buf) < buf_size - 1) *p++ = c; if (dbuf) dbuf_putc(dbuf, c); if (c == '\n') break; } *p = '\0'; return 0; } static int http_get_status(const char *buf) { const char *p = buf; while (*p != ' ' && *p != '\0') p++; if (*p != ' ') return 0; while (*p == ' ') p++; return atoi(p); } static JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *url; DynBuf cmd_buf; DynBuf data_buf_s, *data_buf = &data_buf_s; DynBuf header_buf_s, *header_buf = &header_buf_s; char *buf; size_t i, len; int status; JSValue response = JS_UNDEFINED, ret_obj; JSValueConst options_obj; FILE *f; bool binary_flag, full_flag; url = JS_ToCString(ctx, argv[0]); if (!url) return JS_EXCEPTION; binary_flag = false; full_flag = false; if (argc >= 2) { options_obj = argv[1]; if (get_bool_option(ctx, &binary_flag, options_obj, "binary")) goto fail_obj; if (get_bool_option(ctx, &full_flag, options_obj, "full")) { fail_obj: JS_FreeCString(ctx, url); return JS_EXCEPTION; } } js_std_dbuf_init(ctx, &cmd_buf); dbuf_printf(&cmd_buf, "%s '", URL_GET_PROGRAM); for(i = 0; url[i] != '\0'; i++) { unsigned char c = url[i]; switch (c) { case '\'': /* shell single quoted string does not support \' */ dbuf_putstr(&cmd_buf, "'\\''"); break; case '[': case ']': case '{': case '}': case '\\': /* prevent interpretation by curl as range or set specification */ dbuf_putc(&cmd_buf, '\\'); /* FALLTHROUGH */ default: dbuf_putc(&cmd_buf, c); break; } } JS_FreeCString(ctx, url); dbuf_putstr(&cmd_buf, "'"); dbuf_putc(&cmd_buf, '\0'); if (dbuf_error(&cmd_buf)) { dbuf_free(&cmd_buf); return JS_EXCEPTION; } // printf("%s\n", (char *)cmd_buf.buf); f = popen((char *)cmd_buf.buf, "r"); dbuf_free(&cmd_buf); if (!f) { return JS_ThrowTypeError(ctx, "could not start curl"); } js_std_dbuf_init(ctx, data_buf); js_std_dbuf_init(ctx, header_buf); buf = js_malloc(ctx, URL_GET_BUF_SIZE); if (!buf) goto fail; /* get the HTTP status */ if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) { status = 0; goto bad_header; } status = http_get_status(buf); if (!full_flag && !(status >= 200 && status <= 299)) { goto bad_header; } /* wait until there is an empty line */ for(;;) { if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) { bad_header: response = JS_NULL; goto done; } if (!strcmp(buf, "\r\n")) break; } if (dbuf_error(header_buf)) goto fail; header_buf->size -= 2; /* remove the trailing CRLF */ /* download the data */ for(;;) { len = fread(buf, 1, URL_GET_BUF_SIZE, f); if (len == 0) break; dbuf_put(data_buf, (uint8_t *)buf, len); } if (dbuf_error(data_buf)) goto fail; if (binary_flag) { response = JS_NewArrayBufferCopy(ctx, data_buf->buf, data_buf->size); } else { response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size); } if (JS_IsException(response)) goto fail; done: js_free(ctx, buf); buf = NULL; pclose(f); f = NULL; dbuf_free(data_buf); data_buf = NULL; if (full_flag) { ret_obj = JS_NewObject(ctx); if (JS_IsException(ret_obj)) goto fail; JS_DefinePropertyValueStr(ctx, ret_obj, "response", response, JS_PROP_C_W_E); if (!JS_IsNull(response)) { JS_DefinePropertyValueStr(ctx, ret_obj, "responseHeaders", JS_NewStringLen(ctx, (char *)header_buf->buf, header_buf->size), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, ret_obj, "status", JS_NewInt32(ctx, status), JS_PROP_C_W_E); } } else { ret_obj = response; } dbuf_free(header_buf); return ret_obj; fail: if (f) pclose(f); js_free(ctx, buf); if (data_buf) dbuf_free(data_buf); if (header_buf) dbuf_free(header_buf); JS_FreeValue(ctx, response); return JS_EXCEPTION; } #endif // !defined(__wasi__) static JSClassDef js_std_file_class = { "FILE", .finalizer = js_std_file_finalizer, }; static const JSCFunctionListEntry js_std_error_props[] = { /* various errno values */ #define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE ) DEF(EINVAL), DEF(EIO), DEF(EACCES), DEF(EEXIST), DEF(ENOSPC), DEF(ENOSYS), DEF(EBUSY), DEF(ENOENT), DEF(EPERM), DEF(EPIPE), DEF(EBADF), #undef DEF }; static const JSCFunctionListEntry js_std_funcs[] = { JS_CFUNC_DEF("exit", 1, js_std_exit ), JS_CFUNC_DEF("gc", 0, js_std_gc ), JS_CFUNC_DEF("evalScript", 1, js_evalScript ), JS_CFUNC_DEF("loadScript", 1, js_loadScript ), JS_CFUNC_DEF("getenv", 1, js_std_getenv ), JS_CFUNC_DEF("setenv", 1, js_std_setenv ), JS_CFUNC_DEF("unsetenv", 1, js_std_unsetenv ), JS_CFUNC_DEF("getenviron", 1, js_std_getenviron ), #if !defined(__wasi__) JS_CFUNC_DEF("urlGet", 1, js_std_urlGet ), #endif JS_CFUNC_DEF("loadFile", 1, js_std_loadFile ), JS_CFUNC_DEF("writeFile", 2, js_std_writeFile ), JS_CFUNC_DEF("strerror", 1, js_std_strerror ), /* FILE I/O */ JS_CFUNC_DEF("open", 2, js_std_open ), #if !defined(__wasi__) JS_CFUNC_DEF("popen", 2, js_std_popen ), JS_CFUNC_DEF("tmpfile", 0, js_std_tmpfile ), #endif JS_CFUNC_DEF("fdopen", 2, js_std_fdopen ), JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 0 ), JS_CFUNC_DEF("printf", 1, js_std_printf ), JS_CFUNC_DEF("sprintf", 1, js_std_sprintf ), JS_PROP_INT32_DEF("SEEK_SET", SEEK_SET, JS_PROP_CONFIGURABLE ), JS_PROP_INT32_DEF("SEEK_CUR", SEEK_CUR, JS_PROP_CONFIGURABLE ), JS_PROP_INT32_DEF("SEEK_END", SEEK_END, JS_PROP_CONFIGURABLE ), JS_OBJECT_DEF("Error", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE), }; static const JSCFunctionListEntry js_std_file_proto_funcs[] = { JS_CFUNC_DEF("close", 0, js_std_file_close ), JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 1 ), JS_CFUNC_DEF("printf", 1, js_std_file_printf ), JS_CFUNC_DEF("flush", 0, js_std_file_flush ), JS_CFUNC_MAGIC_DEF("tell", 0, js_std_file_tell, 0 ), JS_CFUNC_MAGIC_DEF("tello", 0, js_std_file_tell, 1 ), JS_CFUNC_DEF("seek", 2, js_std_file_seek ), JS_CFUNC_DEF("eof", 0, js_std_file_eof ), JS_CFUNC_DEF("fileno", 0, js_std_file_fileno ), JS_CFUNC_DEF("error", 0, js_std_file_error ), JS_CFUNC_DEF("clearerr", 0, js_std_file_clearerr ), JS_CFUNC_MAGIC_DEF("read", 3, js_std_file_read_write, 0 ), JS_CFUNC_MAGIC_DEF("write", 3, js_std_file_read_write, 1 ), JS_CFUNC_DEF("getline", 0, js_std_file_getline ), JS_CFUNC_MAGIC_DEF("readAsArrayBuffer", 0, js_std_file_readAs, 0 ), JS_CFUNC_MAGIC_DEF("readAsString", 0, js_std_file_readAs, 1 ), JS_CFUNC_DEF("getByte", 0, js_std_file_getByte ), JS_CFUNC_DEF("putByte", 1, js_std_file_putByte ), /* setvbuf, ... */ }; static int js_std_init(JSContext *ctx, JSModuleDef *m) { JSValue proto; JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); /* FILE class */ /* the class ID is created once */ JS_NewClassID(rt, &ts->std_file_class_id); /* the class is created once per runtime */ JS_NewClass(rt, ts->std_file_class_id, &js_std_file_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs, countof(js_std_file_proto_funcs)); JS_SetClassProto(ctx, ts->std_file_class_id, proto); JS_SetModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs)); JS_SetModuleExport(ctx, m, "in", js_new_std_file(ctx, stdin, false)); JS_SetModuleExport(ctx, m, "out", js_new_std_file(ctx, stdout, false)); JS_SetModuleExport(ctx, m, "err", js_new_std_file(ctx, stderr, false)); return 0; } JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_std_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs)); JS_AddModuleExport(ctx, m, "in"); JS_AddModuleExport(ctx, m, "out"); JS_AddModuleExport(ctx, m, "err"); return m; } /**********************************************************/ /* 'os' object */ static JSValue js_os_open(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; int flags, mode, ret; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; if (JS_ToInt32(ctx, &flags, argv[1])) goto fail; if (argc >= 3 && !JS_IsUndefined(argv[2])) { if (JS_ToInt32(ctx, &mode, argv[2])) { fail: JS_FreeCString(ctx, filename); return JS_EXCEPTION; } } else { mode = 0666; } #if defined(_WIN32) /* force binary mode by default */ if (!(flags & O_TEXT)) flags |= O_BINARY; #endif ret = js_get_errno(open(filename, flags, mode)); JS_FreeCString(ctx, filename); return JS_NewInt32(ctx, ret); } static JSValue js_os_close(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, ret; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; ret = js_get_errno(close(fd)); return JS_NewInt32(ctx, ret); } static JSValue js_os_seek(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, whence; int64_t pos, ret; bool is_bigint; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; is_bigint = JS_IsBigInt(argv[1]); if (JS_ToInt64Ext(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &whence, argv[2])) return JS_EXCEPTION; ret = lseek(fd, pos, whence); if (ret == -1) ret = -errno; if (is_bigint) return JS_NewBigInt64(ctx, ret); else return JS_NewInt64(ctx, ret); } static JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { int fd; uint64_t pos, len; size_t size; ssize_t ret; uint8_t *buf; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &pos, argv[2])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[3])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[1]); if (!buf) return JS_EXCEPTION; if (pos + len > size) return JS_ThrowRangeError(ctx, "read/write array buffer overflow"); if (magic) ret = js_get_errno(write(fd, buf + pos, len)); else ret = js_get_errno(read(fd, buf + pos, len)); return JS_NewInt64(ctx, ret); } static JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; return JS_NewBool(ctx, (isatty(fd) != 0)); } #if defined(_WIN32) static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; HANDLE handle; CONSOLE_SCREEN_BUFFER_INFO info; JSValue obj; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; handle = (HANDLE)_get_osfhandle(fd); if (!GetConsoleScreenBufferInfo(handle, &info)) return JS_NULL; obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E); return obj; } /* Windows 10 built-in VT100 emulation */ #define __ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 #define __ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200 static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; HANDLE handle; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; handle = (HANDLE)_get_osfhandle(fd); SetConsoleMode(handle, ENABLE_WINDOW_INPUT | __ENABLE_VIRTUAL_TERMINAL_INPUT); _setmode(fd, _O_BINARY); if (fd == 0) { handle = (HANDLE)_get_osfhandle(1); /* corresponding output */ SetConsoleMode(handle, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | __ENABLE_VIRTUAL_TERMINAL_PROCESSING); } return JS_UNDEFINED; } #elif !defined(__wasi__) static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd; struct winsize ws; JSValue obj; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; if (ioctl(fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 4 && ws.ws_row >= 4) { obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E); return obj; } else { return JS_NULL; } } static struct termios oldtty; static void term_exit(void) { tcsetattr(0, TCSANOW, &oldtty); } /* XXX: should add a way to go back to normal mode */ static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { struct termios tty; int fd; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; memset(&tty, 0, sizeof(tty)); tcgetattr(fd, &tty); oldtty = tty; tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP |INLCR|IGNCR|ICRNL|IXON); tty.c_oflag |= OPOST; tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN); tty.c_cflag &= ~(CSIZE|PARENB); tty.c_cflag |= CS8; tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 0; tcsetattr(fd, TCSANOW, &tty); atexit(term_exit); return JS_UNDEFINED; } #endif /* !_WIN32 && !__wasi__ */ static JSValue js_os_remove(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *filename; int ret; filename = JS_ToCString(ctx, argv[0]); if (!filename) return JS_EXCEPTION; #if defined(_WIN32) { struct stat st; if (stat(filename, &st) == 0 && (st.st_mode & _S_IFDIR)) { ret = rmdir(filename); } else { ret = unlink(filename); } } #else ret = remove(filename); #endif ret = js_get_errno(ret); JS_FreeCString(ctx, filename); return JS_NewInt32(ctx, ret); } static JSValue js_os_rename(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *oldpath, *newpath; int ret; oldpath = JS_ToCString(ctx, argv[0]); if (!oldpath) return JS_EXCEPTION; newpath = JS_ToCString(ctx, argv[1]); if (!newpath) { JS_FreeCString(ctx, oldpath); return JS_EXCEPTION; } ret = js_get_errno(rename(oldpath, newpath)); JS_FreeCString(ctx, oldpath); JS_FreeCString(ctx, newpath); return JS_NewInt32(ctx, ret); } static bool is_main_thread(JSRuntime *rt) { JSThreadState *ts = js_get_thread_state(rt); return !ts->recv_pipe; } static JSOSRWHandler *find_rh(JSThreadState *ts, int fd) { JSOSRWHandler *rh; struct list_head *el; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == fd) return rh; } return NULL; } static void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh) { int i; list_del(&rh->link); for(i = 0; i < 2; i++) { JS_FreeValueRT(rt, rh->rw_func[i]); } js_free_rt(rt, rh); } static JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSOSRWHandler *rh; int fd; JSValueConst func; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; func = argv[1]; if (JS_IsNull(func)) { rh = find_rh(ts, fd); if (rh) { JS_FreeValue(ctx, rh->rw_func[magic]); rh->rw_func[magic] = JS_NULL; if (JS_IsNull(rh->rw_func[0]) && JS_IsNull(rh->rw_func[1])) { /* remove the entry */ free_rw_handler(JS_GetRuntime(ctx), rh); } } } else { if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); rh = find_rh(ts, fd); if (!rh) { rh = js_mallocz(ctx, sizeof(*rh)); if (!rh) return JS_EXCEPTION; rh->fd = fd; rh->rw_func[0] = JS_NULL; rh->rw_func[1] = JS_NULL; list_add_tail(&rh->link, &ts->os_rw_handlers); } JS_FreeValue(ctx, rh->rw_func[magic]); rh->rw_func[magic] = JS_DupValue(ctx, func); } return JS_UNDEFINED; } static JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num) { JSOSSignalHandler *sh; struct list_head *el; list_for_each(el, &ts->os_signal_handlers) { sh = list_entry(el, JSOSSignalHandler, link); if (sh->sig_num == sig_num) return sh; } return NULL; } static void free_sh(JSRuntime *rt, JSOSSignalHandler *sh) { list_del(&sh->link); JS_FreeValueRT(rt, sh->func); js_free_rt(rt, sh); } static void os_signal_handler(int sig_num) { os_pending_signals |= ((uint64_t)1 << sig_num); } #if defined(_WIN32) typedef void (*sighandler_t)(int sig_num); #endif static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSOSSignalHandler *sh; uint32_t sig_num; JSValueConst func; sighandler_t handler; if (!is_main_thread(rt)) return JS_ThrowTypeError(ctx, "signal handler can only be set in the main thread"); if (JS_ToUint32(ctx, &sig_num, argv[0])) return JS_EXCEPTION; if (sig_num >= 64) return JS_ThrowRangeError(ctx, "invalid signal number"); func = argv[1]; /* func = null: SIG_DFL, func = undefined, SIG_IGN */ if (JS_IsNull(func) || JS_IsUndefined(func)) { sh = find_sh(ts, sig_num); if (sh) { free_sh(JS_GetRuntime(ctx), sh); } if (JS_IsNull(func)) handler = SIG_DFL; else handler = SIG_IGN; signal(sig_num, handler); } else { if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); sh = find_sh(ts, sig_num); if (!sh) { sh = js_mallocz(ctx, sizeof(*sh)); if (!sh) return JS_EXCEPTION; sh->sig_num = sig_num; list_add_tail(&sh->link, &ts->os_signal_handlers); } JS_FreeValue(ctx, sh->func); sh->func = JS_DupValue(ctx, func); signal(sig_num, os_signal_handler); } return JS_UNDEFINED; } #if !defined(_WIN32) && !defined(__wasi__) static JSValue js_os_cputime(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { struct rusage ru; int64_t cputime; cputime = 0; if (!getrusage(RUSAGE_SELF, &ru)) cputime = (int64_t)ru.ru_utime.tv_sec * 1000000 + ru.ru_utime.tv_usec; return JS_NewInt64(ctx, cputime); } #endif static JSValue js_os_exepath(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char buf[JS__PATH_MAX]; size_t len = sizeof(buf); if (js_exepath(buf, &len)) return JS_UNDEFINED; return JS_NewStringLen(ctx, buf, len); } static JSValue js_os_now(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return JS_NewInt64(ctx, js__hrtime_ns() / 1000); } static uint64_t js__hrtime_ms(void) { return js__hrtime_ns() / (1000 * 1000); } static void free_timer(JSRuntime *rt, JSOSTimer *th) { list_del(&th->link); JS_FreeValueRT(rt, th->func); js_free_rt(rt, th); } // TODO(bnoordhuis) accept string as first arg and eval at timer expiry // TODO(bnoordhuis) retain argv[2..] as args for callback if argc > 2 static JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); int64_t delay; JSValueConst func; JSOSTimer *th; func = argv[0]; if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); if (JS_ToInt64(ctx, &delay, argv[1])) return JS_EXCEPTION; if (delay < 1) delay = 1; th = js_mallocz(ctx, sizeof(*th)); if (!th) return JS_EXCEPTION; th->timer_id = ts->next_timer_id++; if (ts->next_timer_id > MAX_SAFE_INTEGER) ts->next_timer_id = 1; th->repeats = (magic > 0); th->timeout = js__hrtime_ms() + delay; th->delay = delay; th->func = JS_DupValue(ctx, func); list_add_tail(&th->link, &ts->os_timers); return JS_NewInt64(ctx, th->timer_id); } static JSOSTimer *find_timer_by_id(JSThreadState *ts, int timer_id) { struct list_head *el; if (timer_id <= 0) return NULL; list_for_each(el, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); if (th->timer_id == timer_id) return th; } return NULL; } static JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSOSTimer *th; int64_t timer_id; if (JS_ToInt64(ctx, &timer_id, argv[0])) return JS_EXCEPTION; th = find_timer_by_id(ts, timer_id); if (!th) return JS_UNDEFINED; free_timer(rt, th); return JS_UNDEFINED; } /* return a promise */ static JSValue js_os_sleepAsync(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); int64_t delay; JSOSTimer *th; JSValue promise, resolving_funcs[2]; if (JS_ToInt64(ctx, &delay, argv[0])) return JS_EXCEPTION; promise = JS_NewPromiseCapability(ctx, resolving_funcs); if (JS_IsException(promise)) return JS_EXCEPTION; th = js_mallocz(ctx, sizeof(*th)); if (!th) { JS_FreeValue(ctx, promise); JS_FreeValue(ctx, resolving_funcs[0]); JS_FreeValue(ctx, resolving_funcs[1]); return JS_EXCEPTION; } th->timer_id = -1; th->timeout = js__hrtime_ms() + delay; th->func = JS_DupValue(ctx, resolving_funcs[0]); list_add_tail(&th->link, &ts->os_timers); JS_FreeValue(ctx, resolving_funcs[0]); JS_FreeValue(ctx, resolving_funcs[1]); return promise; } static int call_handler(JSContext *ctx, JSValue func) { int r; JSValue ret, func1; /* 'func' might be destroyed when calling itself (if it frees the handler), so must take extra care */ func1 = JS_DupValue(ctx, func); ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL); JS_FreeValue(ctx, func1); r = 0; if (JS_IsException(ret)) r = -1; JS_FreeValue(ctx, ret); return r; } static int js_os_run_timers(JSRuntime *rt, JSContext *ctx, JSThreadState *ts, int *min_delay) { JSValue func; JSOSTimer *th; int64_t cur_time, delay; struct list_head *el; int r; if (list_empty(&ts->os_timers)) { *min_delay = -1; return 0; } cur_time = js__hrtime_ms(); *min_delay = INT32_MAX; list_for_each(el, &ts->os_timers) { th = list_entry(el, JSOSTimer, link); delay = th->timeout - cur_time; if (delay > 0) { *min_delay = min_int(*min_delay, delay); } else { *min_delay = 0; func = JS_DupValueRT(rt, th->func); if (th->repeats) th->timeout = cur_time + th->delay; else free_timer(rt, th); r = call_handler(ctx, func); JS_FreeValueRT(rt, func); return r; } } return 0; } #ifdef USE_WORKER #ifdef _WIN32 static int js_waker_init(JSWaker *w) { w->handle = CreateEvent(NULL, TRUE, FALSE, NULL); return w->handle ? 0 : -1; } static void js_waker_signal(JSWaker *w) { SetEvent(w->handle); } static void js_waker_clear(JSWaker *w) { ResetEvent(w->handle); } static void js_waker_close(JSWaker *w) { CloseHandle(w->handle); w->handle = INVALID_HANDLE_VALUE; } #else // !_WIN32 static int js_waker_init(JSWaker *w) { int fds[2]; if (pipe(fds) < 0) return -1; w->read_fd = fds[0]; w->write_fd = fds[1]; return 0; } static void js_waker_signal(JSWaker *w) { int ret; for(;;) { ret = write(w->write_fd, "", 1); if (ret == 1) break; if (ret < 0 && (errno != EAGAIN || errno != EINTR)) break; } } static void js_waker_clear(JSWaker *w) { uint8_t buf[16]; int ret; for(;;) { ret = read(w->read_fd, buf, sizeof(buf)); if (ret >= 0) break; if (errno != EAGAIN && errno != EINTR) break; } } static void js_waker_close(JSWaker *w) { close(w->read_fd); close(w->write_fd); w->read_fd = -1; w->write_fd = -1; } #endif // _WIN32 static void js_free_message(JSWorkerMessage *msg); /* return 1 if a message was handled, 0 if no message */ static int handle_posted_message(JSRuntime *rt, JSContext *ctx, JSWorkerMessageHandler *port) { JSWorkerMessagePipe *ps = port->recv_pipe; int ret; struct list_head *el; JSWorkerMessage *msg; JSValue obj, data_obj, func, retval; js_mutex_lock(&ps->mutex); if (!list_empty(&ps->msg_queue)) { el = ps->msg_queue.next; msg = list_entry(el, JSWorkerMessage, link); /* remove the message from the queue */ list_del(&msg->link); // drain read end of pipe if (list_empty(&ps->msg_queue)) js_waker_clear(&ps->waker); js_mutex_unlock(&ps->mutex); data_obj = JS_ReadObject(ctx, msg->data, msg->data_len, JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE); js_free_message(msg); if (JS_IsException(data_obj)) goto fail; obj = JS_NewObject(ctx); if (JS_IsException(obj)) { JS_FreeValue(ctx, data_obj); goto fail; } JS_DefinePropertyValueStr(ctx, obj, "data", data_obj, JS_PROP_C_W_E); /* 'func' might be destroyed when calling itself (if it frees the handler), so must take extra care */ func = JS_DupValue(ctx, port->on_message_func); retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj); JS_FreeValue(ctx, obj); JS_FreeValue(ctx, func); if (JS_IsException(retval)) { fail: js_std_dump_error(ctx); } else { JS_FreeValue(ctx, retval); } ret = 1; } else { js_mutex_unlock(&ps->mutex); ret = 0; } return ret; } #endif // USE_WORKER #if defined(_WIN32) static int js_os_poll(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); int min_delay, count; JSOSRWHandler *rh; struct list_head *el; HANDLE handles[MAXIMUM_WAIT_OBJECTS]; // 64 /* XXX: handle signals if useful */ if (js_os_run_timers(rt, ctx, ts, &min_delay)) return -1; if (min_delay == 0) return 0; // expired timer if (min_delay < 0) if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->port_list)) return -1; /* no more events */ count = 0; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) handles[count++] = (HANDLE)_get_osfhandle(rh->fd); // stdin if (count == (int)countof(handles)) break; } list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (JS_IsNull(port->on_message_func)) continue; handles[count++] = port->recv_pipe->waker.handle; if (count == (int)countof(handles)) break; } if (count > 0) { DWORD ret, timeout = INFINITE; if (min_delay != -1) timeout = min_delay; ret = WaitForMultipleObjects(count, handles, FALSE, timeout); if (ret < count) { list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) { return call_handler(ctx, rh->rw_func[0]); /* must stop because the list may have been modified */ } } list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; if (ps->waker.handle == handles[ret]) { if (handle_posted_message(rt, ctx, port)) goto done; } } } } } else { Sleep(min_delay); } done: return 0; } #else // !defined(_WIN32) static int js_os_poll(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); int r, w, ret, nfds, min_delay; JSOSRWHandler *rh; struct list_head *el; struct pollfd *pfd, *pfds, pfds_local[64]; /* only check signals in the main thread */ if (!ts->recv_pipe && unlikely(os_pending_signals != 0)) { JSOSSignalHandler *sh; uint64_t mask; list_for_each(el, &ts->os_signal_handlers) { sh = list_entry(el, JSOSSignalHandler, link); mask = (uint64_t)1 << sh->sig_num; if (os_pending_signals & mask) { os_pending_signals &= ~mask; return call_handler(ctx, sh->func); } } } if (js_os_run_timers(rt, ctx, ts, &min_delay)) return -1; if (min_delay == 0) return 0; // expired timer if (min_delay < 0) if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->port_list)) return -1; /* no more events */ nfds = 0; list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); nfds += (!JS_IsNull(rh->rw_func[0]) || !JS_IsNull(rh->rw_func[1])); } #ifdef USE_WORKER list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); nfds += !JS_IsNull(port->on_message_func); } #endif // USE_WORKER pfd = pfds = pfds_local; if (nfds > (int)countof(pfds_local)) { pfd = pfds = js_malloc(ctx, nfds * sizeof(*pfd)); if (!pfd) return -1; } list_for_each(el, &ts->os_rw_handlers) { rh = list_entry(el, JSOSRWHandler, link); r = POLLIN * !JS_IsNull(rh->rw_func[0]); w = POLLOUT * !JS_IsNull(rh->rw_func[1]); if (r || w) *pfd++ = (struct pollfd){rh->fd, r|w, 0}; } #ifdef USE_WORKER list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; *pfd++ = (struct pollfd){ps->waker.read_fd, POLLIN, 0}; } } #endif // USE_WORKER // FIXME(bnoordhuis) the loop below is quadratic in theory but // linear-ish in practice because we bail out on the first hit, // i.e., it's probably good enough for now ret = 0; nfds = poll(pfds, nfds, min_delay); for (pfd = pfds; nfds-- > 0; pfd++) { rh = find_rh(ts, pfd->fd); if (rh) { r = (POLLERR|POLLHUP|POLLNVAL|POLLIN) * !JS_IsNull(rh->rw_func[0]); w = (POLLERR|POLLHUP|POLLNVAL|POLLOUT) * !JS_IsNull(rh->rw_func[1]); if (r & pfd->revents) { ret = call_handler(ctx, rh->rw_func[0]); goto done; /* must stop because the list may have been modified */ } if (w & pfd->revents) { ret = call_handler(ctx, rh->rw_func[1]); goto done; /* must stop because the list may have been modified */ } } else { #ifdef USE_WORKER list_for_each(el, &ts->port_list) { JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link); if (!JS_IsNull(port->on_message_func)) { JSWorkerMessagePipe *ps = port->recv_pipe; if (pfd->fd == ps->waker.read_fd) { if (handle_posted_message(rt, ctx, port)) goto done; } } } #endif // USE_WORKER } } done: if (pfds != pfds_local) js_free(ctx, pfds); return ret; } #endif // defined(_WIN32) static JSValue make_obj_error(JSContext *ctx, JSValue obj, int err) { JSValue arr; if (JS_IsException(obj)) return obj; arr = JS_NewArray(ctx); if (JS_IsException(arr)) return JS_EXCEPTION; JS_DefinePropertyValueUint32(ctx, arr, 0, obj, JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err), JS_PROP_C_W_E); return arr; } static JSValue make_string_error(JSContext *ctx, const char *buf, int err) { return make_obj_error(ctx, JS_NewString(ctx, buf), err); } /* return [cwd, errorcode] */ static JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { char buf[JS__PATH_MAX]; int err; if (!getcwd(buf, sizeof(buf))) { buf[0] = '\0'; err = errno; } else { err = 0; } return make_string_error(ctx, buf, err); } static JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *target; int err; target = JS_ToCString(ctx, argv[0]); if (!target) return JS_EXCEPTION; err = js_get_errno(chdir(target)); JS_FreeCString(ctx, target); return JS_NewInt32(ctx, err); } static JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int mode, ret; const char *path; if (argc >= 2) { if (JS_ToInt32(ctx, &mode, argv[1])) return JS_EXCEPTION; } else { mode = 0777; } path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; #if defined(_WIN32) (void)mode; ret = js_get_errno(mkdir(path)); #else ret = js_get_errno(mkdir(path, mode)); #endif JS_FreeCString(ctx, path); return JS_NewInt32(ctx, ret); } /* return [array, errorcode] */ static JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { #ifdef _WIN32 const char *path; JSValue obj; int err; uint32_t len; HANDLE h; WIN32_FIND_DATAA d; char s[1024]; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; obj = JS_NewArray(ctx); if (JS_IsException(obj)) { JS_FreeCString(ctx, path); return JS_EXCEPTION; } snprintf(s, sizeof(s), "%s/*", path); JS_FreeCString(ctx, path); err = 0; h = FindFirstFileA(s, &d); if (h == INVALID_HANDLE_VALUE) err = GetLastError(); if (err) goto done; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewString(ctx, "."), JS_PROP_C_W_E); for (len = 1; FindNextFileA(h, &d); len++) { JS_DefinePropertyValueUint32(ctx, obj, len, JS_NewString(ctx, d.cFileName), JS_PROP_C_W_E); } FindClose(h); done: return make_obj_error(ctx, obj, err); #else const char *path; DIR *f; struct dirent *d; JSValue obj; int err; uint32_t len; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; obj = JS_NewArray(ctx); if (JS_IsException(obj)) { JS_FreeCString(ctx, path); return JS_EXCEPTION; } f = opendir(path); if (!f) err = errno; else err = 0; JS_FreeCString(ctx, path); if (!f) goto done; len = 0; for(;;) { errno = 0; d = readdir(f); if (!d) { err = errno; break; } JS_DefinePropertyValueUint32(ctx, obj, len++, JS_NewString(ctx, d->d_name), JS_PROP_C_W_E); } closedir(f); done: return make_obj_error(ctx, obj, err); #endif } #if !defined(_WIN32) static int64_t timespec_to_ms(const struct timespec *tv) { return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000); } #endif /* return [obj, errcode] */ static JSValue js_os_stat(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int is_lstat) { const char *path; int err, res; struct stat st; JSValue obj; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; #if defined(_WIN32) res = stat(path, &st); #else if (is_lstat) res = lstat(path, &st); else res = stat(path, &st); #endif err = (res < 0) ? errno : 0; JS_FreeCString(ctx, path); if (res < 0) { obj = JS_NULL; } else { obj = JS_NewObject(ctx); if (JS_IsException(obj)) return JS_EXCEPTION; JS_DefinePropertyValueStr(ctx, obj, "dev", JS_NewInt64(ctx, st.st_dev), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ino", JS_NewInt64(ctx, st.st_ino), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mode", JS_NewInt32(ctx, st.st_mode), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "nlink", JS_NewInt64(ctx, st.st_nlink), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "uid", JS_NewInt64(ctx, st.st_uid), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "gid", JS_NewInt64(ctx, st.st_gid), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "rdev", JS_NewInt64(ctx, st.st_rdev), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "size", JS_NewInt64(ctx, st.st_size), JS_PROP_C_W_E); #if !defined(_WIN32) JS_DefinePropertyValueStr(ctx, obj, "blocks", JS_NewInt64(ctx, st.st_blocks), JS_PROP_C_W_E); #endif #if defined(_WIN32) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, (int64_t)st.st_atime * 1000), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000), JS_PROP_C_W_E); #elif defined(__APPLE__) JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)), JS_PROP_C_W_E); #else JS_DefinePropertyValueStr(ctx, obj, "atime", JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "mtime", JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)), JS_PROP_C_W_E); JS_DefinePropertyValueStr(ctx, obj, "ctime", JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)), JS_PROP_C_W_E); #endif } return make_obj_error(ctx, obj, err); } #if !defined(_WIN32) static void ms_to_timeval(struct timeval *tv, uint64_t v) { tv->tv_sec = v / 1000; tv->tv_usec = (v % 1000) * 1000; } #endif static JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; int64_t atime, mtime; int ret; if (JS_ToInt64(ctx, &atime, argv[1])) return JS_EXCEPTION; if (JS_ToInt64(ctx, &mtime, argv[2])) return JS_EXCEPTION; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; #if defined(_WIN32) { struct _utimbuf times; times.actime = atime / 1000; times.modtime = mtime / 1000; ret = js_get_errno(_utime(path, ×)); } #else { struct timeval times[2]; ms_to_timeval(×[0], atime); ms_to_timeval(×[1], mtime); ret = js_get_errno(utimes(path, times)); } #endif JS_FreeCString(ctx, path); return JS_NewInt32(ctx, ret); } /* sleep(delay_ms) */ static JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int64_t delay; int ret; if (JS_ToInt64(ctx, &delay, argv[0])) return JS_EXCEPTION; if (delay < 0) delay = 0; #if defined(_WIN32) { if (delay > INT32_MAX) delay = INT32_MAX; Sleep(delay); ret = 0; } #else { struct timespec ts; ts.tv_sec = delay / 1000; ts.tv_nsec = (delay % 1000) * 1000000; ret = js_get_errno(nanosleep(&ts, NULL)); } #endif return JS_NewInt32(ctx, ret); } #if defined(_WIN32) static char *realpath(const char *path, char *buf) { if (!_fullpath(buf, path, JS__PATH_MAX)) { errno = ENOENT; return NULL; } else { return buf; } } #endif #if !defined(__wasi__) /* return [path, errorcode] */ static JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; char buf[JS__PATH_MAX], *res; int err; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; res = realpath(path, buf); JS_FreeCString(ctx, path); if (!res) { buf[0] = '\0'; err = errno; } else { err = 0; } return make_string_error(ctx, buf, err); } #endif #if !defined(_WIN32) && !defined(__wasi__) static JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *target, *linkpath; int err; target = JS_ToCString(ctx, argv[0]); if (!target) return JS_EXCEPTION; linkpath = JS_ToCString(ctx, argv[1]); if (!linkpath) { JS_FreeCString(ctx, target); return JS_EXCEPTION; } err = js_get_errno(symlink(target, linkpath)); JS_FreeCString(ctx, target); JS_FreeCString(ctx, linkpath); return JS_NewInt32(ctx, err); } /* return [path, errorcode] */ static JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { const char *path; char buf[JS__PATH_MAX]; int err; ssize_t res; path = JS_ToCString(ctx, argv[0]); if (!path) return JS_EXCEPTION; res = readlink(path, buf, sizeof(buf) - 1); if (res < 0) { buf[0] = '\0'; err = errno; } else { buf[res] = '\0'; err = 0; } JS_FreeCString(ctx, path); return make_string_error(ctx, buf, err); } static char **build_envp(JSContext *ctx, JSValue obj) { uint32_t len, i; JSPropertyEnum *tab; char **envp, *pair; const char *key, *str; JSValue val; size_t key_len, str_len; if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0) return NULL; envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1)); if (!envp) goto fail; for(i = 0; i < len; i++) { val = JS_GetProperty(ctx, obj, tab[i].atom); if (JS_IsException(val)) goto fail; str = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!str) goto fail; key = JS_AtomToCString(ctx, tab[i].atom); if (!key) { JS_FreeCString(ctx, str); goto fail; } key_len = strlen(key); str_len = strlen(str); pair = js_malloc(ctx, key_len + str_len + 2); if (!pair) { JS_FreeCString(ctx, key); JS_FreeCString(ctx, str); goto fail; } memcpy(pair, key, key_len); pair[key_len] = '='; memcpy(pair + key_len + 1, str, str_len); pair[key_len + 1 + str_len] = '\0'; envp[i] = pair; JS_FreeCString(ctx, key); JS_FreeCString(ctx, str); } done: for(i = 0; i < len; i++) JS_FreeAtom(ctx, tab[i].atom); js_free(ctx, tab); return envp; fail: if (envp) { for(i = 0; i < len; i++) js_free(ctx, envp[i]); js_free(ctx, envp); envp = NULL; } goto done; } /* execvpe is not available on non GNU systems */ static int my_execvpe(const char *filename, char **argv, char **envp) { char *path, *p, *p_next, *p1; char buf[JS__PATH_MAX]; size_t filename_len, path_len; bool eacces_error; filename_len = strlen(filename); if (filename_len == 0) { errno = ENOENT; return -1; } if (strchr(filename, '/')) return execve(filename, argv, envp); path = getenv("PATH"); if (!path) path = (char *)"/bin:/usr/bin"; eacces_error = false; p = path; for(p = path; p != NULL; p = p_next) { p1 = strchr(p, ':'); if (!p1) { p_next = NULL; path_len = strlen(p); } else { p_next = p1 + 1; path_len = p1 - p; } /* path too long */ if ((path_len + 1 + filename_len + 1) > JS__PATH_MAX) continue; memcpy(buf, p, path_len); buf[path_len] = '/'; memcpy(buf + path_len + 1, filename, filename_len); buf[path_len + 1 + filename_len] = '\0'; execve(buf, argv, envp); switch(errno) { case EACCES: eacces_error = true; break; case ENOENT: case ENOTDIR: break; default: return -1; } } if (eacces_error) errno = EACCES; return -1; } static void (*js_os_exec_closefrom)(int); #if !defined(EMSCRIPTEN) && !defined(__wasi__) static js_once_t js_os_exec_once = JS_ONCE_INIT; static void js_os_exec_once_init(void) { *(void **) (&js_os_exec_closefrom) = dlsym(RTLD_DEFAULT, "closefrom"); } #endif /* exec(args[, options]) -> exitcode */ static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSValueConst options, args = argv[0]; JSValue val, ret_val; const char **exec_argv, *file = NULL, *str, *cwd = NULL; char **envp = environ; uint32_t exec_argc, i; int ret, pid, status; bool block_flag = true, use_path = true; static const char *std_name[3] = { "stdin", "stdout", "stderr" }; int std_fds[3]; uint32_t uid = -1, gid = -1; int ngroups = -1; gid_t groups[64]; val = JS_GetPropertyStr(ctx, args, "length"); if (JS_IsException(val)) return JS_EXCEPTION; ret = JS_ToUint32(ctx, &exec_argc, val); JS_FreeValue(ctx, val); if (ret) return JS_EXCEPTION; /* arbitrary limit to avoid overflow */ if (exec_argc < 1 || exec_argc > 65535) { return JS_ThrowTypeError(ctx, "invalid number of arguments"); } exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1)); if (!exec_argv) return JS_EXCEPTION; for(i = 0; i < exec_argc; i++) { val = JS_GetPropertyUint32(ctx, args, i); if (JS_IsException(val)) goto exception; str = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!str) goto exception; exec_argv[i] = str; } exec_argv[exec_argc] = NULL; for(i = 0; i < 3; i++) std_fds[i] = i; /* get the options, if any */ if (argc >= 2) { options = argv[1]; if (get_bool_option(ctx, &block_flag, options, "block")) goto exception; if (get_bool_option(ctx, &use_path, options, "usePath")) goto exception; val = JS_GetPropertyStr(ctx, options, "file"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { file = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!file) goto exception; } val = JS_GetPropertyStr(ctx, options, "cwd"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { cwd = JS_ToCString(ctx, val); JS_FreeValue(ctx, val); if (!cwd) goto exception; } /* stdin/stdout/stderr handles */ for(i = 0; i < 3; i++) { val = JS_GetPropertyStr(ctx, options, std_name[i]); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { int fd; ret = JS_ToInt32(ctx, &fd, val); JS_FreeValue(ctx, val); if (ret) goto exception; std_fds[i] = fd; } } val = JS_GetPropertyStr(ctx, options, "env"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { envp = build_envp(ctx, val); JS_FreeValue(ctx, val); if (!envp) goto exception; } val = JS_GetPropertyStr(ctx, options, "uid"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { ret = JS_ToUint32(ctx, &uid, val); JS_FreeValue(ctx, val); if (ret) goto exception; } val = JS_GetPropertyStr(ctx, options, "gid"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { ret = JS_ToUint32(ctx, &gid, val); JS_FreeValue(ctx, val); if (ret) goto exception; } val = JS_GetPropertyStr(ctx, options, "groups"); if (JS_IsException(val)) goto exception; if (!JS_IsUndefined(val)) { int64_t idx, len; JSValue prop; uint32_t id; ngroups = 0; if (JS_GetLength(ctx, val, &len)) { JS_FreeValue(ctx, val); goto exception; } for (idx = 0; idx < len; idx++) { prop = JS_GetPropertyInt64(ctx, val, idx); if (JS_IsException(prop)) break; if (JS_IsUndefined(prop)) continue; ret = JS_ToUint32(ctx, &id, prop); JS_FreeValue(ctx, prop); if (ret) break; if (ngroups == countof(groups)) { JS_ThrowRangeError(ctx, "too many groups"); break; } groups[ngroups++] = id; } JS_FreeValue(ctx, val); if (idx < len) goto exception; } } #if !defined(EMSCRIPTEN) && !defined(__wasi__) // should happen pre-fork because it calls dlsym() // and that's not an async-signal-safe function js_once(&js_os_exec_once, js_os_exec_once_init); #endif pid = fork(); if (pid < 0) { JS_ThrowTypeError(ctx, "fork error"); goto exception; } if (pid == 0) { /* child */ /* remap the stdin/stdout/stderr handles if necessary */ for(i = 0; i < 3; i++) { if (std_fds[i] != i) { if (dup2(std_fds[i], i) < 0) _exit(127); } } if (js_os_exec_closefrom) { js_os_exec_closefrom(3); } else { int fd_max = sysconf(_SC_OPEN_MAX); for(i = 3; i < fd_max; i++) close(i); } if (cwd) { if (chdir(cwd) < 0) _exit(127); } if (ngroups != -1) { if (setgroups(ngroups, groups) < 0) _exit(127); } if (uid != -1) { if (setuid(uid) < 0) _exit(127); } if (gid != -1) { if (setgid(gid) < 0) _exit(127); } if (!file) file = exec_argv[0]; if (use_path) ret = my_execvpe(file, (char **)exec_argv, envp); else ret = execve(file, (char **)exec_argv, envp); _exit(127); } /* parent */ if (block_flag) { for(;;) { ret = waitpid(pid, &status, 0); if (ret == pid) { if (WIFEXITED(status)) { ret = WEXITSTATUS(status); break; } else if (WIFSIGNALED(status)) { ret = -WTERMSIG(status); break; } } } } else { ret = pid; } ret_val = JS_NewInt32(ctx, ret); done: JS_FreeCString(ctx, file); JS_FreeCString(ctx, cwd); for(i = 0; i < exec_argc; i++) JS_FreeCString(ctx, exec_argv[i]); js_free(ctx, exec_argv); if (envp != environ) { char **p; p = envp; while (*p != NULL) { js_free(ctx, *p); p++; } js_free(ctx, envp); } return ret_val; exception: ret_val = JS_EXCEPTION; goto done; } /* getpid() -> pid */ static JSValue js_os_getpid(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { return JS_NewInt32(ctx, getpid()); } /* waitpid(pid, block) -> [pid, status] */ static JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pid, status, options, ret; JSValue obj; if (JS_ToInt32(ctx, &pid, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &options, argv[1])) return JS_EXCEPTION; ret = waitpid(pid, &status, options); if (ret < 0) { ret = -errno; status = 0; } obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status), JS_PROP_C_W_E); return obj; } /* pipe() -> [read_fd, write_fd] or null if error */ static JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pipe_fds[2], ret; JSValue obj; ret = pipe(pipe_fds); if (ret < 0) return JS_NULL; obj = JS_NewArray(ctx); if (JS_IsException(obj)) return obj; JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]), JS_PROP_C_W_E); JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]), JS_PROP_C_W_E); return obj; } /* kill(pid, sig) */ static JSValue js_os_kill(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int pid, sig, ret; if (JS_ToInt32(ctx, &pid, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &sig, argv[1])) return JS_EXCEPTION; ret = js_get_errno(kill(pid, sig)); return JS_NewInt32(ctx, ret); } /* dup(fd) */ static JSValue js_os_dup(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, ret; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; ret = js_get_errno(dup(fd)); return JS_NewInt32(ctx, ret); } /* dup2(fd) */ static JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int fd, fd2, ret; if (JS_ToInt32(ctx, &fd, argv[0])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &fd2, argv[1])) return JS_EXCEPTION; ret = js_get_errno(dup2(fd, fd2)); return JS_NewInt32(ctx, ret); } #endif /* !_WIN32 */ #ifdef USE_WORKER /* Worker */ typedef struct { JSWorkerMessagePipe *recv_pipe; JSWorkerMessagePipe *send_pipe; JSWorkerMessageHandler *msg_handler; } JSWorkerData; typedef struct { char *filename; /* module filename */ char *basename; /* module base name */ JSWorkerMessagePipe *recv_pipe, *send_pipe; } WorkerFuncArgs; typedef struct { int ref_count; uint64_t buf[]; } JSSABHeader; static JSContext *(*js_worker_new_context_func)(JSRuntime *rt); static int atomic_add_int(int *ptr, int v) { return atomic_fetch_add((_Atomic uint32_t*)ptr, v) + v; } /* shared array buffer allocator */ static void *js_sab_alloc(void *opaque, size_t size) { JSSABHeader *sab; sab = malloc(sizeof(JSSABHeader) + size); if (!sab) return NULL; sab->ref_count = 1; return sab->buf; } static void js_sab_free(void *opaque, void *ptr) { JSSABHeader *sab; int ref_count; sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader)); ref_count = atomic_add_int(&sab->ref_count, -1); assert(ref_count >= 0); if (ref_count == 0) { free(sab); } } static void js_sab_dup(void *opaque, void *ptr) { JSSABHeader *sab; sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader)); atomic_add_int(&sab->ref_count, 1); } static JSWorkerMessagePipe *js_new_message_pipe(void) { JSWorkerMessagePipe *ps; ps = malloc(sizeof(*ps)); if (!ps) return NULL; if (js_waker_init(&ps->waker)) { free(ps); return NULL; } ps->ref_count = 1; init_list_head(&ps->msg_queue); js_mutex_init(&ps->mutex); return ps; } static JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps) { atomic_add_int(&ps->ref_count, 1); return ps; } static void js_free_message(JSWorkerMessage *msg) { size_t i; /* free the SAB */ for(i = 0; i < msg->sab_tab_len; i++) { js_sab_free(NULL, msg->sab_tab[i]); } free(msg->sab_tab); free(msg->data); free(msg); } static void js_free_message_pipe(JSWorkerMessagePipe *ps) { struct list_head *el, *el1; JSWorkerMessage *msg; int ref_count; if (!ps) return; ref_count = atomic_add_int(&ps->ref_count, -1); assert(ref_count >= 0); if (ref_count == 0) { list_for_each_safe(el, el1, &ps->msg_queue) { msg = list_entry(el, JSWorkerMessage, link); js_free_message(msg); } js_mutex_destroy(&ps->mutex); js_waker_close(&ps->waker); free(ps); } } static void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port) { if (port) { js_free_message_pipe(port->recv_pipe); JS_FreeValueRT(rt, port->on_message_func); list_del(&port->link); js_free_rt(rt, port); } } static void js_worker_finalizer(JSRuntime *rt, JSValueConst val) { JSThreadState *ts = js_get_thread_state(rt); JSWorkerData *worker = JS_GetOpaque(val, ts->worker_class_id); if (worker) { js_free_message_pipe(worker->recv_pipe); js_free_message_pipe(worker->send_pipe); js_free_port(rt, worker->msg_handler); js_free_rt(rt, worker); } } static JSClassDef js_worker_class = { "Worker", .finalizer = js_worker_finalizer, }; static void worker_func(void *opaque) { WorkerFuncArgs *args = opaque; JSRuntime *rt; JSThreadState *ts; JSContext *ctx; JSValue val; rt = JS_NewRuntime(); if (rt == NULL) { fprintf(stderr, "JS_NewRuntime failure"); exit(1); } js_std_init_handlers(rt); JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL); /* set the pipe to communicate with the parent */ ts = js_get_thread_state(rt); ts->recv_pipe = args->recv_pipe; ts->send_pipe = args->send_pipe; /* function pointer to avoid linking the whole JS_NewContext() if not needed */ ctx = js_worker_new_context_func(rt); if (ctx == NULL) { fprintf(stderr, "JS_NewContext failure"); } JS_SetCanBlock(rt, true); js_std_add_helpers(ctx, -1, NULL); val = JS_LoadModule(ctx, args->basename, args->filename); free(args->filename); free(args->basename); free(args); val = js_std_await(ctx, val); if (JS_IsException(val)) js_std_dump_error(ctx); JS_FreeValue(ctx, val); js_std_loop(ctx); js_std_free_handlers(rt); JS_FreeContext(ctx); JS_FreeRuntime(rt); } static JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target, JSWorkerMessagePipe *recv_pipe, JSWorkerMessagePipe *send_pipe) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSValue obj = JS_UNDEFINED, proto; JSWorkerData *s; /* create the object */ if (JS_IsUndefined(new_target)) { proto = JS_GetClassProto(ctx, ts->worker_class_id); } else { proto = JS_GetPropertyStr(ctx, new_target, "prototype"); if (JS_IsException(proto)) goto fail; } obj = JS_NewObjectProtoClass(ctx, proto, ts->worker_class_id); JS_FreeValue(ctx, proto); if (JS_IsException(obj)) goto fail; s = js_mallocz(ctx, sizeof(*s)); if (!s) goto fail; s->recv_pipe = js_dup_message_pipe(recv_pipe); s->send_pipe = js_dup_message_pipe(send_pipe); JS_SetOpaque(obj, s); return obj; fail: JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); WorkerFuncArgs *args = NULL; js_thread_t thr; JSValue obj = JS_UNDEFINED; int ret; const char *filename = NULL, *basename; JSAtom basename_atom; /* XXX: in order to avoid problems with resource liberation, we don't support creating workers inside workers */ if (!is_main_thread(rt)) return JS_ThrowTypeError(ctx, "cannot create a worker inside a worker"); /* base name, assuming the calling function is a normal JS function */ basename_atom = JS_GetScriptOrModuleName(ctx, 1); if (basename_atom == JS_ATOM_NULL) { return JS_ThrowTypeError(ctx, "could not determine calling script or module name"); } basename = JS_AtomToCString(ctx, basename_atom); JS_FreeAtom(ctx, basename_atom); if (!basename) goto fail; /* module name */ filename = JS_ToCString(ctx, argv[0]); if (!filename) goto fail; args = malloc(sizeof(*args)); if (!args) goto oom_fail; memset(args, 0, sizeof(*args)); args->filename = strdup(filename); args->basename = strdup(basename); /* ports */ args->recv_pipe = js_new_message_pipe(); if (!args->recv_pipe) goto oom_fail; args->send_pipe = js_new_message_pipe(); if (!args->send_pipe) goto oom_fail; obj = js_worker_ctor_internal(ctx, new_target, args->send_pipe, args->recv_pipe); if (JS_IsException(obj)) goto fail; ret = js_thread_create(&thr, worker_func, args, JS_THREAD_CREATE_DETACHED); if (ret != 0) { JS_ThrowTypeError(ctx, "could not create worker"); goto fail; } JS_FreeCString(ctx, basename); JS_FreeCString(ctx, filename); return obj; oom_fail: JS_ThrowOutOfMemory(ctx); fail: JS_FreeCString(ctx, basename); JS_FreeCString(ctx, filename); if (args) { free(args->filename); free(args->basename); js_free_message_pipe(args->recv_pipe); js_free_message_pipe(args->send_pipe); free(args); } JS_FreeValue(ctx, obj); return JS_EXCEPTION; } static JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, ts->worker_class_id); JSWorkerMessagePipe *ps; size_t data_len, i; uint8_t *data; JSWorkerMessage *msg; JSSABTab sab_tab; if (!worker) return JS_EXCEPTION; data = JS_WriteObject2(ctx, &data_len, argv[0], JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE, &sab_tab); if (!data) return JS_EXCEPTION; msg = malloc(sizeof(*msg)); if (!msg) goto fail; msg->data = NULL; msg->sab_tab = NULL; /* must reallocate because the allocator may be different */ msg->data = malloc(data_len); if (!msg->data) goto fail; memcpy(msg->data, data, data_len); msg->data_len = data_len; if (sab_tab.len > 0) { msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab.len); if (!msg->sab_tab) goto fail; memcpy(msg->sab_tab, sab_tab.tab, sizeof(msg->sab_tab[0]) * sab_tab.len); } msg->sab_tab_len = sab_tab.len; js_free(ctx, data); js_free(ctx, sab_tab.tab); /* increment the SAB reference counts */ for(i = 0; i < msg->sab_tab_len; i++) { js_sab_dup(NULL, msg->sab_tab[i]); } ps = worker->send_pipe; js_mutex_lock(&ps->mutex); /* indicate that data is present */ if (list_empty(&ps->msg_queue)) js_waker_signal(&ps->waker); list_add_tail(&msg->link, &ps->msg_queue); js_mutex_unlock(&ps->mutex); return JS_UNDEFINED; fail: if (msg) { free(msg->data); free(msg->sab_tab); free(msg); } js_free(ctx, data); js_free(ctx, sab_tab.tab); return JS_EXCEPTION; } static JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val, JSValueConst func) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, ts->worker_class_id); JSWorkerMessageHandler *port; if (!worker) return JS_EXCEPTION; port = worker->msg_handler; if (JS_IsNull(func)) { if (port) { js_free_port(rt, port); worker->msg_handler = NULL; } } else { if (!JS_IsFunction(ctx, func)) return JS_ThrowTypeError(ctx, "not a function"); if (!port) { port = js_mallocz(ctx, sizeof(*port)); if (!port) return JS_EXCEPTION; port->recv_pipe = js_dup_message_pipe(worker->recv_pipe); port->on_message_func = JS_NULL; list_add_tail(&port->link, &ts->port_list); worker->msg_handler = port; } JS_FreeValue(ctx, port->on_message_func); port->on_message_func = JS_DupValue(ctx, func); } return JS_UNDEFINED; } static JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, ts->worker_class_id); JSWorkerMessageHandler *port; if (!worker) return JS_EXCEPTION; port = worker->msg_handler; if (port) { return JS_DupValue(ctx, port->on_message_func); } else { return JS_NULL; } } static const JSCFunctionListEntry js_worker_proto_funcs[] = { JS_CFUNC_DEF("postMessage", 1, js_worker_postMessage ), JS_CGETSET_DEF("onmessage", js_worker_get_onmessage, js_worker_set_onmessage ), }; #endif /* USE_WORKER */ void js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt)) { #ifdef USE_WORKER js_worker_new_context_func = func; #endif } #if defined(_WIN32) #define OS_PLATFORM "win32" #elif defined(__APPLE__) #define OS_PLATFORM "darwin" #elif defined(EMSCRIPTEN) #define OS_PLATFORM "js" #elif defined(__CYGWIN__) #define OS_PLATFORM "cygwin" #elif defined(__linux__) #define OS_PLATFORM "linux" #elif defined(__OpenBSD__) #define OS_PLATFORM "openbsd" #elif defined(__NetBSD__) #define OS_PLATFORM "netbsd" #elif defined(__FreeBSD__) #define OS_PLATFORM "freebsd" #elif defined(__wasi__) #define OS_PLATFORM "wasi" #elif defined(__GNU__) #define OS_PLATFORM "hurd" #else #define OS_PLATFORM "unknown" #endif #define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE ) static const JSCFunctionListEntry js_os_funcs[] = { JS_CFUNC_DEF("open", 2, js_os_open ), OS_FLAG(O_RDONLY), OS_FLAG(O_WRONLY), OS_FLAG(O_RDWR), OS_FLAG(O_APPEND), OS_FLAG(O_CREAT), OS_FLAG(O_EXCL), OS_FLAG(O_TRUNC), #if defined(_WIN32) OS_FLAG(O_BINARY), OS_FLAG(O_TEXT), #endif JS_CFUNC_DEF("close", 1, js_os_close ), JS_CFUNC_DEF("seek", 3, js_os_seek ), JS_CFUNC_MAGIC_DEF("read", 4, js_os_read_write, 0 ), JS_CFUNC_MAGIC_DEF("write", 4, js_os_read_write, 1 ), JS_CFUNC_DEF("isatty", 1, js_os_isatty ), #if !defined(__wasi__) JS_CFUNC_DEF("ttyGetWinSize", 1, js_os_ttyGetWinSize ), JS_CFUNC_DEF("ttySetRaw", 1, js_os_ttySetRaw ), #endif JS_CFUNC_DEF("remove", 1, js_os_remove ), JS_CFUNC_DEF("rename", 2, js_os_rename ), JS_CFUNC_MAGIC_DEF("setReadHandler", 2, js_os_setReadHandler, 0 ), JS_CFUNC_MAGIC_DEF("setWriteHandler", 2, js_os_setReadHandler, 1 ), JS_CFUNC_DEF("signal", 2, js_os_signal ), OS_FLAG(SIGINT), OS_FLAG(SIGABRT), OS_FLAG(SIGFPE), OS_FLAG(SIGILL), OS_FLAG(SIGSEGV), OS_FLAG(SIGTERM), #if !defined(_WIN32) && !defined(__wasi__) OS_FLAG(SIGQUIT), OS_FLAG(SIGPIPE), OS_FLAG(SIGALRM), OS_FLAG(SIGUSR1), OS_FLAG(SIGUSR2), OS_FLAG(SIGCHLD), OS_FLAG(SIGCONT), OS_FLAG(SIGSTOP), OS_FLAG(SIGTSTP), OS_FLAG(SIGTTIN), OS_FLAG(SIGTTOU), JS_CFUNC_DEF("cputime", 0, js_os_cputime ), #endif JS_CFUNC_DEF("exePath", 0, js_os_exepath ), JS_CFUNC_DEF("now", 0, js_os_now ), JS_CFUNC_MAGIC_DEF("setTimeout", 2, js_os_setTimeout, 0 ), JS_CFUNC_MAGIC_DEF("setInterval", 2, js_os_setTimeout, 1 ), // per spec: both functions can cancel timeouts and intervals JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ), JS_CFUNC_DEF("clearInterval", 1, js_os_clearTimeout ), JS_CFUNC_DEF("sleepAsync", 1, js_os_sleepAsync ), JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ), JS_CFUNC_DEF("getcwd", 0, js_os_getcwd ), JS_CFUNC_DEF("chdir", 0, js_os_chdir ), JS_CFUNC_DEF("mkdir", 1, js_os_mkdir ), JS_CFUNC_DEF("readdir", 1, js_os_readdir ), /* st_mode constants */ OS_FLAG(S_IFMT), OS_FLAG(S_IFIFO), OS_FLAG(S_IFCHR), OS_FLAG(S_IFDIR), OS_FLAG(S_IFBLK), OS_FLAG(S_IFREG), #if !defined(_WIN32) OS_FLAG(S_IFSOCK), OS_FLAG(S_IFLNK), OS_FLAG(S_ISGID), OS_FLAG(S_ISUID), #endif JS_CFUNC_MAGIC_DEF("stat", 1, js_os_stat, 0 ), JS_CFUNC_DEF("utimes", 3, js_os_utimes ), JS_CFUNC_DEF("sleep", 1, js_os_sleep ), #if !defined(__wasi__) JS_CFUNC_DEF("realpath", 1, js_os_realpath ), #endif #if !defined(_WIN32) && !defined(__wasi__) JS_CFUNC_MAGIC_DEF("lstat", 1, js_os_stat, 1 ), JS_CFUNC_DEF("symlink", 2, js_os_symlink ), JS_CFUNC_DEF("readlink", 1, js_os_readlink ), JS_CFUNC_DEF("exec", 1, js_os_exec ), JS_CFUNC_DEF("getpid", 0, js_os_getpid ), JS_CFUNC_DEF("waitpid", 2, js_os_waitpid ), OS_FLAG(WNOHANG), JS_CFUNC_DEF("pipe", 0, js_os_pipe ), JS_CFUNC_DEF("kill", 2, js_os_kill ), JS_CFUNC_DEF("dup", 1, js_os_dup ), JS_CFUNC_DEF("dup2", 2, js_os_dup2 ), #endif }; static int js_os_init(JSContext *ctx, JSModuleDef *m) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); ts->can_js_os_poll = true; #ifdef USE_WORKER { JSValue proto, obj; /* Worker class */ JS_NewClassID(rt, &ts->worker_class_id); JS_NewClass(rt, ts->worker_class_id, &js_worker_class); proto = JS_NewObject(ctx); JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs)); obj = JS_NewCFunction2(ctx, js_worker_ctor, "Worker", 1, JS_CFUNC_constructor, 0); JS_SetConstructor(ctx, obj, proto); JS_SetClassProto(ctx, ts->worker_class_id, proto); /* set 'Worker.parent' if necessary */ if (ts->recv_pipe && ts->send_pipe) { JS_DefinePropertyValueStr(ctx, obj, "parent", js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe), JS_PROP_C_W_E); } JS_SetModuleExport(ctx, m, "Worker", obj); } #endif /* USE_WORKER */ return JS_SetModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs)); } JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_os_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs)); #ifdef USE_WORKER JS_AddModuleExport(ctx, m, "Worker"); #endif return m; } /**********************************************************/ static JSValue js_print(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { #ifdef _WIN32 HANDLE handle; DWORD mode; #endif const char *s; JSValueConst v; DynBuf b; int i; dbuf_init(&b); for(i = 0; i < argc; i++) { v = argv[i]; s = JS_ToCString(ctx, v); if (!s && JS_IsObject(v)) { JS_FreeValue(ctx, JS_GetException(ctx)); JSValue t = JS_ToObjectString(ctx, v); s = JS_ToCString(ctx, t); JS_FreeValue(ctx, t); } if (s) { dbuf_printf(&b, "%s%s", &" "[!i], s); JS_FreeCString(ctx, s); } else { dbuf_printf(&b, "%s", &" "[!i]); JS_FreeValue(ctx, JS_GetException(ctx)); } } dbuf_putc(&b, '\n'); #ifdef _WIN32 // use WriteConsoleA with CP_UTF8 for better Unicode handling vis-a-vis // the mangling that happens when going through msvcrt's stdio layer, // *except* when stdout is redirected to something that is not a console handle = (HANDLE)_get_osfhandle(/*STDOUT_FILENO*/1); // don't CloseHandle if (GetFileType(handle) != FILE_TYPE_CHAR) goto fallback; if (!GetConsoleMode(handle, &mode)) goto fallback; handle = GetStdHandle(STD_OUTPUT_HANDLE); if (handle == INVALID_HANDLE_VALUE) goto fallback; mode = GetConsoleOutputCP(); SetConsoleOutputCP(CP_UTF8); WriteConsoleA(handle, b.buf, b.size, NULL, NULL); SetConsoleOutputCP(mode); FlushFileBuffers(handle); goto done; fallback: #endif fwrite(b.buf, 1, b.size, stdout); fflush(stdout); goto done; // avoid unused label warning done: dbuf_free(&b); return JS_UNDEFINED; } void js_std_add_helpers(JSContext *ctx, int argc, char **argv) { JSValue global_obj, console, args; int i; /* XXX: should these global definitions be enumerable? */ global_obj = JS_GetGlobalObject(ctx); console = JS_NewObject(ctx); JS_SetPropertyStr(ctx, console, "log", JS_NewCFunction(ctx, js_print, "log", 1)); JS_SetPropertyStr(ctx, global_obj, "console", console); /* same methods as the mozilla JS shell */ if (argc >= 0) { args = JS_NewArray(ctx); for(i = 0; i < argc; i++) { JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i])); } JS_SetPropertyStr(ctx, global_obj, "scriptArgs", args); } JS_SetPropertyStr(ctx, global_obj, "print", JS_NewCFunction(ctx, js_print, "print", 1)); JS_FreeValue(ctx, global_obj); } static void js_std_finalize(JSRuntime *rt, void *arg) { JSThreadState *ts = arg; js_set_thread_state(rt, NULL); js_free_rt(rt, ts); } void js_std_init_handlers(JSRuntime *rt) { JSThreadState *ts; ts = js_mallocz_rt(rt, sizeof(*ts)); if (!ts) { fprintf(stderr, "Could not allocate memory for the worker"); exit(1); } init_list_head(&ts->os_rw_handlers); init_list_head(&ts->os_signal_handlers); init_list_head(&ts->os_timers); init_list_head(&ts->port_list); init_list_head(&ts->rejected_promise_list); ts->next_timer_id = 1; js_set_thread_state(rt, ts); JS_AddRuntimeFinalizer(rt, js_std_finalize, ts); #ifdef USE_WORKER /* set the SharedArrayBuffer memory handlers */ { JSSharedArrayBufferFunctions sf; memset(&sf, 0, sizeof(sf)); sf.sab_alloc = js_sab_alloc; sf.sab_free = js_sab_free; sf.sab_dup = js_sab_dup; JS_SetSharedArrayBufferFunctions(rt, &sf); } #endif } static void free_rp(JSRuntime *rt, JSRejectedPromiseEntry *rp) { list_del(&rp->link); JS_FreeValueRT(rt, rp->promise); JS_FreeValueRT(rt, rp->reason); js_free_rt(rt, rp); } void js_std_free_handlers(JSRuntime *rt) { JSThreadState *ts = js_get_thread_state(rt); struct list_head *el, *el1; list_for_each_safe(el, el1, &ts->os_rw_handlers) { JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link); free_rw_handler(rt, rh); } list_for_each_safe(el, el1, &ts->os_signal_handlers) { JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link); free_sh(rt, sh); } list_for_each_safe(el, el1, &ts->os_timers) { JSOSTimer *th = list_entry(el, JSOSTimer, link); free_timer(rt, th); } list_for_each_safe(el, el1, &ts->rejected_promise_list) { JSRejectedPromiseEntry *rp = list_entry(el, JSRejectedPromiseEntry, link); free_rp(rt, rp); } #ifdef USE_WORKER /* XXX: free port_list ? */ js_free_message_pipe(ts->recv_pipe); js_free_message_pipe(ts->send_pipe); #endif } static void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val) { const char *str; str = JS_ToCString(ctx, val); if (str) { fprintf(f, "%s\n", str); JS_FreeCString(ctx, str); } else { fprintf(f, "[exception]\n"); } } static void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val) { JSValue val; bool is_error; is_error = JS_IsError(exception_val); js_dump_obj(ctx, stderr, exception_val); if (is_error) { val = JS_GetPropertyStr(ctx, exception_val, "stack"); } else { js_std_cmd(/*ErrorBackTrace*/2, ctx, &val); } if (!JS_IsUndefined(val)) { js_dump_obj(ctx, stderr, val); JS_FreeValue(ctx, val); } } void js_std_dump_error(JSContext *ctx) { JSValue exception_val; exception_val = JS_GetException(ctx); js_std_dump_error1(ctx, exception_val); JS_FreeValue(ctx, exception_val); } static JSRejectedPromiseEntry *find_rejected_promise(JSContext *ctx, JSThreadState *ts, JSValueConst promise) { struct list_head *el; list_for_each(el, &ts->rejected_promise_list) { JSRejectedPromiseEntry *rp = list_entry(el, JSRejectedPromiseEntry, link); if (JS_IsSameValue(ctx, rp->promise, promise)) return rp; } return NULL; } void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, bool is_handled, void *opaque) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSRejectedPromiseEntry *rp = find_rejected_promise(ctx, ts, promise); if (is_handled) { /* the rejection is handled, so the entry can be removed if present */ if (rp) free_rp(rt, rp); } else { /* add a new entry if needed */ if (!rp) { rp = js_malloc_rt(rt, sizeof(*rp)); if (rp) { rp->promise = JS_DupValue(ctx, promise); rp->reason = JS_DupValue(ctx, reason); list_add_tail(&rp->link, &ts->rejected_promise_list); } } } } /* check if there are pending promise rejections. It must be done asynchrously in case a rejected promise is handled later. Currently we do it once the application is about to sleep. It could be done more often if needed. */ static void js_std_promise_rejection_check(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); struct list_head *el; if (unlikely(!list_empty(&ts->rejected_promise_list))) { list_for_each(el, &ts->rejected_promise_list) { JSRejectedPromiseEntry *rp = list_entry(el, JSRejectedPromiseEntry, link); fprintf(stderr, "Possibly unhandled promise rejection: "); js_std_dump_error1(ctx, rp->reason); fflush(stderr); } exit(1); } } /* main loop which calls the user JS callbacks */ int js_std_loop(JSContext *ctx) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSContext *ctx1; int err; for(;;) { /* execute the pending jobs */ for(;;) { err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (err <= 0) { if (err < 0) goto done; break; } } js_std_promise_rejection_check(ctx); if (!ts->can_js_os_poll || js_os_poll(ctx)) break; } done: return JS_HasException(ctx); } /* Wait for a promise and execute pending jobs while waiting for it. Return the promise result or JS_EXCEPTION in case of promise rejection. */ JSValue js_std_await(JSContext *ctx, JSValue obj) { JSRuntime *rt = JS_GetRuntime(ctx); JSThreadState *ts = js_get_thread_state(rt); JSValue ret; int state; for(;;) { state = JS_PromiseState(ctx, obj); if (state == JS_PROMISE_FULFILLED) { ret = JS_PromiseResult(ctx, obj); JS_FreeValue(ctx, obj); break; } else if (state == JS_PROMISE_REJECTED) { ret = JS_Throw(ctx, JS_PromiseResult(ctx, obj)); JS_FreeValue(ctx, obj); break; } else if (state == JS_PROMISE_PENDING) { JSContext *ctx1; int err; err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1); if (err < 0) { js_std_dump_error(ctx1); } if (err == 0) js_std_promise_rejection_check(ctx); if (ts->can_js_os_poll) js_os_poll(ctx); } else { /* not a promise */ ret = obj; break; } } return ret; } void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len, int load_only) { JSValue obj, val; obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE); if (JS_IsException(obj)) goto exception; if (load_only) { if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { if (js_module_set_import_meta(ctx, obj, false, false) < 0) goto exception; } JS_FreeValue(ctx, obj); } else { if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) { if (JS_ResolveModule(ctx, obj) < 0) { JS_FreeValue(ctx, obj); goto exception; } if (js_module_set_import_meta(ctx, obj, false, true) < 0) goto exception; val = JS_EvalFunction(ctx, obj); val = js_std_await(ctx, val); } else { val = JS_EvalFunction(ctx, obj); } if (JS_IsException(val)) { exception: js_std_dump_error(ctx); exit(1); } JS_FreeValue(ctx, val); } } static JSValue js_bjson_read(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { uint8_t *buf; uint64_t pos, len; JSValue obj; size_t size; int flags; if (JS_ToIndex(ctx, &pos, argv[1])) return JS_EXCEPTION; if (JS_ToIndex(ctx, &len, argv[2])) return JS_EXCEPTION; if (JS_ToInt32(ctx, &flags, argv[3])) return JS_EXCEPTION; buf = JS_GetArrayBuffer(ctx, &size, argv[0]); if (!buf) return JS_EXCEPTION; if (pos + len > size) return JS_ThrowRangeError(ctx, "array buffer overflow"); obj = JS_ReadObject(ctx, buf + pos, len, flags); return obj; } static JSValue js_bjson_write(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { size_t len; uint8_t *buf; JSValue array; int flags; if (JS_ToInt32(ctx, &flags, argv[1])) return JS_EXCEPTION; buf = JS_WriteObject(ctx, &len, argv[0], flags); if (!buf) return JS_EXCEPTION; array = JS_NewArrayBufferCopy(ctx, buf, len); js_free(ctx, buf); return array; } static const JSCFunctionListEntry js_bjson_funcs[] = { JS_CFUNC_DEF("read", 4, js_bjson_read ), JS_CFUNC_DEF("write", 2, js_bjson_write ), #define DEF(x) JS_PROP_INT32_DEF(#x, JS_##x, JS_PROP_CONFIGURABLE) DEF(READ_OBJ_BYTECODE), DEF(READ_OBJ_REFERENCE), DEF(READ_OBJ_SAB), DEF(WRITE_OBJ_BYTECODE), DEF(WRITE_OBJ_REFERENCE), DEF(WRITE_OBJ_SAB), DEF(WRITE_OBJ_STRIP_DEBUG), DEF(WRITE_OBJ_STRIP_SOURCE), #undef DEF }; static int js_bjson_init(JSContext *ctx, JSModuleDef *m) { return JS_SetModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs)); } JSModuleDef *js_init_module_bjson(JSContext *ctx, const char *module_name) { JSModuleDef *m; m = JS_NewCModule(ctx, module_name, js_bjson_init); if (!m) return NULL; JS_AddModuleExportList(ctx, m, js_bjson_funcs, countof(js_bjson_funcs)); return m; } QuickJSR/src/quickjs/quickjs.c0000644000176200001440000720314115122664706016003 0ustar liggesusers/* * QuickJS Javascript Engine * * Copyright (c) 2017-2025 Fabrice Bellard * Copyright (c) 2017-2025 Charlie Gordon * Copyright (c) 2023-2025 Ben Noordhuis * Copyright (c) 2023-2025 Saúl Ibarra Corretgé * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include #include #include #include #include #include #if !defined(_MSC_VER) #include #if defined(_WIN32) #include #endif #endif #if defined(_WIN32) #include #endif #include #include #include #include "cutils.h" #include "list.h" #include "quickjs.h" #include "libregexp.h" #include "dtoa.h" #if defined(EMSCRIPTEN) || defined(_MSC_VER) #define DIRECT_DISPATCH 0 #else #define DIRECT_DISPATCH 1 #endif #if defined(__APPLE__) #define MALLOC_OVERHEAD 0 #else #define MALLOC_OVERHEAD 8 #endif #if defined(__NEWLIB__) #define NO_TM_GMTOFF #endif // atomic_store etc. are completely busted in recent versions of tcc; // somehow the compiler forgets to load |ptr| into %rdi when calling // the __atomic_*() helpers in its lib/stdatomic.c and lib/atomic.S #if !defined(__TINYC__) && !defined(EMSCRIPTEN) && !defined(__wasi__) && !__STDC_NO_ATOMICS__ #include "quickjs-c-atomics.h" #define CONFIG_ATOMICS #endif #ifndef __GNUC__ #define __extension__ #endif #ifndef NDEBUG #define ENABLE_DUMPS #endif //#define FORCE_GC_AT_MALLOC /* test the GC by forcing it before each object allocation */ #define check_dump_flag(rt, flag) ((rt->dump_flags & (flag +0)) == (flag +0)) #define STRINGIFY_(x) #x #define STRINGIFY(x) STRINGIFY_(x) #define QJS_VERSION_STRING \ STRINGIFY(QJS_VERSION_MAJOR) "." STRINGIFY(QJS_VERSION_MINOR) "." STRINGIFY(QJS_VERSION_PATCH) QJS_VERSION_SUFFIX const char* JS_GetVersion(void) { return QJS_VERSION_STRING; } #undef STRINFIGY_ #undef STRINGIFY static inline JSValueConst *vc(JSValue *vals) { return (JSValueConst *)vals; } static inline JSValue unsafe_unconst(JSValueConst v) { #ifdef JS_CHECK_JSVALUE return (JSValue)v; #else return v; #endif } static inline JSValueConst safe_const(JSValue v) { #ifdef JS_CHECK_JSVALUE return (JSValueConst)v; #else return v; #endif } enum { /* classid tag */ /* union usage | properties */ JS_CLASS_OBJECT = 1, /* must be first */ JS_CLASS_ARRAY, /* u.array | length */ JS_CLASS_ERROR, JS_CLASS_NUMBER, /* u.object_data */ JS_CLASS_STRING, /* u.object_data */ JS_CLASS_BOOLEAN, /* u.object_data */ JS_CLASS_SYMBOL, /* u.object_data */ JS_CLASS_ARGUMENTS, /* u.array | length */ JS_CLASS_MAPPED_ARGUMENTS, /* | length */ JS_CLASS_DATE, /* u.object_data */ JS_CLASS_MODULE_NS, JS_CLASS_C_FUNCTION, /* u.cfunc */ JS_CLASS_BYTECODE_FUNCTION, /* u.func */ JS_CLASS_BOUND_FUNCTION, /* u.bound_function */ JS_CLASS_C_FUNCTION_DATA, /* u.c_function_data_record */ JS_CLASS_GENERATOR_FUNCTION, /* u.func */ JS_CLASS_FOR_IN_ITERATOR, /* u.for_in_iterator */ JS_CLASS_REGEXP, /* u.regexp */ JS_CLASS_ARRAY_BUFFER, /* u.array_buffer */ JS_CLASS_SHARED_ARRAY_BUFFER, /* u.array_buffer */ JS_CLASS_UINT8C_ARRAY, /* u.array (typed_array) */ JS_CLASS_INT8_ARRAY, /* u.array (typed_array) */ JS_CLASS_UINT8_ARRAY, /* u.array (typed_array) */ JS_CLASS_INT16_ARRAY, /* u.array (typed_array) */ JS_CLASS_UINT16_ARRAY, /* u.array (typed_array) */ JS_CLASS_INT32_ARRAY, /* u.array (typed_array) */ JS_CLASS_UINT32_ARRAY, /* u.array (typed_array) */ JS_CLASS_BIG_INT64_ARRAY, /* u.array (typed_array) */ JS_CLASS_BIG_UINT64_ARRAY, /* u.array (typed_array) */ JS_CLASS_FLOAT16_ARRAY, /* u.array (typed_array) */ JS_CLASS_FLOAT32_ARRAY, /* u.array (typed_array) */ JS_CLASS_FLOAT64_ARRAY, /* u.array (typed_array) */ JS_CLASS_DATAVIEW, /* u.typed_array */ JS_CLASS_BIG_INT, /* u.object_data */ JS_CLASS_MAP, /* u.map_state */ JS_CLASS_SET, /* u.map_state */ JS_CLASS_WEAKMAP, /* u.map_state */ JS_CLASS_WEAKSET, /* u.map_state */ JS_CLASS_ITERATOR, JS_CLASS_ITERATOR_CONCAT, /* u.iterator_concat_data */ JS_CLASS_ITERATOR_HELPER, /* u.iterator_helper_data */ JS_CLASS_ITERATOR_WRAP, /* u.iterator_wrap_data */ JS_CLASS_MAP_ITERATOR, /* u.map_iterator_data */ JS_CLASS_SET_ITERATOR, /* u.map_iterator_data */ JS_CLASS_ARRAY_ITERATOR, /* u.array_iterator_data */ JS_CLASS_STRING_ITERATOR, /* u.array_iterator_data */ JS_CLASS_REGEXP_STRING_ITERATOR, /* u.regexp_string_iterator_data */ JS_CLASS_GENERATOR, /* u.generator_data */ JS_CLASS_PROXY, /* u.proxy_data */ JS_CLASS_PROMISE, /* u.promise_data */ JS_CLASS_PROMISE_RESOLVE_FUNCTION, /* u.promise_function_data */ JS_CLASS_PROMISE_REJECT_FUNCTION, /* u.promise_function_data */ JS_CLASS_ASYNC_FUNCTION, /* u.func */ JS_CLASS_ASYNC_FUNCTION_RESOLVE, /* u.async_function_data */ JS_CLASS_ASYNC_FUNCTION_REJECT, /* u.async_function_data */ JS_CLASS_ASYNC_FROM_SYNC_ITERATOR, /* u.async_from_sync_iterator_data */ JS_CLASS_ASYNC_GENERATOR_FUNCTION, /* u.func */ JS_CLASS_ASYNC_GENERATOR, /* u.async_generator_data */ JS_CLASS_WEAK_REF, JS_CLASS_FINALIZATION_REGISTRY, JS_CLASS_DOM_EXCEPTION, JS_CLASS_CALL_SITE, JS_CLASS_INIT_COUNT, /* last entry for predefined classes */ }; /* number of typed array types */ #define JS_TYPED_ARRAY_COUNT (JS_CLASS_FLOAT64_ARRAY - JS_CLASS_UINT8C_ARRAY + 1) static uint8_t const typed_array_size_log2[JS_TYPED_ARRAY_COUNT]; #define typed_array_size_log2(classid) (typed_array_size_log2[(classid)- JS_CLASS_UINT8C_ARRAY]) typedef enum JSErrorEnum { JS_EVAL_ERROR, JS_RANGE_ERROR, JS_REFERENCE_ERROR, JS_SYNTAX_ERROR, JS_TYPE_ERROR, JS_URI_ERROR, JS_INTERNAL_ERROR, JS_AGGREGATE_ERROR, JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */ JS_PLAIN_ERROR = JS_NATIVE_ERROR_COUNT } JSErrorEnum; #define JS_MAX_LOCAL_VARS 65535 #define JS_STACK_SIZE_MAX 65534 #define JS_STRING_LEN_MAX ((1 << 30) - 1) // 1,024 bytes is about the cutoff point where it starts getting // more profitable to ref slice than to copy #define JS_STRING_SLICE_LEN_MAX 1024 // in bytes #define __exception __attribute__((warn_unused_result)) typedef struct JSShape JSShape; typedef struct JSString JSString; typedef struct JSString JSAtomStruct; #define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v)) typedef enum { JS_GC_PHASE_NONE, JS_GC_PHASE_DECREF, JS_GC_PHASE_REMOVE_CYCLES, } JSGCPhaseEnum; typedef struct JSMallocState { size_t malloc_count; size_t malloc_size; size_t malloc_limit; void *opaque; /* user opaque */ } JSMallocState; typedef struct JSRuntimeFinalizerState { struct JSRuntimeFinalizerState *next; JSRuntimeFinalizer *finalizer; void *arg; } JSRuntimeFinalizerState; typedef struct JSValueLink { struct JSValueLink *next; JSValueConst value; } JSValueLink; struct JSRuntime { JSMallocFunctions mf; JSMallocState malloc_state; const char *rt_info; int atom_hash_size; /* power of two */ int atom_count; int atom_size; int atom_count_resize; /* resize hash table at this count */ uint32_t *atom_hash; JSAtomStruct **atom_array; int atom_free_index; /* 0 = none */ JSClassID js_class_id_alloc; /* counter for user defined classes */ int class_count; /* size of class_array */ JSClass *class_array; struct list_head context_list; /* list of JSContext.link */ /* list of JSGCObjectHeader.link. List of allocated GC objects (used by the garbage collector) */ struct list_head gc_obj_list; /* list of JSGCObjectHeader.link. Used during JS_FreeValueRT() */ struct list_head gc_zero_ref_count_list; struct list_head tmp_obj_list; /* used during GC */ JSGCPhaseEnum gc_phase : 8; size_t malloc_gc_threshold; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS struct list_head string_list; /* list of JSString.link */ #endif /* stack limitation */ uintptr_t stack_size; /* in bytes, 0 if no limit */ uintptr_t stack_top; uintptr_t stack_limit; /* lower stack limit */ JSValue current_exception; /* true if inside an out of memory error, to avoid recursing */ bool in_out_of_memory; /* true if inside build_backtrace, to avoid recursing */ bool in_build_stack_trace; /* true if inside JS_FreeRuntime */ bool in_free; struct JSStackFrame *current_stack_frame; JSInterruptHandler *interrupt_handler; void *interrupt_opaque; JSPromiseHook *promise_hook; void *promise_hook_opaque; // for smuggling the parent promise from js_promise_then // to js_promise_constructor JSValueLink *parent_promise; JSHostPromiseRejectionTracker *host_promise_rejection_tracker; void *host_promise_rejection_tracker_opaque; struct list_head job_list; /* list of JSJobEntry.link */ JSModuleNormalizeFunc *module_normalize_func; JSModuleLoaderFunc *module_loader_func; void *module_loader_opaque; /* timestamp for internal use in module evaluation */ int64_t module_async_evaluation_next_timestamp; /* used to allocate, free and clone SharedArrayBuffers */ JSSharedArrayBufferFunctions sab_funcs; bool can_block; /* true if Atomics.wait can block */ uint32_t dump_flags : 24; /* Shape hash table */ int shape_hash_bits; int shape_hash_size; int shape_hash_count; /* number of hashed shapes */ JSShape **shape_hash; void *user_opaque; void *libc_opaque; JSRuntimeFinalizerState *finalizers; }; struct JSClass { uint32_t class_id; /* 0 means free entry */ JSAtom class_name; JSClassFinalizer *finalizer; JSClassGCMark *gc_mark; JSClassCall *call; /* pointers for exotic behavior, can be NULL if none are present */ const JSClassExoticMethods *exotic; }; typedef struct JSStackFrame { struct JSStackFrame *prev_frame; /* NULL if first stack frame */ JSValue cur_func; /* current function, JS_UNDEFINED if the frame is detached */ JSValue *arg_buf; /* arguments */ JSValue *var_buf; /* variables */ struct list_head var_ref_list; /* list of JSVarRef.link */ uint8_t *cur_pc; /* only used in bytecode functions : PC of the instruction after the call */ uint32_t arg_count : 31; uint32_t is_strict_mode : 1; /* only used in generators. Current stack pointer value. NULL if the function is running. */ JSValue *cur_sp; } JSStackFrame; typedef enum { JS_GC_OBJ_TYPE_JS_OBJECT, JS_GC_OBJ_TYPE_FUNCTION_BYTECODE, JS_GC_OBJ_TYPE_SHAPE, JS_GC_OBJ_TYPE_VAR_REF, JS_GC_OBJ_TYPE_ASYNC_FUNCTION, JS_GC_OBJ_TYPE_JS_CONTEXT, } JSGCObjectTypeEnum; /* header for GC objects. GC objects are C data structures with a reference count that can reference other GC objects. JS Objects are a particular type of GC object. */ struct JSGCObjectHeader { int ref_count; /* must come first, 32-bit */ JSGCObjectTypeEnum gc_obj_type : 4; uint8_t mark : 4; /* used by the GC */ uint8_t dummy1; /* not used by the GC */ uint16_t dummy2; /* not used by the GC */ struct list_head link; }; typedef struct JSVarRef { union { JSGCObjectHeader header; /* must come first */ struct { int __gc_ref_count; /* corresponds to header.ref_count */ uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */ uint8_t is_detached; }; }; JSValue *pvalue; /* pointer to the value, either on the stack or to 'value' */ JSValue value; /* used when the variable is no longer on the stack */ } JSVarRef; typedef struct JSRefCountHeader { int ref_count; } JSRefCountHeader; /* bigint */ typedef int32_t js_slimb_t; typedef uint32_t js_limb_t; typedef int64_t js_sdlimb_t; typedef uint64_t js_dlimb_t; #define JS_LIMB_DIGITS 9 /* Must match the size of short_big_int in JSValueUnion */ #define JS_LIMB_BITS 32 #define JS_SHORT_BIG_INT_BITS JS_LIMB_BITS #define JS_BIGINT_MAX_SIZE ((1024 * 1024) / JS_LIMB_BITS) /* in limbs */ #define JS_SHORT_BIG_INT_MIN INT32_MIN #define JS_SHORT_BIG_INT_MAX INT32_MAX typedef struct JSBigInt { JSRefCountHeader header; /* must come first, 32-bit */ uint32_t len; /* number of limbs, >= 1 */ js_limb_t tab[]; /* two's complement representation, always normalized so that 'len' is the minimum possible length >= 1 */ } JSBigInt; /* this bigint structure can hold a 64 bit integer */ typedef struct { js_limb_t big_int_buf[sizeof(JSBigInt) / sizeof(js_limb_t)]; /* for JSBigInt */ /* must come just after */ js_limb_t tab[(64 + JS_LIMB_BITS - 1) / JS_LIMB_BITS]; } JSBigIntBuf; typedef enum { JS_AUTOINIT_ID_PROTOTYPE, JS_AUTOINIT_ID_MODULE_NS, JS_AUTOINIT_ID_PROP, JS_AUTOINIT_ID_BYTECODE, } JSAutoInitIDEnum; enum { JS_BUILTIN_ARRAY_FROMASYNC = 1, }; /* must be large enough to have a negligible runtime cost and small enough to call the interrupt callback often. */ #define JS_INTERRUPT_COUNTER_INIT 10000 struct JSContext { JSGCObjectHeader header; /* must come first */ JSRuntime *rt; struct list_head link; uint16_t binary_object_count; int binary_object_size; JSShape *array_shape; /* initial shape for Array objects */ JSValue *class_proto; JSValue function_proto; JSValue function_ctor; JSValue array_ctor; JSValue regexp_ctor; JSValue promise_ctor; JSValue native_error_proto[JS_NATIVE_ERROR_COUNT]; JSValue error_ctor; JSValue error_back_trace; JSValue error_prepare_stack; JSValue error_stack_trace_limit; JSValue iterator_ctor; JSValue iterator_ctor_getset; JSValue iterator_proto; JSValue async_iterator_proto; JSValue array_proto_values; JSValue throw_type_error; JSValue eval_obj; JSValue global_obj; /* global object */ JSValue global_var_obj; /* contains the global let/const definitions */ double time_origin; uint64_t random_state; /* when the counter reaches zero, JSRutime.interrupt_handler is called */ int interrupt_counter; struct list_head loaded_modules; /* list of JSModuleDef.link */ /* if NULL, RegExp compilation is not supported */ JSValue (*compile_regexp)(JSContext *ctx, JSValueConst pattern, JSValueConst flags); /* if NULL, eval is not supported */ JSValue (*eval_internal)(JSContext *ctx, JSValueConst this_obj, const char *input, size_t input_len, const char *filename, int line, int flags, int scope_idx); void *user_opaque; }; typedef union JSFloat64Union { double d; uint64_t u64; uint32_t u32[2]; } JSFloat64Union; typedef enum { JS_WEAK_REF_KIND_MAP, JS_WEAK_REF_KIND_WEAK_REF, JS_WEAK_REF_KIND_FINALIZATION_REGISTRY_ENTRY, } JSWeakRefKindEnum; typedef struct JSWeakRefRecord { JSWeakRefKindEnum kind; struct JSWeakRefRecord *next_weak_ref; union { struct JSMapRecord *map_record; struct JSWeakRefData *weak_ref_data; struct JSFinRecEntry *fin_rec_entry; } u; } JSWeakRefRecord; typedef struct JSMapRecord { int ref_count; /* used during enumeration to avoid freeing the record */ bool empty; /* true if the record is deleted */ struct JSMapState *map; struct list_head link; struct list_head hash_link; JSValue key; JSValue value; } JSMapRecord; typedef struct JSMapState { bool is_weak; /* true if WeakSet/WeakMap */ struct list_head records; /* list of JSMapRecord.link */ uint32_t record_count; struct list_head *hash_table; uint32_t hash_size; /* must be a power of two */ uint32_t record_count_threshold; /* count at which a hash table resize is needed */ } JSMapState; enum { JS_TO_STRING_IS_PROPERTY_KEY = 1 << 0, JS_TO_STRING_NO_SIDE_EFFECTS = 1 << 1, }; enum { JS_ATOM_TYPE_STRING = 1, JS_ATOM_TYPE_GLOBAL_SYMBOL, JS_ATOM_TYPE_SYMBOL, JS_ATOM_TYPE_PRIVATE, }; enum { JS_ATOM_HASH_SYMBOL, JS_ATOM_HASH_PRIVATE, }; typedef enum { JS_ATOM_KIND_STRING, JS_ATOM_KIND_SYMBOL, JS_ATOM_KIND_PRIVATE, } JSAtomKindEnum; typedef enum { JS_STRING_KIND_NORMAL, JS_STRING_KIND_SLICE, } JSStringKind; #define JS_ATOM_HASH_MASK ((1 << 29) - 1) struct JSString { JSRefCountHeader header; /* must come first, 32-bit */ uint32_t len : 31; uint8_t is_wide_char : 1; /* 0 = 8 bits, 1 = 16 bits characters */ /* for JS_ATOM_TYPE_SYMBOL: hash = 0, atom_type = 3, for JS_ATOM_TYPE_PRIVATE: hash = 1, atom_type = 3 XXX: could change encoding to have one more bit in hash */ uint32_t hash : 29; uint8_t kind : 1; uint8_t atom_type : 2; /* != 0 if atom, JS_ATOM_TYPE_x */ uint32_t hash_next; /* atom_index for JS_ATOM_TYPE_SYMBOL */ JSWeakRefRecord *first_weak_ref; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS struct list_head link; /* string list */ #endif }; typedef struct JSStringSlice { JSString *parent; uint32_t start; // in bytes, not characters } JSStringSlice; static inline void *strv(JSString *p) { JSStringSlice *slice; switch (p->kind) { case JS_STRING_KIND_NORMAL: return (void *)&p[1]; case JS_STRING_KIND_SLICE: slice = (void *)&p[1]; return (char *)&slice->parent[1] + slice->start; } abort(); return NULL; } static inline uint8_t *str8(JSString *p) { return strv(p); } static inline uint16_t *str16(JSString *p) { return strv(p); } typedef struct JSClosureVar { uint8_t is_local : 1; uint8_t is_arg : 1; uint8_t is_const : 1; uint8_t is_lexical : 1; uint8_t var_kind : 4; /* see JSVarKindEnum */ /* 8 bits available */ uint16_t var_idx; /* is_local = true: index to a normal variable of the parent function. otherwise: index to a closure variable of the parent function */ JSAtom var_name; } JSClosureVar; #define ARG_SCOPE_INDEX 1 #define ARG_SCOPE_END (-2) typedef struct JSVarScope { int parent; /* index into fd->scopes of the enclosing scope */ int first; /* index into fd->vars of the last variable in this scope */ } JSVarScope; typedef enum { /* XXX: add more variable kinds here instead of using bit fields */ JS_VAR_NORMAL, JS_VAR_FUNCTION_DECL, /* lexical var with function declaration */ JS_VAR_NEW_FUNCTION_DECL, /* lexical var with async/generator function declaration */ JS_VAR_CATCH, JS_VAR_FUNCTION_NAME, /* function expression name */ JS_VAR_PRIVATE_FIELD, JS_VAR_PRIVATE_METHOD, JS_VAR_PRIVATE_GETTER, JS_VAR_PRIVATE_SETTER, /* must come after JS_VAR_PRIVATE_GETTER */ JS_VAR_PRIVATE_GETTER_SETTER, /* must come after JS_VAR_PRIVATE_SETTER */ } JSVarKindEnum; /* XXX: could use a different structure in bytecode functions to save memory */ typedef struct JSVarDef { JSAtom var_name; /* index into fd->scopes of this variable lexical scope */ int scope_level; /* during compilation: - if scope_level = 0: scope in which the variable is defined - if scope_level != 0: index into fd->vars of the next variable in the same or enclosing lexical scope in a bytecode function: index into fd->vars of the next variable in the same or enclosing lexical scope */ int scope_next; uint8_t is_const : 1; uint8_t is_lexical : 1; uint8_t is_captured : 1; uint8_t is_static_private : 1; /* only used during private class field parsing */ uint8_t var_kind : 4; /* see JSVarKindEnum */ /* only used during compilation: function pool index for lexical variables with var_kind = JS_VAR_FUNCTION_DECL/JS_VAR_NEW_FUNCTION_DECL or scope level of the definition of the 'var' variables (they have scope_level = 0) */ int func_pool_idx : 24; /* only used during compilation : index in the constant pool for hoisted function definition */ } JSVarDef; /* for the encoding of the pc2line table */ #define PC2LINE_BASE (-1) #define PC2LINE_RANGE 5 #define PC2LINE_OP_FIRST 1 #define PC2LINE_DIFF_PC_MAX ((255 - PC2LINE_OP_FIRST) / PC2LINE_RANGE) typedef enum JSFunctionKindEnum { JS_FUNC_NORMAL = 0, JS_FUNC_GENERATOR = (1 << 0), JS_FUNC_ASYNC = (1 << 1), JS_FUNC_ASYNC_GENERATOR = (JS_FUNC_GENERATOR | JS_FUNC_ASYNC), } JSFunctionKindEnum; typedef struct JSFunctionBytecode { JSGCObjectHeader header; /* must come first */ uint8_t is_strict_mode : 1; uint8_t has_prototype : 1; /* true if a prototype field is necessary */ uint8_t has_simple_parameter_list : 1; uint8_t is_derived_class_constructor : 1; /* true if home_object needs to be initialized */ uint8_t need_home_object : 1; uint8_t func_kind : 2; uint8_t new_target_allowed : 1; uint8_t super_call_allowed : 1; uint8_t super_allowed : 1; uint8_t arguments_allowed : 1; uint8_t backtrace_barrier : 1; /* stop backtrace on this function */ /* XXX: 5 bits available */ uint8_t *byte_code_buf; /* (self pointer) */ int byte_code_len; JSAtom func_name; JSVarDef *vardefs; /* arguments + local variables (arg_count + var_count) (self pointer) */ JSClosureVar *closure_var; /* list of variables in the closure (self pointer) */ uint16_t arg_count; uint16_t var_count; uint16_t defined_arg_count; /* for length function property */ uint16_t stack_size; /* maximum stack size */ JSContext *realm; /* function realm */ JSValue *cpool; /* constant pool (self pointer) */ int cpool_count; int closure_var_count; JSAtom filename; int line_num; int col_num; int source_len; int pc2line_len; uint8_t *pc2line_buf; char *source; } JSFunctionBytecode; typedef struct JSBoundFunction { JSValue func_obj; JSValue this_val; int argc; JSValue argv[]; } JSBoundFunction; typedef enum JSIteratorKindEnum { JS_ITERATOR_KIND_KEY, JS_ITERATOR_KIND_VALUE, JS_ITERATOR_KIND_KEY_AND_VALUE, } JSIteratorKindEnum; typedef enum JSIteratorHelperKindEnum { JS_ITERATOR_HELPER_KIND_DROP, JS_ITERATOR_HELPER_KIND_EVERY, JS_ITERATOR_HELPER_KIND_FILTER, JS_ITERATOR_HELPER_KIND_FIND, JS_ITERATOR_HELPER_KIND_FLAT_MAP, JS_ITERATOR_HELPER_KIND_FOR_EACH, JS_ITERATOR_HELPER_KIND_MAP, JS_ITERATOR_HELPER_KIND_SOME, JS_ITERATOR_HELPER_KIND_TAKE, } JSIteratorHelperKindEnum; typedef struct JSForInIterator { JSValue obj; bool is_array; uint32_t array_length; uint32_t idx; } JSForInIterator; typedef struct JSRegExp { JSString *pattern; JSString *bytecode; /* also contains the flags */ } JSRegExp; typedef struct JSProxyData { JSValue target; JSValue handler; uint8_t is_func; uint8_t is_revoked; } JSProxyData; typedef struct JSArrayBuffer { int byte_length; /* 0 if detached */ int max_byte_length; /* -1 if not resizable; >= byte_length otherwise */ uint8_t detached; uint8_t shared; /* if shared, the array buffer cannot be detached */ uint8_t *data; /* NULL if detached */ struct list_head array_list; void *opaque; JSFreeArrayBufferDataFunc *free_func; } JSArrayBuffer; typedef struct JSTypedArray { struct list_head link; /* link to arraybuffer */ JSObject *obj; /* back pointer to the TypedArray/DataView object */ JSObject *buffer; /* based array buffer */ uint32_t offset; /* byte offset in the array buffer */ uint32_t length; /* byte length in the array buffer */ bool track_rab; /* auto-track length of backing array buffer */ } JSTypedArray; typedef struct JSAsyncFunctionState { JSValue this_val; /* 'this' generator argument */ int argc; /* number of function arguments */ bool throw_flag; /* used to throw an exception in JS_CallInternal() */ JSStackFrame frame; } JSAsyncFunctionState; /* XXX: could use an object instead to avoid the JS_TAG_ASYNC_FUNCTION tag for the GC */ typedef struct JSAsyncFunctionData { JSGCObjectHeader header; /* must come first */ JSValue resolving_funcs[2]; bool is_active; /* true if the async function state is valid */ JSAsyncFunctionState func_state; } JSAsyncFunctionData; typedef struct JSReqModuleEntry { JSAtom module_name; JSModuleDef *module; /* used using resolution */ } JSReqModuleEntry; typedef enum JSExportTypeEnum { JS_EXPORT_TYPE_LOCAL, JS_EXPORT_TYPE_INDIRECT, } JSExportTypeEnum; typedef struct JSExportEntry { union { struct { int var_idx; /* closure variable index */ JSVarRef *var_ref; /* if != NULL, reference to the variable */ } local; /* for local export */ int req_module_idx; /* module for indirect export */ } u; JSExportTypeEnum export_type; JSAtom local_name; /* '*' if export ns from. not used for local export after compilation */ JSAtom export_name; /* exported variable name */ } JSExportEntry; typedef struct JSStarExportEntry { int req_module_idx; /* in req_module_entries */ } JSStarExportEntry; typedef struct JSImportEntry { int var_idx; /* closure variable index */ JSAtom import_name; int req_module_idx; /* in req_module_entries */ } JSImportEntry; typedef enum { JS_MODULE_STATUS_UNLINKED, JS_MODULE_STATUS_LINKING, JS_MODULE_STATUS_LINKED, JS_MODULE_STATUS_EVALUATING, JS_MODULE_STATUS_EVALUATING_ASYNC, JS_MODULE_STATUS_EVALUATED, } JSModuleStatus; struct JSModuleDef { JSRefCountHeader header; /* must come first, 32-bit */ JSAtom module_name; struct list_head link; JSReqModuleEntry *req_module_entries; int req_module_entries_count; int req_module_entries_size; JSExportEntry *export_entries; int export_entries_count; int export_entries_size; JSStarExportEntry *star_export_entries; int star_export_entries_count; int star_export_entries_size; JSImportEntry *import_entries; int import_entries_count; int import_entries_size; JSValue module_ns; JSValue func_obj; /* only used for JS modules */ JSModuleInitFunc *init_func; /* only used for C modules */ bool has_tla; /* true if func_obj contains await */ bool resolved; bool func_created; JSModuleStatus status : 8; /* temp use during js_module_link() & js_module_evaluate() */ int dfs_index, dfs_ancestor_index; JSModuleDef *stack_prev; /* temp use during js_module_evaluate() */ JSModuleDef **async_parent_modules; int async_parent_modules_count; int async_parent_modules_size; int pending_async_dependencies; bool async_evaluation; int64_t async_evaluation_timestamp; JSModuleDef *cycle_root; JSValue promise; /* corresponds to spec field: capability */ JSValue resolving_funcs[2]; /* corresponds to spec field: capability */ /* true if evaluation yielded an exception. It is saved in eval_exception */ bool eval_has_exception; JSValue eval_exception; JSValue meta_obj; /* for import.meta */ }; typedef struct JSJobEntry { struct list_head link; JSContext *ctx; JSJobFunc *job_func; int argc; JSValue argv[]; } JSJobEntry; typedef struct JSProperty { union { JSValue value; /* JS_PROP_NORMAL */ struct { /* JS_PROP_GETSET */ JSObject *getter; /* NULL if undefined */ JSObject *setter; /* NULL if undefined */ } getset; JSVarRef *var_ref; /* JS_PROP_VARREF */ struct { /* JS_PROP_AUTOINIT */ /* in order to use only 2 pointers, we compress the realm and the init function pointer */ uintptr_t realm_and_id; /* realm and init_id (JS_AUTOINIT_ID_x) in the 2 low bits */ void *opaque; } init; } u; } JSProperty; #define JS_PROP_INITIAL_SIZE 2 #define JS_PROP_INITIAL_HASH_SIZE 4 /* must be a power of two */ #define JS_ARRAY_INITIAL_SIZE 2 typedef struct JSShapeProperty { uint32_t hash_next : 26; /* 0 if last in list */ uint32_t flags : 6; /* JS_PROP_XXX */ JSAtom atom; /* JS_ATOM_NULL = free property entry */ } JSShapeProperty; struct JSShape { /* hash table of size hash_mask + 1 before the start of the structure (see prop_hash_end()). */ JSGCObjectHeader header; /* true if the shape is inserted in the shape hash table. If not, JSShape.hash is not valid */ uint8_t is_hashed; /* If true, the shape may have small array index properties 'n' with 0 <= n <= 2^31-1. If false, the shape is guaranteed not to have small array index properties */ uint8_t has_small_array_index; uint32_t hash; /* current hash value */ uint32_t prop_hash_mask; int prop_size; /* allocated properties */ int prop_count; /* include deleted properties */ int deleted_prop_count; JSShape *shape_hash_next; /* in JSRuntime.shape_hash[h] list */ JSObject *proto; JSShapeProperty prop[]; /* prop_size elements */ }; struct JSObject { union { JSGCObjectHeader header; struct { int __gc_ref_count; /* corresponds to header.ref_count */ uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */ uint8_t extensible : 1; uint8_t free_mark : 1; /* only used when freeing objects with cycles */ uint8_t is_exotic : 1; /* true if object has exotic property handlers */ uint8_t fast_array : 1; /* true if u.array is used for get/put (for JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS and typed arrays) */ uint8_t is_constructor : 1; /* true if object is a constructor function */ uint8_t is_uncatchable_error : 1; /* if true, error is not catchable */ uint8_t tmp_mark : 1; /* used in JS_WriteObjectRec() */ uint8_t is_HTMLDDA : 1; /* specific annex B IsHtmlDDA behavior */ uint16_t class_id; /* see JS_CLASS_x */ }; }; /* byte offsets: 16/24 */ JSShape *shape; /* prototype and property names + flag */ JSProperty *prop; /* array of properties */ /* byte offsets: 24/40 */ JSWeakRefRecord *first_weak_ref; /* byte offsets: 28/48 */ union { void *opaque; struct JSBoundFunction *bound_function; /* JS_CLASS_BOUND_FUNCTION */ struct JSCFunctionDataRecord *c_function_data_record; /* JS_CLASS_C_FUNCTION_DATA */ struct JSForInIterator *for_in_iterator; /* JS_CLASS_FOR_IN_ITERATOR */ struct JSArrayBuffer *array_buffer; /* JS_CLASS_ARRAY_BUFFER, JS_CLASS_SHARED_ARRAY_BUFFER */ struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_DATAVIEW */ struct JSMapState *map_state; /* JS_CLASS_MAP..JS_CLASS_WEAKSET */ struct JSMapIteratorData *map_iterator_data; /* JS_CLASS_MAP_ITERATOR, JS_CLASS_SET_ITERATOR */ struct JSArrayIteratorData *array_iterator_data; /* JS_CLASS_ARRAY_ITERATOR, JS_CLASS_STRING_ITERATOR */ struct JSRegExpStringIteratorData *regexp_string_iterator_data; /* JS_CLASS_REGEXP_STRING_ITERATOR */ struct JSGeneratorData *generator_data; /* JS_CLASS_GENERATOR */ struct JSIteratorConcatData *iterator_concat_data; /* JS_CLASS_ITERATOR_CONCAT */ struct JSIteratorHelperData *iterator_helper_data; /* JS_CLASS_ITERATOR_HELPER */ struct JSIteratorWrapData *iterator_wrap_data; /* JS_CLASS_ITERATOR_WRAP */ struct JSProxyData *proxy_data; /* JS_CLASS_PROXY */ struct JSPromiseData *promise_data; /* JS_CLASS_PROMISE */ struct JSPromiseFunctionData *promise_function_data; /* JS_CLASS_PROMISE_RESOLVE_FUNCTION, JS_CLASS_PROMISE_REJECT_FUNCTION */ struct JSAsyncFunctionData *async_function_data; /* JS_CLASS_ASYNC_FUNCTION_RESOLVE, JS_CLASS_ASYNC_FUNCTION_REJECT */ struct JSAsyncFromSyncIteratorData *async_from_sync_iterator_data; /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */ struct JSAsyncGeneratorData *async_generator_data; /* JS_CLASS_ASYNC_GENERATOR */ struct { /* JS_CLASS_BYTECODE_FUNCTION: 12/24 bytes */ /* also used by JS_CLASS_GENERATOR_FUNCTION, JS_CLASS_ASYNC_FUNCTION and JS_CLASS_ASYNC_GENERATOR_FUNCTION */ struct JSFunctionBytecode *function_bytecode; JSVarRef **var_refs; JSObject *home_object; /* for 'super' access */ } func; struct { /* JS_CLASS_C_FUNCTION: 12/20 bytes */ JSContext *realm; JSCFunctionType c_function; uint8_t length; uint8_t cproto; int16_t magic; } cfunc; /* array part for fast arrays and typed arrays */ struct { /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */ union { uint32_t size; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */ struct JSTypedArray *typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */ } u1; union { JSValue *values; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */ void *ptr; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */ int8_t *int8_ptr; /* JS_CLASS_INT8_ARRAY */ uint8_t *uint8_ptr; /* JS_CLASS_UINT8_ARRAY, JS_CLASS_UINT8C_ARRAY */ int16_t *int16_ptr; /* JS_CLASS_INT16_ARRAY */ uint16_t *uint16_ptr; /* JS_CLASS_UINT16_ARRAY */ int32_t *int32_ptr; /* JS_CLASS_INT32_ARRAY */ uint32_t *uint32_ptr; /* JS_CLASS_UINT32_ARRAY */ int64_t *int64_ptr; /* JS_CLASS_INT64_ARRAY */ uint64_t *uint64_ptr; /* JS_CLASS_UINT64_ARRAY */ uint16_t *fp16_ptr; /* JS_CLASS_FLOAT16_ARRAY */ float *float_ptr; /* JS_CLASS_FLOAT32_ARRAY */ double *double_ptr; /* JS_CLASS_FLOAT64_ARRAY */ } u; uint32_t count; /* <= 2^31-1. 0 for a detached typed array */ } array; /* 12/20 bytes */ JSRegExp regexp; /* JS_CLASS_REGEXP: 8/16 bytes */ JSValue object_data; /* for JS_SetObjectData(): 8/16/16 bytes */ } u; /* byte sizes: 40/48/72 */ }; typedef struct JSCallSiteData { JSValue filename; JSValue func; JSValue func_name; bool native; int line_num; int col_num; } JSCallSiteData; enum { __JS_ATOM_NULL = JS_ATOM_NULL, #define DEF(name, str) JS_ATOM_ ## name, #include "quickjs-atom.h" #undef DEF JS_ATOM_END, }; #define JS_ATOM_LAST_KEYWORD JS_ATOM_super #define JS_ATOM_LAST_STRICT_KEYWORD JS_ATOM_yield static const char js_atom_init[] = #define DEF(name, str) str "\0" #include "quickjs-atom.h" #undef DEF ; typedef enum OPCodeFormat { #define FMT(f) OP_FMT_ ## f, #define DEF(id, size, n_pop, n_push, f) #include "quickjs-opcode.h" #undef DEF #undef FMT } OPCodeFormat; typedef enum OPCodeEnum { #define FMT(f) #define DEF(id, size, n_pop, n_push, f) OP_ ## id, #define def(id, size, n_pop, n_push, f) #include "quickjs-opcode.h" #undef def #undef DEF #undef FMT OP_COUNT, /* excluding temporary opcodes */ /* temporary opcodes : overlap with the short opcodes */ OP_TEMP_START = OP_nop + 1, OP___dummy = OP_TEMP_START - 1, #define FMT(f) #define DEF(id, size, n_pop, n_push, f) #define def(id, size, n_pop, n_push, f) OP_ ## id, #include "quickjs-opcode.h" #undef def #undef DEF #undef FMT OP_TEMP_END, } OPCodeEnum; static int JS_InitAtoms(JSRuntime *rt); static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len, int atom_type); static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p); static void free_function_bytecode(JSRuntime *rt, JSFunctionBytecode *b); static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags); static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags); static JSValue JS_CallInternal(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, JSValueConst new_target, int argc, JSValueConst *argv, int flags); static JSValue JS_CallConstructorInternal(JSContext *ctx, JSValueConst func_obj, JSValueConst new_target, int argc, JSValueConst *argv, int flags); static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj, int argc, JSValueConst *argv); static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom, int argc, JSValueConst *argv); static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen, JSValue val, bool is_array_ctor); static JSValue JS_EvalObject(JSContext *ctx, JSValueConst this_obj, JSValueConst val, int flags, int scope_idx); static __maybe_unused void JS_DumpString(JSRuntime *rt, JSString *p); static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt); static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p); static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p); static __maybe_unused void JS_DumpValue(JSRuntime *rt, JSValueConst val); static __maybe_unused void JS_DumpAtoms(JSRuntime *rt); static __maybe_unused void JS_DumpShapes(JSRuntime *rt); static JSValue js_function_apply(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); static void js_array_finalizer(JSRuntime *rt, JSValueConst val); static void js_array_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_object_data_finalizer(JSRuntime *rt, JSValueConst val); static void js_object_data_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_c_function_finalizer(JSRuntime *rt, JSValueConst val); static void js_c_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_bytecode_function_finalizer(JSRuntime *rt, JSValueConst val); static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_bound_function_finalizer(JSRuntime *rt, JSValueConst val); static void js_bound_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValueConst val); static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_regexp_finalizer(JSRuntime *rt, JSValueConst val); static void js_array_buffer_finalizer(JSRuntime *rt, JSValueConst val); static void js_typed_array_finalizer(JSRuntime *rt, JSValueConst val); static void js_typed_array_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_proxy_finalizer(JSRuntime *rt, JSValueConst val); static void js_proxy_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_map_finalizer(JSRuntime *rt, JSValueConst val); static void js_map_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_map_iterator_finalizer(JSRuntime *rt, JSValueConst val); static void js_map_iterator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_array_iterator_finalizer(JSRuntime *rt, JSValueConst val); static void js_array_iterator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_iterator_concat_finalizer(JSRuntime *rt, JSValueConst val); static void js_iterator_concat_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_iterator_helper_finalizer(JSRuntime *rt, JSValueConst val); static void js_iterator_helper_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_iterator_wrap_finalizer(JSRuntime *rt, JSValueConst val); static void js_iterator_wrap_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_regexp_string_iterator_finalizer(JSRuntime *rt, JSValueConst val); static void js_regexp_string_iterator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_generator_finalizer(JSRuntime *rt, JSValueConst val); static void js_generator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_promise_finalizer(JSRuntime *rt, JSValueConst val); static void js_promise_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static void js_promise_resolve_function_finalizer(JSRuntime *rt, JSValueConst val); static void js_promise_resolve_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); #define HINT_STRING 0 #define HINT_NUMBER 1 #define HINT_NONE 2 #define HINT_FORCE_ORDINARY (1 << 4) // don't try Symbol.toPrimitive static JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint); static JSValue JS_ToStringFree(JSContext *ctx, JSValue val); static int JS_ToBoolFree(JSContext *ctx, JSValue val); static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val); static int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val); static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val); static JSValue JS_ToPropertyKeyInternal(JSContext *ctx, JSValueConst val, int flags); static JSValue js_new_string8_len(JSContext *ctx, const char *buf, int len); static JSValue js_compile_regexp(JSContext *ctx, JSValueConst pattern, JSValueConst flags); static JSValue js_regexp_constructor_internal(JSContext *ctx, JSValueConst ctor, JSValue pattern, JSValue bc); static void gc_decref(JSRuntime *rt); static int JS_NewClass1(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def, JSAtom name); static JSValue js_array_push(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int unshift); static JSValue js_array_constructor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv); static JSValue js_error_constructor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic); static JSValue js_object_defineProperty(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); typedef enum JSStrictEqModeEnum { JS_EQ_STRICT, JS_EQ_SAME_VALUE, JS_EQ_SAME_VALUE_ZERO, } JSStrictEqModeEnum; static bool js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2, JSStrictEqModeEnum eq_mode); static bool js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2); static bool js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2); static bool js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2); static JSValue JS_ToObjectFree(JSContext *ctx, JSValue val); static JSProperty *add_property(JSContext *ctx, JSObject *p, JSAtom prop, int prop_flags); static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val); static JSValue JS_ThrowStackOverflow(JSContext *ctx); static JSValue JS_ThrowTypeErrorRevokedProxy(JSContext *ctx); static JSValue js_proxy_getPrototypeOf(JSContext *ctx, JSValueConst obj); static int js_proxy_setPrototypeOf(JSContext *ctx, JSValueConst obj, JSValueConst proto_val, bool throw_flag); static int js_proxy_isExtensible(JSContext *ctx, JSValueConst obj); static int js_proxy_preventExtensions(JSContext *ctx, JSValueConst obj); static int js_proxy_isArray(JSContext *ctx, JSValueConst obj); static int JS_CreateProperty(JSContext *ctx, JSObject *p, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags); static int js_string_memcmp(JSString *p1, JSString *p2, int len); static void reset_weak_ref(JSRuntime *rt, JSWeakRefRecord **first_weak_ref); static bool is_valid_weakref_target(JSValueConst val); static void insert_weakref_record(JSValueConst target, struct JSWeakRefRecord *wr); static JSValue js_array_buffer_constructor3(JSContext *ctx, JSValueConst new_target, uint64_t len, uint64_t *max_len, JSClassID class_id, uint8_t *buf, JSFreeArrayBufferDataFunc *free_func, void *opaque, bool alloc_flag); static void js_array_buffer_free(JSRuntime *rt, void *opaque, void *ptr); static JSArrayBuffer *js_get_array_buffer(JSContext *ctx, JSValueConst obj); static bool array_buffer_is_resizable(const JSArrayBuffer *abuf); static JSValue js_typed_array_constructor(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int classid); static JSValue js_typed_array_constructor_ta(JSContext *ctx, JSValueConst new_target, JSValueConst src_obj, int classid, uint32_t len); static bool is_typed_array(JSClassID class_id); static bool typed_array_is_oob(JSObject *p); static uint32_t typed_array_length(JSObject *p); static JSValue JS_ThrowTypeErrorDetachedArrayBuffer(JSContext *ctx); static JSValue JS_ThrowTypeErrorArrayBufferOOB(JSContext *ctx); static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx, bool is_arg); static JSValue js_call_generator_function(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags); static void js_async_function_resolve_finalizer(JSRuntime *rt, JSValueConst val); static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static JSValue JS_EvalInternal(JSContext *ctx, JSValueConst this_obj, const char *input, size_t input_len, const char *filename, int line, int flags, int scope_idx); static void js_free_module_def(JSContext *ctx, JSModuleDef *m); static void js_mark_module_def(JSRuntime *rt, JSModuleDef *m, JS_MarkFunc *mark_func); static JSValue js_import_meta(JSContext *ctx); static JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier); static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref); static JSValue js_new_promise_capability(JSContext *ctx, JSValue *resolving_funcs, JSValueConst ctor); static __exception int perform_promise_then(JSContext *ctx, JSValueConst promise, JSValueConst *resolve_reject, JSValueConst *cap_resolving_funcs); static JSValue js_promise_resolve(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); static JSValue js_promise_then(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); static JSValue js_promise_resolve_thenable_job(JSContext *ctx, int argc, JSValueConst *argv); static bool js_string_eq(JSString *p1, JSString *p2); static int js_string_compare(JSString *p1, JSString *p2); static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj, JSValue prop, JSValue val, int flags); static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val); static bool JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val); static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val); static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc, JSObject *p, JSAtom prop); static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc); static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s, JS_MarkFunc *mark_func); static void JS_AddIntrinsicBasicObjects(JSContext *ctx); static void js_free_shape(JSRuntime *rt, JSShape *sh); static void js_free_shape_null(JSRuntime *rt, JSShape *sh); static int js_shape_prepare_update(JSContext *ctx, JSObject *p, JSShapeProperty **pprs); static int init_shape_hash(JSRuntime *rt); static __exception int js_get_length32(JSContext *ctx, uint32_t *pres, JSValueConst obj); static __exception int js_get_length64(JSContext *ctx, int64_t *pres, JSValueConst obj); static __exception int js_set_length64(JSContext *ctx, JSValueConst obj, int64_t len); static void free_arg_list(JSContext *ctx, JSValue *tab, uint32_t len); static JSValue *build_arg_list(JSContext *ctx, uint32_t *plen, JSValueConst array_arg); static JSValue js_create_array(JSContext *ctx, int len, JSValueConst *tab); static bool js_get_fast_array(JSContext *ctx, JSValue obj, JSValue **arrpp, uint32_t *countp); static int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len); static JSValue JS_CreateAsyncFromSyncIterator(JSContext *ctx, JSValue sync_iter); static void js_c_function_data_finalizer(JSRuntime *rt, JSValueConst val); static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); static JSValue js_call_c_function_data(JSContext *ctx, JSValueConst func_obj, JSValueConst this_val, int argc, JSValueConst *argv, int flags); static JSAtom js_symbol_to_atom(JSContext *ctx, JSValueConst val); static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h, JSGCObjectTypeEnum type); static void remove_gc_object(JSGCObjectHeader *h); static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s); static JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); static JSValue js_module_ns_autoinit(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); static JSValue JS_InstantiateFunctionListItem2(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); static void js_set_uncatchable_error(JSContext *ctx, JSValueConst val, bool flag); static JSValue js_new_callsite(JSContext *ctx, JSCallSiteData *csd); static void js_new_callsite_data(JSContext *ctx, JSCallSiteData *csd, JSStackFrame *sf); static void js_new_callsite_data2(JSContext *ctx, JSCallSiteData *csd, const char *filename, int line_num, int col_num); static void _JS_AddIntrinsicCallSite(JSContext *ctx); static void JS_SetOpaqueInternal(JSValueConst obj, void *opaque); static const JSClassExoticMethods js_arguments_exotic_methods; static const JSClassExoticMethods js_string_exotic_methods; static const JSClassExoticMethods js_proxy_exotic_methods; static const JSClassExoticMethods js_module_ns_exotic_methods; static inline bool double_is_int32(double d) { uint64_t u, e; JSFloat64Union t; t.d = d; u = t.u64; e = ((u >> 52) & 0x7FF) - 1023; if (e > 30) { // accept 0, INT32_MIN, reject too large, too small, nan, inf, -0 return !u || (u == 0xc1e0000000000000); } else { // shift out sign, exponent and whole part bits // value is fractional if remaining low bits are non-zero return !(u << 12 << e); } } static JSValue js_float64(double d) { return __JS_NewFloat64(d); } static int compare_u32(uint32_t a, uint32_t b) { return -(a < b) + (b < a); // -1, 0 or 1 } static JSValue js_int32(int32_t v) { return JS_MKVAL(JS_TAG_INT, v); } static JSValue js_uint32(uint32_t v) { if (v <= INT32_MAX) return js_int32(v); else return js_float64(v); } static JSValue js_int64(int64_t v) { if (v >= INT32_MIN && v <= INT32_MAX) return js_int32(v); else return js_float64(v); } static JSValue js_number(double d) { if (double_is_int32(d)) return js_int32((int32_t)d); else return js_float64(d); } JSValue JS_NewNumber(JSContext *ctx, double d) { return js_number(d); } static JSValue js_bool(bool v) { return JS_MKVAL(JS_TAG_BOOL, (v != 0)); } static JSValue js_dup(JSValueConst v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); p->ref_count++; } return unsafe_unconst(v); } JSValue JS_DupValue(JSContext *ctx, JSValueConst v) { return js_dup(v); } JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v) { return js_dup(v); } static void js_trigger_gc(JSRuntime *rt, size_t size) { bool force_gc; #ifdef FORCE_GC_AT_MALLOC force_gc = true; #else force_gc = ((rt->malloc_state.malloc_size + size) > rt->malloc_gc_threshold); #endif if (force_gc) { #ifdef ENABLE_DUMPS // JS_DUMP_GC if (check_dump_flag(rt, JS_DUMP_GC)) { printf("GC: size=%zd\n", rt->malloc_state.malloc_size); } #endif JS_RunGC(rt); rt->malloc_gc_threshold = rt->malloc_state.malloc_size + (rt->malloc_state.malloc_size >> 1); } } static size_t js_malloc_usable_size_unknown(const void *ptr) { return 0; } void *js_calloc_rt(JSRuntime *rt, size_t count, size_t size) { void *ptr; JSMallocState *s; /* Do not allocate zero bytes: behavior is platform dependent */ assert(count != 0 && size != 0); if (size > 0) if (unlikely(count != (count * size) / size)) return NULL; s = &rt->malloc_state; /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */ if (unlikely(s->malloc_size + (count * size) > s->malloc_limit - 1)) return NULL; ptr = rt->mf.js_calloc(s->opaque, count, size); if (!ptr) return NULL; s->malloc_count++; s->malloc_size += rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD; return ptr; } void *js_malloc_rt(JSRuntime *rt, size_t size) { void *ptr; JSMallocState *s; /* Do not allocate zero bytes: behavior is platform dependent */ assert(size != 0); s = &rt->malloc_state; /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */ if (unlikely(s->malloc_size + size > s->malloc_limit - 1)) return NULL; ptr = rt->mf.js_malloc(s->opaque, size); if (!ptr) return NULL; s->malloc_count++; s->malloc_size += rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD; return ptr; } void js_free_rt(JSRuntime *rt, void *ptr) { JSMallocState *s; if (!ptr) return; s = &rt->malloc_state; s->malloc_count--; s->malloc_size -= rt->mf.js_malloc_usable_size(ptr) + MALLOC_OVERHEAD; rt->mf.js_free(s->opaque, ptr); } void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size) { size_t old_size; JSMallocState *s; if (!ptr) { if (size == 0) return NULL; return js_malloc_rt(rt, size); } if (unlikely(size == 0)) { js_free_rt(rt, ptr); return NULL; } old_size = rt->mf.js_malloc_usable_size(ptr); s = &rt->malloc_state; /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */ if (s->malloc_size + size - old_size > s->malloc_limit - 1) return NULL; ptr = rt->mf.js_realloc(s->opaque, ptr, size); if (!ptr) return NULL; s->malloc_size += rt->mf.js_malloc_usable_size(ptr) - old_size; return ptr; } size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr) { return rt->mf.js_malloc_usable_size(ptr); } /** * This used to be implemented as malloc + memset, but using calloc * yields better performance in initial, bursty allocations, something useful * for QuickJS. * * More information: https://github.com/quickjs-ng/quickjs/pull/519 */ void *js_mallocz_rt(JSRuntime *rt, size_t size) { return js_calloc_rt(rt, 1, size); } /* Throw out of memory in case of error */ void *js_calloc(JSContext *ctx, size_t count, size_t size) { void *ptr; ptr = js_calloc_rt(ctx->rt, count, size); if (unlikely(!ptr)) { JS_ThrowOutOfMemory(ctx); return NULL; } return ptr; } /* Throw out of memory in case of error */ void *js_malloc(JSContext *ctx, size_t size) { void *ptr; ptr = js_malloc_rt(ctx->rt, size); if (unlikely(!ptr)) { JS_ThrowOutOfMemory(ctx); return NULL; } return ptr; } /* Throw out of memory in case of error */ void *js_mallocz(JSContext *ctx, size_t size) { void *ptr; ptr = js_mallocz_rt(ctx->rt, size); if (unlikely(!ptr)) { JS_ThrowOutOfMemory(ctx); return NULL; } return ptr; } void js_free(JSContext *ctx, void *ptr) { js_free_rt(ctx->rt, ptr); } /* Throw out of memory in case of error */ void *js_realloc(JSContext *ctx, void *ptr, size_t size) { void *ret; ret = js_realloc_rt(ctx->rt, ptr, size); if (unlikely(!ret && size != 0)) { JS_ThrowOutOfMemory(ctx); return NULL; } return ret; } /* store extra allocated size in *pslack if successful */ void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack) { void *ret; ret = js_realloc_rt(ctx->rt, ptr, size); if (unlikely(!ret && size != 0)) { JS_ThrowOutOfMemory(ctx); return NULL; } if (pslack) { size_t new_size = js_malloc_usable_size_rt(ctx->rt, ret); *pslack = (new_size > size) ? new_size - size : 0; } return ret; } size_t js_malloc_usable_size(JSContext *ctx, const void *ptr) { return js_malloc_usable_size_rt(ctx->rt, ptr); } /* Throw out of memory exception in case of error */ char *js_strndup(JSContext *ctx, const char *s, size_t n) { char *ptr; ptr = js_malloc(ctx, n + 1); if (ptr) { memcpy(ptr, s, n); ptr[n] = '\0'; } return ptr; } char *js_strdup(JSContext *ctx, const char *str) { return js_strndup(ctx, str, strlen(str)); } static no_inline int js_realloc_array(JSContext *ctx, void **parray, int elem_size, int *psize, int req_size) { int new_size; size_t slack; void *new_array; /* XXX: potential arithmetic overflow */ new_size = max_int(req_size, *psize * 3 / 2); new_array = js_realloc2(ctx, *parray, new_size * elem_size, &slack); if (!new_array) return -1; new_size += slack / elem_size; *psize = new_size; *parray = new_array; return 0; } /* resize the array and update its size if req_size > *psize */ static inline int js_resize_array(JSContext *ctx, void **parray, int elem_size, int *psize, int req_size) { if (unlikely(req_size > *psize)) return js_realloc_array(ctx, parray, elem_size, psize, req_size); else return 0; } static void *js_dbuf_realloc(void *ctx, void *ptr, size_t size) { return js_realloc(ctx, ptr, size); } static inline void js_dbuf_init(JSContext *ctx, DynBuf *s) { dbuf_init2(s, ctx, js_dbuf_realloc); } static inline int is_digit(int c) { return c >= '0' && c <= '9'; } static inline int string_get(JSString *p, int idx) { return p->is_wide_char ? str16(p)[idx] : str8(p)[idx]; } typedef struct JSClassShortDef { JSAtom class_name; JSClassFinalizer *finalizer; JSClassGCMark *gc_mark; } JSClassShortDef; static JSClassShortDef const js_std_class_def[] = { { JS_ATOM_Object, NULL, NULL }, /* JS_CLASS_OBJECT */ { JS_ATOM_Array, js_array_finalizer, js_array_mark }, /* JS_CLASS_ARRAY */ { JS_ATOM_Error, NULL, NULL }, /* JS_CLASS_ERROR */ { JS_ATOM_Number, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_NUMBER */ { JS_ATOM_String, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_STRING */ { JS_ATOM_Boolean, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BOOLEAN */ { JS_ATOM_Symbol, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_SYMBOL */ { JS_ATOM_Arguments, js_array_finalizer, js_array_mark }, /* JS_CLASS_ARGUMENTS */ { JS_ATOM_Arguments, NULL, NULL }, /* JS_CLASS_MAPPED_ARGUMENTS */ { JS_ATOM_Date, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_DATE */ { JS_ATOM_Object, NULL, NULL }, /* JS_CLASS_MODULE_NS */ { JS_ATOM_Function, js_c_function_finalizer, js_c_function_mark }, /* JS_CLASS_C_FUNCTION */ { JS_ATOM_Function, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_BYTECODE_FUNCTION */ { JS_ATOM_Function, js_bound_function_finalizer, js_bound_function_mark }, /* JS_CLASS_BOUND_FUNCTION */ { JS_ATOM_Function, js_c_function_data_finalizer, js_c_function_data_mark }, /* JS_CLASS_C_FUNCTION_DATA */ { JS_ATOM_GeneratorFunction, js_bytecode_function_finalizer, js_bytecode_function_mark }, /* JS_CLASS_GENERATOR_FUNCTION */ { JS_ATOM_ForInIterator, js_for_in_iterator_finalizer, js_for_in_iterator_mark }, /* JS_CLASS_FOR_IN_ITERATOR */ { JS_ATOM_RegExp, js_regexp_finalizer, NULL }, /* JS_CLASS_REGEXP */ { JS_ATOM_ArrayBuffer, js_array_buffer_finalizer, NULL }, /* JS_CLASS_ARRAY_BUFFER */ { JS_ATOM_SharedArrayBuffer, js_array_buffer_finalizer, NULL }, /* JS_CLASS_SHARED_ARRAY_BUFFER */ { JS_ATOM_Uint8ClampedArray, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8C_ARRAY */ { JS_ATOM_Int8Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT8_ARRAY */ { JS_ATOM_Uint8Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT8_ARRAY */ { JS_ATOM_Int16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT16_ARRAY */ { JS_ATOM_Uint16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT16_ARRAY */ { JS_ATOM_Int32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_INT32_ARRAY */ { JS_ATOM_Uint32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_UINT32_ARRAY */ { JS_ATOM_BigInt64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_BIG_INT64_ARRAY */ { JS_ATOM_BigUint64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_BIG_UINT64_ARRAY */ { JS_ATOM_Float16Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT16_ARRAY */ { JS_ATOM_Float32Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT32_ARRAY */ { JS_ATOM_Float64Array, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_FLOAT64_ARRAY */ { JS_ATOM_DataView, js_typed_array_finalizer, js_typed_array_mark }, /* JS_CLASS_DATAVIEW */ { JS_ATOM_BigInt, js_object_data_finalizer, js_object_data_mark }, /* JS_CLASS_BIG_INT */ { JS_ATOM_Map, js_map_finalizer, js_map_mark }, /* JS_CLASS_MAP */ { JS_ATOM_Set, js_map_finalizer, js_map_mark }, /* JS_CLASS_SET */ { JS_ATOM_WeakMap, js_map_finalizer, NULL }, /* JS_CLASS_WEAKMAP */ { JS_ATOM_WeakSet, js_map_finalizer, NULL }, /* JS_CLASS_WEAKSET */ { JS_ATOM_Iterator, NULL, NULL }, /* JS_CLASS_ITERATOR */ { JS_ATOM_IteratorConcat, js_iterator_concat_finalizer, js_iterator_concat_mark }, /* JS_CLASS_ITERATOR_CONCAT */ { JS_ATOM_IteratorHelper, js_iterator_helper_finalizer, js_iterator_helper_mark }, /* JS_CLASS_ITERATOR_HELPER */ { JS_ATOM_IteratorWrap, js_iterator_wrap_finalizer, js_iterator_wrap_mark }, /* JS_CLASS_ITERATOR_WRAP */ { JS_ATOM_Map_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_MAP_ITERATOR */ { JS_ATOM_Set_Iterator, js_map_iterator_finalizer, js_map_iterator_mark }, /* JS_CLASS_SET_ITERATOR */ { JS_ATOM_Array_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_ARRAY_ITERATOR */ { JS_ATOM_String_Iterator, js_array_iterator_finalizer, js_array_iterator_mark }, /* JS_CLASS_STRING_ITERATOR */ { JS_ATOM_RegExp_String_Iterator, js_regexp_string_iterator_finalizer, js_regexp_string_iterator_mark }, /* JS_CLASS_REGEXP_STRING_ITERATOR */ { JS_ATOM_Generator, js_generator_finalizer, js_generator_mark }, /* JS_CLASS_GENERATOR */ }; static int init_class_range(JSRuntime *rt, JSClassShortDef const *tab, int start, int count) { JSClassDef cm_s, *cm = &cm_s; int i, class_id; for(i = 0; i < count; i++) { class_id = i + start; memset(cm, 0, sizeof(*cm)); cm->finalizer = tab[i].finalizer; cm->gc_mark = tab[i].gc_mark; if (JS_NewClass1(rt, class_id, cm, tab[i].class_name) < 0) return -1; } return 0; } /* Uses code from LLVM project. */ static inline uintptr_t js_get_stack_pointer(void) { #if defined(__clang__) || defined(__GNUC__) return (uintptr_t)__builtin_frame_address(0); #elif defined(_MSC_VER) return (uintptr_t)_AddressOfReturnAddress(); #else char CharOnStack = 0; // The volatile store here is intended to escape the local variable, to // prevent the compiler from optimizing CharOnStack into anything other // than a char on the stack. // // Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19. char *volatile Ptr = &CharOnStack; return (uintptr_t) Ptr; #endif } static inline bool js_check_stack_overflow(JSRuntime *rt, size_t alloca_size) { uintptr_t sp; sp = js_get_stack_pointer() - alloca_size; return unlikely(sp < rt->stack_limit); } JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque) { JSRuntime *rt; JSMallocState ms; memset(&ms, 0, sizeof(ms)); ms.opaque = opaque; ms.malloc_limit = 0; rt = mf->js_calloc(opaque, 1, sizeof(JSRuntime)); if (!rt) return NULL; rt->mf = *mf; if (!rt->mf.js_malloc_usable_size) { /* use dummy function if none provided */ rt->mf.js_malloc_usable_size = js_malloc_usable_size_unknown; } /* Inline what js_malloc_rt does since we cannot use it here. */ ms.malloc_count++; ms.malloc_size += rt->mf.js_malloc_usable_size(rt) + MALLOC_OVERHEAD; rt->malloc_state = ms; rt->malloc_gc_threshold = 256 * 1024; init_list_head(&rt->context_list); init_list_head(&rt->gc_obj_list); init_list_head(&rt->gc_zero_ref_count_list); rt->gc_phase = JS_GC_PHASE_NONE; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS init_list_head(&rt->string_list); #endif init_list_head(&rt->job_list); if (JS_InitAtoms(rt)) goto fail; /* create the object, array and function classes */ if (init_class_range(rt, js_std_class_def, JS_CLASS_OBJECT, countof(js_std_class_def)) < 0) goto fail; rt->class_array[JS_CLASS_ARGUMENTS].exotic = &js_arguments_exotic_methods; rt->class_array[JS_CLASS_STRING].exotic = &js_string_exotic_methods; rt->class_array[JS_CLASS_MODULE_NS].exotic = &js_module_ns_exotic_methods; rt->class_array[JS_CLASS_C_FUNCTION].call = js_call_c_function; rt->class_array[JS_CLASS_C_FUNCTION_DATA].call = js_call_c_function_data; rt->class_array[JS_CLASS_BOUND_FUNCTION].call = js_call_bound_function; rt->class_array[JS_CLASS_GENERATOR_FUNCTION].call = js_call_generator_function; if (init_shape_hash(rt)) goto fail; rt->js_class_id_alloc = JS_CLASS_INIT_COUNT; rt->stack_size = JS_DEFAULT_STACK_SIZE; #ifdef __wasi__ rt->stack_size = 0; #endif JS_UpdateStackTop(rt); rt->current_exception = JS_UNINITIALIZED; return rt; fail: JS_FreeRuntime(rt); return NULL; } void *JS_GetRuntimeOpaque(JSRuntime *rt) { return rt->user_opaque; } void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque) { rt->user_opaque = opaque; } int JS_AddRuntimeFinalizer(JSRuntime *rt, JSRuntimeFinalizer *finalizer, void *arg) { JSRuntimeFinalizerState *fs = js_malloc_rt(rt, sizeof(*fs)); if (!fs) return -1; fs->next = rt->finalizers; fs->finalizer = finalizer; fs->arg = arg; rt->finalizers = fs; return 0; } static void *js_def_calloc(void *opaque, size_t count, size_t size) { return calloc(count, size); } static void *js_def_malloc(void *opaque, size_t size) { return malloc(size); } static void js_def_free(void *opaque, void *ptr) { free(ptr); } static void *js_def_realloc(void *opaque, void *ptr, size_t size) { return realloc(ptr, size); } static const JSMallocFunctions def_malloc_funcs = { js_def_calloc, js_def_malloc, js_def_free, js_def_realloc, js__malloc_usable_size }; JSRuntime *JS_NewRuntime(void) { return JS_NewRuntime2(&def_malloc_funcs, NULL); } void JS_SetMemoryLimit(JSRuntime *rt, size_t limit) { rt->malloc_state.malloc_limit = limit; } void JS_SetDumpFlags(JSRuntime *rt, uint64_t flags) { #ifdef ENABLE_DUMPS rt->dump_flags = flags; #endif } uint64_t JS_GetDumpFlags(JSRuntime *rt) { #ifdef ENABLE_DUMPS return rt->dump_flags; #else return 0; #endif } size_t JS_GetGCThreshold(JSRuntime *rt) { return rt->malloc_gc_threshold; } /* use -1 to disable automatic GC */ void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold) { rt->malloc_gc_threshold = gc_threshold; } #define malloc(s) malloc_is_forbidden(s) #define free(p) free_is_forbidden(p) #define realloc(p,s) realloc_is_forbidden(p,s) void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque) { rt->interrupt_handler = cb; rt->interrupt_opaque = opaque; } void JS_SetCanBlock(JSRuntime *rt, bool can_block) { rt->can_block = can_block; } void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, const JSSharedArrayBufferFunctions *sf) { rt->sab_funcs = *sf; } /* return 0 if OK, < 0 if exception */ int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, int argc, JSValueConst *argv) { JSRuntime *rt = ctx->rt; JSJobEntry *e; int i; assert(!rt->in_free); e = js_malloc(ctx, sizeof(*e) + argc * sizeof(JSValue)); if (!e) return -1; e->ctx = ctx; e->job_func = job_func; e->argc = argc; for(i = 0; i < argc; i++) { e->argv[i] = js_dup(argv[i]); } list_add_tail(&e->link, &rt->job_list); return 0; } bool JS_IsJobPending(JSRuntime *rt) { return !list_empty(&rt->job_list); } /* return < 0 if exception, 0 if no job pending, 1 if a job was executed successfully. the context of the job is stored in '*pctx' */ int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx) { JSContext *ctx; JSJobEntry *e; JSValue res; int i, ret; if (list_empty(&rt->job_list)) { *pctx = NULL; return 0; } /* get the first pending job and execute it */ e = list_entry(rt->job_list.next, JSJobEntry, link); list_del(&e->link); ctx = e->ctx; res = e->job_func(e->ctx, e->argc, vc(e->argv)); for(i = 0; i < e->argc; i++) JS_FreeValue(ctx, e->argv[i]); if (JS_IsException(res)) ret = -1; else ret = 1; JS_FreeValue(ctx, res); js_free(ctx, e); *pctx = ctx; return ret; } static inline uint32_t atom_get_free(const JSAtomStruct *p) { return (uintptr_t)p >> 1; } static inline bool atom_is_free(const JSAtomStruct *p) { return (uintptr_t)p & 1; } static inline JSAtomStruct *atom_set_free(uint32_t v) { return (JSAtomStruct *)(((uintptr_t)v << 1) | 1); } /* Note: the string contents are uninitialized */ static JSString *js_alloc_string_rt(JSRuntime *rt, int max_len, int is_wide_char) { JSString *str; str = js_malloc_rt(rt, sizeof(JSString) + (max_len << is_wide_char) + 1 - is_wide_char); if (unlikely(!str)) return NULL; str->header.ref_count = 1; str->is_wide_char = is_wide_char; str->len = max_len; str->kind = JS_STRING_KIND_NORMAL; str->atom_type = 0; str->hash = 0; /* optional but costless */ str->hash_next = 0; /* optional */ #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_add_tail(&str->link, &rt->string_list); #endif return str; } static JSString *js_alloc_string(JSContext *ctx, int max_len, int is_wide_char) { JSString *p; p = js_alloc_string_rt(ctx->rt, max_len, is_wide_char); if (unlikely(!p)) { JS_ThrowOutOfMemory(ctx); return NULL; } return p; } static inline void js_free_string0(JSRuntime *rt, JSString *str); /* same as JS_FreeValueRT() but faster */ static inline void js_free_string(JSRuntime *rt, JSString *str) { if (--str->header.ref_count <= 0) js_free_string0(rt, str); } static inline void js_free_string0(JSRuntime *rt, JSString *str) { if (str->atom_type) { JS_FreeAtomStruct(rt, str); } else { #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_del(&str->link); #endif if (str->kind == JS_STRING_KIND_SLICE) { JSStringSlice *slice = (void *)&str[1]; js_free_string(rt, slice->parent); // safe, recurses only 1 level } js_free_rt(rt, str); } } void JS_SetRuntimeInfo(JSRuntime *rt, const char *s) { if (rt) rt->rt_info = s; } void JS_FreeRuntime(JSRuntime *rt) { struct list_head *el, *el1; int i; rt->in_free = true; JS_FreeValueRT(rt, rt->current_exception); list_for_each_safe(el, el1, &rt->job_list) { JSJobEntry *e = list_entry(el, JSJobEntry, link); for(i = 0; i < e->argc; i++) JS_FreeValueRT(rt, e->argv[i]); js_free_rt(rt, e); } init_list_head(&rt->job_list); JS_RunGC(rt); #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS /* leaking objects */ if (check_dump_flag(rt, JS_DUMP_LEAKS)) { bool header_done; JSGCObjectHeader *p; int count; /* remove the internal refcounts to display only the object referenced externally */ list_for_each(el, &rt->gc_obj_list) { p = list_entry(el, JSGCObjectHeader, link); p->mark = 0; } gc_decref(rt); header_done = false; list_for_each(el, &rt->gc_obj_list) { p = list_entry(el, JSGCObjectHeader, link); if (p->ref_count != 0) { if (!header_done) { printf("Object leaks:\n"); JS_DumpObjectHeader(rt); header_done = true; } JS_DumpGCObject(rt, p); } } count = 0; list_for_each(el, &rt->gc_obj_list) { p = list_entry(el, JSGCObjectHeader, link); if (p->ref_count == 0) { count++; } } if (count != 0) printf("Secondary object leaks: %d\n", count); } #endif assert(list_empty(&rt->gc_obj_list)); /* free the classes */ for(i = 0; i < rt->class_count; i++) { JSClass *cl = &rt->class_array[i]; if (cl->class_id != 0) { JS_FreeAtomRT(rt, cl->class_name); } } js_free_rt(rt, rt->class_array); #ifdef ENABLE_DUMPS // JS_DUMP_ATOM_LEAKS /* only the atoms defined in JS_InitAtoms() should be left */ if (check_dump_flag(rt, JS_DUMP_ATOM_LEAKS)) { bool header_done = false; for(i = 0; i < rt->atom_size; i++) { JSAtomStruct *p = rt->atom_array[i]; if (!atom_is_free(p) /* && p->str*/) { if (i >= JS_ATOM_END || p->header.ref_count != 1) { if (!header_done) { header_done = true; if (rt->rt_info) { printf("%s:1: atom leakage:", rt->rt_info); } else { printf("Atom leaks:\n" " %6s %6s %s\n", "ID", "REFCNT", "NAME"); } } if (rt->rt_info) { printf(" "); } else { printf(" %6u %6u ", i, p->header.ref_count); } switch (p->atom_type) { case JS_ATOM_TYPE_STRING: JS_DumpString(rt, p); break; case JS_ATOM_TYPE_GLOBAL_SYMBOL: printf("Symbol.for("); JS_DumpString(rt, p); printf(")"); break; case JS_ATOM_TYPE_SYMBOL: if (p->hash == JS_ATOM_HASH_SYMBOL) { printf("Symbol("); JS_DumpString(rt, p); printf(")"); } else { printf("Private("); JS_DumpString(rt, p); printf(")"); } break; } if (rt->rt_info) { printf(":%u", p->header.ref_count); } else { printf("\n"); } } } } if (rt->rt_info && header_done) printf("\n"); } #endif /* free the atoms */ for(i = 0; i < rt->atom_size; i++) { JSAtomStruct *p = rt->atom_array[i]; if (!atom_is_free(p)) { #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_del(&p->link); #endif js_free_rt(rt, p); } } js_free_rt(rt, rt->atom_array); js_free_rt(rt, rt->atom_hash); js_free_rt(rt, rt->shape_hash); #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS if (check_dump_flag(rt, JS_DUMP_LEAKS) && !list_empty(&rt->string_list)) { if (rt->rt_info) { printf("%s:1: string leakage:", rt->rt_info); } else { printf("String leaks:\n" " %6s %s\n", "REFCNT", "VALUE"); } list_for_each_safe(el, el1, &rt->string_list) { JSString *str = list_entry(el, JSString, link); if (rt->rt_info) { printf(" "); } else { printf(" %6u ", str->header.ref_count); } JS_DumpString(rt, str); if (rt->rt_info) { printf(":%u", str->header.ref_count); } else { printf("\n"); } list_del(&str->link); js_free_rt(rt, str); } if (rt->rt_info) printf("\n"); } #endif while (rt->finalizers) { JSRuntimeFinalizerState *fs = rt->finalizers; rt->finalizers = fs->next; fs->finalizer(rt, fs->arg); js_free_rt(rt, fs); } #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS if (check_dump_flag(rt, JS_DUMP_LEAKS)) { JSMallocState *s = &rt->malloc_state; if (s->malloc_count > 1) { if (rt->rt_info) printf("%s:1: ", rt->rt_info); printf("Memory leak: %zd bytes lost in %zd block%s\n", s->malloc_size - sizeof(JSRuntime), s->malloc_count - 1, &"s"[s->malloc_count == 2]); } } #endif { JSMallocState *ms = &rt->malloc_state; rt->mf.js_free(ms->opaque, rt); } } JSContext *JS_NewContextRaw(JSRuntime *rt) { JSContext *ctx; int i; ctx = js_mallocz_rt(rt, sizeof(JSContext)); if (!ctx) return NULL; ctx->header.ref_count = 1; add_gc_object(rt, &ctx->header, JS_GC_OBJ_TYPE_JS_CONTEXT); ctx->class_proto = js_malloc_rt(rt, sizeof(ctx->class_proto[0]) * rt->class_count); if (!ctx->class_proto) { js_free_rt(rt, ctx); return NULL; } ctx->rt = rt; list_add_tail(&ctx->link, &rt->context_list); for(i = 0; i < rt->class_count; i++) ctx->class_proto[i] = JS_NULL; ctx->array_ctor = JS_NULL; ctx->iterator_ctor = JS_NULL; ctx->iterator_ctor_getset = JS_NULL; ctx->regexp_ctor = JS_NULL; ctx->promise_ctor = JS_NULL; ctx->error_ctor = JS_NULL; ctx->error_back_trace = JS_UNDEFINED; ctx->error_prepare_stack = JS_UNDEFINED; ctx->error_stack_trace_limit = js_int32(10); init_list_head(&ctx->loaded_modules); JS_AddIntrinsicBasicObjects(ctx); return ctx; } JSContext *JS_NewContext(JSRuntime *rt) { JSContext *ctx; ctx = JS_NewContextRaw(rt); if (!ctx) return NULL; JS_AddIntrinsicBaseObjects(ctx); JS_AddIntrinsicDate(ctx); JS_AddIntrinsicEval(ctx); JS_AddIntrinsicRegExp(ctx); JS_AddIntrinsicJSON(ctx); JS_AddIntrinsicProxy(ctx); JS_AddIntrinsicMapSet(ctx); JS_AddIntrinsicTypedArrays(ctx); JS_AddIntrinsicPromise(ctx); JS_AddIntrinsicBigInt(ctx); JS_AddIntrinsicWeakRef(ctx); JS_AddIntrinsicDOMException(ctx); JS_AddPerformance(ctx); return ctx; } void *JS_GetContextOpaque(JSContext *ctx) { return ctx->user_opaque; } void JS_SetContextOpaque(JSContext *ctx, void *opaque) { ctx->user_opaque = opaque; } /* set the new value and free the old value after (freeing the value can reallocate the object data) */ static inline void set_value(JSContext *ctx, JSValue *pval, JSValue new_val) { JSValue old_val; old_val = *pval; *pval = new_val; JS_FreeValue(ctx, old_val); } void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj) { assert(class_id < ctx->rt->class_count); set_value(ctx, &ctx->class_proto[class_id], obj); } JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id) { assert(class_id < ctx->rt->class_count); return js_dup(ctx->class_proto[class_id]); } JSValue JS_GetFunctionProto(JSContext *ctx) { return js_dup(ctx->function_proto); } typedef enum JSFreeModuleEnum { JS_FREE_MODULE_ALL, JS_FREE_MODULE_NOT_RESOLVED, } JSFreeModuleEnum; /* XXX: would be more efficient with separate module lists */ static void js_free_modules(JSContext *ctx, JSFreeModuleEnum flag) { struct list_head *el, *el1; list_for_each_safe(el, el1, &ctx->loaded_modules) { JSModuleDef *m = list_entry(el, JSModuleDef, link); if (flag == JS_FREE_MODULE_ALL || (flag == JS_FREE_MODULE_NOT_RESOLVED && !m->resolved)) { js_free_module_def(ctx, m); } } } JSContext *JS_DupContext(JSContext *ctx) { ctx->header.ref_count++; return ctx; } /* used by the GC */ static void JS_MarkContext(JSRuntime *rt, JSContext *ctx, JS_MarkFunc *mark_func) { int i; struct list_head *el; /* modules are not seen by the GC, so we directly mark the objects referenced by each module */ list_for_each(el, &ctx->loaded_modules) { JSModuleDef *m = list_entry(el, JSModuleDef, link); js_mark_module_def(rt, m, mark_func); } JS_MarkValue(rt, ctx->global_obj, mark_func); JS_MarkValue(rt, ctx->global_var_obj, mark_func); JS_MarkValue(rt, ctx->throw_type_error, mark_func); JS_MarkValue(rt, ctx->eval_obj, mark_func); JS_MarkValue(rt, ctx->array_proto_values, mark_func); for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) { JS_MarkValue(rt, ctx->native_error_proto[i], mark_func); } JS_MarkValue(rt, ctx->error_ctor, mark_func); JS_MarkValue(rt, ctx->error_back_trace, mark_func); JS_MarkValue(rt, ctx->error_prepare_stack, mark_func); JS_MarkValue(rt, ctx->error_stack_trace_limit, mark_func); for(i = 0; i < rt->class_count; i++) { JS_MarkValue(rt, ctx->class_proto[i], mark_func); } JS_MarkValue(rt, ctx->iterator_ctor, mark_func); JS_MarkValue(rt, ctx->iterator_ctor_getset, mark_func); JS_MarkValue(rt, ctx->async_iterator_proto, mark_func); JS_MarkValue(rt, ctx->promise_ctor, mark_func); JS_MarkValue(rt, ctx->array_ctor, mark_func); JS_MarkValue(rt, ctx->regexp_ctor, mark_func); JS_MarkValue(rt, ctx->function_ctor, mark_func); JS_MarkValue(rt, ctx->function_proto, mark_func); if (ctx->array_shape) mark_func(rt, &ctx->array_shape->header); } void JS_FreeContext(JSContext *ctx) { JSRuntime *rt = ctx->rt; int i; if (--ctx->header.ref_count > 0) return; assert(ctx->header.ref_count == 0); #ifdef ENABLE_DUMPS // JS_DUMP_ATOMS if (check_dump_flag(rt, JS_DUMP_ATOMS)) JS_DumpAtoms(ctx->rt); #endif #ifdef ENABLE_DUMPS // JS_DUMP_SHAPES if (check_dump_flag(rt, JS_DUMP_SHAPES)) JS_DumpShapes(ctx->rt); #endif #ifdef ENABLE_DUMPS // JS_DUMP_OBJECTS if (check_dump_flag(rt, JS_DUMP_OBJECTS)) { struct list_head *el; JSGCObjectHeader *p; printf("JSObjects: {\n"); JS_DumpObjectHeader(ctx->rt); list_for_each(el, &rt->gc_obj_list) { p = list_entry(el, JSGCObjectHeader, link); JS_DumpGCObject(rt, p); } printf("}\n"); } #endif #ifdef ENABLE_DUMPS // JS_DUMP_MEM if (check_dump_flag(rt, JS_DUMP_MEM)) { JSMemoryUsage stats; JS_ComputeMemoryUsage(rt, &stats); JS_DumpMemoryUsage(stdout, &stats, rt); } #endif js_free_modules(ctx, JS_FREE_MODULE_ALL); JS_FreeValue(ctx, ctx->global_obj); JS_FreeValue(ctx, ctx->global_var_obj); JS_FreeValue(ctx, ctx->throw_type_error); JS_FreeValue(ctx, ctx->eval_obj); JS_FreeValue(ctx, ctx->array_proto_values); for(i = 0; i < JS_NATIVE_ERROR_COUNT; i++) { JS_FreeValue(ctx, ctx->native_error_proto[i]); } JS_FreeValue(ctx, ctx->error_ctor); JS_FreeValue(ctx, ctx->error_back_trace); JS_FreeValue(ctx, ctx->error_prepare_stack); JS_FreeValue(ctx, ctx->error_stack_trace_limit); for(i = 0; i < rt->class_count; i++) { JS_FreeValue(ctx, ctx->class_proto[i]); } js_free_rt(rt, ctx->class_proto); JS_FreeValue(ctx, ctx->iterator_ctor); JS_FreeValue(ctx, ctx->iterator_ctor_getset); JS_FreeValue(ctx, ctx->async_iterator_proto); JS_FreeValue(ctx, ctx->promise_ctor); JS_FreeValue(ctx, ctx->array_ctor); JS_FreeValue(ctx, ctx->regexp_ctor); JS_FreeValue(ctx, ctx->function_ctor); JS_FreeValue(ctx, ctx->function_proto); js_free_shape_null(ctx->rt, ctx->array_shape); list_del(&ctx->link); remove_gc_object(&ctx->header); js_free_rt(ctx->rt, ctx); } JSRuntime *JS_GetRuntime(JSContext *ctx) { return ctx->rt; } static void update_stack_limit(JSRuntime *rt) { #if defined(__wasi__) rt->stack_limit = 0; /* no limit */ #else if (rt->stack_size == 0) { rt->stack_limit = 0; /* no limit */ } else { rt->stack_limit = rt->stack_top - rt->stack_size; } #endif } void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size) { rt->stack_size = stack_size; update_stack_limit(rt); } void JS_UpdateStackTop(JSRuntime *rt) { rt->stack_top = js_get_stack_pointer(); update_stack_limit(rt); } static inline bool is_strict_mode(JSContext *ctx) { JSStackFrame *sf = ctx->rt->current_stack_frame; return sf && sf->is_strict_mode; } /* JSAtom support */ #define JS_ATOM_TAG_INT (1U << 31) #define JS_ATOM_MAX_INT (JS_ATOM_TAG_INT - 1) #define JS_ATOM_MAX ((1U << 30) - 1) /* return the max count from the hash size */ #define JS_ATOM_COUNT_RESIZE(n) ((n) * 2) static inline bool __JS_AtomIsConst(JSAtom v) { return (int32_t)v < JS_ATOM_END; } static inline bool __JS_AtomIsTaggedInt(JSAtom v) { return (v & JS_ATOM_TAG_INT) != 0; } static inline JSAtom __JS_AtomFromUInt32(uint32_t v) { return v | JS_ATOM_TAG_INT; } static inline uint32_t __JS_AtomToUInt32(JSAtom atom) { return atom & ~JS_ATOM_TAG_INT; } static inline int is_num(int c) { return c >= '0' && c <= '9'; } /* return true if the string is a number n with 0 <= n <= 2^32-1 */ static inline bool is_num_string(uint32_t *pval, JSString *p) { uint32_t n; uint64_t n64; int c, i, len; len = p->len; if (len == 0 || len > 10) return false; c = string_get(p, 0); if (is_num(c)) { if (c == '0') { if (len != 1) return false; n = 0; } else { n = c - '0'; for(i = 1; i < len; i++) { c = string_get(p, i); if (!is_num(c)) return false; n64 = (uint64_t)n * 10 + (c - '0'); if ((n64 >> 32) != 0) return false; n = n64; } } *pval = n; return true; } else { return false; } } /* XXX: could use faster version ? */ static inline uint32_t hash_string8(const uint8_t *str, size_t len, uint32_t h) { size_t i; for(i = 0; i < len; i++) h = h * 263 + str[i]; return h; } static inline uint32_t hash_string16(const uint16_t *str, size_t len, uint32_t h) { size_t i; for(i = 0; i < len; i++) h = h * 263 + str[i]; return h; } static uint32_t hash_string(JSString *str, uint32_t h) { if (str->is_wide_char) h = hash_string16(str16(str), str->len, h); else h = hash_string8(str8(str), str->len, h); return h; } static __maybe_unused void JS_DumpString(JSRuntime *rt, JSString *p) { int i, c, sep; if (p == NULL) { printf(""); return; } if (p->header.ref_count != 1) printf("%d", p->header.ref_count); if (p->is_wide_char) putchar('L'); sep = '\"'; putchar(sep); for(i = 0; i < p->len; i++) { c = string_get(p, i); if (c == sep || c == '\\') { putchar('\\'); putchar(c); } else if (c >= ' ' && c <= 126) { putchar(c); } else if (c == '\n') { putchar('\\'); putchar('n'); } else { printf("\\u%04x", c); } } putchar(sep); } static __maybe_unused void JS_DumpAtoms(JSRuntime *rt) { JSAtomStruct *p; int h, i; /* This only dumps hashed atoms, not JS_ATOM_TYPE_SYMBOL atoms */ printf("JSAtom count=%d size=%d hash_size=%d:\n", rt->atom_count, rt->atom_size, rt->atom_hash_size); printf("JSAtom hash table: {\n"); for(i = 0; i < rt->atom_hash_size; i++) { h = rt->atom_hash[i]; if (h) { printf(" %d:", i); while (h) { p = rt->atom_array[h]; printf(" "); JS_DumpString(rt, p); h = p->hash_next; } printf("\n"); } } printf("}\n"); printf("JSAtom table: {\n"); for(i = 0; i < rt->atom_size; i++) { p = rt->atom_array[i]; if (!atom_is_free(p)) { printf(" %d: { %d %08x ", i, p->atom_type, p->hash); if (!(p->len == 0 && p->is_wide_char != 0)) JS_DumpString(rt, p); printf(" %d }\n", p->hash_next); } } printf("}\n"); } static int JS_ResizeAtomHash(JSRuntime *rt, int new_hash_size) { JSAtomStruct *p; uint32_t new_hash_mask, h, i, hash_next1, j, *new_hash; assert((new_hash_size & (new_hash_size - 1)) == 0); /* power of two */ new_hash_mask = new_hash_size - 1; new_hash = js_mallocz_rt(rt, sizeof(rt->atom_hash[0]) * new_hash_size); if (!new_hash) return -1; for(i = 0; i < rt->atom_hash_size; i++) { h = rt->atom_hash[i]; while (h != 0) { p = rt->atom_array[h]; hash_next1 = p->hash_next; /* add in new hash table */ j = p->hash & new_hash_mask; p->hash_next = new_hash[j]; new_hash[j] = h; h = hash_next1; } } js_free_rt(rt, rt->atom_hash); rt->atom_hash = new_hash; rt->atom_hash_size = new_hash_size; rt->atom_count_resize = JS_ATOM_COUNT_RESIZE(new_hash_size); // JS_DumpAtoms(rt); return 0; } static int JS_InitAtoms(JSRuntime *rt) { int i, len, atom_type; const char *p; rt->atom_hash_size = 0; rt->atom_hash = NULL; rt->atom_count = 0; rt->atom_size = 0; rt->atom_free_index = 0; if (JS_ResizeAtomHash(rt, 256)) /* there are at least 195 predefined atoms */ return -1; p = js_atom_init; for(i = 1; i < JS_ATOM_END; i++) { if (i == JS_ATOM_Private_brand) atom_type = JS_ATOM_TYPE_PRIVATE; else if (i >= JS_ATOM_Symbol_toPrimitive) atom_type = JS_ATOM_TYPE_SYMBOL; else atom_type = JS_ATOM_TYPE_STRING; len = strlen(p); if (__JS_NewAtomInit(rt, p, len, atom_type) == JS_ATOM_NULL) return -1; p = p + len + 1; } return 0; } static JSAtom JS_DupAtomRT(JSRuntime *rt, JSAtom v) { JSAtomStruct *p; if (!__JS_AtomIsConst(v)) { p = rt->atom_array[v]; p->header.ref_count++; } return v; } JSAtom JS_DupAtom(JSContext *ctx, JSAtom v) { JSRuntime *rt; JSAtomStruct *p; if (!__JS_AtomIsConst(v)) { rt = ctx->rt; p = rt->atom_array[v]; p->header.ref_count++; } return v; } static JSAtomKindEnum JS_AtomGetKind(JSContext *ctx, JSAtom v) { JSRuntime *rt; JSAtomStruct *p; rt = ctx->rt; if (__JS_AtomIsTaggedInt(v)) return JS_ATOM_KIND_STRING; p = rt->atom_array[v]; switch(p->atom_type) { case JS_ATOM_TYPE_STRING: return JS_ATOM_KIND_STRING; case JS_ATOM_TYPE_GLOBAL_SYMBOL: return JS_ATOM_KIND_SYMBOL; case JS_ATOM_TYPE_SYMBOL: switch(p->hash) { case JS_ATOM_HASH_SYMBOL: return JS_ATOM_KIND_SYMBOL; case JS_ATOM_HASH_PRIVATE: return JS_ATOM_KIND_PRIVATE; default: abort(); } default: abort(); } return (JSAtomKindEnum){-1}; // pacify compiler } static JSAtom js_get_atom_index(JSRuntime *rt, JSAtomStruct *p) { uint32_t i = p->hash_next; /* atom_index */ if (p->atom_type != JS_ATOM_TYPE_SYMBOL) { JSAtomStruct *p1; i = rt->atom_hash[p->hash & (rt->atom_hash_size - 1)]; p1 = rt->atom_array[i]; while (p1 != p) { assert(i != 0); i = p1->hash_next; p1 = rt->atom_array[i]; } } return i; } /* string case (internal). Return JS_ATOM_NULL if error. 'str' is freed. */ static JSAtom __JS_NewAtom(JSRuntime *rt, JSString *str, int atom_type) { uint32_t h, h1, i; JSAtomStruct *p; int len; if (atom_type < JS_ATOM_TYPE_SYMBOL) { /* str is not NULL */ if (str->atom_type == atom_type) { /* str is the atom, return its index */ i = js_get_atom_index(rt, str); /* reduce string refcount and increase atom's unless constant */ if (__JS_AtomIsConst(i)) str->header.ref_count--; return i; } /* try and locate an already registered atom */ len = str->len; h = hash_string(str, atom_type); h &= JS_ATOM_HASH_MASK; h1 = h & (rt->atom_hash_size - 1); i = rt->atom_hash[h1]; while (i != 0) { p = rt->atom_array[i]; if (p->hash == h && p->atom_type == atom_type && p->len == len && js_string_memcmp(p, str, len) == 0) { if (!__JS_AtomIsConst(i)) p->header.ref_count++; goto done; } i = p->hash_next; } } else { h1 = 0; /* avoid warning */ if (atom_type == JS_ATOM_TYPE_SYMBOL) { h = JS_ATOM_HASH_SYMBOL; } else { h = JS_ATOM_HASH_PRIVATE; atom_type = JS_ATOM_TYPE_SYMBOL; } } if (rt->atom_free_index == 0) { /* allow new atom entries */ uint32_t new_size, start; JSAtomStruct **new_array; /* alloc new with size progression 3/2: 4 6 9 13 19 28 42 63 94 141 211 316 474 711 1066 1599 2398 3597 5395 8092 preallocating space for predefined atoms (at least 195). */ new_size = max_int(211, rt->atom_size * 3 / 2); if (new_size > JS_ATOM_MAX) goto fail; /* XXX: should use realloc2 to use slack space */ new_array = js_realloc_rt(rt, rt->atom_array, sizeof(*new_array) * new_size); if (!new_array) goto fail; /* Note: the atom 0 is not used */ start = rt->atom_size; if (start == 0) { /* JS_ATOM_NULL entry */ p = js_mallocz_rt(rt, sizeof(JSAtomStruct)); if (!p) { js_free_rt(rt, new_array); goto fail; } p->header.ref_count = 1; /* not refcounted */ p->atom_type = JS_ATOM_TYPE_SYMBOL; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_add_tail(&p->link, &rt->string_list); #endif new_array[0] = p; rt->atom_count++; start = 1; } rt->atom_size = new_size; rt->atom_array = new_array; rt->atom_free_index = start; for(i = start; i < new_size; i++) { uint32_t next; if (i == (new_size - 1)) next = 0; else next = i + 1; rt->atom_array[i] = atom_set_free(next); } } if (str) { if (str->atom_type == 0) { p = str; p->atom_type = atom_type; } else { p = js_malloc_rt(rt, sizeof(JSString) + (str->len << str->is_wide_char) + 1 - str->is_wide_char); if (unlikely(!p)) goto fail; p->header.ref_count = 1; p->is_wide_char = str->is_wide_char; p->len = str->len; p->kind = JS_STRING_KIND_NORMAL; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_add_tail(&p->link, &rt->string_list); #endif memcpy(str8(p), str8(str), (str->len << str->is_wide_char) + 1 - str->is_wide_char); js_free_string(rt, str); } } else { p = js_malloc_rt(rt, sizeof(JSAtomStruct)); /* empty wide string */ if (!p) return JS_ATOM_NULL; p->header.ref_count = 1; p->is_wide_char = 1; /* Hack to represent NULL as a JSString */ p->len = 0; p->kind = JS_STRING_KIND_NORMAL; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_add_tail(&p->link, &rt->string_list); #endif } /* use an already free entry */ i = rt->atom_free_index; rt->atom_free_index = atom_get_free(rt->atom_array[i]); rt->atom_array[i] = p; p->hash = h; p->hash_next = i; /* atom_index */ p->atom_type = atom_type; p->first_weak_ref = NULL; rt->atom_count++; if (atom_type != JS_ATOM_TYPE_SYMBOL) { p->hash_next = rt->atom_hash[h1]; rt->atom_hash[h1] = i; if (unlikely(rt->atom_count >= rt->atom_count_resize)) JS_ResizeAtomHash(rt, rt->atom_hash_size * 2); } // JS_DumpAtoms(rt); return i; fail: i = JS_ATOM_NULL; done: if (str) js_free_string(rt, str); return i; } // XXX: `str` must be pure ASCII. No UTF-8 encoded strings // XXX: `str` must not be the string representation of a small integer static JSAtom __JS_NewAtomInit(JSRuntime *rt, const char *str, int len, int atom_type) { JSString *p; p = js_alloc_string_rt(rt, len, 0); if (!p) return JS_ATOM_NULL; memcpy(str8(p), str, len); str8(p)[len] = '\0'; return __JS_NewAtom(rt, p, atom_type); } // XXX: `str` must be raw 8-bit contents. No UTF-8 encoded strings static JSAtom __JS_FindAtom(JSRuntime *rt, const char *str, size_t len, int atom_type) { uint32_t h, h1, i; JSAtomStruct *p; h = hash_string8((const uint8_t *)str, len, JS_ATOM_TYPE_STRING); h &= JS_ATOM_HASH_MASK; h1 = h & (rt->atom_hash_size - 1); i = rt->atom_hash[h1]; while (i != 0) { p = rt->atom_array[i]; if (p->hash == h && p->atom_type == JS_ATOM_TYPE_STRING && p->len == len && p->is_wide_char == 0 && memcmp(str8(p), str, len) == 0) { if (!__JS_AtomIsConst(i)) p->header.ref_count++; return i; } i = p->hash_next; } return JS_ATOM_NULL; } static void JS_FreeAtomStruct(JSRuntime *rt, JSAtomStruct *p) { uint32_t i = p->hash_next; /* atom_index */ if (p->atom_type != JS_ATOM_TYPE_SYMBOL) { JSAtomStruct *p0, *p1; uint32_t h0; h0 = p->hash & (rt->atom_hash_size - 1); i = rt->atom_hash[h0]; p1 = rt->atom_array[i]; if (p1 == p) { rt->atom_hash[h0] = p1->hash_next; } else { for(;;) { assert(i != 0); p0 = p1; i = p1->hash_next; p1 = rt->atom_array[i]; if (p1 == p) { p0->hash_next = p1->hash_next; break; } } } } /* insert in free atom list */ rt->atom_array[i] = atom_set_free(rt->atom_free_index); rt->atom_free_index = i; if (unlikely(p->first_weak_ref)) { reset_weak_ref(rt, &p->first_weak_ref); } /* free the string structure */ #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_del(&p->link); #endif js_free_rt(rt, p); rt->atom_count--; assert(rt->atom_count >= 0); } static void __JS_FreeAtom(JSRuntime *rt, uint32_t i) { JSAtomStruct *p; p = rt->atom_array[i]; if (--p->header.ref_count > 0) return; JS_FreeAtomStruct(rt, p); } /* Warning: 'p' is freed */ static JSAtom JS_NewAtomStr(JSContext *ctx, JSString *p) { JSRuntime *rt = ctx->rt; uint32_t n; if (is_num_string(&n, p)) { if (n <= JS_ATOM_MAX_INT) { js_free_string(rt, p); return __JS_AtomFromUInt32(n); } } /* XXX: should generate an exception */ return __JS_NewAtom(rt, p, JS_ATOM_TYPE_STRING); } /* `str` may be pure ASCII or UTF-8 encoded */ JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len) { JSValue val; if (len == 0 || !is_digit(*str)) { // TODO(chqrlie): this does not work if `str` has UTF-8 encoded contents // bug example: `({ "\u00c3\u00a9": 1 }).\u00e9` evaluates to `1`. JSAtom atom = __JS_FindAtom(ctx->rt, str, len, JS_ATOM_TYPE_STRING); if (atom) return atom; } val = JS_NewStringLen(ctx, str, len); if (JS_IsException(val)) return JS_ATOM_NULL; return JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(val)); } /* `str` may be pure ASCII or UTF-8 encoded */ JSAtom JS_NewAtom(JSContext *ctx, const char *str) { return JS_NewAtomLen(ctx, str, strlen(str)); } JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n) { if (n <= JS_ATOM_MAX_INT) { return __JS_AtomFromUInt32(n); } else { char buf[16]; size_t len = u32toa(buf, n); JSValue val = js_new_string8_len(ctx, buf, len); if (JS_IsException(val)) return JS_ATOM_NULL; return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val), JS_ATOM_TYPE_STRING); } } static JSAtom JS_NewAtomInt64(JSContext *ctx, int64_t n) { if ((uint64_t)n <= JS_ATOM_MAX_INT) { return __JS_AtomFromUInt32((uint32_t)n); } else { char buf[24]; size_t len = i64toa(buf, n); JSValue val = js_new_string8_len(ctx, buf, len); if (JS_IsException(val)) return JS_ATOM_NULL; return __JS_NewAtom(ctx->rt, JS_VALUE_GET_STRING(val), JS_ATOM_TYPE_STRING); } } /* 'p' is freed */ static JSValue JS_NewSymbolInternal(JSContext *ctx, JSString *p, int atom_type) { JSRuntime *rt = ctx->rt; JSAtom atom; atom = __JS_NewAtom(rt, p, atom_type); if (atom == JS_ATOM_NULL) return JS_ThrowOutOfMemory(ctx); return JS_MKPTR(JS_TAG_SYMBOL, rt->atom_array[atom]); } /* descr must be a non-numeric string atom */ static JSValue JS_NewSymbolFromAtom(JSContext *ctx, JSAtom descr, int atom_type) { JSRuntime *rt = ctx->rt; JSString *p; assert(!__JS_AtomIsTaggedInt(descr)); assert(descr < rt->atom_size); p = rt->atom_array[descr]; js_dup(JS_MKPTR(JS_TAG_STRING, p)); return JS_NewSymbolInternal(ctx, p, atom_type); } /* `description` may be pure ASCII or UTF-8 encoded */ JSValue JS_NewSymbol(JSContext *ctx, const char *description, bool is_global) { JSAtom atom = JS_NewAtom(ctx, description); if (atom == JS_ATOM_NULL) return JS_EXCEPTION; return JS_NewSymbolFromAtom(ctx, atom, is_global ? JS_ATOM_TYPE_GLOBAL_SYMBOL : JS_ATOM_TYPE_SYMBOL); } #define ATOM_GET_STR_BUF_SIZE 64 static const char *JS_AtomGetStrRT(JSRuntime *rt, char *buf, int buf_size, JSAtom atom) { if (__JS_AtomIsTaggedInt(atom)) { snprintf(buf, buf_size, "%u", __JS_AtomToUInt32(atom)); } else if (atom == JS_ATOM_NULL) { snprintf(buf, buf_size, ""); } else if (atom >= rt->atom_size) { assert(atom < rt->atom_size); snprintf(buf, buf_size, "", atom); } else { JSAtomStruct *p = rt->atom_array[atom]; *buf = '\0'; if (atom_is_free(p)) { snprintf(buf, buf_size, "", atom); } else if (p != NULL) { JSString *str = p; if (str->is_wide_char) { /* encode surrogates correctly */ utf8_encode_buf16(buf, buf_size, str16(str), str->len); } else { utf8_encode_buf8(buf, buf_size, str8(str), str->len); } } } return buf; } static const char *JS_AtomGetStr(JSContext *ctx, char *buf, int buf_size, JSAtom atom) { return JS_AtomGetStrRT(ctx->rt, buf, buf_size, atom); } static JSValue __JS_AtomToValue(JSContext *ctx, JSAtom atom, bool force_string) { char buf[ATOM_GET_STR_BUF_SIZE]; if (__JS_AtomIsTaggedInt(atom)) { size_t len = u32toa(buf, __JS_AtomToUInt32(atom)); return js_new_string8_len(ctx, buf, len); } else { JSRuntime *rt = ctx->rt; JSAtomStruct *p; assert(atom < rt->atom_size); p = rt->atom_array[atom]; if (p->atom_type == JS_ATOM_TYPE_STRING) { goto ret_string; } else if (force_string) { if (p->len == 0 && p->is_wide_char != 0) { /* no description string */ p = rt->atom_array[JS_ATOM_empty_string]; } ret_string: return js_dup(JS_MKPTR(JS_TAG_STRING, p)); } else { return js_dup(JS_MKPTR(JS_TAG_SYMBOL, p)); } } } JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom) { return __JS_AtomToValue(ctx, atom, false); } JSValue JS_AtomToString(JSContext *ctx, JSAtom atom) { return __JS_AtomToValue(ctx, atom, true); } /* return true if the atom is an array index (i.e. 0 <= index <= 2^32-2 and return its value */ static bool JS_AtomIsArrayIndex(JSContext *ctx, uint32_t *pval, JSAtom atom) { if (__JS_AtomIsTaggedInt(atom)) { *pval = __JS_AtomToUInt32(atom); return true; } else { JSRuntime *rt = ctx->rt; JSAtomStruct *p; uint32_t val; assert(atom < rt->atom_size); p = rt->atom_array[atom]; if (p->atom_type == JS_ATOM_TYPE_STRING && is_num_string(&val, p) && val != -1) { *pval = val; return true; } else { *pval = 0; return false; } } } /* This test must be fast if atom is not a numeric index (e.g. a method name). Return JS_UNDEFINED if not a numeric index. JS_EXCEPTION can also be returned. */ static JSValue JS_AtomIsNumericIndex1(JSContext *ctx, JSAtom atom) { JSRuntime *rt = ctx->rt; JSAtomStruct *p1; JSString *p; int c, len, ret; JSValue num, str; if (__JS_AtomIsTaggedInt(atom)) return js_int32(__JS_AtomToUInt32(atom)); assert(atom < rt->atom_size); p1 = rt->atom_array[atom]; if (p1->atom_type != JS_ATOM_TYPE_STRING) return JS_UNDEFINED; p = p1; len = p->len; if (p->is_wide_char) { const uint16_t *r = str16(p), *r_end = str16(p) + len; if (r >= r_end) return JS_UNDEFINED; c = *r; if (c == '-') { if (r >= r_end) return JS_UNDEFINED; r++; c = *r; /* -0 case is specific */ if (c == '0' && len == 2) goto minus_zero; } /* XXX: should test NaN, but the tests do not check it */ if (!is_num(c)) { /* XXX: String should be normalized, therefore 8-bit only */ const uint16_t nfinity16[7] = { 'n', 'f', 'i', 'n', 'i', 't', 'y' }; if (!(c =='I' && (r_end - r) == 8 && !memcmp(r + 1, nfinity16, sizeof(nfinity16)))) return JS_UNDEFINED; } } else { const uint8_t *r = str8(p), *r_end = str8(p) + len; if (r >= r_end) return JS_UNDEFINED; c = *r; if (c == '-') { if (r >= r_end) return JS_UNDEFINED; r++; c = *r; /* -0 case is specific */ if (c == '0' && len == 2) { minus_zero: return js_float64(-0.0); } } if (!is_num(c)) { if (!(c =='I' && (r_end - r) == 8 && !memcmp(r + 1, "nfinity", 7))) return JS_UNDEFINED; } } /* this is ECMA CanonicalNumericIndexString primitive */ num = JS_ToNumber(ctx, JS_MKPTR(JS_TAG_STRING, p)); if (JS_IsException(num)) return num; str = JS_ToString(ctx, num); if (JS_IsException(str)) { JS_FreeValue(ctx, num); return str; } ret = js_string_eq(p, JS_VALUE_GET_STRING(str)); JS_FreeValue(ctx, str); if (ret) { return num; } else { JS_FreeValue(ctx, num); return JS_UNDEFINED; } } /* return -1 if exception or true/false */ static int JS_AtomIsNumericIndex(JSContext *ctx, JSAtom atom) { JSValue num; num = JS_AtomIsNumericIndex1(ctx, atom); if (likely(JS_IsUndefined(num))) return false; if (JS_IsException(num)) return -1; JS_FreeValue(ctx, num); return true; } void JS_FreeAtom(JSContext *ctx, JSAtom v) { if (!__JS_AtomIsConst(v)) __JS_FreeAtom(ctx->rt, v); } void JS_FreeAtomRT(JSRuntime *rt, JSAtom v) { if (!__JS_AtomIsConst(v)) __JS_FreeAtom(rt, v); } /* return true if 'v' is a symbol with a string description */ static bool JS_AtomSymbolHasDescription(JSContext *ctx, JSAtom v) { JSRuntime *rt; JSAtomStruct *p; rt = ctx->rt; if (__JS_AtomIsTaggedInt(v)) return false; p = rt->atom_array[v]; return (((p->atom_type == JS_ATOM_TYPE_SYMBOL && p->hash == JS_ATOM_HASH_SYMBOL) || p->atom_type == JS_ATOM_TYPE_GLOBAL_SYMBOL) && !(p->len == 0 && p->is_wide_char != 0)); } static __maybe_unused void print_atom(JSContext *ctx, JSAtom atom) { char buf[ATOM_GET_STR_BUF_SIZE]; const char *p; int i; /* XXX: should handle embedded null characters */ /* XXX: should move encoding code to JS_AtomGetStr */ p = JS_AtomGetStr(ctx, buf, sizeof(buf), atom); for (i = 0; p[i]; i++) { int c = (unsigned char)p[i]; if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_' || c == '$') || (c >= '0' && c <= '9' && i > 0))) break; } if (i > 0 && p[i] == '\0') { printf("%s", p); } else { putchar('"'); printf("%.*s", i, p); for (; p[i]; i++) { int c = (unsigned char)p[i]; if (c == '\"' || c == '\\') { putchar('\\'); putchar(c); } else if (c >= ' ' && c <= 126) { putchar(c); } else if (c == '\n') { putchar('\\'); putchar('n'); } else { printf("\\u%04x", c); } } putchar('\"'); } } /* free with JS_FreeCString() */ const char *JS_AtomToCStringLen(JSContext *ctx, size_t *plen, JSAtom atom) { JSValue str; const char *cstr; str = JS_AtomToString(ctx, atom); if (JS_IsException(str)) { if (plen) *plen = 0; return NULL; } cstr = JS_ToCStringLen(ctx, plen, str); JS_FreeValue(ctx, str); return cstr; } #ifndef QJS_DISABLE_PARSER /* return a string atom containing name concatenated with str1 */ /* `str1` may be pure ASCII or UTF-8 encoded */ // TODO(chqrlie): use string concatenation instead of UTF-8 conversion static JSAtom js_atom_concat_str(JSContext *ctx, JSAtom name, const char *str1) { JSValue str; JSAtom atom; const char *cstr; char *cstr2; size_t len, len1; str = JS_AtomToString(ctx, name); if (JS_IsException(str)) return JS_ATOM_NULL; cstr = JS_ToCStringLen(ctx, &len, str); if (!cstr) goto fail; len1 = strlen(str1); cstr2 = js_malloc(ctx, len + len1 + 1); if (!cstr2) goto fail; memcpy(cstr2, cstr, len); memcpy(cstr2 + len, str1, len1); cstr2[len + len1] = '\0'; atom = JS_NewAtomLen(ctx, cstr2, len + len1); js_free(ctx, cstr2); JS_FreeCString(ctx, cstr); JS_FreeValue(ctx, str); return atom; fail: JS_FreeCString(ctx, cstr); JS_FreeValue(ctx, str); return JS_ATOM_NULL; } static JSAtom js_atom_concat_num(JSContext *ctx, JSAtom name, uint32_t n) { char buf[16]; size_t len; len = u32toa(buf, n); buf[len] = '\0'; return js_atom_concat_str(ctx, name, buf); } #endif // QJS_DISABLE_PARSER static inline bool JS_IsEmptyString(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_STRING && JS_VALUE_GET_STRING(v)->len == 0; } /* JSClass support */ /* a new class ID is allocated if *pclass_id == 0, otherwise *pclass_id is left unchanged */ JSClassID JS_NewClassID(JSRuntime *rt, JSClassID *pclass_id) { JSClassID class_id = *pclass_id; if (class_id == 0) { class_id = rt->js_class_id_alloc++; *pclass_id = class_id; } return class_id; } JSClassID JS_GetClassID(JSValueConst v) { JSObject *p; if (JS_VALUE_GET_TAG(v) != JS_TAG_OBJECT) return JS_INVALID_CLASS_ID; p = JS_VALUE_GET_OBJ(v); return p->class_id; } bool JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id) { return (class_id < rt->class_count && rt->class_array[class_id].class_id != 0); } /* create a new object internal class. Return -1 if error, 0 if OK. The finalizer can be NULL if none is needed. */ static int JS_NewClass1(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def, JSAtom name) { int new_size, i; JSClass *cl, *new_class_array; struct list_head *el; if (class_id >= (1 << 16)) return -1; if (class_id < rt->class_count && rt->class_array[class_id].class_id != 0) return -1; if (class_id >= rt->class_count) { new_size = max_int(JS_CLASS_INIT_COUNT, max_int(class_id + 1, rt->class_count * 3 / 2)); /* reallocate the context class prototype array, if any */ list_for_each(el, &rt->context_list) { JSContext *ctx = list_entry(el, JSContext, link); JSValue *new_tab; new_tab = js_realloc_rt(rt, ctx->class_proto, sizeof(ctx->class_proto[0]) * new_size); if (!new_tab) return -1; for(i = rt->class_count; i < new_size; i++) new_tab[i] = JS_NULL; ctx->class_proto = new_tab; } /* reallocate the class array */ new_class_array = js_realloc_rt(rt, rt->class_array, sizeof(JSClass) * new_size); if (!new_class_array) return -1; memset(new_class_array + rt->class_count, 0, (new_size - rt->class_count) * sizeof(JSClass)); rt->class_array = new_class_array; rt->class_count = new_size; } cl = &rt->class_array[class_id]; cl->class_id = class_id; cl->class_name = JS_DupAtomRT(rt, name); cl->finalizer = class_def->finalizer; cl->gc_mark = class_def->gc_mark; cl->call = class_def->call; cl->exotic = class_def->exotic; return 0; } int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def) { int ret, len; JSAtom name; // XXX: class_def->class_name must be raw 8-bit contents. No UTF-8 encoded strings len = strlen(class_def->class_name); name = __JS_FindAtom(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING); if (name == JS_ATOM_NULL) { name = __JS_NewAtomInit(rt, class_def->class_name, len, JS_ATOM_TYPE_STRING); if (name == JS_ATOM_NULL) return -1; } ret = JS_NewClass1(rt, class_id, class_def, name); JS_FreeAtomRT(rt, name); return ret; } static inline JSValue js_empty_string(JSRuntime *rt) { JSAtomStruct *p = rt->atom_array[JS_ATOM_empty_string]; return js_dup(JS_MKPTR(JS_TAG_STRING, p)); } // XXX: `buf` contains raw 8-bit data, no UTF-8 decoding is performed // XXX: no special case for len == 0 static JSValue js_new_string8_len(JSContext *ctx, const char *buf, int len) { JSString *str; str = js_alloc_string(ctx, len, 0); if (!str) return JS_EXCEPTION; memcpy(str8(str), buf, len); str8(str)[len] = '\0'; return JS_MKPTR(JS_TAG_STRING, str); } // XXX: `buf` contains raw 8-bit data, no UTF-8 decoding is performed // XXX: no special case for the empty string static inline JSValue js_new_string8(JSContext *ctx, const char *str) { return js_new_string8_len(ctx, str, strlen(str)); } static JSValue js_new_string16_len(JSContext *ctx, const uint16_t *buf, int len) { JSString *str; str = js_alloc_string(ctx, len, 1); if (!str) return JS_EXCEPTION; memcpy(str16(str), buf, len * 2); return JS_MKPTR(JS_TAG_STRING, str); } static JSValue js_new_string_char(JSContext *ctx, uint16_t c) { if (c < 0x100) { char ch8 = c; return js_new_string8_len(ctx, &ch8, 1); } else { uint16_t ch16 = c; return js_new_string16_len(ctx, &ch16, 1); } } static JSValue js_sub_string(JSContext *ctx, JSString *p, int start, int end) { JSStringSlice *slice; JSString *q; int len; len = end - start; if (start == 0 && end == p->len) { return js_dup(JS_MKPTR(JS_TAG_STRING, p)); } if (len <= 0) { return js_empty_string(ctx->rt); } if (len > (JS_STRING_SLICE_LEN_MAX >> p->is_wide_char)) { if (p->kind == JS_STRING_KIND_SLICE) { slice = (void *)&p[1]; p = slice->parent; start += slice->start >> p->is_wide_char; // bytes -> chars } // allocate as 16 bit wide string to avoid wastage; // js_alloc_string allocates 1 byte extra for 8 bit strings; q = js_alloc_string(ctx, sizeof(*slice)/2, /*is_wide_char*/true); if (!q) return JS_EXCEPTION; q->is_wide_char = p->is_wide_char; q->kind = JS_STRING_KIND_SLICE; q->len = len; slice = (void *)&q[1]; slice->parent = p; slice->start = start << p->is_wide_char; // chars -> bytes p->header.ref_count++; return JS_MKPTR(JS_TAG_STRING, q); } if (p->is_wide_char) { JSString *str; int i; uint16_t c = 0; for (i = start; i < end; i++) { c |= str16(p)[i]; } if (c > 0xFF) return js_new_string16_len(ctx, str16(p) + start, len); str = js_alloc_string(ctx, len, 0); if (!str) return JS_EXCEPTION; for (i = 0; i < len; i++) { str8(str)[i] = str16(p)[start + i]; } str8(str)[len] = '\0'; return JS_MKPTR(JS_TAG_STRING, str); } else { return js_new_string8_len(ctx, (const char *)(str8(p) + start), len); } } typedef struct StringBuffer { JSContext *ctx; JSString *str; int len; int size; int is_wide_char; int error_status; } StringBuffer; /* It is valid to call string_buffer_end() and all string_buffer functions even if string_buffer_init() or another string_buffer function returns an error. If the error_status is set, string_buffer_end() returns JS_EXCEPTION. */ static int string_buffer_init2(JSContext *ctx, StringBuffer *s, int size, int is_wide) { s->ctx = ctx; s->size = size; s->len = 0; s->is_wide_char = is_wide; s->error_status = 0; s->str = js_alloc_string(ctx, size, is_wide); if (unlikely(!s->str)) { s->size = 0; return s->error_status = -1; } #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS /* the StringBuffer may reallocate the JSString, only link it at the end */ list_del(&s->str->link); #endif return 0; } static inline int string_buffer_init(JSContext *ctx, StringBuffer *s, int size) { return string_buffer_init2(ctx, s, size, 0); } static void string_buffer_free(StringBuffer *s) { js_free(s->ctx, s->str); s->str = NULL; } static int string_buffer_set_error(StringBuffer *s) { js_free(s->ctx, s->str); s->str = NULL; s->size = 0; s->len = 0; return s->error_status = -1; } static no_inline int string_buffer_widen(StringBuffer *s, int size) { JSString *str; size_t slack; int i; if (s->error_status) return -1; str = js_realloc2(s->ctx, s->str, sizeof(JSString) + (size << 1), &slack); if (!str) return string_buffer_set_error(s); size += slack >> 1; for(i = s->len; i-- > 0;) { str16(str)[i] = str8(str)[i]; } s->is_wide_char = 1; s->size = size; s->str = str; return 0; } static no_inline int string_buffer_realloc(StringBuffer *s, int new_len, int c) { JSString *new_str; int new_size; size_t new_size_bytes, slack; if (s->error_status) return -1; if (new_len > JS_STRING_LEN_MAX) { JS_ThrowRangeError(s->ctx, "invalid string length"); return string_buffer_set_error(s); } new_size = min_int(max_int(new_len, s->size * 3 / 2), JS_STRING_LEN_MAX); if (!s->is_wide_char && c >= 0x100) { return string_buffer_widen(s, new_size); } new_size_bytes = sizeof(JSString) + (new_size << s->is_wide_char) + 1 - s->is_wide_char; new_str = js_realloc2(s->ctx, s->str, new_size_bytes, &slack); if (!new_str) return string_buffer_set_error(s); new_size = min_int(new_size + (slack >> s->is_wide_char), JS_STRING_LEN_MAX); s->size = new_size; s->str = new_str; return 0; } static no_inline int string_buffer_putc_slow(StringBuffer *s, uint32_t c) { if (unlikely(s->len >= s->size)) { if (string_buffer_realloc(s, s->len + 1, c)) return -1; } if (s->is_wide_char) { str16(s->str)[s->len++] = c; } else if (c < 0x100) { str8(s->str)[s->len++] = c; } else { if (string_buffer_widen(s, s->size)) return -1; str16(s->str)[s->len++] = c; } return 0; } /* 0 <= c <= 0xff */ static int string_buffer_putc8(StringBuffer *s, uint32_t c) { if (unlikely(s->len >= s->size)) { if (string_buffer_realloc(s, s->len + 1, c)) return -1; } if (s->is_wide_char) { str16(s->str)[s->len++] = c; } else { str8(s->str)[s->len++] = c; } return 0; } /* 0 <= c <= 0xffff */ static int string_buffer_putc16(StringBuffer *s, uint32_t c) { if (likely(s->len < s->size)) { if (s->is_wide_char) { str16(s->str)[s->len++] = c; return 0; } else if (c < 0x100) { str8(s->str)[s->len++] = c; return 0; } } return string_buffer_putc_slow(s, c); } /* 0 <= c <= 0x10ffff */ static int string_buffer_putc(StringBuffer *s, uint32_t c) { if (unlikely(c >= 0x10000)) { /* surrogate pair */ if (string_buffer_putc16(s, get_hi_surrogate(c))) return -1; c = get_lo_surrogate(c); } return string_buffer_putc16(s, c); } static int string_getc(JSString *p, int *pidx) { int idx, c, c1; idx = *pidx; if (p->is_wide_char) { c = str16(p)[idx++]; if (is_hi_surrogate(c) && idx < p->len) { c1 = str16(p)[idx]; if (is_lo_surrogate(c1)) { c = from_surrogate(c, c1); idx++; } } } else { c = str8(p)[idx++]; } *pidx = idx; return c; } static int string_buffer_write8(StringBuffer *s, const uint8_t *p, int len) { int i; if (s->len + len > s->size) { if (string_buffer_realloc(s, s->len + len, 0)) return -1; } if (s->is_wide_char) { for (i = 0; i < len; i++) { str16(s->str)[s->len + i] = p[i]; } s->len += len; } else { memcpy(&str8(s->str)[s->len], p, len); s->len += len; } return 0; } static int string_buffer_write16(StringBuffer *s, const uint16_t *p, int len) { int c = 0, i; for (i = 0; i < len; i++) { c |= p[i]; } if (s->len + len > s->size) { if (string_buffer_realloc(s, s->len + len, c)) return -1; } else if (!s->is_wide_char && c >= 0x100) { if (string_buffer_widen(s, s->size)) return -1; } if (s->is_wide_char) { memcpy(&str16(s->str)[s->len], p, len << 1); s->len += len; } else { for (i = 0; i < len; i++) { str8(s->str)[s->len + i] = p[i]; } s->len += len; } return 0; } /* appending an ASCII string */ static int string_buffer_puts8(StringBuffer *s, const char *str) { return string_buffer_write8(s, (const uint8_t *)str, strlen(str)); } static int string_buffer_concat(StringBuffer *s, JSString *p, uint32_t from, uint32_t to) { if (to <= from) return 0; if (p->is_wide_char) return string_buffer_write16(s, str16(p) + from, to - from); else return string_buffer_write8(s, str8(p) + from, to - from); } static int string_buffer_concat_value(StringBuffer *s, JSValueConst v) { JSString *p; JSValue v1; int res; if (s->error_status) { /* prevent exception overload */ return -1; } if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) { v1 = JS_ToString(s->ctx, v); if (JS_IsException(v1)) return string_buffer_set_error(s); p = JS_VALUE_GET_STRING(v1); res = string_buffer_concat(s, p, 0, p->len); JS_FreeValue(s->ctx, v1); return res; } p = JS_VALUE_GET_STRING(v); return string_buffer_concat(s, p, 0, p->len); } static int string_buffer_concat_value_free(StringBuffer *s, JSValue v) { JSString *p; int res; if (s->error_status) { /* prevent exception overload */ JS_FreeValue(s->ctx, v); return -1; } if (unlikely(JS_VALUE_GET_TAG(v) != JS_TAG_STRING)) { v = JS_ToStringFree(s->ctx, v); if (JS_IsException(v)) return string_buffer_set_error(s); } p = JS_VALUE_GET_STRING(v); res = string_buffer_concat(s, p, 0, p->len); JS_FreeValue(s->ctx, v); return res; } static int string_buffer_fill(StringBuffer *s, int c, int count) { /* XXX: optimize */ if (s->len + count > s->size) { if (string_buffer_realloc(s, s->len + count, c)) return -1; } while (count-- > 0) { if (string_buffer_putc16(s, c)) return -1; } return 0; } static JSValue string_buffer_end(StringBuffer *s) { JSString *str; str = s->str; if (s->error_status) return JS_EXCEPTION; if (s->len == 0) { js_free(s->ctx, str); s->str = NULL; return js_empty_string(s->ctx->rt); } if (s->len < s->size) { /* smaller size so js_realloc should not fail, but OK if it does */ /* XXX: should add some slack to avoid unnecessary calls */ /* XXX: might need to use malloc+free to ensure smaller size */ str = js_realloc_rt(s->ctx->rt, str, sizeof(JSString) + (s->len << s->is_wide_char) + 1 - s->is_wide_char); if (str == NULL) str = s->str; s->str = str; } if (!s->is_wide_char) str8(str)[s->len] = 0; #ifdef ENABLE_DUMPS // JS_DUMP_LEAKS list_add_tail(&str->link, &s->ctx->rt->string_list); #endif str->is_wide_char = s->is_wide_char; str->len = s->len; s->str = NULL; return JS_MKPTR(JS_TAG_STRING, str); } /* create a string from a UTF-8 buffer */ JSValue JS_NewStringLen(JSContext *ctx, const char *buf, size_t buf_len) { JSString *str; size_t len; int kind; if (buf_len <= 0) { return js_empty_string(ctx->rt); } /* Compute string kind and length: 7-bit, 8-bit, 16-bit, 16-bit UTF-16 */ kind = utf8_scan(buf, buf_len, &len); if (len > JS_STRING_LEN_MAX) return JS_ThrowRangeError(ctx, "invalid string length"); switch (kind) { case UTF8_PLAIN_ASCII: str = js_alloc_string(ctx, len, 0); if (!str) return JS_EXCEPTION; memcpy(str8(str), buf, len); str8(str)[len] = '\0'; break; case UTF8_NON_ASCII: /* buf contains non-ASCII code-points, but limited to 8-bit values */ str = js_alloc_string(ctx, len, 0); if (!str) return JS_EXCEPTION; utf8_decode_buf8(str8(str), len + 1, buf, buf_len); break; default: // This causes a potential problem in JS_ThrowError if message is invalid //if (kind & UTF8_HAS_ERRORS) // return JS_ThrowRangeError(ctx, "invalid UTF-8 sequence"); str = js_alloc_string(ctx, len, 1); if (!str) return JS_EXCEPTION; utf8_decode_buf16(str16(str), len, buf, buf_len); break; } return JS_MKPTR(JS_TAG_STRING, str); } JSValue JS_NewTwoByteString(JSContext *ctx, const uint16_t *buf, size_t len) { JSString *str; if (!len) return js_empty_string(ctx->rt); str = js_alloc_string(ctx, len, 1); if (!str) return JS_EXCEPTION; memcpy(str16(str), buf, len * sizeof(*buf)); return JS_MKPTR(JS_TAG_STRING, str); } static JSValue JS_ConcatString3(JSContext *ctx, const char *str1, JSValue str2, const char *str3) { StringBuffer b_s, *b = &b_s; int len1, len3; JSString *p; if (unlikely(JS_VALUE_GET_TAG(str2) != JS_TAG_STRING)) { str2 = JS_ToStringFree(ctx, str2); if (JS_IsException(str2)) goto fail; } p = JS_VALUE_GET_STRING(str2); len1 = strlen(str1); len3 = strlen(str3); if (string_buffer_init2(ctx, b, len1 + p->len + len3, p->is_wide_char)) goto fail; string_buffer_write8(b, (const uint8_t *)str1, len1); string_buffer_concat(b, p, 0, p->len); string_buffer_write8(b, (const uint8_t *)str3, len3); JS_FreeValue(ctx, str2); return string_buffer_end(b); fail: JS_FreeValue(ctx, str2); return JS_EXCEPTION; } /* `str` may be pure ASCII or UTF-8 encoded */ JSValue JS_NewAtomString(JSContext *ctx, const char *str) { JSAtom atom = JS_NewAtom(ctx, str); if (atom == JS_ATOM_NULL) return JS_EXCEPTION; JSValue val = JS_AtomToString(ctx, atom); JS_FreeAtom(ctx, atom); return val; } /* return (NULL, 0) if exception. */ /* return pointer into a JSString with a live ref_count */ /* cesu8 determines if non-BMP1 codepoints are encoded as 1 or 2 utf-8 sequences */ const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, bool cesu8) { JSValue val; JSString *str, *str_new; int pos, len, c, c1; JSObject *p; uint8_t *q; if (JS_VALUE_GET_TAG(val1) == JS_TAG_STRING) { val = js_dup(val1); goto go; } val = JS_ToString(ctx, val1); if (!JS_IsException(val)) goto go; // Stringification can fail when there is an exception pending, // e.g. a stack overflow InternalError. Special-case exception // objects to make debugging easier, look up the .message property // and stringify that. if (JS_VALUE_GET_TAG(val1) != JS_TAG_OBJECT) goto fail; p = JS_VALUE_GET_OBJ(val1); if (p->class_id != JS_CLASS_ERROR) goto fail; val = JS_GetProperty(ctx, val1, JS_ATOM_message); if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) { JS_FreeValue(ctx, val); goto fail; } go: str = JS_VALUE_GET_STRING(val); len = str->len; if (!str->is_wide_char) { const uint8_t *src = str8(str); int count; /* count the number of non-ASCII characters */ /* Scanning the whole string is required for ASCII strings, and computing the number of non-ASCII bytes is less expensive than testing each byte, hence this method is faster for ASCII strings, which is the most common case. */ count = 0; for (pos = 0; pos < len; pos++) { count += src[pos] >> 7; } if (count == 0 && str->kind == JS_STRING_KIND_NORMAL) { if (plen) *plen = len; return (const char *)src; } str_new = js_alloc_string(ctx, len + count, 0); if (!str_new) goto fail; q = str8(str_new); for (pos = 0; pos < len; pos++) { c = src[pos]; if (c < 0x80) { *q++ = c; } else { *q++ = (c >> 6) | 0xc0; *q++ = (c & 0x3f) | 0x80; } } } else { const uint16_t *src = str16(str); /* Allocate 3 bytes per 16 bit code point. Surrogate pairs may produce 4 bytes but use 2 code points. */ str_new = js_alloc_string(ctx, len * 3, 0); if (!str_new) goto fail; q = str8(str_new); pos = 0; while (pos < len) { c = src[pos++]; if (c < 0x80) { *q++ = c; } else { if (is_hi_surrogate(c)) { if (pos < len && !cesu8) { c1 = src[pos]; if (is_lo_surrogate(c1)) { pos++; c = from_surrogate(c, c1); } else { /* Keep unmatched surrogate code points */ /* c = 0xfffd; */ /* error */ } } else { /* Keep unmatched surrogate code points */ /* c = 0xfffd; */ /* error */ } } q += utf8_encode(q, c); } } } *q = '\0'; str_new->len = q - str8(str_new); JS_FreeValue(ctx, val); if (plen) *plen = str_new->len; return (const char *)str8(str_new); fail: if (plen) *plen = 0; return NULL; } void JS_FreeCString(JSContext *ctx, const char *ptr) { if (!ptr) return; /* purposely removing constness */ JS_FreeValue(ctx, JS_MKPTR(JS_TAG_STRING, (JSString *)ptr - 1)); } static int memcmp16_8(const uint16_t *src1, const uint8_t *src2, int len) { int c, i; for(i = 0; i < len; i++) { c = src1[i] - src2[i]; if (c != 0) return c; } return 0; } static int memcmp16(const uint16_t *src1, const uint16_t *src2, int len) { int c, i; for(i = 0; i < len; i++) { c = src1[i] - src2[i]; if (c != 0) return c; } return 0; } static int js_string_memcmp(JSString *p1, JSString *p2, int len) { int res; if (likely(!p1->is_wide_char)) { if (likely(!p2->is_wide_char)) res = memcmp(str8(p1), str8(p2), len); else res = -memcmp16_8(str16(p2), str8(p1), len); } else { if (!p2->is_wide_char) res = memcmp16_8(str16(p1), str8(p2), len); else res = memcmp16(str16(p1), str16(p2), len); } return res; } static bool js_string_eq(JSString *p1, JSString *p2) { if (p1->len != p2->len) return false; return js_string_memcmp(p1, p2, p1->len) == 0; } /* return < 0, 0 or > 0 */ static int js_string_compare(JSString *p1, JSString *p2) { int res, len; len = min_int(p1->len, p2->len); res = js_string_memcmp(p1, p2, len); if (res == 0) res = compare_u32(p1->len, p2->len); return res; } static void copy_str16(uint16_t *dst, JSString *p, int offset, int len) { if (p->is_wide_char) { memcpy(dst, str16(p) + offset, len * 2); } else { const uint8_t *src1 = str8(p) + offset; int i; for(i = 0; i < len; i++) dst[i] = src1[i]; } } static JSValue JS_ConcatString1(JSContext *ctx, JSString *p1, JSString *p2) { JSString *p; uint32_t len; int is_wide_char; len = p1->len + p2->len; if (len > JS_STRING_LEN_MAX) return JS_ThrowRangeError(ctx, "invalid string length"); is_wide_char = p1->is_wide_char | p2->is_wide_char; p = js_alloc_string(ctx, len, is_wide_char); if (!p) return JS_EXCEPTION; if (!is_wide_char) { memcpy(str8(p), str8(p1), p1->len); memcpy(str8(p) + p1->len, str8(p2), p2->len); str8(p)[len] = '\0'; } else { copy_str16(str16(p), p1, 0, p1->len); copy_str16(str16(p) + p1->len, p2, 0, p2->len); } return JS_MKPTR(JS_TAG_STRING, p); } /* op1 and op2 are converted to strings. For convience, op1 or op2 = JS_EXCEPTION are accepted and return JS_EXCEPTION. */ static JSValue JS_ConcatString(JSContext *ctx, JSValue op1, JSValue op2) { JSValue ret; JSString *p1, *p2; if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_STRING)) { op1 = JS_ToStringFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); return JS_EXCEPTION; } } if (unlikely(JS_VALUE_GET_TAG(op2) != JS_TAG_STRING)) { op2 = JS_ToStringFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); return JS_EXCEPTION; } } p1 = JS_VALUE_GET_STRING(op1); p2 = JS_VALUE_GET_STRING(op2); /* XXX: could also check if p1 is empty */ if (p2->len == 0) { goto ret_op1; } if (p1->header.ref_count == 1 && p1->is_wide_char == p2->is_wide_char && js_malloc_usable_size(ctx, p1) >= sizeof(*p1) + ((p1->len + p2->len) << p2->is_wide_char) + 1 - p1->is_wide_char) { /* Concatenate in place in available space at the end of p1 */ if (p1->is_wide_char) { memcpy(str16(p1) + p1->len, str16(p2), p2->len << 1); p1->len += p2->len; } else { memcpy(str8(p1) + p1->len, str8(p2), p2->len); p1->len += p2->len; str8(p1)[p1->len] = '\0'; } ret_op1: JS_FreeValue(ctx, op2); return op1; } ret = JS_ConcatString1(ctx, p1, p2); JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); return ret; } /* Shape support */ static inline size_t get_shape_size(size_t hash_size, size_t prop_size) { return hash_size * sizeof(uint32_t) + sizeof(JSShape) + prop_size * sizeof(JSShapeProperty); } static inline JSShape *get_shape_from_alloc(void *sh_alloc, size_t hash_size) { return (JSShape *)(void *)((uint32_t *)sh_alloc + hash_size); } static inline uint32_t *prop_hash_end(JSShape *sh) { return (uint32_t *)sh; } static inline void *get_alloc_from_shape(JSShape *sh) { return prop_hash_end(sh) - ((intptr_t)sh->prop_hash_mask + 1); } static inline JSShapeProperty *get_shape_prop(JSShape *sh) { return sh->prop; } static int init_shape_hash(JSRuntime *rt) { rt->shape_hash_bits = 6; /* 64 shapes */ rt->shape_hash_size = 1 << rt->shape_hash_bits; rt->shape_hash_count = 0; rt->shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) * rt->shape_hash_size); if (!rt->shape_hash) return -1; return 0; } /* same magic hash multiplier as the Linux kernel */ static uint32_t shape_hash(uint32_t h, uint32_t val) { return (h + val) * 0x9e370001; } /* truncate the shape hash to 'hash_bits' bits */ static uint32_t get_shape_hash(uint32_t h, int hash_bits) { return h >> (32 - hash_bits); } static uint32_t shape_initial_hash(JSObject *proto) { uint32_t h; h = shape_hash(1, (uintptr_t)proto); if (sizeof(proto) > 4) h = shape_hash(h, (uint64_t)(uintptr_t)proto >> 32); return h; } static int resize_shape_hash(JSRuntime *rt, int new_shape_hash_bits) { int new_shape_hash_size, i; uint32_t h; JSShape **new_shape_hash, *sh, *sh_next; new_shape_hash_size = 1 << new_shape_hash_bits; new_shape_hash = js_mallocz_rt(rt, sizeof(rt->shape_hash[0]) * new_shape_hash_size); if (!new_shape_hash) return -1; for(i = 0; i < rt->shape_hash_size; i++) { for(sh = rt->shape_hash[i]; sh != NULL; sh = sh_next) { sh_next = sh->shape_hash_next; h = get_shape_hash(sh->hash, new_shape_hash_bits); sh->shape_hash_next = new_shape_hash[h]; new_shape_hash[h] = sh; } } js_free_rt(rt, rt->shape_hash); rt->shape_hash_bits = new_shape_hash_bits; rt->shape_hash_size = new_shape_hash_size; rt->shape_hash = new_shape_hash; return 0; } static void js_shape_hash_link(JSRuntime *rt, JSShape *sh) { uint32_t h; h = get_shape_hash(sh->hash, rt->shape_hash_bits); sh->shape_hash_next = rt->shape_hash[h]; rt->shape_hash[h] = sh; rt->shape_hash_count++; } static void js_shape_hash_unlink(JSRuntime *rt, JSShape *sh) { uint32_t h; JSShape **psh; h = get_shape_hash(sh->hash, rt->shape_hash_bits); psh = &rt->shape_hash[h]; while (*psh != sh) psh = &(*psh)->shape_hash_next; *psh = sh->shape_hash_next; rt->shape_hash_count--; } /* create a new empty shape with prototype 'proto' */ static no_inline JSShape *js_new_shape2(JSContext *ctx, JSObject *proto, int hash_size, int prop_size) { JSRuntime *rt = ctx->rt; void *sh_alloc; JSShape *sh; /* resize the shape hash table if necessary */ if (2 * (rt->shape_hash_count + 1) > rt->shape_hash_size) { resize_shape_hash(rt, rt->shape_hash_bits + 1); } sh_alloc = js_malloc(ctx, get_shape_size(hash_size, prop_size)); if (!sh_alloc) return NULL; sh = get_shape_from_alloc(sh_alloc, hash_size); sh->header.ref_count = 1; add_gc_object(rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE); if (proto) js_dup(JS_MKPTR(JS_TAG_OBJECT, proto)); sh->proto = proto; memset(prop_hash_end(sh) - hash_size, 0, sizeof(prop_hash_end(sh)[0]) * hash_size); sh->prop_hash_mask = hash_size - 1; sh->prop_size = prop_size; sh->prop_count = 0; sh->deleted_prop_count = 0; /* insert in the hash table */ sh->hash = shape_initial_hash(proto); sh->is_hashed = true; sh->has_small_array_index = false; js_shape_hash_link(ctx->rt, sh); return sh; } static JSShape *js_new_shape(JSContext *ctx, JSObject *proto) { return js_new_shape2(ctx, proto, JS_PROP_INITIAL_HASH_SIZE, JS_PROP_INITIAL_SIZE); } /* The shape is cloned. The new shape is not inserted in the shape hash table */ static JSShape *js_clone_shape(JSContext *ctx, JSShape *sh1) { JSShape *sh; void *sh_alloc, *sh_alloc1; size_t size; JSShapeProperty *pr; uint32_t i, hash_size; hash_size = sh1->prop_hash_mask + 1; size = get_shape_size(hash_size, sh1->prop_size); sh_alloc = js_malloc(ctx, size); if (!sh_alloc) return NULL; sh_alloc1 = get_alloc_from_shape(sh1); memcpy(sh_alloc, sh_alloc1, size); sh = get_shape_from_alloc(sh_alloc, hash_size); sh->header.ref_count = 1; add_gc_object(ctx->rt, &sh->header, JS_GC_OBJ_TYPE_SHAPE); sh->is_hashed = false; if (sh->proto) { js_dup(JS_MKPTR(JS_TAG_OBJECT, sh->proto)); } for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) { JS_DupAtom(ctx, pr->atom); } return sh; } static JSShape *js_dup_shape(JSShape *sh) { sh->header.ref_count++; return sh; } static void js_free_shape0(JSRuntime *rt, JSShape *sh) { uint32_t i; JSShapeProperty *pr; assert(sh->header.ref_count == 0); if (sh->is_hashed) js_shape_hash_unlink(rt, sh); if (sh->proto != NULL) { JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, sh->proto)); } pr = get_shape_prop(sh); for(i = 0; i < sh->prop_count; i++) { JS_FreeAtomRT(rt, pr->atom); pr++; } remove_gc_object(&sh->header); js_free_rt(rt, get_alloc_from_shape(sh)); } static void js_free_shape(JSRuntime *rt, JSShape *sh) { if (unlikely(--sh->header.ref_count <= 0)) { js_free_shape0(rt, sh); } } static void js_free_shape_null(JSRuntime *rt, JSShape *sh) { if (sh) js_free_shape(rt, sh); } /* make space to hold at least 'count' properties */ static no_inline int resize_properties(JSContext *ctx, JSShape **psh, JSObject *p, uint32_t count) { JSShape *sh; uint32_t new_size, new_hash_size, new_hash_mask, i; JSShapeProperty *pr; void *sh_alloc; intptr_t h; sh = *psh; new_size = max_int(count, sh->prop_size * 3 / 2); /* Reallocate prop array first to avoid crash or size inconsistency in case of memory allocation failure */ if (p) { JSProperty *new_prop; new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size); if (unlikely(!new_prop)) return -1; p->prop = new_prop; } new_hash_size = sh->prop_hash_mask + 1; while (new_hash_size < new_size) new_hash_size = 2 * new_hash_size; if (new_hash_size != (sh->prop_hash_mask + 1)) { JSShape *old_sh; /* resize the hash table and the properties */ old_sh = sh; sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size)); if (!sh_alloc) return -1; sh = get_shape_from_alloc(sh_alloc, new_hash_size); list_del(&old_sh->header.link); /* copy all the fields and the properties */ memcpy(sh, old_sh, sizeof(JSShape) + sizeof(sh->prop[0]) * old_sh->prop_count); list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); new_hash_mask = new_hash_size - 1; sh->prop_hash_mask = new_hash_mask; memset(prop_hash_end(sh) - new_hash_size, 0, sizeof(prop_hash_end(sh)[0]) * new_hash_size); for(i = 0, pr = sh->prop; i < sh->prop_count; i++, pr++) { if (pr->atom != JS_ATOM_NULL) { h = ((uintptr_t)pr->atom & new_hash_mask); pr->hash_next = prop_hash_end(sh)[-h - 1]; prop_hash_end(sh)[-h - 1] = i + 1; } } js_free(ctx, get_alloc_from_shape(old_sh)); } else { /* only resize the properties */ list_del(&sh->header.link); sh_alloc = js_realloc(ctx, get_alloc_from_shape(sh), get_shape_size(new_hash_size, new_size)); if (unlikely(!sh_alloc)) { /* insert again in the GC list */ list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); return -1; } sh = get_shape_from_alloc(sh_alloc, new_hash_size); list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); } *psh = sh; sh->prop_size = new_size; return 0; } /* remove the deleted properties. */ static int compact_properties(JSContext *ctx, JSObject *p) { JSShape *sh, *old_sh; void *sh_alloc; intptr_t h; uint32_t new_hash_size, i, j, new_hash_mask, new_size; JSShapeProperty *old_pr, *pr; JSProperty *prop, *new_prop; sh = p->shape; assert(!sh->is_hashed); new_size = max_int(JS_PROP_INITIAL_SIZE, sh->prop_count - sh->deleted_prop_count); assert(new_size <= sh->prop_size); new_hash_size = sh->prop_hash_mask + 1; while ((new_hash_size / 2) >= new_size) new_hash_size = new_hash_size / 2; new_hash_mask = new_hash_size - 1; /* resize the hash table and the properties */ old_sh = sh; sh_alloc = js_malloc(ctx, get_shape_size(new_hash_size, new_size)); if (!sh_alloc) return -1; sh = get_shape_from_alloc(sh_alloc, new_hash_size); list_del(&old_sh->header.link); memcpy(sh, old_sh, sizeof(JSShape)); list_add_tail(&sh->header.link, &ctx->rt->gc_obj_list); memset(prop_hash_end(sh) - new_hash_size, 0, sizeof(prop_hash_end(sh)[0]) * new_hash_size); j = 0; old_pr = old_sh->prop; pr = sh->prop; prop = p->prop; for(i = 0; i < sh->prop_count; i++) { if (old_pr->atom != JS_ATOM_NULL) { pr->atom = old_pr->atom; pr->flags = old_pr->flags; h = ((uintptr_t)old_pr->atom & new_hash_mask); pr->hash_next = prop_hash_end(sh)[-h - 1]; prop_hash_end(sh)[-h - 1] = j + 1; prop[j] = prop[i]; j++; pr++; } old_pr++; } assert(j == (sh->prop_count - sh->deleted_prop_count)); sh->prop_hash_mask = new_hash_mask; sh->prop_size = new_size; sh->deleted_prop_count = 0; sh->prop_count = j; p->shape = sh; js_free(ctx, get_alloc_from_shape(old_sh)); /* reduce the size of the object properties */ new_prop = js_realloc(ctx, p->prop, sizeof(new_prop[0]) * new_size); if (new_prop) p->prop = new_prop; return 0; } static int add_shape_property(JSContext *ctx, JSShape **psh, JSObject *p, JSAtom atom, int prop_flags) { JSRuntime *rt = ctx->rt; JSShape *sh = *psh; JSShapeProperty *pr, *prop; uint32_t hash_mask, new_shape_hash = 0; intptr_t h; /* update the shape hash */ if (sh->is_hashed) { js_shape_hash_unlink(rt, sh); new_shape_hash = shape_hash(shape_hash(sh->hash, atom), prop_flags); } if (unlikely(sh->prop_count >= sh->prop_size)) { if (resize_properties(ctx, psh, p, sh->prop_count + 1)) { /* in case of error, reinsert in the hash table. sh is still valid if resize_properties() failed */ if (sh->is_hashed) js_shape_hash_link(rt, sh); return -1; } sh = *psh; } if (sh->is_hashed) { sh->hash = new_shape_hash; js_shape_hash_link(rt, sh); } /* Initialize the new shape property. The object property at p->prop[sh->prop_count] is uninitialized */ prop = get_shape_prop(sh); pr = &prop[sh->prop_count++]; pr->atom = JS_DupAtom(ctx, atom); pr->flags = prop_flags; sh->has_small_array_index |= __JS_AtomIsTaggedInt(atom); /* add in hash table */ hash_mask = sh->prop_hash_mask; h = atom & hash_mask; pr->hash_next = prop_hash_end(sh)[-h - 1]; prop_hash_end(sh)[-h - 1] = sh->prop_count; return 0; } /* find a hashed empty shape matching the prototype. Return NULL if not found */ static JSShape *find_hashed_shape_proto(JSRuntime *rt, JSObject *proto) { JSShape *sh1; uint32_t h, h1; h = shape_initial_hash(proto); h1 = get_shape_hash(h, rt->shape_hash_bits); for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) { if (sh1->hash == h && sh1->proto == proto && sh1->prop_count == 0) { return sh1; } } return NULL; } /* find a hashed shape matching sh + (prop, prop_flags). Return NULL if not found */ static JSShape *find_hashed_shape_prop(JSRuntime *rt, JSShape *sh, JSAtom atom, int prop_flags) { JSShape *sh1; uint32_t h, h1, i, n; h = sh->hash; h = shape_hash(h, atom); h = shape_hash(h, prop_flags); h1 = get_shape_hash(h, rt->shape_hash_bits); for(sh1 = rt->shape_hash[h1]; sh1 != NULL; sh1 = sh1->shape_hash_next) { /* we test the hash first so that the rest is done only if the shapes really match */ if (sh1->hash == h && sh1->proto == sh->proto && sh1->prop_count == ((n = sh->prop_count) + 1)) { for(i = 0; i < n; i++) { if (unlikely(sh1->prop[i].atom != sh->prop[i].atom) || unlikely(sh1->prop[i].flags != sh->prop[i].flags)) goto next; } if (unlikely(sh1->prop[n].atom != atom) || unlikely(sh1->prop[n].flags != prop_flags)) goto next; return sh1; } next: ; } return NULL; } static __maybe_unused void JS_DumpShape(JSRuntime *rt, int i, JSShape *sh) { char atom_buf[ATOM_GET_STR_BUF_SIZE]; int j; /* XXX: should output readable class prototype */ printf("%5d %3d%c %14p %5d %5d", i, sh->header.ref_count, " *"[sh->is_hashed], (void *)sh->proto, sh->prop_size, sh->prop_count); for(j = 0; j < sh->prop_count; j++) { printf(" %s", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), sh->prop[j].atom)); } printf("\n"); } static __maybe_unused void JS_DumpShapes(JSRuntime *rt) { int i; JSShape *sh; struct list_head *el; JSObject *p; JSGCObjectHeader *gp; printf("JSShapes: {\n"); printf("%5s %4s %14s %5s %5s %s\n", "SLOT", "REFS", "PROTO", "SIZE", "COUNT", "PROPS"); for(i = 0; i < rt->shape_hash_size; i++) { for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) { JS_DumpShape(rt, i, sh); assert(sh->is_hashed); } } /* dump non-hashed shapes */ list_for_each(el, &rt->gc_obj_list) { gp = list_entry(el, JSGCObjectHeader, link); if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) { p = (JSObject *)gp; if (!p->shape->is_hashed) { JS_DumpShape(rt, -1, p->shape); } } } printf("}\n"); } static JSValue JS_NewObjectFromShape(JSContext *ctx, JSShape *sh, JSClassID class_id) { JSObject *p; js_trigger_gc(ctx->rt, sizeof(JSObject)); p = js_malloc(ctx, sizeof(JSObject)); if (unlikely(!p)) goto fail; p->class_id = class_id; p->extensible = true; p->free_mark = 0; p->is_exotic = 0; p->fast_array = 0; p->is_constructor = 0; p->is_uncatchable_error = 0; p->tmp_mark = 0; p->is_HTMLDDA = 0; p->first_weak_ref = NULL; p->u.opaque = NULL; p->shape = sh; p->prop = js_malloc(ctx, sizeof(JSProperty) * sh->prop_size); if (unlikely(!p->prop)) { js_free(ctx, p); fail: js_free_shape(ctx->rt, sh); return JS_EXCEPTION; } switch(class_id) { case JS_CLASS_OBJECT: break; case JS_CLASS_ARRAY: { JSProperty *pr; p->is_exotic = 1; p->fast_array = 1; p->u.array.u.values = NULL; p->u.array.count = 0; p->u.array.u1.size = 0; /* the length property is always the first one */ if (likely(sh == ctx->array_shape)) { pr = &p->prop[0]; } else { /* only used for the first array */ /* cannot fail */ pr = add_property(ctx, p, JS_ATOM_length, JS_PROP_WRITABLE | JS_PROP_LENGTH); } pr->u.value = js_int32(0); } break; case JS_CLASS_C_FUNCTION: p->prop[0].u.value = JS_UNDEFINED; break; case JS_CLASS_ARGUMENTS: case JS_CLASS_UINT8C_ARRAY: case JS_CLASS_INT8_ARRAY: case JS_CLASS_UINT8_ARRAY: case JS_CLASS_INT16_ARRAY: case JS_CLASS_UINT16_ARRAY: case JS_CLASS_INT32_ARRAY: case JS_CLASS_UINT32_ARRAY: case JS_CLASS_BIG_INT64_ARRAY: case JS_CLASS_BIG_UINT64_ARRAY: case JS_CLASS_FLOAT16_ARRAY: case JS_CLASS_FLOAT32_ARRAY: case JS_CLASS_FLOAT64_ARRAY: p->is_exotic = 1; p->fast_array = 1; p->u.array.u.ptr = NULL; p->u.array.count = 0; break; case JS_CLASS_DATAVIEW: p->u.array.u.ptr = NULL; p->u.array.count = 0; break; case JS_CLASS_NUMBER: case JS_CLASS_STRING: case JS_CLASS_BOOLEAN: case JS_CLASS_SYMBOL: case JS_CLASS_DATE: case JS_CLASS_BIG_INT: p->u.object_data = JS_UNDEFINED; goto set_exotic; case JS_CLASS_REGEXP: p->u.regexp.pattern = NULL; p->u.regexp.bytecode = NULL; goto set_exotic; default: set_exotic: if (ctx->rt->class_array[class_id].exotic) { p->is_exotic = 1; } break; } p->header.ref_count = 1; add_gc_object(ctx->rt, &p->header, JS_GC_OBJ_TYPE_JS_OBJECT); return JS_MKPTR(JS_TAG_OBJECT, p); } static JSObject *get_proto_obj(JSValueConst proto_val) { if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) return NULL; else return JS_VALUE_GET_OBJ(proto_val); } /* WARNING: proto must be an object or JS_NULL */ JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto_val, JSClassID class_id) { JSShape *sh; JSObject *proto; proto = get_proto_obj(proto_val); sh = find_hashed_shape_proto(ctx->rt, proto); if (likely(sh)) { sh = js_dup_shape(sh); } else { sh = js_new_shape(ctx, proto); if (!sh) return JS_EXCEPTION; } return JS_NewObjectFromShape(ctx, sh, class_id); } static int JS_SetObjectData(JSContext *ctx, JSValueConst obj, JSValue val) { JSObject *p; if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { p = JS_VALUE_GET_OBJ(obj); switch(p->class_id) { case JS_CLASS_NUMBER: case JS_CLASS_STRING: case JS_CLASS_BOOLEAN: case JS_CLASS_SYMBOL: case JS_CLASS_DATE: case JS_CLASS_BIG_INT: JS_FreeValue(ctx, p->u.object_data); p->u.object_data = val; return 0; } } JS_FreeValue(ctx, val); if (!JS_IsException(obj)) JS_ThrowTypeError(ctx, "invalid object type"); return -1; } JSValue JS_NewObjectClass(JSContext *ctx, JSClassID class_id) { return JS_NewObjectProtoClass(ctx, ctx->class_proto[class_id], class_id); } JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto) { return JS_NewObjectProtoClass(ctx, proto, JS_CLASS_OBJECT); } JSValue JS_NewObjectFrom(JSContext *ctx, int count, const JSAtom *props, const JSValue *values) { JSShapeProperty *pr; uint32_t *hash; JSRuntime *rt; JSObject *p; JSShape *sh; JSValue obj; JSAtom atom; intptr_t h; int i; rt = ctx->rt; obj = JS_NewObject(ctx); if (JS_IsException(obj)) return JS_EXCEPTION; if (count > 0) { p = JS_VALUE_GET_OBJ(obj); sh = p->shape; assert(sh->is_hashed); assert(sh->header.ref_count == 1); js_shape_hash_unlink(rt, sh); if (resize_properties(ctx, &sh, p, count)) { js_shape_hash_link(rt, sh); JS_FreeValue(ctx, obj); return JS_EXCEPTION; } p->shape = sh; for (i = 0; i < count; i++) { atom = props[i]; pr = &sh->prop[i]; sh->hash = shape_hash(shape_hash(sh->hash, atom), JS_PROP_C_W_E); sh->has_small_array_index |= __JS_AtomIsTaggedInt(atom); h = atom & sh->prop_hash_mask; hash = &prop_hash_end(sh)[-h - 1]; pr->hash_next = *hash; *hash = i + 1; pr->atom = JS_DupAtom(ctx, atom); pr->flags = JS_PROP_C_W_E; p->prop[i].u.value = values[i]; } js_shape_hash_link(rt, sh); sh->prop_count = count; } return obj; } JSValue JS_NewObjectFromStr(JSContext *ctx, int count, const char **props, const JSValue *values) { JSAtom atoms_s[16], *atoms = atoms_s; JSValue ret; int i; i = 0; ret = JS_EXCEPTION; if (count < 1) goto out; if (count > (int)countof(atoms_s)) { atoms = js_malloc(ctx, count * sizeof(*atoms)); if (!atoms) return JS_EXCEPTION; } for (i = 0; i < count; i++) { atoms[i] = JS_NewAtom(ctx, props[i]); if (atoms[i] == JS_ATOM_NULL) goto out; } ret = JS_NewObjectFrom(ctx, count, atoms, values); out: while (i-- > 0) JS_FreeAtom(ctx, atoms[i]); if (atoms != atoms_s) js_free(ctx, atoms); return ret; } JSValue JS_NewArray(JSContext *ctx) { return JS_NewObjectFromShape(ctx, js_dup_shape(ctx->array_shape), JS_CLASS_ARRAY); } // note: takes ownership of |values|, unlike js_create_array JSValue JS_NewArrayFrom(JSContext *ctx, int count, const JSValue *values) { JSObject *p; JSValue obj; int i; obj = JS_NewArray(ctx); if (JS_IsException(obj)) goto exception; if (count > 0) { p = JS_VALUE_GET_OBJ(obj); if (expand_fast_array(ctx, p, count)) { JS_FreeValue(ctx, obj); goto exception; } p->u.array.count = count; p->prop[0].u.value = js_int32(count); memcpy(p->u.array.u.values, values, count * sizeof(*values)); } return obj; exception: for (i = 0; i < count; i++) JS_FreeValue(ctx, values[i]); return JS_EXCEPTION; } JSValue JS_NewObject(JSContext *ctx) { /* inline JS_NewObjectClass(ctx, JS_CLASS_OBJECT); */ return JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_OBJECT); } static void js_function_set_properties(JSContext *ctx, JSValue func_obj, JSAtom name, int len) { /* ES6 feature non compatible with ES5.1: length is configurable */ JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_length, js_int32(len), JS_PROP_CONFIGURABLE); JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, JS_AtomToString(ctx, name), JS_PROP_CONFIGURABLE); } static bool js_class_has_bytecode(JSClassID class_id) { return (class_id == JS_CLASS_BYTECODE_FUNCTION || class_id == JS_CLASS_GENERATOR_FUNCTION || class_id == JS_CLASS_ASYNC_FUNCTION || class_id == JS_CLASS_ASYNC_GENERATOR_FUNCTION); } /* return NULL without exception if not a function or no bytecode */ static JSFunctionBytecode *JS_GetFunctionBytecode(JSValueConst val) { JSObject *p; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return NULL; p = JS_VALUE_GET_OBJ(val); if (!js_class_has_bytecode(p->class_id)) return NULL; return p->u.func.function_bytecode; } static void js_method_set_home_object(JSContext *ctx, JSValue func_obj, JSValue home_obj) { JSObject *p, *p1; JSFunctionBytecode *b; if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT) return; p = JS_VALUE_GET_OBJ(func_obj); if (!js_class_has_bytecode(p->class_id)) return; b = p->u.func.function_bytecode; if (b->need_home_object) { p1 = p->u.func.home_object; if (p1) { JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p1)); } if (JS_VALUE_GET_TAG(home_obj) == JS_TAG_OBJECT) p1 = JS_VALUE_GET_OBJ(js_dup(home_obj)); else p1 = NULL; p->u.func.home_object = p1; } } static JSValue js_get_function_name(JSContext *ctx, JSAtom name) { JSValue name_str; name_str = JS_AtomToString(ctx, name); if (JS_AtomSymbolHasDescription(ctx, name)) { name_str = JS_ConcatString3(ctx, "[", name_str, "]"); } return name_str; } /* Modify the name of a method according to the atom and 'flags'. 'flags' is a bitmask of JS_PROP_HAS_GET and JS_PROP_HAS_SET. Also set the home object of the method. Return < 0 if exception. */ static int js_method_set_properties(JSContext *ctx, JSValue func_obj, JSAtom name, int flags, JSValue home_obj) { JSValue name_str; name_str = js_get_function_name(ctx, name); if (flags & JS_PROP_HAS_GET) { name_str = JS_ConcatString3(ctx, "get ", name_str, ""); } else if (flags & JS_PROP_HAS_SET) { name_str = JS_ConcatString3(ctx, "set ", name_str, ""); } if (JS_IsException(name_str)) return -1; if (JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_name, name_str, JS_PROP_CONFIGURABLE) < 0) return -1; js_method_set_home_object(ctx, func_obj, home_obj); return 0; } /* Note: at least 'length' arguments will be readable in 'argv' */ /* `name` may be NULL, pure ASCII or UTF-8 encoded */ JSValue JS_NewCFunction3(JSContext *ctx, JSCFunction *func, const char *name, int length, JSCFunctionEnum cproto, int magic, JSValueConst proto_val) { JSValue func_obj; JSObject *p; JSAtom name_atom; func_obj = JS_NewObjectProtoClass(ctx, proto_val, JS_CLASS_C_FUNCTION); if (JS_IsException(func_obj)) return func_obj; p = JS_VALUE_GET_OBJ(func_obj); p->u.cfunc.realm = JS_DupContext(ctx); p->u.cfunc.c_function.generic = func; p->u.cfunc.length = length; p->u.cfunc.cproto = cproto; p->u.cfunc.magic = magic; p->is_constructor = (cproto == JS_CFUNC_constructor || cproto == JS_CFUNC_constructor_magic || cproto == JS_CFUNC_constructor_or_func || cproto == JS_CFUNC_constructor_or_func_magic); name_atom = JS_ATOM_empty_string; if (name && *name) { name_atom = JS_NewAtom(ctx, name); if (name_atom == JS_ATOM_NULL) { JS_FreeValue(ctx, func_obj); return JS_EXCEPTION; } } js_function_set_properties(ctx, func_obj, name_atom, length); JS_FreeAtom(ctx, name_atom); return func_obj; } /* Note: at least 'length' arguments will be readable in 'argv' */ JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func, const char *name, int length, JSCFunctionEnum cproto, int magic) { return JS_NewCFunction3(ctx, func, name, length, cproto, magic, ctx->function_proto); } typedef struct JSCFunctionDataRecord { JSCFunctionData *func; uint8_t length; uint8_t data_len; uint16_t magic; JSValue data[]; } JSCFunctionDataRecord; static void js_c_function_data_finalizer(JSRuntime *rt, JSValueConst val) { JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA); int i; if (s) { for(i = 0; i < s->data_len; i++) { JS_FreeValueRT(rt, s->data[i]); } js_free_rt(rt, s); } } static void js_c_function_data_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSCFunctionDataRecord *s = JS_GetOpaque(val, JS_CLASS_C_FUNCTION_DATA); int i; if (s) { for(i = 0; i < s->data_len; i++) { JS_MarkValue(rt, s->data[i], mark_func); } } } static JSValue js_call_c_function_data(JSContext *ctx, JSValueConst func_obj, JSValueConst this_val, int argc, JSValueConst *argv, int flags) { JSRuntime *rt = ctx->rt; JSStackFrame sf_s, *sf = &sf_s, *prev_sf; JSCFunctionDataRecord *s; JSValueConst *arg_buf; JSValue ret; size_t stack_size; int arg_count; int i; s = JS_GetOpaque(func_obj, JS_CLASS_C_FUNCTION_DATA); if (!s) return JS_EXCEPTION; // can't really happen arg_buf = argv; arg_count = s->length; if (unlikely(argc < arg_count)) { stack_size = arg_count * sizeof(arg_buf[0]); if (js_check_stack_overflow(rt, stack_size)) return JS_ThrowStackOverflow(ctx); arg_buf = alloca(stack_size); for(i = 0; i < argc; i++) arg_buf[i] = argv[i]; for(i = argc; i < arg_count; i++) arg_buf[i] = JS_UNDEFINED; } prev_sf = rt->current_stack_frame; sf->prev_frame = prev_sf; rt->current_stack_frame = sf; // TODO(bnoordhuis) switch realms like js_call_c_function does sf->is_strict_mode = false; sf->cur_func = unsafe_unconst(func_obj); sf->arg_count = argc; ret = s->func(ctx, this_val, argc, arg_buf, s->magic, vc(s->data)); rt->current_stack_frame = sf->prev_frame; return ret; } JSValue JS_NewCFunctionData2(JSContext *ctx, JSCFunctionData *func, const char *name, int length, int magic, int data_len, JSValueConst *data) { JSCFunctionDataRecord *s; JSAtom name_atom; JSValue func_obj; int i; func_obj = JS_NewObjectProtoClass(ctx, ctx->function_proto, JS_CLASS_C_FUNCTION_DATA); if (JS_IsException(func_obj)) return func_obj; s = js_malloc(ctx, sizeof(*s) + data_len * sizeof(JSValue)); if (!s) { JS_FreeValue(ctx, func_obj); return JS_EXCEPTION; } s->func = func; s->length = length; s->data_len = data_len; s->magic = magic; for(i = 0; i < data_len; i++) s->data[i] = js_dup(data[i]); JS_SetOpaqueInternal(func_obj, s); name_atom = JS_ATOM_empty_string; if (name && *name) { name_atom = JS_NewAtom(ctx, name); if (name_atom == JS_ATOM_NULL) { JS_FreeValue(ctx, func_obj); return JS_EXCEPTION; } } js_function_set_properties(ctx, func_obj, name_atom, length); JS_FreeAtom(ctx, name_atom); return func_obj; } JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func, int length, int magic, int data_len, JSValueConst *data) { return JS_NewCFunctionData2(ctx, func, NULL, length, magic, data_len, data); } static JSContext *js_autoinit_get_realm(JSProperty *pr) { return (JSContext *)(pr->u.init.realm_and_id & ~3); } static JSAutoInitIDEnum js_autoinit_get_id(JSProperty *pr) { return pr->u.init.realm_and_id & 3; } static void js_autoinit_free(JSRuntime *rt, JSProperty *pr) { JS_FreeContext(js_autoinit_get_realm(pr)); } static void js_autoinit_mark(JSRuntime *rt, JSProperty *pr, JS_MarkFunc *mark_func) { mark_func(rt, &js_autoinit_get_realm(pr)->header); } static void free_property(JSRuntime *rt, JSProperty *pr, int prop_flags) { if (unlikely(prop_flags & JS_PROP_TMASK)) { if ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET) { if (pr->u.getset.getter) JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); if (pr->u.getset.setter) JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_VARREF) { free_var_ref(rt, pr->u.var_ref); } else if ((prop_flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { js_autoinit_free(rt, pr); } } else { JS_FreeValueRT(rt, pr->u.value); } } static force_inline JSShapeProperty *find_own_property1(JSObject *p, JSAtom atom) { JSShape *sh; JSShapeProperty *pr, *prop; intptr_t h; sh = p->shape; h = (uintptr_t)atom & sh->prop_hash_mask; h = prop_hash_end(sh)[-h - 1]; prop = get_shape_prop(sh); while (h) { pr = &prop[h - 1]; if (likely(pr->atom == atom)) { return pr; } h = pr->hash_next; } return NULL; } static force_inline JSShapeProperty *find_own_property(JSProperty **ppr, JSObject *p, JSAtom atom) { JSShape *sh; JSShapeProperty *pr, *prop; intptr_t h; sh = p->shape; h = (uintptr_t)atom & sh->prop_hash_mask; h = prop_hash_end(sh)[-h - 1]; prop = get_shape_prop(sh); while (h) { pr = &prop[h - 1]; if (likely(pr->atom == atom)) { *ppr = &p->prop[h - 1]; /* the compiler should be able to assume that pr != NULL here */ return pr; } h = pr->hash_next; } *ppr = NULL; return NULL; } static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref) { if (var_ref) { assert(var_ref->header.ref_count > 0); if (--var_ref->header.ref_count == 0) { if (var_ref->is_detached) { JS_FreeValueRT(rt, var_ref->value); remove_gc_object(&var_ref->header); } else { list_del(&var_ref->header.link); /* still on the stack */ } js_free_rt(rt, var_ref); } } } static void js_array_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p = JS_VALUE_GET_OBJ(val); int i; for(i = 0; i < p->u.array.count; i++) { JS_FreeValueRT(rt, p->u.array.u.values[i]); } js_free_rt(rt, p->u.array.u.values); } static void js_array_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); int i; for(i = 0; i < p->u.array.count; i++) { JS_MarkValue(rt, p->u.array.u.values[i], mark_func); } } static void js_object_data_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p = JS_VALUE_GET_OBJ(val); JS_FreeValueRT(rt, p->u.object_data); p->u.object_data = JS_UNDEFINED; } static void js_object_data_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); JS_MarkValue(rt, p->u.object_data, mark_func); } static void js_c_function_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p = JS_VALUE_GET_OBJ(val); if (p->u.cfunc.realm) JS_FreeContext(p->u.cfunc.realm); } static void js_c_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); if (p->u.cfunc.realm) mark_func(rt, &p->u.cfunc.realm->header); } static void js_bytecode_function_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p1, *p = JS_VALUE_GET_OBJ(val); JSFunctionBytecode *b; JSVarRef **var_refs; int i; p1 = p->u.func.home_object; if (p1) { JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, p1)); } b = p->u.func.function_bytecode; if (b) { var_refs = p->u.func.var_refs; if (var_refs) { for(i = 0; i < b->closure_var_count; i++) free_var_ref(rt, var_refs[i]); js_free_rt(rt, var_refs); } JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b)); } } static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); JSVarRef **var_refs = p->u.func.var_refs; JSFunctionBytecode *b = p->u.func.function_bytecode; int i; if (p->u.func.home_object) { JS_MarkValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object), mark_func); } if (b) { if (var_refs) { for(i = 0; i < b->closure_var_count; i++) { JSVarRef *var_ref = var_refs[i]; if (var_ref && var_ref->is_detached) { mark_func(rt, &var_ref->header); } } } /* must mark the function bytecode because template objects may be part of a cycle */ JS_MarkValue(rt, JS_MKPTR(JS_TAG_FUNCTION_BYTECODE, b), mark_func); } } static void js_bound_function_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p = JS_VALUE_GET_OBJ(val); JSBoundFunction *bf = p->u.bound_function; int i; JS_FreeValueRT(rt, bf->func_obj); JS_FreeValueRT(rt, bf->this_val); for(i = 0; i < bf->argc; i++) { JS_FreeValueRT(rt, bf->argv[i]); } js_free_rt(rt, bf); } static void js_bound_function_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); JSBoundFunction *bf = p->u.bound_function; int i; JS_MarkValue(rt, bf->func_obj, mark_func); JS_MarkValue(rt, bf->this_val, mark_func); for(i = 0; i < bf->argc; i++) JS_MarkValue(rt, bf->argv[i], mark_func); } static void js_for_in_iterator_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p = JS_VALUE_GET_OBJ(val); JSForInIterator *it = p->u.for_in_iterator; JS_FreeValueRT(rt, it->obj); js_free_rt(rt, it); } static void js_for_in_iterator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); JSForInIterator *it = p->u.for_in_iterator; JS_MarkValue(rt, it->obj, mark_func); } static void free_object(JSRuntime *rt, JSObject *p) { int i; JSClassFinalizer *finalizer; JSShape *sh; JSShapeProperty *pr; p->free_mark = 1; /* used to tell the object is invalid when freeing cycles */ /* free all the fields */ sh = p->shape; pr = get_shape_prop(sh); for(i = 0; i < sh->prop_count; i++) { free_property(rt, &p->prop[i], pr->flags); pr++; } js_free_rt(rt, p->prop); /* as an optimization we destroy the shape immediately without putting it in gc_zero_ref_count_list */ js_free_shape(rt, sh); /* fail safe */ p->shape = NULL; p->prop = NULL; if (unlikely(p->first_weak_ref)) { reset_weak_ref(rt, &p->first_weak_ref); } finalizer = rt->class_array[p->class_id].finalizer; if (finalizer) (*finalizer)(rt, JS_MKPTR(JS_TAG_OBJECT, p)); /* fail safe */ p->class_id = 0; p->u.opaque = NULL; p->u.func.var_refs = NULL; p->u.func.home_object = NULL; remove_gc_object(&p->header); if (rt->gc_phase == JS_GC_PHASE_REMOVE_CYCLES && p->header.ref_count != 0) { list_add_tail(&p->header.link, &rt->gc_zero_ref_count_list); } else { js_free_rt(rt, p); } } static void free_gc_object(JSRuntime *rt, JSGCObjectHeader *gp) { switch(gp->gc_obj_type) { case JS_GC_OBJ_TYPE_JS_OBJECT: free_object(rt, (JSObject *)gp); break; case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: free_function_bytecode(rt, (JSFunctionBytecode *)gp); break; default: abort(); } } static void free_zero_refcount(JSRuntime *rt) { struct list_head *el; JSGCObjectHeader *p; rt->gc_phase = JS_GC_PHASE_DECREF; for(;;) { el = rt->gc_zero_ref_count_list.next; if (el == &rt->gc_zero_ref_count_list) break; p = list_entry(el, JSGCObjectHeader, link); assert(p->ref_count == 0); free_gc_object(rt, p); } rt->gc_phase = JS_GC_PHASE_NONE; } /* called with the ref_count of 'v' reaches zero. */ static void js_free_value_rt(JSRuntime *rt, JSValue v) { uint32_t tag = JS_VALUE_GET_TAG(v); #ifdef ENABLE_DUMPS // JS_DUMP_FREE if (check_dump_flag(rt, JS_DUMP_FREE)) { /* Prevent invalid object access during GC */ if ((rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) || (tag != JS_TAG_OBJECT && tag != JS_TAG_FUNCTION_BYTECODE)) { printf("Freeing "); if (tag == JS_TAG_OBJECT) { JS_DumpObject(rt, JS_VALUE_GET_OBJ(v)); } else { JS_DumpValue(rt, v); printf("\n"); } } } #endif switch(tag) { case JS_TAG_STRING: js_free_string0(rt, JS_VALUE_GET_STRING(v)); break; case JS_TAG_OBJECT: case JS_TAG_FUNCTION_BYTECODE: { JSGCObjectHeader *p = JS_VALUE_GET_PTR(v); if (rt->gc_phase != JS_GC_PHASE_REMOVE_CYCLES) { list_del(&p->link); list_add(&p->link, &rt->gc_zero_ref_count_list); if (rt->gc_phase == JS_GC_PHASE_NONE) { free_zero_refcount(rt); } } } break; case JS_TAG_MODULE: abort(); /* never freed here */ break; case JS_TAG_BIG_INT: { JSBigInt *p = JS_VALUE_GET_PTR(v); js_free_rt(rt, p); } break; case JS_TAG_SYMBOL: { JSAtomStruct *p = JS_VALUE_GET_PTR(v); JS_FreeAtomStruct(rt, p); } break; default: printf("js_free_value_rt: unknown tag=%d\n", tag); abort(); } } void JS_FreeValueRT(JSRuntime *rt, JSValue v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); if (--p->ref_count <= 0) { js_free_value_rt(rt, v); } } } void JS_FreeValue(JSContext *ctx, JSValue v) { JS_FreeValueRT(ctx->rt, v); } /* garbage collection */ static void add_gc_object(JSRuntime *rt, JSGCObjectHeader *h, JSGCObjectTypeEnum type) { h->mark = 0; h->gc_obj_type = type; list_add_tail(&h->link, &rt->gc_obj_list); } static void remove_gc_object(JSGCObjectHeader *h) { list_del(&h->link); } void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { if (JS_VALUE_HAS_REF_COUNT(val)) { switch(JS_VALUE_GET_TAG(val)) { case JS_TAG_OBJECT: case JS_TAG_FUNCTION_BYTECODE: mark_func(rt, JS_VALUE_GET_PTR(val)); break; default: break; } } } static void mark_weak_map_value(JSRuntime *rt, JSWeakRefRecord *first_weak_ref, JS_MarkFunc *mark_func) { JSWeakRefRecord *wr; JSMapRecord *mr; JSMapState *s; for (wr = first_weak_ref; wr != NULL; wr = wr->next_weak_ref) { if (wr->kind == JS_WEAK_REF_KIND_MAP) { mr = wr->u.map_record; s = mr->map; assert(s->is_weak); assert(!mr->empty); /* no iterator on WeakMap/WeakSet */ JS_MarkValue(rt, mr->value, mark_func); } } } static void mark_children(JSRuntime *rt, JSGCObjectHeader *gp, JS_MarkFunc *mark_func) { switch(gp->gc_obj_type) { case JS_GC_OBJ_TYPE_JS_OBJECT: { JSObject *p = (JSObject *)gp; JSShapeProperty *prs; JSShape *sh; int i; sh = p->shape; mark_func(rt, &sh->header); /* mark all the fields */ prs = get_shape_prop(sh); for(i = 0; i < sh->prop_count; i++) { JSProperty *pr = &p->prop[i]; if (prs->atom != JS_ATOM_NULL) { if (prs->flags & JS_PROP_TMASK) { if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { if (pr->u.getset.getter) mark_func(rt, &pr->u.getset.getter->header); if (pr->u.getset.setter) mark_func(rt, &pr->u.getset.setter->header); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { if (pr->u.var_ref->is_detached) { /* Note: the tag does not matter provided it is a GC object */ mark_func(rt, &pr->u.var_ref->header); } } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { js_autoinit_mark(rt, pr, mark_func); } } else { JS_MarkValue(rt, pr->u.value, mark_func); } } prs++; } if (unlikely(p->first_weak_ref)) { mark_weak_map_value(rt, p->first_weak_ref, mark_func); } if (p->class_id != JS_CLASS_OBJECT) { JSClassGCMark *gc_mark; gc_mark = rt->class_array[p->class_id].gc_mark; if (gc_mark) gc_mark(rt, JS_MKPTR(JS_TAG_OBJECT, p), mark_func); } } break; case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: /* the template objects can be part of a cycle */ { JSFunctionBytecode *b = (JSFunctionBytecode *)gp; int i; for(i = 0; i < b->cpool_count; i++) { JS_MarkValue(rt, b->cpool[i], mark_func); } if (b->realm) mark_func(rt, &b->realm->header); } break; case JS_GC_OBJ_TYPE_VAR_REF: { JSVarRef *var_ref = (JSVarRef *)gp; /* only detached variable referenced are taken into account */ assert(var_ref->is_detached); JS_MarkValue(rt, *var_ref->pvalue, mark_func); } break; case JS_GC_OBJ_TYPE_ASYNC_FUNCTION: { JSAsyncFunctionData *s = (JSAsyncFunctionData *)gp; if (s->is_active) async_func_mark(rt, &s->func_state, mark_func); JS_MarkValue(rt, s->resolving_funcs[0], mark_func); JS_MarkValue(rt, s->resolving_funcs[1], mark_func); } break; case JS_GC_OBJ_TYPE_SHAPE: { JSShape *sh = (JSShape *)gp; if (sh->proto != NULL) { mark_func(rt, &sh->proto->header); } } break; case JS_GC_OBJ_TYPE_JS_CONTEXT: { JSContext *ctx = (JSContext *)gp; JS_MarkContext(rt, ctx, mark_func); } break; default: abort(); } } static void gc_decref_child(JSRuntime *rt, JSGCObjectHeader *p) { assert(p->ref_count > 0); p->ref_count--; if (p->ref_count == 0 && p->mark == 1) { list_del(&p->link); list_add_tail(&p->link, &rt->tmp_obj_list); } } static void gc_decref(JSRuntime *rt) { struct list_head *el, *el1; JSGCObjectHeader *p; init_list_head(&rt->tmp_obj_list); /* decrement the refcount of all the children of all the GC objects and move the GC objects with zero refcount to tmp_obj_list */ list_for_each_safe(el, el1, &rt->gc_obj_list) { p = list_entry(el, JSGCObjectHeader, link); assert(p->mark == 0); mark_children(rt, p, gc_decref_child); p->mark = 1; if (p->ref_count == 0) { list_del(&p->link); list_add_tail(&p->link, &rt->tmp_obj_list); } } } static void gc_scan_incref_child(JSRuntime *rt, JSGCObjectHeader *p) { p->ref_count++; if (p->ref_count == 1) { /* ref_count was 0: remove from tmp_obj_list and add at the end of gc_obj_list */ list_del(&p->link); list_add_tail(&p->link, &rt->gc_obj_list); p->mark = 0; /* reset the mark for the next GC call */ } } static void gc_scan_incref_child2(JSRuntime *rt, JSGCObjectHeader *p) { p->ref_count++; } static void gc_scan(JSRuntime *rt) { struct list_head *el; JSGCObjectHeader *p; /* keep the objects with a refcount > 0 and their children. */ list_for_each(el, &rt->gc_obj_list) { p = list_entry(el, JSGCObjectHeader, link); assert(p->ref_count > 0); p->mark = 0; /* reset the mark for the next GC call */ mark_children(rt, p, gc_scan_incref_child); } /* restore the refcount of the objects to be deleted. */ list_for_each(el, &rt->tmp_obj_list) { p = list_entry(el, JSGCObjectHeader, link); mark_children(rt, p, gc_scan_incref_child2); } } static void gc_free_cycles(JSRuntime *rt) { struct list_head *el, *el1; JSGCObjectHeader *p; #ifdef ENABLE_DUMPS // JS_DUMP_GC_FREE bool header_done = false; #endif rt->gc_phase = JS_GC_PHASE_REMOVE_CYCLES; for(;;) { el = rt->tmp_obj_list.next; if (el == &rt->tmp_obj_list) break; p = list_entry(el, JSGCObjectHeader, link); /* Only need to free the GC object associated with JS values. The rest will be automatically removed because they must be referenced by them. */ switch(p->gc_obj_type) { case JS_GC_OBJ_TYPE_JS_OBJECT: case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: #ifdef ENABLE_DUMPS // JS_DUMP_GC_FREE if (check_dump_flag(rt, JS_DUMP_GC_FREE)) { if (!header_done) { printf("Freeing cycles:\n"); JS_DumpObjectHeader(rt); header_done = true; } JS_DumpGCObject(rt, p); } #endif free_gc_object(rt, p); break; default: list_del(&p->link); list_add_tail(&p->link, &rt->gc_zero_ref_count_list); break; } } rt->gc_phase = JS_GC_PHASE_NONE; list_for_each_safe(el, el1, &rt->gc_zero_ref_count_list) { p = list_entry(el, JSGCObjectHeader, link); assert(p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT || p->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE); js_free_rt(rt, p); } init_list_head(&rt->gc_zero_ref_count_list); } void JS_RunGC(JSRuntime *rt) { /* decrement the reference of the children of each object. mark = 1 after this pass. */ gc_decref(rt); /* keep the GC objects with a non zero refcount and their childs */ gc_scan(rt); /* free the GC objects in a cycle */ gc_free_cycles(rt); } /* Return false if not an object or if the object has already been freed (zombie objects are visible in finalizers when freeing cycles). */ bool JS_IsLiveObject(JSRuntime *rt, JSValueConst obj) { JSObject *p; if (!JS_IsObject(obj)) return false; p = JS_VALUE_GET_OBJ(obj); return !p->free_mark; } /* Compute memory used by various object types */ /* XXX: poor man's approach to handling multiply referenced objects */ typedef struct JSMemoryUsage_helper { double memory_used_count; double str_count; double str_size; int64_t js_func_count; double js_func_size; int64_t js_func_code_size; int64_t js_func_pc2line_count; int64_t js_func_pc2line_size; } JSMemoryUsage_helper; static void compute_value_size(JSValue val, JSMemoryUsage_helper *hp); static void compute_jsstring_size(JSString *str, JSMemoryUsage_helper *hp) { if (!str->atom_type) { /* atoms are handled separately */ double s_ref_count = str->header.ref_count; hp->str_count += 1 / s_ref_count; hp->str_size += ((sizeof(*str) + (str->len << str->is_wide_char) + 1 - str->is_wide_char) / s_ref_count); } } static void compute_bytecode_size(JSFunctionBytecode *b, JSMemoryUsage_helper *hp) { int memory_used_count, js_func_size, i; memory_used_count = 0; js_func_size = sizeof(*b); if (b->vardefs) { js_func_size += (b->arg_count + b->var_count) * sizeof(*b->vardefs); } if (b->cpool) { js_func_size += b->cpool_count * sizeof(*b->cpool); for (i = 0; i < b->cpool_count; i++) { JSValue val = b->cpool[i]; compute_value_size(val, hp); } } if (b->closure_var) { js_func_size += b->closure_var_count * sizeof(*b->closure_var); } if (b->byte_code_buf) { hp->js_func_code_size += b->byte_code_len; } memory_used_count++; js_func_size += b->source_len + 1; if (b->pc2line_len) { memory_used_count++; hp->js_func_pc2line_count += 1; hp->js_func_pc2line_size += b->pc2line_len; } hp->js_func_size += js_func_size; hp->js_func_count += 1; hp->memory_used_count += memory_used_count; } static void compute_value_size(JSValue val, JSMemoryUsage_helper *hp) { switch(JS_VALUE_GET_TAG(val)) { case JS_TAG_STRING: compute_jsstring_size(JS_VALUE_GET_STRING(val), hp); break; case JS_TAG_BIG_INT: /* should track JSBigInt usage */ break; } } void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s) { struct list_head *el, *el1; int i; JSMemoryUsage_helper mem = { 0 }, *hp = &mem; memset(s, 0, sizeof(*s)); s->malloc_count = rt->malloc_state.malloc_count; s->malloc_size = rt->malloc_state.malloc_size; s->malloc_limit = rt->malloc_state.malloc_limit; s->memory_used_count = 2; /* rt + rt->class_array */ s->memory_used_size = sizeof(JSRuntime) + sizeof(JSClass) * rt->class_count; list_for_each(el, &rt->context_list) { JSContext *ctx = list_entry(el, JSContext, link); JSShape *sh = ctx->array_shape; s->memory_used_count += 2; /* ctx + ctx->class_proto */ s->memory_used_size += sizeof(JSContext) + sizeof(JSValue) * rt->class_count; s->binary_object_count += ctx->binary_object_count; s->binary_object_size += ctx->binary_object_size; /* the hashed shapes are counted separately */ if (sh && !sh->is_hashed) { int hash_size = sh->prop_hash_mask + 1; s->shape_count++; s->shape_size += get_shape_size(hash_size, sh->prop_size); } list_for_each(el1, &ctx->loaded_modules) { JSModuleDef *m = list_entry(el1, JSModuleDef, link); s->memory_used_count += 1; s->memory_used_size += sizeof(*m); if (m->req_module_entries) { s->memory_used_count += 1; s->memory_used_size += m->req_module_entries_count * sizeof(*m->req_module_entries); } if (m->export_entries) { s->memory_used_count += 1; s->memory_used_size += m->export_entries_count * sizeof(*m->export_entries); for (i = 0; i < m->export_entries_count; i++) { JSExportEntry *me = &m->export_entries[i]; if (me->export_type == JS_EXPORT_TYPE_LOCAL && me->u.local.var_ref) { /* potential multiple count */ s->memory_used_count += 1; compute_value_size(me->u.local.var_ref->value, hp); } } } if (m->star_export_entries) { s->memory_used_count += 1; s->memory_used_size += m->star_export_entries_count * sizeof(*m->star_export_entries); } if (m->import_entries) { s->memory_used_count += 1; s->memory_used_size += m->import_entries_count * sizeof(*m->import_entries); } compute_value_size(m->module_ns, hp); compute_value_size(m->func_obj, hp); } } list_for_each(el, &rt->gc_obj_list) { JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link); JSObject *p; JSShape *sh; JSShapeProperty *prs; /* XXX: could count the other GC object types too */ if (gp->gc_obj_type == JS_GC_OBJ_TYPE_FUNCTION_BYTECODE) { compute_bytecode_size((JSFunctionBytecode *)gp, hp); continue; } else if (gp->gc_obj_type != JS_GC_OBJ_TYPE_JS_OBJECT) { continue; } p = (JSObject *)gp; sh = p->shape; s->obj_count++; if (p->prop) { s->memory_used_count++; s->prop_size += sh->prop_size * sizeof(*p->prop); s->prop_count += sh->prop_count; prs = get_shape_prop(sh); for(i = 0; i < sh->prop_count; i++) { JSProperty *pr = &p->prop[i]; if (prs->atom != JS_ATOM_NULL && !(prs->flags & JS_PROP_TMASK)) { compute_value_size(pr->u.value, hp); } prs++; } } /* the hashed shapes are counted separately */ if (!sh->is_hashed) { int hash_size = sh->prop_hash_mask + 1; s->shape_count++; s->shape_size += get_shape_size(hash_size, sh->prop_size); } switch(p->class_id) { case JS_CLASS_ARRAY: /* u.array | length */ case JS_CLASS_ARGUMENTS: /* u.array | length */ s->array_count++; if (p->fast_array) { s->fast_array_count++; if (p->u.array.u.values) { s->memory_used_count++; s->memory_used_size += p->u.array.count * sizeof(*p->u.array.u.values); s->fast_array_elements += p->u.array.count; for (i = 0; i < p->u.array.count; i++) { compute_value_size(p->u.array.u.values[i], hp); } } } break; case JS_CLASS_NUMBER: /* u.object_data */ case JS_CLASS_STRING: /* u.object_data */ case JS_CLASS_BOOLEAN: /* u.object_data */ case JS_CLASS_SYMBOL: /* u.object_data */ case JS_CLASS_DATE: /* u.object_data */ case JS_CLASS_BIG_INT: /* u.object_data */ compute_value_size(p->u.object_data, hp); break; case JS_CLASS_C_FUNCTION: /* u.cfunc */ s->c_func_count++; break; case JS_CLASS_BYTECODE_FUNCTION: /* u.func */ { JSFunctionBytecode *b = p->u.func.function_bytecode; JSVarRef **var_refs = p->u.func.var_refs; /* home_object: object will be accounted for in list scan */ if (var_refs) { s->memory_used_count++; s->js_func_size += b->closure_var_count * sizeof(*var_refs); for (i = 0; i < b->closure_var_count; i++) { if (var_refs[i]) { double ref_count = var_refs[i]->header.ref_count; s->memory_used_count += 1 / ref_count; s->js_func_size += sizeof(*var_refs[i]) / ref_count; /* handle non object closed values */ if (var_refs[i]->pvalue == &var_refs[i]->value) { /* potential multiple count */ compute_value_size(var_refs[i]->value, hp); } } } } } break; case JS_CLASS_BOUND_FUNCTION: /* u.bound_function */ { JSBoundFunction *bf = p->u.bound_function; /* func_obj and this_val are objects */ for (i = 0; i < bf->argc; i++) { compute_value_size(bf->argv[i], hp); } s->memory_used_count += 1; s->memory_used_size += sizeof(*bf) + bf->argc * sizeof(*bf->argv); } break; case JS_CLASS_C_FUNCTION_DATA: /* u.c_function_data_record */ { JSCFunctionDataRecord *fd = p->u.c_function_data_record; if (fd) { for (i = 0; i < fd->data_len; i++) { compute_value_size(fd->data[i], hp); } s->memory_used_count += 1; s->memory_used_size += sizeof(*fd) + fd->data_len * sizeof(*fd->data); } } break; case JS_CLASS_REGEXP: /* u.regexp */ compute_jsstring_size(p->u.regexp.pattern, hp); compute_jsstring_size(p->u.regexp.bytecode, hp); break; case JS_CLASS_FOR_IN_ITERATOR: /* u.for_in_iterator */ { JSForInIterator *it = p->u.for_in_iterator; if (it) { compute_value_size(it->obj, hp); s->memory_used_count += 1; s->memory_used_size += sizeof(*it); } } break; case JS_CLASS_ARRAY_BUFFER: /* u.array_buffer */ case JS_CLASS_SHARED_ARRAY_BUFFER: /* u.array_buffer */ { JSArrayBuffer *abuf = p->u.array_buffer; if (abuf) { s->memory_used_count += 1; s->memory_used_size += sizeof(*abuf); if (abuf->data) { s->memory_used_count += 1; s->memory_used_size += abuf->byte_length; } } } break; case JS_CLASS_GENERATOR: /* u.generator_data */ case JS_CLASS_UINT8C_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_INT8_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_UINT8_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_INT16_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_UINT16_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_INT32_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_UINT32_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_BIG_INT64_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_BIG_UINT64_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_FLOAT16_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_FLOAT32_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_FLOAT64_ARRAY: /* u.typed_array / u.array */ case JS_CLASS_DATAVIEW: /* u.typed_array */ case JS_CLASS_MAP: /* u.map_state */ case JS_CLASS_SET: /* u.map_state */ case JS_CLASS_WEAKMAP: /* u.map_state */ case JS_CLASS_WEAKSET: /* u.map_state */ case JS_CLASS_MAP_ITERATOR: /* u.map_iterator_data */ case JS_CLASS_SET_ITERATOR: /* u.map_iterator_data */ case JS_CLASS_ARRAY_ITERATOR: /* u.array_iterator_data */ case JS_CLASS_STRING_ITERATOR: /* u.array_iterator_data */ case JS_CLASS_PROXY: /* u.proxy_data */ case JS_CLASS_PROMISE: /* u.promise_data */ case JS_CLASS_PROMISE_RESOLVE_FUNCTION: /* u.promise_function_data */ case JS_CLASS_PROMISE_REJECT_FUNCTION: /* u.promise_function_data */ case JS_CLASS_ASYNC_FUNCTION_RESOLVE: /* u.async_function_data */ case JS_CLASS_ASYNC_FUNCTION_REJECT: /* u.async_function_data */ case JS_CLASS_ASYNC_FROM_SYNC_ITERATOR: /* u.async_from_sync_iterator_data */ case JS_CLASS_ASYNC_GENERATOR: /* u.async_generator_data */ /* TODO */ default: /* XXX: class definition should have an opaque block size */ if (p->u.opaque) { s->memory_used_count += 1; } break; } } s->obj_size += s->obj_count * sizeof(JSObject); /* hashed shapes */ s->memory_used_count++; /* rt->shape_hash */ s->memory_used_size += sizeof(rt->shape_hash[0]) * rt->shape_hash_size; for(i = 0; i < rt->shape_hash_size; i++) { JSShape *sh; for(sh = rt->shape_hash[i]; sh != NULL; sh = sh->shape_hash_next) { int hash_size = sh->prop_hash_mask + 1; s->shape_count++; s->shape_size += get_shape_size(hash_size, sh->prop_size); } } /* atoms */ s->memory_used_count += 2; /* rt->atom_array, rt->atom_hash */ s->atom_count = rt->atom_count; s->atom_size = sizeof(rt->atom_array[0]) * rt->atom_size + sizeof(rt->atom_hash[0]) * rt->atom_hash_size; for(i = 0; i < rt->atom_size; i++) { JSAtomStruct *p = rt->atom_array[i]; if (!atom_is_free(p)) { s->atom_size += (sizeof(*p) + (p->len << p->is_wide_char) + 1 - p->is_wide_char); } } s->str_count = round(mem.str_count); s->str_size = round(mem.str_size); s->js_func_count = mem.js_func_count; s->js_func_size = round(mem.js_func_size); s->js_func_code_size = mem.js_func_code_size; s->js_func_pc2line_count = mem.js_func_pc2line_count; s->js_func_pc2line_size = mem.js_func_pc2line_size; s->memory_used_count += round(mem.memory_used_count) + s->atom_count + s->str_count + s->obj_count + s->shape_count + s->js_func_count + s->js_func_pc2line_count; s->memory_used_size += s->atom_size + s->str_size + s->obj_size + s->prop_size + s->shape_size + s->js_func_size + s->js_func_code_size + s->js_func_pc2line_size; } void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt) { fprintf(fp, "QuickJS-ng memory usage -- %s version, %d-bit, %s Endian, malloc limit: %"PRId64"\n\n", JS_GetVersion(), (int)sizeof(void *) * 8, is_be() ? "Big" : "Little", s->malloc_limit); if (rt) { static const struct { const char *name; size_t size; } object_types[] = { { "JSRuntime", sizeof(JSRuntime) }, { "JSContext", sizeof(JSContext) }, { "JSObject", sizeof(JSObject) }, { "JSString", sizeof(JSString) }, { "JSFunctionBytecode", sizeof(JSFunctionBytecode) }, }; int i, usage_size_ok = 0; for(i = 0; i < countof(object_types); i++) { unsigned int size = object_types[i].size; void *p = js_malloc_rt(rt, size); if (p) { unsigned int size1 = js_malloc_usable_size_rt(rt, p); if (size1 >= size) { usage_size_ok = 1; fprintf(fp, " %3u + %-2u %s\n", size, size1 - size, object_types[i].name); } js_free_rt(rt, p); } } if (!usage_size_ok) { fprintf(fp, " malloc_usable_size unavailable\n"); } { int obj_classes[JS_CLASS_INIT_COUNT + 1] = { 0 }; int class_id; struct list_head *el; list_for_each(el, &rt->gc_obj_list) { JSGCObjectHeader *gp = list_entry(el, JSGCObjectHeader, link); JSObject *p; if (gp->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) { p = (JSObject *)gp; obj_classes[min_uint32(p->class_id, JS_CLASS_INIT_COUNT)]++; } } fprintf(fp, "\n" "JSObject classes\n"); if (obj_classes[0]) fprintf(fp, " %5d %2.0d %s\n", obj_classes[0], 0, "none"); for (class_id = 1; class_id < JS_CLASS_INIT_COUNT; class_id++) { if (obj_classes[class_id] && class_id < rt->class_count) { char buf[ATOM_GET_STR_BUF_SIZE]; fprintf(fp, " %5d %2.0d %s\n", obj_classes[class_id], class_id, JS_AtomGetStrRT(rt, buf, sizeof(buf), rt->class_array[class_id].class_name)); } } if (obj_classes[JS_CLASS_INIT_COUNT]) fprintf(fp, " %5d %2.0d %s\n", obj_classes[JS_CLASS_INIT_COUNT], 0, "other"); } fprintf(fp, "\n"); } fprintf(fp, "%-20s %8s %8s\n", "NAME", "COUNT", "SIZE"); if (s->malloc_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per block)\n", "memory allocated", s->malloc_count, s->malloc_size, (double)s->malloc_size / s->malloc_count); fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%d overhead, %0.1f average slack)\n", "memory used", s->memory_used_count, s->memory_used_size, MALLOC_OVERHEAD, ((double)(s->malloc_size - s->memory_used_size) / s->memory_used_count)); } if (s->atom_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per atom)\n", "atoms", s->atom_count, s->atom_size, (double)s->atom_size / s->atom_count); } if (s->str_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per string)\n", "strings", s->str_count, s->str_size, (double)s->str_size / s->str_count); } if (s->obj_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per object)\n", "objects", s->obj_count, s->obj_size, (double)s->obj_size / s->obj_count); fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per object)\n", " properties", s->prop_count, s->prop_size, (double)s->prop_count / s->obj_count); fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per shape)\n", " shapes", s->shape_count, s->shape_size, (double)s->shape_size / s->shape_count); } if (s->js_func_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64"\n", "bytecode functions", s->js_func_count, s->js_func_size); fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per function)\n", " bytecode", s->js_func_count, s->js_func_code_size, (double)s->js_func_code_size / s->js_func_count); if (s->js_func_pc2line_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per function)\n", " pc2line", s->js_func_pc2line_count, s->js_func_pc2line_size, (double)s->js_func_pc2line_size / s->js_func_pc2line_count); } } if (s->c_func_count) { fprintf(fp, "%-20s %8"PRId64"\n", "C functions", s->c_func_count); } if (s->array_count) { fprintf(fp, "%-20s %8"PRId64"\n", "arrays", s->array_count); if (s->fast_array_count) { fprintf(fp, "%-20s %8"PRId64"\n", " fast arrays", s->fast_array_count); fprintf(fp, "%-20s %8"PRId64" %8"PRId64" (%0.1f per fast array)\n", " elements", s->fast_array_elements, s->fast_array_elements * (int)sizeof(JSValue), (double)s->fast_array_elements / s->fast_array_count); } } if (s->binary_object_count) { fprintf(fp, "%-20s %8"PRId64" %8"PRId64"\n", "binary objects", s->binary_object_count, s->binary_object_size); } } JSValue JS_GetGlobalObject(JSContext *ctx) { return js_dup(ctx->global_obj); } /* WARNING: obj is freed */ JSValue JS_Throw(JSContext *ctx, JSValue obj) { JSRuntime *rt = ctx->rt; JS_FreeValue(ctx, rt->current_exception); rt->current_exception = obj; return JS_EXCEPTION; } /* return the pending exception (cannot be called twice). */ JSValue JS_GetException(JSContext *ctx) { JSValue val; JSRuntime *rt = ctx->rt; val = rt->current_exception; rt->current_exception = JS_UNINITIALIZED; return val; } bool JS_HasException(JSContext *ctx) { return !JS_IsUninitialized(ctx->rt->current_exception); } static void dbuf_put_leb128(DynBuf *s, uint32_t v) { uint32_t a; for(;;) { a = v & 0x7f; v >>= 7; if (v != 0) { dbuf_putc(s, a | 0x80); } else { dbuf_putc(s, a); break; } } } static void dbuf_put_sleb128(DynBuf *s, int32_t v1) { uint32_t v = v1; dbuf_put_leb128(s, (2 * v) ^ -(v >> 31)); } static int get_leb128(uint32_t *pval, const uint8_t *buf, const uint8_t *buf_end) { const uint8_t *ptr = buf; uint32_t v, a, i; v = 0; for(i = 0; i < 5; i++) { if (unlikely(ptr >= buf_end)) break; a = *ptr++; v |= (a & 0x7f) << (i * 7); if (!(a & 0x80)) { *pval = v; return ptr - buf; } } *pval = 0; return -1; } static int get_sleb128(int32_t *pval, const uint8_t *buf, const uint8_t *buf_end) { int ret; uint32_t val; ret = get_leb128(&val, buf, buf_end); if (ret < 0) { *pval = 0; return -1; } *pval = (val >> 1) ^ -(val & 1); return ret; } static int find_line_num(JSContext *ctx, JSFunctionBytecode *b, uint32_t pc_value, int *col) { const uint8_t *p_end, *p; int new_line_num, new_col_num, line_num, col_num, pc, v, ret; unsigned int op; *col = 1; p = b->pc2line_buf; if (!p) goto fail; p_end = p + b->pc2line_len; pc = 0; line_num = b->line_num; col_num = b->col_num; while (p < p_end) { op = *p++; if (op == 0) { uint32_t val; ret = get_leb128(&val, p, p_end); if (ret < 0) goto fail; pc += val; p += ret; ret = get_sleb128(&v, p, p_end); if (ret < 0) goto fail; p += ret; new_line_num = line_num + v; } else { op -= PC2LINE_OP_FIRST; pc += (op / PC2LINE_RANGE); new_line_num = line_num + (op % PC2LINE_RANGE) + PC2LINE_BASE; } ret = get_sleb128(&v, p, p_end); if (ret < 0) goto fail; p += ret; new_col_num = col_num + v; if (pc_value < pc) break; line_num = new_line_num; col_num = new_col_num; } *col = col_num; return line_num; fail: /* should never happen */ return b->line_num; } /* in order to avoid executing arbitrary code during the stack trace generation, we only look at simple 'name' properties containing a string. */ static const char *get_func_name(JSContext *ctx, JSValueConst func) { JSProperty *pr; JSShapeProperty *prs; JSValue val; if (JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT) return NULL; prs = find_own_property(&pr, JS_VALUE_GET_OBJ(func), JS_ATOM_name); if (!prs) return NULL; if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL) return NULL; val = pr->u.value; if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) return NULL; return JS_ToCString(ctx, val); } /* Note: it is important that no exception is returned by this function */ static bool can_add_backtrace(JSValueConst obj) { JSObject *p; if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(obj); if (p->class_id != JS_CLASS_ERROR && p->class_id != JS_CLASS_DOM_EXCEPTION) return false; if (find_own_property1(p, JS_ATOM_stack)) return false; return true; } #define JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL (1 << 0) /* only taken into account if filename is provided */ #define JS_BACKTRACE_FLAG_SINGLE_LEVEL (1 << 1) #define JS_BACKTRACE_FLAG_FILTER_FUNC (1 << 2) /* if filename != NULL, an additional level is added with the filename and line number information (used for parse error). */ static void build_backtrace(JSContext *ctx, JSValueConst error_val, JSValueConst filter_func, const char *filename, int line_num, int col_num, int backtrace_flags) { JSStackFrame *sf, *sf_start; JSValue stack, prepare, saved_exception; DynBuf dbuf; const char *func_name_str; const char *str1; JSObject *p; JSFunctionBytecode *b; bool backtrace_barrier, has_prepare, has_filter_func; JSRuntime *rt; JSCallSiteData csd[64]; uint32_t i; double d; int stack_trace_limit; rt = ctx->rt; if (rt->in_build_stack_trace) return; rt->in_build_stack_trace = true; // Save exception because conversion to double may fail. saved_exception = JS_GetException(ctx); // Extract stack trace limit. // Ignore error since it sets d to NAN anyway. // coverity[check_return] JS_ToFloat64(ctx, &d, ctx->error_stack_trace_limit); if (isnan(d) || d < 0.0) stack_trace_limit = 0; else if (d > INT32_MAX) stack_trace_limit = INT32_MAX; else stack_trace_limit = fabs(d); // Restore current exception. JS_Throw(ctx, saved_exception); saved_exception = JS_UNINITIALIZED; stack_trace_limit = min_int(stack_trace_limit, countof(csd)); stack_trace_limit = max_int(stack_trace_limit, 0); has_prepare = false; has_filter_func = backtrace_flags & JS_BACKTRACE_FLAG_FILTER_FUNC; i = 0; if (!JS_IsNull(ctx->error_ctor)) { prepare = js_dup(ctx->error_prepare_stack); has_prepare = JS_IsFunction(ctx, prepare); } if (has_prepare) { saved_exception = JS_GetException(ctx); if (stack_trace_limit == 0) goto done; if (filename) js_new_callsite_data2(ctx, &csd[i++], filename, line_num, col_num); } else { js_dbuf_init(ctx, &dbuf); if (stack_trace_limit == 0) goto done; if (filename) { i++; dbuf_printf(&dbuf, " at %s", filename); if (line_num != -1) dbuf_printf(&dbuf, ":%d:%d", line_num, col_num); dbuf_putc(&dbuf, '\n'); } } if (filename && (backtrace_flags & JS_BACKTRACE_FLAG_SINGLE_LEVEL)) goto done; sf_start = rt->current_stack_frame; /* Find the frame we want to start from. Note that when a filter is used the filter function will be the first, but we also specify we want to skip the first one. */ if (has_filter_func) { for (sf = sf_start; sf != NULL && i < stack_trace_limit; sf = sf->prev_frame) { if (js_same_value(ctx, sf->cur_func, filter_func)) { sf_start = sf; break; } } } for (sf = sf_start; sf != NULL && i < stack_trace_limit; sf = sf->prev_frame) { if (backtrace_flags & JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL) { backtrace_flags &= ~JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL; continue; } p = JS_VALUE_GET_OBJ(sf->cur_func); b = NULL; backtrace_barrier = false; if (js_class_has_bytecode(p->class_id)) { b = p->u.func.function_bytecode; backtrace_barrier = b->backtrace_barrier; } if (has_prepare) { js_new_callsite_data(ctx, &csd[i], sf); } else { /* func_name_str is UTF-8 encoded if needed */ func_name_str = get_func_name(ctx, sf->cur_func); if (!func_name_str || func_name_str[0] == '\0') str1 = ""; else str1 = func_name_str; dbuf_printf(&dbuf, " at %s", str1); JS_FreeCString(ctx, func_name_str); if (b && sf->cur_pc) { const char *atom_str; int line_num1, col_num1; uint32_t pc; pc = sf->cur_pc - b->byte_code_buf - 1; line_num1 = find_line_num(ctx, b, pc, &col_num1); atom_str = b->filename ? JS_AtomToCString(ctx, b->filename) : NULL; dbuf_printf(&dbuf, " (%s", atom_str ? atom_str : ""); JS_FreeCString(ctx, atom_str); if (line_num1 != -1) dbuf_printf(&dbuf, ":%d:%d", line_num1, col_num1); dbuf_putc(&dbuf, ')'); } else if (b) { // FIXME(bnoordhuis) Missing `sf->cur_pc = pc` in bytecode // handler in JS_CallInternal. Almost never user observable // except with intercepting JS proxies that throw exceptions. dbuf_printf(&dbuf, " (missing)"); } else { dbuf_printf(&dbuf, " (native)"); } dbuf_putc(&dbuf, '\n'); } i++; /* stop backtrace if JS_EVAL_FLAG_BACKTRACE_BARRIER was used */ if (backtrace_barrier) break; } done: if (has_prepare) { int j = 0, k; stack = JS_NewArray(ctx); if (JS_IsException(stack)) { stack = JS_NULL; } else { for (; j < i; j++) { JSValue v = js_new_callsite(ctx, &csd[j]); if (JS_IsException(v)) break; if (JS_DefinePropertyValueUint32(ctx, stack, j, v, JS_PROP_C_W_E) < 0) { JS_FreeValue(ctx, v); break; } } } // Clear the csd's we didn't use in case of error. for (k = j; k < i; k++) { JS_FreeValue(ctx, csd[k].filename); JS_FreeValue(ctx, csd[k].func); JS_FreeValue(ctx, csd[k].func_name); } JSValueConst args[] = { error_val, stack, }; JSValue stack2 = JS_Call(ctx, prepare, ctx->error_ctor, countof(args), args); JS_FreeValue(ctx, stack); if (JS_IsException(stack2)) stack = JS_NULL; else stack = stack2; JS_FreeValue(ctx, prepare); JS_Throw(ctx, saved_exception); } else { if (dbuf_error(&dbuf)) stack = JS_NULL; else stack = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size); dbuf_free(&dbuf); } if (JS_IsUndefined(ctx->error_back_trace)) ctx->error_back_trace = js_dup(stack); if (has_filter_func || can_add_backtrace(error_val)) { JS_DefinePropertyValue(ctx, error_val, JS_ATOM_stack, stack, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); } else { JS_FreeValue(ctx, stack); } rt->in_build_stack_trace = false; } JSValue JS_NewError(JSContext *ctx) { JSValue obj = JS_NewObjectClass(ctx, JS_CLASS_ERROR); if (JS_IsException(obj)) return JS_EXCEPTION; build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, 0); return obj; } static JSValue JS_MakeError2(JSContext *ctx, JSErrorEnum error_num, bool add_backtrace, const char *message) { JSValue obj, msg; if (error_num == JS_PLAIN_ERROR) { obj = JS_NewObjectClass(ctx, JS_CLASS_ERROR); } else { obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num], JS_CLASS_ERROR); } if (JS_IsException(obj)) return JS_EXCEPTION; msg = JS_NewString(ctx, message); if (JS_IsException(msg)) msg = JS_NewString(ctx, "Invalid error message"); if (!JS_IsException(msg)) { JS_DefinePropertyValue(ctx, obj, JS_ATOM_message, msg, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); } if (add_backtrace) build_backtrace(ctx, obj, JS_UNDEFINED, NULL, 0, 0, 0); return obj; } static JSValue JS_PRINTF_FORMAT_ATTR(4, 0) JS_MakeError(JSContext *ctx, JSErrorEnum error_num, bool add_backtrace, JS_PRINTF_FORMAT const char *fmt, va_list ap) { char buf[256]; vsnprintf(buf, sizeof(buf), fmt, ap); return JS_MakeError2(ctx, error_num, add_backtrace, buf); } /* fmt and arguments may be pure ASCII or UTF-8 encoded contents */ static JSValue JS_PRINTF_FORMAT_ATTR(4, 0) JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num, bool add_backtrace, JS_PRINTF_FORMAT const char *fmt, va_list ap) { JSValue obj; obj = JS_MakeError(ctx, error_num, add_backtrace, fmt, ap); if (unlikely(JS_IsException(obj))) { /* out of memory: throw JS_NULL to avoid recursing */ obj = JS_NULL; } return JS_Throw(ctx, obj); } static JSValue JS_PRINTF_FORMAT_ATTR(3, 0) JS_ThrowError(JSContext *ctx, JSErrorEnum error_num, JS_PRINTF_FORMAT const char *fmt, va_list ap) { JSRuntime *rt = ctx->rt; JSStackFrame *sf; bool add_backtrace; /* the backtrace is added later if called from a bytecode function */ sf = rt->current_stack_frame; add_backtrace = !rt->in_out_of_memory && (!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL)); return JS_ThrowError2(ctx, error_num, add_backtrace, fmt, ap); } #define JS_ERROR_MAP(X) \ X(Internal, INTERNAL) \ X(Plain, PLAIN) \ X(Range, RANGE) \ X(Reference, REFERENCE) \ X(Syntax, SYNTAX) \ X(Type, TYPE) \ #define X(lc, uc) \ JSValue JS_PRINTF_FORMAT_ATTR(2, 3) \ JS_New##lc##Error(JSContext *ctx, \ JS_PRINTF_FORMAT const char *fmt, ...) \ { \ JSValue val; \ va_list ap; \ \ va_start(ap, fmt); \ val = JS_MakeError(ctx, JS_##uc##_ERROR, \ /*add_backtrace*/true, fmt, ap); \ va_end(ap); \ return val; \ } \ JSValue JS_PRINTF_FORMAT_ATTR(2, 3) \ JS_Throw##lc##Error(JSContext *ctx, \ JS_PRINTF_FORMAT const char *fmt, ...) \ { \ JSValue val; \ va_list ap; \ \ va_start(ap, fmt); \ val = JS_ThrowError(ctx, JS_##uc##_ERROR, fmt, ap); \ va_end(ap); \ return val; \ } \ JS_ERROR_MAP(X) #undef X #undef JS_ERROR_MAP static int JS_PRINTF_FORMAT_ATTR(3, 4) JS_ThrowTypeErrorOrFalse(JSContext *ctx, int flags, JS_PRINTF_FORMAT const char *fmt, ...) { va_list ap; if ((flags & JS_PROP_THROW) || ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { va_start(ap, fmt); JS_ThrowError(ctx, JS_TYPE_ERROR, fmt, ap); va_end(ap); return -1; } else { return false; } } static JSValue JS_ThrowTypeErrorAtom(JSContext *ctx, const char *fmt, JSAtom atom) { char buf[ATOM_GET_STR_BUF_SIZE]; JS_AtomGetStr(ctx, buf, sizeof(buf), atom); return JS_ThrowTypeError(ctx, fmt, buf); } static JSValue JS_ThrowSyntaxErrorAtom(JSContext *ctx, const char *fmt, JSAtom atom) { char buf[ATOM_GET_STR_BUF_SIZE]; JS_AtomGetStr(ctx, buf, sizeof(buf), atom); return JS_ThrowSyntaxError(ctx, fmt, buf); } static int JS_ThrowTypeErrorReadOnly(JSContext *ctx, int flags, JSAtom atom) { if ((flags & JS_PROP_THROW) || ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { JS_ThrowTypeErrorAtom(ctx, "'%s' is read-only", atom); return -1; } else { return false; } } JSValue JS_ThrowOutOfMemory(JSContext *ctx) { JSRuntime *rt = ctx->rt; if (!rt->in_out_of_memory) { rt->in_out_of_memory = true; JS_ThrowInternalError(ctx, "out of memory"); rt->in_out_of_memory = false; } return JS_EXCEPTION; } static JSValue JS_ThrowStackOverflow(JSContext *ctx) { return JS_ThrowRangeError(ctx, "Maximum call stack size exceeded"); } static JSValue JS_ThrowTypeErrorNotAConstructor(JSContext *ctx, JSValueConst func_obj) { JSObject *p; JSAtom name; if (JS_TAG_OBJECT != JS_VALUE_GET_TAG(func_obj)) goto fini; p = JS_VALUE_GET_OBJ(func_obj); if (!js_class_has_bytecode(p->class_id)) goto fini; name = p->u.func.function_bytecode->func_name; if (name == JS_ATOM_NULL) goto fini; return JS_ThrowTypeErrorAtom(ctx, "%s is not a constructor", name); fini: return JS_ThrowTypeError(ctx, "not a constructor"); } static JSValue JS_ThrowTypeErrorNotAFunction(JSContext *ctx) { return JS_ThrowTypeError(ctx, "not a function"); } static JSValue JS_ThrowTypeErrorNotAnObject(JSContext *ctx) { return JS_ThrowTypeError(ctx, "not an object"); } static JSValue JS_ThrowTypeErrorNotASymbol(JSContext *ctx) { return JS_ThrowTypeError(ctx, "not a symbol"); } static JSValue JS_ThrowReferenceErrorNotDefined(JSContext *ctx, JSAtom name) { char buf[ATOM_GET_STR_BUF_SIZE]; return JS_ThrowReferenceError(ctx, "%s is not defined", JS_AtomGetStr(ctx, buf, sizeof(buf), name)); } static JSValue JS_ThrowReferenceErrorUninitialized(JSContext *ctx, JSAtom name) { char buf[ATOM_GET_STR_BUF_SIZE]; return JS_ThrowReferenceError(ctx, "%s is not initialized", name == JS_ATOM_NULL ? "lexical variable" : JS_AtomGetStr(ctx, buf, sizeof(buf), name)); } static JSValue JS_ThrowReferenceErrorUninitialized2(JSContext *ctx, JSFunctionBytecode *b, int idx, bool is_ref) { JSAtom atom = JS_ATOM_NULL; if (is_ref) { atom = b->closure_var[idx].var_name; } else { /* not present if the function is stripped and contains no eval() */ if (b->vardefs) atom = b->vardefs[b->arg_count + idx].var_name; } return JS_ThrowReferenceErrorUninitialized(ctx, atom); } static JSValue JS_ThrowTypeErrorInvalidClass(JSContext *ctx, int class_id) { JSRuntime *rt = ctx->rt; JSAtom name; name = rt->class_array[class_id].class_name; return JS_ThrowTypeErrorAtom(ctx, "%s object expected", name); } static void JS_ThrowInterrupted(JSContext *ctx) { JS_ThrowInternalError(ctx, "interrupted"); JS_SetUncatchableError(ctx, ctx->rt->current_exception); } static no_inline __exception int __js_poll_interrupts(JSContext *ctx) { JSRuntime *rt = ctx->rt; ctx->interrupt_counter = JS_INTERRUPT_COUNTER_INIT; if (rt->interrupt_handler) { if (rt->interrupt_handler(rt, rt->interrupt_opaque)) { JS_ThrowInterrupted(ctx); return -1; } } return 0; } static inline __exception int js_poll_interrupts(JSContext *ctx) { if (unlikely(--ctx->interrupt_counter <= 0)) { return __js_poll_interrupts(ctx); } else { return 0; } } /* return -1 (exception) or true/false */ static int JS_SetPrototypeInternal(JSContext *ctx, JSValueConst obj, JSValueConst proto_val, bool throw_flag) { JSObject *proto, *p, *p1; JSShape *sh; if (throw_flag) { if (JS_VALUE_GET_TAG(obj) == JS_TAG_NULL || JS_VALUE_GET_TAG(obj) == JS_TAG_UNDEFINED) goto not_obj; } else { if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) goto not_obj; } p = JS_VALUE_GET_OBJ(obj); if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_OBJECT) { if (JS_VALUE_GET_TAG(proto_val) != JS_TAG_NULL) { not_obj: JS_ThrowTypeErrorNotAnObject(ctx); return -1; } proto = NULL; } else { proto = JS_VALUE_GET_OBJ(proto_val); } if (throw_flag && JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) return true; if (unlikely(p->class_id == JS_CLASS_PROXY)) return js_proxy_setPrototypeOf(ctx, obj, proto_val, throw_flag); sh = p->shape; if (sh->proto == proto) return true; if (p == JS_VALUE_GET_OBJ(ctx->class_proto[JS_CLASS_OBJECT])) { if (throw_flag) { JS_ThrowTypeError(ctx, "'Immutable prototype object \'Object.prototype\' cannot have their prototype set'"); return -1; } return false; } if (!p->extensible) { if (throw_flag) { JS_ThrowTypeError(ctx, "object is not extensible"); return -1; } else { return false; } } if (proto) { /* check if there is a cycle */ p1 = proto; do { if (p1 == p) { if (throw_flag) { JS_ThrowTypeError(ctx, "circular prototype chain"); return -1; } else { return false; } } /* Note: for Proxy objects, proto is NULL */ p1 = p1->shape->proto; } while (p1 != NULL); js_dup(proto_val); } if (js_shape_prepare_update(ctx, p, NULL)) return -1; sh = p->shape; if (sh->proto) JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, sh->proto)); sh->proto = proto; return true; } /* return -1 (exception) or true/false */ int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val) { return JS_SetPrototypeInternal(ctx, obj, proto_val, true); } /* Only works for primitive types, otherwise return JS_NULL. */ static JSValueConst JS_GetPrototypePrimitive(JSContext *ctx, JSValueConst val) { JSValue ret; switch(JS_VALUE_GET_NORM_TAG(val)) { case JS_TAG_SHORT_BIG_INT: case JS_TAG_BIG_INT: ret = ctx->class_proto[JS_CLASS_BIG_INT]; break; case JS_TAG_INT: case JS_TAG_FLOAT64: ret = ctx->class_proto[JS_CLASS_NUMBER]; break; case JS_TAG_BOOL: ret = ctx->class_proto[JS_CLASS_BOOLEAN]; break; case JS_TAG_STRING: ret = ctx->class_proto[JS_CLASS_STRING]; break; case JS_TAG_SYMBOL: ret = ctx->class_proto[JS_CLASS_SYMBOL]; break; case JS_TAG_OBJECT: case JS_TAG_NULL: case JS_TAG_UNDEFINED: default: ret = JS_NULL; break; } return ret; } /* Return an Object, JS_NULL or JS_EXCEPTION in case of Proxy object. */ JSValue JS_GetPrototype(JSContext *ctx, JSValueConst obj) { JSValue val; if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { JSObject *p; p = JS_VALUE_GET_OBJ(obj); if (unlikely(p->class_id == JS_CLASS_PROXY)) { val = js_proxy_getPrototypeOf(ctx, obj); } else { p = p->shape->proto; if (!p) val = JS_NULL; else val = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); } } else { val = js_dup(JS_GetPrototypePrimitive(ctx, obj)); } return val; } static JSValue JS_GetPrototypeFree(JSContext *ctx, JSValue obj) { JSValue obj1; obj1 = JS_GetPrototype(ctx, obj); JS_FreeValue(ctx, obj); return obj1; } int JS_GetLength(JSContext *ctx, JSValueConst obj, int64_t *pres) { return js_get_length64(ctx, pres, obj); } int JS_SetLength(JSContext *ctx, JSValueConst obj, int64_t len) { return js_set_length64(ctx, obj, len); } /* return true, false or (-1) in case of exception */ static int JS_OrdinaryIsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj) { JSValue obj_proto; JSObject *proto; const JSObject *p, *proto1; int ret; if (!JS_IsFunction(ctx, obj)) return false; p = JS_VALUE_GET_OBJ(obj); if (p->class_id == JS_CLASS_BOUND_FUNCTION) { JSBoundFunction *s = p->u.bound_function; return JS_IsInstanceOf(ctx, val, s->func_obj); } /* Only explicitly boxed values are instances of constructors */ if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return false; obj_proto = JS_GetProperty(ctx, obj, JS_ATOM_prototype); if (JS_VALUE_GET_TAG(obj_proto) != JS_TAG_OBJECT) { if (!JS_IsException(obj_proto)) JS_ThrowTypeError(ctx, "operand 'prototype' property is not an object"); ret = -1; goto done; } proto = JS_VALUE_GET_OBJ(obj_proto); p = JS_VALUE_GET_OBJ(val); for(;;) { proto1 = p->shape->proto; if (!proto1) { /* slow case if proxy in the prototype chain */ if (unlikely(p->class_id == JS_CLASS_PROXY)) { JSValue obj1; obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, (JSObject *)p)); for(;;) { obj1 = JS_GetPrototypeFree(ctx, obj1); if (JS_IsException(obj1)) { ret = -1; break; } if (JS_IsNull(obj1)) { ret = false; break; } if (proto == JS_VALUE_GET_OBJ(obj1)) { JS_FreeValue(ctx, obj1); ret = true; break; } /* must check for timeout to avoid infinite loop */ if (js_poll_interrupts(ctx)) { JS_FreeValue(ctx, obj1); ret = -1; break; } } } else { ret = false; } break; } p = proto1; if (proto == p) { ret = true; break; } } done: JS_FreeValue(ctx, obj_proto); return ret; } /* return true, false or (-1) in case of exception */ int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj) { JSValue method; if (!JS_IsObject(obj)) goto fail; method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_hasInstance); if (JS_IsException(method)) return -1; if (!JS_IsNull(method) && !JS_IsUndefined(method)) { JSValue ret; ret = JS_CallFree(ctx, method, obj, 1, &val); return JS_ToBoolFree(ctx, ret); } /* legacy case */ if (!JS_IsFunction(ctx, obj)) { fail: JS_ThrowTypeError(ctx, "invalid 'instanceof' right operand"); return -1; } return JS_OrdinaryIsInstanceOf(ctx, val, obj); } #include "builtin-array-fromasync.h" static JSValue js_bytecode_autoinit(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque) { switch ((uintptr_t)opaque) { default: abort(); case JS_BUILTIN_ARRAY_FROMASYNC: { JSValue obj = JS_ReadObject(ctx, qjsc_builtin_array_fromasync, sizeof(qjsc_builtin_array_fromasync), JS_READ_OBJ_BYTECODE); if (JS_IsException(obj)) return JS_EXCEPTION; JSValue fun = JS_EvalFunction(ctx, obj); if (JS_IsException(fun)) return JS_EXCEPTION; assert(JS_IsFunction(ctx, fun)); JSValue args[] = { JS_NewCFunction(ctx, js_array_constructor, "Array", 0), JS_NewCFunctionMagic(ctx, js_error_constructor, "TypeError", 1, JS_CFUNC_constructor_or_func_magic, JS_TYPE_ERROR), JS_AtomToValue(ctx, JS_ATOM_Symbol_asyncIterator), JS_NewCFunctionMagic(ctx, js_object_defineProperty, "Object.defineProperty", 3, JS_CFUNC_generic_magic, 0), JS_AtomToValue(ctx, JS_ATOM_Symbol_iterator), }; JSValue result = JS_Call(ctx, fun, JS_UNDEFINED, countof(args), vc(args)); for (size_t i = 0; i < countof(args); i++) JS_FreeValue(ctx, args[i]); JS_FreeValue(ctx, fun); if (JS_SetPrototypeInternal(ctx, result, ctx->function_proto, /*throw_flag*/true) < 0) { JS_FreeValue(ctx, result); return JS_EXCEPTION; } return result; } } return JS_UNDEFINED; } /* return the value associated to the autoinit property or an exception */ typedef JSValue JSAutoInitFunc(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque); static JSAutoInitFunc *const js_autoinit_func_table[] = { js_instantiate_prototype, /* JS_AUTOINIT_ID_PROTOTYPE */ js_module_ns_autoinit, /* JS_AUTOINIT_ID_MODULE_NS */ JS_InstantiateFunctionListItem2, /* JS_AUTOINIT_ID_PROP */ js_bytecode_autoinit, /* JS_AUTOINIT_ID_BYTECODE */ }; /* warning: 'prs' is reallocated after it */ static int JS_AutoInitProperty(JSContext *ctx, JSObject *p, JSAtom prop, JSProperty *pr, JSShapeProperty *prs) { JSValue val; JSContext *realm; JSAutoInitFunc *func; if (js_shape_prepare_update(ctx, p, &prs)) return -1; realm = js_autoinit_get_realm(pr); func = js_autoinit_func_table[js_autoinit_get_id(pr)]; /* 'func' shall not modify the object properties 'pr' */ val = func(realm, p, prop, pr->u.init.opaque); js_autoinit_free(ctx->rt, pr); prs->flags &= ~JS_PROP_TMASK; pr->u.value = JS_UNDEFINED; if (JS_IsException(val)) return -1; pr->u.value = val; return 0; } static JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj, JSAtom prop, JSValueConst this_obj, bool throw_ref_error) { JSObject *p; JSProperty *pr; JSShapeProperty *prs; uint32_t tag; tag = JS_VALUE_GET_TAG(obj); if (unlikely(tag != JS_TAG_OBJECT)) { switch(tag) { case JS_TAG_NULL: return JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of null", prop); case JS_TAG_UNDEFINED: return JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of undefined", prop); case JS_TAG_EXCEPTION: return JS_EXCEPTION; case JS_TAG_STRING: { JSString *p1 = JS_VALUE_GET_STRING(obj); if (__JS_AtomIsTaggedInt(prop)) { uint32_t idx, ch; idx = __JS_AtomToUInt32(prop); if (idx < p1->len) { ch = string_get(p1, idx); return js_new_string_char(ctx, ch); } } else if (prop == JS_ATOM_length) { return js_int32(p1->len); } } break; default: break; } /* cannot raise an exception */ p = JS_VALUE_GET_OBJ(JS_GetPrototypePrimitive(ctx, obj)); if (!p) return JS_UNDEFINED; } else { p = JS_VALUE_GET_OBJ(obj); } for(;;) { prs = find_own_property(&pr, p, prop); if (prs) { /* found */ if (unlikely(prs->flags & JS_PROP_TMASK)) { if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { if (unlikely(!pr->u.getset.getter)) { return JS_UNDEFINED; } else { JSValue func = JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter); /* Note: the field could be removed in the getter */ func = js_dup(func); return JS_CallFree(ctx, func, this_obj, 0, NULL); } } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { JSValue val = *pr->u.var_ref->pvalue; if (unlikely(JS_IsUninitialized(val))) return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return js_dup(val); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { /* Instantiate property and retry */ if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) return JS_EXCEPTION; continue; } } else { return js_dup(pr->u.value); } } if (unlikely(p->is_exotic)) { /* exotic behaviors */ if (p->fast_array) { if (__JS_AtomIsTaggedInt(prop)) { uint32_t idx = __JS_AtomToUInt32(prop); if (idx < p->u.array.count) { /* we avoid duplicating the code */ return JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx); } else if (is_typed_array(p->class_id)) { return JS_UNDEFINED; } } else if (is_typed_array(p->class_id)) { int ret; ret = JS_AtomIsNumericIndex(ctx, prop); if (ret != 0) { if (ret < 0) return JS_EXCEPTION; return JS_UNDEFINED; } } } else { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; if (em) { if (em->get_property) { JSValue obj1, retval; /* XXX: should pass throw_ref_error */ /* Note: if 'p' is a prototype, it can be freed in the called function */ obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); retval = em->get_property(ctx, obj1, prop, this_obj); JS_FreeValue(ctx, obj1); return retval; } if (em->get_own_property) { JSPropertyDescriptor desc; int ret; JSValue obj1; /* Note: if 'p' is a prototype, it can be freed in the called function */ obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); ret = em->get_own_property(ctx, &desc, obj1, prop); JS_FreeValue(ctx, obj1); if (ret < 0) return JS_EXCEPTION; if (ret) { if (desc.flags & JS_PROP_GETSET) { JS_FreeValue(ctx, desc.setter); return JS_CallFree(ctx, desc.getter, this_obj, 0, NULL); } else { return desc.value; } } } } } } p = p->shape->proto; if (!p) break; } if (unlikely(throw_ref_error)) { return JS_ThrowReferenceErrorNotDefined(ctx, prop); } else { return JS_UNDEFINED; } } JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop) { return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, false); } static JSValue JS_ThrowTypeErrorPrivateNotFound(JSContext *ctx, JSAtom atom) { return JS_ThrowTypeErrorAtom(ctx, "private class field '%s' does not exist", atom); } /* Private fields can be added even on non extensible objects or Proxies */ static int JS_DefinePrivateField(JSContext *ctx, JSValueConst obj, JSValue name, JSValue val) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; JSAtom prop; if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) { JS_ThrowTypeErrorNotAnObject(ctx); goto fail; } /* safety check */ if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) { JS_ThrowTypeErrorNotASymbol(ctx); goto fail; } prop = js_symbol_to_atom(ctx, name); p = JS_VALUE_GET_OBJ(obj); prs = find_own_property(&pr, p, prop); if (prs) { JS_ThrowTypeErrorAtom(ctx, "private class field '%s' already exists", prop); goto fail; } pr = add_property(ctx, p, prop, JS_PROP_C_W_E); if (unlikely(!pr)) { fail: JS_FreeValue(ctx, val); return -1; } pr->u.value = val; return 0; } static JSValue JS_GetPrivateField(JSContext *ctx, JSValueConst obj, JSValueConst name) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; JSAtom prop; if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) return JS_ThrowTypeErrorNotAnObject(ctx); /* safety check */ if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) return JS_ThrowTypeErrorNotASymbol(ctx); prop = js_symbol_to_atom(ctx, name); p = JS_VALUE_GET_OBJ(obj); prs = find_own_property(&pr, p, prop); if (!prs) { JS_ThrowTypeErrorPrivateNotFound(ctx, prop); return JS_EXCEPTION; } return js_dup(pr->u.value); } static int JS_SetPrivateField(JSContext *ctx, JSValueConst obj, JSValueConst name, JSValue val) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; JSAtom prop; if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) { JS_ThrowTypeErrorNotAnObject(ctx); goto fail; } /* safety check */ if (unlikely(JS_VALUE_GET_TAG(name) != JS_TAG_SYMBOL)) { JS_ThrowTypeErrorNotASymbol(ctx); goto fail; } prop = js_symbol_to_atom(ctx, name); p = JS_VALUE_GET_OBJ(obj); prs = find_own_property(&pr, p, prop); if (!prs) { JS_ThrowTypeErrorPrivateNotFound(ctx, prop); fail: JS_FreeValue(ctx, val); return -1; } set_value(ctx, &pr->u.value, val); return 0; } /* add a private brand field to 'home_obj' if not already present and if obj is != null add a private brand to it */ static int JS_AddBrand(JSContext *ctx, JSValueConst obj, JSValueConst home_obj) { JSObject *p, *p1; JSShapeProperty *prs; JSProperty *pr; JSValue brand; JSAtom brand_atom; if (unlikely(JS_VALUE_GET_TAG(home_obj) != JS_TAG_OBJECT)) { JS_ThrowTypeErrorNotAnObject(ctx); return -1; } p = JS_VALUE_GET_OBJ(home_obj); prs = find_own_property(&pr, p, JS_ATOM_Private_brand); if (!prs) { /* if the brand is not present, add it */ brand = JS_NewSymbolFromAtom(ctx, JS_ATOM_brand, JS_ATOM_TYPE_PRIVATE); if (JS_IsException(brand)) return -1; pr = add_property(ctx, p, JS_ATOM_Private_brand, JS_PROP_C_W_E); if (!pr) { JS_FreeValue(ctx, brand); return -1; } pr->u.value = js_dup(brand); } else { brand = js_dup(pr->u.value); } brand_atom = js_symbol_to_atom(ctx, brand); if (JS_IsObject(obj)) { p1 = JS_VALUE_GET_OBJ(obj); prs = find_own_property(&pr, p1, brand_atom); if (unlikely(prs)) { JS_FreeAtom(ctx, brand_atom); JS_ThrowTypeError(ctx, "private method is already present"); return -1; } pr = add_property(ctx, p1, brand_atom, JS_PROP_C_W_E); JS_FreeAtom(ctx, brand_atom); if (!pr) return -1; pr->u.value = JS_UNDEFINED; } else { JS_FreeAtom(ctx, brand_atom); } return 0; } /* return a boolean telling if the brand of the home object of 'func' is present on 'obj' or -1 in case of exception */ static int JS_CheckBrand(JSContext *ctx, JSValue obj, JSValue func) { JSObject *p, *p1, *home_obj; JSShapeProperty *prs; JSProperty *pr; JSValue brand; /* get the home object of 'func' */ if (unlikely(JS_VALUE_GET_TAG(func) != JS_TAG_OBJECT)) goto not_obj; p1 = JS_VALUE_GET_OBJ(func); if (!js_class_has_bytecode(p1->class_id)) goto not_obj; home_obj = p1->u.func.home_object; if (!home_obj) goto not_obj; prs = find_own_property(&pr, home_obj, JS_ATOM_Private_brand); if (!prs) { JS_ThrowTypeError(ctx, "expecting private field"); return -1; } brand = pr->u.value; /* safety check */ if (unlikely(JS_VALUE_GET_TAG(brand) != JS_TAG_SYMBOL)) goto not_obj; /* get the brand array of 'obj' */ if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) { not_obj: JS_ThrowTypeErrorNotAnObject(ctx); return -1; } p = JS_VALUE_GET_OBJ(obj); prs = find_own_property(&pr, p, js_symbol_to_atom(ctx, brand)); return (prs != NULL); } static uint32_t js_string_obj_get_length(JSContext *ctx, JSValueConst obj) { JSObject *p; JSString *p1; uint32_t len = 0; /* This is a class exotic method: obj class_id is JS_CLASS_STRING */ p = JS_VALUE_GET_OBJ(obj); if (JS_VALUE_GET_TAG(p->u.object_data) == JS_TAG_STRING) { p1 = JS_VALUE_GET_STRING(p->u.object_data); len = p1->len; } return len; } static int num_keys_cmp(const void *p1, const void *p2, void *opaque) { JSContext *ctx = opaque; JSAtom atom1 = ((const JSPropertyEnum *)p1)->atom; JSAtom atom2 = ((const JSPropertyEnum *)p2)->atom; uint32_t v1, v2; bool atom1_is_integer, atom2_is_integer; atom1_is_integer = JS_AtomIsArrayIndex(ctx, &v1, atom1); atom2_is_integer = JS_AtomIsArrayIndex(ctx, &v2, atom2); assert(atom1_is_integer && atom2_is_integer); if (v1 < v2) return -1; else if (v1 == v2) return 0; else return 1; } static void js_free_prop_enum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len) { uint32_t i; if (tab) { for(i = 0; i < len; i++) JS_FreeAtom(ctx, tab[i].atom); js_free(ctx, tab); } } /* return < 0 in case if exception, 0 if OK. ptab and its atoms must be freed by the user. */ static int __exception JS_GetOwnPropertyNamesInternal(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSObject *p, int flags) { int i, j; JSShape *sh; JSShapeProperty *prs; JSPropertyEnum *tab_atom, *tab_exotic; JSAtom atom; uint32_t num_keys_count, str_keys_count, sym_keys_count, atom_count; uint32_t num_index, str_index, sym_index, exotic_count, exotic_keys_count; bool is_enumerable, num_sorted; uint32_t num_key; JSAtomKindEnum kind; /* clear pointer for consistency in case of failure */ *ptab = NULL; *plen = 0; /* compute the number of returned properties */ num_keys_count = 0; str_keys_count = 0; sym_keys_count = 0; exotic_keys_count = 0; exotic_count = 0; tab_exotic = NULL; sh = p->shape; for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { atom = prs->atom; if (atom != JS_ATOM_NULL) { is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0); kind = JS_AtomGetKind(ctx, atom); if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) && ((flags >> kind) & 1) != 0) { /* need to raise an exception in case of the module name space (implicit GetOwnProperty) */ if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) && (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY))) { JSVarRef *var_ref = p->prop[i].u.var_ref; if (unlikely(JS_IsUninitialized(*var_ref->pvalue))) { JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return -1; } } if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) { num_keys_count++; } else if (kind == JS_ATOM_KIND_STRING) { str_keys_count++; } else { sym_keys_count++; } } } } if (p->is_exotic) { if (p->fast_array) { if (flags & JS_GPN_STRING_MASK) { num_keys_count += p->u.array.count; } } else if (p->class_id == JS_CLASS_STRING) { if (flags & JS_GPN_STRING_MASK) { num_keys_count += js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); } } else { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; if (em && em->get_own_property_names) { if (em->get_own_property_names(ctx, &tab_exotic, &exotic_count, JS_MKPTR(JS_TAG_OBJECT, p))) return -1; for(i = 0; i < exotic_count; i++) { atom = tab_exotic[i].atom; kind = JS_AtomGetKind(ctx, atom); if (((flags >> kind) & 1) != 0) { is_enumerable = false; if (flags & (JS_GPN_SET_ENUM | JS_GPN_ENUM_ONLY)) { JSPropertyDescriptor desc; int res; /* set the "is_enumerable" field if necessary */ res = JS_GetOwnPropertyInternal(ctx, &desc, p, atom); if (res < 0) { js_free_prop_enum(ctx, tab_exotic, exotic_count); return -1; } if (res) { is_enumerable = ((desc.flags & JS_PROP_ENUMERABLE) != 0); js_free_desc(ctx, &desc); } tab_exotic[i].is_enumerable = is_enumerable; } if (!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) { exotic_keys_count++; } } } } } } /* fill them */ atom_count = num_keys_count + str_keys_count + sym_keys_count + exotic_keys_count; /* avoid allocating 0 bytes */ tab_atom = js_malloc(ctx, sizeof(tab_atom[0]) * max_int(atom_count, 1)); if (!tab_atom) { js_free_prop_enum(ctx, tab_exotic, exotic_count); return -1; } num_index = 0; str_index = num_keys_count; sym_index = str_index + str_keys_count; num_sorted = true; sh = p->shape; for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { atom = prs->atom; if (atom != JS_ATOM_NULL) { is_enumerable = ((prs->flags & JS_PROP_ENUMERABLE) != 0); kind = JS_AtomGetKind(ctx, atom); if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) && ((flags >> kind) & 1) != 0) { if (JS_AtomIsArrayIndex(ctx, &num_key, atom)) { j = num_index++; num_sorted = false; } else if (kind == JS_ATOM_KIND_STRING) { j = str_index++; } else { j = sym_index++; } tab_atom[j].atom = JS_DupAtom(ctx, atom); tab_atom[j].is_enumerable = is_enumerable; } } } if (p->is_exotic) { int len; if (p->fast_array) { if (flags & JS_GPN_STRING_MASK) { len = p->u.array.count; goto add_array_keys; } } else if (p->class_id == JS_CLASS_STRING) { if (flags & JS_GPN_STRING_MASK) { len = js_string_obj_get_length(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); add_array_keys: for(i = 0; i < len; i++) { tab_atom[num_index].atom = __JS_AtomFromUInt32(i); if (tab_atom[num_index].atom == JS_ATOM_NULL) { js_free_prop_enum(ctx, tab_atom, num_index); return -1; } tab_atom[num_index].is_enumerable = true; num_index++; } } } else { /* Note: exotic keys are not reordered and comes after the object own properties. */ for(i = 0; i < exotic_count; i++) { atom = tab_exotic[i].atom; is_enumerable = tab_exotic[i].is_enumerable; kind = JS_AtomGetKind(ctx, atom); if ((!(flags & JS_GPN_ENUM_ONLY) || is_enumerable) && ((flags >> kind) & 1) != 0) { tab_atom[sym_index].atom = atom; tab_atom[sym_index].is_enumerable = is_enumerable; sym_index++; } else { JS_FreeAtom(ctx, atom); } } js_free(ctx, tab_exotic); } } assert(num_index == num_keys_count); assert(str_index == num_keys_count + str_keys_count); assert(sym_index == atom_count); if (num_keys_count != 0 && !num_sorted) { rqsort(tab_atom, num_keys_count, sizeof(tab_atom[0]), num_keys_cmp, ctx); } *ptab = tab_atom; *plen = atom_count; return 0; } int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj, int flags) { if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) { JS_ThrowTypeErrorNotAnObject(ctx); return -1; } return JS_GetOwnPropertyNamesInternal(ctx, ptab, plen, JS_VALUE_GET_OBJ(obj), flags); } /* Return -1 if exception, false if the property does not exist, true if it exists. If true is returned, the property descriptor 'desc' is filled present. */ static int JS_GetOwnPropertyInternal(JSContext *ctx, JSPropertyDescriptor *desc, JSObject *p, JSAtom prop) { JSShapeProperty *prs; JSProperty *pr; retry: prs = find_own_property(&pr, p, prop); if (prs) { if (desc) { desc->flags = prs->flags & JS_PROP_C_W_E; desc->getter = JS_UNDEFINED; desc->setter = JS_UNDEFINED; desc->value = JS_UNDEFINED; if (unlikely(prs->flags & JS_PROP_TMASK)) { if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { desc->flags |= JS_PROP_GETSET; if (pr->u.getset.getter) desc->getter = js_dup(JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); if (pr->u.getset.setter) desc->setter = js_dup(JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { JSValue val = *pr->u.var_ref->pvalue; if (unlikely(JS_IsUninitialized(val))) { JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return -1; } desc->value = js_dup(val); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { /* Instantiate property and retry */ if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) return -1; goto retry; } } else { desc->value = js_dup(pr->u.value); } } else { /* for consistency, send the exception even if desc is NULL */ if (unlikely((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF)) { if (unlikely(JS_IsUninitialized(*pr->u.var_ref->pvalue))) { JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return -1; } } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { /* nothing to do: delay instantiation until actual value and/or attributes are read */ } } return true; } if (p->is_exotic) { if (p->fast_array) { /* specific case for fast arrays */ if (__JS_AtomIsTaggedInt(prop)) { uint32_t idx; idx = __JS_AtomToUInt32(prop); if (idx < p->u.array.count) { if (desc) { desc->flags = JS_PROP_WRITABLE | JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE; desc->getter = JS_UNDEFINED; desc->setter = JS_UNDEFINED; desc->value = JS_GetPropertyUint32(ctx, JS_MKPTR(JS_TAG_OBJECT, p), idx); } return true; } } } else { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; if (em && em->get_own_property) { return em->get_own_property(ctx, desc, JS_MKPTR(JS_TAG_OBJECT, p), prop); } } } return false; } int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom prop) { if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) { JS_ThrowTypeErrorNotAnObject(ctx); return -1; } return JS_GetOwnPropertyInternal(ctx, desc, JS_VALUE_GET_OBJ(obj), prop); } void JS_FreePropertyEnum(JSContext *ctx, JSPropertyEnum *tab, uint32_t len) { js_free_prop_enum(ctx, tab, len); } /* return -1 if exception (Proxy object only) or true/false */ int JS_IsExtensible(JSContext *ctx, JSValueConst obj) { JSObject *p; if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) return false; p = JS_VALUE_GET_OBJ(obj); if (unlikely(p->class_id == JS_CLASS_PROXY)) return js_proxy_isExtensible(ctx, obj); else return p->extensible; } /* return -1 if exception (Proxy object only) or true/false */ int JS_PreventExtensions(JSContext *ctx, JSValueConst obj) { JSObject *p; if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) return false; p = JS_VALUE_GET_OBJ(obj); if (unlikely(p->class_id == JS_CLASS_PROXY)) return js_proxy_preventExtensions(ctx, obj); p->extensible = false; return true; } /* return -1 if exception otherwise true or false */ int JS_HasProperty(JSContext *ctx, JSValueConst obj, JSAtom prop) { JSObject *p; int ret; JSValue obj1; if (unlikely(JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)) return false; p = JS_VALUE_GET_OBJ(obj); for(;;) { if (p->is_exotic) { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; if (em && em->has_property) { /* has_property can free the prototype */ obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); ret = em->has_property(ctx, obj1, prop); JS_FreeValue(ctx, obj1); return ret; } } /* JS_GetOwnPropertyInternal can free the prototype */ js_dup(JS_MKPTR(JS_TAG_OBJECT, p)); ret = JS_GetOwnPropertyInternal(ctx, NULL, p, prop); JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); if (ret != 0) return ret; if (is_typed_array(p->class_id)) { ret = JS_AtomIsNumericIndex(ctx, prop); if (ret != 0) { if (ret < 0) return -1; return false; } } p = p->shape->proto; if (!p) break; } return false; } /* val must be a symbol */ static JSAtom js_symbol_to_atom(JSContext *ctx, JSValueConst val) { JSAtomStruct *p = JS_VALUE_GET_PTR(val); return js_get_atom_index(ctx->rt, p); } /* return JS_ATOM_NULL in case of exception */ static JSAtom JS_ValueToAtomInternal(JSContext *ctx, JSValueConst val, int flags) { JSAtom atom; uint32_t tag; tag = JS_VALUE_GET_TAG(val); if (tag == JS_TAG_INT && (uint32_t)JS_VALUE_GET_INT(val) <= JS_ATOM_MAX_INT) { /* fast path for integer values */ atom = __JS_AtomFromUInt32(JS_VALUE_GET_INT(val)); } else if (tag == JS_TAG_SYMBOL) { JSAtomStruct *p = JS_VALUE_GET_PTR(val); atom = JS_DupAtom(ctx, js_get_atom_index(ctx->rt, p)); } else { JSValue str; str = JS_ToPropertyKeyInternal(ctx, val, flags); if (JS_IsException(str)) return JS_ATOM_NULL; if (JS_VALUE_GET_TAG(str) == JS_TAG_SYMBOL) { atom = js_symbol_to_atom(ctx, str); } else { atom = JS_NewAtomStr(ctx, JS_VALUE_GET_STRING(str)); } } return atom; } JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val) { return JS_ValueToAtomInternal(ctx, val, /*flags*/0); } static bool js_get_fast_array_element(JSContext *ctx, JSObject *p, uint32_t idx, JSValue *pval) { switch(p->class_id) { case JS_CLASS_ARRAY: case JS_CLASS_ARGUMENTS: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_dup(p->u.array.u.values[idx]); return true; case JS_CLASS_INT8_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_int32(p->u.array.u.int8_ptr[idx]); return true; case JS_CLASS_UINT8C_ARRAY: case JS_CLASS_UINT8_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_int32(p->u.array.u.uint8_ptr[idx]); return true; case JS_CLASS_INT16_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_int32(p->u.array.u.int16_ptr[idx]); return true; case JS_CLASS_UINT16_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_int32(p->u.array.u.uint16_ptr[idx]); return true; case JS_CLASS_INT32_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_int32(p->u.array.u.int32_ptr[idx]); return true; case JS_CLASS_UINT32_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_uint32(p->u.array.u.uint32_ptr[idx]); return true; case JS_CLASS_BIG_INT64_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = JS_NewBigInt64(ctx, p->u.array.u.int64_ptr[idx]); return true; case JS_CLASS_BIG_UINT64_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = JS_NewBigUint64(ctx, p->u.array.u.uint64_ptr[idx]); return true; case JS_CLASS_FLOAT16_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_float64(fromfp16(p->u.array.u.fp16_ptr[idx])); return true; case JS_CLASS_FLOAT32_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_float64(p->u.array.u.float_ptr[idx]); return true; case JS_CLASS_FLOAT64_ARRAY: if (unlikely(idx >= p->u.array.count)) return false; *pval = js_float64(p->u.array.u.double_ptr[idx]); return true; default: return false; } } static JSValue JS_GetPropertyValue(JSContext *ctx, JSValueConst this_obj, JSValue prop) { JSAtom atom; JSValue ret; uint32_t tag; tag = JS_VALUE_GET_TAG(this_obj); if (likely(tag == JS_TAG_OBJECT)) { if (JS_VALUE_GET_TAG(prop) == JS_TAG_INT) { JSObject *p = JS_VALUE_GET_OBJ(this_obj); uint32_t idx = JS_VALUE_GET_INT(prop); JSValue val; /* fast path for array and typed array access */ if (js_get_fast_array_element(ctx, p, idx, &val)) return val; } } else if (unlikely(tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED)) { // per spec: not allowed to call ToPropertyKey before ToObject // so we must ensure to not invoke JS anything that's observable // from JS code atom = JS_ValueToAtomInternal(ctx, prop, JS_TO_STRING_NO_SIDE_EFFECTS); JS_FreeValue(ctx, prop); if (unlikely(atom == JS_ATOM_NULL)) return JS_EXCEPTION; if (tag == JS_TAG_NULL) { JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of null", atom); } else { JS_ThrowTypeErrorAtom(ctx, "cannot read property '%s' of undefined", atom); } JS_FreeAtom(ctx, atom); return JS_EXCEPTION; } atom = JS_ValueToAtom(ctx, prop); JS_FreeValue(ctx, prop); if (unlikely(atom == JS_ATOM_NULL)) return JS_EXCEPTION; ret = JS_GetProperty(ctx, this_obj, atom); JS_FreeAtom(ctx, atom); return ret; } JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx) { return JS_GetPropertyInt64(ctx, this_obj, idx); } /* Check if an object has a generalized numeric property. Return value: -1 for exception, *pval set to JS_EXCEPTION true if property exists, stored into *pval, false if property does not exist. *pval set to JS_UNDEFINED. */ static int JS_TryGetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, JSValue *pval) { JSValue val; JSAtom prop; int present; if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT && (uint64_t)idx <= INT32_MAX)) { /* fast path for array and typed array access */ JSObject *p = JS_VALUE_GET_OBJ(obj); if (js_get_fast_array_element(ctx, p, idx, pval)) return true; } val = JS_EXCEPTION; present = -1; prop = JS_NewAtomInt64(ctx, idx); if (likely(prop != JS_ATOM_NULL)) { present = JS_HasProperty(ctx, obj, prop); if (present > 0) { val = JS_GetProperty(ctx, obj, prop); if (unlikely(JS_IsException(val))) present = -1; } else if (present == false) { val = JS_UNDEFINED; } JS_FreeAtom(ctx, prop); } *pval = val; return present; } JSValue JS_GetPropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx) { JSAtom prop; JSValue val; if (likely(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT && (uint64_t)idx <= INT32_MAX)) { /* fast path for array and typed array access */ JSObject *p = JS_VALUE_GET_OBJ(obj); if (js_get_fast_array_element(ctx, p, idx, &val)) return val; } prop = JS_NewAtomInt64(ctx, idx); if (prop == JS_ATOM_NULL) return JS_EXCEPTION; val = JS_GetProperty(ctx, obj, prop); JS_FreeAtom(ctx, prop); return val; } /* `prop` may be pure ASCII or UTF-8 encoded */ JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj, const char *prop) { JSAtom atom; JSValue ret; atom = JS_NewAtom(ctx, prop); if (atom == JS_ATOM_NULL) return JS_EXCEPTION; ret = JS_GetProperty(ctx, this_obj, atom); JS_FreeAtom(ctx, atom); return ret; } /* Note: the property value is not initialized. Return NULL if memory error. */ static JSProperty *add_property(JSContext *ctx, JSObject *p, JSAtom prop, int prop_flags) { JSShape *sh, *new_sh; sh = p->shape; if (sh->is_hashed) { /* try to find an existing shape */ new_sh = find_hashed_shape_prop(ctx->rt, sh, prop, prop_flags); if (new_sh) { /* matching shape found: use it */ /* the property array may need to be resized */ if (new_sh->prop_size != sh->prop_size) { JSProperty *new_prop; new_prop = js_realloc(ctx, p->prop, sizeof(p->prop[0]) * new_sh->prop_size); if (!new_prop) return NULL; p->prop = new_prop; } p->shape = js_dup_shape(new_sh); js_free_shape(ctx->rt, sh); return &p->prop[new_sh->prop_count - 1]; } else if (sh->header.ref_count != 1) { /* if the shape is shared, clone it */ new_sh = js_clone_shape(ctx, sh); if (!new_sh) return NULL; /* hash the cloned shape */ new_sh->is_hashed = true; js_shape_hash_link(ctx->rt, new_sh); js_free_shape(ctx->rt, p->shape); p->shape = new_sh; } } assert(p->shape->header.ref_count == 1); if (add_shape_property(ctx, &p->shape, p, prop, prop_flags)) return NULL; return &p->prop[p->shape->prop_count - 1]; } /* can be called on Array or Arguments objects. return < 0 if memory alloc error. */ static no_inline __exception int convert_fast_array_to_array(JSContext *ctx, JSObject *p) { JSProperty *pr; JSShape *sh; JSValue *tab; uint32_t i, len, new_count; if (js_shape_prepare_update(ctx, p, NULL)) return -1; len = p->u.array.count; /* resize the properties once to simplify the error handling */ sh = p->shape; new_count = sh->prop_count + len; if (new_count > sh->prop_size) { if (resize_properties(ctx, &p->shape, p, new_count)) return -1; } tab = p->u.array.u.values; for(i = 0; i < len; i++) { /* add_property cannot fail here but __JS_AtomFromUInt32(i) fails for i > INT32_MAX */ pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E); pr->u.value = *tab++; } js_free(ctx, p->u.array.u.values); p->u.array.count = 0; p->u.array.u.values = NULL; /* fail safe */ p->u.array.u1.size = 0; p->fast_array = 0; return 0; } static int delete_property(JSContext *ctx, JSObject *p, JSAtom atom) { JSShape *sh; JSShapeProperty *pr, *lpr, *prop; JSProperty *pr1; uint32_t lpr_idx; intptr_t h, h1; redo: sh = p->shape; h1 = atom & sh->prop_hash_mask; h = prop_hash_end(sh)[-h1 - 1]; prop = get_shape_prop(sh); lpr = NULL; lpr_idx = 0; /* prevent warning */ while (h != 0) { pr = &prop[h - 1]; if (likely(pr->atom == atom)) { /* found ! */ if (!(pr->flags & JS_PROP_CONFIGURABLE)) return false; /* realloc the shape if needed */ if (lpr) lpr_idx = lpr - get_shape_prop(sh); if (js_shape_prepare_update(ctx, p, &pr)) return -1; sh = p->shape; /* remove property */ if (lpr) { lpr = get_shape_prop(sh) + lpr_idx; lpr->hash_next = pr->hash_next; } else { prop_hash_end(sh)[-h1 - 1] = pr->hash_next; } sh->deleted_prop_count++; /* free the entry */ pr1 = &p->prop[h - 1]; free_property(ctx->rt, pr1, pr->flags); JS_FreeAtom(ctx, pr->atom); /* put default values */ pr->flags = 0; pr->atom = JS_ATOM_NULL; pr1->u.value = JS_UNDEFINED; /* compact the properties if too many deleted properties */ if (sh->deleted_prop_count >= 8 && sh->deleted_prop_count >= ((unsigned)sh->prop_count / 2)) { compact_properties(ctx, p); } return true; } lpr = pr; h = pr->hash_next; } if (p->is_exotic) { if (p->fast_array) { uint32_t idx; if (JS_AtomIsArrayIndex(ctx, &idx, atom) && idx < p->u.array.count) { if (p->class_id == JS_CLASS_ARRAY || p->class_id == JS_CLASS_ARGUMENTS) { /* Special case deleting the last element of a fast Array */ if (idx == p->u.array.count - 1) { JS_FreeValue(ctx, p->u.array.u.values[idx]); p->u.array.count = idx; return true; } if (convert_fast_array_to_array(ctx, p)) return -1; goto redo; } else { return false; } } } else { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; if (em && em->delete_property) { return em->delete_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), atom); } } } /* not found */ return true; } static int call_setter(JSContext *ctx, JSObject *setter, JSValueConst this_obj, JSValue val, int flags) { JSValue ret, func; if (likely(setter)) { func = JS_MKPTR(JS_TAG_OBJECT, setter); /* Note: the field could be removed in the setter */ func = js_dup(func); ret = JS_CallFree(ctx, func, this_obj, 1, vc(&val)); JS_FreeValue(ctx, val); if (JS_IsException(ret)) return -1; JS_FreeValue(ctx, ret); return true; } else { JS_FreeValue(ctx, val); if ((flags & JS_PROP_THROW) || ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { JS_ThrowTypeError(ctx, "no setter for property"); return -1; } return false; } } /* set the array length and remove the array elements if necessary. */ static int set_array_length(JSContext *ctx, JSObject *p, JSValue val, int flags) { uint32_t len, idx, cur_len; int i, ret; /* Note: this call can reallocate the properties of 'p' */ ret = JS_ToArrayLengthFree(ctx, &len, val, false); if (ret) return -1; /* JS_ToArrayLengthFree() must be done before the read-only test */ if (unlikely(!(p->shape->prop[0].flags & JS_PROP_WRITABLE))) return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length); if (likely(p->fast_array)) { uint32_t old_len = p->u.array.count; if (len < old_len) { for(i = len; i < old_len; i++) { JS_FreeValue(ctx, p->u.array.u.values[i]); } p->u.array.count = len; } p->prop[0].u.value = js_uint32(len); } else { /* Note: length is always a uint32 because the object is an array */ JS_ToUint32(ctx, &cur_len, p->prop[0].u.value); if (len < cur_len) { uint32_t d; JSShape *sh; JSShapeProperty *pr; d = cur_len - len; sh = p->shape; if (d <= sh->prop_count) { JSAtom atom; /* faster to iterate */ while (cur_len > len) { atom = JS_NewAtomUInt32(ctx, cur_len - 1); ret = delete_property(ctx, p, atom); JS_FreeAtom(ctx, atom); if (unlikely(!ret)) { /* unlikely case: property is not configurable */ break; } cur_len--; } } else { /* faster to iterate thru all the properties. Need two passes in case one of the property is not configurable */ cur_len = len; for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) { if (pr->atom != JS_ATOM_NULL && JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) { if (idx >= cur_len && !(pr->flags & JS_PROP_CONFIGURABLE)) { cur_len = idx + 1; } } } for(i = 0, pr = get_shape_prop(sh); i < sh->prop_count; i++, pr++) { if (pr->atom != JS_ATOM_NULL && JS_AtomIsArrayIndex(ctx, &idx, pr->atom)) { if (idx >= cur_len) { /* remove the property */ delete_property(ctx, p, pr->atom); /* WARNING: the shape may have been modified */ sh = p->shape; pr = get_shape_prop(sh) + i; } } } } } else { cur_len = len; } set_value(ctx, &p->prop[0].u.value, js_uint32(cur_len)); if (unlikely(cur_len > len)) { return JS_ThrowTypeErrorOrFalse(ctx, flags, "not configurable"); } } return true; } /* return -1 if exception */ static int expand_fast_array(JSContext *ctx, JSObject *p, uint32_t new_len) { uint32_t new_size; size_t slack; JSValue *new_array_prop; /* XXX: potential arithmetic overflow */ new_size = max_int(new_len, p->u.array.u1.size * 3 / 2); new_array_prop = js_realloc2(ctx, p->u.array.u.values, sizeof(JSValue) * new_size, &slack); if (!new_array_prop) return -1; new_size += slack / sizeof(*new_array_prop); p->u.array.u.values = new_array_prop; p->u.array.u1.size = new_size; return 0; } /* Preconditions: 'p' must be of class JS_CLASS_ARRAY, p->fast_array = true and p->extensible = true */ static int add_fast_array_element(JSContext *ctx, JSObject *p, JSValue val, int flags) { uint32_t new_len, array_len; /* extend the array by one */ /* XXX: convert to slow array if new_len > 2^31-1 elements */ new_len = p->u.array.count + 1; /* update the length if necessary. We assume that if the length is not an integer, then if it >= 2^31. */ if (likely(JS_VALUE_GET_TAG(p->prop[0].u.value) == JS_TAG_INT)) { array_len = JS_VALUE_GET_INT(p->prop[0].u.value); if (new_len > array_len) { if (unlikely(!(get_shape_prop(p->shape)->flags & JS_PROP_WRITABLE))) { JS_FreeValue(ctx, val); return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length); } p->prop[0].u.value = js_int32(new_len); } } if (unlikely(new_len > p->u.array.u1.size)) { if (expand_fast_array(ctx, p, new_len)) { JS_FreeValue(ctx, val); return -1; } } p->u.array.u.values[new_len - 1] = val; p->u.array.count = new_len; return true; } static void js_free_desc(JSContext *ctx, JSPropertyDescriptor *desc) { JS_FreeValue(ctx, desc->getter); JS_FreeValue(ctx, desc->setter); JS_FreeValue(ctx, desc->value); } /* return -1 in case of exception or true or false. Warning: 'val' is freed by the function. 'flags' is a bitmask of JS_PROP_NO_ADD, JS_PROP_THROW or JS_PROP_THROW_STRICT. If JS_PROP_NO_ADD is set, the new property is not added and an error is raised. 'obj' must be an object when obj != this_obj. */ static int JS_SetPropertyInternal2(JSContext *ctx, JSValueConst obj, JSAtom prop, JSValue val, JSValueConst this_obj, int flags) { JSObject *p, *p1; JSShapeProperty *prs; JSProperty *pr; JSPropertyDescriptor desc; int ret; switch(JS_VALUE_GET_TAG(this_obj)) { case JS_TAG_NULL: JS_ThrowTypeErrorAtom(ctx, "cannot set property '%s' of null", prop); goto fail; case JS_TAG_UNDEFINED: JS_ThrowTypeErrorAtom(ctx, "cannot set property '%s' of undefined", prop); goto fail; case JS_TAG_OBJECT: p = JS_VALUE_GET_OBJ(this_obj); p1 = JS_VALUE_GET_OBJ(obj); if (p == p1) break; goto retry2; default: if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) obj = JS_GetPrototypePrimitive(ctx, obj); p = NULL; p1 = JS_VALUE_GET_OBJ(obj); goto prototype_lookup; } retry: prs = find_own_property(&pr, p1, prop); if (prs) { if (likely((prs->flags & (JS_PROP_TMASK | JS_PROP_WRITABLE | JS_PROP_LENGTH)) == JS_PROP_WRITABLE)) { /* fast case */ set_value(ctx, &pr->u.value, val); return true; } else if (prs->flags & JS_PROP_LENGTH) { assert(p->class_id == JS_CLASS_ARRAY); assert(prop == JS_ATOM_length); return set_array_length(ctx, p, val, flags); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { /* JS_PROP_WRITABLE is always true for variable references, but they are write protected in module name spaces. */ if (p->class_id == JS_CLASS_MODULE_NS) goto read_only_prop; set_value(ctx, pr->u.var_ref->pvalue, val); return true; } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { /* Instantiate property and retry (potentially useless) */ if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) goto fail; goto retry; } else { goto read_only_prop; } } for(;;) { if (p1->is_exotic) { if (p1->fast_array) { if (__JS_AtomIsTaggedInt(prop)) { uint32_t idx = __JS_AtomToUInt32(prop); if (idx < p1->u.array.count) { if (unlikely(p == p1)) return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), val, flags); else break; } else if (is_typed_array(p1->class_id)) { goto typed_array_oob; } } else if (is_typed_array(p1->class_id)) { ret = JS_AtomIsNumericIndex(ctx, prop); if (ret != 0) { if (ret < 0) goto fail; typed_array_oob: // per spec: evaluate value for side effects if (p1->class_id == JS_CLASS_BIG_INT64_ARRAY || p1->class_id == JS_CLASS_BIG_UINT64_ARRAY) { int64_t v; if (JS_ToBigInt64Free(ctx, &v, val)) return -1; } else { val = JS_ToNumberFree(ctx, val); JS_FreeValue(ctx, val); if (JS_IsException(val)) return -1; } return true; } } } else { const JSClassExoticMethods *em = ctx->rt->class_array[p1->class_id].exotic; if (em) { JSValue obj1; if (em->set_property) { /* set_property can free the prototype */ obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1)); ret = em->set_property(ctx, obj1, prop, val, this_obj, flags); JS_FreeValue(ctx, obj1); JS_FreeValue(ctx, val); return ret; } if (em->get_own_property) { /* get_own_property can free the prototype */ obj1 = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1)); ret = em->get_own_property(ctx, &desc, obj1, prop); JS_FreeValue(ctx, obj1); if (ret < 0) goto fail; if (ret) { if (desc.flags & JS_PROP_GETSET) { JSObject *setter; if (JS_IsUndefined(desc.setter)) setter = NULL; else setter = JS_VALUE_GET_OBJ(desc.setter); ret = call_setter(ctx, setter, this_obj, val, flags); JS_FreeValue(ctx, desc.getter); JS_FreeValue(ctx, desc.setter); return ret; } else { JS_FreeValue(ctx, desc.value); if (!(desc.flags & JS_PROP_WRITABLE)) goto read_only_prop; if (likely(p == p1)) { ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED, JS_PROP_HAS_VALUE); JS_FreeValue(ctx, val); return ret; } else { break; } } } } } } } p1 = p1->shape->proto; prototype_lookup: if (!p1) break; retry2: prs = find_own_property(&pr, p1, prop); if (prs) { if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { return call_setter(ctx, pr->u.getset.setter, this_obj, val, flags); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { /* Instantiate property and retry (potentially useless) */ if (JS_AutoInitProperty(ctx, p1, prop, pr, prs)) return -1; goto retry2; } else if (!(prs->flags & JS_PROP_WRITABLE)) { goto read_only_prop; } else { break; } } } if (unlikely(flags & JS_PROP_NO_ADD)) { JS_ThrowReferenceErrorNotDefined(ctx, prop); goto fail; } if (unlikely(!p)) { ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "not an object"); goto done; } if (unlikely(!p->extensible)) { ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "object is not extensible"); goto done; } if (p == JS_VALUE_GET_OBJ(obj)) { if (p->is_exotic) { if (p->class_id == JS_CLASS_ARRAY && p->fast_array && __JS_AtomIsTaggedInt(prop)) { uint32_t idx = __JS_AtomToUInt32(prop); if (idx == p->u.array.count) { /* fast case */ return add_fast_array_element(ctx, p, val, flags); } } goto generic_create_prop; } else { pr = add_property(ctx, p, prop, JS_PROP_C_W_E); if (!pr) goto fail; pr->u.value = val; return true; } } // TODO(bnoordhuis) return JSProperty slot and update in place // when plain property (not is_exotic/setter/etc.) to avoid // calling find_own_property() thrice? ret = JS_GetOwnPropertyInternal(ctx, &desc, p, prop); if (ret < 0) goto fail; if (ret) { JS_FreeValue(ctx, desc.value); if (desc.flags & JS_PROP_GETSET) { JS_FreeValue(ctx, desc.getter); JS_FreeValue(ctx, desc.setter); ret = JS_ThrowTypeErrorOrFalse(ctx, flags, "setter is forbidden"); goto done; } else if (!(desc.flags & JS_PROP_WRITABLE) || p->class_id == JS_CLASS_MODULE_NS) { read_only_prop: ret = JS_ThrowTypeErrorReadOnly(ctx, flags, prop); goto done; } ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED, JS_PROP_HAS_VALUE); } else { generic_create_prop: ret = JS_CreateProperty(ctx, p, prop, val, JS_UNDEFINED, JS_UNDEFINED, flags | JS_PROP_HAS_VALUE | JS_PROP_HAS_ENUMERABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_C_W_E); } done: JS_FreeValue(ctx, val); return ret; fail: JS_FreeValue(ctx, val); return -1; } static int JS_SetPropertyInternal(JSContext *ctx, JSValueConst obj, JSAtom prop, JSValue val, int flags) { return JS_SetPropertyInternal2(ctx, obj, prop, val, obj, flags); } int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val) { return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW); } /* flags can be JS_PROP_THROW or JS_PROP_THROW_STRICT */ static int JS_SetPropertyValue(JSContext *ctx, JSValueConst this_obj, JSValue prop, JSValue val, int flags) { if (likely(JS_VALUE_GET_TAG(this_obj) == JS_TAG_OBJECT && JS_VALUE_GET_TAG(prop) == JS_TAG_INT)) { JSObject *p; uint32_t idx; double d; int32_t v; /* fast path for array access */ p = JS_VALUE_GET_OBJ(this_obj); idx = JS_VALUE_GET_INT(prop); switch(p->class_id) { case JS_CLASS_ARRAY: if (unlikely(idx >= (uint32_t)p->u.array.count)) { JSObject *p1; JSShape *sh1; /* fast path to add an element to the array */ if (idx != (uint32_t)p->u.array.count || !p->fast_array || !p->extensible) goto slow_path; /* check if prototype chain has a numeric property */ p1 = p->shape->proto; while (p1 != NULL) { sh1 = p1->shape; if (p1->class_id == JS_CLASS_ARRAY) { if (unlikely(!p1->fast_array)) goto slow_path; } else if (p1->class_id == JS_CLASS_OBJECT) { if (unlikely(sh1->has_small_array_index)) goto slow_path; } else { goto slow_path; } p1 = sh1->proto; } /* add element */ return add_fast_array_element(ctx, p, val, flags); } set_value(ctx, &p->u.array.u.values[idx], val); break; case JS_CLASS_ARGUMENTS: if (unlikely(idx >= (uint32_t)p->u.array.count)) goto slow_path; set_value(ctx, &p->u.array.u.values[idx], val); break; case JS_CLASS_UINT8C_ARRAY: if (JS_ToUint8ClampFree(ctx, &v, val)) goto ta_cvt_fail; /* Note: the conversion can detach the typed array, so the array bound check must be done after */ if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.uint8_ptr[idx] = v; break; case JS_CLASS_INT8_ARRAY: case JS_CLASS_UINT8_ARRAY: if (JS_ToInt32Free(ctx, &v, val)) goto ta_cvt_fail; if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.uint8_ptr[idx] = v; break; case JS_CLASS_INT16_ARRAY: case JS_CLASS_UINT16_ARRAY: if (JS_ToInt32Free(ctx, &v, val)) goto ta_cvt_fail; if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.uint16_ptr[idx] = v; break; case JS_CLASS_INT32_ARRAY: case JS_CLASS_UINT32_ARRAY: if (JS_ToInt32Free(ctx, &v, val)) goto ta_cvt_fail; if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.uint32_ptr[idx] = v; break; case JS_CLASS_BIG_INT64_ARRAY: case JS_CLASS_BIG_UINT64_ARRAY: /* XXX: need specific conversion function */ { int64_t v; if (JS_ToBigInt64Free(ctx, &v, val)) goto ta_cvt_fail; if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.uint64_ptr[idx] = v; } break; case JS_CLASS_FLOAT16_ARRAY: if (JS_ToFloat64Free(ctx, &d, val)) goto ta_cvt_fail; if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.fp16_ptr[idx] = tofp16(d); break; case JS_CLASS_FLOAT32_ARRAY: if (JS_ToFloat64Free(ctx, &d, val)) goto ta_cvt_fail; if (unlikely(idx >= (uint32_t)p->u.array.count)) goto ta_out_of_bound; p->u.array.u.float_ptr[idx] = d; break; case JS_CLASS_FLOAT64_ARRAY: if (JS_ToFloat64Free(ctx, &d, val)) { ta_cvt_fail: if (flags & JS_PROP_REFLECT_DEFINE_PROPERTY) { JS_FreeValue(ctx, JS_GetException(ctx)); return false; } return -1; } if (unlikely(idx >= (uint32_t)p->u.array.count)) { ta_out_of_bound: if (typed_array_is_oob(p)) if (flags & JS_PROP_DEFINE_PROPERTY) return JS_ThrowTypeErrorOrFalse(ctx, flags, "out-of-bound numeric index"); return true; // per spec: no OOB exception } p->u.array.u.double_ptr[idx] = d; break; default: goto slow_path; } return true; } else { JSAtom atom; int ret; slow_path: atom = JS_ValueToAtom(ctx, prop); JS_FreeValue(ctx, prop); if (unlikely(atom == JS_ATOM_NULL)) { JS_FreeValue(ctx, val); return -1; } ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, flags); JS_FreeAtom(ctx, atom); return ret; } } int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx, JSValue val) { return JS_SetPropertyValue(ctx, this_obj, js_uint32(idx), val, JS_PROP_THROW); } int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj, int64_t idx, JSValue val) { JSAtom prop; int res; if ((uint64_t)idx <= INT32_MAX) { /* fast path for fast arrays */ return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), val, JS_PROP_THROW); } prop = JS_NewAtomInt64(ctx, idx); if (prop == JS_ATOM_NULL) { JS_FreeValue(ctx, val); return -1; } res = JS_SetProperty(ctx, this_obj, prop, val); JS_FreeAtom(ctx, prop); return res; } /* `prop` may be pure ASCII or UTF-8 encoded */ int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj, const char *prop, JSValue val) { JSAtom atom; int ret; atom = JS_NewAtom(ctx, prop); if (atom == JS_ATOM_NULL) { JS_FreeValue(ctx, val); return -1; } ret = JS_SetPropertyInternal(ctx, this_obj, atom, val, JS_PROP_THROW); JS_FreeAtom(ctx, atom); return ret; } /* compute the property flags. For each flag: (JS_PROP_HAS_x forces it, otherwise def_flags is used) Note: makes assumption about the bit pattern of the flags */ static int get_prop_flags(int flags, int def_flags) { int mask; mask = (flags >> JS_PROP_HAS_SHIFT) & JS_PROP_C_W_E; return (flags & mask) | (def_flags & ~mask); } static int JS_CreateProperty(JSContext *ctx, JSObject *p, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags) { JSProperty *pr; int ret, prop_flags; /* add a new property or modify an existing exotic one */ if (p->is_exotic) { if (p->class_id == JS_CLASS_ARRAY) { uint32_t idx, len; if (p->fast_array) { if (__JS_AtomIsTaggedInt(prop)) { idx = __JS_AtomToUInt32(prop); if (idx == p->u.array.count) { if (!p->extensible) goto not_extensible; if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) goto convert_to_array; prop_flags = get_prop_flags(flags, 0); if (prop_flags != JS_PROP_C_W_E) goto convert_to_array; return add_fast_array_element(ctx, p, js_dup(val), flags); } else { goto convert_to_array; } } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) { /* convert the fast array to normal array */ convert_to_array: if (convert_fast_array_to_array(ctx, p)) return -1; goto generic_array; } } else if (JS_AtomIsArrayIndex(ctx, &idx, prop)) { JSProperty *plen; JSShapeProperty *pslen; generic_array: /* update the length field */ plen = &p->prop[0]; JS_ToUint32(ctx, &len, plen->u.value); if ((idx + 1) > len) { pslen = get_shape_prop(p->shape); if (unlikely(!(pslen->flags & JS_PROP_WRITABLE))) return JS_ThrowTypeErrorReadOnly(ctx, flags, JS_ATOM_length); /* XXX: should update the length after defining the property */ len = idx + 1; set_value(ctx, &plen->u.value, js_uint32(len)); } } } else if (is_typed_array(p->class_id)) { ret = JS_AtomIsNumericIndex(ctx, prop); if (ret != 0) { if (ret < 0) return -1; return JS_ThrowTypeErrorOrFalse(ctx, flags, "cannot create numeric index in typed array"); } } else if (!(flags & JS_PROP_NO_EXOTIC)) { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; if (em) { if (em->define_own_property) { return em->define_own_property(ctx, JS_MKPTR(JS_TAG_OBJECT, p), prop, val, getter, setter, flags); } ret = JS_IsExtensible(ctx, JS_MKPTR(JS_TAG_OBJECT, p)); if (ret < 0) return -1; if (!ret) goto not_extensible; } } } if (!p->extensible) { not_extensible: return JS_ThrowTypeErrorOrFalse(ctx, flags, "object is not extensible"); } if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { prop_flags = (flags & (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) | JS_PROP_GETSET; } else { prop_flags = flags & JS_PROP_C_W_E; } pr = add_property(ctx, p, prop, prop_flags); if (unlikely(!pr)) return -1; if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { pr->u.getset.getter = NULL; if ((flags & JS_PROP_HAS_GET) && JS_IsFunction(ctx, getter)) { pr->u.getset.getter = JS_VALUE_GET_OBJ(js_dup(getter)); } pr->u.getset.setter = NULL; if ((flags & JS_PROP_HAS_SET) && JS_IsFunction(ctx, setter)) { pr->u.getset.setter = JS_VALUE_GET_OBJ(js_dup(setter)); } } else { if (flags & JS_PROP_HAS_VALUE) { pr->u.value = js_dup(val); } else { pr->u.value = JS_UNDEFINED; } } return true; } /* return false if not OK */ static bool check_define_prop_flags(int prop_flags, int flags) { bool has_accessor, is_getset; if (!(prop_flags & JS_PROP_CONFIGURABLE)) { if ((flags & (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) == (JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE)) { return false; } if ((flags & JS_PROP_HAS_ENUMERABLE) && (flags & JS_PROP_ENUMERABLE) != (prop_flags & JS_PROP_ENUMERABLE)) return false; } if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { if (!(prop_flags & JS_PROP_CONFIGURABLE)) { has_accessor = ((flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) != 0); is_getset = ((prop_flags & JS_PROP_TMASK) == JS_PROP_GETSET); if (has_accessor != is_getset) return false; if (!has_accessor && !is_getset && !(prop_flags & JS_PROP_WRITABLE)) { /* not writable: cannot set the writable bit */ if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) return false; } } } return true; } /* ensure that the shape can be safely modified */ static int js_shape_prepare_update(JSContext *ctx, JSObject *p, JSShapeProperty **pprs) { JSShape *sh; uint32_t idx = 0; /* prevent warning */ sh = p->shape; if (sh->is_hashed) { if (sh->header.ref_count != 1) { if (pprs) idx = *pprs - get_shape_prop(sh); /* clone the shape (the resulting one is no longer hashed) */ sh = js_clone_shape(ctx, sh); if (!sh) return -1; js_free_shape(ctx->rt, p->shape); p->shape = sh; if (pprs) *pprs = get_shape_prop(sh) + idx; } else { js_shape_hash_unlink(ctx->rt, sh); sh->is_hashed = false; } } return 0; } static int js_update_property_flags(JSContext *ctx, JSObject *p, JSShapeProperty **pprs, int flags) { if (flags != (*pprs)->flags) { if (js_shape_prepare_update(ctx, p, pprs)) return -1; (*pprs)->flags = flags; } return 0; } /* allowed flags: JS_PROP_CONFIGURABLE, JS_PROP_WRITABLE, JS_PROP_ENUMERABLE JS_PROP_HAS_GET, JS_PROP_HAS_SET, JS_PROP_HAS_VALUE, JS_PROP_HAS_CONFIGURABLE, JS_PROP_HAS_WRITABLE, JS_PROP_HAS_ENUMERABLE, JS_PROP_THROW, JS_PROP_NO_EXOTIC. If JS_PROP_THROW is set, return an exception instead of false. if JS_PROP_NO_EXOTIC is set, do not call the exotic define_own_property callback. return -1 (exception), false or true. */ int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; int mask, res; if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) { JS_ThrowTypeErrorNotAnObject(ctx); return -1; } p = JS_VALUE_GET_OBJ(this_obj); redo_prop_update: prs = find_own_property(&pr, p, prop); if (prs) { /* the range of the Array length property is always tested before */ if ((prs->flags & JS_PROP_LENGTH) && (flags & JS_PROP_HAS_VALUE)) { uint32_t array_length; if (JS_ToArrayLengthFree(ctx, &array_length, js_dup(val), false)) { return -1; } /* this code relies on the fact that Uint32 are never allocated */ val = js_uint32(array_length); /* prs may have been modified */ prs = find_own_property(&pr, p, prop); assert(prs != NULL); } /* property already exists */ if (!check_define_prop_flags(prs->flags, flags)) { not_configurable: return JS_ThrowTypeErrorOrFalse(ctx, flags, "property is not configurable"); } if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { /* Instantiate property and retry */ if (JS_AutoInitProperty(ctx, p, prop, pr, prs)) return -1; goto redo_prop_update; } if (flags & (JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { JSObject *new_getter, *new_setter; if (JS_IsFunction(ctx, getter)) { new_getter = JS_VALUE_GET_OBJ(getter); } else { new_getter = NULL; } if (JS_IsFunction(ctx, setter)) { new_setter = JS_VALUE_GET_OBJ(setter); } else { new_setter = NULL; } if ((prs->flags & JS_PROP_TMASK) != JS_PROP_GETSET) { if (js_shape_prepare_update(ctx, p, &prs)) return -1; /* convert to getset */ if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { free_var_ref(ctx->rt, pr->u.var_ref); } else { JS_FreeValue(ctx, pr->u.value); } prs->flags = (prs->flags & (JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE)) | JS_PROP_GETSET; pr->u.getset.getter = NULL; pr->u.getset.setter = NULL; } else { if (!(prs->flags & JS_PROP_CONFIGURABLE)) { if ((flags & JS_PROP_HAS_GET) && new_getter != pr->u.getset.getter) { goto not_configurable; } if ((flags & JS_PROP_HAS_SET) && new_setter != pr->u.getset.setter) { goto not_configurable; } } } if (flags & JS_PROP_HAS_GET) { if (pr->u.getset.getter) JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); if (new_getter) js_dup(getter); pr->u.getset.getter = new_getter; } if (flags & JS_PROP_HAS_SET) { if (pr->u.getset.setter) JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); if (new_setter) js_dup(setter); pr->u.getset.setter = new_setter; } } else { if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { /* convert to data descriptor */ if (js_shape_prepare_update(ctx, p, &prs)) return -1; if (pr->u.getset.getter) JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.getter)); if (pr->u.getset.setter) JS_FreeValue(ctx, JS_MKPTR(JS_TAG_OBJECT, pr->u.getset.setter)); prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE); pr->u.value = JS_UNDEFINED; } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { /* Note: JS_PROP_VARREF is always writable */ } else { if ((prs->flags & (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE)) == 0 && (flags & JS_PROP_HAS_VALUE)) { if (!js_same_value(ctx, val, pr->u.value)) { goto not_configurable; } else { return true; } } } if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { if (flags & JS_PROP_HAS_VALUE) { if (p->class_id == JS_CLASS_MODULE_NS) { /* JS_PROP_WRITABLE is always true for variable references, but they are write protected in module name spaces. */ if (!js_same_value(ctx, val, *pr->u.var_ref->pvalue)) goto not_configurable; } /* update the reference */ set_value(ctx, pr->u.var_ref->pvalue, js_dup(val)); } /* if writable is set to false, no longer a reference (for mapped arguments) */ if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == JS_PROP_HAS_WRITABLE) { JSValue val1; if (js_shape_prepare_update(ctx, p, &prs)) return -1; val1 = js_dup(*pr->u.var_ref->pvalue); free_var_ref(ctx->rt, pr->u.var_ref); pr->u.value = val1; prs->flags &= ~(JS_PROP_TMASK | JS_PROP_WRITABLE); } } else if (prs->flags & JS_PROP_LENGTH) { if (flags & JS_PROP_HAS_VALUE) { /* Note: no JS code is executable because 'val' is guaranted to be a Uint32 */ res = set_array_length(ctx, p, js_dup(val), flags); } else { res = true; } /* still need to reset the writable flag if needed. The JS_PROP_LENGTH is kept because the Uint32 test is still done if the length property is read-only. */ if ((flags & (JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE)) == JS_PROP_HAS_WRITABLE) { prs = get_shape_prop(p->shape); if (js_update_property_flags(ctx, p, &prs, prs->flags & ~JS_PROP_WRITABLE)) return -1; } return res; } else { if (flags & JS_PROP_HAS_VALUE) { JS_FreeValue(ctx, pr->u.value); pr->u.value = js_dup(val); } if (flags & JS_PROP_HAS_WRITABLE) { if (js_update_property_flags(ctx, p, &prs, (prs->flags & ~JS_PROP_WRITABLE) | (flags & JS_PROP_WRITABLE))) return -1; } } } } mask = 0; if (flags & JS_PROP_HAS_CONFIGURABLE) mask |= JS_PROP_CONFIGURABLE; if (flags & JS_PROP_HAS_ENUMERABLE) mask |= JS_PROP_ENUMERABLE; if (js_update_property_flags(ctx, p, &prs, (prs->flags & ~mask) | (flags & mask))) return -1; return true; } /* handle modification of fast array elements */ if (p->fast_array) { uint32_t idx; uint32_t prop_flags; if (p->class_id == JS_CLASS_ARRAY) { if (__JS_AtomIsTaggedInt(prop)) { idx = __JS_AtomToUInt32(prop); if (idx < p->u.array.count) { prop_flags = get_prop_flags(flags, JS_PROP_C_W_E); if (prop_flags != JS_PROP_C_W_E) goto convert_to_slow_array; if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET)) { convert_to_slow_array: if (convert_fast_array_to_array(ctx, p)) return -1; else goto redo_prop_update; } if (flags & JS_PROP_HAS_VALUE) { set_value(ctx, &p->u.array.u.values[idx], js_dup(val)); } return true; } } } else if (is_typed_array(p->class_id)) { JSValue num; int ret; if (!__JS_AtomIsTaggedInt(prop)) { /* slow path with to handle all numeric indexes */ num = JS_AtomIsNumericIndex1(ctx, prop); if (JS_IsUndefined(num)) goto typed_array_done; if (JS_IsException(num)) return -1; ret = JS_NumberIsInteger(ctx, num); if (ret < 0) { JS_FreeValue(ctx, num); return -1; } if (!ret) { JS_FreeValue(ctx, num); return JS_ThrowTypeErrorOrFalse(ctx, flags, "non integer index in typed array"); } ret = JS_NumberIsNegativeOrMinusZero(ctx, num); JS_FreeValue(ctx, num); if (ret) { return JS_ThrowTypeErrorOrFalse(ctx, flags, "negative index in typed array"); } if (!__JS_AtomIsTaggedInt(prop)) goto typed_array_oob; } idx = __JS_AtomToUInt32(prop); /* if the typed array is detached, p->u.array.count = 0 */ if (idx >= p->u.array.count) { typed_array_oob: return JS_ThrowTypeErrorOrFalse(ctx, flags, "out-of-bound index in typed array"); } prop_flags = get_prop_flags(flags, JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); if (flags & (JS_PROP_HAS_GET | JS_PROP_HAS_SET) || prop_flags != (JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE)) { return JS_ThrowTypeErrorOrFalse(ctx, flags, "invalid descriptor flags"); } if (flags & JS_PROP_HAS_VALUE) { return JS_SetPropertyValue(ctx, this_obj, js_int32(idx), js_dup(val), flags); } return true; typed_array_done: ; } } return JS_CreateProperty(ctx, p, prop, val, getter, setter, flags); } static int JS_DefineAutoInitProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSAutoInitIDEnum id, void *opaque, int flags) { JSObject *p; JSProperty *pr; if (JS_VALUE_GET_TAG(this_obj) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(this_obj); if (find_own_property(&pr, p, prop)) { /* property already exists */ abort(); return false; } /* Specialized CreateProperty */ pr = add_property(ctx, p, prop, (flags & JS_PROP_C_W_E) | JS_PROP_AUTOINIT); if (unlikely(!pr)) return -1; pr->u.init.realm_and_id = (uintptr_t)JS_DupContext(ctx); assert((pr->u.init.realm_and_id & 3) == 0); assert(id <= 3); pr->u.init.realm_and_id |= id; pr->u.init.opaque = opaque; return true; } /* shortcut to add or redefine a new property value */ int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags) { int ret; ret = JS_DefineProperty(ctx, this_obj, prop, val, JS_UNDEFINED, JS_UNDEFINED, flags | JS_PROP_HAS_VALUE | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE); JS_FreeValue(ctx, val); return ret; } int JS_DefinePropertyValueValue(JSContext *ctx, JSValueConst this_obj, JSValue prop, JSValue val, int flags) { JSAtom atom; int ret; atom = JS_ValueToAtom(ctx, prop); JS_FreeValue(ctx, prop); if (unlikely(atom == JS_ATOM_NULL)) { JS_FreeValue(ctx, val); return -1; } ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags); JS_FreeAtom(ctx, atom); return ret; } int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx, JSValue val, int flags) { return JS_DefinePropertyValueValue(ctx, this_obj, js_uint32(idx), val, flags); } int JS_DefinePropertyValueInt64(JSContext *ctx, JSValueConst this_obj, int64_t idx, JSValue val, int flags) { return JS_DefinePropertyValueValue(ctx, this_obj, js_int64(idx), val, flags); } /* `prop` may be pure ASCII or UTF-8 encoded */ int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj, const char *prop, JSValue val, int flags) { JSAtom atom; int ret; atom = JS_NewAtom(ctx, prop); if (atom == JS_ATOM_NULL) { JS_FreeValue(ctx, val); return -1; } ret = JS_DefinePropertyValue(ctx, this_obj, atom, val, flags); JS_FreeAtom(ctx, atom); return ret; } /* shortcut to add getter & setter */ int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue getter, JSValue setter, int flags) { int ret; ret = JS_DefineProperty(ctx, this_obj, prop, JS_UNDEFINED, getter, setter, flags | JS_PROP_HAS_GET | JS_PROP_HAS_SET | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE); JS_FreeValue(ctx, getter); JS_FreeValue(ctx, setter); return ret; } static int JS_CreateDataPropertyUint32(JSContext *ctx, JSValueConst this_obj, int64_t idx, JSValue val, int flags) { return JS_DefinePropertyValueValue(ctx, this_obj, js_int64(idx), val, flags | JS_PROP_CONFIGURABLE | JS_PROP_ENUMERABLE | JS_PROP_WRITABLE); } /* return true if 'obj' has a non empty 'name' string */ static bool js_object_has_name(JSContext *ctx, JSValue obj) { JSProperty *pr; JSShapeProperty *prs; JSValue val; JSString *p; prs = find_own_property(&pr, JS_VALUE_GET_OBJ(obj), JS_ATOM_name); if (!prs) return false; if ((prs->flags & JS_PROP_TMASK) != JS_PROP_NORMAL) return true; val = pr->u.value; if (JS_VALUE_GET_TAG(val) != JS_TAG_STRING) return true; p = JS_VALUE_GET_STRING(val); return (p->len != 0); } static int JS_DefineObjectName(JSContext *ctx, JSValue obj, JSAtom name, int flags) { if (name != JS_ATOM_NULL && JS_IsObject(obj) && !js_object_has_name(ctx, obj) && JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, JS_AtomToString(ctx, name), flags) < 0) { return -1; } return 0; } static int JS_DefineObjectNameComputed(JSContext *ctx, JSValue obj, JSValue str, int flags) { if (JS_IsObject(obj) && !js_object_has_name(ctx, obj)) { JSAtom prop; JSValue name_str; prop = JS_ValueToAtom(ctx, str); if (prop == JS_ATOM_NULL) return -1; name_str = js_get_function_name(ctx, prop); JS_FreeAtom(ctx, prop); if (JS_IsException(name_str)) return -1; if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_name, name_str, flags) < 0) return -1; } return 0; } #define DEFINE_GLOBAL_LEX_VAR (1 << 7) #define DEFINE_GLOBAL_FUNC_VAR (1 << 6) static JSValue JS_ThrowSyntaxErrorVarRedeclaration(JSContext *ctx, JSAtom prop) { return JS_ThrowSyntaxErrorAtom(ctx, "redeclaration of '%s'", prop); } /* flags is 0, DEFINE_GLOBAL_LEX_VAR or DEFINE_GLOBAL_FUNC_VAR */ /* XXX: could support exotic global object. */ static int JS_CheckDefineGlobalVar(JSContext *ctx, JSAtom prop, int flags) { JSObject *p; JSShapeProperty *prs; p = JS_VALUE_GET_OBJ(ctx->global_obj); prs = find_own_property1(p, prop); /* XXX: should handle JS_PROP_AUTOINIT */ if (flags & DEFINE_GLOBAL_LEX_VAR) { if (prs && !(prs->flags & JS_PROP_CONFIGURABLE)) goto fail_redeclaration; } else { if (!prs && !p->extensible) goto define_error; if (flags & DEFINE_GLOBAL_FUNC_VAR) { if (prs) { if (!(prs->flags & JS_PROP_CONFIGURABLE) && ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET || ((prs->flags & (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)) != (JS_PROP_WRITABLE | JS_PROP_ENUMERABLE)))) { define_error: JS_ThrowTypeErrorAtom(ctx, "cannot define variable '%s'", prop); return -1; } } } } /* check if there already is a lexical declaration */ p = JS_VALUE_GET_OBJ(ctx->global_var_obj); prs = find_own_property1(p, prop); if (prs) { fail_redeclaration: JS_ThrowSyntaxErrorVarRedeclaration(ctx, prop); return -1; } return 0; } /* def_flags is (0, DEFINE_GLOBAL_LEX_VAR) | JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE */ /* XXX: could support exotic global object. */ static int JS_DefineGlobalVar(JSContext *ctx, JSAtom prop, int def_flags) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; JSValue val; int flags; if (def_flags & DEFINE_GLOBAL_LEX_VAR) { p = JS_VALUE_GET_OBJ(ctx->global_var_obj); flags = JS_PROP_ENUMERABLE | (def_flags & JS_PROP_WRITABLE) | JS_PROP_CONFIGURABLE; val = JS_UNINITIALIZED; } else { p = JS_VALUE_GET_OBJ(ctx->global_obj); flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | (def_flags & JS_PROP_CONFIGURABLE); val = JS_UNDEFINED; } prs = find_own_property1(p, prop); if (prs) return 0; if (!p->extensible) return 0; pr = add_property(ctx, p, prop, flags); if (unlikely(!pr)) return -1; pr->u.value = val; return 0; } /* 'def_flags' is 0 or JS_PROP_CONFIGURABLE. */ /* XXX: could support exotic global object. */ static int JS_DefineGlobalFunction(JSContext *ctx, JSAtom prop, JSValue func, int def_flags) { JSObject *p; JSShapeProperty *prs; int flags; p = JS_VALUE_GET_OBJ(ctx->global_obj); prs = find_own_property1(p, prop); flags = JS_PROP_HAS_VALUE | JS_PROP_THROW; if (!prs || (prs->flags & JS_PROP_CONFIGURABLE)) { flags |= JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | def_flags | JS_PROP_HAS_CONFIGURABLE | JS_PROP_HAS_WRITABLE | JS_PROP_HAS_ENUMERABLE; } if (JS_DefineProperty(ctx, ctx->global_obj, prop, func, JS_UNDEFINED, JS_UNDEFINED, flags) < 0) return -1; return 0; } static JSValue JS_GetGlobalVar(JSContext *ctx, JSAtom prop, bool throw_ref_error) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; /* no exotic behavior is possible in global_var_obj */ p = JS_VALUE_GET_OBJ(ctx->global_var_obj); prs = find_own_property(&pr, p, prop); if (prs) { /* XXX: should handle JS_PROP_TMASK properties */ if (unlikely(JS_IsUninitialized(pr->u.value))) return JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return js_dup(pr->u.value); } return JS_GetPropertyInternal(ctx, ctx->global_obj, prop, ctx->global_obj, throw_ref_error); } /* construct a reference to a global variable */ static int JS_GetGlobalVarRef(JSContext *ctx, JSAtom prop, JSValue *sp) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; /* no exotic behavior is possible in global_var_obj */ p = JS_VALUE_GET_OBJ(ctx->global_var_obj); prs = find_own_property(&pr, p, prop); if (prs) { /* XXX: should handle JS_PROP_AUTOINIT properties? */ /* XXX: conformance: do these tests in OP_put_var_ref/OP_get_var_ref ? */ if (unlikely(JS_IsUninitialized(pr->u.value))) { JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return -1; } if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) { return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop); } sp[0] = js_dup(ctx->global_var_obj); } else { int ret; ret = JS_HasProperty(ctx, ctx->global_obj, prop); if (ret < 0) return -1; if (ret) { sp[0] = js_dup(ctx->global_obj); } else { sp[0] = JS_UNDEFINED; } } sp[1] = JS_AtomToValue(ctx, prop); return 0; } /* use for strict variable access: test if the variable exists */ static int JS_CheckGlobalVar(JSContext *ctx, JSAtom prop) { JSObject *p; JSShapeProperty *prs; int ret; /* no exotic behavior is possible in global_var_obj */ p = JS_VALUE_GET_OBJ(ctx->global_var_obj); prs = find_own_property1(p, prop); if (prs) { ret = true; } else { ret = JS_HasProperty(ctx, ctx->global_obj, prop); if (ret < 0) return -1; } return ret; } /* flag = 0: normal variable write flag = 1: initialize lexical variable flag = 2: normal variable write, strict check was done before */ static int JS_SetGlobalVar(JSContext *ctx, JSAtom prop, JSValue val, int flag) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; int flags; /* no exotic behavior is possible in global_var_obj */ p = JS_VALUE_GET_OBJ(ctx->global_var_obj); prs = find_own_property(&pr, p, prop); if (prs) { /* XXX: should handle JS_PROP_AUTOINIT properties? */ if (flag != 1) { if (unlikely(JS_IsUninitialized(pr->u.value))) { JS_FreeValue(ctx, val); JS_ThrowReferenceErrorUninitialized(ctx, prs->atom); return -1; } if (unlikely(!(prs->flags & JS_PROP_WRITABLE))) { JS_FreeValue(ctx, val); return JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, prop); } } set_value(ctx, &pr->u.value, val); return 0; } flags = JS_PROP_THROW_STRICT; if (is_strict_mode(ctx)) flags |= JS_PROP_NO_ADD; return JS_SetPropertyInternal(ctx, ctx->global_obj, prop, val, flags); } /* return -1, false or true */ static int JS_DeleteGlobalVar(JSContext *ctx, JSAtom prop) { JSObject *p; JSShapeProperty *prs; JSProperty *pr; int ret; /* 9.1.1.4.7 DeleteBinding ( N ) */ p = JS_VALUE_GET_OBJ(ctx->global_var_obj); prs = find_own_property(&pr, p, prop); if (prs) return false; /* lexical variables cannot be deleted */ ret = JS_HasProperty(ctx, ctx->global_obj, prop); if (ret < 0) return -1; if (ret) { return JS_DeleteProperty(ctx, ctx->global_obj, prop, 0); } else { return true; } } /* return -1, false or true. return false if not configurable or invalid object. return -1 in case of exception. flags can be 0, JS_PROP_THROW or JS_PROP_THROW_STRICT */ int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags) { JSValue obj1; JSObject *p; int res; obj1 = JS_ToObject(ctx, obj); if (JS_IsException(obj1)) return -1; p = JS_VALUE_GET_OBJ(obj1); res = delete_property(ctx, p, prop); JS_FreeValue(ctx, obj1); if (res != false) return res; if ((flags & JS_PROP_THROW) || ((flags & JS_PROP_THROW_STRICT) && is_strict_mode(ctx))) { JS_ThrowTypeError(ctx, "could not delete property"); return -1; } return false; } int JS_DeletePropertyInt64(JSContext *ctx, JSValueConst obj, int64_t idx, int flags) { JSAtom prop; int res; if ((uint64_t)idx <= JS_ATOM_MAX_INT) { /* fast path for fast arrays */ return JS_DeleteProperty(ctx, obj, __JS_AtomFromUInt32(idx), flags); } prop = JS_NewAtomInt64(ctx, idx); if (prop == JS_ATOM_NULL) return -1; res = JS_DeleteProperty(ctx, obj, prop, flags); JS_FreeAtom(ctx, prop); return res; } bool JS_IsFunction(JSContext *ctx, JSValueConst val) { JSObject *p; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(val); switch(p->class_id) { case JS_CLASS_BYTECODE_FUNCTION: return true; case JS_CLASS_PROXY: return p->u.proxy_data->is_func; default: return (ctx->rt->class_array[p->class_id].call != NULL); } } static bool JS_IsCFunction(JSContext *ctx, JSValueConst val, JSCFunction *func, int magic) { JSObject *p; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(val); if (p->class_id == JS_CLASS_C_FUNCTION) return (p->u.cfunc.c_function.generic == func && p->u.cfunc.magic == magic); else return false; } bool JS_IsConstructor(JSContext *ctx, JSValueConst val) { JSObject *p; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(val); return p->is_constructor; } bool JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, bool val) { JSObject *p; if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(func_obj); p->is_constructor = val; return true; } bool JS_IsRegExp(JSValueConst val) { return JS_CLASS_REGEXP == JS_GetClassID(val); } bool JS_IsMap(JSValueConst val) { return JS_CLASS_MAP == JS_GetClassID(val); } bool JS_IsSet(JSValueConst val) { return JS_CLASS_SET == JS_GetClassID(val); } bool JS_IsWeakRef(JSValueConst val) { return JS_CLASS_WEAK_REF == JS_GetClassID(val); } bool JS_IsWeakSet(JSValueConst val) { return JS_CLASS_WEAKSET == JS_GetClassID(val); } bool JS_IsWeakMap(JSValueConst val) { return JS_CLASS_WEAKMAP == JS_GetClassID(val); } bool JS_IsDataView(JSValueConst val) { return JS_CLASS_DATAVIEW == JS_GetClassID(val); } bool JS_IsError(JSValueConst val) { return JS_CLASS_ERROR == JS_GetClassID(val); } /* used to avoid catching interrupt exceptions */ bool JS_IsUncatchableError(JSValueConst val) { JSObject *p; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(val); return p->class_id == JS_CLASS_ERROR && p->is_uncatchable_error; } static void js_set_uncatchable_error(JSContext *ctx, JSValueConst val, bool flag) { JSObject *p; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return; p = JS_VALUE_GET_OBJ(val); if (p->class_id == JS_CLASS_ERROR) p->is_uncatchable_error = flag; } void JS_SetUncatchableError(JSContext *ctx, JSValueConst val) { js_set_uncatchable_error(ctx, val, true); } void JS_ClearUncatchableError(JSContext *ctx, JSValueConst val) { js_set_uncatchable_error(ctx, val, false); } void JS_ResetUncatchableError(JSContext *ctx) { js_set_uncatchable_error(ctx, ctx->rt->current_exception, false); } int JS_SetOpaque(JSValueConst obj, void *opaque) { JSObject *p; if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { p = JS_VALUE_GET_OBJ(obj); // User code can't set the opaque of internal objects. if (p->class_id >= JS_CLASS_INIT_COUNT) { p->u.opaque = opaque; return 0; } } return -1; } /* |obj| must be a JSObject of an internal class. */ static void JS_SetOpaqueInternal(JSValueConst obj, void *opaque) { JSObject *p; assert(JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT); p = JS_VALUE_GET_OBJ(obj); assert(p->class_id < JS_CLASS_INIT_COUNT); p->u.opaque = opaque; } /* return NULL if not an object of class class_id */ void *JS_GetOpaque(JSValueConst obj, JSClassID class_id) { JSObject *p; if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) return NULL; p = JS_VALUE_GET_OBJ(obj); if (p->class_id != class_id) return NULL; return p->u.opaque; } void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id) { void *p = JS_GetOpaque(obj, class_id); if (unlikely(!p)) { JS_ThrowTypeErrorInvalidClass(ctx, class_id); } return p; } void *JS_GetAnyOpaque(JSValueConst obj, JSClassID *class_id) { JSObject *p; if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) { *class_id = 0; return NULL; } p = JS_VALUE_GET_OBJ(obj); *class_id = p->class_id; return p->u.opaque; } static JSValue JS_ToPrimitiveFree(JSContext *ctx, JSValue val, int hint) { int i; bool force_ordinary; JSAtom method_name; JSValue method, ret; if (JS_VALUE_GET_TAG(val) != JS_TAG_OBJECT) return val; force_ordinary = hint & HINT_FORCE_ORDINARY; hint &= ~HINT_FORCE_ORDINARY; if (!force_ordinary) { method = JS_GetProperty(ctx, val, JS_ATOM_Symbol_toPrimitive); if (JS_IsException(method)) goto exception; /* ECMA says *If exoticToPrim is not undefined* but tests in test262 use null as a non callable converter */ if (!JS_IsUndefined(method) && !JS_IsNull(method)) { JSAtom atom; JSValue arg; switch(hint) { case HINT_STRING: atom = JS_ATOM_string; break; case HINT_NUMBER: atom = JS_ATOM_number; break; default: case HINT_NONE: atom = JS_ATOM_default; break; } arg = JS_AtomToString(ctx, atom); ret = JS_CallFree(ctx, method, val, 1, vc(&arg)); JS_FreeValue(ctx, arg); if (JS_IsException(ret)) goto exception; JS_FreeValue(ctx, val); if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) return ret; JS_FreeValue(ctx, ret); return JS_ThrowTypeError(ctx, "toPrimitive"); } } if (hint != HINT_STRING) hint = HINT_NUMBER; for(i = 0; i < 2; i++) { if ((i ^ hint) == 0) { method_name = JS_ATOM_toString; } else { method_name = JS_ATOM_valueOf; } method = JS_GetProperty(ctx, val, method_name); if (JS_IsException(method)) goto exception; if (JS_IsFunction(ctx, method)) { ret = JS_CallFree(ctx, method, val, 0, NULL); if (JS_IsException(ret)) goto exception; if (JS_VALUE_GET_TAG(ret) != JS_TAG_OBJECT) { JS_FreeValue(ctx, val); return ret; } JS_FreeValue(ctx, ret); } else { JS_FreeValue(ctx, method); } } JS_ThrowTypeError(ctx, "toPrimitive"); exception: JS_FreeValue(ctx, val); return JS_EXCEPTION; } static JSValue JS_ToPrimitive(JSContext *ctx, JSValueConst val, int hint) { return JS_ToPrimitiveFree(ctx, js_dup(val), hint); } void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj) { JSObject *p; if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) return; p = JS_VALUE_GET_OBJ(obj); p->is_HTMLDDA = true; } static inline bool JS_IsHTMLDDA(JSContext *ctx, JSValueConst obj) { JSObject *p; if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(obj); return p->is_HTMLDDA; } static int JS_ToBoolFree(JSContext *ctx, JSValue val) { uint32_t tag = JS_VALUE_GET_TAG(val); switch(tag) { case JS_TAG_INT: return JS_VALUE_GET_INT(val) != 0; case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: return JS_VALUE_GET_INT(val); case JS_TAG_EXCEPTION: return -1; case JS_TAG_STRING: { bool ret = JS_VALUE_GET_STRING(val)->len != 0; JS_FreeValue(ctx, val); return ret; } case JS_TAG_SHORT_BIG_INT: return JS_VALUE_GET_SHORT_BIG_INT(val) != 0; case JS_TAG_BIG_INT: { JSBigInt *p = JS_VALUE_GET_PTR(val); bool ret; int i; /* fail safe: we assume it is not necessarily normalized. Beginning from the MSB ensures that the test is fast. */ ret = false; for(i = p->len - 1; i >= 0; i--) { if (p->tab[i] != 0) { ret = true; break; } } JS_FreeValue(ctx, val); return ret; } case JS_TAG_OBJECT: { JSObject *p = JS_VALUE_GET_OBJ(val); bool ret = !p->is_HTMLDDA; JS_FreeValue(ctx, val); return ret; } break; default: if (JS_TAG_IS_FLOAT64(tag)) { double d = JS_VALUE_GET_FLOAT64(val); return !isnan(d) && d != 0; } else { JS_FreeValue(ctx, val); return true; } } } int JS_ToBool(JSContext *ctx, JSValueConst val) { return JS_ToBoolFree(ctx, js_dup(val)); } /* pc points to pure ASCII or UTF-8, null terminated contents */ static int skip_spaces(const char *pc) { const uint8_t *p, *p_next, *p_start; uint32_t c; p = p_start = (const uint8_t *)pc; for (;;) { c = *p++; if (c < 0x80) { if (!((c >= 0x09 && c <= 0x0d) || (c == 0x20))) break; } else { c = utf8_decode(p - 1, &p_next); /* no need to test for invalid UTF-8, 0xFFFD is not a space */ if (!lre_is_space(c)) break; p = p_next; } } return p - 1 - p_start; } static inline int js_to_digit(int c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'Z') return c - 'A' + 10; else if (c >= 'a' && c <= 'z') return c - 'a' + 10; else return 36; } /* bigint support */ #define ADDC(res, carry_out, op1, op2, carry_in) \ do { \ js_limb_t __v, __a, __k, __k1; \ __v = (op1); \ __a = __v + (op2); \ __k1 = __a < __v; \ __k = (carry_in); \ __a = __a + __k; \ carry_out = (__a < __k) | __k1; \ res = __a; \ } while (0) /* a != 0 */ static inline js_limb_t js_limb_clz(js_limb_t a) { if (!a) return JS_LIMB_BITS; return clz32(a); } static js_limb_t js_mp_add(js_limb_t *res, const js_limb_t *op1, const js_limb_t *op2, js_limb_t n, js_limb_t carry) { int i; for(i = 0;i < n; i++) { ADDC(res[i], carry, op1[i], op2[i], carry); } return carry; } static js_limb_t js_mp_sub(js_limb_t *res, const js_limb_t *op1, const js_limb_t *op2, int n, js_limb_t carry) { int i; js_limb_t k, a, v, k1; k = carry; for(i=0;i v; v = a - k; k = (v > a) | k1; res[i] = v; } return k; } /* compute 0 - op2. carry = 0 or 1. */ static js_limb_t js_mp_neg(js_limb_t *res, const js_limb_t *op2, int n) { int i; js_limb_t v, carry; carry = 1; for(i=0;i> JS_LIMB_BITS; } return l; } static js_limb_t js_mp_div1(js_limb_t *tabr, const js_limb_t *taba, js_limb_t n, js_limb_t b, js_limb_t r) { js_slimb_t i; js_dlimb_t a1; for(i = n - 1; i >= 0; i--) { a1 = ((js_dlimb_t)r << JS_LIMB_BITS) | taba[i]; tabr[i] = a1 / b; r = a1 % b; } return r; } /* tabr[] += taba[] * b, return the high word. */ static js_limb_t js_mp_add_mul1(js_limb_t *tabr, const js_limb_t *taba, js_limb_t n, js_limb_t b) { js_limb_t i, l; js_dlimb_t t; l = 0; for(i = 0; i < n; i++) { t = (js_dlimb_t)taba[i] * (js_dlimb_t)b + l + tabr[i]; tabr[i] = t; l = t >> JS_LIMB_BITS; } return l; } /* size of the result : op1_size + op2_size. */ static void js_mp_mul_basecase(js_limb_t *result, const js_limb_t *op1, js_limb_t op1_size, const js_limb_t *op2, js_limb_t op2_size) { int i; js_limb_t r; result[op1_size] = js_mp_mul1(result, op1, op1_size, op2[0], 0); for(i=1;i> JS_LIMB_BITS); } return l; } /* WARNING: d must be >= 2^(JS_LIMB_BITS-1) */ static inline js_limb_t js_udiv1norm_init(js_limb_t d) { js_limb_t a0, a1; a1 = -d - 1; a0 = -1; return (((js_dlimb_t)a1 << JS_LIMB_BITS) | a0) / d; } /* return the quotient and the remainder in '*pr'of 'a1*2^JS_LIMB_BITS+a0 / d' with 0 <= a1 < d. */ static inline js_limb_t js_udiv1norm(js_limb_t *pr, js_limb_t a1, js_limb_t a0, js_limb_t d, js_limb_t d_inv) { js_limb_t n1m, n_adj, q, r, ah; js_dlimb_t a; n1m = ((js_slimb_t)a0 >> (JS_LIMB_BITS - 1)); n_adj = a0 + (n1m & d); a = (js_dlimb_t)d_inv * (a1 - n1m) + n_adj; q = (a >> JS_LIMB_BITS) + a1; /* compute a - q * r and update q so that the remainder is\ between 0 and d - 1 */ a = ((js_dlimb_t)a1 << JS_LIMB_BITS) | a0; a = a - (js_dlimb_t)q * d - d; ah = a >> JS_LIMB_BITS; q += 1 + ah; r = (js_limb_t)a + (ah & d); *pr = r; return q; } #define UDIV1NORM_THRESHOLD 3 /* b must be >= 1 << (JS_LIMB_BITS - 1) */ static js_limb_t js_mp_div1norm(js_limb_t *tabr, const js_limb_t *taba, js_limb_t n, js_limb_t b, js_limb_t r) { js_slimb_t i; if (n >= UDIV1NORM_THRESHOLD) { js_limb_t b_inv; b_inv = js_udiv1norm_init(b); for(i = n - 1; i >= 0; i--) { tabr[i] = js_udiv1norm(&r, r, taba[i], b, b_inv); } } else { js_dlimb_t a1; for(i = n - 1; i >= 0; i--) { a1 = ((js_dlimb_t)r << JS_LIMB_BITS) | taba[i]; tabr[i] = a1 / b; r = a1 % b; } } return r; } /* base case division: divides taba[0..na-1] by tabb[0..nb-1]. tabb[nb - 1] must be >= 1 << (JS_LIMB_BITS - 1). na - nb must be >= 0. 'taba' is modified and contains the remainder (nb limbs). tabq[0..na-nb] contains the quotient with tabq[na - nb] <= 1. */ static void js_mp_divnorm(js_limb_t *tabq, js_limb_t *taba, js_limb_t na, const js_limb_t *tabb, js_limb_t nb) { js_limb_t r, a, c, q, v, b1, b1_inv, n, dummy_r; int i, j; b1 = tabb[nb - 1]; if (nb == 1) { taba[0] = js_mp_div1norm(tabq, taba, na, b1, 0); return; } n = na - nb; if (n >= UDIV1NORM_THRESHOLD) b1_inv = js_udiv1norm_init(b1); else b1_inv = 0; /* first iteration: the quotient is only 0 or 1 */ q = 1; for(j = nb - 1; j >= 0; j--) { if (taba[n + j] != tabb[j]) { if (taba[n + j] < tabb[j]) q = 0; break; } } tabq[n] = q; if (q) { js_mp_sub(taba + n, taba + n, tabb, nb, 0); } for(i = n - 1; i >= 0; i--) { if (unlikely(taba[i + nb] >= b1)) { q = -1; } else if (b1_inv) { q = js_udiv1norm(&dummy_r, taba[i + nb], taba[i + nb - 1], b1, b1_inv); } else { js_dlimb_t al; al = ((js_dlimb_t)taba[i + nb] << JS_LIMB_BITS) | taba[i + nb - 1]; q = al / b1; r = al % b1; } r = js_mp_sub_mul1(taba + i, tabb, nb, q); v = taba[i + nb]; a = v - r; c = (a > v); taba[i + nb] = a; if (c != 0) { /* negative result */ for(;;) { q--; c = js_mp_add(taba + i, taba + i, tabb, nb, 0); /* propagate carry and test if positive result */ if (c != 0) { if (++taba[i + nb] == 0) { break; } } } } tabq[i] = q; } } /* 1 <= shift <= JS_LIMB_BITS - 1 */ static js_limb_t js_mp_shl(js_limb_t *tabr, const js_limb_t *taba, int n, int shift) { int i; js_limb_t l, v; l = 0; for(i = 0; i < n; i++) { v = taba[i]; tabr[i] = (v << shift) | l; l = v >> (JS_LIMB_BITS - shift); } return l; } /* r = (a + high*B^n) >> shift. Return the remainder r (0 <= r < 2^shift). 1 <= shift <= LIMB_BITS - 1 */ static js_limb_t js_mp_shr(js_limb_t *tab_r, const js_limb_t *tab, int n, int shift, js_limb_t high) { int i; js_limb_t l, a; l = high; for(i = n - 1; i >= 0; i--) { a = tab[i]; tab_r[i] = (a >> shift) | (l << (JS_LIMB_BITS - shift)); l = a; } return l & (((js_limb_t)1 << shift) - 1); } static JSBigInt *js_bigint_new(JSContext *ctx, int len) { JSBigInt *r; if (len > JS_BIGINT_MAX_SIZE) { JS_ThrowRangeError(ctx, "BigInt is too large to allocate"); return NULL; } r = js_malloc(ctx, sizeof(JSBigInt) + len * sizeof(js_limb_t)); if (!r) return NULL; r->header.ref_count = 1; r->len = len; return r; } static JSBigInt *js_bigint_set_si(JSBigIntBuf *buf, js_slimb_t a) { JSBigInt *r = (JSBigInt *)buf->big_int_buf; r->header.ref_count = 0; /* fail safe */ r->len = 1; r->tab[0] = a; return r; } static JSBigInt *js_bigint_set_si64(JSBigIntBuf *buf, int64_t a) { JSBigInt *r = (JSBigInt *)buf->big_int_buf; r->header.ref_count = 0; /* fail safe */ if (a >= INT32_MIN && a <= INT32_MAX) { r->len = 1; r->tab[0] = a; } else { r->len = 2; r->tab[0] = a; r->tab[1] = a >> JS_LIMB_BITS; } return r; } /* val must be a short big int */ static JSBigInt *js_bigint_set_short(JSBigIntBuf *buf, JSValueConst val) { return js_bigint_set_si(buf, JS_VALUE_GET_SHORT_BIG_INT(val)); } static __maybe_unused void js_bigint_dump1(JSContext *ctx, const char *str, const js_limb_t *tab, int len) { int i; printf("%s: ", str); for(i = len - 1; i >= 0; i--) { printf(" %08x", tab[i]); } printf("\n"); } static __maybe_unused void js_bigint_dump(JSContext *ctx, const char *str, const JSBigInt *p) { js_bigint_dump1(ctx, str, p->tab, p->len); } static JSBigInt *js_bigint_new_si(JSContext *ctx, js_slimb_t a) { JSBigInt *r; r = js_bigint_new(ctx, 1); if (!r) return NULL; r->tab[0] = a; return r; } static JSBigInt *js_bigint_new_si64(JSContext *ctx, int64_t a) { if (a >= INT32_MIN && a <= INT32_MAX) { return js_bigint_new_si(ctx, a); } else { JSBigInt *r; r = js_bigint_new(ctx, 2); if (!r) return NULL; r->tab[0] = a; r->tab[1] = a >> 32; return r; } } static JSBigInt *js_bigint_new_ui64(JSContext *ctx, uint64_t a) { if (a <= INT64_MAX) { return js_bigint_new_si64(ctx, a); } else { JSBigInt *r; r = js_bigint_new(ctx, (65 + JS_LIMB_BITS - 1) / JS_LIMB_BITS); if (!r) return NULL; r->tab[0] = a; r->tab[1] = a >> 32; r->tab[2] = 0; return r; } } static JSBigInt *js_bigint_new_di(JSContext *ctx, js_sdlimb_t a) { JSBigInt *r; if (a == (js_slimb_t)a) { r = js_bigint_new(ctx, 1); if (!r) return NULL; r->tab[0] = a; } else { r = js_bigint_new(ctx, 2); if (!r) return NULL; r->tab[0] = a; r->tab[1] = a >> JS_LIMB_BITS; } return r; } /* Remove redundant high order limbs. Warning: 'a' may be reallocated. Can never fail. */ static JSBigInt *js_bigint_normalize1(JSContext *ctx, JSBigInt *a, int l) { js_limb_t v; assert(a->header.ref_count == 1); while (l > 1) { v = a->tab[l - 1]; if ((v != 0 && v != -1) || (v & 1) != (a->tab[l - 2] >> (JS_LIMB_BITS - 1))) { break; } l--; } if (l != a->len) { JSBigInt *a1; /* realloc to reduce the size */ a->len = l; a1 = js_realloc(ctx, a, sizeof(JSBigInt) + l * sizeof(js_limb_t)); if (a1) a = a1; } return a; } static JSBigInt *js_bigint_normalize(JSContext *ctx, JSBigInt *a) { return js_bigint_normalize1(ctx, a, a->len); } /* return 0 or 1 depending on the sign */ static inline int js_bigint_sign(const JSBigInt *a) { return a->tab[a->len - 1] >> (JS_LIMB_BITS - 1); } static js_slimb_t js_bigint_get_si_sat(const JSBigInt *a) { if (a->len == 1) { return a->tab[0]; } else { if (js_bigint_sign(a)) return INT32_MIN; else return INT32_MAX; } } /* add the op1 limb */ static JSBigInt *js_bigint_extend(JSContext *ctx, JSBigInt *r, js_limb_t op1) { int n2 = r->len; if ((op1 != 0 && op1 != -1) || (op1 & 1) != r->tab[n2 - 1] >> (JS_LIMB_BITS - 1)) { JSBigInt *r1; r1 = js_realloc(ctx, r, sizeof(JSBigInt) + (n2 + 1) * sizeof(js_limb_t)); if (!r1) { js_free(ctx, r); return NULL; } r = r1; r->len = n2 + 1; r->tab[n2] = op1; } else { /* otherwise still need to normalize the result */ r = js_bigint_normalize(ctx, r); } return r; } /* return NULL in case of error. Compute a + b (b_neg = 0) or a - b (b_neg = 1) */ /* XXX: optimize */ static JSBigInt *js_bigint_add(JSContext *ctx, const JSBigInt *a, const JSBigInt *b, int b_neg) { JSBigInt *r; int n1, n2, i; js_limb_t carry, op1, op2, a_sign, b_sign; n2 = max_int(a->len, b->len); n1 = min_int(a->len, b->len); r = js_bigint_new(ctx, n2); if (!r) return NULL; /* XXX: optimize */ /* common part */ carry = b_neg; for(i = 0; i < n1; i++) { op1 = a->tab[i]; op2 = b->tab[i] ^ (-b_neg); ADDC(r->tab[i], carry, op1, op2, carry); } a_sign = -js_bigint_sign(a); b_sign = (-js_bigint_sign(b)) ^ (-b_neg); /* part with sign extension of one operand */ if (a->len > b->len) { for(i = n1; i < n2; i++) { op1 = a->tab[i]; ADDC(r->tab[i], carry, op1, b_sign, carry); } } else if (a->len < b->len) { for(i = n1; i < n2; i++) { op2 = b->tab[i] ^ (-b_neg); ADDC(r->tab[i], carry, a_sign, op2, carry); } } /* part with sign extension for both operands. Extend the result if necessary */ return js_bigint_extend(ctx, r, a_sign + b_sign + carry); } /* XXX: optimize */ static JSBigInt *js_bigint_neg(JSContext *ctx, const JSBigInt *a) { JSBigIntBuf buf; JSBigInt *b; b = js_bigint_set_si(&buf, 0); return js_bigint_add(ctx, b, a, 1); } static JSBigInt *js_bigint_mul(JSContext *ctx, const JSBigInt *a, const JSBigInt *b) { JSBigInt *r; r = js_bigint_new(ctx, a->len + b->len); if (!r) return NULL; js_mp_mul_basecase(r->tab, a->tab, a->len, b->tab, b->len); /* correct the result if negative operands (no overflow is possible) */ if (js_bigint_sign(a)) js_mp_sub(r->tab + a->len, r->tab + a->len, b->tab, b->len, 0); if (js_bigint_sign(b)) js_mp_sub(r->tab + b->len, r->tab + b->len, a->tab, a->len, 0); return js_bigint_normalize(ctx, r); } /* return the division or the remainder. 'b' must be != 0. return NULL in case of exception (division by zero or memory error) */ static JSBigInt *js_bigint_divrem(JSContext *ctx, const JSBigInt *a, const JSBigInt *b, bool is_rem) { JSBigInt *r, *q; js_limb_t *tabb, h; int na, nb, a_sign, b_sign, shift; if (b->len == 1 && b->tab[0] == 0) { JS_ThrowRangeError(ctx, "BigInt division by zero"); return NULL; } a_sign = js_bigint_sign(a); b_sign = js_bigint_sign(b); na = a->len; nb = b->len; r = js_bigint_new(ctx, na + 2); if (!r) return NULL; if (a_sign) { js_mp_neg(r->tab, a->tab, na); } else { memcpy(r->tab, a->tab, na * sizeof(a->tab[0])); } /* normalize */ while (na > 1 && r->tab[na - 1] == 0) na--; tabb = js_malloc(ctx, nb * sizeof(tabb[0])); if (!tabb) { js_free(ctx, r); return NULL; } if (b_sign) { js_mp_neg(tabb, b->tab, nb); } else { memcpy(tabb, b->tab, nb * sizeof(tabb[0])); } /* normalize */ while (nb > 1 && tabb[nb - 1] == 0) nb--; /* trivial case if 'a' is small */ if (na < nb) { js_free(ctx, r); js_free(ctx, tabb); if (is_rem) { /* r = a */ r = js_bigint_new(ctx, a->len); if (!r) return NULL; memcpy(r->tab, a->tab, a->len * sizeof(a->tab[0])); return r; } else { /* q = 0 */ return js_bigint_new_si(ctx, 0); } } /* normalize 'b' */ shift = js_limb_clz(tabb[nb - 1]); if (shift != 0) { js_mp_shl(tabb, tabb, nb, shift); h = js_mp_shl(r->tab, r->tab, na, shift); if (h != 0) r->tab[na++] = h; } q = js_bigint_new(ctx, na - nb + 2); /* one more limb for the sign */ if (!q) { js_free(ctx, r); js_free(ctx, tabb); return NULL; } // js_bigint_dump1(ctx, "a", r->tab, na); // js_bigint_dump1(ctx, "b", tabb, nb); js_mp_divnorm(q->tab, r->tab, na, tabb, nb); js_free(ctx, tabb); if (is_rem) { js_free(ctx, q); if (shift != 0) js_mp_shr(r->tab, r->tab, nb, shift, 0); r->tab[nb++] = 0; if (a_sign) js_mp_neg(r->tab, r->tab, nb); r = js_bigint_normalize1(ctx, r, nb); return r; } else { js_free(ctx, r); q->tab[na - nb + 1] = 0; if (a_sign ^ b_sign) { js_mp_neg(q->tab, q->tab, q->len); } q = js_bigint_normalize(ctx, q); return q; } } /* and, or, xor */ static JSBigInt *js_bigint_logic(JSContext *ctx, const JSBigInt *a, const JSBigInt *b, OPCodeEnum op) { JSBigInt *r; js_limb_t b_sign; int a_len, b_len, i; if (a->len < b->len) { const JSBigInt *tmp; tmp = a; a = b; b = tmp; } /* a_len >= b_len */ a_len = a->len; b_len = b->len; b_sign = -js_bigint_sign(b); r = js_bigint_new(ctx, a_len); if (!r) return NULL; switch(op) { case OP_or: for(i = 0; i < b_len; i++) { r->tab[i] = a->tab[i] | b->tab[i]; } for(i = b_len; i < a_len; i++) { r->tab[i] = a->tab[i] | b_sign; } break; case OP_and: for(i = 0; i < b_len; i++) { r->tab[i] = a->tab[i] & b->tab[i]; } for(i = b_len; i < a_len; i++) { r->tab[i] = a->tab[i] & b_sign; } break; case OP_xor: for(i = 0; i < b_len; i++) { r->tab[i] = a->tab[i] ^ b->tab[i]; } for(i = b_len; i < a_len; i++) { r->tab[i] = a->tab[i] ^ b_sign; } break; default: abort(); } return js_bigint_normalize(ctx, r); } static JSBigInt *js_bigint_not(JSContext *ctx, const JSBigInt *a) { JSBigInt *r; int i; r = js_bigint_new(ctx, a->len); if (!r) return NULL; for(i = 0; i < a->len; i++) { r->tab[i] = ~a->tab[i]; } /* no normalization is needed */ return r; } static JSBigInt *js_bigint_shl(JSContext *ctx, const JSBigInt *a, unsigned int shift1) { int d, i, shift; JSBigInt *r; js_limb_t l; if (a->len == 1 && a->tab[0] == 0) return js_bigint_new_si(ctx, 0); /* zero case */ d = shift1 / JS_LIMB_BITS; shift = shift1 % JS_LIMB_BITS; r = js_bigint_new(ctx, a->len + d); if (!r) return NULL; for(i = 0; i < d; i++) r->tab[i] = 0; if (shift == 0) { for(i = 0; i < a->len; i++) { r->tab[i + d] = a->tab[i]; } } else { l = js_mp_shl(r->tab + d, a->tab, a->len, shift); if (js_bigint_sign(a)) l |= (js_limb_t)(-1) << shift; r = js_bigint_extend(ctx, r, l); } return r; } static JSBigInt *js_bigint_shr(JSContext *ctx, const JSBigInt *a, unsigned int shift1) { int d, i, shift, a_sign, n1; JSBigInt *r; d = shift1 / JS_LIMB_BITS; shift = shift1 % JS_LIMB_BITS; a_sign = js_bigint_sign(a); if (d >= a->len) return js_bigint_new_si(ctx, -a_sign); n1 = a->len - d; r = js_bigint_new(ctx, n1); if (!r) return NULL; if (shift == 0) { for(i = 0; i < n1; i++) { r->tab[i] = a->tab[i + d]; } /* no normalization is needed */ } else { js_mp_shr(r->tab, a->tab + d, n1, shift, -a_sign); r = js_bigint_normalize(ctx, r); } return r; } static JSBigInt *js_bigint_pow(JSContext *ctx, const JSBigInt *a, JSBigInt *b) { uint32_t e; int n_bits, i; JSBigInt *r, *r1; /* b must be >= 0 */ if (js_bigint_sign(b)) { JS_ThrowRangeError(ctx, "BigInt negative exponent"); return NULL; } if (b->len == 1 && b->tab[0] == 0) { /* a^0 = 1 */ return js_bigint_new_si(ctx, 1); } else if (a->len == 1) { js_limb_t v; bool is_neg; v = a->tab[0]; if (v <= 1) return js_bigint_new_si(ctx, v); else if (v == -1) return js_bigint_new_si(ctx, 1 - 2 * (b->tab[0] & 1)); is_neg = (js_slimb_t)v < 0; if (is_neg) v = -v; if ((v & (v - 1)) == 0) { uint64_t e1; int n; /* v = 2^n */ n = JS_LIMB_BITS - 1 - js_limb_clz(v); if (b->len > 1) goto overflow; if (b->tab[0] > INT32_MAX) goto overflow; e = b->tab[0]; e1 = (uint64_t)e * n; if (e1 > JS_BIGINT_MAX_SIZE * JS_LIMB_BITS) goto overflow; e = e1; if (is_neg) is_neg = b->tab[0] & 1; r = js_bigint_new(ctx, (e + JS_LIMB_BITS + 1 - is_neg) / JS_LIMB_BITS); if (!r) return NULL; memset(r->tab, 0, sizeof(r->tab[0]) * r->len); r->tab[e / JS_LIMB_BITS] = (js_limb_t)(1 - 2 * is_neg) << (e % JS_LIMB_BITS); return r; } } if (b->len > 1) goto overflow; if (b->tab[0] > INT32_MAX) goto overflow; e = b->tab[0]; n_bits = 32 - clz32(e); r = js_bigint_new(ctx, a->len); if (!r) return NULL; memcpy(r->tab, a->tab, a->len * sizeof(a->tab[0])); for(i = n_bits - 2; i >= 0; i--) { r1 = js_bigint_mul(ctx, r, r); if (!r1) return NULL; js_free(ctx, r); r = r1; if ((e >> i) & 1) { r1 = js_bigint_mul(ctx, r, a); if (!r1) return NULL; js_free(ctx, r); r = r1; } } return r; overflow: JS_ThrowRangeError(ctx, "BigInt is too large"); return NULL; } /* return (mant, exp) so that abs(a) ~ mant*2^(exp - (limb_bits - 1). a must be != 0. */ static uint64_t js_bigint_get_mant_exp(JSContext *ctx, int *pexp, const JSBigInt *a) { js_limb_t t[4 - JS_LIMB_BITS / 32], carry, v, low_bits; int n1, n2, sgn, shift, i, j, e; uint64_t a1, a0; n2 = 4 - JS_LIMB_BITS / 32; n1 = a->len - n2; sgn = js_bigint_sign(a); /* low_bits != 0 if there are a non zero low bit in abs(a) */ low_bits = 0; carry = sgn; for(i = 0; i < n1; i++) { v = (a->tab[i] ^ (-sgn)) + carry; carry = v < carry; low_bits |= v; } /* get the n2 high limbs of abs(a) */ for(j = 0; j < n2; j++) { i = j + n1; if (i < 0) { v = 0; } else { v = (a->tab[i] ^ (-sgn)) + carry; carry = v < carry; } t[j] = v; } a1 = ((uint64_t)t[2] << 32) | t[1]; a0 = (uint64_t)t[0] << 32; a0 |= (low_bits != 0); /* normalize */ { shift = clz64(a1); if (shift != 0) { a1 = (a1 << shift) | (a0 >> (64 - shift)); a0 <<= shift; } } a1 |= (a0 != 0); /* keep the bits for the final rounding */ /* compute the exponent */ e = a->len * JS_LIMB_BITS - shift - 1; *pexp = e; return a1; } /* shift left with round to nearest, ties to even. n >= 1 */ static uint64_t shr_rndn(uint64_t a, int n) { uint64_t addend = ((a >> n) & 1) + ((1 << (n - 1)) - 1); return (a + addend) >> n; } /* convert to float64 with round to nearest, ties to even. Return +/-infinity if too large. */ static double js_bigint_to_float64(JSContext *ctx, const JSBigInt *a) { int sgn, e; uint64_t mant; if (a->len == 1) { /* fast case, including zero */ return (double)(js_slimb_t)a->tab[0]; } sgn = js_bigint_sign(a); mant = js_bigint_get_mant_exp(ctx, &e, a); if (e > 1023) { /* overflow: return infinity */ mant = 0; e = 1024; } else { mant = (mant >> 1) | (mant & 1); /* avoid overflow in rounding */ mant = shr_rndn(mant, 10); /* rounding can cause an overflow */ if (mant >= ((uint64_t)1 << 53)) { mant >>= 1; e++; } mant &= (((uint64_t)1 << 52) - 1); } return uint64_as_float64(((uint64_t)sgn << 63) | ((uint64_t)(e + 1023) << 52) | mant); } /* return (1, NULL) if not an integer, (2, NULL) if NaN or Infinity, (0, n) if an integer, (0, NULL) in case of memory error */ static JSBigInt *js_bigint_from_float64(JSContext *ctx, int *pres, double a1) { uint64_t a = float64_as_uint64(a1); int sgn, e, shift; uint64_t mant; JSBigIntBuf buf; JSBigInt *r; sgn = a >> 63; e = (a >> 52) & ((1 << 11) - 1); mant = a & (((uint64_t)1 << 52) - 1); if (e == 2047) { /* NaN, Infinity */ *pres = 2; return NULL; } if (e == 0 && mant == 0) { /* zero */ *pres = 0; return js_bigint_new_si(ctx, 0); } e -= 1023; /* 0 < a < 1 : not an integer */ if (e < 0) goto not_an_integer; mant |= (uint64_t)1 << 52; if (e < 52) { shift = 52 - e; /* check that there is no fractional part */ if (mant & (((uint64_t)1 << shift) - 1)) { not_an_integer: *pres = 1; return NULL; } mant >>= shift; e = 0; } else { e -= 52; } if (sgn) mant = -mant; /* the integer is mant*2^e */ r = js_bigint_set_si64(&buf, (int64_t)mant); *pres = 0; return js_bigint_shl(ctx, r, e); } /* return -1, 0, 1 or (2) (unordered) */ static int js_bigint_float64_cmp(JSContext *ctx, const JSBigInt *a, double b) { int b_sign, a_sign, e, f; uint64_t mant, b1, a_mant; b1 = float64_as_uint64(b); b_sign = b1 >> 63; e = (b1 >> 52) & ((1 << 11) - 1); mant = b1 & (((uint64_t)1 << 52) - 1); a_sign = js_bigint_sign(a); if (e == 2047) { if (mant != 0) { /* NaN */ return 2; } else { /* +/- infinity */ return 2 * b_sign - 1; } } else if (e == 0 && mant == 0) { /* b = +/-0 */ if (a->len == 1 && a->tab[0] == 0) return 0; else return 1 - 2 * a_sign; } else if (a->len == 1 && a->tab[0] == 0) { /* a = 0, b != 0 */ return 2 * b_sign - 1; } else if (a_sign != b_sign) { return 1 - 2 * a_sign; } else { e -= 1023; /* Note: handling denormals is not necessary because we compare to integers hence f >= 0 */ /* compute f so that 2^f <= abs(a) < 2^(f+1) */ a_mant = js_bigint_get_mant_exp(ctx, &f, a); if (f != e) { if (f < e) return -1; else return 1; } else { mant = (mant | ((uint64_t)1 << 52)) << 11; /* align to a_mant */ if (a_mant < mant) return 2 * a_sign - 1; else if (a_mant > mant) return 1 - 2 * a_sign; else return 0; } } } /* return -1, 0 or 1 */ static int js_bigint_cmp(JSContext *ctx, const JSBigInt *a, const JSBigInt *b) { int a_sign, b_sign, res, i; a_sign = js_bigint_sign(a); b_sign = js_bigint_sign(b); if (a_sign != b_sign) { res = 1 - 2 * a_sign; } else { /* we assume the numbers are normalized */ if (a->len != b->len) { if (a->len < b->len) res = 2 * a_sign - 1; else res = 1 - 2 * a_sign; } else { res = 0; for(i = a->len -1; i >= 0; i--) { if (a->tab[i] != b->tab[i]) { if (a->tab[i] < b->tab[i]) res = -1; else res = 1; break; } } } } return res; } /* contains 10^i */ static const js_limb_t js_pow_dec[JS_LIMB_DIGITS + 1] = { 1U, 10U, 100U, 1000U, 10000U, 100000U, 1000000U, 10000000U, 100000000U, 1000000000U, }; /* syntax: [-]digits in base radix. Return NULL if memory error. radix = 10, 2, 8 or 16. */ static JSBigInt *js_bigint_from_string(JSContext *ctx, const char *str, int radix) { const char *p = str; size_t n_digits1; int is_neg, n_digits, n_limbs, len, log2_radix, n_bits, i; JSBigInt *r; js_limb_t v, c, h; is_neg = 0; if (*p == '-') { is_neg = 1; p++; } while (*p == '0') p++; n_digits1 = strlen(p); /* the real check for overflox is done js_bigint_new(). Here we just avoid integer overflow */ if (n_digits1 > JS_BIGINT_MAX_SIZE * JS_LIMB_BITS) { JS_ThrowRangeError(ctx, "BigInt is too large to allocate"); return NULL; } n_digits = n_digits1; log2_radix = 32 - clz32(radix - 1); /* ceil(log2(radix)) */ /* compute the maximum number of limbs */ if (radix == 10) { n_bits = (n_digits * 27 + 7) / 8; /* >= ceil(n_digits * log2(10)) */ } else { n_bits = n_digits * log2_radix; } /* we add one extra bit for the sign */ n_limbs = max_int(1, n_bits / JS_LIMB_BITS + 1); r = js_bigint_new(ctx, n_limbs); if (!r) return NULL; if (radix == 10) { int digits_per_limb = JS_LIMB_DIGITS; len = 1; r->tab[0] = 0; for(;;) { /* XXX: slow */ v = 0; for(i = 0; i < digits_per_limb; i++) { c = js_to_digit(*p); if (c >= radix) break; p++; v = v * 10 + c; } if (i == 0) break; if (len == 1 && r->tab[0] == 0) { r->tab[0] = v; } else { h = js_mp_mul1(r->tab, r->tab, len, js_pow_dec[i], v); if (h != 0) { r->tab[len++] = h; } } } /* add one extra limb to have the correct sign*/ if ((r->tab[len - 1] >> (JS_LIMB_BITS - 1)) != 0) r->tab[len++] = 0; r->len = len; } else { unsigned int bit_pos, shift, pos; /* power of two base: no multiplication is needed */ r->len = n_limbs; memset(r->tab, 0, sizeof(r->tab[0]) * n_limbs); for(i = 0; i < n_digits; i++) { c = js_to_digit(p[n_digits - 1 - i]); assert(c < radix); bit_pos = i * log2_radix; shift = bit_pos & (JS_LIMB_BITS - 1); pos = bit_pos / JS_LIMB_BITS; r->tab[pos] |= c << shift; /* if log2_radix does not divide JS_LIMB_BITS, needed an additional op */ if (shift + log2_radix > JS_LIMB_BITS) { r->tab[pos + 1] |= c >> (JS_LIMB_BITS - shift); } } } r = js_bigint_normalize(ctx, r); /* XXX: could do it in place */ if (is_neg) { JSBigInt *r1; r1 = js_bigint_neg(ctx, r); js_free(ctx, r); r = r1; } return r; } /* 2 <= base <= 36 */ static char const digits[36] = { '0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j', 'k','l','m','n','o','p','q','r','s','t', 'u','v','w','x','y','z' }; /* special version going backwards */ /* XXX: use dtoa.c */ static char *js_u64toa(char *q, int64_t n, unsigned int base) { int digit; if (base == 10) { /* division by known base uses multiplication */ do { digit = (uint64_t)n % 10; n = (uint64_t)n / 10; *--q = '0' + digit; } while (n != 0); } else { do { digit = (uint64_t)n % base; n = (uint64_t)n / base; *--q = digits[digit]; } while (n != 0); } return q; } /* len >= 1. 2 <= radix <= 36 */ static char *js_limb_to_a(char *q, js_limb_t n, unsigned int radix, int len) { int digit, i; if (radix == 10) { /* specific case with constant divisor */ /* XXX: optimize */ for(i = 0; i < len; i++) { digit = (js_limb_t)n % 10; n = (js_limb_t)n / 10; *--q = digit + '0'; } } else { for(i = 0; i < len; i++) { digit = (js_limb_t)n % radix; n = (js_limb_t)n / radix; *--q = digits[digit]; } } return q; } #define JS_RADIX_MAX 36 static const uint8_t js_digits_per_limb_table[JS_RADIX_MAX - 1] = { 32,20,16,13,12,11,10,10, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, }; static const js_limb_t js_radix_base_table[JS_RADIX_MAX - 1] = { 0x00000000, 0xcfd41b91, 0x00000000, 0x48c27395, 0x81bf1000, 0x75db9c97, 0x40000000, 0xcfd41b91, 0x3b9aca00, 0x8c8b6d2b, 0x19a10000, 0x309f1021, 0x57f6c100, 0x98c29b81, 0x00000000, 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, 0x94ace180, 0xcaf18367, 0x0b640000, 0x0e8d4a51, 0x1269ae40, 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x81bf1000, }; static JSValue js_bigint_to_string1(JSContext *ctx, JSValueConst val, int radix) { if (JS_VALUE_GET_TAG(val) == JS_TAG_SHORT_BIG_INT) { char buf[66]; int len; len = i64toa_radix(buf, JS_VALUE_GET_SHORT_BIG_INT(val), radix); return js_new_string8_len(ctx, buf, len); } else { JSBigInt *r, *tmp = NULL; char *buf, *q, *buf_end; int is_neg, n_bits, log2_radix, n_digits; bool is_binary_radix; JSValue res; assert(JS_VALUE_GET_TAG(val) == JS_TAG_BIG_INT); r = JS_VALUE_GET_PTR(val); if (r->len == 1 && r->tab[0] == 0) { /* '0' case */ return js_new_string8_len(ctx, "0", 1); } is_binary_radix = ((radix & (radix - 1)) == 0); is_neg = js_bigint_sign(r); if (is_neg) { tmp = js_bigint_neg(ctx, r); if (!tmp) return JS_EXCEPTION; r = tmp; } else if (!is_binary_radix) { /* need to modify 'r' */ tmp = js_bigint_new(ctx, r->len); if (!tmp) return JS_EXCEPTION; memcpy(tmp->tab, r->tab, r->len * sizeof(r->tab[0])); r = tmp; } log2_radix = 31 - clz32(radix); /* floor(log2(radix)) */ n_bits = r->len * JS_LIMB_BITS - js_limb_clz(r->tab[r->len - 1]); /* n_digits is exact only if radix is a power of two. Otherwise it is >= the exact number of digits */ n_digits = (n_bits + log2_radix - 1) / log2_radix; /* XXX: could directly build the JSString */ buf = js_malloc(ctx, n_digits + is_neg + 1); if (!buf) { js_free(ctx, tmp); return JS_EXCEPTION; } q = buf + n_digits + is_neg + 1; *--q = '\0'; buf_end = q; if (!is_binary_radix) { int len; js_limb_t radix_base, v; radix_base = js_radix_base_table[radix - 2]; len = r->len; for(;;) { /* remove leading zero limbs */ while (len > 1 && r->tab[len - 1] == 0) len--; if (len == 1 && r->tab[0] < radix_base) { v = r->tab[0]; if (v != 0) { q = js_u64toa(q, v, radix); } break; } else { v = js_mp_div1(r->tab, r->tab, len, radix_base, 0); q = js_limb_to_a(q, v, radix, js_digits_per_limb_table[radix - 2]); } } } else { int i, shift; unsigned int bit_pos, pos, c; /* radix is a power of two */ for(i = 0; i < n_digits; i++) { bit_pos = i * log2_radix; pos = bit_pos / JS_LIMB_BITS; shift = bit_pos % JS_LIMB_BITS; c = r->tab[pos] >> shift; if ((shift + log2_radix) > JS_LIMB_BITS && (pos + 1) < r->len) { c |= r->tab[pos + 1] << (JS_LIMB_BITS - shift); } c &= (radix - 1); *--q = digits[c]; } } if (is_neg) *--q = '-'; js_free(ctx, tmp); res = js_new_string8_len(ctx, q, buf_end - q); js_free(ctx, buf); return res; } } /* if possible transform a BigInt to short big and free it, otherwise return a normal bigint */ static JSValue JS_CompactBigInt(JSContext *ctx, JSBigInt *p) { JSValue res; if (p->len == 1) { res = __JS_NewShortBigInt(ctx, (js_slimb_t)p->tab[0]); js_free(ctx, p); return res; } else { return JS_MKPTR(JS_TAG_BIG_INT, p); } } #define ATOD_INT_ONLY (1 << 0) /* accept Oo and Ob prefixes in addition to 0x prefix if radix = 0 */ #define ATOD_ACCEPT_BIN_OCT (1 << 2) /* accept O prefix as octal if radix == 0 and properly formed (Annex B) */ #define ATOD_ACCEPT_LEGACY_OCTAL (1 << 4) /* accept _ between digits as a digit separator */ #define ATOD_ACCEPT_UNDERSCORES (1 << 5) /* allow a suffix to override the type */ #define ATOD_ACCEPT_SUFFIX (1 << 6) /* default type */ #define ATOD_TYPE_MASK (3 << 7) #define ATOD_TYPE_FLOAT64 (0 << 7) #define ATOD_TYPE_BIG_INT (1 << 7) /* accept -0x1 */ #define ATOD_ACCEPT_PREFIX_AFTER_SIGN (1 << 10) /* return an exception in case of memory error. Return JS_NAN if invalid syntax */ /* XXX: directly use js_atod() */ static JSValue js_atof(JSContext *ctx, const char *str, const char **pp, int radix, int flags) { const char *p, *p_start; int sep, is_neg; bool is_float, has_legacy_octal; int atod_type = flags & ATOD_TYPE_MASK; char buf1[64], *buf; int i, j, len; bool buf_allocated = false; JSValue val; JSATODTempMem atod_mem; /* optional separator between digits */ sep = (flags & ATOD_ACCEPT_UNDERSCORES) ? '_' : 256; has_legacy_octal = false; p = str; p_start = p; is_neg = 0; if (p[0] == '+') { p++; p_start++; if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN)) goto no_radix_prefix; } else if (p[0] == '-') { p++; p_start++; is_neg = 1; if (!(flags & ATOD_ACCEPT_PREFIX_AFTER_SIGN)) goto no_radix_prefix; } if (p[0] == '0') { if ((p[1] == 'x' || p[1] == 'X') && (radix == 0 || radix == 16)) { p += 2; radix = 16; } else if ((p[1] == 'o' || p[1] == 'O') && radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) { p += 2; radix = 8; } else if ((p[1] == 'b' || p[1] == 'B') && radix == 0 && (flags & ATOD_ACCEPT_BIN_OCT)) { p += 2; radix = 2; } else if ((p[1] >= '0' && p[1] <= '9') && radix == 0 && (flags & ATOD_ACCEPT_LEGACY_OCTAL)) { int i; has_legacy_octal = true; sep = 256; for (i = 1; (p[i] >= '0' && p[i] <= '7'); i++) continue; if (p[i] == '8' || p[i] == '9') goto no_prefix; p += 1; radix = 8; } else { goto no_prefix; } /* there must be a digit after the prefix */ if (js_to_digit((uint8_t)*p) >= radix) goto fail; no_prefix: ; } else { no_radix_prefix: if (!(flags & ATOD_INT_ONLY) && (atod_type == ATOD_TYPE_FLOAT64) && js__strstart(p, "Infinity", &p)) { double d = INF; if (is_neg) d = -d; val = js_float64(d); goto done; } } if (radix == 0) radix = 10; is_float = false; p_start = p; while (js_to_digit((uint8_t)*p) < radix || (*p == sep && (radix != 10 || p != p_start + 1 || p[-1] != '0') && js_to_digit((uint8_t)p[1]) < radix)) { p++; } if (!(flags & ATOD_INT_ONLY) && radix == 10) { if (*p == '.' && (p > p_start || js_to_digit((uint8_t)p[1]) < radix)) { is_float = true; p++; if (*p == sep) goto fail; while (js_to_digit((uint8_t)*p) < radix || (*p == sep && js_to_digit((uint8_t)p[1]) < radix)) p++; } if (p > p_start && (*p == 'e' || *p == 'E')) { const char *p1 = p + 1; is_float = true; if (*p1 == '+') { p1++; } else if (*p1 == '-') { p1++; } if (is_digit((uint8_t)*p1)) { p = p1 + 1; while (is_digit((uint8_t)*p) || (*p == sep && is_digit((uint8_t)p[1]))) p++; } } } if (p == p_start) goto fail; buf = buf1; buf_allocated = false; len = p - p_start; if (unlikely((len + 2) > sizeof(buf1))) { buf = js_malloc_rt(ctx->rt, len + 2); /* no exception raised */ if (!buf) goto mem_error; buf_allocated = true; } /* remove the separators and the radix prefixes */ j = 0; if (is_neg) buf[j++] = '-'; for (i = 0; i < len; i++) { if (p_start[i] != '_') buf[j++] = p_start[i]; } buf[j] = '\0'; if (flags & ATOD_ACCEPT_SUFFIX) { if (*p == 'n') { p++; atod_type = ATOD_TYPE_BIG_INT; } } switch(atod_type) { case ATOD_TYPE_FLOAT64: { double d; d = js_atod(buf, NULL, radix, is_float ? 0 : JS_ATOD_INT_ONLY, &atod_mem); /* return int or float64 */ val = js_number(d); } break; case ATOD_TYPE_BIG_INT: { JSBigInt *r; if (has_legacy_octal || is_float) goto fail; r = js_bigint_from_string(ctx, buf, radix); if (!r) { val = JS_EXCEPTION; goto done; } val = JS_CompactBigInt(ctx, r); } break; default: abort(); } done: if (buf_allocated) js_free_rt(ctx->rt, buf); if (pp) *pp = p; return val; fail: val = JS_NAN; goto done; mem_error: val = JS_ThrowOutOfMemory(ctx); goto done; } typedef enum JSToNumberHintEnum { TON_FLAG_NUMBER, TON_FLAG_NUMERIC, } JSToNumberHintEnum; static JSValue JS_ToNumberHintFree(JSContext *ctx, JSValue val, JSToNumberHintEnum flag) { uint32_t tag; JSValue ret; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_BIG_INT: case JS_TAG_SHORT_BIG_INT: if (flag != TON_FLAG_NUMERIC) { JS_FreeValue(ctx, val); return JS_ThrowTypeError(ctx, "cannot convert BigInt to number"); } ret = val; break; case JS_TAG_FLOAT64: case JS_TAG_INT: case JS_TAG_EXCEPTION: ret = val; break; case JS_TAG_BOOL: case JS_TAG_NULL: ret = js_int32(JS_VALUE_GET_INT(val)); break; case JS_TAG_UNDEFINED: ret = JS_NAN; break; case JS_TAG_OBJECT: val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER); if (JS_IsException(val)) return JS_EXCEPTION; goto redo; case JS_TAG_STRING: { const char *str; const char *p; size_t len; str = JS_ToCStringLen(ctx, &len, val); JS_FreeValue(ctx, val); if (!str) return JS_EXCEPTION; p = str; p += skip_spaces(p); if ((p - str) == len) { ret = JS_NewInt32(ctx, 0); } else { int flags = ATOD_ACCEPT_BIN_OCT; ret = js_atof(ctx, p, &p, 0, flags); if (!JS_IsException(ret)) { p += skip_spaces(p); if ((p - str) != len) { JS_FreeValue(ctx, ret); ret = JS_NAN; } } } JS_FreeCString(ctx, str); } break; case JS_TAG_SYMBOL: JS_FreeValue(ctx, val); return JS_ThrowTypeError(ctx, "cannot convert symbol to number"); default: JS_FreeValue(ctx, val); ret = JS_NAN; break; } return ret; } static JSValue JS_ToNumberFree(JSContext *ctx, JSValue val) { return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMBER); } static JSValue JS_ToNumericFree(JSContext *ctx, JSValue val) { return JS_ToNumberHintFree(ctx, val, TON_FLAG_NUMERIC); } static JSValue JS_ToNumeric(JSContext *ctx, JSValueConst val) { return JS_ToNumericFree(ctx, js_dup(val)); } static __exception int __JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val) { double d; uint32_t tag; val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) goto fail; tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: d = JS_VALUE_GET_INT(val); break; case JS_TAG_FLOAT64: d = JS_VALUE_GET_FLOAT64(val); break; default: abort(); } *pres = d; return 0; fail: *pres = NAN; return -1; } static inline int JS_ToFloat64Free(JSContext *ctx, double *pres, JSValue val) { uint32_t tag; tag = JS_VALUE_GET_TAG(val); if (tag <= JS_TAG_NULL) { *pres = JS_VALUE_GET_INT(val); return 0; } else if (JS_TAG_IS_FLOAT64(tag)) { *pres = JS_VALUE_GET_FLOAT64(val); return 0; } else { return __JS_ToFloat64Free(ctx, pres, val); } } int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val) { return JS_ToFloat64Free(ctx, pres, js_dup(val)); } JSValue JS_ToNumber(JSContext *ctx, JSValueConst val) { return JS_ToNumberFree(ctx, js_dup(val)); } /* same as JS_ToNumber() but return 0 in case of NaN/Undefined */ static __maybe_unused JSValue JS_ToIntegerFree(JSContext *ctx, JSValue val) { uint32_t tag; JSValue ret; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: ret = js_int32(JS_VALUE_GET_INT(val)); break; case JS_TAG_FLOAT64: { double d = JS_VALUE_GET_FLOAT64(val); if (isnan(d)) { ret = js_int32(0); } else { /* convert -0 to +0 */ d = trunc(d) + 0.0; ret = js_number(d); } } break; default: val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) return val; goto redo; } return ret; } /* Note: the integer value is satured to 32 bits */ static int JS_ToInt32SatFree(JSContext *ctx, int *pres, JSValue val) { uint32_t tag; int ret; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: ret = JS_VALUE_GET_INT(val); break; case JS_TAG_EXCEPTION: *pres = 0; return -1; case JS_TAG_FLOAT64: { double d = JS_VALUE_GET_FLOAT64(val); if (isnan(d)) { ret = 0; } else { if (d < INT32_MIN) ret = INT32_MIN; else if (d > INT32_MAX) ret = INT32_MAX; else ret = (int)d; } } break; default: val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) { *pres = 0; return -1; } goto redo; } *pres = ret; return 0; } static int JS_ToInt32Sat(JSContext *ctx, int *pres, JSValueConst val) { return JS_ToInt32SatFree(ctx, pres, js_dup(val)); } static int JS_ToInt32Clamp(JSContext *ctx, int *pres, JSValueConst val, int min, int max, int min_offset) { int res = JS_ToInt32SatFree(ctx, pres, js_dup(val)); if (res == 0) { if (*pres < min) { *pres += min_offset; if (*pres < min) *pres = min; } else { if (*pres > max) *pres = max; } } return res; } static int JS_ToInt64SatFree(JSContext *ctx, int64_t *pres, JSValue val) { uint32_t tag; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: *pres = JS_VALUE_GET_INT(val); return 0; case JS_TAG_EXCEPTION: *pres = 0; return -1; case JS_TAG_FLOAT64: { double d = JS_VALUE_GET_FLOAT64(val); if (isnan(d)) { *pres = 0; } else { if (d < INT64_MIN) *pres = INT64_MIN; else if (d >= 0x1p63) *pres = INT64_MAX; else *pres = (int64_t)d; } } return 0; default: val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) { *pres = 0; return -1; } goto redo; } } int JS_ToInt64Sat(JSContext *ctx, int64_t *pres, JSValueConst val) { return JS_ToInt64SatFree(ctx, pres, js_dup(val)); } int JS_ToInt64Clamp(JSContext *ctx, int64_t *pres, JSValueConst val, int64_t min, int64_t max, int64_t neg_offset) { int res = JS_ToInt64SatFree(ctx, pres, js_dup(val)); if (res == 0) { if (*pres < 0) *pres += neg_offset; if (*pres < min) *pres = min; else if (*pres > max) *pres = max; } return res; } /* Same as JS_ToInt32Free() but with a 64 bit result. Return (<0, 0) in case of exception */ static int JS_ToInt64Free(JSContext *ctx, int64_t *pres, JSValue val) { uint32_t tag; int64_t ret; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: ret = JS_VALUE_GET_INT(val); break; case JS_TAG_FLOAT64: { JSFloat64Union u; double d; int e; d = JS_VALUE_GET_FLOAT64(val); u.d = d; /* we avoid doing fmod(x, 2^64) */ e = (u.u64 >> 52) & 0x7ff; if (likely(e <= (1023 + 62))) { /* fast case */ ret = (int64_t)d; } else if (e <= (1023 + 62 + 53)) { uint64_t v; /* remainder modulo 2^64 */ v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52); ret = v << ((e - 1023) - 52); /* take the sign into account */ if (u.u64 >> 63) if (ret != INT64_MIN) ret = -ret; } else { ret = 0; /* also handles NaN and +inf */ } } break; default: val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) { *pres = 0; return -1; } goto redo; } *pres = ret; return 0; } int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val) { return JS_ToInt64Free(ctx, pres, js_dup(val)); } int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val) { if (JS_IsBigInt(val)) return JS_ToBigInt64(ctx, pres, val); else return JS_ToInt64(ctx, pres, val); } /* return (<0, 0) in case of exception */ static int JS_ToInt32Free(JSContext *ctx, int32_t *pres, JSValue val) { uint32_t tag; int32_t ret; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: ret = JS_VALUE_GET_INT(val); break; case JS_TAG_FLOAT64: { JSFloat64Union u; double d; int e; d = JS_VALUE_GET_FLOAT64(val); u.d = d; /* we avoid doing fmod(x, 2^32) */ e = (u.u64 >> 52) & 0x7ff; if (likely(e <= (1023 + 30))) { /* fast case */ ret = (int32_t)d; } else if (e <= (1023 + 30 + 53)) { uint64_t v; /* remainder modulo 2^32 */ v = (u.u64 & (((uint64_t)1 << 52) - 1)) | ((uint64_t)1 << 52); v = v << ((e - 1023) - 52 + 32); ret = v >> 32; /* take the sign into account */ if (u.u64 >> 63) if (ret != INT32_MIN) ret = -ret; } else { ret = 0; /* also handles NaN and +inf */ } } break; default: val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) { *pres = 0; return -1; } goto redo; } *pres = ret; return 0; } int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val) { return JS_ToInt32Free(ctx, pres, js_dup(val)); } static inline int JS_ToUint32Free(JSContext *ctx, uint32_t *pres, JSValue val) { return JS_ToInt32Free(ctx, (int32_t *)pres, val); } static int JS_ToUint8ClampFree(JSContext *ctx, int32_t *pres, JSValue val) { uint32_t tag; int res; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: case JS_TAG_UNDEFINED: res = JS_VALUE_GET_INT(val); res = max_int(0, min_int(255, res)); break; case JS_TAG_FLOAT64: { double d = JS_VALUE_GET_FLOAT64(val); if (isnan(d)) { res = 0; } else { if (d < 0) res = 0; else if (d > 255) res = 255; else res = lrint(d); } } break; default: val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) { *pres = 0; return -1; } goto redo; } *pres = res; return 0; } static __exception int JS_ToArrayLengthFree(JSContext *ctx, uint32_t *plen, JSValue val, bool is_array_ctor) { uint32_t tag, len; tag = JS_VALUE_GET_TAG(val); switch(tag) { case JS_TAG_INT: case JS_TAG_BOOL: case JS_TAG_NULL: { int v; v = JS_VALUE_GET_INT(val); if (v < 0) goto fail; len = v; } break; default: if (JS_TAG_IS_FLOAT64(tag)) { double d; d = JS_VALUE_GET_FLOAT64(val); if (!(d >= 0 && d <= UINT32_MAX)) goto fail; len = (uint32_t)d; if (len != d) goto fail; } else { uint32_t len1; if (is_array_ctor) { val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) return -1; /* cannot recurse because val is a number */ if (JS_ToArrayLengthFree(ctx, &len, val, true)) return -1; } else { /* legacy behavior: must do the conversion twice and compare */ if (JS_ToUint32(ctx, &len, val)) { JS_FreeValue(ctx, val); return -1; } val = JS_ToNumberFree(ctx, val); if (JS_IsException(val)) return -1; /* cannot recurse because val is a number */ if (JS_ToArrayLengthFree(ctx, &len1, val, false)) return -1; if (len1 != len) { fail: JS_ThrowRangeError(ctx, "invalid array length"); return -1; } } } break; } *plen = len; return 0; } #define MAX_SAFE_INTEGER (((int64_t)1 << 53) - 1) static bool is_safe_integer(double d) { return isfinite(d) && floor(d) == d && fabs(d) <= (double)MAX_SAFE_INTEGER; } int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val) { int64_t v; if (JS_ToInt64Sat(ctx, &v, val)) return -1; if (v < 0 || v > MAX_SAFE_INTEGER) { JS_ThrowRangeError(ctx, "invalid array index"); *plen = 0; return -1; } *plen = v; return 0; } /* convert a value to a length between 0 and MAX_SAFE_INTEGER. return -1 for exception */ static __exception int JS_ToLengthFree(JSContext *ctx, int64_t *plen, JSValue val) { int res = JS_ToInt64Clamp(ctx, plen, val, 0, MAX_SAFE_INTEGER, 0); JS_FreeValue(ctx, val); return res; } /* Note: can return an exception */ static int JS_NumberIsInteger(JSContext *ctx, JSValueConst val) { double d; if (!JS_IsNumber(val)) return false; if (unlikely(JS_ToFloat64(ctx, &d, val))) return -1; return isfinite(d) && floor(d) == d; } static bool JS_NumberIsNegativeOrMinusZero(JSContext *ctx, JSValueConst val) { uint32_t tag; tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_INT: { int v; v = JS_VALUE_GET_INT(val); return (v < 0); } case JS_TAG_FLOAT64: { JSFloat64Union u; u.d = JS_VALUE_GET_FLOAT64(val); return (u.u64 >> 63); } case JS_TAG_SHORT_BIG_INT: return (JS_VALUE_GET_SHORT_BIG_INT(val) < 0); case JS_TAG_BIG_INT: { JSBigInt *p = JS_VALUE_GET_PTR(val); return js_bigint_sign(p); } default: return false; } } static JSValue js_bigint_to_string(JSContext *ctx, JSValueConst val) { return js_bigint_to_string1(ctx, val, 10); } /*---- floating point number to string conversions ----*/ static JSValue js_dtoa2(JSContext *ctx, double d, int radix, int n_digits, int flags) { char static_buf[128], *buf, *tmp_buf; int len, len_max; JSValue res; JSDTOATempMem dtoa_mem; len_max = js_dtoa_max_len(d, radix, n_digits, flags); /* longer buffer may be used if radix != 10 */ if (len_max > sizeof(static_buf) - 1) { tmp_buf = js_malloc(ctx, len_max + 1); if (!tmp_buf) return JS_EXCEPTION; buf = tmp_buf; } else { tmp_buf = NULL; buf = static_buf; } len = js_dtoa(buf, d, radix, n_digits, flags, &dtoa_mem); res = js_new_string8_len(ctx, buf, len); js_free(ctx, tmp_buf); return res; } static JSValue JS_ToStringInternal(JSContext *ctx, JSValueConst val, int flags) { uint32_t tag; char buf[32]; size_t len; tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_STRING: return js_dup(val); case JS_TAG_INT: len = i32toa(buf, JS_VALUE_GET_INT(val)); return js_new_string8_len(ctx, buf, len); case JS_TAG_BOOL: return JS_AtomToString(ctx, JS_VALUE_GET_BOOL(val) ? JS_ATOM_true : JS_ATOM_false); case JS_TAG_NULL: return JS_AtomToString(ctx, JS_ATOM_null); case JS_TAG_UNDEFINED: return JS_AtomToString(ctx, JS_ATOM_undefined); case JS_TAG_EXCEPTION: return JS_EXCEPTION; case JS_TAG_OBJECT: if (flags & JS_TO_STRING_NO_SIDE_EFFECTS) { return js_new_string8(ctx, "{}"); } else { JSValue val1, ret; val1 = JS_ToPrimitive(ctx, val, HINT_STRING); if (JS_IsException(val1)) return val1; ret = JS_ToStringInternal(ctx, val1, flags); JS_FreeValue(ctx, val1); return ret; } break; case JS_TAG_FUNCTION_BYTECODE: return js_new_string8(ctx, "[function bytecode]"); case JS_TAG_SYMBOL: if (flags & JS_TO_STRING_IS_PROPERTY_KEY) { return js_dup(val); } else { return JS_ThrowTypeError(ctx, "cannot convert symbol to string"); } case JS_TAG_FLOAT64: return js_dtoa2(ctx, JS_VALUE_GET_FLOAT64(val), 10, 0, JS_DTOA_FORMAT_FREE); case JS_TAG_SHORT_BIG_INT: case JS_TAG_BIG_INT: return js_bigint_to_string(ctx, val); case JS_TAG_UNINITIALIZED: return js_new_string8(ctx, "[uninitialized]"); default: return js_new_string8(ctx, "[unsupported type]"); } } JSValue JS_ToString(JSContext *ctx, JSValueConst val) { return JS_ToStringInternal(ctx, val, /*flags*/0); } static JSValue JS_ToStringFree(JSContext *ctx, JSValue val) { JSValue ret; ret = JS_ToString(ctx, val); JS_FreeValue(ctx, val); return ret; } static JSValue JS_ToLocaleStringFree(JSContext *ctx, JSValue val) { if (JS_IsUndefined(val) || JS_IsNull(val)) return JS_ToStringFree(ctx, val); return JS_InvokeFree(ctx, val, JS_ATOM_toLocaleString, 0, NULL); } static JSValue JS_ToPropertyKeyInternal(JSContext *ctx, JSValueConst val, int flags) { return JS_ToStringInternal(ctx, val, flags | JS_TO_STRING_IS_PROPERTY_KEY); } JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val) { return JS_ToPropertyKeyInternal(ctx, val, /*flags*/0); } static JSValue JS_ToStringCheckObject(JSContext *ctx, JSValueConst val) { uint32_t tag = JS_VALUE_GET_TAG(val); if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) return JS_ThrowTypeError(ctx, "null or undefined are forbidden"); return JS_ToString(ctx, val); } static JSValue JS_ToQuotedString(JSContext *ctx, JSValueConst val1) { JSValue val; JSString *p; int i; uint32_t c; StringBuffer b_s, *b = &b_s; char buf[16]; val = JS_ToStringCheckObject(ctx, val1); if (JS_IsException(val)) return val; p = JS_VALUE_GET_STRING(val); if (string_buffer_init(ctx, b, p->len + 2)) goto fail; if (string_buffer_putc8(b, '\"')) goto fail; for(i = 0; i < p->len; ) { c = string_getc(p, &i); switch(c) { case '\t': c = 't'; goto quote; case '\r': c = 'r'; goto quote; case '\n': c = 'n'; goto quote; case '\b': c = 'b'; goto quote; case '\f': c = 'f'; goto quote; case '\"': case '\\': quote: if (string_buffer_putc8(b, '\\')) goto fail; if (string_buffer_putc8(b, c)) goto fail; break; default: if (c < 32 || is_surrogate(c)) { snprintf(buf, sizeof(buf), "\\u%04x", c); if (string_buffer_write8(b, (uint8_t*)buf, 6)) goto fail; } else { if (string_buffer_putc(b, c)) goto fail; } break; } } if (string_buffer_putc8(b, '\"')) goto fail; JS_FreeValue(ctx, val); return string_buffer_end(b); fail: JS_FreeValue(ctx, val); string_buffer_free(b); return JS_EXCEPTION; } static __maybe_unused void JS_DumpObjectHeader(JSRuntime *rt) { printf("%14s %4s %4s %14s %10s %s\n", "ADDRESS", "REFS", "SHRF", "PROTO", "CLASS", "PROPS"); } /* for debug only: dump an object without side effect */ static __maybe_unused void JS_DumpObject(JSRuntime *rt, JSObject *p) { uint32_t i; char atom_buf[ATOM_GET_STR_BUF_SIZE]; JSShape *sh; JSShapeProperty *prs; JSProperty *pr; bool is_first = true; /* XXX: should encode atoms with special characters */ sh = p->shape; /* the shape can be NULL while freeing an object */ printf("%14p %4d ", (void *)p, p->header.ref_count); if (sh) { printf("%3d%c %14p ", sh->header.ref_count, " *"[sh->is_hashed], (void *)sh->proto); } else { printf("%3s %14s ", "-", "-"); } printf("%10s ", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), rt->class_array[p->class_id].class_name)); if (p->is_exotic && p->fast_array) { printf("[ "); for(i = 0; i < p->u.array.count; i++) { if (i != 0) printf(", "); switch (p->class_id) { case JS_CLASS_ARRAY: case JS_CLASS_ARGUMENTS: JS_DumpValue(rt, p->u.array.u.values[i]); break; case JS_CLASS_UINT8C_ARRAY: case JS_CLASS_INT8_ARRAY: case JS_CLASS_UINT8_ARRAY: case JS_CLASS_INT16_ARRAY: case JS_CLASS_UINT16_ARRAY: case JS_CLASS_INT32_ARRAY: case JS_CLASS_UINT32_ARRAY: case JS_CLASS_BIG_INT64_ARRAY: case JS_CLASS_BIG_UINT64_ARRAY: case JS_CLASS_FLOAT16_ARRAY: case JS_CLASS_FLOAT32_ARRAY: case JS_CLASS_FLOAT64_ARRAY: { int size = 1 << typed_array_size_log2(p->class_id); const uint8_t *b = p->u.array.u.uint8_ptr + i * size; while (size-- > 0) printf("%02X", *b++); } break; } } printf(" ] "); } if (sh) { printf("{ "); for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { if (prs->atom != JS_ATOM_NULL) { pr = &p->prop[i]; if (!is_first) printf(", "); printf("%s: ", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), prs->atom)); if ((prs->flags & JS_PROP_TMASK) == JS_PROP_GETSET) { printf("[getset %p %p]", (void *)pr->u.getset.getter, (void *)pr->u.getset.setter); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) { printf("[varref %p]", (void *)pr->u.var_ref); } else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_AUTOINIT) { printf("[autoinit %p %d %p]", (void *)js_autoinit_get_realm(pr), js_autoinit_get_id(pr), (void *)pr->u.init.opaque); } else { JS_DumpValue(rt, pr->u.value); } is_first = false; } } printf(" }"); } if (js_class_has_bytecode(p->class_id)) { JSFunctionBytecode *b = p->u.func.function_bytecode; JSVarRef **var_refs; if (b->closure_var_count) { var_refs = p->u.func.var_refs; printf(" Closure:"); for(i = 0; i < b->closure_var_count; i++) { printf(" "); JS_DumpValue(rt, var_refs[i]->value); } if (p->u.func.home_object) { printf(" HomeObject: "); JS_DumpValue(rt, JS_MKPTR(JS_TAG_OBJECT, p->u.func.home_object)); } } } printf("\n"); } static __maybe_unused void JS_DumpGCObject(JSRuntime *rt, JSGCObjectHeader *p) { if (p->gc_obj_type == JS_GC_OBJ_TYPE_JS_OBJECT) { JS_DumpObject(rt, (JSObject *)p); } else { printf("%14p %4d ", (void *)p, p->ref_count); switch(p->gc_obj_type) { case JS_GC_OBJ_TYPE_FUNCTION_BYTECODE: printf("[function bytecode]"); break; case JS_GC_OBJ_TYPE_SHAPE: printf("[shape]"); break; case JS_GC_OBJ_TYPE_VAR_REF: printf("[var_ref]"); break; case JS_GC_OBJ_TYPE_ASYNC_FUNCTION: printf("[async_function]"); break; case JS_GC_OBJ_TYPE_JS_CONTEXT: printf("[js_context]"); break; default: printf("[unknown %d]", p->gc_obj_type); break; } printf("\n"); } } static __maybe_unused void JS_DumpValue(JSRuntime *rt, JSValueConst val) { uint32_t tag = JS_VALUE_GET_NORM_TAG(val); const char *str; switch(tag) { case JS_TAG_INT: printf("%d", JS_VALUE_GET_INT(val)); break; case JS_TAG_BOOL: if (JS_VALUE_GET_BOOL(val)) str = "true"; else str = "false"; goto print_str; case JS_TAG_NULL: str = "null"; goto print_str; case JS_TAG_EXCEPTION: str = "exception"; goto print_str; case JS_TAG_UNINITIALIZED: str = "uninitialized"; goto print_str; case JS_TAG_UNDEFINED: str = "undefined"; print_str: printf("%s", str); break; case JS_TAG_FLOAT64: printf("%.14g", JS_VALUE_GET_FLOAT64(val)); break; case JS_TAG_SHORT_BIG_INT: printf("%" PRId64 "n", (int64_t)JS_VALUE_GET_SHORT_BIG_INT(val)); break; case JS_TAG_BIG_INT: { JSBigInt *p = JS_VALUE_GET_PTR(val); int sgn, i; /* In order to avoid allocations we just dump the limbs */ sgn = js_bigint_sign(p); if (sgn) printf("BigInt.asIntN(%d,", p->len * JS_LIMB_BITS); printf("0x"); for(i = p->len - 1; i >= 0; i--) { if (i != p->len - 1) printf("_"); printf("%08x", p->tab[i]); } printf("n"); if (sgn) printf(")"); } break; case JS_TAG_STRING: { JSString *p; p = JS_VALUE_GET_STRING(val); JS_DumpString(rt, p); } break; case JS_TAG_FUNCTION_BYTECODE: { JSFunctionBytecode *b = JS_VALUE_GET_PTR(val); char buf[ATOM_GET_STR_BUF_SIZE]; if (b->func_name) { printf("[bytecode %s]", JS_AtomGetStrRT(rt, buf, sizeof(buf), b->func_name)); } else { printf("[bytecode (anonymous)]"); } } break; case JS_TAG_OBJECT: { JSObject *p = JS_VALUE_GET_OBJ(val); JSAtom atom = rt->class_array[p->class_id].class_name; char atom_buf[ATOM_GET_STR_BUF_SIZE]; printf("[%s %p]", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), atom), (void *)p); } break; case JS_TAG_SYMBOL: { JSAtomStruct *p = JS_VALUE_GET_PTR(val); char atom_buf[ATOM_GET_STR_BUF_SIZE]; printf("Symbol(%s)", JS_AtomGetStrRT(rt, atom_buf, sizeof(atom_buf), js_get_atom_index(rt, p))); } break; case JS_TAG_MODULE: printf("[module]"); break; default: printf("[unknown tag %d]", tag); break; } } bool JS_IsArray(JSValueConst val) { if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) { JSObject *p = JS_VALUE_GET_OBJ(val); return p->class_id == JS_CLASS_ARRAY; } return false; } /* return -1 if exception (proxy case) or true/false */ static int js_is_array(JSContext *ctx, JSValueConst val) { JSObject *p; if (JS_VALUE_GET_TAG(val) == JS_TAG_OBJECT) { p = JS_VALUE_GET_OBJ(val); if (unlikely(p->class_id == JS_CLASS_PROXY)) return js_proxy_isArray(ctx, val); else return p->class_id == JS_CLASS_ARRAY; } else { return false; } } static double js_math_pow(double a, double b) { if (unlikely(!isfinite(b)) && fabs(a) == 1) { /* not compatible with IEEE 754 */ return NAN; } else { return pow(a, b); } } JSValue JS_NewBigInt64(JSContext *ctx, int64_t v) { if (v >= JS_SHORT_BIG_INT_MIN && v <= JS_SHORT_BIG_INT_MAX) { return __JS_NewShortBigInt(ctx, v); } else { JSBigInt *p; p = js_bigint_new_si64(ctx, v); if (!p) return JS_EXCEPTION; return JS_MKPTR(JS_TAG_BIG_INT, p); } } JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v) { if (v <= JS_SHORT_BIG_INT_MAX) { return __JS_NewShortBigInt(ctx, v); } else { JSBigInt *p; p = js_bigint_new_ui64(ctx, v); if (!p) return JS_EXCEPTION; return JS_MKPTR(JS_TAG_BIG_INT, p); } } /* return NaN if bad bigint literal */ static JSValue JS_StringToBigInt(JSContext *ctx, JSValue val) { const char *str, *p; size_t len; int flags; str = JS_ToCStringLen(ctx, &len, val); JS_FreeValue(ctx, val); if (!str) return JS_EXCEPTION; p = str; p += skip_spaces(p); if ((p - str) == len) { val = JS_NewBigInt64(ctx, 0); } else { flags = ATOD_INT_ONLY | ATOD_ACCEPT_BIN_OCT | ATOD_TYPE_BIG_INT; val = js_atof(ctx, p, &p, 0, flags); p += skip_spaces(p); if (!JS_IsException(val)) { if ((p - str) != len) { JS_FreeValue(ctx, val); val = JS_NAN; } } } JS_FreeCString(ctx, str); return val; } static JSValue JS_StringToBigIntErr(JSContext *ctx, JSValue val) { val = JS_StringToBigInt(ctx, val); if (JS_VALUE_IS_NAN(val)) return JS_ThrowSyntaxError(ctx, "invalid BigInt literal"); return val; } /* JS Numbers are not allowed */ static JSValue JS_ToBigIntFree(JSContext *ctx, JSValue val) { uint32_t tag; redo: tag = JS_VALUE_GET_NORM_TAG(val); switch(tag) { case JS_TAG_SHORT_BIG_INT: case JS_TAG_BIG_INT: break; case JS_TAG_INT: case JS_TAG_NULL: case JS_TAG_UNDEFINED: case JS_TAG_FLOAT64: goto fail; case JS_TAG_BOOL: val = __JS_NewShortBigInt(ctx, JS_VALUE_GET_INT(val)); break; case JS_TAG_STRING: val = JS_StringToBigIntErr(ctx, val); if (JS_IsException(val)) return val; goto redo; case JS_TAG_OBJECT: val = JS_ToPrimitiveFree(ctx, val, HINT_NUMBER); if (JS_IsException(val)) return val; goto redo; default: fail: JS_FreeValue(ctx, val); return JS_ThrowTypeError(ctx, "cannot convert to bigint"); } return val; } static JSValue JS_ToBigInt(JSContext *ctx, JSValueConst val) { return JS_ToBigIntFree(ctx, js_dup(val)); } /* XXX: merge with JS_ToInt64Free with a specific flag */ static int JS_ToBigInt64Free(JSContext *ctx, int64_t *pres, JSValue val) { uint64_t res; val = JS_ToBigIntFree(ctx, val); if (JS_IsException(val)) { *pres = 0; return -1; } if (JS_VALUE_GET_TAG(val) == JS_TAG_SHORT_BIG_INT) { res = JS_VALUE_GET_SHORT_BIG_INT(val); } else { JSBigInt *p = JS_VALUE_GET_PTR(val); /* return the value mod 2^64 */ res = p->tab[0]; if (p->len >= 2) res |= (uint64_t)p->tab[1] << 32; JS_FreeValue(ctx, val); } *pres = res; return 0; } int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val) { return JS_ToBigInt64Free(ctx, pres, js_dup(val)); } int JS_ToBigUint64(JSContext *ctx, uint64_t *pres, JSValueConst val) { return JS_ToBigInt64Free(ctx, (int64_t *)pres, js_dup(val)); } static no_inline __exception int js_unary_arith_slow(JSContext *ctx, JSValue *sp, OPCodeEnum op) { JSValue op1; int v; uint32_t tag; JSBigIntBuf buf1; JSBigInt *p1; op1 = sp[-1]; /* fast path for float64 */ if (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(op1))) goto handle_float64; op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) goto exception; tag = JS_VALUE_GET_TAG(op1); switch(tag) { case JS_TAG_INT: { int64_t v64; v64 = JS_VALUE_GET_INT(op1); switch(op) { case OP_inc: case OP_dec: v = 2 * (op - OP_dec) - 1; v64 += v; break; case OP_plus: break; case OP_neg: if (v64 == 0) { sp[-1] = js_float64(-0.0); return 0; } else { v64 = -v64; } break; default: abort(); } sp[-1] = js_int64(v64); } break; case JS_TAG_SHORT_BIG_INT: { int64_t v; v = JS_VALUE_GET_SHORT_BIG_INT(op1); switch(op) { case OP_plus: JS_ThrowTypeError(ctx, "bigint argument with unary +"); goto exception; case OP_inc: if (v == JS_SHORT_BIG_INT_MAX) goto bigint_slow_case; sp[-1] = __JS_NewShortBigInt(ctx, v + 1); break; case OP_dec: if (v == JS_SHORT_BIG_INT_MIN) goto bigint_slow_case; sp[-1] = __JS_NewShortBigInt(ctx, v - 1); break; case OP_neg: v = JS_VALUE_GET_SHORT_BIG_INT(op1); if (v == JS_SHORT_BIG_INT_MIN) { bigint_slow_case: p1 = js_bigint_set_short(&buf1, op1); goto bigint_slow_case1; } sp[-1] = __JS_NewShortBigInt(ctx, -v); break; default: abort(); } } break; case JS_TAG_BIG_INT: { JSBigInt *r; p1 = JS_VALUE_GET_PTR(op1); bigint_slow_case1: switch(op) { case OP_plus: JS_ThrowTypeError(ctx, "bigint argument with unary +"); JS_FreeValue(ctx, op1); goto exception; case OP_inc: case OP_dec: { JSBigIntBuf buf2; JSBigInt *p2; p2 = js_bigint_set_si(&buf2, 2 * (op - OP_dec) - 1); r = js_bigint_add(ctx, p1, p2, 0); } break; case OP_neg: r = js_bigint_neg(ctx, p1); break; case OP_not: r = js_bigint_not(ctx, p1); break; default: abort(); } JS_FreeValue(ctx, op1); if (!r) goto exception; sp[-1] = JS_CompactBigInt(ctx, r); } break; default: handle_float64: { double d; d = JS_VALUE_GET_FLOAT64(op1); switch(op) { case OP_inc: case OP_dec: v = 2 * (op - OP_dec) - 1; d += v; break; case OP_plus: break; case OP_neg: d = -d; break; default: abort(); } sp[-1] = js_float64(d); } break; } return 0; exception: sp[-1] = JS_UNDEFINED; return -1; } static __exception int js_post_inc_slow(JSContext *ctx, JSValue *sp, OPCodeEnum op) { JSValue op1; /* XXX: allow custom operators */ op1 = sp[-1]; op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { sp[-1] = JS_UNDEFINED; return -1; } sp[-1] = op1; sp[0] = js_dup(op1); return js_unary_arith_slow(ctx, sp + 1, op - OP_post_dec + OP_dec); } static no_inline int js_not_slow(JSContext *ctx, JSValue *sp) { JSValue op1; op1 = sp[-1]; op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) goto exception; if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) { sp[-1] = __JS_NewShortBigInt(ctx, ~JS_VALUE_GET_SHORT_BIG_INT(op1)); } else if (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT) { JSBigInt *r; r = js_bigint_not(ctx, JS_VALUE_GET_PTR(op1)); JS_FreeValue(ctx, op1); if (!r) goto exception; sp[-1] = JS_CompactBigInt(ctx, r); } else { int32_t v1; if (unlikely(JS_ToInt32Free(ctx, &v1, op1))) goto exception; sp[-1] = js_int32(~v1); } return 0; exception: sp[-1] = JS_UNDEFINED; return -1; } static no_inline __exception int js_binary_arith_slow(JSContext *ctx, JSValue *sp, OPCodeEnum op) { JSValue op1, op2; uint32_t tag1, tag2; double d1, d2; op1 = sp[-2]; op2 = sp[-1]; tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); /* fast path for float operations */ if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) { d1 = JS_VALUE_GET_FLOAT64(op1); d2 = JS_VALUE_GET_FLOAT64(op2); goto handle_float64; } /* fast path for short big int operations */ if (tag1 == JS_TAG_SHORT_BIG_INT && tag2 == JS_TAG_SHORT_BIG_INT) { js_slimb_t v1, v2; js_sdlimb_t v; v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); switch(op) { case OP_sub: v = (js_sdlimb_t)v1 - (js_sdlimb_t)v2; break; case OP_mul: v = (js_sdlimb_t)v1 * (js_sdlimb_t)v2; break; case OP_div: if (v2 == 0 || ((js_limb_t)v1 == (js_limb_t)1 << (JS_LIMB_BITS - 1) && v2 == -1)) { goto slow_big_int; } sp[-2] = __JS_NewShortBigInt(ctx, v1 / v2); return 0; case OP_mod: if (v2 == 0 || ((js_limb_t)v1 == (js_limb_t)1 << (JS_LIMB_BITS - 1) && v2 == -1)) { goto slow_big_int; } sp[-2] = __JS_NewShortBigInt(ctx, v1 % v2); return 0; case OP_pow: goto slow_big_int; default: abort(); } if (likely(v >= JS_SHORT_BIG_INT_MIN && v <= JS_SHORT_BIG_INT_MAX)) { sp[-2] = __JS_NewShortBigInt(ctx, v); } else { JSBigInt *r = js_bigint_new_di(ctx, v); if (!r) goto exception; sp[-2] = JS_MKPTR(JS_TAG_BIG_INT, r); } return 0; } op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToNumericFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) { int32_t v1, v2; int64_t v; v1 = JS_VALUE_GET_INT(op1); v2 = JS_VALUE_GET_INT(op2); switch(op) { case OP_sub: v = (int64_t)v1 - (int64_t)v2; break; case OP_mul: v = (int64_t)v1 * (int64_t)v2; if (v == 0 && (v1 | v2) < 0) { sp[-2] = js_float64(-0.0); return 0; } break; case OP_div: sp[-2] = js_number((double)v1 / (double)v2); return 0; case OP_mod: if (v1 < 0 || v2 <= 0) { sp[-2] = js_number(fmod(v1, v2)); return 0; } else { v = (int64_t)v1 % (int64_t)v2; } break; case OP_pow: sp[-2] = js_number(js_math_pow(v1, v2)); return 0; default: abort(); } sp[-2] = js_int64(v); } else if ((tag1 == JS_TAG_SHORT_BIG_INT || tag1 == JS_TAG_BIG_INT) && (tag2 == JS_TAG_SHORT_BIG_INT || tag2 == JS_TAG_BIG_INT)) { JSBigInt *p1, *p2, *r; JSBigIntBuf buf1, buf2; slow_big_int: /* bigint result */ if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) p1 = js_bigint_set_short(&buf1, op1); else p1 = JS_VALUE_GET_PTR(op1); if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) p2 = js_bigint_set_short(&buf2, op2); else p2 = JS_VALUE_GET_PTR(op2); switch(op) { case OP_add: r = js_bigint_add(ctx, p1, p2, 0); break; case OP_sub: r = js_bigint_add(ctx, p1, p2, 1); break; case OP_mul: r = js_bigint_mul(ctx, p1, p2); break; case OP_div: r = js_bigint_divrem(ctx, p1, p2, false); break; case OP_mod: r = js_bigint_divrem(ctx, p1, p2, true); break; case OP_pow: r = js_bigint_pow(ctx, p1, p2); break; default: abort(); } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); if (!r) goto exception; sp[-2] = JS_CompactBigInt(ctx, r); } else { double dr; /* float64 result */ if (JS_ToFloat64Free(ctx, &d1, op1)) { JS_FreeValue(ctx, op2); goto exception; } if (JS_ToFloat64Free(ctx, &d2, op2)) goto exception; handle_float64: switch(op) { case OP_sub: dr = d1 - d2; break; case OP_mul: dr = d1 * d2; break; case OP_div: dr = d1 / d2; break; case OP_mod: dr = fmod(d1, d2); break; case OP_pow: dr = js_math_pow(d1, d2); break; default: abort(); } sp[-2] = js_float64(dr); } return 0; exception: sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } static no_inline __exception int js_add_slow(JSContext *ctx, JSValue *sp) { JSValue op1, op2; uint32_t tag1, tag2; op1 = sp[-2]; op2 = sp[-1]; tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); /* fast path for float64 */ if (tag1 == JS_TAG_FLOAT64 && tag2 == JS_TAG_FLOAT64) { double d1, d2; d1 = JS_VALUE_GET_FLOAT64(op1); d2 = JS_VALUE_GET_FLOAT64(op2); sp[-2] = js_float64(d1 + d2); return 0; } /* fast path for short bigint */ if (tag1 == JS_TAG_SHORT_BIG_INT && tag2 == JS_TAG_SHORT_BIG_INT) { js_slimb_t v1, v2; js_sdlimb_t v; v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); v = (js_sdlimb_t)v1 + (js_sdlimb_t)v2; if (likely(v >= JS_SHORT_BIG_INT_MIN && v <= JS_SHORT_BIG_INT_MAX)) { sp[-2] = __JS_NewShortBigInt(ctx, v); } else { JSBigInt *r = js_bigint_new_di(ctx, v); if (!r) goto exception; sp[-2] = JS_MKPTR(JS_TAG_BIG_INT, r); } return 0; } if (tag1 == JS_TAG_OBJECT || tag2 == JS_TAG_OBJECT) { op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); } if (tag1 == JS_TAG_STRING || tag2 == JS_TAG_STRING) { sp[-2] = JS_ConcatString(ctx, op1, op2); if (JS_IsException(sp[-2])) goto exception; return 0; } op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToNumericFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) { int32_t v1, v2; int64_t v; v1 = JS_VALUE_GET_INT(op1); v2 = JS_VALUE_GET_INT(op2); v = (int64_t)v1 + (int64_t)v2; sp[-2] = js_int64(v); } else if ((tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT) && (tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT)) { JSBigInt *p1, *p2, *r; JSBigIntBuf buf1, buf2; /* bigint result */ if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) p1 = js_bigint_set_short(&buf1, op1); else p1 = JS_VALUE_GET_PTR(op1); if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) p2 = js_bigint_set_short(&buf2, op2); else p2 = JS_VALUE_GET_PTR(op2); r = js_bigint_add(ctx, p1, p2, 0); JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); if (!r) goto exception; sp[-2] = JS_CompactBigInt(ctx, r); } else { double d1, d2; /* float64 result */ if (JS_ToFloat64Free(ctx, &d1, op1)) { JS_FreeValue(ctx, op2); goto exception; } if (JS_ToFloat64Free(ctx, &d2, op2)) goto exception; sp[-2] = js_float64(d1 + d2); } return 0; exception: sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } static no_inline __exception int js_binary_logic_slow(JSContext *ctx, JSValue *sp, OPCodeEnum op) { JSValue op1, op2; uint32_t tag1, tag2; uint32_t v1, v2, r; op1 = sp[-2]; op2 = sp[-1]; tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if (tag1 == JS_TAG_SHORT_BIG_INT && tag2 == JS_TAG_SHORT_BIG_INT) { js_slimb_t v1, v2, v; js_sdlimb_t vd; v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); /* bigint fast path */ switch(op) { case OP_and: v = v1 & v2; break; case OP_or: v = v1 | v2; break; case OP_xor: v = v1 ^ v2; break; case OP_sar: if (v2 > (JS_LIMB_BITS - 1)) { goto slow_big_int; } else if (v2 < 0) { if (v2 < -(JS_LIMB_BITS - 1)) goto slow_big_int; v2 = -v2; goto bigint_shl; } bigint_sar: v = v1 >> v2; break; case OP_shl: if (v2 > (JS_LIMB_BITS - 1)) { goto slow_big_int; } else if (v2 < 0) { if (v2 < -(JS_LIMB_BITS - 1)) goto slow_big_int; v2 = -v2; goto bigint_sar; } bigint_shl: vd = (js_dlimb_t)v1 << v2; if (likely(vd >= JS_SHORT_BIG_INT_MIN && vd <= JS_SHORT_BIG_INT_MAX)) { v = vd; } else { JSBigInt *r = js_bigint_new_di(ctx, vd); if (!r) goto exception; sp[-2] = JS_MKPTR(JS_TAG_BIG_INT, r); return 0; } break; default: abort(); } sp[-2] = __JS_NewShortBigInt(ctx, v); return 0; } op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToNumericFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } tag1 = JS_VALUE_GET_TAG(op1); tag2 = JS_VALUE_GET_TAG(op2); if ((tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT) && (tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT)) { JSBigInt *p1, *p2, *r; JSBigIntBuf buf1, buf2; slow_big_int: if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) p1 = js_bigint_set_short(&buf1, op1); else p1 = JS_VALUE_GET_PTR(op1); if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) p2 = js_bigint_set_short(&buf2, op2); else p2 = JS_VALUE_GET_PTR(op2); switch(op) { case OP_and: case OP_or: case OP_xor: r = js_bigint_logic(ctx, p1, p2, op); break; case OP_shl: case OP_sar: { js_slimb_t shift; shift = js_bigint_get_si_sat(p2); if (shift > INT32_MAX) shift = INT32_MAX; else if (shift < -INT32_MAX) shift = -INT32_MAX; if (op == OP_sar) shift = -shift; if (shift >= 0) r = js_bigint_shl(ctx, p1, shift); else r = js_bigint_shr(ctx, p1, -shift); } break; default: abort(); } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); if (!r) goto exception; sp[-2] = JS_CompactBigInt(ctx, r); } else { if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v1, op1))) { JS_FreeValue(ctx, op2); goto exception; } if (unlikely(JS_ToInt32Free(ctx, (int32_t *)&v2, op2))) goto exception; switch(op) { case OP_shl: r = v1 << (v2 & 0x1f); break; case OP_sar: r = (int)v1 >> (v2 & 0x1f); break; case OP_and: r = v1 & v2; break; case OP_or: r = v1 | v2; break; case OP_xor: r = v1 ^ v2; break; default: abort(); } sp[-2] = js_int32(r); } return 0; exception: sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } /* op1 must be a bigint or int. */ static JSBigInt *JS_ToBigIntBuf(JSContext *ctx, JSBigIntBuf *buf1, JSValue op1) { JSBigInt *p1; switch(JS_VALUE_GET_TAG(op1)) { case JS_TAG_INT: p1 = js_bigint_set_si(buf1, JS_VALUE_GET_INT(op1)); break; case JS_TAG_SHORT_BIG_INT: p1 = js_bigint_set_short(buf1, op1); break; case JS_TAG_BIG_INT: p1 = JS_VALUE_GET_PTR(op1); break; default: abort(); } return p1; } /* op1 and op2 must be numeric types and at least one must be a bigint. No exception is generated. */ static int js_compare_bigint(JSContext *ctx, OPCodeEnum op, JSValue op1, JSValue op2) { int res, val, tag1, tag2; JSBigIntBuf buf1, buf2; JSBigInt *p1, *p2; tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if ((tag1 == JS_TAG_SHORT_BIG_INT || tag1 == JS_TAG_INT) && (tag2 == JS_TAG_SHORT_BIG_INT || tag2 == JS_TAG_INT)) { /* fast path */ js_slimb_t v1, v2; if (tag1 == JS_TAG_INT) v1 = JS_VALUE_GET_INT(op1); else v1 = JS_VALUE_GET_SHORT_BIG_INT(op1); if (tag2 == JS_TAG_INT) v2 = JS_VALUE_GET_INT(op2); else v2 = JS_VALUE_GET_SHORT_BIG_INT(op2); val = (v1 > v2) - (v1 < v2); } else { if (tag1 == JS_TAG_FLOAT64) { p2 = JS_ToBigIntBuf(ctx, &buf2, op2); val = js_bigint_float64_cmp(ctx, p2, JS_VALUE_GET_FLOAT64(op1)); if (val == 2) goto unordered; val = -val; } else if (tag2 == JS_TAG_FLOAT64) { p1 = JS_ToBigIntBuf(ctx, &buf1, op1); val = js_bigint_float64_cmp(ctx, p1, JS_VALUE_GET_FLOAT64(op2)); if (val == 2) { unordered: JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); return false; } } else { p1 = JS_ToBigIntBuf(ctx, &buf1, op1); p2 = JS_ToBigIntBuf(ctx, &buf2, op2); val = js_bigint_cmp(ctx, p1, p2); } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); } switch(op) { case OP_lt: res = val < 0; break; case OP_lte: res = val <= 0; break; case OP_gt: res = val > 0; break; case OP_gte: res = val >= 0; break; case OP_eq: res = val == 0; break; default: abort(); } return res; } static no_inline int js_relational_slow(JSContext *ctx, JSValue *sp, OPCodeEnum op) { JSValue op1, op2; int res; uint32_t tag1, tag2; op1 = sp[-2]; op2 = sp[-1]; tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NUMBER); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NUMBER); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if (tag1 == JS_TAG_STRING && tag2 == JS_TAG_STRING) { JSString *p1, *p2; p1 = JS_VALUE_GET_STRING(op1); p2 = JS_VALUE_GET_STRING(op2); res = js_string_compare(p1, p2); switch(op) { case OP_lt: res = (res < 0); break; case OP_lte: res = (res <= 0); break; case OP_gt: res = (res > 0); break; default: case OP_gte: res = (res >= 0); break; } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); } else if ((tag1 <= JS_TAG_NULL || tag1 == JS_TAG_FLOAT64) && (tag2 <= JS_TAG_NULL || tag2 == JS_TAG_FLOAT64)) { /* fast path for float64/int */ goto float64_compare; } else { if ((((tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT) && tag2 == JS_TAG_STRING) || ((tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT) && tag1 == JS_TAG_STRING))) { if (tag1 == JS_TAG_STRING) { op1 = JS_StringToBigInt(ctx, op1); if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT && JS_VALUE_GET_TAG(op1) != JS_TAG_SHORT_BIG_INT) goto invalid_bigint_string; } if (tag2 == JS_TAG_STRING) { op2 = JS_StringToBigInt(ctx, op2); if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT && JS_VALUE_GET_TAG(op2) != JS_TAG_SHORT_BIG_INT) { invalid_bigint_string: JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); res = false; goto done; } } } else { op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToNumericFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } } tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if (tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT || tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT) { res = js_compare_bigint(ctx, op, op1, op2); } else { double d1, d2; float64_compare: /* can use floating point comparison */ if (tag1 == JS_TAG_FLOAT64) { d1 = JS_VALUE_GET_FLOAT64(op1); } else { d1 = JS_VALUE_GET_INT(op1); } if (tag2 == JS_TAG_FLOAT64) { d2 = JS_VALUE_GET_FLOAT64(op2); } else { d2 = JS_VALUE_GET_INT(op2); } switch(op) { case OP_lt: res = (d1 < d2); /* if NaN return false */ break; case OP_lte: res = (d1 <= d2); /* if NaN return false */ break; case OP_gt: res = (d1 > d2); /* if NaN return false */ break; default: case OP_gte: res = (d1 >= d2); /* if NaN return false */ break; } } } done: sp[-2] = js_bool(res); return 0; exception: sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } static bool tag_is_number(uint32_t tag) { return (tag == JS_TAG_INT || tag == JS_TAG_FLOAT64 || tag == JS_TAG_BIG_INT || tag == JS_TAG_SHORT_BIG_INT); } static no_inline __exception int js_eq_slow(JSContext *ctx, JSValue *sp, bool is_neq) { JSValue op1, op2; int res; uint32_t tag1, tag2; op1 = sp[-2]; op2 = sp[-1]; redo: tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); if (tag_is_number(tag1) && tag_is_number(tag2)) { if (tag1 == JS_TAG_INT && tag2 == JS_TAG_INT) { res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2); } else if ((tag1 == JS_TAG_FLOAT64 && (tag2 == JS_TAG_INT || tag2 == JS_TAG_FLOAT64)) || (tag2 == JS_TAG_FLOAT64 && (tag1 == JS_TAG_INT || tag1 == JS_TAG_FLOAT64))) { double d1, d2; if (tag1 == JS_TAG_FLOAT64) { d1 = JS_VALUE_GET_FLOAT64(op1); } else { d1 = JS_VALUE_GET_INT(op1); } if (tag2 == JS_TAG_FLOAT64) { d2 = JS_VALUE_GET_FLOAT64(op2); } else { d2 = JS_VALUE_GET_INT(op2); } res = (d1 == d2); } else { res = js_compare_bigint(ctx, OP_eq, op1, op2); if (res < 0) goto exception; } } else if (tag1 == tag2) { res = js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT); } else if ((tag1 == JS_TAG_NULL && tag2 == JS_TAG_UNDEFINED) || (tag2 == JS_TAG_NULL && tag1 == JS_TAG_UNDEFINED)) { res = true; } else if ((tag1 == JS_TAG_STRING && tag_is_number(tag2)) || (tag2 == JS_TAG_STRING && tag_is_number(tag1))) { if (tag1 == JS_TAG_BIG_INT || tag1 == JS_TAG_SHORT_BIG_INT || tag2 == JS_TAG_BIG_INT || tag2 == JS_TAG_SHORT_BIG_INT) { if (tag1 == JS_TAG_STRING) { op1 = JS_StringToBigInt(ctx, op1); if (JS_VALUE_GET_TAG(op1) != JS_TAG_BIG_INT && JS_VALUE_GET_TAG(op1) != JS_TAG_SHORT_BIG_INT) goto invalid_bigint_string; } if (tag2 == JS_TAG_STRING) { op2 = JS_StringToBigInt(ctx, op2); if (JS_VALUE_GET_TAG(op2) != JS_TAG_BIG_INT && JS_VALUE_GET_TAG(op2) != JS_TAG_SHORT_BIG_INT ) { invalid_bigint_string: JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); res = false; goto done; } } } else { op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToNumericFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } } res = js_strict_eq(ctx, op1, op2); } else if (tag1 == JS_TAG_BOOL) { op1 = js_int32(JS_VALUE_GET_INT(op1)); goto redo; } else if (tag2 == JS_TAG_BOOL) { op2 = js_int32(JS_VALUE_GET_INT(op2)); goto redo; } else if ((tag1 == JS_TAG_OBJECT && (tag_is_number(tag2) || tag2 == JS_TAG_STRING || tag2 == JS_TAG_SYMBOL)) || (tag2 == JS_TAG_OBJECT && (tag_is_number(tag1) || tag1 == JS_TAG_STRING || tag1 == JS_TAG_SYMBOL))) { op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToPrimitiveFree(ctx, op2, HINT_NONE); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } goto redo; } else { /* IsHTMLDDA object is equivalent to undefined for '==' and '!=' */ if ((JS_IsHTMLDDA(ctx, op1) && (tag2 == JS_TAG_NULL || tag2 == JS_TAG_UNDEFINED)) || (JS_IsHTMLDDA(ctx, op2) && (tag1 == JS_TAG_NULL || tag1 == JS_TAG_UNDEFINED))) { res = true; } else { res = false; } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); } done: sp[-2] = js_bool(res ^ is_neq); return 0; exception: sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } static no_inline int js_shr_slow(JSContext *ctx, JSValue *sp) { JSValue op1, op2; uint32_t v1, v2, r; op1 = sp[-2]; op2 = sp[-1]; op1 = JS_ToNumericFree(ctx, op1); if (JS_IsException(op1)) { JS_FreeValue(ctx, op2); goto exception; } op2 = JS_ToNumericFree(ctx, op2); if (JS_IsException(op2)) { JS_FreeValue(ctx, op1); goto exception; } if (JS_VALUE_GET_TAG(op1) == JS_TAG_BIG_INT || JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT || JS_VALUE_GET_TAG(op2) == JS_TAG_BIG_INT || JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) { JS_ThrowTypeError(ctx, "BigInt operands are forbidden for >>>"); JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); goto exception; } /* cannot give an exception */ JS_ToUint32Free(ctx, &v1, op1); JS_ToUint32Free(ctx, &v2, op2); r = v1 >> (v2 & 0x1f); sp[-2] = js_uint32(r); return 0; exception: sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } static bool js_strict_eq2(JSContext *ctx, JSValue op1, JSValue op2, JSStrictEqModeEnum eq_mode) { bool res; int tag1, tag2; double d1, d2; tag1 = JS_VALUE_GET_NORM_TAG(op1); tag2 = JS_VALUE_GET_NORM_TAG(op2); switch(tag1) { case JS_TAG_BOOL: if (tag1 != tag2) { res = false; } else { res = JS_VALUE_GET_INT(op1) == JS_VALUE_GET_INT(op2); goto done_no_free; } break; case JS_TAG_NULL: case JS_TAG_UNDEFINED: res = (tag1 == tag2); break; case JS_TAG_STRING: { JSString *p1, *p2; if (tag1 != tag2) { res = false; } else { p1 = JS_VALUE_GET_STRING(op1); p2 = JS_VALUE_GET_STRING(op2); res = js_string_eq(p1, p2); } } break; case JS_TAG_SYMBOL: { JSAtomStruct *p1, *p2; if (tag1 != tag2) { res = false; } else { p1 = JS_VALUE_GET_PTR(op1); p2 = JS_VALUE_GET_PTR(op2); res = (p1 == p2); } } break; case JS_TAG_OBJECT: if (tag1 != tag2) res = false; else res = JS_VALUE_GET_OBJ(op1) == JS_VALUE_GET_OBJ(op2); break; case JS_TAG_INT: d1 = JS_VALUE_GET_INT(op1); if (tag2 == JS_TAG_INT) { d2 = JS_VALUE_GET_INT(op2); goto number_test; } else if (tag2 == JS_TAG_FLOAT64) { d2 = JS_VALUE_GET_FLOAT64(op2); goto number_test; } else { res = false; } break; case JS_TAG_FLOAT64: d1 = JS_VALUE_GET_FLOAT64(op1); if (tag2 == JS_TAG_FLOAT64) { d2 = JS_VALUE_GET_FLOAT64(op2); } else if (tag2 == JS_TAG_INT) { d2 = JS_VALUE_GET_INT(op2); } else { res = false; break; } number_test: if (unlikely(eq_mode >= JS_EQ_SAME_VALUE)) { JSFloat64Union u1, u2; /* NaN is not always normalized, so this test is necessary */ if (isnan(d1) || isnan(d2)) { res = isnan(d1) == isnan(d2); } else if (eq_mode == JS_EQ_SAME_VALUE_ZERO) { res = (d1 == d2); /* +0 == -0 */ } else { u1.d = d1; u2.d = d2; res = (u1.u64 == u2.u64); /* +0 != -0 */ } } else { res = (d1 == d2); /* if NaN return false and +0 == -0 */ } goto done_no_free; case JS_TAG_SHORT_BIG_INT: case JS_TAG_BIG_INT: { JSBigIntBuf buf1, buf2; JSBigInt *p1, *p2; if (tag2 != JS_TAG_SHORT_BIG_INT && tag2 != JS_TAG_BIG_INT) { res = false; break; } if (JS_VALUE_GET_TAG(op1) == JS_TAG_SHORT_BIG_INT) p1 = js_bigint_set_short(&buf1, op1); else p1 = JS_VALUE_GET_PTR(op1); if (JS_VALUE_GET_TAG(op2) == JS_TAG_SHORT_BIG_INT) p2 = js_bigint_set_short(&buf2, op2); else p2 = JS_VALUE_GET_PTR(op2); res = (js_bigint_cmp(ctx, p1, p2) == 0); } break; default: res = false; break; } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); done_no_free: return res; } static bool js_strict_eq(JSContext *ctx, JSValue op1, JSValue op2) { return js_strict_eq2(ctx, op1, op2, JS_EQ_STRICT); } static bool js_same_value(JSContext *ctx, JSValueConst op1, JSValueConst op2) { return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_SAME_VALUE); } static bool js_same_value_zero(JSContext *ctx, JSValueConst op1, JSValueConst op2) { return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_SAME_VALUE_ZERO); } static no_inline int js_strict_eq_slow(JSContext *ctx, JSValue *sp, bool is_neq) { bool res; res = js_strict_eq(ctx, sp[-2], sp[-1]); sp[-2] = js_bool(res ^ is_neq); return 0; } static __exception int js_operator_in(JSContext *ctx, JSValue *sp) { JSValue op1, op2; JSAtom atom; int ret; op1 = sp[-2]; op2 = sp[-1]; if (JS_VALUE_GET_TAG(op2) != JS_TAG_OBJECT) { JS_ThrowTypeError(ctx, "invalid 'in' operand"); return -1; } atom = JS_ValueToAtom(ctx, op1); if (unlikely(atom == JS_ATOM_NULL)) return -1; ret = JS_HasProperty(ctx, op2, atom); JS_FreeAtom(ctx, atom); if (ret < 0) return -1; JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); sp[-2] = js_bool(ret); return 0; } static __exception int js_operator_private_in(JSContext *ctx, JSValue *sp) { JSValue op1, op2; int ret; op1 = sp[-2]; /* object */ op2 = sp[-1]; /* field name or method function */ if (JS_VALUE_GET_TAG(op1) != JS_TAG_OBJECT) { JS_ThrowTypeError(ctx, "invalid 'in' operand"); return -1; } if (JS_IsObject(op2)) { /* method: use the brand */ ret = JS_CheckBrand(ctx, op1, op2); if (ret < 0) return -1; } else { JSAtom atom; JSObject *p; JSShapeProperty *prs; JSProperty *pr; /* field */ atom = JS_ValueToAtom(ctx, op2); if (unlikely(atom == JS_ATOM_NULL)) return -1; p = JS_VALUE_GET_OBJ(op1); prs = find_own_property(&pr, p, atom); JS_FreeAtom(ctx, atom); ret = (prs != NULL); } JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); sp[-2] = js_bool(ret); return 0; } static __exception int js_has_unscopable(JSContext *ctx, JSValue obj, JSAtom atom) { JSValue arr, val; int ret; arr = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_unscopables); if (JS_IsException(arr)) return -1; ret = 0; if (JS_IsObject(arr)) { val = JS_GetProperty(ctx, arr, atom); ret = JS_ToBoolFree(ctx, val); } JS_FreeValue(ctx, arr); return ret; } static __exception int js_operator_instanceof(JSContext *ctx, JSValue *sp) { JSValue op1, op2; int ret; op1 = sp[-2]; op2 = sp[-1]; ret = JS_IsInstanceOf(ctx, op1, op2); if (ret < 0) return ret; JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); sp[-2] = js_bool(ret); return 0; } static __exception int js_operator_typeof(JSContext *ctx, JSValue op1) { JSAtom atom; uint32_t tag; tag = JS_VALUE_GET_NORM_TAG(op1); switch(tag) { case JS_TAG_SHORT_BIG_INT: case JS_TAG_BIG_INT: atom = JS_ATOM_bigint; break; case JS_TAG_INT: case JS_TAG_FLOAT64: atom = JS_ATOM_number; break; case JS_TAG_UNDEFINED: atom = JS_ATOM_undefined; break; case JS_TAG_BOOL: atom = JS_ATOM_boolean; break; case JS_TAG_STRING: atom = JS_ATOM_string; break; case JS_TAG_OBJECT: { JSObject *p; p = JS_VALUE_GET_OBJ(op1); if (unlikely(p->is_HTMLDDA)) atom = JS_ATOM_undefined; else if (JS_IsFunction(ctx, op1)) atom = JS_ATOM_function; else goto obj_type; } break; case JS_TAG_NULL: obj_type: atom = JS_ATOM_object; break; case JS_TAG_SYMBOL: atom = JS_ATOM_symbol; break; default: atom = JS_ATOM_unknown; break; } return atom; } static __exception int js_operator_delete(JSContext *ctx, JSValue *sp) { JSValue op1, op2; JSAtom atom; int ret; op1 = sp[-2]; op2 = sp[-1]; atom = JS_ValueToAtom(ctx, op2); if (unlikely(atom == JS_ATOM_NULL)) return -1; ret = JS_DeleteProperty(ctx, op1, atom, JS_PROP_THROW_STRICT); JS_FreeAtom(ctx, atom); if (unlikely(ret < 0)) return -1; JS_FreeValue(ctx, op1); JS_FreeValue(ctx, op2); sp[-2] = js_bool(ret); return 0; } static JSValue js_throw_type_error(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val); if (!b || b->is_strict_mode || !b->has_prototype) { return JS_ThrowTypeError(ctx, "invalid property access"); } return JS_UNDEFINED; } static JSValue js_function_proto_fileName(JSContext *ctx, JSValueConst this_val) { JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val); if (b) { return JS_AtomToString(ctx, b->filename); } return JS_UNDEFINED; } static JSValue js_function_proto_int32(JSContext *ctx, JSValueConst this_val, int magic) { JSFunctionBytecode *b = JS_GetFunctionBytecode(this_val); if (b) { int *field = (int *) ((char *)b + magic); return js_int32(*field); } return JS_UNDEFINED; } static int js_arguments_define_own_property(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags) { JSObject *p; uint32_t idx; p = JS_VALUE_GET_OBJ(this_obj); /* convert to normal array when redefining an existing numeric field */ if (p->fast_array && JS_AtomIsArrayIndex(ctx, &idx, prop) && idx < p->u.array.count) { if (convert_fast_array_to_array(ctx, p)) return -1; } /* run the default define own property */ return JS_DefineProperty(ctx, this_obj, prop, val, getter, setter, flags | JS_PROP_NO_EXOTIC); } static const JSClassExoticMethods js_arguments_exotic_methods = { .define_own_property = js_arguments_define_own_property, }; static JSValue js_build_arguments(JSContext *ctx, int argc, JSValueConst *argv) { JSValue val, *tab; JSProperty *pr; JSObject *p; int i; val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_ARGUMENTS); if (JS_IsException(val)) return val; p = JS_VALUE_GET_OBJ(val); /* add the length field (cannot fail) */ pr = add_property(ctx, p, JS_ATOM_length, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); if (!pr) { JS_FreeValue(ctx, val); return JS_EXCEPTION; } pr->u.value = js_int32(argc); /* initialize the fast array part */ tab = NULL; if (argc > 0) { tab = js_malloc(ctx, sizeof(tab[0]) * argc); if (!tab) { JS_FreeValue(ctx, val); return JS_EXCEPTION; } for(i = 0; i < argc; i++) { tab[i] = js_dup(argv[i]); } } p->u.array.u.values = tab; p->u.array.count = argc; JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator, js_dup(ctx->array_proto_values), JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE); /* add callee property to throw a TypeError in strict mode */ JS_DefineProperty(ctx, val, JS_ATOM_callee, JS_UNDEFINED, ctx->throw_type_error, ctx->throw_type_error, JS_PROP_HAS_GET | JS_PROP_HAS_SET); return val; } #define GLOBAL_VAR_OFFSET 0x40000000 #define ARGUMENT_VAR_OFFSET 0x20000000 /* legacy arguments object: add references to the function arguments */ static JSValue js_build_mapped_arguments(JSContext *ctx, int argc, JSValueConst *argv, JSStackFrame *sf, int arg_count) { JSValue val; JSProperty *pr; JSObject *p; int i; val = JS_NewObjectProtoClass(ctx, ctx->class_proto[JS_CLASS_OBJECT], JS_CLASS_MAPPED_ARGUMENTS); if (JS_IsException(val)) return val; p = JS_VALUE_GET_OBJ(val); /* add the length field (cannot fail) */ pr = add_property(ctx, p, JS_ATOM_length, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); if (!pr) goto fail; pr->u.value = js_int32(argc); for(i = 0; i < arg_count; i++) { JSVarRef *var_ref; var_ref = get_var_ref(ctx, sf, i, true); if (!var_ref) goto fail; pr = add_property(ctx, p, __JS_AtomFromUInt32(i), JS_PROP_C_W_E | JS_PROP_VARREF); if (!pr) { free_var_ref(ctx->rt, var_ref); goto fail; } pr->u.var_ref = var_ref; } /* the arguments not mapped to the arguments of the function can be normal properties */ for(i = arg_count; i < argc; i++) { if (JS_DefinePropertyValueUint32(ctx, val, i, js_dup(argv[i]), JS_PROP_C_W_E) < 0) goto fail; } JS_DefinePropertyValue(ctx, val, JS_ATOM_Symbol_iterator, js_dup(ctx->array_proto_values), JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE); /* callee returns this function in non strict mode */ JS_DefinePropertyValue(ctx, val, JS_ATOM_callee, js_dup(ctx->rt->current_stack_frame->cur_func), JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE); return val; fail: JS_FreeValue(ctx, val); return JS_EXCEPTION; } static JSValue build_for_in_iterator(JSContext *ctx, JSValue obj) { JSObject *p; JSPropertyEnum *tab_atom; int i; JSValue enum_obj, obj1; JSForInIterator *it; uint32_t tag, tab_atom_count; tag = JS_VALUE_GET_TAG(obj); if (tag != JS_TAG_OBJECT && tag != JS_TAG_NULL && tag != JS_TAG_UNDEFINED) { obj = JS_ToObjectFree(ctx, obj); } it = js_malloc(ctx, sizeof(*it)); if (!it) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } enum_obj = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_FOR_IN_ITERATOR); if (JS_IsException(enum_obj)) { js_free(ctx, it); JS_FreeValue(ctx, obj); return JS_EXCEPTION; } it->is_array = false; it->obj = obj; it->idx = 0; p = JS_VALUE_GET_OBJ(enum_obj); p->u.for_in_iterator = it; if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) return enum_obj; /* fast path: assume no enumerable properties in the prototype chain */ obj1 = js_dup(obj); for(;;) { obj1 = JS_GetPrototypeFree(ctx, obj1); if (JS_IsNull(obj1)) break; if (JS_IsException(obj1)) goto fail; if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, JS_VALUE_GET_OBJ(obj1), JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) { JS_FreeValue(ctx, obj1); goto fail; } js_free_prop_enum(ctx, tab_atom, tab_atom_count); if (tab_atom_count != 0) { JS_FreeValue(ctx, obj1); goto slow_path; } /* must check for timeout to avoid infinite loop */ if (js_poll_interrupts(ctx)) { JS_FreeValue(ctx, obj1); goto fail; } } p = JS_VALUE_GET_OBJ(obj); if (p->fast_array) { JSShape *sh; JSShapeProperty *prs; /* check that there are no enumerable normal fields */ sh = p->shape; for(i = 0, prs = get_shape_prop(sh); i < sh->prop_count; i++, prs++) { if (prs->flags & JS_PROP_ENUMERABLE) goto normal_case; } /* for fast arrays, we only store the number of elements */ it->is_array = true; it->array_length = p->u.array.count; } else { normal_case: if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) goto fail; for(i = 0; i < tab_atom_count; i++) { JS_SetPropertyInternal(ctx, enum_obj, tab_atom[i].atom, JS_NULL, 0); } js_free_prop_enum(ctx, tab_atom, tab_atom_count); } return enum_obj; slow_path: /* non enumerable properties hide the enumerables ones in the prototype chain */ obj1 = js_dup(obj); for(;;) { if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, JS_VALUE_GET_OBJ(obj1), JS_GPN_STRING_MASK | JS_GPN_SET_ENUM)) { JS_FreeValue(ctx, obj1); goto fail; } for(i = 0; i < tab_atom_count; i++) { JS_DefinePropertyValue(ctx, enum_obj, tab_atom[i].atom, JS_NULL, (tab_atom[i].is_enumerable ? JS_PROP_ENUMERABLE : 0)); } js_free_prop_enum(ctx, tab_atom, tab_atom_count); obj1 = JS_GetPrototypeFree(ctx, obj1); if (JS_IsNull(obj1)) break; if (JS_IsException(obj1)) goto fail; /* must check for timeout to avoid infinite loop */ if (js_poll_interrupts(ctx)) { JS_FreeValue(ctx, obj1); goto fail; } } return enum_obj; fail: JS_FreeValue(ctx, enum_obj); return JS_EXCEPTION; } /* obj -> enum_obj */ static __exception int js_for_in_start(JSContext *ctx, JSValue *sp) { sp[-1] = build_for_in_iterator(ctx, sp[-1]); if (JS_IsException(sp[-1])) return -1; return 0; } /* enum_obj -> enum_obj value done */ static __exception int js_for_in_next(JSContext *ctx, JSValue *sp) { JSValue enum_obj; JSObject *p; JSAtom prop; JSForInIterator *it; int ret; enum_obj = sp[-1]; /* fail safe */ if (JS_VALUE_GET_TAG(enum_obj) != JS_TAG_OBJECT) goto done; p = JS_VALUE_GET_OBJ(enum_obj); if (p->class_id != JS_CLASS_FOR_IN_ITERATOR) goto done; it = p->u.for_in_iterator; for(;;) { if (it->is_array) { if (it->idx >= it->array_length) goto done; prop = __JS_AtomFromUInt32(it->idx); it->idx++; } else { JSShape *sh = p->shape; JSShapeProperty *prs; if (it->idx >= sh->prop_count) goto done; prs = get_shape_prop(sh) + it->idx; prop = prs->atom; it->idx++; if (prop == JS_ATOM_NULL || !(prs->flags & JS_PROP_ENUMERABLE)) continue; } // check if the property was deleted unless we're dealing with a proxy JSValue obj = it->obj; if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { JSObject *p = JS_VALUE_GET_OBJ(obj); if (p->class_id == JS_CLASS_PROXY) break; } ret = JS_HasProperty(ctx, obj, prop); if (ret < 0) return ret; if (ret) break; } /* return the property */ sp[0] = JS_AtomToValue(ctx, prop); sp[1] = JS_FALSE; return 0; done: /* return the end */ sp[0] = JS_UNDEFINED; sp[1] = JS_TRUE; return 0; } static JSValue JS_GetIterator2(JSContext *ctx, JSValueConst obj, JSValueConst method) { JSValue enum_obj; enum_obj = JS_Call(ctx, method, obj, 0, NULL); if (JS_IsException(enum_obj)) return enum_obj; if (!JS_IsObject(enum_obj)) { JS_FreeValue(ctx, enum_obj); return JS_ThrowTypeErrorNotAnObject(ctx); } return enum_obj; } static JSValue JS_GetIterator(JSContext *ctx, JSValueConst obj, bool is_async) { JSValue method, ret, sync_iter; if (is_async) { method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_asyncIterator); if (JS_IsException(method)) return method; if (JS_IsUndefined(method) || JS_IsNull(method)) { method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator); if (JS_IsException(method)) return method; sync_iter = JS_GetIterator2(ctx, obj, method); JS_FreeValue(ctx, method); if (JS_IsException(sync_iter)) return sync_iter; ret = JS_CreateAsyncFromSyncIterator(ctx, sync_iter); JS_FreeValue(ctx, sync_iter); return ret; } } else { method = JS_GetProperty(ctx, obj, JS_ATOM_Symbol_iterator); if (JS_IsException(method)) return method; } if (!JS_IsFunction(ctx, method)) { JS_FreeValue(ctx, method); return JS_ThrowTypeError(ctx, "value is not iterable"); } ret = JS_GetIterator2(ctx, obj, method); JS_FreeValue(ctx, method); return ret; } /* return *pdone = 2 if the iterator object is not parsed */ static JSValue JS_IteratorNext2(JSContext *ctx, JSValueConst enum_obj, JSValueConst method, int argc, JSValueConst *argv, int *pdone) { JSValue obj; /* fast path for the built-in iterators (avoid creating the intermediate result object) */ if (JS_IsObject(method)) { JSObject *p = JS_VALUE_GET_OBJ(method); if (p->class_id == JS_CLASS_C_FUNCTION && p->u.cfunc.cproto == JS_CFUNC_iterator_next) { JSCFunctionType func; JSValueConst args[1]; /* in case the function expects one argument */ if (argc == 0) { args[0] = JS_UNDEFINED; argv = args; } func = p->u.cfunc.c_function; return func.iterator_next(ctx, enum_obj, argc, argv, pdone, p->u.cfunc.magic); } } obj = JS_Call(ctx, method, enum_obj, argc, argv); if (JS_IsException(obj)) goto fail; if (!JS_IsObject(obj)) { JS_FreeValue(ctx, obj); JS_ThrowTypeError(ctx, "iterator must return an object"); goto fail; } *pdone = 2; return obj; fail: *pdone = false; return JS_EXCEPTION; } static JSValue JS_IteratorNext(JSContext *ctx, JSValueConst enum_obj, JSValueConst method, int argc, JSValueConst *argv, int *pdone) { JSValue obj, value, done_val; int done; obj = JS_IteratorNext2(ctx, enum_obj, method, argc, argv, &done); if (JS_IsException(obj)) goto fail; if (likely(done == 0)) { *pdone = false; return obj; } else if (done != 2) { JS_FreeValue(ctx, obj); *pdone = true; return JS_UNDEFINED; } else { done_val = JS_GetProperty(ctx, obj, JS_ATOM_done); if (JS_IsException(done_val)) goto fail; *pdone = JS_ToBoolFree(ctx, done_val); value = JS_UNDEFINED; if (!*pdone) { value = JS_GetProperty(ctx, obj, JS_ATOM_value); } JS_FreeValue(ctx, obj); return value; } fail: JS_FreeValue(ctx, obj); *pdone = false; return JS_EXCEPTION; } /* return < 0 in case of exception */ static int JS_IteratorClose(JSContext *ctx, JSValueConst enum_obj, bool is_exception_pending) { JSValue method, ret, ex_obj; int res; if (is_exception_pending) { ex_obj = ctx->rt->current_exception; ctx->rt->current_exception = JS_UNINITIALIZED; res = -1; } else { ex_obj = JS_UNDEFINED; res = 0; } method = JS_GetProperty(ctx, enum_obj, JS_ATOM_return); if (JS_IsException(method)) { res = -1; goto done; } if (JS_IsUndefined(method) || JS_IsNull(method)) { goto done; } ret = JS_CallFree(ctx, method, enum_obj, 0, NULL); if (!is_exception_pending) { if (JS_IsException(ret)) { res = -1; } else if (!JS_IsObject(ret)) { JS_ThrowTypeErrorNotAnObject(ctx); res = -1; } } JS_FreeValue(ctx, ret); done: if (is_exception_pending) { JS_Throw(ctx, ex_obj); } return res; } /* obj -> enum_rec (3 slots) */ static __exception int js_for_of_start(JSContext *ctx, JSValue *sp, bool is_async) { JSValue op1, obj, method; op1 = sp[-1]; obj = JS_GetIterator(ctx, op1, is_async); if (JS_IsException(obj)) return -1; JS_FreeValue(ctx, op1); sp[-1] = obj; method = JS_GetProperty(ctx, obj, JS_ATOM_next); if (JS_IsException(method)) return -1; sp[0] = method; return 0; } /* enum_rec [objs] -> enum_rec [objs] value done. There are 'offset' objs. If 'done' is true or in case of exception, 'enum_rec' is set to undefined. If 'done' is true, 'value' is always set to undefined. */ static __exception int js_for_of_next(JSContext *ctx, JSValue *sp, int offset) { JSValue value = JS_UNDEFINED; int done = 1; if (likely(!JS_IsUndefined(sp[offset]))) { value = JS_IteratorNext(ctx, sp[offset], sp[offset + 1], 0, NULL, &done); if (JS_IsException(value)) done = -1; if (done) { /* value is JS_UNDEFINED or JS_EXCEPTION */ /* replace the iteration object with undefined */ JS_FreeValue(ctx, sp[offset]); sp[offset] = JS_UNDEFINED; if (done < 0) { return -1; } else { JS_FreeValue(ctx, value); value = JS_UNDEFINED; } } } sp[0] = value; sp[1] = js_bool(done); return 0; } static JSValue JS_IteratorGetCompleteValue(JSContext *ctx, JSValue obj, int *pdone) { JSValue done_val, value; int done; done_val = JS_GetProperty(ctx, obj, JS_ATOM_done); if (JS_IsException(done_val)) goto fail; done = JS_ToBoolFree(ctx, done_val); value = JS_GetProperty(ctx, obj, JS_ATOM_value); if (JS_IsException(value)) goto fail; *pdone = done; return value; fail: *pdone = false; return JS_EXCEPTION; } static __exception int js_iterator_get_value_done(JSContext *ctx, JSValue *sp) { JSValue obj, value; int done; obj = sp[-1]; if (!JS_IsObject(obj)) { JS_ThrowTypeError(ctx, "iterator must return an object"); return -1; } value = JS_IteratorGetCompleteValue(ctx, obj, &done); if (JS_IsException(value)) return -1; JS_FreeValue(ctx, obj); sp[-1] = value; sp[0] = js_bool(done); return 0; } static JSValue js_create_iterator_result(JSContext *ctx, JSValue val, bool done) { JSValue obj; obj = JS_NewObject(ctx); if (JS_IsException(obj)) { JS_FreeValue(ctx, val); return obj; } if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_value, val, JS_PROP_C_W_E) < 0) { goto fail; } if (JS_DefinePropertyValue(ctx, obj, JS_ATOM_done, js_bool(done), JS_PROP_C_W_E) < 0) { fail: JS_FreeValue(ctx, obj); return JS_EXCEPTION; } return obj; } static JSValue js_array_iterator_next(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int *pdone, int magic); static JSValue js_create_array_iterator(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); static bool js_is_fast_array(JSContext *ctx, JSValue obj) { /* Try and handle fast arrays explicitly */ if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { JSObject *p = JS_VALUE_GET_OBJ(obj); if (p->class_id == JS_CLASS_ARRAY && p->fast_array) { return true; } } return false; } /* Access an Array's internal JSValue array if available */ static bool js_get_fast_array(JSContext *ctx, JSValue obj, JSValue **arrpp, uint32_t *countp) { /* Try and handle fast arrays explicitly */ if (JS_VALUE_GET_TAG(obj) == JS_TAG_OBJECT) { JSObject *p = JS_VALUE_GET_OBJ(obj); if (p->class_id == JS_CLASS_ARRAY && p->fast_array) { *countp = p->u.array.count; *arrpp = p->u.array.u.values; return true; } } return false; } static __exception int js_append_enumerate(JSContext *ctx, JSValue *sp) { JSValue iterator, enumobj, method, value; int is_array_iterator; JSValue *arrp; uint32_t i, count32, pos; if (JS_VALUE_GET_TAG(sp[-2]) != JS_TAG_INT) { JS_ThrowInternalError(ctx, "invalid index for append"); return -1; } pos = JS_VALUE_GET_INT(sp[-2]); /* XXX: further optimisations: - use ctx->array_proto_values? - check if array_iterator_prototype next method is built-in and avoid constructing actual iterator object? - build this into js_for_of_start and use in all `for (x of o)` loops */ iterator = JS_GetProperty(ctx, sp[-1], JS_ATOM_Symbol_iterator); if (JS_IsException(iterator)) return -1; /* Used to squelch a -Wcast-function-type warning. */ JSCFunctionType ft = { .generic_magic = js_create_array_iterator }; is_array_iterator = JS_IsCFunction(ctx, iterator, ft.generic, JS_ITERATOR_KIND_VALUE); JS_FreeValue(ctx, iterator); enumobj = JS_GetIterator(ctx, sp[-1], false); if (JS_IsException(enumobj)) return -1; method = JS_GetProperty(ctx, enumobj, JS_ATOM_next); if (JS_IsException(method)) { JS_FreeValue(ctx, enumobj); return -1; } /* Used to squelch a -Wcast-function-type warning. */ JSCFunctionType ft2 = { .iterator_next = js_array_iterator_next }; if (is_array_iterator && JS_IsCFunction(ctx, method, ft2.generic, 0) && js_get_fast_array(ctx, sp[-1], &arrp, &count32)) { uint32_t len; if (js_get_length32(ctx, &len, sp[-1])) goto exception; /* if len > count32, the elements >= count32 might be read in the prototypes and might have side effects */ if (len != count32) goto general_case; /* Handle fast arrays explicitly */ for (i = 0; i < count32; i++) { if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, js_dup(arrp[i]), JS_PROP_C_W_E) < 0) goto exception; } } else { general_case: for (;;) { int done; value = JS_IteratorNext(ctx, enumobj, method, 0, NULL, &done); if (JS_IsException(value)) goto exception; if (done) { /* value is JS_UNDEFINED */ break; } if (JS_DefinePropertyValueUint32(ctx, sp[-3], pos++, value, JS_PROP_C_W_E) < 0) goto exception; } } /* Note: could raise an error if too many elements */ sp[-2] = js_int32(pos); JS_FreeValue(ctx, enumobj); JS_FreeValue(ctx, method); return 0; exception: JS_IteratorClose(ctx, enumobj, true); JS_FreeValue(ctx, enumobj); JS_FreeValue(ctx, method); return -1; } static __exception int JS_CopyDataProperties(JSContext *ctx, JSValue target, JSValue source, JSValue excluded, bool setprop) { JSPropertyEnum *tab_atom; JSValue val; uint32_t i, tab_atom_count; JSObject *p; JSObject *pexcl = NULL; int ret, gpn_flags; JSPropertyDescriptor desc; bool is_enumerable; if (JS_VALUE_GET_TAG(source) != JS_TAG_OBJECT) return 0; if (JS_VALUE_GET_TAG(excluded) == JS_TAG_OBJECT) pexcl = JS_VALUE_GET_OBJ(excluded); p = JS_VALUE_GET_OBJ(source); gpn_flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY; if (p->is_exotic) { const JSClassExoticMethods *em = ctx->rt->class_array[p->class_id].exotic; /* cannot use JS_GPN_ENUM_ONLY with e.g. proxies because it introduces a visible change */ if (em && em->get_own_property_names) { gpn_flags &= ~JS_GPN_ENUM_ONLY; } } if (JS_GetOwnPropertyNamesInternal(ctx, &tab_atom, &tab_atom_count, p, gpn_flags)) return -1; for (i = 0; i < tab_atom_count; i++) { if (pexcl) { ret = JS_GetOwnPropertyInternal(ctx, NULL, pexcl, tab_atom[i].atom); if (ret) { if (ret < 0) goto exception; continue; } } if (!(gpn_flags & JS_GPN_ENUM_ONLY)) { /* test if the property is enumerable */ ret = JS_GetOwnPropertyInternal(ctx, &desc, p, tab_atom[i].atom); if (ret < 0) goto exception; if (!ret) continue; is_enumerable = (desc.flags & JS_PROP_ENUMERABLE) != 0; js_free_desc(ctx, &desc); if (!is_enumerable) continue; } val = JS_GetProperty(ctx, source, tab_atom[i].atom); if (JS_IsException(val)) goto exception; if (setprop) ret = JS_SetProperty(ctx, target, tab_atom[i].atom, val); else ret = JS_DefinePropertyValue(ctx, target, tab_atom[i].atom, val, JS_PROP_C_W_E); if (ret < 0) goto exception; } js_free_prop_enum(ctx, tab_atom, tab_atom_count); return 0; exception: js_free_prop_enum(ctx, tab_atom, tab_atom_count); return -1; } /* only valid inside C functions */ static JSValueConst JS_GetActiveFunction(JSContext *ctx) { return ctx->rt->current_stack_frame->cur_func; } static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx, bool is_arg) { JSVarRef *var_ref; struct list_head *el; JSValue *pvalue; if (is_arg) pvalue = &sf->arg_buf[var_idx]; else pvalue = &sf->var_buf[var_idx]; list_for_each(el, &sf->var_ref_list) { var_ref = list_entry(el, JSVarRef, header.link); if (var_ref->pvalue == pvalue) { var_ref->header.ref_count++; return var_ref; } } /* create a new one */ var_ref = js_malloc(ctx, sizeof(JSVarRef)); if (!var_ref) return NULL; var_ref->header.ref_count = 1; var_ref->is_detached = false; list_add_tail(&var_ref->header.link, &sf->var_ref_list); var_ref->pvalue = pvalue; var_ref->value = JS_UNDEFINED; return var_ref; } static JSValue js_closure2(JSContext *ctx, JSValue func_obj, JSFunctionBytecode *b, JSVarRef **cur_var_refs, JSStackFrame *sf) { JSObject *p; JSVarRef **var_refs; int i; p = JS_VALUE_GET_OBJ(func_obj); p->u.func.function_bytecode = b; p->u.func.home_object = NULL; p->u.func.var_refs = NULL; if (b->closure_var_count) { var_refs = js_mallocz(ctx, sizeof(var_refs[0]) * b->closure_var_count); if (!var_refs) goto fail; p->u.func.var_refs = var_refs; for(i = 0; i < b->closure_var_count; i++) { JSClosureVar *cv = &b->closure_var[i]; JSVarRef *var_ref; if (cv->is_local) { /* reuse the existing variable reference if it already exists */ var_ref = get_var_ref(ctx, sf, cv->var_idx, cv->is_arg); if (!var_ref) goto fail; } else { var_ref = cur_var_refs[cv->var_idx]; var_ref->header.ref_count++; } var_refs[i] = var_ref; } } return func_obj; fail: /* bfunc is freed when func_obj is freed */ JS_FreeValue(ctx, func_obj); return JS_EXCEPTION; } static JSValue js_instantiate_prototype(JSContext *ctx, JSObject *p, JSAtom atom, void *opaque) { JSValue obj, this_val; int ret; this_val = JS_MKPTR(JS_TAG_OBJECT, p); obj = JS_NewObject(ctx); if (JS_IsException(obj)) return JS_EXCEPTION; ret = JS_DefinePropertyValue(ctx, obj, JS_ATOM_constructor, js_dup(this_val), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE); if (ret < 0) { JS_FreeValue(ctx, obj); return JS_EXCEPTION; } return obj; } static const uint16_t func_kind_to_class_id[] = { [JS_FUNC_NORMAL] = JS_CLASS_BYTECODE_FUNCTION, [JS_FUNC_GENERATOR] = JS_CLASS_GENERATOR_FUNCTION, [JS_FUNC_ASYNC] = JS_CLASS_ASYNC_FUNCTION, [JS_FUNC_ASYNC_GENERATOR] = JS_CLASS_ASYNC_GENERATOR_FUNCTION, }; static JSValue js_closure(JSContext *ctx, JSValue bfunc, JSVarRef **cur_var_refs, JSStackFrame *sf) { JSFunctionBytecode *b; JSValue func_obj; JSAtom name_atom; b = JS_VALUE_GET_PTR(bfunc); func_obj = JS_NewObjectClass(ctx, func_kind_to_class_id[b->func_kind]); if (JS_IsException(func_obj)) { JS_FreeValue(ctx, bfunc); return JS_EXCEPTION; } func_obj = js_closure2(ctx, func_obj, b, cur_var_refs, sf); if (JS_IsException(func_obj)) { /* bfunc has been freed */ goto fail; } name_atom = b->func_name; if (name_atom == JS_ATOM_NULL) name_atom = JS_ATOM_empty_string; js_function_set_properties(ctx, func_obj, name_atom, b->defined_arg_count); if (b->func_kind & JS_FUNC_GENERATOR) { JSValue proto; int proto_class_id; /* generators have a prototype field which is used as prototype for the generator object */ if (b->func_kind == JS_FUNC_ASYNC_GENERATOR) proto_class_id = JS_CLASS_ASYNC_GENERATOR; else proto_class_id = JS_CLASS_GENERATOR; proto = JS_NewObjectProto(ctx, ctx->class_proto[proto_class_id]); if (JS_IsException(proto)) goto fail; JS_DefinePropertyValue(ctx, func_obj, JS_ATOM_prototype, proto, JS_PROP_WRITABLE); } else if (b->has_prototype) { /* add the 'prototype' property: delay instantiation to avoid creating cycles for every javascript function. The prototype object is created on the fly when first accessed */ JS_SetConstructorBit(ctx, func_obj, true); JS_DefineAutoInitProperty(ctx, func_obj, JS_ATOM_prototype, JS_AUTOINIT_ID_PROTOTYPE, NULL, JS_PROP_WRITABLE); } return func_obj; fail: /* bfunc is freed when func_obj is freed */ JS_FreeValue(ctx, func_obj); return JS_EXCEPTION; } #define JS_DEFINE_CLASS_HAS_HERITAGE (1 << 0) static int js_op_define_class(JSContext *ctx, JSValue *sp, JSAtom class_name, int class_flags, JSVarRef **cur_var_refs, JSStackFrame *sf, bool is_computed_name) { JSValue bfunc, parent_class, proto = JS_UNDEFINED; JSValue ctor = JS_UNDEFINED, parent_proto = JS_UNDEFINED; JSFunctionBytecode *b; parent_class = sp[-2]; bfunc = sp[-1]; if (class_flags & JS_DEFINE_CLASS_HAS_HERITAGE) { if (JS_IsNull(parent_class)) { parent_proto = JS_NULL; parent_class = js_dup(ctx->function_proto); } else { if (!JS_IsConstructor(ctx, parent_class)) { JS_ThrowTypeError(ctx, "parent class must be constructor"); goto fail; } parent_proto = JS_GetProperty(ctx, parent_class, JS_ATOM_prototype); if (JS_IsException(parent_proto)) goto fail; if (!JS_IsNull(parent_proto) && !JS_IsObject(parent_proto)) { JS_ThrowTypeError(ctx, "parent prototype must be an object or null"); goto fail; } } } else { /* parent_class is JS_UNDEFINED in this case */ parent_proto = js_dup(ctx->class_proto[JS_CLASS_OBJECT]); parent_class = js_dup(ctx->function_proto); } proto = JS_NewObjectProto(ctx, parent_proto); if (JS_IsException(proto)) goto fail; b = JS_VALUE_GET_PTR(bfunc); assert(b->func_kind == JS_FUNC_NORMAL); ctor = JS_NewObjectProtoClass(ctx, parent_class, JS_CLASS_BYTECODE_FUNCTION); if (JS_IsException(ctor)) goto fail; ctor = js_closure2(ctx, ctor, b, cur_var_refs, sf); bfunc = JS_UNDEFINED; if (JS_IsException(ctor)) goto fail; js_method_set_home_object(ctx, ctor, proto); JS_SetConstructorBit(ctx, ctor, true); JS_DefinePropertyValue(ctx, ctor, JS_ATOM_length, js_int32(b->defined_arg_count), JS_PROP_CONFIGURABLE); if (is_computed_name) { if (JS_DefineObjectNameComputed(ctx, ctor, sp[-3], JS_PROP_CONFIGURABLE) < 0) goto fail; } else { if (JS_DefineObjectName(ctx, ctor, class_name, JS_PROP_CONFIGURABLE) < 0) goto fail; } /* the constructor property must be first. It can be overriden by computed property names */ if (JS_DefinePropertyValue(ctx, proto, JS_ATOM_constructor, js_dup(ctor), JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_THROW) < 0) goto fail; /* set the prototype property */ if (JS_DefinePropertyValue(ctx, ctor, JS_ATOM_prototype, js_dup(proto), JS_PROP_THROW) < 0) goto fail; JS_FreeValue(ctx, parent_proto); JS_FreeValue(ctx, parent_class); sp[-2] = ctor; sp[-1] = proto; return 0; fail: JS_FreeValue(ctx, parent_class); JS_FreeValue(ctx, parent_proto); JS_FreeValue(ctx, bfunc); JS_FreeValue(ctx, proto); JS_FreeValue(ctx, ctor); sp[-2] = JS_UNDEFINED; sp[-1] = JS_UNDEFINED; return -1; } static void close_var_refs(JSRuntime *rt, JSStackFrame *sf) { struct list_head *el, *el1; JSVarRef *var_ref; list_for_each_safe(el, el1, &sf->var_ref_list) { var_ref = list_entry(el, JSVarRef, header.link); var_ref->value = js_dup(*var_ref->pvalue); var_ref->pvalue = &var_ref->value; /* the reference is no longer to a local variable */ var_ref->is_detached = true; add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF); } } static void close_lexical_var(JSContext *ctx, JSStackFrame *sf, int var_idx) { JSValue *pvalue; struct list_head *el, *el1; JSVarRef *var_ref; pvalue = &sf->var_buf[var_idx]; list_for_each_safe(el, el1, &sf->var_ref_list) { var_ref = list_entry(el, JSVarRef, header.link); if (var_ref->pvalue == pvalue) { var_ref->value = js_dup(*var_ref->pvalue); var_ref->pvalue = &var_ref->value; list_del(&var_ref->header.link); /* the reference is no longer to a local variable */ var_ref->is_detached = true; add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF); } } } #define JS_CALL_FLAG_COPY_ARGV (1 << 1) #define JS_CALL_FLAG_GENERATOR (1 << 2) static JSValue js_call_c_function(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags) { JSRuntime *rt = ctx->rt; JSCFunctionType func; JSObject *p; JSStackFrame sf_s, *sf = &sf_s, *prev_sf; JSValue ret_val; JSValueConst *arg_buf; int arg_count, i; JSCFunctionEnum cproto; p = JS_VALUE_GET_OBJ(func_obj); cproto = p->u.cfunc.cproto; arg_count = p->u.cfunc.length; /* better to always check stack overflow */ if (js_check_stack_overflow(rt, sizeof(arg_buf[0]) * arg_count)) return JS_ThrowStackOverflow(ctx); prev_sf = rt->current_stack_frame; sf->prev_frame = prev_sf; rt->current_stack_frame = sf; ctx = p->u.cfunc.realm; /* change the current realm */ sf->is_strict_mode = false; sf->cur_func = unsafe_unconst(func_obj); sf->arg_count = argc; arg_buf = argv; if (unlikely(argc < arg_count)) { /* ensure that at least argc_count arguments are readable */ arg_buf = alloca(sizeof(arg_buf[0]) * arg_count); for(i = 0; i < argc; i++) arg_buf[i] = argv[i]; for(i = argc; i < arg_count; i++) arg_buf[i] = JS_UNDEFINED; sf->arg_count = arg_count; } sf->arg_buf = (JSValue *)arg_buf; func = p->u.cfunc.c_function; switch(cproto) { case JS_CFUNC_constructor: case JS_CFUNC_constructor_or_func: if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) { if (cproto == JS_CFUNC_constructor) { not_a_constructor: ret_val = JS_ThrowTypeError(ctx, "must be called with new"); break; } else { this_obj = JS_UNDEFINED; } } /* here this_obj is new_target */ /* fall thru */ case JS_CFUNC_generic: ret_val = func.generic(ctx, this_obj, argc, arg_buf); break; case JS_CFUNC_constructor_magic: case JS_CFUNC_constructor_or_func_magic: if (!(flags & JS_CALL_FLAG_CONSTRUCTOR)) { if (cproto == JS_CFUNC_constructor_magic) { goto not_a_constructor; } else { this_obj = JS_UNDEFINED; } } /* fall thru */ case JS_CFUNC_generic_magic: ret_val = func.generic_magic(ctx, this_obj, argc, arg_buf, p->u.cfunc.magic); break; case JS_CFUNC_getter: ret_val = func.getter(ctx, this_obj); break; case JS_CFUNC_setter: ret_val = func.setter(ctx, this_obj, arg_buf[0]); break; case JS_CFUNC_getter_magic: ret_val = func.getter_magic(ctx, this_obj, p->u.cfunc.magic); break; case JS_CFUNC_setter_magic: ret_val = func.setter_magic(ctx, this_obj, arg_buf[0], p->u.cfunc.magic); break; case JS_CFUNC_f_f: { double d1; if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) { ret_val = JS_EXCEPTION; break; } ret_val = js_number(func.f_f(d1)); } break; case JS_CFUNC_f_f_f: { double d1, d2; if (unlikely(JS_ToFloat64(ctx, &d1, arg_buf[0]))) { ret_val = JS_EXCEPTION; break; } if (unlikely(JS_ToFloat64(ctx, &d2, arg_buf[1]))) { ret_val = JS_EXCEPTION; break; } ret_val = js_number(func.f_f_f(d1, d2)); } break; case JS_CFUNC_iterator_next: { int done; ret_val = func.iterator_next(ctx, this_obj, argc, arg_buf, &done, p->u.cfunc.magic); if (!JS_IsException(ret_val) && done != 2) { ret_val = js_create_iterator_result(ctx, ret_val, done); } } break; default: abort(); } rt->current_stack_frame = sf->prev_frame; return ret_val; } static JSValue js_call_bound_function(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags) { JSObject *p; JSBoundFunction *bf; JSValueConst *arg_buf, new_target; int arg_count, i; p = JS_VALUE_GET_OBJ(func_obj); bf = p->u.bound_function; arg_count = bf->argc + argc; if (js_check_stack_overflow(ctx->rt, sizeof(JSValue) * arg_count)) return JS_ThrowStackOverflow(ctx); arg_buf = alloca(sizeof(JSValue) * arg_count); for(i = 0; i < bf->argc; i++) { arg_buf[i] = bf->argv[i]; } for(i = 0; i < argc; i++) { arg_buf[bf->argc + i] = argv[i]; } if (flags & JS_CALL_FLAG_CONSTRUCTOR) { new_target = this_obj; if (js_same_value(ctx, func_obj, new_target)) new_target = bf->func_obj; return JS_CallConstructor2(ctx, bf->func_obj, new_target, arg_count, arg_buf); } else { return JS_Call(ctx, bf->func_obj, bf->this_val, arg_count, arg_buf); } } /* argument of OP_special_object */ typedef enum { OP_SPECIAL_OBJECT_ARGUMENTS, OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS, OP_SPECIAL_OBJECT_THIS_FUNC, OP_SPECIAL_OBJECT_NEW_TARGET, OP_SPECIAL_OBJECT_HOME_OBJECT, OP_SPECIAL_OBJECT_VAR_OBJECT, OP_SPECIAL_OBJECT_IMPORT_META, OP_SPECIAL_OBJECT_NULL_PROTO, } OPSpecialObjectEnum; #define FUNC_RET_AWAIT 0 #define FUNC_RET_YIELD 1 #define FUNC_RET_YIELD_STAR 2 #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_* static void dump_single_byte_code(JSContext *ctx, const uint8_t *pc, JSFunctionBytecode *b, int start_pos); static void print_func_name(JSFunctionBytecode *b); #endif static bool needs_backtrace(JSValue exc) { JSObject *p; if (JS_VALUE_GET_TAG(exc) != JS_TAG_OBJECT) return false; p = JS_VALUE_GET_OBJ(exc); if (p->class_id != JS_CLASS_ERROR) return false; return !find_own_property1(p, JS_ATOM_stack); } /* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */ static JSValue JS_CallInternal(JSContext *caller_ctx, JSValueConst func_obj, JSValueConst this_obj, JSValueConst new_target, int argc, JSValueConst *argv, int flags) { JSRuntime *rt = caller_ctx->rt; JSContext *ctx; JSObject *p; JSFunctionBytecode *b; JSStackFrame sf_s, *sf = &sf_s; uint8_t *pc; int opcode, arg_allocated_size, i; JSValue *local_buf, *stack_buf, *var_buf, *arg_buf, *sp, ret_val, *pval; JSVarRef **var_refs; size_t alloca_size; #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STEP #define DUMP_BYTECODE_OR_DONT(pc) \ if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STEP)) dump_single_byte_code(ctx, pc, b, 0); #else #define DUMP_BYTECODE_OR_DONT(pc) #endif #if !DIRECT_DISPATCH #define SWITCH(pc) DUMP_BYTECODE_OR_DONT(pc) switch (opcode = *pc++) #define CASE(op) case op #define DEFAULT default #define BREAK break #else __extension__ static const void * const dispatch_table[256] = { #define DEF(id, size, n_pop, n_push, f) && case_OP_ ## id, #define def(id, size, n_pop, n_push, f) #include "quickjs-opcode.h" [ OP_COUNT ... 255 ] = &&case_default }; #define SWITCH(pc) DUMP_BYTECODE_OR_DONT(pc) __extension__ ({ goto *dispatch_table[opcode = *pc++]; }); #define CASE(op) case_ ## op #define DEFAULT case_default #define BREAK SWITCH(pc) #endif if (js_poll_interrupts(caller_ctx)) return JS_EXCEPTION; if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) { if (flags & JS_CALL_FLAG_GENERATOR) { JSAsyncFunctionState *s = JS_VALUE_GET_PTR(func_obj); /* func_obj get contains a pointer to JSFuncAsyncState */ /* the stack frame is already allocated */ sf = &s->frame; p = JS_VALUE_GET_OBJ(sf->cur_func); b = p->u.func.function_bytecode; ctx = b->realm; var_refs = p->u.func.var_refs; local_buf = arg_buf = sf->arg_buf; var_buf = sf->var_buf; stack_buf = sf->var_buf + b->var_count; sp = sf->cur_sp; sf->cur_sp = NULL; /* cur_sp is NULL if the function is running */ pc = sf->cur_pc; sf->prev_frame = rt->current_stack_frame; rt->current_stack_frame = sf; if (s->throw_flag) goto exception; else goto restart; } else { goto not_a_function; } } p = JS_VALUE_GET_OBJ(func_obj); if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) { JSClassCall *call_func; call_func = rt->class_array[p->class_id].call; if (!call_func) { not_a_function: return JS_ThrowTypeErrorNotAFunction(caller_ctx); } return call_func(caller_ctx, func_obj, this_obj, argc, argv, flags); } b = p->u.func.function_bytecode; if (unlikely(argc < b->arg_count || (flags & JS_CALL_FLAG_COPY_ARGV))) { arg_allocated_size = b->arg_count; } else { arg_allocated_size = 0; } alloca_size = sizeof(JSValue) * (arg_allocated_size + b->var_count + b->stack_size); if (js_check_stack_overflow(rt, alloca_size)) return JS_ThrowStackOverflow(caller_ctx); sf->is_strict_mode = b->is_strict_mode; arg_buf = (JSValue *)argv; sf->arg_count = argc; sf->cur_func = unsafe_unconst(func_obj); init_list_head(&sf->var_ref_list); var_refs = p->u.func.var_refs; local_buf = alloca(alloca_size); if (unlikely(arg_allocated_size)) { int n = min_int(argc, b->arg_count); arg_buf = local_buf; for(i = 0; i < n; i++) arg_buf[i] = js_dup(argv[i]); for(; i < b->arg_count; i++) arg_buf[i] = JS_UNDEFINED; sf->arg_count = b->arg_count; } var_buf = local_buf + arg_allocated_size; sf->var_buf = var_buf; sf->arg_buf = arg_buf; for(i = 0; i < b->var_count; i++) var_buf[i] = JS_UNDEFINED; stack_buf = var_buf + b->var_count; sp = stack_buf; pc = b->byte_code_buf; /* sf->cur_pc must we set to pc before any recursive calls to JS_CallInternal. */ sf->cur_pc = NULL; sf->prev_frame = rt->current_stack_frame; rt->current_stack_frame = sf; ctx = b->realm; /* set the current realm */ #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_STEP if (check_dump_flag(ctx->rt, JS_DUMP_BYTECODE_STEP)) print_func_name(b); #endif restart: for(;;) { int call_argc; JSValue *call_argv; SWITCH(pc) { CASE(OP_push_i32): *sp++ = js_int32(get_u32(pc)); pc += 4; BREAK; CASE(OP_push_bigint_i32): *sp++ = __JS_NewShortBigInt(ctx, (int)get_u32(pc)); pc += 4; BREAK; CASE(OP_push_const): *sp++ = js_dup(b->cpool[get_u32(pc)]); pc += 4; BREAK; CASE(OP_push_minus1): CASE(OP_push_0): CASE(OP_push_1): CASE(OP_push_2): CASE(OP_push_3): CASE(OP_push_4): CASE(OP_push_5): CASE(OP_push_6): CASE(OP_push_7): *sp++ = js_int32(opcode - OP_push_0); BREAK; CASE(OP_push_i8): *sp++ = js_int32(get_i8(pc)); pc += 1; BREAK; CASE(OP_push_i16): *sp++ = js_int32(get_i16(pc)); pc += 2; BREAK; CASE(OP_push_const8): *sp++ = js_dup(b->cpool[*pc++]); BREAK; CASE(OP_fclosure8): *sp++ = js_closure(ctx, js_dup(b->cpool[*pc++]), var_refs, sf); if (unlikely(JS_IsException(sp[-1]))) goto exception; BREAK; CASE(OP_push_empty_string): *sp++ = js_empty_string(rt); BREAK; CASE(OP_get_length): { JSValue val; sf->cur_pc = pc; val = JS_GetProperty(ctx, sp[-1], JS_ATOM_length); if (unlikely(JS_IsException(val))) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = val; } BREAK; CASE(OP_push_atom_value): *sp++ = JS_AtomToValue(ctx, get_u32(pc)); pc += 4; BREAK; CASE(OP_undefined): *sp++ = JS_UNDEFINED; BREAK; CASE(OP_null): *sp++ = JS_NULL; BREAK; CASE(OP_push_this): /* OP_push_this is only called at the start of a function */ { JSValue val; if (!b->is_strict_mode) { uint32_t tag = JS_VALUE_GET_TAG(this_obj); if (likely(tag == JS_TAG_OBJECT)) goto normal_this; if (tag == JS_TAG_NULL || tag == JS_TAG_UNDEFINED) { val = js_dup(ctx->global_obj); } else { val = JS_ToObject(ctx, this_obj); if (JS_IsException(val)) goto exception; } } else { normal_this: val = js_dup(this_obj); } *sp++ = val; } BREAK; CASE(OP_push_false): *sp++ = JS_FALSE; BREAK; CASE(OP_push_true): *sp++ = JS_TRUE; BREAK; CASE(OP_object): *sp++ = JS_NewObject(ctx); if (unlikely(JS_IsException(sp[-1]))) goto exception; BREAK; CASE(OP_special_object): { int arg = *pc++; switch(arg) { case OP_SPECIAL_OBJECT_ARGUMENTS: *sp++ = js_build_arguments(ctx, argc, argv); if (unlikely(JS_IsException(sp[-1]))) goto exception; break; case OP_SPECIAL_OBJECT_MAPPED_ARGUMENTS: *sp++ = js_build_mapped_arguments(ctx, argc, argv, sf, min_int(argc, b->arg_count)); if (unlikely(JS_IsException(sp[-1]))) goto exception; break; case OP_SPECIAL_OBJECT_THIS_FUNC: *sp++ = js_dup(sf->cur_func); break; case OP_SPECIAL_OBJECT_NEW_TARGET: *sp++ = js_dup(new_target); break; case OP_SPECIAL_OBJECT_HOME_OBJECT: { JSObject *p1; p1 = p->u.func.home_object; if (unlikely(!p1)) *sp++ = JS_UNDEFINED; else *sp++ = js_dup(JS_MKPTR(JS_TAG_OBJECT, p1)); } break; case OP_SPECIAL_OBJECT_VAR_OBJECT: *sp++ = JS_NewObjectProto(ctx, JS_NULL); if (unlikely(JS_IsException(sp[-1]))) goto exception; break; case OP_SPECIAL_OBJECT_IMPORT_META: *sp++ = js_import_meta(ctx); if (unlikely(JS_IsException(sp[-1]))) goto exception; break; case OP_SPECIAL_OBJECT_NULL_PROTO: *sp++ = JS_NewObjectProtoClass(ctx, JS_NULL, JS_CLASS_OBJECT); if (unlikely(JS_IsException(sp[-1]))) goto exception; break; default: abort(); } } BREAK; CASE(OP_rest): { int i, n, first = get_u16(pc); pc += 2; i = min_int(first, argc); n = argc - i; *sp++ = js_create_array(ctx, n, &argv[i]); if (unlikely(JS_IsException(sp[-1]))) goto exception; } BREAK; CASE(OP_drop): JS_FreeValue(ctx, sp[-1]); sp--; BREAK; CASE(OP_nip): JS_FreeValue(ctx, sp[-2]); sp[-2] = sp[-1]; sp--; BREAK; CASE(OP_nip1): /* a b c -> b c */ JS_FreeValue(ctx, sp[-3]); sp[-3] = sp[-2]; sp[-2] = sp[-1]; sp--; BREAK; CASE(OP_dup): sp[0] = js_dup(sp[-1]); sp++; BREAK; CASE(OP_dup2): /* a b -> a b a b */ sp[0] = js_dup(sp[-2]); sp[1] = js_dup(sp[-1]); sp += 2; BREAK; CASE(OP_dup3): /* a b c -> a b c a b c */ sp[0] = js_dup(sp[-3]); sp[1] = js_dup(sp[-2]); sp[2] = js_dup(sp[-1]); sp += 3; BREAK; CASE(OP_dup1): /* a b -> a a b */ sp[0] = sp[-1]; sp[-1] = js_dup(sp[-2]); sp++; BREAK; CASE(OP_insert2): /* obj a -> a obj a (dup_x1) */ sp[0] = sp[-1]; sp[-1] = sp[-2]; sp[-2] = js_dup(sp[0]); sp++; BREAK; CASE(OP_insert3): /* obj prop a -> a obj prop a (dup_x2) */ sp[0] = sp[-1]; sp[-1] = sp[-2]; sp[-2] = sp[-3]; sp[-3] = js_dup(sp[0]); sp++; BREAK; CASE(OP_insert4): /* this obj prop a -> a this obj prop a */ sp[0] = sp[-1]; sp[-1] = sp[-2]; sp[-2] = sp[-3]; sp[-3] = sp[-4]; sp[-4] = js_dup(sp[0]); sp++; BREAK; CASE(OP_perm3): /* obj a b -> a obj b (213) */ { JSValue tmp; tmp = sp[-2]; sp[-2] = sp[-3]; sp[-3] = tmp; } BREAK; CASE(OP_rot3l): /* x a b -> a b x (231) */ { JSValue tmp; tmp = sp[-3]; sp[-3] = sp[-2]; sp[-2] = sp[-1]; sp[-1] = tmp; } BREAK; CASE(OP_rot4l): /* x a b c -> a b c x */ { JSValue tmp; tmp = sp[-4]; sp[-4] = sp[-3]; sp[-3] = sp[-2]; sp[-2] = sp[-1]; sp[-1] = tmp; } BREAK; CASE(OP_rot5l): /* x a b c d -> a b c d x */ { JSValue tmp; tmp = sp[-5]; sp[-5] = sp[-4]; sp[-4] = sp[-3]; sp[-3] = sp[-2]; sp[-2] = sp[-1]; sp[-1] = tmp; } BREAK; CASE(OP_rot3r): /* a b x -> x a b (312) */ { JSValue tmp; tmp = sp[-1]; sp[-1] = sp[-2]; sp[-2] = sp[-3]; sp[-3] = tmp; } BREAK; CASE(OP_perm4): /* obj prop a b -> a obj prop b */ { JSValue tmp; tmp = sp[-2]; sp[-2] = sp[-3]; sp[-3] = sp[-4]; sp[-4] = tmp; } BREAK; CASE(OP_perm5): /* this obj prop a b -> a this obj prop b */ { JSValue tmp; tmp = sp[-2]; sp[-2] = sp[-3]; sp[-3] = sp[-4]; sp[-4] = sp[-5]; sp[-5] = tmp; } BREAK; CASE(OP_swap): /* a b -> b a */ { JSValue tmp; tmp = sp[-2]; sp[-2] = sp[-1]; sp[-1] = tmp; } BREAK; CASE(OP_swap2): /* a b c d -> c d a b */ { JSValue tmp1, tmp2; tmp1 = sp[-4]; tmp2 = sp[-3]; sp[-4] = sp[-2]; sp[-3] = sp[-1]; sp[-2] = tmp1; sp[-1] = tmp2; } BREAK; CASE(OP_fclosure): { JSValue bfunc = js_dup(b->cpool[get_u32(pc)]); pc += 4; *sp++ = js_closure(ctx, bfunc, var_refs, sf); if (unlikely(JS_IsException(sp[-1]))) goto exception; } BREAK; CASE(OP_call0): CASE(OP_call1): CASE(OP_call2): CASE(OP_call3): call_argc = opcode - OP_call0; goto has_call_argc; CASE(OP_call): CASE(OP_tail_call): { call_argc = get_u16(pc); pc += 2; goto has_call_argc; has_call_argc: call_argv = sp - call_argc; sf->cur_pc = pc; ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED, JS_UNDEFINED, call_argc, vc(call_argv), 0); if (unlikely(JS_IsException(ret_val))) goto exception; if (opcode == OP_tail_call) goto done; for(i = -1; i < call_argc; i++) JS_FreeValue(ctx, call_argv[i]); sp -= call_argc + 1; *sp++ = ret_val; } BREAK; CASE(OP_call_constructor): { call_argc = get_u16(pc); pc += 2; call_argv = sp - call_argc; sf->cur_pc = pc; ret_val = JS_CallConstructorInternal(ctx, call_argv[-2], call_argv[-1], call_argc, vc(call_argv), 0); if (unlikely(JS_IsException(ret_val))) goto exception; for(i = -2; i < call_argc; i++) JS_FreeValue(ctx, call_argv[i]); sp -= call_argc + 2; *sp++ = ret_val; } BREAK; CASE(OP_call_method): CASE(OP_tail_call_method): { call_argc = get_u16(pc); pc += 2; call_argv = sp - call_argc; sf->cur_pc = pc; ret_val = JS_CallInternal(ctx, call_argv[-1], call_argv[-2], JS_UNDEFINED, call_argc, vc(call_argv), 0); if (unlikely(JS_IsException(ret_val))) goto exception; if (opcode == OP_tail_call_method) goto done; for(i = -2; i < call_argc; i++) JS_FreeValue(ctx, call_argv[i]); sp -= call_argc + 2; *sp++ = ret_val; } BREAK; CASE(OP_array_from): { call_argc = get_u16(pc); pc += 2; call_argv = sp - call_argc; ret_val = JS_NewArrayFrom(ctx, call_argc, call_argv); sp -= call_argc; if (unlikely(JS_IsException(ret_val))) goto exception; *sp++ = ret_val; } BREAK; CASE(OP_apply): { int magic; magic = get_u16(pc); pc += 2; sf->cur_pc = pc; ret_val = js_function_apply(ctx, sp[-3], 2, vc(&sp[-2]), magic); if (unlikely(JS_IsException(ret_val))) goto exception; JS_FreeValue(ctx, sp[-3]); JS_FreeValue(ctx, sp[-2]); JS_FreeValue(ctx, sp[-1]); sp -= 3; *sp++ = ret_val; } BREAK; CASE(OP_return): ret_val = *--sp; goto done; CASE(OP_return_undef): ret_val = JS_UNDEFINED; goto done; CASE(OP_check_ctor_return): /* return true if 'this' should be returned */ if (!JS_IsObject(sp[-1])) { if (!JS_IsUndefined(sp[-1])) { JS_ThrowTypeError(caller_ctx, "derived class constructor must return an object or undefined"); goto exception; } sp[0] = JS_TRUE; } else { sp[0] = JS_FALSE; } sp++; BREAK; CASE(OP_check_ctor): if (JS_IsUndefined(new_target)) { non_ctor_call: JS_ThrowTypeError(ctx, "class constructors must be invoked with 'new'"); goto exception; } BREAK; CASE(OP_init_ctor): { JSValue super, ret; sf->cur_pc = pc; if (JS_IsUndefined(new_target)) goto non_ctor_call; super = JS_GetPrototype(ctx, func_obj); if (JS_IsException(super)) goto exception; ret = JS_CallConstructor2(ctx, super, new_target, argc, argv); JS_FreeValue(ctx, super); if (JS_IsException(ret)) goto exception; *sp++ = ret; } BREAK; CASE(OP_check_brand): { int ret = JS_CheckBrand(ctx, sp[-2], sp[-1]); if (ret < 0) goto exception; if (!ret) { JS_ThrowTypeError(ctx, "invalid brand on object"); goto exception; } } BREAK; CASE(OP_add_brand): if (JS_AddBrand(ctx, sp[-2], sp[-1]) < 0) goto exception; JS_FreeValue(ctx, sp[-2]); JS_FreeValue(ctx, sp[-1]); sp -= 2; BREAK; CASE(OP_throw): JS_Throw(ctx, *--sp); goto exception; CASE(OP_throw_error): #define JS_THROW_VAR_RO 0 #define JS_THROW_VAR_REDECL 1 #define JS_THROW_VAR_UNINITIALIZED 2 #define JS_THROW_ERROR_DELETE_SUPER 3 #define JS_THROW_ERROR_ITERATOR_THROW 4 { JSAtom atom; int type; atom = get_u32(pc); type = pc[4]; pc += 5; if (type == JS_THROW_VAR_RO) JS_ThrowTypeErrorReadOnly(ctx, JS_PROP_THROW, atom); else if (type == JS_THROW_VAR_REDECL) JS_ThrowSyntaxErrorVarRedeclaration(ctx, atom); else if (type == JS_THROW_VAR_UNINITIALIZED) JS_ThrowReferenceErrorUninitialized(ctx, atom); else if (type == JS_THROW_ERROR_DELETE_SUPER) JS_ThrowReferenceError(ctx, "unsupported reference to 'super'"); else if (type == JS_THROW_ERROR_ITERATOR_THROW) JS_ThrowTypeError(ctx, "iterator does not have a throw method"); else JS_ThrowInternalError(ctx, "invalid throw var type %d", type); } goto exception; CASE(OP_eval): { JSValue obj; int scope_idx; call_argc = get_u16(pc); scope_idx = get_u16(pc + 2) - 1; pc += 4; call_argv = sp - call_argc; sf->cur_pc = pc; if (js_same_value(ctx, call_argv[-1], ctx->eval_obj)) { if (call_argc >= 1) obj = call_argv[0]; else obj = JS_UNDEFINED; ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj, JS_EVAL_TYPE_DIRECT, scope_idx); } else { ret_val = JS_CallInternal(ctx, call_argv[-1], JS_UNDEFINED, JS_UNDEFINED, call_argc, vc(call_argv), 0); } if (unlikely(JS_IsException(ret_val))) goto exception; for(i = -1; i < call_argc; i++) JS_FreeValue(ctx, call_argv[i]); sp -= call_argc + 1; *sp++ = ret_val; } BREAK; /* could merge with OP_apply */ CASE(OP_apply_eval): { int scope_idx; uint32_t len; JSValue *tab; JSValue obj; scope_idx = get_u16(pc) - 1; pc += 2; sf->cur_pc = pc; tab = build_arg_list(ctx, &len, sp[-1]); if (!tab) goto exception; if (js_same_value(ctx, sp[-2], ctx->eval_obj)) { if (len >= 1) obj = tab[0]; else obj = JS_UNDEFINED; ret_val = JS_EvalObject(ctx, JS_UNDEFINED, obj, JS_EVAL_TYPE_DIRECT, scope_idx); } else { ret_val = JS_Call(ctx, sp[-2], JS_UNDEFINED, len, vc(tab)); } free_arg_list(ctx, tab, len); if (unlikely(JS_IsException(ret_val))) goto exception; JS_FreeValue(ctx, sp[-2]); JS_FreeValue(ctx, sp[-1]); sp -= 2; *sp++ = ret_val; } BREAK; CASE(OP_regexp): { sp[-2] = js_regexp_constructor_internal(ctx, JS_UNDEFINED, sp[-2], sp[-1]); sp--; } BREAK; CASE(OP_get_super): { JSValue proto; proto = JS_GetPrototype(ctx, sp[-1]); if (JS_IsException(proto)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = proto; } BREAK; CASE(OP_import): { JSValue val; sf->cur_pc = pc; val = js_dynamic_import(ctx, sp[-1]); if (JS_IsException(val)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = val; } BREAK; CASE(OP_check_var): { int ret; JSAtom atom; atom = get_u32(pc); pc += 4; ret = JS_CheckGlobalVar(ctx, atom); if (ret < 0) goto exception; *sp++ = js_bool(ret); } BREAK; CASE(OP_get_var_undef): CASE(OP_get_var): { JSValue val; JSAtom atom; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; val = JS_GetGlobalVar(ctx, atom, opcode - OP_get_var_undef); if (unlikely(JS_IsException(val))) goto exception; *sp++ = val; } BREAK; CASE(OP_put_var): CASE(OP_put_var_init): { int ret; JSAtom atom; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; ret = JS_SetGlobalVar(ctx, atom, sp[-1], opcode - OP_put_var); sp--; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_put_var_strict): { int ret; JSAtom atom; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; /* sp[-2] is JS_TRUE or JS_FALSE */ if (unlikely(!JS_VALUE_GET_INT(sp[-2]))) { JS_ThrowReferenceErrorNotDefined(ctx, atom); goto exception; } ret = JS_SetGlobalVar(ctx, atom, sp[-1], 2); sp -= 2; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_check_define_var): { JSAtom atom; int flags; atom = get_u32(pc); flags = pc[4]; pc += 5; if (JS_CheckDefineGlobalVar(ctx, atom, flags)) goto exception; } BREAK; CASE(OP_define_var): { JSAtom atom; int flags; atom = get_u32(pc); flags = pc[4]; pc += 5; if (JS_DefineGlobalVar(ctx, atom, flags)) goto exception; } BREAK; CASE(OP_define_func): { JSAtom atom; int flags; atom = get_u32(pc); flags = pc[4]; pc += 5; if (JS_DefineGlobalFunction(ctx, atom, sp[-1], flags)) goto exception; JS_FreeValue(ctx, sp[-1]); sp--; } BREAK; CASE(OP_get_loc): { int idx; idx = get_u16(pc); pc += 2; sp[0] = js_dup(var_buf[idx]); sp++; } BREAK; CASE(OP_put_loc): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, &var_buf[idx], sp[-1]); sp--; } BREAK; CASE(OP_set_loc): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, &var_buf[idx], js_dup(sp[-1])); } BREAK; CASE(OP_get_arg): { int idx; idx = get_u16(pc); pc += 2; sp[0] = js_dup(arg_buf[idx]); sp++; } BREAK; CASE(OP_put_arg): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, &arg_buf[idx], sp[-1]); sp--; } BREAK; CASE(OP_set_arg): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, &arg_buf[idx], js_dup(sp[-1])); } BREAK; CASE(OP_get_loc8): *sp++ = js_dup(var_buf[*pc++]); BREAK; CASE(OP_put_loc8): set_value(ctx, &var_buf[*pc++], *--sp); BREAK; CASE(OP_set_loc8): set_value(ctx, &var_buf[*pc++], js_dup(sp[-1])); BREAK; // Observation: get_loc0 and get_loc1 are individually very // frequent opcodes _and_ they are very often paired together, // making them ideal candidates for opcode fusion. CASE(OP_get_loc0_loc1): *sp++ = js_dup(var_buf[0]); *sp++ = js_dup(var_buf[1]); BREAK; CASE(OP_get_loc0): *sp++ = js_dup(var_buf[0]); BREAK; CASE(OP_get_loc1): *sp++ = js_dup(var_buf[1]); BREAK; CASE(OP_get_loc2): *sp++ = js_dup(var_buf[2]); BREAK; CASE(OP_get_loc3): *sp++ = js_dup(var_buf[3]); BREAK; CASE(OP_put_loc0): set_value(ctx, &var_buf[0], *--sp); BREAK; CASE(OP_put_loc1): set_value(ctx, &var_buf[1], *--sp); BREAK; CASE(OP_put_loc2): set_value(ctx, &var_buf[2], *--sp); BREAK; CASE(OP_put_loc3): set_value(ctx, &var_buf[3], *--sp); BREAK; CASE(OP_set_loc0): set_value(ctx, &var_buf[0], js_dup(sp[-1])); BREAK; CASE(OP_set_loc1): set_value(ctx, &var_buf[1], js_dup(sp[-1])); BREAK; CASE(OP_set_loc2): set_value(ctx, &var_buf[2], js_dup(sp[-1])); BREAK; CASE(OP_set_loc3): set_value(ctx, &var_buf[3], js_dup(sp[-1])); BREAK; CASE(OP_get_arg0): *sp++ = js_dup(arg_buf[0]); BREAK; CASE(OP_get_arg1): *sp++ = js_dup(arg_buf[1]); BREAK; CASE(OP_get_arg2): *sp++ = js_dup(arg_buf[2]); BREAK; CASE(OP_get_arg3): *sp++ = js_dup(arg_buf[3]); BREAK; CASE(OP_put_arg0): set_value(ctx, &arg_buf[0], *--sp); BREAK; CASE(OP_put_arg1): set_value(ctx, &arg_buf[1], *--sp); BREAK; CASE(OP_put_arg2): set_value(ctx, &arg_buf[2], *--sp); BREAK; CASE(OP_put_arg3): set_value(ctx, &arg_buf[3], *--sp); BREAK; CASE(OP_set_arg0): set_value(ctx, &arg_buf[0], js_dup(sp[-1])); BREAK; CASE(OP_set_arg1): set_value(ctx, &arg_buf[1], js_dup(sp[-1])); BREAK; CASE(OP_set_arg2): set_value(ctx, &arg_buf[2], js_dup(sp[-1])); BREAK; CASE(OP_set_arg3): set_value(ctx, &arg_buf[3], js_dup(sp[-1])); BREAK; CASE(OP_get_var_ref0): *sp++ = js_dup(*var_refs[0]->pvalue); BREAK; CASE(OP_get_var_ref1): *sp++ = js_dup(*var_refs[1]->pvalue); BREAK; CASE(OP_get_var_ref2): *sp++ = js_dup(*var_refs[2]->pvalue); BREAK; CASE(OP_get_var_ref3): *sp++ = js_dup(*var_refs[3]->pvalue); BREAK; CASE(OP_put_var_ref0): set_value(ctx, var_refs[0]->pvalue, *--sp); BREAK; CASE(OP_put_var_ref1): set_value(ctx, var_refs[1]->pvalue, *--sp); BREAK; CASE(OP_put_var_ref2): set_value(ctx, var_refs[2]->pvalue, *--sp); BREAK; CASE(OP_put_var_ref3): set_value(ctx, var_refs[3]->pvalue, *--sp); BREAK; CASE(OP_set_var_ref0): set_value(ctx, var_refs[0]->pvalue, js_dup(sp[-1])); BREAK; CASE(OP_set_var_ref1): set_value(ctx, var_refs[1]->pvalue, js_dup(sp[-1])); BREAK; CASE(OP_set_var_ref2): set_value(ctx, var_refs[2]->pvalue, js_dup(sp[-1])); BREAK; CASE(OP_set_var_ref3): set_value(ctx, var_refs[3]->pvalue, js_dup(sp[-1])); BREAK; CASE(OP_get_var_ref): { int idx; JSValue val; idx = get_u16(pc); pc += 2; val = *var_refs[idx]->pvalue; sp[0] = js_dup(val); sp++; } BREAK; CASE(OP_put_var_ref): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, var_refs[idx]->pvalue, sp[-1]); sp--; } BREAK; CASE(OP_set_var_ref): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, var_refs[idx]->pvalue, js_dup(sp[-1])); } BREAK; CASE(OP_get_var_ref_check): { int idx; JSValue val; idx = get_u16(pc); pc += 2; val = *var_refs[idx]->pvalue; if (unlikely(JS_IsUninitialized(val))) { JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true); goto exception; } sp[0] = js_dup(val); sp++; } BREAK; CASE(OP_put_var_ref_check): { int idx; idx = get_u16(pc); pc += 2; if (unlikely(JS_IsUninitialized(*var_refs[idx]->pvalue))) { JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true); goto exception; } set_value(ctx, var_refs[idx]->pvalue, sp[-1]); sp--; } BREAK; CASE(OP_put_var_ref_check_init): { int idx; idx = get_u16(pc); pc += 2; if (unlikely(!JS_IsUninitialized(*var_refs[idx]->pvalue))) { JS_ThrowReferenceErrorUninitialized2(ctx, b, idx, true); goto exception; } set_value(ctx, var_refs[idx]->pvalue, sp[-1]); sp--; } BREAK; CASE(OP_set_loc_uninitialized): { int idx; idx = get_u16(pc); pc += 2; set_value(ctx, &var_buf[idx], JS_UNINITIALIZED); } BREAK; CASE(OP_get_loc_check): { int idx; idx = get_u16(pc); pc += 2; if (unlikely(JS_IsUninitialized(var_buf[idx]))) { JS_ThrowReferenceErrorUninitialized2(caller_ctx, b, idx, false); goto exception; } sp[0] = js_dup(var_buf[idx]); sp++; } BREAK; CASE(OP_put_loc_check): { int idx; idx = get_u16(pc); pc += 2; if (unlikely(JS_IsUninitialized(var_buf[idx]))) { JS_ThrowReferenceErrorUninitialized2(caller_ctx, b, idx, false); goto exception; } set_value(ctx, &var_buf[idx], sp[-1]); sp--; } BREAK; CASE(OP_put_loc_check_init): { int idx; idx = get_u16(pc); pc += 2; if (unlikely(!JS_IsUninitialized(var_buf[idx]))) { JS_ThrowReferenceError(caller_ctx, "'this' can be initialized only once"); goto exception; } set_value(ctx, &var_buf[idx], sp[-1]); sp--; } BREAK; CASE(OP_close_loc): { int idx; idx = get_u16(pc); pc += 2; close_lexical_var(ctx, sf, idx); } BREAK; CASE(OP_make_loc_ref): CASE(OP_make_arg_ref): CASE(OP_make_var_ref_ref): { JSVarRef *var_ref; JSProperty *pr; JSAtom atom; int idx; atom = get_u32(pc); idx = get_u16(pc + 4); pc += 6; *sp++ = JS_NewObjectProto(ctx, JS_NULL); if (unlikely(JS_IsException(sp[-1]))) goto exception; if (opcode == OP_make_var_ref_ref) { var_ref = var_refs[idx]; var_ref->header.ref_count++; } else { var_ref = get_var_ref(ctx, sf, idx, opcode == OP_make_arg_ref); if (!var_ref) goto exception; } pr = add_property(ctx, JS_VALUE_GET_OBJ(sp[-1]), atom, JS_PROP_WRITABLE | JS_PROP_VARREF); if (!pr) { free_var_ref(rt, var_ref); goto exception; } pr->u.var_ref = var_ref; *sp++ = JS_AtomToValue(ctx, atom); } BREAK; CASE(OP_make_var_ref): { JSAtom atom; atom = get_u32(pc); pc += 4; if (JS_GetGlobalVarRef(ctx, atom, sp)) goto exception; sp += 2; } BREAK; CASE(OP_goto): pc += (int32_t)get_u32(pc); if (unlikely(js_poll_interrupts(ctx))) goto exception; BREAK; CASE(OP_goto16): pc += (int16_t)get_u16(pc); if (unlikely(js_poll_interrupts(ctx))) goto exception; BREAK; CASE(OP_goto8): pc += (int8_t)pc[0]; if (unlikely(js_poll_interrupts(ctx))) goto exception; BREAK; CASE(OP_if_true): { int res; JSValue op1; op1 = sp[-1]; pc += 4; if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { res = JS_VALUE_GET_INT(op1); } else { res = JS_ToBoolFree(ctx, op1); } sp--; if (res) { pc += (int32_t)get_u32(pc - 4) - 4; } if (unlikely(js_poll_interrupts(ctx))) goto exception; } BREAK; CASE(OP_if_false): { int res; JSValue op1; op1 = sp[-1]; pc += 4; if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { res = JS_VALUE_GET_INT(op1); } else { res = JS_ToBoolFree(ctx, op1); } sp--; if (!res) { pc += (int32_t)get_u32(pc - 4) - 4; } if (unlikely(js_poll_interrupts(ctx))) goto exception; } BREAK; CASE(OP_if_true8): { int res; JSValue op1; op1 = sp[-1]; pc += 1; if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { res = JS_VALUE_GET_INT(op1); } else { res = JS_ToBoolFree(ctx, op1); } sp--; if (res) { pc += (int8_t)pc[-1] - 1; } if (unlikely(js_poll_interrupts(ctx))) goto exception; } BREAK; CASE(OP_if_false8): { int res; JSValue op1; op1 = sp[-1]; pc += 1; if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { res = JS_VALUE_GET_INT(op1); } else { res = JS_ToBoolFree(ctx, op1); } sp--; if (!res) { pc += (int8_t)pc[-1] - 1; } if (unlikely(js_poll_interrupts(ctx))) goto exception; } BREAK; CASE(OP_catch): { int32_t diff; diff = get_u32(pc); sp[0] = JS_NewCatchOffset(ctx, pc + diff - b->byte_code_buf); sp++; pc += 4; } BREAK; CASE(OP_gosub): { int32_t diff; diff = get_u32(pc); /* XXX: should have a different tag to avoid security flaw */ sp[0] = js_int32(pc + 4 - b->byte_code_buf); sp++; pc += diff; } BREAK; CASE(OP_ret): { JSValue op1; uint32_t pos; op1 = sp[-1]; if (unlikely(JS_VALUE_GET_TAG(op1) != JS_TAG_INT)) goto ret_fail; pos = JS_VALUE_GET_INT(op1); if (unlikely(pos >= b->byte_code_len)) { ret_fail: JS_ThrowInternalError(ctx, "invalid ret value"); goto exception; } sp--; pc = b->byte_code_buf + pos; } BREAK; CASE(OP_for_in_start): sf->cur_pc = pc; if (js_for_in_start(ctx, sp)) goto exception; BREAK; CASE(OP_for_in_next): sf->cur_pc = pc; if (js_for_in_next(ctx, sp)) goto exception; sp += 2; BREAK; CASE(OP_for_of_start): sf->cur_pc = pc; if (js_for_of_start(ctx, sp, false)) goto exception; sp += 1; *sp++ = JS_NewCatchOffset(ctx, 0); BREAK; CASE(OP_for_of_next): { int offset = -3 - pc[0]; pc += 1; sf->cur_pc = pc; if (js_for_of_next(ctx, sp, offset)) goto exception; sp += 2; } BREAK; CASE(OP_for_await_of_start): sf->cur_pc = pc; if (js_for_of_start(ctx, sp, true)) goto exception; sp += 1; *sp++ = JS_NewCatchOffset(ctx, 0); BREAK; CASE(OP_iterator_get_value_done): sf->cur_pc = pc; if (js_iterator_get_value_done(ctx, sp)) goto exception; sp += 1; BREAK; CASE(OP_iterator_check_object): if (unlikely(!JS_IsObject(sp[-1]))) { JS_ThrowTypeError(ctx, "iterator must return an object"); goto exception; } BREAK; CASE(OP_iterator_close): /* iter_obj next catch_offset -> */ sp--; /* drop the catch offset to avoid getting caught by exception */ JS_FreeValue(ctx, sp[-1]); /* drop the next method */ sp--; if (!JS_IsUndefined(sp[-1])) { sf->cur_pc = pc; if (JS_IteratorClose(ctx, sp[-1], false)) goto exception; JS_FreeValue(ctx, sp[-1]); } sp--; BREAK; CASE(OP_nip_catch): { JSValue ret_val; /* catch_offset ... ret_val -> ret_eval */ ret_val = *--sp; while (sp > stack_buf && JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_CATCH_OFFSET) { JS_FreeValue(ctx, *--sp); } if (unlikely(sp == stack_buf)) { JS_ThrowInternalError(ctx, "nip_catch"); JS_FreeValue(ctx, ret_val); goto exception; } sp[-1] = ret_val; } BREAK; CASE(OP_iterator_next): /* stack: iter_obj next catch_offset val */ { JSValue ret; sf->cur_pc = pc; ret = JS_Call(ctx, sp[-3], sp[-4], 1, vc(sp - 1)); if (JS_IsException(ret)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = ret; } BREAK; CASE(OP_iterator_call): /* stack: iter_obj next catch_offset val */ { JSValue method, ret; bool ret_flag; int flags; flags = *pc++; sf->cur_pc = pc; method = JS_GetProperty(ctx, sp[-4], (flags & 1) ? JS_ATOM_throw : JS_ATOM_return); if (JS_IsException(method)) goto exception; if (JS_IsUndefined(method) || JS_IsNull(method)) { ret_flag = true; } else { if (flags & 2) { /* no argument */ ret = JS_CallFree(ctx, method, sp[-4], 0, NULL); } else { ret = JS_CallFree(ctx, method, sp[-4], 1, vc(sp - 1)); } if (JS_IsException(ret)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = ret; ret_flag = false; } sp[0] = js_bool(ret_flag); sp += 1; } BREAK; CASE(OP_lnot): { int res; JSValue op1; op1 = sp[-1]; if ((uint32_t)JS_VALUE_GET_TAG(op1) <= JS_TAG_UNDEFINED) { res = JS_VALUE_GET_INT(op1) != 0; } else { res = JS_ToBoolFree(ctx, op1); } sp[-1] = js_bool(!res); } BREAK; CASE(OP_get_field): { JSValue val; JSAtom atom; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; val = JS_GetPropertyInternal(ctx, sp[-1], atom, sp[-1], false); if (unlikely(JS_IsException(val))) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = val; } BREAK; CASE(OP_get_field2): { JSValue val; JSAtom atom; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; val = JS_GetPropertyInternal(ctx, sp[-1], atom, sp[-1], false); if (unlikely(JS_IsException(val))) goto exception; *sp++ = val; } BREAK; CASE(OP_put_field): { int ret; JSAtom atom; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; ret = JS_SetPropertyInternal2(ctx, sp[-2], atom, sp[-1], sp[-2], JS_PROP_THROW_STRICT); JS_FreeValue(ctx, sp[-2]); sp -= 2; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_private_symbol): { JSAtom atom; JSValue val; atom = get_u32(pc); pc += 4; val = JS_NewSymbolFromAtom(ctx, atom, JS_ATOM_TYPE_PRIVATE); if (JS_IsException(val)) goto exception; *sp++ = val; } BREAK; CASE(OP_get_private_field): { JSValue val; sf->cur_pc = pc; val = JS_GetPrivateField(ctx, sp[-2], sp[-1]); JS_FreeValue(ctx, sp[-1]); JS_FreeValue(ctx, sp[-2]); sp[-2] = val; sp--; if (unlikely(JS_IsException(val))) goto exception; } BREAK; CASE(OP_put_private_field): { int ret; sf->cur_pc = pc; ret = JS_SetPrivateField(ctx, sp[-3], sp[-1], sp[-2]); JS_FreeValue(ctx, sp[-3]); JS_FreeValue(ctx, sp[-1]); sp -= 3; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_define_private_field): { int ret; ret = JS_DefinePrivateField(ctx, sp[-3], sp[-2], sp[-1]); JS_FreeValue(ctx, sp[-2]); sp -= 2; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_define_field): { int ret; JSAtom atom; atom = get_u32(pc); pc += 4; ret = JS_DefinePropertyValue(ctx, sp[-2], atom, sp[-1], JS_PROP_C_W_E | JS_PROP_THROW); sp--; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_set_name): { int ret; JSAtom atom; atom = get_u32(pc); pc += 4; ret = JS_DefineObjectName(ctx, sp[-1], atom, JS_PROP_CONFIGURABLE); if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_set_name_computed): { int ret; ret = JS_DefineObjectNameComputed(ctx, sp[-1], sp[-2], JS_PROP_CONFIGURABLE); if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_set_proto): { JSValue proto; proto = sp[-1]; if (JS_IsObject(proto) || JS_IsNull(proto)) { if (JS_SetPrototypeInternal(ctx, sp[-2], proto, true) < 0) goto exception; } JS_FreeValue(ctx, proto); sp--; } BREAK; CASE(OP_set_home_object): js_method_set_home_object(ctx, sp[-1], sp[-2]); BREAK; CASE(OP_define_method): CASE(OP_define_method_computed): { JSValue getter, setter, value; JSValue obj; JSAtom atom; int flags, ret, op_flags; bool is_computed; #define OP_DEFINE_METHOD_METHOD 0 #define OP_DEFINE_METHOD_GETTER 1 #define OP_DEFINE_METHOD_SETTER 2 #define OP_DEFINE_METHOD_ENUMERABLE 4 is_computed = (opcode == OP_define_method_computed); if (is_computed) { atom = JS_ValueToAtom(ctx, sp[-2]); if (unlikely(atom == JS_ATOM_NULL)) goto exception; opcode += OP_define_method - OP_define_method_computed; } else { atom = get_u32(pc); pc += 4; } op_flags = *pc++; obj = sp[-2 - is_computed]; flags = JS_PROP_HAS_CONFIGURABLE | JS_PROP_CONFIGURABLE | JS_PROP_HAS_ENUMERABLE | JS_PROP_THROW; if (op_flags & OP_DEFINE_METHOD_ENUMERABLE) flags |= JS_PROP_ENUMERABLE; op_flags &= 3; value = JS_UNDEFINED; getter = JS_UNDEFINED; setter = JS_UNDEFINED; if (op_flags == OP_DEFINE_METHOD_METHOD) { value = sp[-1]; flags |= JS_PROP_HAS_VALUE | JS_PROP_HAS_WRITABLE | JS_PROP_WRITABLE; } else if (op_flags == OP_DEFINE_METHOD_GETTER) { getter = sp[-1]; flags |= JS_PROP_HAS_GET; } else { setter = sp[-1]; flags |= JS_PROP_HAS_SET; } ret = js_method_set_properties(ctx, sp[-1], atom, flags, obj); if (ret >= 0) { ret = JS_DefineProperty(ctx, obj, atom, value, getter, setter, flags); } JS_FreeValue(ctx, sp[-1]); if (is_computed) { JS_FreeAtom(ctx, atom); JS_FreeValue(ctx, sp[-2]); } sp -= 1 + is_computed; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_define_class): CASE(OP_define_class_computed): { int class_flags; JSAtom atom; atom = get_u32(pc); class_flags = pc[4]; pc += 5; if (js_op_define_class(ctx, sp, atom, class_flags, var_refs, sf, (opcode == OP_define_class_computed)) < 0) goto exception; } BREAK; CASE(OP_get_array_el): { JSValue val; sf->cur_pc = pc; val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]); JS_FreeValue(ctx, sp[-2]); sp[-2] = val; sp--; if (unlikely(JS_IsException(val))) goto exception; } BREAK; CASE(OP_get_array_el2): { JSValue val; sf->cur_pc = pc; val = JS_GetPropertyValue(ctx, sp[-2], sp[-1]); sp[-1] = val; if (unlikely(JS_IsException(val))) goto exception; } BREAK; CASE(OP_get_ref_value): { JSValue val; sf->cur_pc = pc; if (unlikely(JS_IsUndefined(sp[-2]))) { JSAtom atom = JS_ValueToAtom(ctx, sp[-1]); if (atom != JS_ATOM_NULL) { JS_ThrowReferenceErrorNotDefined(ctx, atom); JS_FreeAtom(ctx, atom); } goto exception; } val = JS_GetPropertyValue(ctx, sp[-2], js_dup(sp[-1])); if (unlikely(JS_IsException(val))) goto exception; sp[0] = val; sp++; } BREAK; CASE(OP_get_super_value): { JSValue val; JSAtom atom; sf->cur_pc = pc; atom = JS_ValueToAtom(ctx, sp[-1]); if (unlikely(atom == JS_ATOM_NULL)) goto exception; val = JS_GetPropertyInternal(ctx, sp[-2], atom, sp[-3], false); JS_FreeAtom(ctx, atom); if (unlikely(JS_IsException(val))) goto exception; JS_FreeValue(ctx, sp[-1]); JS_FreeValue(ctx, sp[-2]); JS_FreeValue(ctx, sp[-3]); sp[-3] = val; sp -= 2; } BREAK; CASE(OP_put_array_el): { int ret; sf->cur_pc = pc; ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], JS_PROP_THROW_STRICT); JS_FreeValue(ctx, sp[-3]); sp -= 3; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_put_ref_value): { int ret, flags; sf->cur_pc = pc; flags = JS_PROP_THROW_STRICT; if (unlikely(JS_IsUndefined(sp[-3]))) { if (is_strict_mode(ctx)) { JSAtom atom = JS_ValueToAtom(ctx, sp[-2]); if (atom != JS_ATOM_NULL) { JS_ThrowReferenceErrorNotDefined(ctx, atom); JS_FreeAtom(ctx, atom); } goto exception; } else { sp[-3] = js_dup(ctx->global_obj); } } else { if (is_strict_mode(ctx)) flags |= JS_PROP_NO_ADD; } ret = JS_SetPropertyValue(ctx, sp[-3], sp[-2], sp[-1], flags); JS_FreeValue(ctx, sp[-3]); sp -= 3; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_put_super_value): { int ret; JSAtom atom; sf->cur_pc = pc; if (JS_VALUE_GET_TAG(sp[-3]) != JS_TAG_OBJECT) { JS_ThrowTypeErrorNotAnObject(ctx); goto exception; } atom = JS_ValueToAtom(ctx, sp[-2]); if (unlikely(atom == JS_ATOM_NULL)) goto exception; ret = JS_SetPropertyInternal2(ctx, sp[-3], atom, sp[-1], sp[-4], JS_PROP_THROW_STRICT); JS_FreeAtom(ctx, atom); JS_FreeValue(ctx, sp[-4]); JS_FreeValue(ctx, sp[-3]); JS_FreeValue(ctx, sp[-2]); sp -= 4; if (ret < 0) goto exception; } BREAK; CASE(OP_define_array_el): { int ret; ret = JS_DefinePropertyValueValue(ctx, sp[-3], js_dup(sp[-2]), sp[-1], JS_PROP_C_W_E | JS_PROP_THROW); sp -= 1; if (unlikely(ret < 0)) goto exception; } BREAK; CASE(OP_append): /* array pos enumobj -- array pos */ { sf->cur_pc = pc; if (js_append_enumerate(ctx, sp)) goto exception; JS_FreeValue(ctx, *--sp); } BREAK; CASE(OP_copy_data_properties): /* target source excludeList */ { /* stack offsets (-1 based): 2 bits for target, 3 bits for source, 2 bits for exclusionList */ int mask; mask = *pc++; sf->cur_pc = pc; if (JS_CopyDataProperties(ctx, sp[-1 - (mask & 3)], sp[-1 - ((mask >> 2) & 7)], sp[-1 - ((mask >> 5) & 7)], 0)) goto exception; } BREAK; CASE(OP_add): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { int64_t r; r = (int64_t)JS_VALUE_GET_INT(op1) + JS_VALUE_GET_INT(op2); if (unlikely((int)r != r)) goto add_slow; sp[-2] = js_int32(r); sp--; } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) { sp[-2] = js_float64(JS_VALUE_GET_FLOAT64(op1) + JS_VALUE_GET_FLOAT64(op2)); sp--; } else { add_slow: sf->cur_pc = pc; if (js_add_slow(ctx, sp)) goto exception; sp--; } } BREAK; CASE(OP_add_loc): { JSValue *pv; int idx; idx = *pc; pc += 1; pv = &var_buf[idx]; if (likely(JS_VALUE_IS_BOTH_INT(*pv, sp[-1]))) { int64_t r; r = (int64_t)JS_VALUE_GET_INT(*pv) + JS_VALUE_GET_INT(sp[-1]); if (unlikely((int)r != r)) goto add_loc_slow; *pv = js_int32(r); sp--; } else if (JS_VALUE_GET_TAG(*pv) == JS_TAG_STRING) { JSValue op1; op1 = sp[-1]; sp--; sf->cur_pc = pc; op1 = JS_ToPrimitiveFree(ctx, op1, HINT_NONE); if (JS_IsException(op1)) goto exception; op1 = JS_ConcatString(ctx, js_dup(*pv), op1); if (JS_IsException(op1)) goto exception; set_value(ctx, pv, op1); } else { JSValue ops[2]; add_loc_slow: /* In case of exception, js_add_slow frees ops[0] and ops[1], so we must duplicate *pv */ sf->cur_pc = pc; ops[0] = js_dup(*pv); ops[1] = sp[-1]; sp--; if (js_add_slow(ctx, ops + 2)) goto exception; set_value(ctx, pv, ops[0]); } } BREAK; CASE(OP_sub): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { int64_t r; r = (int64_t)JS_VALUE_GET_INT(op1) - JS_VALUE_GET_INT(op2); if (unlikely((int)r != r)) goto binary_arith_slow; sp[-2] = js_int32(r); sp--; } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) { sp[-2] = js_float64(JS_VALUE_GET_FLOAT64(op1) - JS_VALUE_GET_FLOAT64(op2)); sp--; } else { goto binary_arith_slow; } } BREAK; CASE(OP_mul): { JSValue op1, op2; double d; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { int32_t v1, v2; int64_t r; v1 = JS_VALUE_GET_INT(op1); v2 = JS_VALUE_GET_INT(op2); r = (int64_t)v1 * v2; if (unlikely((int)r != r)) { d = (double)r; goto mul_fp_res; } /* need to test zero case for -0 result */ if (unlikely(r == 0 && (v1 | v2) < 0)) { d = -0.0; goto mul_fp_res; } sp[-2] = js_int32(r); sp--; } else if (JS_VALUE_IS_BOTH_FLOAT(op1, op2)) { d = JS_VALUE_GET_FLOAT64(op1) * JS_VALUE_GET_FLOAT64(op2); mul_fp_res: sp[-2] = js_float64(d); sp--; } else { goto binary_arith_slow; } } BREAK; CASE(OP_div): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { int v1, v2; v1 = JS_VALUE_GET_INT(op1); v2 = JS_VALUE_GET_INT(op2); sp[-2] = js_number((double)v1 / (double)v2); sp--; } else { goto binary_arith_slow; } } BREAK; CASE(OP_mod): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { int v1, v2, r; v1 = JS_VALUE_GET_INT(op1); v2 = JS_VALUE_GET_INT(op2); /* We must avoid v2 = 0, v1 = INT32_MIN and v2 = -1 and the cases where the result is -0. */ if (unlikely(v1 < 0 || v2 <= 0)) goto binary_arith_slow; r = v1 % v2; sp[-2] = js_int32(r); sp--; } else { goto binary_arith_slow; } } BREAK; CASE(OP_pow): binary_arith_slow: sf->cur_pc = pc; if (js_binary_arith_slow(ctx, sp, opcode)) goto exception; sp--; BREAK; CASE(OP_plus): { JSValue op1; uint32_t tag; op1 = sp[-1]; tag = JS_VALUE_GET_TAG(op1); if (tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag)) { } else { sf->cur_pc = pc; if (js_unary_arith_slow(ctx, sp, opcode)) goto exception; } } BREAK; CASE(OP_neg): { JSValue op1; uint32_t tag; int val; double d; op1 = sp[-1]; tag = JS_VALUE_GET_TAG(op1); if (tag == JS_TAG_INT) { val = JS_VALUE_GET_INT(op1); /* Note: -0 cannot be expressed as integer */ if (unlikely(val == 0)) { d = -0.0; goto neg_fp_res; } if (unlikely(val == INT32_MIN)) { d = -(double)val; goto neg_fp_res; } sp[-1] = js_int32(-val); } else if (JS_TAG_IS_FLOAT64(tag)) { d = -JS_VALUE_GET_FLOAT64(op1); neg_fp_res: sp[-1] = js_float64(d); } else { sf->cur_pc = pc; if (js_unary_arith_slow(ctx, sp, opcode)) goto exception; } } BREAK; CASE(OP_inc): { JSValue op1; int val; op1 = sp[-1]; if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { val = JS_VALUE_GET_INT(op1); if (unlikely(val == INT32_MAX)) goto inc_slow; sp[-1] = js_int32(val + 1); } else { inc_slow: sf->cur_pc = pc; if (js_unary_arith_slow(ctx, sp, opcode)) goto exception; } } BREAK; CASE(OP_dec): { JSValue op1; int val; op1 = sp[-1]; if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { val = JS_VALUE_GET_INT(op1); if (unlikely(val == INT32_MIN)) goto dec_slow; sp[-1] = js_int32(val - 1); } else { dec_slow: sf->cur_pc = pc; if (js_unary_arith_slow(ctx, sp, opcode)) goto exception; } } BREAK; CASE(OP_post_inc): CASE(OP_post_dec): sf->cur_pc = pc; if (js_post_inc_slow(ctx, sp, opcode)) goto exception; sp++; BREAK; CASE(OP_inc_loc): { JSValue op1; int val; int idx; idx = *pc; pc += 1; op1 = var_buf[idx]; if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { val = JS_VALUE_GET_INT(op1); if (unlikely(val == INT32_MAX)) goto inc_loc_slow; var_buf[idx] = js_int32(val + 1); } else { inc_loc_slow: sf->cur_pc = pc; /* must duplicate otherwise the variable value may be destroyed before JS code accesses it */ op1 = js_dup(op1); if (js_unary_arith_slow(ctx, &op1 + 1, OP_inc)) goto exception; set_value(ctx, &var_buf[idx], op1); } } BREAK; CASE(OP_dec_loc): { JSValue op1; int val; int idx; idx = *pc; pc += 1; op1 = var_buf[idx]; if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { val = JS_VALUE_GET_INT(op1); if (unlikely(val == INT32_MIN)) goto dec_loc_slow; var_buf[idx] = js_int32(val - 1); } else { dec_loc_slow: sf->cur_pc = pc; /* must duplicate otherwise the variable value may be destroyed before JS code accesses it */ op1 = js_dup(op1); if (js_unary_arith_slow(ctx, &op1 + 1, OP_dec)) goto exception; set_value(ctx, &var_buf[idx], op1); } } BREAK; CASE(OP_not): { JSValue op1; op1 = sp[-1]; if (JS_VALUE_GET_TAG(op1) == JS_TAG_INT) { sp[-1] = js_int32(~JS_VALUE_GET_INT(op1)); } else { sf->cur_pc = pc; if (js_not_slow(ctx, sp)) goto exception; } } BREAK; CASE(OP_shl): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { uint32_t v1, v2; v1 = JS_VALUE_GET_INT(op1); v2 = JS_VALUE_GET_INT(op2) & 0x1f; sp[-2] = js_int32(v1 << v2); sp--; } else { sf->cur_pc = pc; if (js_binary_logic_slow(ctx, sp, opcode)) goto exception; sp--; } } BREAK; CASE(OP_shr): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { uint32_t v2; v2 = JS_VALUE_GET_INT(op2); v2 &= 0x1f; sp[-2] = js_uint32((uint32_t)JS_VALUE_GET_INT(op1) >> v2); sp--; } else { sf->cur_pc = pc; if (js_shr_slow(ctx, sp)) goto exception; sp--; } } BREAK; CASE(OP_sar): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { uint32_t v2; v2 = JS_VALUE_GET_INT(op2); if (unlikely(v2 > 0x1f)) { v2 &= 0x1f; } sp[-2] = js_int32((int)JS_VALUE_GET_INT(op1) >> v2); sp--; } else { sf->cur_pc = pc; if (js_binary_logic_slow(ctx, sp, opcode)) goto exception; sp--; } } BREAK; CASE(OP_and): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { sp[-2] = js_int32(JS_VALUE_GET_INT(op1) & JS_VALUE_GET_INT(op2)); sp--; } else { sf->cur_pc = pc; if (js_binary_logic_slow(ctx, sp, opcode)) goto exception; sp--; } } BREAK; CASE(OP_or): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { sp[-2] = js_int32(JS_VALUE_GET_INT(op1) | JS_VALUE_GET_INT(op2)); sp--; } else { sf->cur_pc = pc; if (js_binary_logic_slow(ctx, sp, opcode)) goto exception; sp--; } } BREAK; CASE(OP_xor): { JSValue op1, op2; op1 = sp[-2]; op2 = sp[-1]; if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { sp[-2] = js_int32(JS_VALUE_GET_INT(op1) ^ JS_VALUE_GET_INT(op2)); sp--; } else { sf->cur_pc = pc; if (js_binary_logic_slow(ctx, sp, opcode)) goto exception; sp--; } } BREAK; #define OP_CMP(opcode, binary_op, slow_call) \ CASE(opcode): \ { \ JSValue op1, op2; \ op1 = sp[-2]; \ op2 = sp[-1]; \ if (likely(JS_VALUE_IS_BOTH_INT(op1, op2))) { \ sp[-2] = js_bool(JS_VALUE_GET_INT(op1) binary_op JS_VALUE_GET_INT(op2)); \ sp--; \ } else { \ sf->cur_pc = pc; \ if (slow_call) \ goto exception; \ sp--; \ } \ } \ BREAK OP_CMP(OP_lt, <, js_relational_slow(ctx, sp, opcode)); OP_CMP(OP_lte, <=, js_relational_slow(ctx, sp, opcode)); OP_CMP(OP_gt, >, js_relational_slow(ctx, sp, opcode)); OP_CMP(OP_gte, >=, js_relational_slow(ctx, sp, opcode)); OP_CMP(OP_eq, ==, js_eq_slow(ctx, sp, 0)); OP_CMP(OP_neq, !=, js_eq_slow(ctx, sp, 1)); OP_CMP(OP_strict_eq, ==, js_strict_eq_slow(ctx, sp, 0)); OP_CMP(OP_strict_neq, !=, js_strict_eq_slow(ctx, sp, 1)); CASE(OP_in): sf->cur_pc = pc; if (js_operator_in(ctx, sp)) goto exception; sp--; BREAK; CASE(OP_private_in): if (js_operator_private_in(ctx, sp)) goto exception; sp--; BREAK; CASE(OP_instanceof): sf->cur_pc = pc; if (js_operator_instanceof(ctx, sp)) goto exception; sp--; BREAK; CASE(OP_typeof): { JSValue op1; JSAtom atom; op1 = sp[-1]; atom = js_operator_typeof(ctx, op1); JS_FreeValue(ctx, op1); sp[-1] = JS_AtomToString(ctx, atom); } BREAK; CASE(OP_delete): sf->cur_pc = pc; if (js_operator_delete(ctx, sp)) goto exception; sp--; BREAK; CASE(OP_delete_var): { JSAtom atom; int ret; atom = get_u32(pc); pc += 4; sf->cur_pc = pc; ret = JS_DeleteGlobalVar(ctx, atom); if (unlikely(ret < 0)) goto exception; *sp++ = js_bool(ret); } BREAK; CASE(OP_to_object): if (JS_VALUE_GET_TAG(sp[-1]) != JS_TAG_OBJECT) { sf->cur_pc = pc; ret_val = JS_ToObject(ctx, sp[-1]); if (JS_IsException(ret_val)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = ret_val; } BREAK; CASE(OP_to_propkey): switch (JS_VALUE_GET_TAG(sp[-1])) { case JS_TAG_INT: case JS_TAG_STRING: case JS_TAG_SYMBOL: break; default: sf->cur_pc = pc; ret_val = JS_ToPropertyKey(ctx, sp[-1]); if (JS_IsException(ret_val)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = ret_val; break; } BREAK; CASE(OP_to_propkey2): /* must be tested first */ if (unlikely(JS_IsUndefined(sp[-2]) || JS_IsNull(sp[-2]))) { JS_ThrowTypeError(ctx, "value has no property"); goto exception; } switch (JS_VALUE_GET_TAG(sp[-1])) { case JS_TAG_INT: case JS_TAG_STRING: case JS_TAG_SYMBOL: break; default: sf->cur_pc = pc; ret_val = JS_ToPropertyKey(ctx, sp[-1]); if (JS_IsException(ret_val)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = ret_val; break; } BREAK; CASE(OP_with_get_var): CASE(OP_with_put_var): CASE(OP_with_delete_var): CASE(OP_with_make_ref): CASE(OP_with_get_ref): CASE(OP_with_get_ref_undef): { JSAtom atom; int32_t diff; JSValue obj, val; int ret, is_with; atom = get_u32(pc); diff = get_u32(pc + 4); is_with = pc[8]; pc += 9; sf->cur_pc = pc; obj = sp[-1]; ret = JS_HasProperty(ctx, obj, atom); if (unlikely(ret < 0)) goto exception; if (ret) { if (is_with) { ret = js_has_unscopable(ctx, obj, atom); if (unlikely(ret < 0)) goto exception; if (ret) goto no_with; } switch (opcode) { case OP_with_get_var: val = JS_GetProperty(ctx, obj, atom); if (unlikely(JS_IsException(val))) goto exception; set_value(ctx, &sp[-1], val); break; case OP_with_put_var: /* XXX: check if strict mode */ ret = JS_SetPropertyInternal(ctx, obj, atom, sp[-2], JS_PROP_THROW_STRICT); JS_FreeValue(ctx, sp[-1]); sp -= 2; if (unlikely(ret < 0)) goto exception; break; case OP_with_delete_var: ret = JS_DeleteProperty(ctx, obj, atom, 0); if (unlikely(ret < 0)) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = js_bool(ret); break; case OP_with_make_ref: /* produce a pair object/propname on the stack */ *sp++ = JS_AtomToValue(ctx, atom); break; case OP_with_get_ref: /* produce a pair object/method on the stack */ val = JS_GetProperty(ctx, obj, atom); if (unlikely(JS_IsException(val))) goto exception; *sp++ = val; break; case OP_with_get_ref_undef: /* produce a pair undefined/function on the stack */ val = JS_GetProperty(ctx, obj, atom); if (unlikely(JS_IsException(val))) goto exception; JS_FreeValue(ctx, sp[-1]); sp[-1] = JS_UNDEFINED; *sp++ = val; break; } pc += diff - 5; } else { no_with: /* if not jumping, drop the object argument */ JS_FreeValue(ctx, sp[-1]); sp--; } } BREAK; CASE(OP_await): ret_val = js_int32(FUNC_RET_AWAIT); goto done_generator; CASE(OP_yield): ret_val = js_int32(FUNC_RET_YIELD); goto done_generator; CASE(OP_yield_star): CASE(OP_async_yield_star): ret_val = js_int32(FUNC_RET_YIELD_STAR); goto done_generator; CASE(OP_return_async): CASE(OP_initial_yield): ret_val = JS_UNDEFINED; goto done_generator; CASE(OP_nop): BREAK; CASE(OP_is_undefined_or_null): if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED || JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) { goto set_true; } else { goto free_and_set_false; } CASE(OP_is_undefined): if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_UNDEFINED) { goto set_true; } else { goto free_and_set_false; } CASE(OP_is_null): if (JS_VALUE_GET_TAG(sp[-1]) == JS_TAG_NULL) { goto set_true; } else { goto free_and_set_false; } /* XXX: could merge to a single opcode */ CASE(OP_typeof_is_undefined): /* different from OP_is_undefined because of isHTMLDDA */ if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_undefined) { goto free_and_set_true; } else { goto free_and_set_false; } CASE(OP_typeof_is_function): if (js_operator_typeof(ctx, sp[-1]) == JS_ATOM_function) { goto free_and_set_true; } else { goto free_and_set_false; } free_and_set_true: JS_FreeValue(ctx, sp[-1]); set_true: sp[-1] = JS_TRUE; BREAK; free_and_set_false: JS_FreeValue(ctx, sp[-1]); sp[-1] = JS_FALSE; BREAK; CASE(OP_invalid): DEFAULT: JS_ThrowInternalError(ctx, "invalid opcode: pc=%u opcode=0x%02x", (int)(pc - b->byte_code_buf - 1), opcode); goto exception; } } exception: if (needs_backtrace(rt->current_exception) || JS_IsUndefined(ctx->error_back_trace)) { sf->cur_pc = pc; build_backtrace(ctx, rt->current_exception, JS_UNDEFINED, NULL, 0, 0, 0); } if (!JS_IsUncatchableError(rt->current_exception)) { while (sp > stack_buf) { JSValue val = *--sp; JS_FreeValue(ctx, val); if (JS_VALUE_GET_TAG(val) == JS_TAG_CATCH_OFFSET) { int pos = JS_VALUE_GET_INT(val); if (pos == 0) { /* enumerator: close it with a throw */ JS_FreeValue(ctx, sp[-1]); /* drop the next method */ sp--; JS_IteratorClose(ctx, sp[-1], true); } else { *sp++ = rt->current_exception; rt->current_exception = JS_UNINITIALIZED; JS_FreeValueRT(rt, ctx->error_back_trace); ctx->error_back_trace = JS_UNDEFINED; pc = b->byte_code_buf + pos; goto restart; } } } } ret_val = JS_EXCEPTION; /* the local variables are freed by the caller in the generator case. Hence the label 'done' should never be reached in a generator function. */ if (b->func_kind != JS_FUNC_NORMAL) { done_generator: sf->cur_pc = pc; sf->cur_sp = sp; } else { done: if (unlikely(!list_empty(&sf->var_ref_list))) { /* variable references reference the stack: must close them */ close_var_refs(rt, sf); } /* free the local variables and stack */ for(pval = local_buf; pval < sp; pval++) { JS_FreeValue(ctx, *pval); } } rt->current_stack_frame = sf->prev_frame; return ret_val; } JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv) { return JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED, argc, argv, JS_CALL_FLAG_COPY_ARGV); } static JSValue JS_CallFree(JSContext *ctx, JSValue func_obj, JSValueConst this_obj, int argc, JSValueConst *argv) { JSValue res = JS_CallInternal(ctx, func_obj, this_obj, JS_UNDEFINED, argc, argv, JS_CALL_FLAG_COPY_ARGV); JS_FreeValue(ctx, func_obj); return res; } /* warning: the refcount of the context is not incremented. Return NULL in case of exception (case of revoked proxy only) */ static JSContext *JS_GetFunctionRealm(JSContext *ctx, JSValueConst func_obj) { JSObject *p; JSContext *realm; if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT) return ctx; p = JS_VALUE_GET_OBJ(func_obj); switch(p->class_id) { case JS_CLASS_C_FUNCTION: realm = p->u.cfunc.realm; break; case JS_CLASS_BYTECODE_FUNCTION: case JS_CLASS_GENERATOR_FUNCTION: case JS_CLASS_ASYNC_FUNCTION: case JS_CLASS_ASYNC_GENERATOR_FUNCTION: { JSFunctionBytecode *b; b = p->u.func.function_bytecode; realm = b->realm; } break; case JS_CLASS_PROXY: { JSProxyData *s = p->u.opaque; if (!s) return ctx; if (s->is_revoked) { JS_ThrowTypeErrorRevokedProxy(ctx); return NULL; } else { realm = JS_GetFunctionRealm(ctx, s->target); } } break; case JS_CLASS_BOUND_FUNCTION: { JSBoundFunction *bf = p->u.bound_function; realm = JS_GetFunctionRealm(ctx, bf->func_obj); } break; default: realm = ctx; break; } return realm; } static JSValue js_create_from_ctor(JSContext *ctx, JSValueConst ctor, int class_id) { JSValue proto, obj; JSContext *realm; if (JS_IsUndefined(ctor)) { proto = js_dup(ctx->class_proto[class_id]); } else { proto = JS_GetProperty(ctx, ctor, JS_ATOM_prototype); if (JS_IsException(proto)) return proto; if (!JS_IsObject(proto)) { JS_FreeValue(ctx, proto); realm = JS_GetFunctionRealm(ctx, ctor); if (!realm) return JS_EXCEPTION; proto = js_dup(realm->class_proto[class_id]); } } obj = JS_NewObjectProtoClass(ctx, proto, class_id); JS_FreeValue(ctx, proto); return obj; } /* argv[] is modified if (flags & JS_CALL_FLAG_COPY_ARGV) = 0. */ static JSValue JS_CallConstructorInternal(JSContext *ctx, JSValueConst func_obj, JSValueConst new_target, int argc, JSValueConst *argv, int flags) { JSObject *p; JSFunctionBytecode *b; if (js_poll_interrupts(ctx)) return JS_EXCEPTION; flags |= JS_CALL_FLAG_CONSTRUCTOR; if (unlikely(JS_VALUE_GET_TAG(func_obj) != JS_TAG_OBJECT)) goto not_a_function; p = JS_VALUE_GET_OBJ(func_obj); if (unlikely(!p->is_constructor)) return JS_ThrowTypeErrorNotAConstructor(ctx, func_obj); if (unlikely(p->class_id != JS_CLASS_BYTECODE_FUNCTION)) { JSClassCall *call_func; call_func = ctx->rt->class_array[p->class_id].call; if (!call_func) { not_a_function: return JS_ThrowTypeErrorNotAFunction(ctx); } return call_func(ctx, func_obj, new_target, argc, argv, flags); } b = p->u.func.function_bytecode; if (b->is_derived_class_constructor) { return JS_CallInternal(ctx, func_obj, JS_UNDEFINED, new_target, argc, argv, flags); } else { JSValue obj, ret; /* legacy constructor behavior */ obj = js_create_from_ctor(ctx, new_target, JS_CLASS_OBJECT); if (JS_IsException(obj)) return JS_EXCEPTION; ret = JS_CallInternal(ctx, func_obj, obj, new_target, argc, argv, flags); if (JS_VALUE_GET_TAG(ret) == JS_TAG_OBJECT || JS_IsException(ret)) { JS_FreeValue(ctx, obj); return ret; } else { JS_FreeValue(ctx, ret); return obj; } } } JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj, JSValueConst new_target, int argc, JSValueConst *argv) { return JS_CallConstructorInternal(ctx, func_obj, new_target, argc, argv, JS_CALL_FLAG_COPY_ARGV); } JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj, int argc, JSValueConst *argv) { return JS_CallConstructorInternal(ctx, func_obj, func_obj, argc, argv, JS_CALL_FLAG_COPY_ARGV); } JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom, int argc, JSValueConst *argv) { JSValue func_obj; func_obj = JS_GetProperty(ctx, this_val, atom); if (JS_IsException(func_obj)) return func_obj; return JS_CallFree(ctx, func_obj, this_val, argc, argv); } static JSValue JS_InvokeFree(JSContext *ctx, JSValue this_val, JSAtom atom, int argc, JSValueConst *argv) { JSValue res = JS_Invoke(ctx, this_val, atom, argc, argv); JS_FreeValue(ctx, this_val); return res; } /* JSAsyncFunctionState (used by generator and async functions) */ static __exception int async_func_init(JSContext *ctx, JSAsyncFunctionState *s, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv) { JSObject *p; JSFunctionBytecode *b; JSStackFrame *sf; int local_count, i, arg_buf_len, n; sf = &s->frame; init_list_head(&sf->var_ref_list); p = JS_VALUE_GET_OBJ(func_obj); b = p->u.func.function_bytecode; sf->is_strict_mode = b->is_strict_mode; sf->cur_pc = b->byte_code_buf; arg_buf_len = max_int(b->arg_count, argc); local_count = arg_buf_len + b->var_count + b->stack_size; sf->arg_buf = js_malloc(ctx, sizeof(JSValue) * max_int(local_count, 1)); if (!sf->arg_buf) return -1; sf->cur_func = js_dup(func_obj); s->this_val = js_dup(this_obj); s->argc = argc; sf->arg_count = arg_buf_len; sf->var_buf = sf->arg_buf + arg_buf_len; sf->cur_sp = sf->var_buf + b->var_count; for(i = 0; i < argc; i++) sf->arg_buf[i] = js_dup(argv[i]); n = arg_buf_len + b->var_count; for(i = argc; i < n; i++) sf->arg_buf[i] = JS_UNDEFINED; return 0; } static void async_func_mark(JSRuntime *rt, JSAsyncFunctionState *s, JS_MarkFunc *mark_func) { JSStackFrame *sf; JSValue *sp; sf = &s->frame; JS_MarkValue(rt, sf->cur_func, mark_func); JS_MarkValue(rt, s->this_val, mark_func); if (sf->cur_sp) { /* if the function is running, cur_sp is not known so we cannot mark the stack. Marking the variables is not needed because a running function cannot be part of a removable cycle */ for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) JS_MarkValue(rt, *sp, mark_func); } } static void async_func_free(JSRuntime *rt, JSAsyncFunctionState *s) { JSStackFrame *sf; JSValue *sp; sf = &s->frame; /* close the closure variables. */ close_var_refs(rt, sf); if (sf->arg_buf) { /* cannot free the function if it is running */ assert(sf->cur_sp != NULL); for(sp = sf->arg_buf; sp < sf->cur_sp; sp++) { JS_FreeValueRT(rt, *sp); } js_free_rt(rt, sf->arg_buf); } JS_FreeValueRT(rt, sf->cur_func); JS_FreeValueRT(rt, s->this_val); } static JSValue async_func_resume(JSContext *ctx, JSAsyncFunctionState *s) { JSValue func_obj; if (js_check_stack_overflow(ctx->rt, 0)) return JS_ThrowStackOverflow(ctx); /* the tag does not matter provided it is not an object */ func_obj = JS_MKPTR(JS_TAG_INT, s); return JS_CallInternal(ctx, func_obj, s->this_val, JS_UNDEFINED, s->argc, vc(s->frame.arg_buf), JS_CALL_FLAG_GENERATOR); } /* Generators */ typedef enum JSGeneratorStateEnum { JS_GENERATOR_STATE_SUSPENDED_START, JS_GENERATOR_STATE_SUSPENDED_YIELD, JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR, JS_GENERATOR_STATE_EXECUTING, JS_GENERATOR_STATE_COMPLETED, } JSGeneratorStateEnum; typedef struct JSGeneratorData { JSGeneratorStateEnum state; JSAsyncFunctionState func_state; } JSGeneratorData; static void free_generator_stack_rt(JSRuntime *rt, JSGeneratorData *s) { if (s->state == JS_GENERATOR_STATE_COMPLETED) return; async_func_free(rt, &s->func_state); s->state = JS_GENERATOR_STATE_COMPLETED; } static void js_generator_finalizer(JSRuntime *rt, JSValueConst obj) { JSGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_GENERATOR); if (s) { free_generator_stack_rt(rt, s); js_free_rt(rt, s); } } static void free_generator_stack(JSContext *ctx, JSGeneratorData *s) { free_generator_stack_rt(ctx->rt, s); } static void js_generator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); JSGeneratorData *s = p->u.generator_data; if (!s || s->state == JS_GENERATOR_STATE_COMPLETED) return; async_func_mark(rt, &s->func_state, mark_func); } /* XXX: use enum */ #define GEN_MAGIC_NEXT 0 #define GEN_MAGIC_RETURN 1 #define GEN_MAGIC_THROW 2 static JSValue js_generator_next(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int *pdone, int magic) { JSGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_GENERATOR); JSStackFrame *sf; JSValue ret, func_ret; *pdone = true; if (!s) return JS_ThrowTypeError(ctx, "not a generator"); sf = &s->func_state.frame; switch(s->state) { default: case JS_GENERATOR_STATE_SUSPENDED_START: if (magic == GEN_MAGIC_NEXT) { goto exec_no_arg; } else { free_generator_stack(ctx, s); goto done; } break; case JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR: case JS_GENERATOR_STATE_SUSPENDED_YIELD: /* cur_sp[-1] was set to JS_UNDEFINED in the previous call */ ret = js_dup(argv[0]); if (magic == GEN_MAGIC_THROW && s->state == JS_GENERATOR_STATE_SUSPENDED_YIELD) { JS_Throw(ctx, ret); s->func_state.throw_flag = true; } else { sf->cur_sp[-1] = ret; sf->cur_sp[0] = js_int32(magic); sf->cur_sp++; exec_no_arg: s->func_state.throw_flag = false; } s->state = JS_GENERATOR_STATE_EXECUTING; func_ret = async_func_resume(ctx, &s->func_state); s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD; if (JS_IsException(func_ret)) { /* finalize the execution in case of exception */ free_generator_stack(ctx, s); return func_ret; } if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) { /* get the returned yield value at the top of the stack */ ret = sf->cur_sp[-1]; sf->cur_sp[-1] = JS_UNDEFINED; if (JS_VALUE_GET_INT(func_ret) == FUNC_RET_YIELD_STAR) { s->state = JS_GENERATOR_STATE_SUSPENDED_YIELD_STAR; /* return (value, done) object */ *pdone = 2; } else { *pdone = false; } } else { /* end of iterator */ ret = sf->cur_sp[-1]; sf->cur_sp[-1] = JS_UNDEFINED; JS_FreeValue(ctx, func_ret); free_generator_stack(ctx, s); } break; case JS_GENERATOR_STATE_COMPLETED: done: /* execution is finished */ switch(magic) { default: case GEN_MAGIC_NEXT: ret = JS_UNDEFINED; break; case GEN_MAGIC_RETURN: ret = js_dup(argv[0]); break; case GEN_MAGIC_THROW: ret = JS_Throw(ctx, js_dup(argv[0])); break; } break; case JS_GENERATOR_STATE_EXECUTING: ret = JS_ThrowTypeError(ctx, "cannot invoke a running generator"); break; } return ret; } static JSValue js_call_generator_function(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags) { JSValue obj, func_ret; JSGeneratorData *s; s = js_mallocz(ctx, sizeof(*s)); if (!s) return JS_EXCEPTION; s->state = JS_GENERATOR_STATE_SUSPENDED_START; if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { s->state = JS_GENERATOR_STATE_COMPLETED; goto fail; } /* execute the function up to 'OP_initial_yield' */ func_ret = async_func_resume(ctx, &s->func_state); if (JS_IsException(func_ret)) goto fail; JS_FreeValue(ctx, func_ret); obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_GENERATOR); if (JS_IsException(obj)) goto fail; JS_SetOpaqueInternal(obj, s); return obj; fail: free_generator_stack_rt(ctx->rt, s); js_free(ctx, s); return JS_EXCEPTION; } /* AsyncFunction */ static void js_async_function_terminate(JSRuntime *rt, JSAsyncFunctionData *s) { if (s->is_active) { async_func_free(rt, &s->func_state); s->is_active = false; } } static void js_async_function_free0(JSRuntime *rt, JSAsyncFunctionData *s) { js_async_function_terminate(rt, s); JS_FreeValueRT(rt, s->resolving_funcs[0]); JS_FreeValueRT(rt, s->resolving_funcs[1]); remove_gc_object(&s->header); js_free_rt(rt, s); } static void js_async_function_free(JSRuntime *rt, JSAsyncFunctionData *s) { if (--s->header.ref_count == 0) { js_async_function_free0(rt, s); } } static void js_async_function_resolve_finalizer(JSRuntime *rt, JSValueConst val) { JSObject *p = JS_VALUE_GET_OBJ(val); JSAsyncFunctionData *s = p->u.async_function_data; if (s) { js_async_function_free(rt, s); } } static void js_async_function_resolve_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSObject *p = JS_VALUE_GET_OBJ(val); JSAsyncFunctionData *s = p->u.async_function_data; if (s) { mark_func(rt, &s->header); } } static int js_async_function_resolve_create(JSContext *ctx, JSAsyncFunctionData *s, JSValue *resolving_funcs) { int i; JSObject *p; for(i = 0; i < 2; i++) { resolving_funcs[i] = JS_NewObjectProtoClass(ctx, ctx->function_proto, JS_CLASS_ASYNC_FUNCTION_RESOLVE + i); if (JS_IsException(resolving_funcs[i])) { if (i == 1) JS_FreeValue(ctx, resolving_funcs[0]); return -1; } p = JS_VALUE_GET_OBJ(resolving_funcs[i]); s->header.ref_count++; p->u.async_function_data = s; } return 0; } static bool js_async_function_resume(JSContext *ctx, JSAsyncFunctionData *s) { bool is_success = true; JSValue func_ret, ret2; func_ret = async_func_resume(ctx, &s->func_state); if (JS_IsException(func_ret)) { fail: if (unlikely(JS_IsUncatchableError(ctx->rt->current_exception))) { is_success = false; } else { JSValue error = JS_GetException(ctx); ret2 = JS_Call(ctx, s->resolving_funcs[1], JS_UNDEFINED, 1, vc(&error)); JS_FreeValue(ctx, error); resolved: if (unlikely(JS_IsException(ret2))) { if (JS_IsUncatchableError(ctx->rt->current_exception)) { is_success = false; } else { abort(); /* BUG */ } } JS_FreeValue(ctx, ret2); } js_async_function_terminate(ctx->rt, s); } else { JSValue value; value = s->func_state.frame.cur_sp[-1]; s->func_state.frame.cur_sp[-1] = JS_UNDEFINED; if (JS_IsUndefined(func_ret)) { /* function returned */ ret2 = JS_Call(ctx, s->resolving_funcs[0], JS_UNDEFINED, 1, vc(&value)); JS_FreeValue(ctx, value); goto resolved; } else { JSValue promise, resolving_funcs[2], resolving_funcs1[2]; int i, res; /* await */ JS_FreeValue(ctx, func_ret); /* not used */ promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&value), 0); JS_FreeValue(ctx, value); if (JS_IsException(promise)) goto fail; if (js_async_function_resolve_create(ctx, s, resolving_funcs)) { JS_FreeValue(ctx, promise); goto fail; } /* Note: no need to create 'thrownawayCapability' as in the spec */ for(i = 0; i < 2; i++) resolving_funcs1[i] = JS_UNDEFINED; res = perform_promise_then(ctx, promise, vc(resolving_funcs), vc(resolving_funcs1)); JS_FreeValue(ctx, promise); for(i = 0; i < 2; i++) JS_FreeValue(ctx, resolving_funcs[i]); if (res) goto fail; } } return is_success; } static JSValue js_async_function_resolve_call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags) { JSObject *p = JS_VALUE_GET_OBJ(func_obj); JSAsyncFunctionData *s = p->u.async_function_data; bool is_reject = p->class_id - JS_CLASS_ASYNC_FUNCTION_RESOLVE; JSValueConst arg; if (argc > 0) arg = argv[0]; else arg = JS_UNDEFINED; s->func_state.throw_flag = is_reject; if (is_reject) { JS_Throw(ctx, js_dup(arg)); } else { /* return value of await */ s->func_state.frame.cur_sp[-1] = js_dup(arg); } if (!js_async_function_resume(ctx, s)) return JS_EXCEPTION; return JS_UNDEFINED; } static JSValue js_async_function_call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags) { JSValue promise; JSAsyncFunctionData *s; s = js_mallocz(ctx, sizeof(*s)); if (!s) return JS_EXCEPTION; s->header.ref_count = 1; add_gc_object(ctx->rt, &s->header, JS_GC_OBJ_TYPE_ASYNC_FUNCTION); s->is_active = false; s->resolving_funcs[0] = JS_UNDEFINED; s->resolving_funcs[1] = JS_UNDEFINED; promise = JS_NewPromiseCapability(ctx, s->resolving_funcs); if (JS_IsException(promise)) goto fail; if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { fail: JS_FreeValue(ctx, promise); js_async_function_free(ctx->rt, s); return JS_EXCEPTION; } s->is_active = true; if (!js_async_function_resume(ctx, s)) goto fail; js_async_function_free(ctx->rt, s); return promise; } /* AsyncGenerator */ typedef enum JSAsyncGeneratorStateEnum { JS_ASYNC_GENERATOR_STATE_SUSPENDED_START, JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD, JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR, JS_ASYNC_GENERATOR_STATE_EXECUTING, JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN, JS_ASYNC_GENERATOR_STATE_COMPLETED, } JSAsyncGeneratorStateEnum; typedef struct JSAsyncGeneratorRequest { struct list_head link; /* completion */ int completion_type; /* GEN_MAGIC_x */ JSValue result; /* promise capability */ JSValue promise; JSValue resolving_funcs[2]; } JSAsyncGeneratorRequest; typedef struct JSAsyncGeneratorData { JSObject *generator; /* back pointer to the object (const) */ JSAsyncGeneratorStateEnum state; JSAsyncFunctionState func_state; struct list_head queue; /* list of JSAsyncGeneratorRequest.link */ } JSAsyncGeneratorData; static void js_async_generator_free(JSRuntime *rt, JSAsyncGeneratorData *s) { struct list_head *el, *el1; JSAsyncGeneratorRequest *req; list_for_each_safe(el, el1, &s->queue) { req = list_entry(el, JSAsyncGeneratorRequest, link); JS_FreeValueRT(rt, req->result); JS_FreeValueRT(rt, req->promise); JS_FreeValueRT(rt, req->resolving_funcs[0]); JS_FreeValueRT(rt, req->resolving_funcs[1]); js_free_rt(rt, req); } if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED && s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) { async_func_free(rt, &s->func_state); } js_free_rt(rt, s); } static void js_async_generator_finalizer(JSRuntime *rt, JSValueConst obj) { JSAsyncGeneratorData *s = JS_GetOpaque(obj, JS_CLASS_ASYNC_GENERATOR); if (s) { js_async_generator_free(rt, s); } } static void js_async_generator_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) { JSAsyncGeneratorData *s = JS_GetOpaque(val, JS_CLASS_ASYNC_GENERATOR); struct list_head *el; JSAsyncGeneratorRequest *req; if (s) { list_for_each(el, &s->queue) { req = list_entry(el, JSAsyncGeneratorRequest, link); JS_MarkValue(rt, req->result, mark_func); JS_MarkValue(rt, req->promise, mark_func); JS_MarkValue(rt, req->resolving_funcs[0], mark_func); JS_MarkValue(rt, req->resolving_funcs[1], mark_func); } if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED && s->state != JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN) { async_func_mark(rt, &s->func_state, mark_func); } } } static JSValue js_async_generator_resolve_function(JSContext *ctx, JSValueConst this_obj, int argc, JSValueConst *argv, int magic, JSValueConst *func_data); static int js_async_generator_resolve_function_create(JSContext *ctx, JSValue generator, JSValue *resolving_funcs, bool is_resume_next) { int i; JSValue func; for(i = 0; i < 2; i++) { func = JS_NewCFunctionData(ctx, js_async_generator_resolve_function, 1, i + is_resume_next * 2, 1, vc(&generator)); if (JS_IsException(func)) { if (i == 1) JS_FreeValue(ctx, resolving_funcs[0]); return -1; } resolving_funcs[i] = func; } return 0; } static int js_async_generator_await(JSContext *ctx, JSAsyncGeneratorData *s, JSValue value) { JSValue promise, resolving_funcs[2], resolving_funcs1[2]; int i, res; promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&value), 0); if (JS_IsException(promise)) goto fail; if (js_async_generator_resolve_function_create(ctx, JS_MKPTR(JS_TAG_OBJECT, s->generator), resolving_funcs, false)) { JS_FreeValue(ctx, promise); goto fail; } /* Note: no need to create 'thrownawayCapability' as in the spec */ for(i = 0; i < 2; i++) resolving_funcs1[i] = JS_UNDEFINED; res = perform_promise_then(ctx, promise, vc(resolving_funcs), vc(resolving_funcs1)); JS_FreeValue(ctx, promise); for(i = 0; i < 2; i++) JS_FreeValue(ctx, resolving_funcs[i]); if (res) goto fail; return 0; fail: return -1; } static void js_async_generator_resolve_or_reject(JSContext *ctx, JSAsyncGeneratorData *s, JSValueConst result, int is_reject) { JSAsyncGeneratorRequest *next; JSValue ret; next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link); list_del(&next->link); ret = JS_Call(ctx, next->resolving_funcs[is_reject], JS_UNDEFINED, 1, &result); JS_FreeValue(ctx, ret); JS_FreeValue(ctx, next->result); JS_FreeValue(ctx, next->promise); JS_FreeValue(ctx, next->resolving_funcs[0]); JS_FreeValue(ctx, next->resolving_funcs[1]); js_free(ctx, next); } static void js_async_generator_resolve(JSContext *ctx, JSAsyncGeneratorData *s, JSValueConst value, bool done) { JSValue result; result = js_create_iterator_result(ctx, js_dup(value), done); /* XXX: better exception handling ? */ js_async_generator_resolve_or_reject(ctx, s, result, 0); JS_FreeValue(ctx, result); } static void js_async_generator_reject(JSContext *ctx, JSAsyncGeneratorData *s, JSValueConst exception) { js_async_generator_resolve_or_reject(ctx, s, exception, 1); } static void js_async_generator_complete(JSContext *ctx, JSAsyncGeneratorData *s) { if (s->state != JS_ASYNC_GENERATOR_STATE_COMPLETED) { s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED; async_func_free(ctx->rt, &s->func_state); } } static int js_async_generator_completed_return(JSContext *ctx, JSAsyncGeneratorData *s, JSValue value) { JSValue promise, resolving_funcs[2], resolving_funcs1[2]; int res; // Can fail looking up JS_ATOM_constructor when is_reject==0. promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&value), /*is_reject*/0); // A poisoned .constructor property is observable and the resulting // exception should be delivered to the catch handler. if (JS_IsException(promise)) { JSValue err = JS_GetException(ctx); promise = js_promise_resolve(ctx, ctx->promise_ctor, 1, vc(&err), /*is_reject*/1); JS_FreeValue(ctx, err); if (JS_IsException(promise)) return -1; } if (js_async_generator_resolve_function_create(ctx, JS_MKPTR(JS_TAG_OBJECT, s->generator), resolving_funcs1, true)) { JS_FreeValue(ctx, promise); return -1; } resolving_funcs[0] = JS_UNDEFINED; resolving_funcs[1] = JS_UNDEFINED; res = perform_promise_then(ctx, promise, vc(resolving_funcs1), vc(resolving_funcs)); JS_FreeValue(ctx, resolving_funcs1[0]); JS_FreeValue(ctx, resolving_funcs1[1]); JS_FreeValue(ctx, promise); return res; } static void js_async_generator_resume_next(JSContext *ctx, JSAsyncGeneratorData *s) { JSAsyncGeneratorRequest *next; JSValue func_ret, value; for(;;) { if (list_empty(&s->queue)) break; next = list_entry(s->queue.next, JSAsyncGeneratorRequest, link); switch(s->state) { case JS_ASYNC_GENERATOR_STATE_EXECUTING: /* only happens when restarting execution after await() */ goto resume_exec; case JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN: goto done; case JS_ASYNC_GENERATOR_STATE_SUSPENDED_START: if (next->completion_type == GEN_MAGIC_NEXT) { goto exec_no_arg; } else { js_async_generator_complete(ctx, s); } break; case JS_ASYNC_GENERATOR_STATE_COMPLETED: if (next->completion_type == GEN_MAGIC_NEXT) { js_async_generator_resolve(ctx, s, JS_UNDEFINED, true); } else if (next->completion_type == GEN_MAGIC_RETURN) { s->state = JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN; js_async_generator_completed_return(ctx, s, next->result); } else { js_async_generator_reject(ctx, s, next->result); } goto done; case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD: case JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR: value = js_dup(next->result); if (next->completion_type == GEN_MAGIC_THROW && s->state == JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD) { JS_Throw(ctx, value); s->func_state.throw_flag = true; } else { /* 'yield' returns a value. 'yield *' also returns a value in case the 'throw' method is called */ s->func_state.frame.cur_sp[-1] = value; s->func_state.frame.cur_sp[0] = js_int32(next->completion_type); s->func_state.frame.cur_sp++; exec_no_arg: s->func_state.throw_flag = false; } s->state = JS_ASYNC_GENERATOR_STATE_EXECUTING; resume_exec: func_ret = async_func_resume(ctx, &s->func_state); if (JS_IsException(func_ret)) { value = JS_GetException(ctx); js_async_generator_complete(ctx, s); js_async_generator_reject(ctx, s, value); JS_FreeValue(ctx, value); } else if (JS_VALUE_GET_TAG(func_ret) == JS_TAG_INT) { int func_ret_code, ret; value = s->func_state.frame.cur_sp[-1]; s->func_state.frame.cur_sp[-1] = JS_UNDEFINED; func_ret_code = JS_VALUE_GET_INT(func_ret); switch(func_ret_code) { case FUNC_RET_YIELD: case FUNC_RET_YIELD_STAR: if (func_ret_code == FUNC_RET_YIELD_STAR) s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD_STAR; else s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_YIELD; js_async_generator_resolve(ctx, s, value, false); JS_FreeValue(ctx, value); break; case FUNC_RET_AWAIT: ret = js_async_generator_await(ctx, s, value); JS_FreeValue(ctx, value); if (ret < 0) { /* exception: throw it */ s->func_state.throw_flag = true; goto resume_exec; } goto done; default: abort(); } } else { assert(JS_IsUndefined(func_ret)); /* end of function */ value = s->func_state.frame.cur_sp[-1]; s->func_state.frame.cur_sp[-1] = JS_UNDEFINED; js_async_generator_complete(ctx, s); js_async_generator_resolve(ctx, s, value, true); JS_FreeValue(ctx, value); } break; default: abort(); } } done: ; } static JSValue js_async_generator_resolve_function(JSContext *ctx, JSValueConst this_obj, int argc, JSValueConst *argv, int magic, JSValueConst *func_data) { bool is_reject = magic & 1; JSAsyncGeneratorData *s = JS_GetOpaque(func_data[0], JS_CLASS_ASYNC_GENERATOR); JSValueConst arg = argv[0]; /* XXX: what if s == NULL */ if (magic >= 2) { /* resume next case in AWAITING_RETURN state */ assert(s->state == JS_ASYNC_GENERATOR_STATE_AWAITING_RETURN || s->state == JS_ASYNC_GENERATOR_STATE_COMPLETED); s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED; if (is_reject) { js_async_generator_reject(ctx, s, arg); } else { js_async_generator_resolve(ctx, s, arg, true); } } else { /* restart function execution after await() */ assert(s->state == JS_ASYNC_GENERATOR_STATE_EXECUTING); s->func_state.throw_flag = is_reject; if (is_reject) { JS_Throw(ctx, js_dup(arg)); } else { /* return value of await */ s->func_state.frame.cur_sp[-1] = js_dup(arg); } js_async_generator_resume_next(ctx, s); } return JS_UNDEFINED; } /* magic = GEN_MAGIC_x */ static JSValue js_async_generator_next(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) { JSAsyncGeneratorData *s = JS_GetOpaque(this_val, JS_CLASS_ASYNC_GENERATOR); JSValue promise, resolving_funcs[2]; JSAsyncGeneratorRequest *req; promise = JS_NewPromiseCapability(ctx, resolving_funcs); if (JS_IsException(promise)) return JS_EXCEPTION; if (!s) { JSValue err, res2; JS_ThrowTypeError(ctx, "not an AsyncGenerator object"); err = JS_GetException(ctx); res2 = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, vc(&err)); JS_FreeValue(ctx, err); JS_FreeValue(ctx, res2); JS_FreeValue(ctx, resolving_funcs[0]); JS_FreeValue(ctx, resolving_funcs[1]); return promise; } req = js_mallocz(ctx, sizeof(*req)); if (!req) goto fail; req->completion_type = magic; req->result = js_dup(argv[0]); req->promise = js_dup(promise); req->resolving_funcs[0] = resolving_funcs[0]; req->resolving_funcs[1] = resolving_funcs[1]; list_add_tail(&req->link, &s->queue); if (s->state != JS_ASYNC_GENERATOR_STATE_EXECUTING) { js_async_generator_resume_next(ctx, s); } return promise; fail: JS_FreeValue(ctx, resolving_funcs[0]); JS_FreeValue(ctx, resolving_funcs[1]); JS_FreeValue(ctx, promise); return JS_EXCEPTION; } static JSValue js_async_generator_function_call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv, int flags) { JSValue obj, func_ret; JSAsyncGeneratorData *s; s = js_mallocz(ctx, sizeof(*s)); if (!s) return JS_EXCEPTION; s->state = JS_ASYNC_GENERATOR_STATE_SUSPENDED_START; init_list_head(&s->queue); if (async_func_init(ctx, &s->func_state, func_obj, this_obj, argc, argv)) { s->state = JS_ASYNC_GENERATOR_STATE_COMPLETED; goto fail; } /* execute the function up to 'OP_initial_yield' (no yield nor await are possible) */ func_ret = async_func_resume(ctx, &s->func_state); if (JS_IsException(func_ret)) goto fail; JS_FreeValue(ctx, func_ret); obj = js_create_from_ctor(ctx, func_obj, JS_CLASS_ASYNC_GENERATOR); if (JS_IsException(obj)) goto fail; s->generator = JS_VALUE_GET_OBJ(obj); JS_SetOpaqueInternal(obj, s); return obj; fail: js_async_generator_free(ctx->rt, s); return JS_EXCEPTION; } /* JS parser */ enum { TOK_NUMBER = -128, TOK_STRING, TOK_TEMPLATE, TOK_IDENT, TOK_REGEXP, /* warning: order matters (see js_parse_assign_expr) */ TOK_MUL_ASSIGN, TOK_DIV_ASSIGN, TOK_MOD_ASSIGN, TOK_PLUS_ASSIGN, TOK_MINUS_ASSIGN, TOK_SHL_ASSIGN, TOK_SAR_ASSIGN, TOK_SHR_ASSIGN, TOK_AND_ASSIGN, TOK_XOR_ASSIGN, TOK_OR_ASSIGN, TOK_POW_ASSIGN, TOK_LAND_ASSIGN, TOK_LOR_ASSIGN, TOK_DOUBLE_QUESTION_MARK_ASSIGN, TOK_DEC, TOK_INC, TOK_SHL, TOK_SAR, TOK_SHR, TOK_LT, TOK_LTE, TOK_GT, TOK_GTE, TOK_EQ, TOK_STRICT_EQ, TOK_NEQ, TOK_STRICT_NEQ, TOK_LAND, TOK_LOR, TOK_POW, TOK_ARROW, TOK_ELLIPSIS, TOK_DOUBLE_QUESTION_MARK, TOK_QUESTION_MARK_DOT, TOK_ERROR, TOK_PRIVATE_NAME, TOK_EOF, /* keywords: WARNING: same order as atoms */ TOK_NULL, /* must be first */ TOK_FALSE, TOK_TRUE, TOK_IF, TOK_ELSE, TOK_RETURN, TOK_VAR, TOK_THIS, TOK_DELETE, TOK_VOID, TOK_TYPEOF, TOK_NEW, TOK_IN, TOK_INSTANCEOF, TOK_DO, TOK_WHILE, TOK_FOR, TOK_BREAK, TOK_CONTINUE, TOK_SWITCH, TOK_CASE, TOK_DEFAULT, TOK_THROW, TOK_TRY, TOK_CATCH, TOK_FINALLY, TOK_FUNCTION, TOK_DEBUGGER, TOK_WITH, /* FutureReservedWord */ TOK_CLASS, TOK_CONST, TOK_ENUM, TOK_EXPORT, TOK_EXTENDS, TOK_IMPORT, TOK_SUPER, /* FutureReservedWords when parsing strict mode code */ TOK_IMPLEMENTS, TOK_INTERFACE, TOK_LET, TOK_PACKAGE, TOK_PRIVATE, TOK_PROTECTED, TOK_PUBLIC, TOK_STATIC, TOK_YIELD, TOK_AWAIT, /* must be last */ TOK_OF, /* only used for js_parse_skip_parens_token() */ }; #define TOK_FIRST_KEYWORD TOK_NULL #define TOK_LAST_KEYWORD TOK_AWAIT /* unicode code points */ #define CP_NBSP 0x00a0 #define CP_BOM 0xfeff #define CP_LS 0x2028 #define CP_PS 0x2029 typedef struct BlockEnv { struct BlockEnv *prev; JSAtom label_name; /* JS_ATOM_NULL if none */ int label_break; /* -1 if none */ int label_cont; /* -1 if none */ int drop_count; /* number of stack elements to drop */ int label_finally; /* -1 if none */ int scope_level; uint8_t has_iterator : 1; uint8_t is_regular_stmt : 1; // i.e. not a loop statement } BlockEnv; typedef struct JSGlobalVar { int cpool_idx; /* if >= 0, index in the constant pool for hoisted function defintion*/ uint8_t force_init : 1; /* force initialization to undefined */ uint8_t is_lexical : 1; /* global let/const definition */ uint8_t is_const : 1; /* const definition */ int scope_level; /* scope of definition */ JSAtom var_name; /* variable name */ } JSGlobalVar; typedef struct RelocEntry { struct RelocEntry *next; uint32_t addr; /* address to patch */ int size; /* address size: 1, 2 or 4 bytes */ } RelocEntry; typedef struct JumpSlot { int op; int size; int pos; int label; } JumpSlot; typedef struct LabelSlot { int ref_count; int pos; /* phase 1 address, -1 means not resolved yet */ int pos2; /* phase 2 address, -1 means not resolved yet */ int addr; /* phase 3 address, -1 means not resolved yet */ RelocEntry *first_reloc; } LabelSlot; typedef struct SourceLocSlot { uint32_t pc; int line_num; int col_num; } SourceLocSlot; typedef enum JSParseFunctionEnum { JS_PARSE_FUNC_STATEMENT, JS_PARSE_FUNC_VAR, JS_PARSE_FUNC_EXPR, JS_PARSE_FUNC_ARROW, JS_PARSE_FUNC_GETTER, JS_PARSE_FUNC_SETTER, JS_PARSE_FUNC_METHOD, JS_PARSE_FUNC_CLASS_STATIC_INIT, JS_PARSE_FUNC_CLASS_CONSTRUCTOR, JS_PARSE_FUNC_DERIVED_CLASS_CONSTRUCTOR, } JSParseFunctionEnum; typedef enum JSParseExportEnum { JS_PARSE_EXPORT_NONE, JS_PARSE_EXPORT_NAMED, JS_PARSE_EXPORT_DEFAULT, } JSParseExportEnum; typedef struct JSFunctionDef { JSContext *ctx; struct JSFunctionDef *parent; int parent_cpool_idx; /* index in the constant pool of the parent or -1 if none */ int parent_scope_level; /* scope level in parent at point of definition */ struct list_head child_list; /* list of JSFunctionDef.link */ struct list_head link; bool is_eval; /* true if eval code */ int eval_type; /* only valid if is_eval = true */ bool is_global_var; /* true if variables are not defined locally: eval global, eval module or non strict eval */ bool is_func_expr; /* true if function expression */ bool has_home_object; /* true if the home object is available */ bool has_prototype; /* true if a prototype field is necessary */ bool has_simple_parameter_list; bool has_parameter_expressions; /* if true, an argument scope is created */ bool has_use_strict; /* to reject directive in special cases */ bool has_eval_call; /* true if the function contains a call to eval() */ bool has_arguments_binding; /* true if the 'arguments' binding is available in the function */ bool has_this_binding; /* true if the 'this' and new.target binding are available in the function */ bool new_target_allowed; /* true if the 'new.target' does not throw a syntax error */ bool super_call_allowed; /* true if super() is allowed */ bool super_allowed; /* true if super. or super[] is allowed */ bool arguments_allowed; /* true if the 'arguments' identifier is allowed */ bool is_derived_class_constructor; bool in_function_body; bool backtrace_barrier; JSFunctionKindEnum func_kind : 8; JSParseFunctionEnum func_type : 7; uint8_t is_strict_mode : 1; JSAtom func_name; /* JS_ATOM_NULL if no name */ JSVarDef *vars; uint32_t *vars_htab; // indexes into vars[] int var_size; /* allocated size for vars[] */ int var_count; JSVarDef *args; int arg_size; /* allocated size for args[] */ int arg_count; /* number of arguments */ int defined_arg_count; int var_object_idx; /* -1 if none */ int arg_var_object_idx; /* -1 if none (var object for the argument scope) */ int arguments_var_idx; /* -1 if none */ int arguments_arg_idx; /* argument variable definition in argument scope, -1 if none */ int func_var_idx; /* variable containing the current function (-1 if none, only used if is_func_expr is true) */ int eval_ret_idx; /* variable containing the return value of the eval, -1 if none */ int this_var_idx; /* variable containg the 'this' value, -1 if none */ int new_target_var_idx; /* variable containg the 'new.target' value, -1 if none */ int this_active_func_var_idx; /* variable containg the 'this.active_func' value, -1 if none */ int home_object_var_idx; bool need_home_object; int scope_level; /* index into fd->scopes if the current lexical scope */ int scope_first; /* index into vd->vars of first lexically scoped variable */ int scope_size; /* allocated size of fd->scopes array */ int scope_count; /* number of entries used in the fd->scopes array */ JSVarScope *scopes; JSVarScope def_scope_array[4]; int body_scope; /* scope of the body of the function or eval */ int global_var_count; int global_var_size; JSGlobalVar *global_vars; DynBuf byte_code; int last_opcode_pos; /* -1 if no last opcode */ bool use_short_opcodes; /* true if short opcodes are used in byte_code */ LabelSlot *label_slots; int label_size; /* allocated size for label_slots[] */ int label_count; BlockEnv *top_break; /* break/continue label stack */ /* constant pool (strings, functions, numbers) */ JSValue *cpool; int cpool_count; int cpool_size; /* list of variables in the closure */ int closure_var_count; int closure_var_size; JSClosureVar *closure_var; JumpSlot *jump_slots; int jump_size; int jump_count; SourceLocSlot *source_loc_slots; int source_loc_size; int source_loc_count; int line_number_last; int line_number_last_pc; int col_number_last; /* pc2line table */ JSAtom filename; int line_num; int col_num; DynBuf pc2line; char *source; /* raw source, utf-8 encoded */ int source_len; JSModuleDef *module; /* != NULL when parsing a module */ bool has_await; /* true if await is used (used in module eval) */ } JSFunctionDef; typedef struct JSToken { int val; int line_num; /* line number of token start */ int col_num; /* column number of token start */ const uint8_t *ptr; union { struct { JSValue str; int sep; } str; struct { JSValue val; } num; struct { JSAtom atom; bool has_escape; bool is_reserved; } ident; struct { JSValue body; JSValue flags; } regexp; } u; } JSToken; typedef struct JSParseState { JSContext *ctx; int last_line_num; /* line number of last token */ int last_col_num; /* column number of last token */ int line_num; /* line number of current offset */ int col_num; /* column number of current offset */ const char *filename; JSToken token; bool got_lf; /* true if got line feed before the current token */ const uint8_t *last_ptr; const uint8_t *buf_start; const uint8_t *buf_ptr; const uint8_t *buf_end; const uint8_t *eol; // most recently seen end-of-line character const uint8_t *mark; // first token character, invariant: eol < mark /* current function code */ JSFunctionDef *cur_func; bool is_module; /* parsing a module */ bool allow_html_comments; } JSParseState; typedef struct JSOpCode { #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_* const char *name; #endif uint8_t size; /* in bytes */ /* the opcodes remove n_pop items from the top of the stack, then pushes n_push items */ uint8_t n_pop; uint8_t n_push; uint8_t fmt; } JSOpCode; static const JSOpCode opcode_info[OP_COUNT + (OP_TEMP_END - OP_TEMP_START)] = { #define FMT(f) #ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_* #define DEF(id, size, n_pop, n_push, f) { #id, size, n_pop, n_push, OP_FMT_ ## f }, #else #define DEF(id, size, n_pop, n_push, f) { size, n_pop, n_push, OP_FMT_ ## f }, #endif #include "quickjs-opcode.h" #undef DEF #undef FMT }; /* After the final compilation pass, short opcodes are used. Their opcodes overlap with the temporary opcodes which cannot appear in the final bytecode. Their description is after the temporary opcodes in opcode_info[]. */ #define short_opcode_info(op) \ opcode_info[(op) >= OP_TEMP_START ? \ (op) + (OP_TEMP_END - OP_TEMP_START) : (op)] static void free_token(JSParseState *s, JSToken *token) { switch(token->val) { case TOK_NUMBER: JS_FreeValue(s->ctx, token->u.num.val); break; case TOK_STRING: case TOK_TEMPLATE: JS_FreeValue(s->ctx, token->u.str.str); break; case TOK_REGEXP: JS_FreeValue(s->ctx, token->u.regexp.body); JS_FreeValue(s->ctx, token->u.regexp.flags); break; case TOK_IDENT: case TOK_PRIVATE_NAME: JS_FreeAtom(s->ctx, token->u.ident.atom); break; default: if (token->val >= TOK_FIRST_KEYWORD && token->val <= TOK_LAST_KEYWORD) { JS_FreeAtom(s->ctx, token->u.ident.atom); } break; } } static void __attribute((unused)) dump_token(JSParseState *s, const JSToken *token) { printf("%d:%d ", token->line_num, token->col_num); switch(token->val) { case TOK_NUMBER: { double d; JS_ToFloat64(s->ctx, &d, token->u.num.val); /* no exception possible */ printf("number: %.14g\n", d); } break; case TOK_IDENT: dump_atom: { char buf[ATOM_GET_STR_BUF_SIZE]; printf("ident: '%s'\n", JS_AtomGetStr(s->ctx, buf, sizeof(buf), token->u.ident.atom)); } break; case TOK_STRING: { const char *str; /* XXX: quote the string */ str = JS_ToCString(s->ctx, token->u.str.str); printf("string: '%s'\n", str); JS_FreeCString(s->ctx, str); } break; case TOK_TEMPLATE: { const char *str; str = JS_ToCString(s->ctx, token->u.str.str); printf("template: `%s`\n", str); JS_FreeCString(s->ctx, str); } break; case TOK_REGEXP: { const char *str, *str2; str = JS_ToCString(s->ctx, token->u.regexp.body); str2 = JS_ToCString(s->ctx, token->u.regexp.flags); printf("regexp: '%s' '%s'\n", str, str2); JS_FreeCString(s->ctx, str); JS_FreeCString(s->ctx, str2); } break; case TOK_EOF: printf("eof\n"); break; default: if (s->token.val >= TOK_NULL && s->token.val <= TOK_LAST_KEYWORD) { goto dump_atom; } else if (s->token.val >= 256) { printf("token: %d\n", token->val); } else { printf("token: '%c'\n", token->val); } break; } } int JS_PRINTF_FORMAT_ATTR(2, 3) js_parse_error(JSParseState *s, JS_PRINTF_FORMAT const char *fmt, ...) { JSContext *ctx = s->ctx; va_list ap; int backtrace_flags; va_start(ap, fmt); JS_ThrowError2(ctx, JS_SYNTAX_ERROR, false, fmt, ap); va_end(ap); backtrace_flags = 0; if (s->cur_func && s->cur_func->backtrace_barrier) backtrace_flags = JS_BACKTRACE_FLAG_SINGLE_LEVEL; build_backtrace(ctx, ctx->rt->current_exception, JS_UNDEFINED, s->filename, s->line_num, s->col_num, backtrace_flags); return -1; } #ifndef QJS_DISABLE_PARSER static __exception int next_token(JSParseState *s); static int js_parse_expect(JSParseState *s, int tok) { char buf[ATOM_GET_STR_BUF_SIZE]; if (s->token.val == tok) return next_token(s); switch(s->token.val) { case TOK_EOF: return js_parse_error(s, "Unexpected end of input"); case TOK_NUMBER: return js_parse_error(s, "Unexpected number"); case TOK_STRING: return js_parse_error(s, "Unexpected string"); case TOK_TEMPLATE: return js_parse_error(s, "Unexpected string template"); case TOK_REGEXP: return js_parse_error(s, "Unexpected regexp"); case TOK_IDENT: return js_parse_error(s, "Unexpected identifier '%s'", JS_AtomGetStr(s->ctx, buf, sizeof(buf), s->token.u.ident.atom)); case TOK_ERROR: return js_parse_error(s, "Invalid or unexpected token"); default: return js_parse_error(s, "Unexpected token '%.*s'", (int)(s->buf_ptr - s->token.ptr), (const char *)s->token.ptr); } } static int js_parse_expect_semi(JSParseState *s) { if (s->token.val != ';') { /* automatic insertion of ';' */ if (s->token.val == TOK_EOF || s->token.val == '}' || s->got_lf) { return 0; } return js_parse_error(s, "expecting '%c'", ';'); } return next_token(s); } static int js_parse_error_reserved_identifier(JSParseState *s) { char buf1[ATOM_GET_STR_BUF_SIZE]; return js_parse_error(s, "'%s' is a reserved identifier", JS_AtomGetStr(s->ctx, buf1, sizeof(buf1), s->token.u.ident.atom)); } static __exception int js_parse_template_part(JSParseState *s, const uint8_t *p) { const uint8_t *p_next; uint32_t c; StringBuffer b_s, *b = &b_s; JSValue str; /* p points to the first byte of the template part */ if (string_buffer_init(s->ctx, b, 32)) goto fail; for(;;) { if (p >= s->buf_end) goto unexpected_eof; c = *p++; if (c == '`') { /* template end part */ break; } if (c == '$' && *p == '{') { /* template start or middle part */ p++; break; } if (c == '\\') { if (string_buffer_putc8(b, c)) goto fail; if (p >= s->buf_end) goto unexpected_eof; c = *p++; } /* newline sequences are normalized as single '\n' bytes */ if (c == '\r') { if (*p == '\n') p++; c = '\n'; } if (c == '\n') { s->line_num++; s->eol = &p[-1]; s->mark = p; } else if (c >= 0x80) { c = utf8_decode(p - 1, &p_next); if (p_next == p) { js_parse_error(s, "invalid UTF-8 sequence"); goto fail; } p = p_next; } if (string_buffer_putc(b, c)) goto fail; } str = string_buffer_end(b); if (JS_IsException(str)) return -1; s->token.val = TOK_TEMPLATE; s->token.u.str.sep = c; s->token.u.str.str = str; s->buf_ptr = p; return 0; unexpected_eof: js_parse_error(s, "unexpected end of string"); fail: string_buffer_free(b); return -1; } static __exception int js_parse_string(JSParseState *s, int sep, bool do_throw, const uint8_t *p, JSToken *token, const uint8_t **pp) { const uint8_t *p_next; int ret; uint32_t c; StringBuffer b_s, *b = &b_s; JSValue str; /* string */ if (string_buffer_init(s->ctx, b, 32)) goto fail; for(;;) { if (p >= s->buf_end) goto invalid_char; c = *p; if (c < 0x20) { if (sep == '`') { if (c == '\r') { if (p[1] == '\n') p++; c = '\n'; } /* do not update s->line_num */ } else if (c == '\n' || c == '\r') goto invalid_char; } p++; if (c == sep) break; if (c == '$' && *p == '{' && sep == '`') { /* template start or middle part */ p++; break; } if (c == '\\') { c = *p; switch(c) { case '\0': if (p >= s->buf_end) { if (sep != '`') goto invalid_char; if (do_throw) js_parse_error(s, "Unexpected end of input"); goto fail; } p++; break; case '\'': case '\"': case '\\': p++; break; case '\r': /* accept DOS and MAC newline sequences */ if (p[1] == '\n') { p++; } /* fall thru */ case '\n': /* ignore escaped newline sequence */ p++; if (sep != '`') { s->line_num++; s->eol = &p[-1]; s->mark = p; } continue; default: if (c == '0' && !(p[1] >= '0' && p[1] <= '9')) { /* accept isolated \0 */ p++; c = '\0'; } else if ((c >= '0' && c <= '9') && (s->cur_func->is_strict_mode || sep == '`')) { if (do_throw) { js_parse_error(s, "%s are not allowed in %s", (c >= '8') ? "\\8 and \\9" : "Octal escape sequences", (sep == '`') ? "template strings" : "strict mode"); } goto fail; } else if (c >= 0x80) { c = utf8_decode(p, &p_next); if (p_next == p + 1) { goto invalid_utf8; } p = p_next; /* LS or PS are skipped */ if (c == CP_LS || c == CP_PS) continue; } else { ret = lre_parse_escape(&p, true); if (ret == -1) { if (do_throw) { js_parse_error(s, "Invalid %s escape sequence", c == 'u' ? "Unicode" : "hexadecimal"); } goto fail; } else if (ret < 0) { /* ignore the '\' (could output a warning) */ p++; } else { c = ret; } } break; } } else if (c >= 0x80) { c = utf8_decode(p - 1, &p_next); if (p_next == p) goto invalid_utf8; p = p_next; } if (string_buffer_putc(b, c)) goto fail; } str = string_buffer_end(b); if (JS_IsException(str)) return -1; token->val = TOK_STRING; token->u.str.sep = c; token->u.str.str = str; *pp = p; return 0; invalid_utf8: if (do_throw) js_parse_error(s, "invalid UTF-8 sequence"); goto fail; invalid_char: if (do_throw) js_parse_error(s, "unexpected end of string"); fail: string_buffer_free(b); return -1; } static inline bool token_is_pseudo_keyword(JSParseState *s, JSAtom atom) { return s->token.val == TOK_IDENT && s->token.u.ident.atom == atom && !s->token.u.ident.has_escape; } static __exception int js_parse_regexp(JSParseState *s) { const uint8_t *p, *p_next; bool in_class; StringBuffer b_s, *b = &b_s; StringBuffer b2_s, *b2 = &b2_s; uint32_t c; JSValue body_str, flags_str; p = s->buf_ptr; p++; in_class = false; if (string_buffer_init(s->ctx, b, 32)) return -1; if (string_buffer_init(s->ctx, b2, 1)) goto fail; for(;;) { if (p >= s->buf_end) { eof_error: js_parse_error(s, "unexpected end of regexp"); goto fail; } c = *p++; if (c == '\n' || c == '\r') { goto eol_error; } else if (c == '/') { if (!in_class) break; } else if (c == '[') { in_class = true; } else if (c == ']') { /* XXX: incorrect as the first character in a class */ in_class = false; } else if (c == '\\') { if (string_buffer_putc8(b, c)) goto fail; c = *p++; if (c == '\n' || c == '\r') goto eol_error; else if (c == '\0' && p >= s->buf_end) goto eof_error; else if (c >= 0x80) { c = utf8_decode(p - 1, &p_next); if (p_next == p) { goto invalid_utf8; } p = p_next; if (c == CP_LS || c == CP_PS) goto eol_error; } } else if (c >= 0x80) { c = utf8_decode(p - 1, &p_next); if (p_next == p) { invalid_utf8: js_parse_error(s, "invalid UTF-8 sequence"); goto fail; } p = p_next; /* LS or PS are considered as line terminator */ if (c == CP_LS || c == CP_PS) { eol_error: js_parse_error(s, "unexpected line terminator in regexp"); goto fail; } } if (string_buffer_putc(b, c)) goto fail; } /* flags */ for(;;) { c = utf8_decode(p, &p_next); /* no need to test for invalid UTF-8, 0xFFFD is not ident_next */ if (!lre_js_is_ident_next(c)) break; if (string_buffer_putc(b2, c)) goto fail; p = p_next; } body_str = string_buffer_end(b); flags_str = string_buffer_end(b2); if (JS_IsException(body_str) || JS_IsException(flags_str)) { JS_FreeValue(s->ctx, body_str); JS_FreeValue(s->ctx, flags_str); return -1; } s->token.val = TOK_REGEXP; s->token.u.regexp.body = body_str; s->token.u.regexp.flags = flags_str; s->buf_ptr = p; return 0; fail: string_buffer_free(b); string_buffer_free(b2); return -1; } #endif // QJS_DISABLE_PARSER static __exception int ident_realloc(JSContext *ctx, char **pbuf, size_t *psize, char *static_buf) { char *buf, *new_buf; size_t size, new_size; buf = *pbuf; size = *psize; if (size >= (SIZE_MAX / 3) * 2) new_size = SIZE_MAX; else new_size = size + (size >> 1); if (buf == static_buf) { new_buf = js_malloc(ctx, new_size); if (!new_buf) return -1; memcpy(new_buf, buf, size); } else { new_buf = js_realloc(ctx, buf, new_size); if (!new_buf) return -1; } *pbuf = new_buf; *psize = new_size; return 0; } #ifndef QJS_DISABLE_PARSER /* convert a TOK_IDENT to a keyword when needed */ static void update_token_ident(JSParseState *s) { if (s->token.u.ident.atom <= JS_ATOM_LAST_KEYWORD || (s->token.u.ident.atom <= JS_ATOM_LAST_STRICT_KEYWORD && s->cur_func->is_strict_mode) || (s->token.u.ident.atom == JS_ATOM_yield && ((s->cur_func->func_kind & JS_FUNC_GENERATOR) || (s->cur_func->func_type == JS_PARSE_FUNC_ARROW && !s->cur_func->in_function_body && s->cur_func->parent && (s->cur_func->parent->func_kind & JS_FUNC_GENERATOR)))) || (s->token.u.ident.atom == JS_ATOM_await && (s->is_module || (s->cur_func->func_kind & JS_FUNC_ASYNC) || s->cur_func->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT || (s->cur_func->func_type == JS_PARSE_FUNC_ARROW && !s->cur_func->in_function_body && s->cur_func->parent && ((s->cur_func->parent->func_kind & JS_FUNC_ASYNC) || s->cur_func->parent->func_type == JS_PARSE_FUNC_CLASS_STATIC_INIT))))) { if (s->token.u.ident.has_escape) { s->token.u.ident.is_reserved = true; s->token.val = TOK_IDENT; } else { /* The keywords atoms are pre allocated */ s->token.val = s->token.u.ident.atom - 1 + TOK_FIRST_KEYWORD; } } } /* if the current token is an identifier or keyword, reparse it according to the current function type */ static void reparse_ident_token(JSParseState *s) { if (s->token.val == TOK_IDENT || (s->token.val >= TOK_FIRST_KEYWORD && s->token.val <= TOK_LAST_KEYWORD)) { s->token.val = TOK_IDENT; s->token.u.ident.is_reserved = false; update_token_ident(s); } } /* 'c' is the first character. Return JS_ATOM_NULL in case of error */ static JSAtom parse_ident(JSParseState *s, const uint8_t **pp, bool *pident_has_escape, int c, bool is_private) { const uint8_t *p, *p_next; char ident_buf[128], *buf; size_t ident_size, ident_pos; JSAtom atom = JS_ATOM_NULL; p = *pp; buf = ident_buf; ident_size = sizeof(ident_buf); ident_pos = 0; if (is_private) buf[ident_pos++] = '#'; for(;;) { if (c < 0x80) { buf[ident_pos++] = c; } else { ident_pos += utf8_encode((uint8_t*)buf + ident_pos, c); } c = *p; p_next = p + 1; if (c == '\\' && *p_next == 'u') { c = lre_parse_escape(&p_next, true); *pident_has_escape = true; } else if (c >= 0x80) { c = utf8_decode(p, &p_next); /* no need to test for invalid UTF-8, 0xFFFD is not ident_next */ } if (!lre_js_is_ident_next(c)) break; p = p_next; if (unlikely(ident_pos >= ident_size - UTF8_CHAR_LEN_MAX)) { if (ident_realloc(s->ctx, &buf, &ident_size, ident_buf)) goto done; } } /* buf is pure ASCII or UTF-8 encoded */ atom = JS_NewAtomLen(s->ctx, buf, ident_pos); done: if (unlikely(buf != ident_buf)) js_free(s->ctx, buf); *pp = p; return atom; } static __exception int next_token(JSParseState *s) { const uint8_t *p, *p_next; int c; bool ident_has_escape; JSAtom atom; if (js_check_stack_overflow(s->ctx->rt, 1000)) { JS_ThrowStackOverflow(s->ctx); return -1; } free_token(s, &s->token); p = s->last_ptr = s->buf_ptr; s->got_lf = false; s->last_line_num = s->token.line_num; s->last_col_num = s->token.col_num; redo: s->token.line_num = s->line_num; s->token.col_num = s->col_num; s->token.ptr = p; c = *p; switch(c) { case 0: if (p >= s->buf_end) { s->token.val = TOK_EOF; } else { goto def_token; } break; case '`': if (js_parse_template_part(s, p + 1)) goto fail; p = s->buf_ptr; break; case '\'': case '\"': if (js_parse_string(s, c, true, p + 1, &s->token, &p)) goto fail; break; case '\r': /* accept DOS and MAC newline sequences */ if (p[1] == '\n') { p++; } /* fall thru */ case '\n': p++; line_terminator: s->eol = &p[-1]; s->mark = p; s->got_lf = true; s->line_num++; goto redo; case '\f': case '\v': case ' ': case '\t': s->mark = ++p; goto redo; case '/': if (p[1] == '*') { /* comment */ p += 2; for(;;) { if (*p == '\0' && p >= s->buf_end) { js_parse_error(s, "unexpected end of comment"); goto fail; } if (p[0] == '*' && p[1] == '/') { p += 2; break; } if (*p == '\n') { s->line_num++; s->got_lf = true; /* considered as LF for ASI */ s->eol = p++; s->mark = p; } else if (*p == '\r') { s->got_lf = true; /* considered as LF for ASI */ p++; } else if (*p >= 0x80) { c = utf8_decode(p, &p); /* ignore invalid UTF-8 in comments */ if (c == CP_LS || c == CP_PS) { s->got_lf = true; /* considered as LF for ASI */ } } else { p++; } } s->mark = p; goto redo; } else if (p[1] == '/') { /* line comment */ p += 2; skip_line_comment: for(;;) { if (*p == '\0' && p >= s->buf_end) break; if (*p == '\r' || *p == '\n') break; if (*p >= 0x80) { c = utf8_decode(p, &p); /* ignore invalid UTF-8 in comments */ /* LS or PS are considered as line terminator */ if (c == CP_LS || c == CP_PS) { break; } } else { p++; } } s->mark = p; goto redo; } else if (p[1] == '=') { p += 2; s->token.val = TOK_DIV_ASSIGN; } else { p++; s->token.val = c; } break; case '\\': if (p[1] == 'u') { const uint8_t *p1 = p + 1; int c1 = lre_parse_escape(&p1, true); if (c1 >= 0 && lre_js_is_ident_first(c1)) { c = c1; p = p1; ident_has_escape = true; goto has_ident; } else { /* XXX: syntax error? */ } } goto def_token; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case '$': /* identifier */ s->mark = p; p++; ident_has_escape = false; has_ident: atom = parse_ident(s, &p, &ident_has_escape, c, false); if (atom == JS_ATOM_NULL) goto fail; s->token.u.ident.atom = atom; s->token.u.ident.has_escape = ident_has_escape; s->token.u.ident.is_reserved = false; s->token.val = TOK_IDENT; update_token_ident(s); break; case '#': /* private name */ { p++; c = *p; p_next = p + 1; if (c == '\\' && *p_next == 'u') { c = lre_parse_escape(&p_next, true); } else if (c >= 0x80) { c = utf8_decode(p, &p_next); if (p_next == p + 1) goto invalid_utf8; } if (!lre_js_is_ident_first(c)) { js_parse_error(s, "invalid first character of private name"); goto fail; } p = p_next; ident_has_escape = false; /* not used */ atom = parse_ident(s, &p, &ident_has_escape, c, true); if (atom == JS_ATOM_NULL) goto fail; s->token.u.ident.atom = atom; s->token.val = TOK_PRIVATE_NAME; } break; case '.': if (p[1] == '.' && p[2] == '.') { p += 3; s->token.val = TOK_ELLIPSIS; break; } if (p[1] >= '0' && p[1] <= '9') { goto parse_number; } else { goto def_token; } break; case '0': /* in strict mode, octal literals are not accepted */ if (is_digit(p[1]) && (s->cur_func->is_strict_mode)) { js_parse_error(s, "Octal literals are not allowed in strict mode"); goto fail; } goto parse_number; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* number */ parse_number: { JSValue ret; const uint8_t *p1; int flags; flags = ATOD_ACCEPT_BIN_OCT | ATOD_ACCEPT_LEGACY_OCTAL | ATOD_ACCEPT_UNDERSCORES | ATOD_ACCEPT_SUFFIX; ret = js_atof(s->ctx, (const char *)p, (const char **)&p, 0, flags); if (JS_IsException(ret)) goto fail; /* reject `10instanceof Number` */ if (JS_VALUE_IS_NAN(ret) || lre_js_is_ident_next(utf8_decode(p, &p1))) { JS_FreeValue(s->ctx, ret); js_parse_error(s, "invalid number literal"); goto fail; } s->token.val = TOK_NUMBER; s->token.u.num.val = ret; } break; case '*': if (p[1] == '=') { p += 2; s->token.val = TOK_MUL_ASSIGN; } else if (p[1] == '*') { if (p[2] == '=') { p += 3; s->token.val = TOK_POW_ASSIGN; } else { p += 2; s->token.val = TOK_POW; } } else { goto def_token; } break; case '%': if (p[1] == '=') { p += 2; s->token.val = TOK_MOD_ASSIGN; } else { goto def_token; } break; case '+': if (p[1] == '=') { p += 2; s->token.val = TOK_PLUS_ASSIGN; } else if (p[1] == '+') { p += 2; s->token.val = TOK_INC; } else { goto def_token; } break; case '-': if (p[1] == '=') { p += 2; s->token.val = TOK_MINUS_ASSIGN; } else if (p[1] == '-') { if (s->allow_html_comments && p[2] == '>' && (s->got_lf || s->last_ptr == s->buf_start)) { /* Annex B: `-->` at beginning of line is an html comment end. It extends to the end of the line. */ goto skip_line_comment; } p += 2; s->token.val = TOK_DEC; } else { goto def_token; } break; case '<': if (p[1] == '=') { p += 2; s->token.val = TOK_LTE; } else if (p[1] == '<') { if (p[2] == '=') { p += 3; s->token.val = TOK_SHL_ASSIGN; } else { p += 2; s->token.val = TOK_SHL; } } else if (s->allow_html_comments && p[1] == '!' && p[2] == '-' && p[3] == '-') { /* Annex B: handle ` QuickJSR/inst/doc/working_with_js_types.Rmd0000644000176200001440000000676115122664674020555 0ustar liggesusers--- title: "Working with R and JS Types" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with R and JS Types} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(QuickJSR) ``` ## Mappings and Conversions Between R and JS Types `QuickJSR` uses the respective `C` APIs of `R` and `QuickJS` in order to pass values between the two. This allows for increased efficiency in passing and returning values (as no serialisation or de-serialisation is required) and also allows for greater flexibility in working with R closures, functions, and environments in JS code. `QuickJSR` aims to broadly follow the conventions of `jsonlite` in terms of how R types are converted to JS types and vice-versa. ### Primitive & Scalar Types The following table outlines the basic mappings of primitive types between R and JS types: | R Type | JS Type | |--------|---------| | NULL | null | | logical| boolean | | integer| number | | double | number | | character| string| | date | date | | POSIXct| date | | factor | string | Note that the handling of `Date`/`POSIXct` types differs from `jsonlite`, where they are converted to strings. In `QuickJSR`, they are treated directly as `Date` objects in JS. ### Container Types The following table outlines the basic mappings of container types between R and JS types: | R Type | JS Type | |--------|---------| | named list | object | | unnamed list | array | | vector | array | | array | array | | matrix | 2D number array | | data.frame | array of objects | Examples of the `matrix` and `data.frame` conversions are shown below: ```{r} m <- matrix(1:6, nrow = 2) cat(to_json(m)) ``` ```{r} df <- data.frame(a = 1:3, b = c("x", "y", "z")) cat(to_json(df)) ``` Note that the `to_json()` function operates by converting R objects to their JS equivalents, and then calling `JSON.stringify()` on the result. This allows you to explore how different types are being converted to JS. ### Functions and Closures Functions and closures can be passed between R and JS code. In JS, functions are represented as `Function` objects, and can be called directly from JS code. ```{r} ctx <- JSContext$new() ctx$source(code = "function callRFunction(f, x, y) { return f(x, y); }") ctx$call("callRFunction", function(x, y) x + y, 1, 2) ctx$call("callRFunction", function(x, y) paste0(x, ",", y), "a", "b") ``` ## Working with R Environments R environments are represented in JS as a custom class: `REnv`. The `REnv` class simply wraps the pointer to the R environment, and provides methods for getting and setting values - this means that there is only a 'cost' for conversion when values or accessed or updated. Environment values can be accessed using either `env.value` or `env["value"]` syntax: ```{r} ctx$source(code = 'function env_test(env) { return env.a + env["b"]; }') env <- new.env() env$a <- 1 env$b <- 2 ctx$call("env_test", env) ``` Values in the environment can also be updated from JS code: ```{r} ctx$source(code = "function env_update(env) { env.a = 10; env.b = 20; }") ctx$call("env_update", env) env$a env$b ``` ## Accessing Package Namespaces & Functions `QuickJSR` automatically adds a global object `R` to each context, which can be used to access the namespaces of installed packages - and subsequently extract and use functions and objects from them. ```{r} qjs_eval('R.package("base").getwd()') ```QuickJSR/inst/doc/working_with_js_types.R0000644000176200001440000000251215135347454020220 0ustar liggesusers## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(QuickJSR) ## ----------------------------------------------------------------------------- m <- matrix(1:6, nrow = 2) cat(to_json(m)) ## ----------------------------------------------------------------------------- df <- data.frame(a = 1:3, b = c("x", "y", "z")) cat(to_json(df)) ## ----------------------------------------------------------------------------- ctx <- JSContext$new() ctx$source(code = "function callRFunction(f, x, y) { return f(x, y); }") ctx$call("callRFunction", function(x, y) x + y, 1, 2) ctx$call("callRFunction", function(x, y) paste0(x, ",", y), "a", "b") ## ----------------------------------------------------------------------------- ctx$source(code = 'function env_test(env) { return env.a + env["b"]; }') env <- new.env() env$a <- 1 env$b <- 2 ctx$call("env_test", env) ## ----------------------------------------------------------------------------- ctx$source(code = "function env_update(env) { env.a = 10; env.b = 20; }") ctx$call("env_update", env) env$a env$b ## ----------------------------------------------------------------------------- qjs_eval('R.package("base").getwd()') QuickJSR/inst/tinytest/0000755000176200001440000000000015122664674014562 5ustar liggesusersQuickJSR/inst/tinytest/test_to_json_dataframe.R0000644000176200001440000000112115122664674021416 0ustar liggesuserstest <- data.frame(foo=1:2) expect_equal(to_json(test), '[{"foo":1},{"foo":2}]'); test <- data.frame(foo=1:2) expect_equal(to_json(test), '[{"foo":1},{"foo":2}]'); test <- data.frame(foo=1:2, bar=data.frame(x=123:123)) test <- data.frame(foo=1:2, bar=123:124) rownames(test) <- c("a", "b") expect_equal(to_json(test), '[{"foo":1,"bar":123,"_row":"a"},{"foo":2,"bar":124,"_row":"b"}]'); test <- data.frame(foo=1:2) test$bar <- list(x=123, y=123) test$baz <- data.frame(z=456:457) expect_equal(to_json(test), '[{"foo":1,"bar":[123],"baz":{"z":456}},{"foo":2,"bar":[123],"baz":{"z":457}}]'); QuickJSR/inst/tinytest/test_JSContext.R0000644000176200001440000000301615122664674017625 0ustar liggesusers jsc <- JSContext$new() jsc$source(code = "function add_test(x, y) { return x + y; }") expect_true(jsc$validate("add_test")) expect_equal(jsc$call("add_test", 1, 2), 3) expect_equal(jsc$call("add_test", 1, "a"), "1a") js_file <- tempfile(fileext = ".js") writeLines("function mult_test(x, y) { return x * y; }", con = js_file) jsc$source(file = js_file) expect_true(jsc$validate("mult_test")) expect_equal(jsc$call("mult_test", 1, 2), 2) expect_equal(jsc$call("mult_test", 10, 15), 150) # Test that R functions can be passed and evaluated in JS jsc$source(code = "function fun_test(f, x, y) { return f(x, y); }") expect_equal(jsc$call("fun_test", function(x, y){ x + y }, 1, 2), 3) # Test that closures/captures work a <- 3 expect_equal(jsc$call("fun_test", function(x, y){ (x + y) * a }, 1, 2), 9) expect_equal(jsc$call("fun_test", function(x, y){ paste(x, y) }, "a", "b"), "a b") # Test that R environments can be passed to JS and values accessed jsc$source(code = "function env_test(env) { return env.a + env.b; }") env <- new.env() env$a <- 1 env$b <- 2 expect_equal(jsc$call("env_test", env), 3) # Test JS functions can update values in R environments jsc$source(code = "function env_update(env) { env.a = 10; env.b = 20; }") jsc$call("env_update", env) expect_equal(env$a, 10) expect_equal(env$b, 20) # Fails on 3.6 CI, but can't be replicated locally exit_if_not(R.version$major > "3") jsc$source(code = 'function r_fun_test1() { return R.package("base")["Sys.Date"]() }') expect_equal(as.Date(jsc$call("r_fun_test1")), Sys.Date()) QuickJSR/inst/tinytest/test_qjs_eval.R0000644000176200001440000000044215122664674017550 0ustar liggesusers expect_equal(1, qjs_eval("1")) expect_equal(2.5, qjs_eval("1 + 1.5")) expect_equal("Hello World!", qjs_eval("'Hello World!'")) expect_equal("Hello World!", qjs_eval("'Hello' + ' ' + 'World!'")) expect_equal(list(a = 1, b = "2"), qjs_eval("var t = {'a' : 1, 'b' : '2'}; t")) QuickJSR/inst/tinytest/test_to_json_date.R0000644000176200001440000000113115122664674020410 0ustar liggesusers# Fails on 3.6 CI, but can't be replicated locally exit_if_not(R.version$major > "3") object <- as.Date("1985-06-18"); expect_equal(to_json(object), "[\"1985-06-18T00:00:00.000Z\"]"); expect_equal(to_json(list(object)), "[[\"1985-06-18T00:00:00.000Z\"]]"); expect_equal(to_json(data.frame(foo=object)), "[{\"foo\":\"1985-06-18T00:00:00.000Z\"}]"); expect_equal(to_json(list(foo=data.frame(bar=object))), "{\"foo\":[{\"bar\":\"1985-06-18T00:00:00.000Z\"}]}"); object <- as.POSIXct("1985-06-18 12:34:56"); expect_equal(to_json(object), "[\"1985-06-18T12:34:56.000Z\"]"); QuickJSR/inst/tinytest/test_to_json_factor.R0000644000176200001440000000041115122664674020751 0ustar liggesusersfactor_var <- iris$Species factor_var_json <- paste0("[\"", paste0(as.character(factor_var), collapse="\",\""), "\"]") expect_equal(to_json(factor_var), factor_var_json) expect_equal(to_json(factor_var[1], auto_unbox=TRUE), "\"setosa\"") QuickJSR/inst/tinytest/test_to_json_matrix.R0000644000176200001440000000071615122664674021007 0ustar liggesusersempty_matrix <- matrix(nrow = 0, ncol = 0) expect_equal(to_json(empty_matrix), "[]") numeric_matrix <- matrix(1:6, nrow = 2, ncol = 3) expect_equal(to_json(numeric_matrix), "[[1,3,5],[2,4,6]]") character_matrix <- matrix(letters[1:6], nrow = 2, ncol = 3) expect_equal(to_json(character_matrix), "[[\"a\",\"c\",\"e\"],[\"b\",\"d\",\"f\"]]") logical_matrix <- matrix(c(TRUE, FALSE), nrow = 2, ncol = 1) expect_equal(to_json(logical_matrix), "[[true],[false]]") QuickJSR/inst/tinytest/test_data_conversion.R0000644000176200001440000000645415122664674021133 0ustar liggesusersexpect_equal(to_json(1), "[1]") expect_equal(to_json(c(NA, 1:3, NA)), "[null,1,2,3,null]") expect_equal(to_json(c(NA, 1.5, NA, 2.5)), "[null,1.5,null,2.5]") expect_equal(to_json("a"), "[\"a\"]") expect_equal(to_json(c("a", "b", NA, "c")), "[\"a\",\"b\",null,\"c\"]") expect_equal(to_json(TRUE), "[true]") expect_equal(to_json(FALSE), "[false]") expect_equal(to_json(c(TRUE, NA, FALSE)), "[true,null,false]") expect_equal(to_json(list(1, 2, 3, NA)), "[[1],[2],[3],[null]]") expect_equal(to_json(list(a = 1, b = 2, c = NA, d = 3)), "{\"a\":[1],\"b\":[2],\"c\":[null],\"d\":[3]}") expect_equal(to_json(list(a = "d", b = "e", c = "f")), "{\"a\":[\"d\"],\"b\":[\"e\"],\"c\":[\"f\"]}") expect_equal(to_json(list(c(1, 2), c(3, 4))), "[[1,2],[3,4]]") expect_equal(to_json(list(list(1, 2), list(3, 4))), "[[[1],[2]],[[3],[4]]]") expect_equal(to_json(list(list(a = 1, b = 2), list(c = 3, d = 4))), "[{\"a\":[1],\"b\":[2]},{\"c\":[3],\"d\":[4]}]") expect_equal(to_json(list(c("e", "f"), c("g", "h"))), "[[\"e\",\"f\"],[\"g\",\"h\"]]") expect_equal(to_json(list(list("e", "f"), list("g", "h"))), "[[[\"e\"],[\"f\"]],[[\"g\"],[\"h\"]]]") expect_equal(to_json(list(list(a = "e", b = "f"), list(c = "g", d = "h"))), "[{\"a\":[\"e\"],\"b\":[\"f\"]},{\"c\":[\"g\"],\"d\":[\"h\"]}]") expect_equal(1, from_json("[1]")) expect_equal(1:3, from_json("[1,2,3]")) expect_equal(c(1.5, 2.5), from_json("[1.5,2.5]")) expect_equal("a", from_json("[\"a\"]")) expect_equal(c("a", "b", "c"), from_json("[\"a\",\"b\",\"c\"]")) expect_equal(TRUE, from_json("[true]")) expect_equal(FALSE, from_json("[false]")) expect_equal(c(TRUE, FALSE), from_json("[true,false]")) # Mixed-Type Conversions expect_equal(c(1, 1), from_json("[1,true]")) expect_equal(c(1.5, 1.0), from_json("[1.5,true]")) expect_equal(c(1, "a"), from_json("[1,\"a\"]")) expect_equal(c(1.2, 1.0), from_json("[1.2,1]")) expect_equal(c("1", "a", "TRUE"), from_json("[1,\"a\",true]")) expect_equal(c("1.5", "TRUE", "a", "1"), from_json("[1.5,true,\"a\",1]")) expect_equal(matrix(1:3, ncol=1), from_json("[[1],[2],[3]]")) expect_equal(matrix(1:6, ncol=2), from_json("[[1,4],[2,5],[3,6]]")) expect_equal(list(1,c(2,3)), from_json("[[1],[2,3]]")) expect_equal(list(1,c(2,3),list(3,c(4,5))), from_json("[[1],[2,3],[3,[4,5]]]")) expect_equal(list(a = 1, b = 2, c = 3), from_json("{\"a\":[1],\"b\":[2],\"c\":[3]}")) expect_equal(list(a = "d", b = "e", c = "f"), from_json("{\"a\":[\"d\"],\"b\":[\"e\"],\"c\":[\"f\"]}")) expect_equal(list(list(a = 1, b = 2), list(c = 3, d = 4)), from_json("[{\"a\":[1],\"b\":[2]},{\"c\":[3],\"d\":[4]}]")) expect_equal(list(c("e", "f"), c("g", "h")), from_json("[[\"e\",\"f\"],[\"g\",\"h\"]]")) expect_equal(list(list("e", "f"), list("g", "h")), from_json("[[[\"e\"],[\"f\"]],[[\"g\"],[\"h\"]]]")) expect_equal(list(list(a = "e", b = "f"), list(c = "g", d = "h")), from_json("[{\"a\":[\"e\"],\"b\":[\"f\"]},{\"c\":[\"g\"],\"d\":[\"h\"]}]")) # NULL conversions expect_equal(NULL, from_json("null")) expect_equal(NA, from_json("[null]")) expect_equal(c(NA, 1), from_json("[null, 1]")) expect_equal(c(1, NA, 1), from_json("[1, null, 1]")) expect_equal("[null]", to_json(NULL)) expect_equal("null", to_json(NULL, auto_unbox = TRUE)) expect_equal("[null]", to_json(NA)) expect_equal("null", to_json(NA, auto_unbox = TRUE)) QuickJSR/inst/tinytest/test_to_json_asis.R0000644000176200001440000000100015122664674020425 0ustar liggesusersexpect_equal(to_json(list(1), auto_unbox=TRUE), "[1]"); expect_equal(to_json(list(I(1)), auto_unbox=TRUE), "[[1]]"); expect_equal(to_json(I(list(1)), auto_unbox=TRUE), "[1]"); expect_equal(to_json(list(x=1)), "{\"x\":[1]}"); expect_equal(to_json(list(x=1), auto_unbox=TRUE), "{\"x\":1}"); expect_equal(to_json(list(x=I(1)), auto_unbox=TRUE), "{\"x\":[1]}"); expect_equal(to_json(list(x=I(list(1))), auto_unbox=TRUE), "{\"x\":[1]}"); expect_equal(to_json(list(x=list(I(1))), auto_unbox=TRUE), "{\"x\":[[1]]}"); QuickJSR/README.md0000644000176200001440000000670715122664674013213 0ustar liggesusers # QuickJSR [![R-CMD-check](https://github.com/andrjohns/QuickJSR/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/andrjohns/QuickJSR/actions/workflows/R-CMD-check.yaml) [![CRAN status](https://www.r-pkg.org/badges/version/QuickJSR)](https://CRAN.R-project.org/package=QuickJSR) [![Monthly Downloads](https://cranlogs.r-pkg.org/badges/QuickJSR?color=blue)](https://CRAN.R-project.org/package=QuickJSR) [![Total Downloads](https://cranlogs.r-pkg.org/badges/grand-total/QuickJSR)](https://cranlogs.r-pkg.org/badges/grand-total/QuickJSR) [![QuickJSR status badge](https://andrjohns.r-universe.dev/badges/QuickJSR)](https://andrjohns.r-universe.dev/QuickJSR) A portable, lightweight, zero-dependency JavaScript engine for R, using [QuickJS](https://bellard.org/quickjs/). Values and objects are directly passed between R and QuickJS, with no need for serialization or deserialization. This both reduces overhead and allows for more complex data structures to be passed between R and JavaScript - including functions. ## Installation You can install the development version of QuickJSR from [GitHub](https://github.com/) with: ``` r # install.packages("remotes") remotes::install_github("andrjohns/QuickJSR") ``` Or you can install pre-built binaries from R-Universe: ``` r install.packages("QuickJSR", repos = c("https://andrjohns.r-universe.dev", "https://cran.r-project.org")) ``` ## Usage For standalone or simple JavaScript code, you can use the `qjs_eval()` function: ``` r library(QuickJSR) qjs_eval("1 + 1") #> [1] 2 qjs_eval("Math.random()") #> [1] 0.2441212 ``` For more complex interactions, you can create a QuickJS context and evaluate code within that context: ``` r ctx <- JSContext$new() ``` Use the `$source()` method to load JavaScript code into the context: ``` r # Code can be provided as a string ctx$source(code = "function add(a, b) { return a + b; }") # Or read from a file subtract_js <- tempfile(fileext = ".js") writeLines("function subtract(a, b) { return a - b; }", subtract_js) ctx$source(file = subtract_js) ``` Then use the `$call()` method to call a specified function with arguments: ``` r ctx$call("add", 1, 2) #> [1] 3 ctx$call("subtract", 5, 3) #> [1] 2 ``` ### Interacting with R objects, environments, and functions As QuickJSR uses the respective C APIs of R and QuickJS to pass values between the two, this allows for more complex data structures to be passed between R and JavaScript. For example, you can also pass R functions to be evaluated using JavaScript arguments: ``` r ctx$source(code = "function callRFunction(f, x, y) { return f(x, y); }") ctx$call("callRFunction", function(x, y) x + y, 1, 2) #> [1] 3 ctx$call("callRFunction", function(x, y) paste0(x, ",", y), "a", "b") #> [1] "a,b" ``` You can pass R environments to JavaScript, and both access and update their contents: ``` r env <- new.env() env$x <- 1 env$y <- 2 ctx$source(code = "function accessEnv(env) { return env.x + env.y; }") ctx$call("accessEnv", env) #> [1] 3 ctx$source(code = "function updateEnv(env) { env.z = env.x * env.y; return env.z;}") ctx$call("updateEnv", env) #> [1] 2 env$z #> [1] 2 ``` QuickJSR also provides a global `R` object, which you can use to access objects and functions from various R packages: ``` r qjs_eval('R.package("base")["Sys.Date"]()') #> [1] "2025-09-17 08:00:00 AWST" ``` QuickJSR/build/0000755000176200001440000000000015135347454013017 5ustar liggesusersQuickJSR/build/vignette.rds0000644000176200001440000000034115135347454015354 0ustar liggesusersb```b`aed`b2 1# ',/K/,Ɉ*/,H- MAS(QRRT %9h*qt0XD90!icKŰ% 5/$~hZ8S+.AQU▙ 7$apq2݀a>9`~RMI,F(WJbI^ZP?;_QuickJSR/man/0000755000176200001440000000000015122664674012475 5ustar liggesusersQuickJSR/man/JSContext-method-get.Rd0000644000176200001440000000111215122664674016673 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JSContext.R \docType{data} \name{JSContext-method-get} \alias{JSContext-method-get} \alias{get} \title{Get a variable from the current context} \format{ An object of class \code{NULL} of length 0. } \usage{ get(var_name) } \arguments{ \item{var_name}{The name of the variable to retrieve} } \value{ The value of the variable } \description{ Get the value of a variable from the current context } \examples{ \dontrun{ ctx <- JSContext$new() ctx$source(code = "var a = 1;") ctx$get("a") } } \keyword{datasets} QuickJSR/man/JSContext-method-validate.Rd0000644000176200001440000000114215122664674017710 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JSContext.R \docType{data} \name{JSContext-method-validate} \alias{JSContext-method-validate} \alias{validate} \title{Assess validity of JS code without evaluating} \format{ An object of class \code{NULL} of length 0. } \usage{ validate(code_string) } \arguments{ \item{code_string}{The JS code to check} } \value{ A boolean indicating whether code is valid } \description{ Checks whether JS code string is valid code in the current context } \examples{ \dontrun{ ctx <- JSContext$new() ctx$validate("1 + 2") } } \keyword{datasets} QuickJSR/man/qjs_eval.Rd0000644000176200001440000000102615122664674014567 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qjs.R \name{qjs_eval} \alias{qjs_eval} \title{qjs_eval} \usage{ qjs_eval(eval_string) } \arguments{ \item{eval_string}{A single string of the expression to evaluate} } \value{ The result of the provided expression } \description{ Evaluate a single Javascript expression. } \examples{ # Return the sum of two numbers: qjs_eval("1 + 2") # Concatenate strings: qjs_eval("'1' + '2'") # Create lists from objects: qjs_eval("var t = {'a' : 1, 'b' : 2}; t") } QuickJSR/man/QuickJSR-package.Rd0000644000176200001440000000147715122664674016021 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/quickjsr-package.R \docType{package} \name{QuickJSR-package} \alias{QuickJSR-package} \alias{QuickJSR} \title{The QuickJSR package.} \description{ An interface to the QuickJS lightweight Javascript engine } \seealso{ Useful links: \itemize{ \item \url{https://github.com/andrjohns/QuickJSR} \item \url{https://github.com/quickjs-ng/quickjs} \item Report bugs at \url{https://github.com/andrjohns/QuickJSR/issues} } } \author{ \strong{Maintainer}: Andrew R. Johnson \email{andrew.johnson@arjohnsonau.com} (\href{https://orcid.org/0000-0001-7000-8065}{ORCID}) Other contributors: \itemize{ \item QuickJS Authors (QuickJS sources and headers) [copyright holder] \item QuickJS-NG Authors (QuickJS-NG sources and headers) [copyright holder] } } QuickJSR/man/JSContext-method-source.Rd0000644000176200001440000000164215122664674017424 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JSContext.R \docType{data} \name{JSContext-method-source} \alias{JSContext-method-source} \alias{source} \title{Evaluate JS string or file in the current context} \format{ An object of class \code{NULL} of length 0. } \usage{ source(file = NULL, code = NULL) } \arguments{ \item{file}{A path to the JavaScript file to load} \item{code}{A single string of JavaScript to evaluate} } \value{ No return value, called for side effects } \description{ Evaluate a provided JavaScript file or string within the initialised context. Note that this method should only be used for initialising functions or values within the context, no values are returned from this function. See the \verb{$call()} method for returning values. } \examples{ \dontrun{ ctx <- JSContext$new() ctx$source(file = "path/to/file.js") ctx$source(code = "1 + 2") } } \keyword{datasets} QuickJSR/man/to_json.Rd0000644000176200001440000000060715122664674014442 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qjs.R \name{to_json} \alias{to_json} \title{to_json} \usage{ to_json(arg, auto_unbox = FALSE) } \arguments{ \item{arg}{Argument to convert to JSON} \item{auto_unbox}{Automatically unbox single element vectors} } \value{ JSON string } \description{ Use the QuickJS C API to convert an R object to a JSON string } QuickJSR/man/JSContext.Rd0000644000176200001440000000071515122664674014650 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JSContext.R \docType{data} \name{JSContext} \alias{JSContext} \title{JSContext object} \format{ An object of class \code{list} of length 1. } \usage{ JSContext } \value{ A JSContext object containing an initialised JavaScript context for evaluating scripts/commands } \description{ An initialised context within which to evaluate Javascript scripts or commands. } \keyword{datasets} QuickJSR/man/from_json.Rd0000644000176200001440000000050515122664674014760 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qjs.R \name{from_json} \alias{from_json} \title{from_json} \usage{ from_json(json) } \arguments{ \item{json}{JSON string to convert to an R object} } \value{ R object } \description{ Use the QuickJS C API to convert a JSON string to an R object } QuickJSR/man/quickjs_version.Rd0000644000176200001440000000053615122664674016206 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qjs.R \name{quickjs_version} \alias{quickjs_version} \title{Get the version of the bundled QuickJS library} \usage{ quickjs_version() } \value{ Character string of the version of the bundled QuickJS library } \description{ Get the version of the bundled QuickJS library } QuickJSR/man/JSContext-method-assign.Rd0000644000176200001440000000123315122664674017404 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JSContext.R \docType{data} \name{JSContext-method-assign} \alias{JSContext-method-assign} \alias{assign} \title{Assign a value to a variable in the current context} \format{ An object of class \code{NULL} of length 0. } \usage{ assign(var_name, value) } \arguments{ \item{var_name}{The name of the variable to assign} \item{value}{The value to assign to the variable} } \value{ No return value, called for side effects } \description{ Assign a value to a variable in the current context } \examples{ \dontrun{ ctx <- JSContext$new() ctx$assign("a", 1) ctx$get("a") } } \keyword{datasets} QuickJSR/man/JSContext-method-call.Rd0000644000176200001440000000133615122664674017037 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JSContext.R \docType{data} \name{JSContext-method-call} \alias{JSContext-method-call} \alias{call} \title{Call a JS function in the current context} \format{ An object of class \code{NULL} of length 0. } \usage{ call(function_name, ...) } \arguments{ \item{function_name}{The function to be called} \item{...}{The arguments to be passed to the function} } \value{ The result of calling the specified function } \description{ Call a specified function in the JavaScript context with the provided arguments. } \examples{ \dontrun{ ctx <- JSContext$new() ctx$source(code = "function add(a, b) { return a + b; }") ctx$call("add", 1, 2) } } \keyword{datasets} QuickJSR/DESCRIPTION0000644000176200001440000000266215135354472013432 0ustar liggesusersPackage: QuickJSR Title: Interface for the 'QuickJS-NG' Lightweight 'JavaScript' Engine Version: 1.9.0 Authors@R: c( person(c("Andrew", "R."), "Johnson", , "andrew.johnson@arjohnsonau.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0001-7000-8065")), person("QuickJS", "Authors", role = c("cph"), comment = "QuickJS sources and headers"), person("QuickJS-NG", "Authors", role = c("cph"), comment = "QuickJS-NG sources and headers") ) Description: An 'R' interface to the 'QuickJS' portable 'JavaScript' engine. The engine and all 'R' to 'JavaScript' interoperability is bundled within the package, requiring no dependencies beyond a 'C' compiler. License: MIT + file LICENSE URL: https://github.com/andrjohns/QuickJSR, https://github.com/quickjs-ng/quickjs BugReports: https://github.com/andrjohns/QuickJSR/issues Suggests: knitr, rmarkdown, tinytest Encoding: UTF-8 Language: en-AU NeedsCompilation: yes RoxygenNote: 7.3.3 SystemRequirements: GNU make VignetteBuilder: knitr Config/build/compilation-database: true Packaged: 2026-01-25 08:07:09 UTC; andrew Author: Andrew R. Johnson [aut, cre] (ORCID: ), QuickJS Authors [cph] (QuickJS sources and headers), QuickJS-NG Authors [cph] (QuickJS-NG sources and headers) Maintainer: Andrew R. Johnson Repository: CRAN Date/Publication: 2026-01-25 08:50:02 UTC