#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "quickjs.h"
static int failures;
static void check(int ok, const char *what)
{
if (!ok) {
printf(" FAIL %s\n", what);
failures++;
} else {
printf(" ok %s\n", what);
}
}
static void describe_exception(JSContext *ctx, char *out, size_t n, JSValue v)
{
if (!JS_IsException(v)) {
snprintf(out, n, "no exception");
return;
}
JSValue e = JS_GetException(ctx);
JSValue name = JS_GetPropertyStr(ctx, e, "name");
JSValue message = JS_GetPropertyStr(ctx, e, "message");
const char *name_text = JS_ToCString(ctx, name);
const char *message_text = JS_ToCString(ctx, message);
snprintf(out, n, "%s: %s", name_text ? name_text : "?", message_text ? message_text : "?");
JS_FreeCString(ctx, name_text);
JS_FreeCString(ctx, message_text);
JS_FreeValue(ctx, name);
JS_FreeValue(ctx, message);
JS_FreeValue(ctx, e);
}
static int run(JSContext *ctx, const char *what, const char *source)
{
JSValue v = JS_Eval(ctx, source, strlen(source), "<embed>", JS_EVAL_TYPE_GLOBAL);
char text[256];
if (JS_IsException(v)) {
describe_exception(ctx, text, sizeof text, v);
printf(" %-8s threw %s\n", what, text);
return 0;
}
const char *value = JS_ToCString(ctx, v);
printf(" %-8s %s\n", what, value ? value : "?");
JS_FreeCString(ctx, value);
JS_FreeValue(ctx, v);
return 1;
}
static int polls;
static int interrupt_handler(JSRuntime *rt, void *opaque)
{
(void)rt;
(void)opaque;
polls++;
return polls >= 2;
}
static JSValue multiply(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
{
(void)this_val;
int a, b;
if (argc < 2)
return JS_ThrowTypeError(ctx, "multiply needs two arguments");
if (JS_ToInt32(ctx, &a, argv[0]) < 0 || JS_ToInt32(ctx, &b, argv[1]) < 0)
return JS_EXCEPTION;
return JS_NewInt32(ctx, a * b);
}
static JSClassID counter_class_id;
typedef struct {
int value;
} Counter;
static void counter_finalizer(JSRuntime *rt, JSValue obj)
{
Counter *c = JS_GetOpaque(obj, counter_class_id);
if (c)
js_free_rt(rt, c);
}
static JSValue counter_ctor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv)
{
JSValue obj, proto;
Counter *c;
int start = 0;
if (argc > 0 && JS_ToInt32(ctx, &start, argv[0]) < 0)
return JS_EXCEPTION;
obj = JS_NewObjectClass(ctx, counter_class_id);
if (JS_IsException(obj))
return obj;
c = js_mallocz(ctx, sizeof *c);
if (!c) {
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
c->value = start;
JS_SetOpaque(obj, c);
proto = JS_GetPropertyStr(ctx, new_target, "prototype");
if (JS_IsException(proto)) {
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
JS_SetPrototype(ctx, obj, proto);
JS_FreeValue(ctx, proto);
return obj;
}
static JSValue counter_bump(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
{
Counter *c = JS_GetOpaque2(ctx, this_val, counter_class_id);
int by = 1;
if (!c)
return JS_EXCEPTION;
if (argc > 0 && JS_ToInt32(ctx, &by, argv[0]) < 0)
return JS_EXCEPTION;
c->value += by;
return JS_NewInt32(ctx, c->value);
}
int main(void)
{
JSRuntime *rt;
JSContext *ctx;
JSValue global, fn, instance, result;
char text[256];
setvbuf(stdout, NULL, _IOLBF, 0);
printf("1. runtime and context\n");
rt = JS_NewRuntime();
check(rt != NULL, "JS_NewRuntime");
ctx = JS_NewContext(rt);
check(ctx != NULL, "JS_NewContext");
if (!rt || !ctx)
return 1;
check(run(ctx, "intr", "typeof Object + ' ' + typeof JSON + ' ' + typeof Promise"), "a raw context has the intrinsics");
printf("2. memory limit\n");
JS_SetMemoryLimit(rt, 8 * 1024 * 1024);
if (run(ctx, "limit", "try { new Array(64 << 20).fill(0).length } catch (e) { throw e }") == 0)
check(1, "the allocation limit stops the script");
JS_SetMemoryLimit(rt, (size_t)-1);
printf("3. stack limit\n");
JS_SetMaxStackSize(rt, 256 * 1024);
{
JSValue v = JS_Eval(ctx,
"(function depth(n){ try { return depth(n + 1); } "
"catch (e) { return n; } })(0)",
strlen("(function depth(n){ try { return depth(n + 1); } "
"catch (e) { return n; } })(0)"),
"<embed>", JS_EVAL_TYPE_GLOBAL);
double depth = 0;
JS_ToFloat64(ctx, &depth, v);
check(!JS_IsException(v) && depth > 100, "deep recursion stops instead of crashing");
JS_FreeValue(ctx, v);
}
{
JSValue v = JS_Eval(ctx, "function f(){ return f() } f()",
strlen("function f(){ return f() } f()"), "<embed>",
JS_EVAL_TYPE_GLOBAL);
describe_exception(ctx, text, sizeof text, v);
printf(" %-8s threw %s\n", "overflow", text);
check(strstr(text, "stack overflow") != NULL, "stack overflow is InternalError");
}
JS_SetMaxStackSize(rt, 0);
printf("4. interrupt\n");
polls = 0;
JS_SetInterruptHandler(rt, interrupt_handler, NULL);
{
JSValue v = JS_Eval(ctx, "for(;;){}", strlen("for(;;){}"), "<embed>",
JS_EVAL_TYPE_GLOBAL);
describe_exception(ctx, text, sizeof text, v);
printf(" %-8s threw %s (%d poll(s))\n", "loop", text, polls);
check(strstr(text, "interrupted") != NULL, "a runaway loop is interrupted");
}
JS_SetInterruptHandler(rt, NULL, NULL);
check(run(ctx, "loop", "var n = 0; for (var i = 0; i < 100000; i++) n++; n"),
"a loop finishes when no handler is installed");
printf("5. globals and properties\n");
global = JS_GetGlobalObject(ctx);
fn = JS_NewCFunction(ctx, multiply, "multiply", 2);
JS_SetPropertyStr(ctx, global, "multiply", fn);
JS_FreeValue(ctx, global);
check(run(ctx, "call", "multiply(6, 7)"), "a C function installed from C is callable");
printf("6. a host class\n");
JS_NewClassID(&counter_class_id);
{
JSClassDef def = { "Counter", .finalizer = counter_finalizer };
check(JS_NewClass(rt, counter_class_id, &def) == 0, "JS_NewClass");
}
{
JSValue proto = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, proto, "bump",
JS_NewCFunction(ctx, counter_bump, "bump", 1));
JS_SetClassProto(ctx, counter_class_id, proto);
}
global = JS_GetGlobalObject(ctx);
{
JSValue ctor = JS_NewCFunction2(ctx, counter_ctor, "Counter", 1,
JS_CFUNC_constructor, 0);
JSValue proto = JS_GetClassProto(ctx, counter_class_id);
JS_SetPropertyStr(ctx, ctor, "prototype", proto);
JS_SetPropertyStr(ctx, global, "Counter", ctor);
}
JS_FreeValue(ctx, global);
instance = JS_Eval(ctx, "var c = new Counter(10); c.bump(5)",
strlen("var c = new Counter(10); c.bump(5)"), "<embed>",
JS_EVAL_TYPE_GLOBAL);
{
const char *bumped = JS_ToCString(ctx, instance);
printf(" %-8s %s\n", "class", bumped ? bumped : "?");
JS_FreeCString(ctx, bumped);
JS_FreeValue(ctx, instance);
}
global = JS_GetGlobalObject(ctx);
{
JSValue c = JS_GetPropertyStr(ctx, global, "c");
Counter *payload = JS_GetOpaque(c, counter_class_id);
check(payload != NULL && payload->value == 15, "the opaque payload round-trips");
JS_FreeValue(ctx, c);
}
JS_FreeValue(ctx, global);
printf("7. JSON\n");
{
const char *json = "{\"a\":[1,2,{\"b\":null}],\"c\":\"text\"}";
JSValue parsed = JS_ParseJSON(ctx, json, strlen(json), "<embed>");
check(!JS_IsException(parsed), "JS_ParseJSON");
{
JSValue stringified = JS_JSONStringify(ctx, parsed, JS_UNDEFINED, JS_UNDEFINED);
const char *again = JS_ToCString(ctx, stringified);
check(again != NULL && strcmp(again, json) == 0, "round trips through the C API");
JS_FreeCString(ctx, again);
JS_FreeValue(ctx, stringified);
}
JS_FreeValue(ctx, parsed);
}
printf("8. memory report\n");
{
JSMemoryUsage usage;
memset(&usage, 0, sizeof usage);
JS_ComputeMemoryUsage(rt, &usage);
check(usage.obj_count > 0, "obj_count is populated");
check(usage.atom_count > 0, "atom_count is populated");
}
printf("9. teardown\n");
result = JS_Eval(ctx, "c.bump()", strlen("c.bump()"), "<embed>", JS_EVAL_TYPE_GLOBAL);
JS_FreeValue(ctx, result);
JS_FreeContext(ctx);
JS_RunGC(rt);
JS_FreeRuntime(rt);
check(1, "context and runtime freed in the header's order");
printf(failures ? "embed: %d failure(s)\n" : "embed: %d failure(s)\n", failures);
return failures ? 1 : 0;
}