Skip to content

Fix dangling V8 handles in v8ToChoc object conversion with V8 15.4+ - #114

Closed
danielraffel wants to merge 1 commit into
Tracktion:mainfrom
danielraffel:fix/v8-iterate-dangling-locals
Closed

danielraffel wants to merge 1 commit into
Tracktion:mainfrom
danielraffel:fix/v8-iterate-dangling-locals

Conversation

@danielraffel

Copy link
Copy Markdown

What breaks

With V8 15.4 and later, converting a JS object to a choc::value::Value through V8Context (for example the result of evaluateExpression on an object literal with several members) can return garbage for some members or crash. We see SIGBUS inside v8::internal::KeyAccumulator::CollectOwnElementIndices with V8 15.7.112.5; the same code works with 15.3.

Why

V8Context::v8ToChoc walks the property names with v8::Array::Iterate, calls o->Get (c, key) inside the callback, and stores the returned v8::Local values in propValues, converting them after Iterate returns.

Since V8 15.4 (V8 commit 3186b30e34b4, "Expect callback passed to Array::Iterate() may potentially cause a GC"), FastIterateArray in src/api/api.cc runs the callback inside a HandleScope that V8 opens itself. The Locals created in the callback are released when Iterate returns, so propValues holds dangling handles. The next conversion reuses those slots and later members read whatever was written there.

Independently of that change, the Array::Iterate documentation already says the callback must not allocate or call back into V8, and Get() can run a getter.

Fix

Replace the Iterate call with a plain index loop over the property-name array, so the Locals live in the caller's scope. The now-unused IteratorType alias is removed.

Standalone repro (plain V8, same pattern)

#include <libplatform/libplatform.h>
#include <v8.h>
#include <cstdio>
#include <vector>

int main()
{
    auto platform = v8::platform::NewDefaultPlatform();
    v8::V8::InitializePlatform (platform.get());
    v8::V8::Initialize();
    v8::Isolate::CreateParams p;
    p.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
    auto iso = v8::Isolate::New (p);
    int bad = 0;
    {
        v8::Isolate::Scope is (iso);
        v8::HandleScope hs (iso);
        auto c = v8::Context::New (iso);
        v8::Context::Scope cs (c);
        auto src = v8::String::NewFromUtf8Literal (iso, "({ a: function(){}, b: function(){}, c: function(){}, d: {x: 1}, e: 'str' })");
        auto o = v8::Script::Compile (c, src).ToLocalChecked()->Run (c).ToLocalChecked()->ToObject (c).ToLocalChecked();
        auto names = o->GetPropertyNames (c).ToLocalChecked();

        // Same as v8ToChoc: Get() inside the callback, keep the Local afterwards
        struct Ctx { v8::Local<v8::Context> c; v8::Local<v8::Object> o; std::vector<v8::Local<v8::Value>> vals; } ctx { c, o, {} };
        (void) names->Iterate (c, +[] (uint32_t, v8::Local<v8::Value> key, void* d)
        {
            auto& x = *static_cast<Ctx*> (d);
            x.vals.push_back (x.o->Get (x.c, key).ToLocalChecked());
            return v8::Array::CallbackResult::kContinue;
        }, &ctx);

        // Any handle allocation afterwards reuses the released slots
        for (int i = 0; i < 16; ++i)
            (void) v8::Object::New (iso);

        for (uint32_t i = 0; i < names->Length(); ++i)
        {
            auto key = names->Get (c, i).ToLocalChecked();
            if (! ctx.vals[i]->StrictEquals (o->Get (c, key).ToLocalChecked()))
                ++bad;
        }
    }
    std::printf ("V8 %s: %d dangling\n", v8::V8::GetVersion(), bad);
    return bad ? 1 : 0;
}

Reports dangling handles with V8 15.7.112.5 and none with 15.3.

Separately, and not addressed here: current choc main does not compile against V8 15.4+ headers at all, because the two module-loading callbacks call v8::Context::GetIsolate(), which those headers no longer provide. With those two calls replaced locally, the patched header compiles cleanly (-std=c++20 -fsyntax-only -Wall -Wextra) against the V8 15.4 and 15.7 headers.

V8Context::v8ToChoc walked an object's property names with
v8::Array::Iterate and stored the v8::Local values returned by Get()
inside the callback, converting them after Iterate returned. Since V8
15.4 (V8 commit 3186b30e34b4) Iterate runs the callback inside its own
HandleScope, so those Locals are released when Iterate returns and
later conversions read freed handle slots, crashing or producing
garbage. V8 also documents that the Iterate callback must not allocate
or call back into V8, which Get() can do.

Use a plain index loop over the property names instead.
@julianstorer

Copy link
Copy Markdown
Collaborator

Thanks! I've had a look at this now and pushed some changes that should do the same thing a bit more efficiently, and also sort out the GetIsolate() issue - let me know if you have any problems with it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants