V8引擎之initContextIfNeeded(...)函數,context

來源:互聯網
上載者:User

V8引擎之initContextIfNeeded(...)函數,context

上篇說到一個很重要的函數initContextIfNeeded,這裡專門來分析下這個函數:

// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance. However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object. The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript. The javascript object that corresponds to a
// DOMWindow instance is the shadow object. When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
//
// To implement split-window, see
//   1) https://bugs.webkit.org/show_bug.cgi?id=17249
//   2) https://wiki.mozilla.org/Gecko:SplitWindow
//   3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
// we need to split the shadow object further into two objects:
// an outer window and an inner window. The inner window is the hidden
// prototype of the outer window. The inner window is the default
// global object of the context. A variable declared in the global
// scope is a property of the inner window.
//
// The outer window sticks to a Frame, it is exposed to JavaScript
// via window.window, window.self, window.parent, etc. The outer window
// has a security token which is the domain. The outer window cannot
// have its own properties. window.foo = 'x' is delegated to the
// inner window.
//
// When a frame navigates to a new page, the inner window is cut off
// the outer window, and the outer window identify is preserved for
// the frame. However, a new inner window is created for the new page.
// If there are JS code holds a closure to the old inner window,
// it won't be able to reach the outer window via its global object.
bool V8DOMWindowShell::initContextIfNeeded()
{
    // Bail out if the context has already been initialized.
    if (!m_context.IsEmpty())
        return false;

    // Create a handle scope for all local handles.
    v8::HandleScope handleScope;

    // Setup the security handlers and message listener. This only has
    // to be done once.
    static bool isV8Initialized = false;
    if (!isV8Initialized) {
        // Tells V8 not to call the default OOM handler, binding code
        // will handle it.
        v8::V8::IgnoreOutOfMemoryException();
        v8::V8::SetFatalErrorHandler(reportFatalErrorInV8);

        v8::V8::SetGlobalGCPrologueCallback(&V8GCController::gcPrologue);
        v8::V8::SetGlobalGCEpilogueCallback(&V8GCController::gcEpilogue);

        v8::V8::AddMessageListener(&v8UncaughtExceptionHandler);

        v8::V8::SetFailedAccessCheckCallbackFunction(reportUnsafeJavaScriptAccess);
#if ENABLE(JAVASCRIPT_DEBUGGER)
        ScriptProfiler::initialize();
#endif
        isV8Initialized = true;
    }

    m_context = createNewContext(m_global, 0);
    if (m_context.IsEmpty())
        return false;


    v8::Local<v8::Context> v8Context = v8::Local<v8::Context>::New(m_context);
    v8::Context::Scope contextScope(v8Context);

    // Store the first global object created so we can reuse it.
    if (m_global.IsEmpty()) {
        m_global = v8::Persistent<v8::Object>::New(v8Context->Global());
        // Bail out if allocation of the first global objects fails.
        if (m_global.IsEmpty()) {
            disposeContextHandles();
            return false;
        }
#ifndef NDEBUG
        V8GCController::registerGlobalHandle(PROXY, this, m_global);
#endif
    }

    if (!installHiddenObjectPrototype(v8Context)) {
        disposeContextHandles();
        return false;
    }

    if (!installDOMWindow(v8Context, m_frame->domWindow())) {
        disposeContextHandles();
        return false;
    }
    updateDocument();


    setSecurityToken();


    m_frame->loader()->client()->didCreateScriptContextForFrame();

    // FIXME: This is wrong. We should actually do this for the proper world once
    // we do isolated worlds the WebCore way.
    m_frame->loader()->dispatchDidClearWindowObjectInWorld(0);

    return true;
}

前面的英文注釋很多,同時也說明了這個函數的作用,先把注釋翻譯一下,也方便自己日後查看:


建立一個新的環境和建立全域對象

//
JavaScript全域對象對應於一個domwindow執行個體。
然而為了讓domWindow執行個體的屬性被隱藏起來,我們使用一個影子物件作為全域對象和使用JS DomWindow執行個體作為影子物件的屬性。
JS domwindow執行個體在js代碼中不會被檢測到,因為__proto__訪問器略過了這個對象。

影子物件和DomWindow 執行個體在javascript中被看作同一對象。對應於一個DomWindow執行個體的javascript對象其實是影子物件。
當映射一個DomWindow執行個體到一個V8對象的時候,我們返回影子物件。

//

//
為了實現分離視窗,參考:
//   1) https://bugs.webkit.org/show_bug.cgi?id=17249
//   2) https://wiki.mozilla.org/Gecko:SplitWindow
//   3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639


我們需要把隱形對象分成兩個對象:
一個外部的window和內部的window.內部的window是外部window的隱藏原型(prototype)。內部window是上下文預設的全域對象。在全域範圍的變數聲明是內部window的一個屬性。
//
外部window與一個frame相關,它通過window.window,window.self,window.parent等調用暴露給javascript。外部window有一個安全的範圍欄位。因此window.foo = 'x' 這種只代表內部window。
//
當一個frame導航到一個新頁面時,內部window被從外部window切斷,外部window標誌用來儲存frame。然而一個新的內部window被用於建立一個新的頁面。如果有JS代碼擁有一個以前內部window的閉包,那就不能通過全域對象訪問到外部window。



在這個函數內部和之前說的那個有點類似,為所有的局部handle建立handleScope對象,建立上下文,關聯上下文到範圍。
在這些步驟過後有一個  updateDocument();為新的document初始化js上下文。在updateDocument()中會調用initContextIfNeeded,為什麼updateDocument這個函數會調用initContextIfNeeded呢?看注釋:

 // There is an existing JavaScript wrapper for the global object
    // of this frame. JavaScript code in other frames might hold a
    // reference to this wrapper. We eagerly initialize the JavaScript
    // context for the new document to make property access on the
    // global object wrapper succeed.

存在這個frame的全域對象js外殼。在其他frame的js代碼可能擁有這個外殼的引用。我們急切的為這個新document初始化js上下文,是為了能夠成功的訪問到全域對象的外殼。


在這個updateDocument中除了初始化上下文還要更新document的wraperCache,以及更新JS安全起點和安全欄位。


如有問題,歡迎大家指出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.