blob: 7bd22bfef650dbd9a0228e4d3038cbf580c4cc44 [file] [log] [blame] [view]
Ken Rockotab035122019-02-06 00:35:241# Converting Legacy IPC to Mojo
2
3[TOC]
4
5## Overview
6
7A number of IPC messages sent (primarily between the browser and renderer
8processes) are still defined using Chrome's old IPC system in `//ipc`. This
9system uses
10[`base::Pickle`](https://cs.chromium.org/chromium/src/base/pickle.h?rcl=8b7842262ee1239b1f3ae20b9c851748ef0b9a8b&l=128)
11as the basis for message serialization and is supported by a number if `IPC_*`
12preprocessor macros defined in `//ipc` and used around the source tree.
13
14There is an ongoing, distributed effort to get these messages converted to Mojo
15interface messages. Messages that still need to be converted are tracked in two
16spreadsheets:
17
18- [Chrome IPC to Mojo migration](https://docs.google.com/spreadsheets/d/1pGWX_wxGdjAVtQOmlDDfhuIc3Pbwg9FtvFXAXYu7b7c/edit#gid=0) for non-web platform messages
19- [Mojoifying Platform Features](https://docs.google.com/spreadsheets/d/1VIINt17Dg2cJjPpoJ_HY3HI0uLpidql-1u8pBJtpbGk/edit#gid=1603373208) for web platform messages
20
21This document is concerned primarily with rote conversion of legacy IPC messages
22to Mojo interface messages. If you are considering more holistic refactoring and
23better isolation of an entire subsystem of the browser, you may consider
24[servicifying](servicification.md) the feature instead of merely converting its
25IPCs.
26
27See other [Mojo & Services](/docs/README.md#Mojo-Services) documentation
28for introductory guides, API references, and more.
29
30## Legacy IPC Concepts
31
32Each Content child process has a single **`IPC::Channel`** implementation going
33between it and the browser process, and this is used as the sole two-way FIFO
34to send legacy IPC messages between the processes.
35
36There are two fundamental types of legacy IPC messages: **control** messages,
37defined via `IPC_MESSAGE_CONTROLn` macros (where `n` is some small integer) and
38**routed** messages defined via `IPC_MESSAGE_ROUTEDn` macros.
39
40Control messages generally go between a browser-side process host (*e.g.*,
41`RenderProcessHost` or `GpuProcessHost`) and the child-side `ChildThreadImpl`
42subclass. All of these classes implement `IPC::Sender` and thus have a `Send`
43method for sending a control message to their remote counterpart, and they
44implement `IPC::Listener` to receive incoming control messages via
45`OnMessageReceived`.
46
47Routed messages are relegated to **routes** which have arbitrary meaning
48determined by their use within a given process. For example, renderers use
49routes to isolate messages scoped to individual render frames, and so such
50routed messages will travel between a `RenderFrameHostImpl` and its
51corresponding `RenderFrameImpl`, both of which also implement `IPC::Sender` and
52`IPC::Listener`.
53
54## Mojo Interfaces as Routes
55
56Routed messages in the old IPC system always carry a **routing ID** to identify
57to the receiving endpoint which routed object (*e.g.* which `RenderFrameImpl`
58or `RenderViewImpl` or whatever) the message is targeting. Each endpoint is thus
59required to do some additional book-keeping to track what each routing ID means.
60
61Mojo interfaces obviate the need for routing IDs, as new "routes" can be
62established by simply creating a new interface pipe and passing one endpoint to
63something which knows how to bind it.
64
65When thinking about an IPC message conversion to Mojo, it's important to
66consider whether the message is a control message or a routed message, as this
67determines where you might find an existing Mojo interface to carry your
68message, or where you will want to add a new end-to-end Mojo interface for that
69purpose. This can mean the difference between a single per-process interface
70going between each `RenderProcessHostImpl` and its corresponding
71`RenderThreadImpl`, vs a per-frame interface going between each
72`RenderFrameHostImpl` and its corresponding `RenderFrameImpl`.
73
74## Ordering Considerations
75
76One **very important** consideration when doing IPC conversions is the relative
77ordering of IPC-driven operations. With the old IPC system, because every
78message between two processes is globally ordered, it is quite easy for parts
79of the system to (intentionally or often unintentionally) rely on strict
80ordering guarantees.
81
82For example, imagine a `WebContentsObserver` in the browser processes observes
83a frame navigation and immediately sends an IPC message to the frame to
84configure some new behavior. The implementation may be inadvertently relying on
85this message arriving *before* some other tangentially related message sent to
86the same frame shortly after the same navigation event.
87
88Mojo does not (and in fact cannot) make any strict ordering guarantees between
89separate message pipes, as message pipes may be freely moved across process
90boundaries and thus cannot necessarily share a common FIFO at all times.
91
92If the two messages described above were moved to separate Mojo interfaces on
93separate message pipes, renderer behavior could break as the first message may
94arrive after the second message.
95
96The best solution to this problem is to rethink the IPC surface and/or
97implementation on either side to eliminate ordering dependencies between two
98interfaces that otherwise seem to be logically distinct. Failing that, Mojo's
99solution to this problem is to support
100[**associated interfaces**](/mojo/public/tools/bindings/README.md#Associated-Interfaces).
101In a nutshell, these allow multiple distinct interfaces to be multiplexed over
102a shared message pipe.
103
104## Channel-Associated Interfaces
105
106The previous section mentions **associated interfaces** as a general-purpose
107solution for establishing a mutual FIFO between multiple logical Mojo interfaces
108by having them share a single message pipe.
109
110In Chrome, the `IPC::Channel` which carries all legacy IPC messages between
111two processes is itself a Mojo message pipe. We provide a mechanism for
112associating arbitrary Mojo interfaces with this pipe, which means messages can
113be converted to Mojo while preserving strict FIFO with respect to other legacy
114IPC messages. Such interfaces are designated in Chrome parlance as
115**Channel-associated interfaces**.
116
117*** aside
118**NOTE:** Channel-associated interface acquisition is not constrained by the
119Service Manager in any way, so security reviewers need to be careful to inspect
120new additions and uses of such interfaces.
121***
122
123Usage of Channel-associated interfaces should be rare but is considered a
124reasonable intermediate solution for incremental IPC conversions where it would
125be too risky or noisy to convert a large IPC surface all at once, but it would
126also be impossible to split the IPC surface between legacy IPC and a dedicated
127Mojo interface pipe without introducing timing bugs.
128
129At this point in Chrome's development, practical usage of Channel-associated
130interfaces is restricted to the `IPC::Channel` between the browser process and
131a renderer process, as this is the most complex IPC surface with the most
132implicit ordering dependencies. A few simple APIs exist to support this.
133
134`RenderProcessHostImpl` owns an `IPC::Channel` to its corresponding
135`RenderThreadImpl` in the render process. This object has a
136`GetRemoteAssociatedInterfaces` method which can be used to pass arbitrary
137associated interface requests:
138
139``` cpp
140magic::mojom::GoatTeleporterAssociatedPtr teleporter;
141channel_->GetRemoteAssociatedInterfaces()->GetInterface(&teleporter);
142
143// These messages are all guaranteed to arrive in the same order they were sent.
144channel_->Send(new FooMsg_SomeLegacyIPC);
145teleporter->TeleportAllGoats();
146channel_->Send(new FooMsg_AnotherLegacyIPC);
147```
148
149Likewise, `ChildThreadImpl` has an `IPC::Channel` that can be used in the same
150way to send such messages back to the browser.
151
152To receive and bind incoming Channel-associated interface requests, the above
153objects also implement `IPC::Listener::OnAssociatedInterfaceRequest`.
154
155For supplementation of routed messages, both `RenderFrameHostImpl` and
156`RenderFrameImpl` define a `GetRemoteAssociatedInterfaces` method which works
157like the one on `IPC::Channel`, and both objects also implement
158`IPC::Listener::OnAssociatedInterfaceRequest` for processing incoming associated
159interface requests specific to their own frame.
160
161There are some example conversion CLs which use Channel-associated interfaces
162[here](https://codereview.chromium.org/2381493003) and
163[here](https://codereview.chromium.org/2400313002).
164
165## Deciding How to Approach a Conversion
166
167There are a few questions you should ask before embarking upon any IPC message
168conversion journey, and there are many potential approaches to consider. The
169right one depends on context.
170
171Note that this section assumes the message is traveling between the browser
172process and a renderer process. Other cases are rare and developers may wish to
173consult
174[[email protected]](https://groups.google.com/a/chromium.org/forum/#!forum/chromium-mojo)
175before proceeding with them. Otherwise, apply the following basic algorithm to
176decide how to proceed:
177
178- General note: If the message is a reply to some other message (typically these
179 take a "request ID" argument), see the note about message replies at the
180 bottom of this section.
181- Consider whether or not the message makes sense as part of the IPC surface of
182 a new or existing service somewhere in `//services` or `//chrome/services`,
183 *etc.* This is less and less likely to be the case as time goes on, as many
184 remaining IPC conversions are quite narrowly dealing with specific
185 browser/renderer details rather than the browser's supporting subsystems. If
186 defining a new service, you may wish to consult some of the other
187 [Mojo & Services documentation](/docs/README.md#Mojo-Services) first.
188- If the message is an `IPC_MESSAGE_CONTROL` message:
189 - If there are likely to be strict ordering requirements between this
190 message and other legacy IPC or Channel-associated interface messages,
191 consider using a new or existing
192 [Channel-associated interface](#Channel-Associated-Interfaces) between
193 `RenderProcessHostImpl` and `RenderThreadImpl`.
194 - If the message is sent from a renderer to the browser:
195 - If an existing interface is bound by `RenderProcessHostImpl` and
196 requested through `RenderThread`'s Connector and seems to be a good
197 fit for the message, add the equivalent Mojo message to that
198 interface.
199 - If no such interface exists, consider adding one for this message and
200 any related messages.
201 - If the message is sent from the browser to a renderer:
202 - If an existing interface is bound by `RenderThreadImpl` and requested
203 through a `BrowserContext` Connector referencing a specific
204 `RenderProcessHost` [identity](https://cs.chromium.org/chromium/src/content/public/browser/render_process_host.h?rcl=1497b88b7d6400a2a5cced258df03d53800d7848&l=327),
205 and the interface seems to be a good fit for the message, add the
206 equivalent Mojo message to that interface.
207 - If no such interface exists, consider adding one for this message and
208 any related messages.
209- If the message is an `IPC_MESSAGE_ROUTED` message:
210 - Determine what the routing endpoints are. If they are
211 `RenderFrameHostImpl` and `RenderFrameImpl`:
212 - If there are likely to be strict ordering requirements between this
213 message and other legacy IPC or Channel-associated interface messages,
214 consider using a new or existing
215 [Channel-associated interface](#Channel-Associated-Interfaces) between
216 `RenderFrameHostImpl` and `RenderFrameImpl`.
217 - If the message is sent from a renderer to the browser:
218 - If an existing interface is bound by `RenderFrameHostImpl` and
219 acquired either via `RenderFrame::GetRemoteInterfaces` or
220 `RenderFrame::GetDocumentInterfaceBroker` and the interface seems
221 to be a good fit for this message, add the equivalent Mojo message
222 to that interface.
223 - If no such interface exists, consider adding one and exposing it
224 via a new getter method on `DocumentInterfaceBroker`. See the
225 [simple example](/docs/mojo_and_services.md#Example_Defining-a-New-Frame-Interface)
226 earlier in this document.
227 - If the message is sent from the browser to a renderer, consider
228 adding a Mojo equivalent to the `content.mojom.Frame` interface
229 defined
230 [here](https://cs.chromium.org/chromium/src/content/common/frame.mojom?rcl=138b66744ee9ee853cbb0ae8437b71eaa1fafaa9&l=42).
231 - If the routing endpoints are **not** frame objects (for example, they may
232 be `RenderView`/`RenderViewHost` objects), this is a special case which
233 does not yet have an easy conversion approach readily available. Contact
234 [[email protected]](https://groups.google.com/a/chromium.org/forum#!forum/chromium-mojo)
235 to propose or discuss options.
236
Oksana Zhuravlova355fa642019-02-15 22:21:04237*** aside
238**NOTE**: If you are converting a sync IPC, see the section on
239[Synchronous Calls](/mojo/public/cpp/bindings/README.md#Synchronous-Calls)
240in the Mojo documentation.
241***
242
Ken Rockotab035122019-02-06 00:35:24243### Dealing With Replies
244
245If the message is a **reply**, meaning it has a "request ID" which correlates it
246to a prior message in the opposite direction, consider converting the
247**request** message following the algorithm above. Unlike with legacy IPC, Mojo
248messages support replies as a first-class concept. So for example if you have:
249
250``` cpp
251IPC_CONTROL_MESSAGE2(FooHostMsg_DoTheThing,
252 int /* request_id */,
253 std::string /* name */);
254IPC_CONTROL_MESSAGE2(FooMsg_DidTheThing,
255 int /* request_id */,
256 bool /* success */);
257```
258
259You should consider defining an interface `Foo` which is bound in
260`RenderProcessHostImpl` and acquired from `RenderThreadImpl`, with the following
261mojom definition:
262
263``` cpp
264interface Foo {
265 DoTheThing(string name) => (bool success);
266};
267```
Oksana Zhuravlova87b225a2019-03-07 01:08:03268See [Receiving responses](/mojo/public/cpp/bindings/README.md#receiving-responses)
269for more information.
Ken Rockotab035122019-02-06 00:35:24270
271## Repurposing `IPC::ParamTraits` and `IPC_STRUCT*` Invocations
272
273Occasionally it is useful to do partial IPC conversions, where you want to
274convert a message to a Mojo interface method but you don't want to necessarily
275convert every structure passed by the message. In this case, you can leverage
276Mojo's
277[type-mapping](https://chromium.googlesource.com/chromium/src/+/master/mojo/public/cpp/bindings/README.md#Type-Mapping)
278system to repurpose existing `IPC::ParamTraits`.
279
280*** aside
281**NOTE**: Although in some cases `IPC::ParamTraits<T>` specializations are
282defined manually in library code, the `IPC_STRUCT*` macro helpers also define
283`IPC::ParamTraits<T>` specializations under the hood. All advice in this section
284pertains to both kinds of definitions.
285***
286
287If a mojom struct is declared without a struct body and is tagged with
288`[Native]`, and a corresponding typemap is provided for the struct, the emitted
289C++ bindings will -- as if by magic -- replace the mojom type with the
290typemapped C++ type and will internally use the existing `IPC::ParamTraits<T>`
291specialization for that type in order to serialize and deserialize the struct.
292
293For example, given the
294[`resource_messages.h`](https://cs.chromium.org/chromium/src/content/common/resource_messages.h?rcl=2e7a430d8d88222c04ab3ffb0a143fa85b3cec5b&l=215) header
295which defines an IPC mapping for `content::ResourceRequest`:
296
297``` cpp
298IPC_STRUCT_TRAITS_BEGIN(content::ResourceRequest)
299 IPC_STRUCT_TRAITS_MEMBER(method)
300 IPC_STRUCT_TRAITS_MEMBER(url)
301 // ...
302IPC_STRUCT_TRAITS_END()
303```
304
305and the
306[`resource_request.h`](https://cs.chromium.org/chromium/src/content/common/resource_request.h?rcl=dce9e476a525e4ff0304787935dc1a8c38392ac8&l=32) header
307which actually defines the `content::ResourceRequest` type:
308
309``` cpp
310namespace content {
311
312struct CONTENT_EXPORT ResourceRequest {
313 // ...
314};
315
316} // namespace content
317```
318
319we can declare a corresponding "native" mojom struct:
320
321``` cpp
322module content.mojom;
323
324[Native]
325struct URLRequest;
326```
327
328and add a typemap like
329[`url_request.typemap`](https://cs.chromium.org/chromium/src/content/common/url_request.typemap?rcl=4b5963fa744a706398f8f06a4cbbf70d7fa3213d)
330to define how to map between them:
331
332``` python
333mojom = "//content/public/common/url_loader.mojom"
334public_headers = [ "//content/common/resource_request.h" ]
335traits_headers = [ "//content/common/resource_messages.h" ]
336...
337type_mappings = [ "content.mojom.URLRequest=content::ResourceRequest" ]
338```
339
340Note specifically that public_headers includes the definition of the native C++
341type, and traits_headers includes the definition of the legacy IPC traits.
342
343As a result of all this, other mojom files can now reference
344`content.mojom.URLRequest` as a type for method parameters and other struct
345fields, and the generated C++ bindings will represent those values exclusively
346as `content::ResourceRequest` objects.
347
348This same basic approach can be used to leverage existing `IPC_ENUM_TRAITS` for
349invocations for `[Native]` mojom enum aliases.
350
351*** aside
352**NOTE:** Use of `[Native]` mojom definitions is strictly limited to C++
353bindings. If a mojom message depends on such definitions, it cannot be sent or
354received by other language bindings. This feature also depends on continued
355support for legacy IPC serialization and all uses of it should therefore be
356treated as technical debt.
357***
358
Oksana Zhuravlova4f3692b2019-02-08 21:00:58359## Blink-Specific Advice
360
361### Variants
362Let's assume we have a mojom file such as this:
363
364``` cpp
365module example.mojom;
366
367interface Foo {
368 SendData(string param1, array<int32> param2);
369};
370```
371
372The following GN snippet will generate two concrete targets: `example` and
373`example_blink`:
374
375```
376mojom("example") {
377 sources = [ "example.mojom" ]
378}
379```
380
381The target `example` will generate Chromium-style C++ bindings using STL types:
382
383``` cpp
384// example.mojom.h
385namespace example {
386namespace mojom {
387
388class Example {
389 virtual void SendArray(const std::string& param1, const std::vector<int32_t>& param2) = 0;
390}
391
392} // namespace mojom
393} // namespace example
394```
395
396The target `example_blink` will generate Blink-style C++ bindings using WTF types:
397
398``` cpp
399// example.mojom-blink.h
400namespace example {
401namespace mojom {
402namespace blink {
403
404class Example {
405 virtual void SendArray(const WTF::String& param1, const WTF::Vector<int32_t>& param2) = 0;
406}
407
408} // namespace blink
409} // namespace mojom
410} // namespace example
411```
412
413Thanks to these separate sets of bindings no work is necessary to convert types
414between Blink-style code and Chromium-style code. It is handled automatically
415during message serialization and deserialization.
416
417For more information about variants, see
418[this section](/mojo/public/cpp/bindings/README.md#Variants) of the C++ bindings
419documentation.
420
421### Binding callbacks
422
423Mojo methods that return a value take an instance of `base::OnceCallback`.
424Use `WTF::Bind()` and an appropriate wrapper function depending on the type of
425object and the callback.
426
427For garbage-collected (Oilpan) classes owning the `InterfacePtr`, it is recommended
Oksana Zhuravlova6fac3d132019-02-19 23:58:33428to use `WrapWeakPersistent(this)` for connection error handlers since they
429are not guaranteed to get called in a finite time period (wrapping the object
430with `WrapPersistent` in this case would cause memory leaks).
431
432If the response can be discarded in case the object is not alive by the time
433the response is received, use `WrapWeakPersistent(this)` for binding the response callback:
Oksana Zhuravlova4f3692b2019-02-08 21:00:58434
435``` cpp
Oksana Zhuravlova6fac3d132019-02-19 23:58:33436// src/third_party/blink/renderer/modules/device_orientation/device_sensor_entry.cc
437sensor_.set_connection_error_handler(WTF::Bind(
438 &DeviceSensorEntry::HandleSensorError, WrapWeakPersistent(this)));
439sensor_->ConfigureReadingChangeNotifications(/*enabled=*/false);
440sensor_->AddConfiguration(
441 std::move(config), WTF::Bind(&DeviceSensorEntry::OnSensorAddConfiguration,
442 WrapWeakPersistent(this)));
443```
444
445Otherwise (for example, if the response callback is used to resolve a Promise),
446use `WrapPersistent(this)` to keep the object alive:
447
448``` cpp
449// src/third_party/blink/renderer/modules/nfc/nfc.cc
450ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
451...
452nfc_->CancelAllWatches(WTF::Bind(&NFC::OnRequestCompleted,
453 WrapPersistent(this),
454 WrapPersistent(resolver)));
Oksana Zhuravlova4f3692b2019-02-08 21:00:58455```
456
457Non-garbage-collected objects can use `WTF::Unretained(this)` for both response
458and error handler callbacks when the `InterfacePtr` is owned by the object bound
459to the callback or the object is guaranteed to outlive the Mojo connection for
460another reason. Otherwise a weak pointer should be used. However, it is not a
461common pattern since using Oilpan is recommended for all Blink code.
462
463### Implementing Mojo interfaces in Blink
464
465Only a `mojo::Binding` or `mojo::BindingSet` should be used when implementing a
466Mojo interface in an Oilpan-managed object. The object must then have a pre-finalizer
467to close any open pipes when the object is about to be swept as lazy sweeping
468means that it may be invalid long before the destructor is called. This requires
469setup in both the object header and implementation.
470
471``` cpp
472// MyObject.h
473class MyObject : public GarbageCollected,
474 public example::mojom::blink::Example {
475 USING_PRE_FINALIZER(MyObject, Dispose);
476
477 public:
478 MyObject();
479 void Dispose();
480
481 // Implementation of example::mojom::blink::Example.
482
483 private:
484 mojo::Binding<example::mojom::blink::Example> m_binding{this};
485};
486
487// MyObject.cpp
488void MyObject::Dispose() {
489 m_binding.Close();
490}
491```
492
493For more information about Blink's Garbage Collector, see
494[Blink GC API Reference](/third_party/blink/renderer/platform/heap/BlinkGCAPIReference.md).
495
496### Typemaps For Content and Blink Types
Ken Rockotab035122019-02-06 00:35:24497
498Using typemapping for messages that go between Blink and content browser code
499can sometimes be tricky due to things like dependency cycles or confusion over
500the correct place for some definition
501to live. There are some example CLs provided here, but feel free to also contact
502[[email protected]](https://groups.google.com/a/chromium.org/forum/#!forum/chromium-mojo)
503with specific details if you encounter trouble.
504
505[This CL](https://codereview.chromium.org/2363533002) introduces a Mojom
506definition and typemap for `ui::WindowOpenDisposition` as a precursor to the
507IPC conversion below.
508
509The [follow-up CL](https://codereview.chromium.org/2363573002) uses that
510definition along with several other new typemaps (including native typemaps as
511described above) to convert the relatively large `ViewHostMsg_CreateWindow`
512message to Mojo.
513
514## Additional Support
515
516If this document was not helpful in some way, please post a message to your
517friendly
518[[email protected]](https://groups.google.com/a/chromium.org/forum/#!forum/chromium-mojo)
519mailing list.