Search code examples
quickjs

QuickJS: Possible memory leak due to modifying function prototype


I've encountered what seems like a bug in the QuickJS JavaScript engine. I've submitted a GitHub issue, but am also asking here to see if it might be user error, and/or to find out if others have encountered similar issues.

The following test code:

#include <string>
#include "quickjs.h"

int main() {
    auto runtime = JS_NewRuntime();
    auto context = JS_NewContext(runtime);

    std::string source =
        "function foo() {}\n"
        "foo.prototype.bar = function() {};";
    JS_Eval(context, source.c_str(), source.size(), "", JS_EVAL_TYPE_GLOBAL);

    JS_FreeContext(context);
    JS_FreeRuntime(runtime);
}

Produces the assertion:

Assertion failed: (list_empty(&rt->gc_obj_list)), function JS_FreeRuntime

Using the 'dump leaks' feature outputs the following:

Object leaks:
       ADDRESS REFS SHRF          PROTO      CLASS PROPS
   0x1071d4bc0    1   0*    0x1071c5510   Function { length: 0, name: 14'', prototype: [autoinit 0x1071c4e80 0 0x0] }

Which seems to suggest that modifying the function prototype is causing a memory leak. (This doesn't happen if the function prototype is left unmodified.)

Is there anything obviously wrong with my test code? Perhaps misuse of the API? If not, has anyone else run into this issue or similar issues with QuickJS?


Solution

  • For anyone who might stumble on this in the future, this was due to incorrect API usage. The leak wasn't due to the JavaScript code itself, but rather because JS_Eval() returns a JSValue, which needs to be freed using JS_FreeValue().