aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/mozilla/firefox/multiprocess_firefox/technical_overview/index.html
blob: 18917fabc488c64b68598db487ddb3012f85e806 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
---
title: 技术概述
slug: Mozilla/Firefox/Multiprocess_Firefox/Technical_overview
translation_of: Mozilla/Firefox/Multiprocess_Firefox/Technical_overview
---
<div>{{FirefoxSidebar}}</div><div class="note">
<p>这个页面主要是 Bill McCloskey 的关于多进程 Firefox 的摘要: <a class="external external-icon" href="http://billmccloskey.wordpress.com/2013/12/05/multiprocess-firefox/">http://billmccloskey.wordpress.com/2013/12/05/multiprocess-firefox/</a></p>
</div>

<p>从总体上来看,多进程 Firefox 的运行方式如下。当 Firefox 启动时的进程被称为父进程。起初和单程 Firefox 一样:打开一个窗口用于显示<code><a href="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/browser.xul">browser.xul</a>,它</code>包含主要的 UI 元素。XUL是Firefox的GUI工具箱, 由它提供了类似Web HTML的方式来声明定义UI元素。Firefox 的 UI也有一个<code>window</code> 对象。它有一个<code>document</code> 属性,并含了在 <code>browser.xul</code> 中所有的XML元素。所有的菜单,工具栏,侧边栏和标签页都是 <code>document</code> 下的 XML 元素。每一个标签页(tab)都包含一个 <code>&lt;browser&gt;</code> 元素用来显示网页内容.</p>

<p>多进程与单进程的最主要区别是每个 <code>&lt;browser&gt;</code> 都有一个<code>remote="true"</code> 的属性。当这个 browser 元素被添加到 document 时,将会启动一个新的内容进程,也称为子进程。同时创建一个跨进程通信的IPC通道。开始时子进程显示<code> about:blank</code>,父进程通过给子进程发送命令来导航显示的内容。</p>

<h2 id="绘制"><strong id="drawing">绘制</strong></h2>

<p>有时,显示的网页内容需要从子进程传递到父进程然后再显示到屏幕。多进程模式依赖于一个新的特性(<a href="http://benoitgirard.wordpress.com/2012/05/15/off-main-thread-compositing-omtc-and-why-it-matters/"><em>off main thread compositing</em></a> ,OMTC)。简单来说,每个窗口被分成若干层,概念上类似于photoshop中的层。每一次Firefox进行渲染时,这些层被提交到合成线程来构建为一个图片。</p>

<p>层是树状结构。树的根节点对应一个Firefox窗口。根节点层包其他子层,如绘制菜单和标签页。一个子树对应所有网页内容。网页内容可被分成更多的层,这些层都以同一个内容层为根节点。</p>

<p>在多进程Firefox中,内容层的子树是一个垫片(shim)。在大多数时间,它包含一个能够简单地保持到子进程的通信链接的引用的占位符节点。内容进程包括网页内容的层树。它构建并且描绘这个层树。当描绘完成时,它通过IPC将层数的结构发送给父进程。当父进程受到这个层树时,它删除这个占位符内容节点并且将其替换为源于内容的实际树。然后它正常地合成并且绘制。当它完成后,它将占位符放回。</p>

<p>因为Firefox OS的需要,OMTC怎样于多进程一起工作的基本构架已经存在了一段时间。然而,Matt Woodrow和 David Anderson已经完成了大量工作来使得其在Windows,Mac和Linux正常工作。一个巨大的挑战是使多进程Firefox能够在所有平台下都能使OMTC启动。现在,只有Macs默认使用OMTC。</p>

<h2 id="用户输入"><strong id="input">用户输入</strong></h2>

<p>Events in Firefox work the same way as they do on the web. Namely, there is a DOM tree for the entire window, and events are threaded through this tree in capture and bubbling phases. Imagine that the user clicks on a button on a web page. In single-process Firefox, the root DOM node of the Firefox window gets the first chance to process the event. Then, nodes lower down in the DOM tree get a chance. The event handling proceeds down through to the XUL <code>&lt;browser&gt;</code> element. At this point, nodes in the web page’s DOM tree are given a chance to handle the event, all the way down to the button. The bubble phase follows, running in the opposite order, all the way back up to the root node of the Firefox window.</p>

<p>With multiple processes, event handling works the same way until the <code>&lt;browser&gt;</code> element is hit. At that point, if the event hasn’t been handled yet, it gets sent to the child process by IPC, where handling starts at the root of the content DOM tree. The parent process then waits to run its bubbling phase until the content process has finished handling the event.</p>

<h2 id="进程间通信"><strong id="ipc">进程间通信</strong></h2>

<p>所有 IPC 使用 Chromium IPC 程序库。每个子进程都有单独的与父进程的 IPC 链接。子进程之间不能直接通信。为了避免死锁和确保响应能力,父进程不允许坐等子进程的消息。但是,子进程可以阻塞等待父进程的消息。</p>

<p>相比于人们预期的直接通过 IPC 发送数据包,我们使用代码生成使这个过程更漂亮。IPC 协议在 <a href="https://wiki.mozilla.org/IPDL">IPDL</a> 中定义, which sort of stands for “inter-* protocol definition language”. A typical IPDL file is <code><a href="http://mxr.mozilla.org/mozilla-central/source/netwerk/ipc/PNecko.ipdl">PNecko.ipdl</a></code>. It defines a set messages and their parameters. Parameters are serialized and included in the message. To send a message <code>M</code>, C++ code just needs to call the method <code>SendM</code>. To receive the message, it implements the method <code>RecvM</code>.</p>

<p>IPDL is used in all the low-level C++ parts of Gecko where IPC is required. In many cases, IPC is just used to forward actions from the child to the parent. This is a common pattern in Gecko:</p>

<pre class="brush: cpp">void AddHistoryEntry(param) {
  if (XRE_GetProcessType() == GeckoProcessType_Content) {
    // If we're in the child, ask the parent to do this for us.
    SendAddHistoryEntry(param);
    return;
  }

  // Actually add the history entry...
}

bool RecvAddHistoryEntry(param) {
  // Got a message from the child. Do the work for it.
  AddHistoryEntry(param);
  return true;
}
</pre>

<p>When <code>AddHistoryEntry</code> is called in the child, we detect that we’re inside the child process and send an IPC message to the parent. When the parent receives that message, it calls <code>AddHistoryEntry</code> on its side.</p>

<p>For a more realistic illustration, consider the Places database, which stores visited URLs for populating the awesome bar. Whenever the user visits a URL in the content process, we call <a href="http://mxr.mozilla.org/mozilla-central/source/toolkit/components/places/History.cpp?rev=8b9687f6c602#2326">this code</a>. Notice the content process check followed by the <code>SendVisitURI</code> call and an immediate return. The message is received <a href="http://mxr.mozilla.org/mozilla-central/source/dom/ipc/ContentParent.cpp?rev=fecda5f4a0df#2666">here</a>; this code just calls <code>VisitURI</code> in the parent.</p>

<p>The code for IndexedDB, the places database, and HTTP connections all runs in the parent process, and they all use roughly the same proxying mechanism in the child.</p>

<h2 id="框架脚本"><strong id="contentscripts">框架脚本</strong></h2>

<p>IPDL takes care of passing messages in C++, but much of Firefox is actually written in JavaScript. Instead of using IPDL directly, JavaScript code relies on <a href="/en-US/Firefox/Multiprocess_Firefox/The_message_manager">the message manager</a> to communicate between processes. To use the message manager in JS, you need to get hold of a message manager object. There is a global message manager, message managers for each Firefox window, and message managers for each <code>&lt;browser&gt;</code> element. A message manager can be used to load JS code into the child process and to exchange messages with it.</p>

<p>As a simple example, imagine that we want to be informed every time a <code>load</code> event triggers in web content. We’re not interested in any particular browser or window, so we use the global message manager. The basic process is as follows:</p>

<pre class="brush: js">// Get the global message manager.
let mm = Cc["@<span class="skimlinks-unlinked">mozilla.org/globalmessagemanager;1</span>"].
         getService(Ci.nsIMessageListenerManager);

// Wait for load event.
mm.addMessageListener("GotLoadEvent", function (msg) {
  dump("Received load event: " + <span class="skimlinks-unlinked">msg.data.url</span> + "\n");
});

// Load code into the child process to listen for the event.
mm.loadFrameScript("chrome://content/<span class="skimlinks-unlinked">content-script.js</span>", true);
</pre>

<p>For this to work, we also need to have a file <code>content-script.js</code>:</p>

<pre class="brush: js">// Listen for the load event.
addEventListener("load", function (e) {
  // Inform the parent process.
  let docURL = content.document.documentURI;
  sendAsyncMessage("GotLoadEvent", {url: docURL});
}, false);
</pre>

<p>This file is called a <em>frame script</em>. When the <code>loadFrameScript</code> function call runs, the code for the script is run once for each <code>&lt;browser&gt;</code> element. This includes both remote browsers and regular ones. If we had used a per-window message manager, the code would only be run for the browser elements in that window. Any time a new browser element is added, the script is run automatically (this is the purpose of the <code>true</code> parameter to <code>loadFrameScript</code>). Since the script is run once per browser, it can access the browser’s window object and docshell via the <code>content</code> and <code>docShell</code> globals.</p>

<p>The great thing about frame scripts is that they work in both single-process and multiprocess Firefox. To learn more about the message manager, see the <a href="/en-US/Firefox/Multiprocess_Firefox/The_message_manager">message manager guide</a>.</p>

<h2 id="跨进程_API"><strong id="shims">跨进程 API</strong></h2>

<p>There are a lot of APIs in Firefox that cross between the parent and child processes. An example is the <code>webNavigation</code> property of XUL <code>&lt;browser&gt;</code> elements. The <code>webNavigation</code> property is an object that provides methods like <code>loadURI</code>, <code>goBack</code>, and <code>goForward</code>. These methods are called in the parent process, but the actions need to happen in the child. First I’ll cover how these methods work in single-process Firefox, and then I’ll describe how we adapted them for multiple processes.</p>

<p>The <code>webNavigation</code> property is defined using the XML Binding Language (XBL). XBL is a declarative language for customizing how XML elements work. Its syntax is a combination of XML and JavaScript. Firefox uses XBL extensively to customize XUL elements like <code>&lt;browser&gt;</code> and <code>&lt;tabbrowser&gt;</code>. The <code>&lt;browser&gt;</code> customizations reside in <code><a href="http://mxr.mozilla.org/mozilla-central/source/toolkit/content/widgets/browser.xml?rev=754cf7fc84cd">browser.xml</a></code>. <a href="http://mxr.mozilla.org/mozilla-central/source/toolkit/content/widgets/browser.xml?rev=754cf7fc84cd#262">Here</a> is how <code>browser.webNavigation</code> is defined:</p>

<pre class="brush: xml">&lt;field name="_webNavigation"&gt;null&lt;/field&gt;

&lt;property name="webNavigation" readonly="true"&gt;
   &lt;getter&gt;
   &lt;![CDATA[
     if (!this._webNavigation)
       this._webNavigation = this.docShell.QueryInterface(Components.interfaces.nsIWebNavigation);
     return this._webNavigation;
   ]]&gt;
   &lt;/getter&gt;
&lt;/property&gt;
</pre>

<p>This code is invoked whenever JavaScript code in Firefox accesses <code>browser.webNavigation</code>, where <code>browser</code> is some <code>&lt;browser&gt;</code> element. It checks if the result has already been cached in the <code>browser._webNavigation</code> field. If it hasn’t been cached, then it fetches the navigation object based off the browser’s <em>docshell</em>. The docshell is a Firefox-specific object that encapsulates a lot of functionality for loading new pages, navigating back and forth, and saving page history. In multiprocess Firefox, the docshell lives in the child process. Since the <code>webNavigation</code> accessor runs in the parent process, <code>this.docShell</code> above will just return null. As a consequence, this code will fail completely.</p>

<p>One way to fix this problem would be to create a fake docshell in C++ that could be returned. It would operate by sending IPDL messages to the real docshell in the child to get work done. We may eventually take this route in the future. We decided to do the message passing in JavaScript instead, since it’s easier and faster to prototype things there. Rather than change every docshell-using accessor to test if we’re using multiprocess browsing, we decided to create a new XBL binding that applies only to remote <code>&lt;browser&gt;</code> elements. It is called <a href="http://mxr.mozilla.org/mozilla-central/source/toolkit/content/widgets/remote-browser.xml?rev=9583bd3099ae"><code>remote-browser.xml</code></a>, and it extends the existing <code>browser.xml</code> binding.</p>

<p>The <code>remote-browser.xml</code> binding returns a JavaScript <em>shim object</em> whenever anyone uses <code>browser.webNavigation</code> or other similar objects. The shim object is implemented <a href="http://mxr.mozilla.org/mozilla-central/source/toolkit/modules/RemoteWebNavigation.jsm">in its own JavaScript module</a>. It uses the message manager to send messages like <code>"WebNavigation:LoadURI"</code> to <a href="http://mxr.mozilla.org/mozilla-central/source/toolkit/content/browser-child.js?rev=9583bd3099ae#107">a content script loaded by <code>remote-browser.xml</code></a>. The content script performs the actual action.</p>

<p>The shims we provide emulate their real counterparts imperfectly. They offer enough functionality to make Firefox work, but add-ons that use them may find them insufficient. I’ll discuss strategies for making add-ons work in more detail later.</p>

<h2 id="跨进程对象包装器"><strong id="cpows">跨进程对象包装器</strong></h2>

<p>The message manager API does not allow the parent process to call <code>sendSyncMessage</code>; that is, the parent is not allowed to wait for a response from the child. It’s detrimental for the parent to wait on the child, since we don’t want the browser UI to be unresponsive because of slow content. However, converting Firefox code to be asynchronous (i.e., to use <code>sendAsyncMessage</code> instead) can sometimes be onerous. As an expedient, we’ve introduced a new primitive that allows code in the parent process to access objects in the child process synchronously.</p>

<p>These objects are called cross-process object wrappers, frequently abbreviated to CPOWs. They’re created using the message manager. Consider this example content script:</p>

<pre class="brush: js">addEventListener("load", function (e) {
  let doc = content.document;
  sendAsyncMessage("GotLoadEvent", <strong>{}, {document: doc}</strong>);
}, false);
</pre>

<p>In this code, we want to be able to send a reference to the document to the parent process. We can’t use the second parameter to <code>sendAsyncMessage</code> to do this: that argument is converted to JSON before it is sent up. The optional third parameter allows us to send object references. Each property of this argument becomes accessible in the parent process as a CPOW. Here’s what the parent code might look like:</p>

<pre class="brush: js">let mm = Cc["@<span class="skimlinks-unlinked">mozilla.org/globalmessagemanager;1</span>"].
         getService(Ci.nsIMessageListenerManager);

mm.addMessageListener("GotLoadEvent", function (msg) {
  let uri = <strong>msg.objects.document.documentURI</strong>;
  dump("Received load event: " + uri + "\n");
});
mm.loadFrameScript("chrome://content/<span class="skimlinks-unlinked">content-script.js</span>", true);
</pre>

<p>It’s important to realize that we’re send object <em>references</em>. The <code>msg.objects.document</code> object is only a wrapper. The access to its <code>documentURI</code> property sends a synchronous message down to the child asking for the value. The dump statement only happens after a reply has come back from the child.</p>

<p>Because every property access sends a message, CPOWs can be slow to use. There is no caching, so 1,000 accesses to the same property will send 1,000 messages.</p>

<p>Another problem with CPOWs is that they violate some assumptions people might have about message ordering. Consider this code:</p>

<pre class="brush: js">mm.addMessageListener("GotLoadEvent", function (msg) {
  mm.sendAsyncMessage("ChangeDocumentURI", {newURI: "<span class="skimlinks-unlinked">hello.com</span>"});
  let uri = <strong>msg.objects.document.documentURI</strong>;
  dump("Received load event: " + uri + "\n");
});
</pre>

<p>This code sends a message asking the child to change the current document URI. Then it accesses the current document URI via a CPOW. You might expect the value of <code>uri</code> to come back as <code>"hello.com"</code>. But it might not. In order to avoid deadlocks, CPOW messages can bypass normal messages and be processed first. It’s possible that the request for the <code>documentURI</code> property will be processed before the <code>"ChangeDocumentURI"</code> message, in which case <code>uri</code> will have some other value.</p>

<p>For this reason, it’s best not to mix CPOWs with normal message manager messages. It’s also a bad idea to use CPOWs for anything security-related, since you may not get results that are consistent with surrounding code that might use the message manager.</p>

<p>Despite these problems, we’ve found CPOWs to be useful for converting certain parts of Firefox to be multiprocess-compatible. It’s best to use them in cases where users are less likely to notice poor responsiveness. As an example, we use CPOWs to implement the context menu that pops up when users right-click on content elements. Whether this code is asynchronous or synchronous, the menu cannot be displayed until content has responded with data about the element that has been clicked. The user is unlikely to notice if, for example, tab animations don’t run while waiting for the menu to pop up. Their only concern is for the menu to come up as quickly as possible, which is entirely gated on the response time of the content process. For this reason, we chose to use CPOWs, since they’re easier than converting the code to be asynchronous.</p>

<p>It’s possible that CPOWs will be phased out in the future. Asynchronous messaging using the message manager gives a user experience that is at least as good as, and often strictly better than, CPOWs. We strongly recommend that people use the message manager over CPOWs when possible. Nevertheless, CPOWs are sometimes useful.</p>