Skip to content

segmentation fault if setting opaque on constructor #657

@boot2linux

Description

@boot2linux

Please check below code. I want to hide class ID, so plan to retrieve class from opaque. It works well if using context opaque, but it does not works well for multiple class directly.

#include "quickjs.h"
#include <stdio.h>
#include <stdlib.h>


// static JSClassID globalClassID;
static JSValue js_class_constructor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv) {

    JSClassID id;
    id=(JSClassID)(intptr_t)JS_GetAnyOpaque(new_target, &id);
    printf("Class ID: %d fetched from opaque\n", id);

    // JSClassID id=globalClassID;
    // crash here
    JSValue obj = JS_NewObjectClass(ctx, id);
    if (JS_IsException(obj)) {
        return obj;
    }

    return obj;
}

int main(int argc, char **argv) {
    JSRuntime *rt;
    JSContext *ctx;
    JSClassID js_class_id =0;

    rt = JS_NewRuntime();
    ctx = JS_NewContext(rt);

    JS_NewClassID(rt, &js_class_id);
    printf("Class ID %d is created!\n", js_class_id);
    // globalClassID = js_class_id;

    JSClassDef js_class = {
        .class_name = "MyClass",
    };
    JS_NewClass(rt, js_class_id, &js_class);

    JSValue constructor = JS_NewCFunction2(ctx, js_class_constructor, "MyClass", 0, JS_CFUNC_constructor, 0);

    void *opaque = (void *)(intptr_t)js_class_id;
    JS_SetOpaque(constructor, opaque);

    JS_SetPropertyStr(ctx, JS_GetGlobalObject(ctx), "MyClass", constructor);

    const char *script =
        "const obj = new MyClass();\n";

    JSValue result = JS_Eval(ctx, script, strlen(script), "<input>", JS_EVAL_TYPE_GLOBAL);

    if (JS_IsException(result)) {
        JSValue exception = JS_GetException(ctx);
        JSValue message = JS_GetPropertyStr(ctx, exception, "message");
        const char *str = JS_ToCString(ctx, message);
        printf("Exception: %s\n", str);
        JS_FreeCString(ctx, str);
    }

    JS_FreeValue(ctx, result);
    JS_FreeContext(ctx);
    JS_FreeRuntime(rt);

    return 0;
}
clang cutils.c libbf.c libregexp.c quickjs-libc.c quickjs.c libunicode.c t.c -o t && ./t
Class ID 59 is created!
Class ID: 59 fetched from opaque
[1]    2046 segmentation fault  ./t

It's crashed on function JS_NewObjectClass, but I don't know.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions