This document contains the minimum amount of information needed for a developer to start using Mojo effectively in Chromium, with example Mojo interface usage, service definition and hookup, and a brief overview of the Content layer's core services.
See otherMojo & Services documentation for introductory guides, API references, and more.
Amessage pipe is a pair ofendpoints. Each endpoint has a queue of incoming messages, and writing a message at one endpoint effectively enqueues that message on the other (peer) endpoint. Message pipes are thus bidirectional.
Amojom file describesinterfaces, which are strongly-typed collections ofmessages. Each interface message is roughly analogous to a single proto message, for developers who are familiar with Google protobufs.
Given a mojom interface and a message pipe, one of the endpoints can be designated as aRemote
and is used tosend messages described by the interface. The other endpoint can be designated as aReceiver
and is used toreceive interface messages.
Receiver
endpoint and received by theRemote
endpoint.TheReceiver
endpoint must be associated with (i.e.bound to) animplementation of its mojom interface in order to process received messages. A received message is dispatched as a scheduled task invoking the corresponding interface method on the implementation object.
Another way to think about all this is simply thataRemote
makes calls on a remote implementation of its interface associated with a corresponding remoteReceiver
.
Let's apply this to Chrome. Suppose we want to send a “Ping” message from a render frame to its correspondingRenderFrameHostImpl
instance in the browser process. We need to define a nice mojom interface for this purpose, create a pipe to use that interface, and then plumb one end of the pipe to the right place so the sent messages can be received and processed there. This section goes through that process in detail.
The first step involves creating a new.mojom
file with an interface definition, like so:
// src/example/public/mojom/pingable.mojommodule example.mojom;interfacePingable{// Receives a "Ping" and responds with a random integer.Ping()=>(int32 random);};
This should have a corresponding build rule to generate C++ bindings for the definition here:
# src/example/public/mojom/BUILD.gnimport("//mojo/public/tools/bindings/mojom.gni")mojom("mojom"){ sources=["pingable.mojom"]}
Now let's create a message pipe to use this interface.
Remote
side) is typically the party who creates a new pipe. This is convenient because theRemote
may be used to start sending messages immediately without waiting for the InterfaceRequest endpoint to be transferred or bound anywhere.This code would be placed somewhere in the renderer:
// src/third_party/blink/example/public/pingable.hmojo::Remote<example::mojom::Pingable> pingable;mojo::PendingReceiver<example::mojom::Pingable> receiver= pingable.BindNewPipeAndPassReceiver();
In this example,pingable
is theRemote
, andreceiver
is aPendingReceiver
, which is aReceiver
precursor that will eventually be turned into aReceiver
.BindNewPipeAndPassReceiver
is the most common way to create a message pipe: it yields thePendingReceiver
as the return value.
PendingReceiver
doesn't actuallydo anything. It is an inert holder of a single message pipe endpoint. It exists only to make its endpoint more strongly-typed at compile-time, indicating that the endpoint expects to be bound by aReceiver
of the same interface type.Finally, we can call thePing()
method on ourRemote
to send a message:
// src/third_party/blink/example/public/pingable.hpingable->Ping(base::BindOnce(&OnPong));
pingable
object alive untilOnPong
is invoked. After all,pingable
owns its message pipe endpoint. If it's destroyed then so is the endpoint, and there will be nothing to receive the response message.We‘re almost done! Of course, if everything were this easy, this document wouldn’t need to exist. We've taken the hard problem of sending a message from a renderer process to the browser process, and transformed it into a problem where we just need to take thereceiver
object from above and pass it to the browser process somehow where it can be turned into aReceiver
that dispatches its received messages.
PendingReceiver
to the BrowserIt's worth noting thatPendingReceiver
s (and message pipe endpoints in general) are just another type of object that can be freely sent over mojom messages. The most common way to get aPendingReceiver
somewhere is to pass it as a method argument on some other already-connected interface.
One such interface which we always have connected between a renderer'sRenderFrameImpl
and its correspondingRenderFrameHostImpl
in the browser isBrowserInterfaceBroker
. This interface is a factory for acquiring other interfaces. ItsGetInterface
method takes aGenericPendingReceiver
, which allows passing arbitrary interface receivers.
interfaceBrowserInterfaceBroker{GetInterface(mojo_base.mojom.GenericPendingReceiver receiver);}
SinceGenericPendingReceiver
can be implicitly constructed from any specificPendingReceiver
, it can call this method with thereceiver
object it created earlier viaBindNewPipeAndPassReceiver
:
RenderFrame* my_frame=GetMyFrame();my_frame->GetBrowserInterfaceBroker().GetInterface(std::move(receiver));
This will transfer thePendingReceiver
endpoint to the browser process where it will be received by the correspondingBrowserInterfaceBroker
implementation. More on that below.
Finally, we need a browser-side implementation of ourPingable
interface.
#include"example/public/mojom/pingable.mojom.h"classPingableImpl: example::mojom::Pingable{public:explicitPingableImpl(mojo::PendingReceiver<example::mojom::Pingable> receiver): receiver_(this, std::move(receiver)){}PingableImpl(constPingableImpl&)=delete;PingableImpl&operator=(constPingableImpl&)=delete;// example::mojom::Pingable:voidPing(PingCallback callback) override{// Respond with a random 4, chosen by fair dice roll. std::move(callback).Run(4);}private: mojo::Receiver<example::mojom::Pingable> receiver_;};
RenderFrameHostImpl
owns an implementation ofBrowserInterfaceBroker
. When this implementation receives aGetInterface
method call, it calls the handler previously registered for this specific interface.
// render_frame_host_impl.hclassRenderFrameHostImpl...voidGetPingable(mojo::PendingReceiver<example::mojom::Pingable> receiver);...private:... std::unique_ptr<PingableImpl> pingable_;...};// render_frame_host_impl.ccvoidRenderFrameHostImpl::GetPingable( mojo::PendingReceiver<example::mojom::Pingable> receiver){ pingable_= std::make_unique<PingableImpl>(std::move(receiver));}// browser_interface_binders.ccvoidPopulateFrameBinders(RenderFrameHostImpl* host, mojo::BinderMap*map){...// Register the handler for Pingable.map->Add<example::mojom::Pingable>(base::BindRepeating(&RenderFrameHostImpl::GetPingable, base::Unretained(host)));}
And we're done. This setup is sufficient to plumb a new interface connection between a renderer frame and its browser-side host object!
Assuming we kept ourpingable
object alive in the renderer long enough, we would eventually see itsOnPong
callback invoked with the totally random value of4
, as defined by the browser-side implementation above.
The previous section only scratches the surface of how Mojo IPC is used in Chromium. While renderer-to-browser messaging is simple and possibly the most prevalent usage by sheer code volume, we are incrementally decomposing the codebase into a set of services with a bit more granularity than the traditional Content browser/renderer/gpu/utility process split.
Aservice is a self-contained library of code which implements one or more related features or behaviors and whose interaction with outside code is doneexclusively through Mojo interface connections, typically brokered by the browser process.
Each service defines and implements a main Mojo interface which can be used by the browser to manage an instance of the service.
There are multiple steps typically involved to get a new service up and running in Chromium:
This section walks through these steps with some brief explanations. For more thorough documentation of the concepts and APIs used herein, see theMojo documentation.
Typically service definitions are placed in aservices
directory, either at the top level of the tree or within some subdirectory. In this example, we‘ll define a new service for use by Chrome specifically, so we’ll define it within//chrome/services
.
We can create the following files. First some mojoms:
// src/chrome/services/math/public/mojom/math_service.mojommodule math.mojom;interfaceMathService{Divide(int32 dividend,int32 divisor)=>(int32 quotient);};
# src/chrome/services/math/public/mojom/BUILD.gnimport("//mojo/public/tools/bindings/mojom.gni")mojom("mojom"){ sources=["math_service.mojom",]}
Then the actualMathService
implementation:
// src/chrome/services/math/math_service.h#include"chrome/services/math/public/mojom/math_service.mojom.h"namespace math{classMathService:public mojom::MathService{public:explicitMathService(mojo::PendingReceiver<mojom::MathService> receiver);MathService(constMathService&)=delete;MathService&operator=(constMathService&)=delete;~MathService() override;private:// mojom::MathService:voidDivide(int32_t dividend,int32_t divisor,DivideCallback callback) override; mojo::Receiver<mojom::MathService> receiver_;};}// namespace math
// src/chrome/services/math/math_service.cc#include"chrome/services/math/math_service.h"namespace math{MathService::MathService(mojo::PendingReceiver<mojom::MathService> receiver): receiver_(this, std::move(receiver)){}MathService::~MathService()=default;voidMathService::Divide(int32_t dividend,int32_t divisor,DivideCallback callback){// Respond with the quotient! std::move(callback).Run(dividend/ divisor);}}// namespace math
# src/chrome/services/math/BUILD.gnsource_set("math"){ sources=["math_service.cc","math_service.h",] deps=["//base","//chrome/services/math/public/mojom",]}
Now we have a fully definedMathService
implementation that we can make available in- or out-of-process.
For an out-of-process Chrome service, we simply register a factory function in//chrome/utility/services.cc
.
autoRunMathService(mojo::PendingReceiver<math::mojom::MathService> receiver){return std::make_unique<math::MathService>(std::move(receiver));}voidRegisterMainThreadServices(mojo::ServiceFactory& services){// Existing services... services.Add(RunFilePatcher); services.Add(RunUnzipper);// We add our own factory to this list services.Add(RunMathService);//...
With this done, it is now possible for the browser process to launch new out-of-process instances of MathService.
If you‘re running your service in-process, there’s really nothing interesting left to do. You can instantiate the service implementation just like any other object, yet you can also talk to it via a Mojo Remote as if it were out-of-process.
To launch an out-of-process service instance after the hookup performed in the previous section, use Content'sServiceProcessHost
API:
mojo::Remote<math::mojom::MathService> math_service= content::ServiceProcessHost::Launch<math::mojom::MathService>( content::ServiceProcessHost::Options().WithDisplayName("Math!").Pass());
Except in the case of crashes, the launched process will live as long asmath_service
lives. As a corollary, you can force the process to be torn down by destroying (or resetting)math_service
.
We can now perform an out-of-process division:
// NOTE: As a client, we do not have to wait for any acknowledgement or// confirmation of a connection. We can start queueing messages immediately and// they will be delivered as soon as the service is up and running.math_service->Divide(42,6, base::BindOnce([](int32_t quotient){ LOG(INFO)<< quotient;}));
mojo::Remote<math::mojom::MathService>
object must be kept alive (seethis section andthis note from an earlier section).All services must specify a sandbox. Ideally services will run inside thekService
process sandbox unless they need access to operating system resources. For services that need a custom sandbox, a new sandbox type must be defined in consultation withsecurity-dev@chromium.org.
The preferred way to define the sandbox for your interface is by specifying a[ServiceSandbox=type]
attribute on yourinterface {}
in its.mojom
file:
import "sandbox/policy/mojom/sandbox.mojom";[ServiceSandbox=sandbox.mojom.Sandbox.kService]interface FakeService { ...};
Valid values are those in//sandbox/policy/mojom/sandbox.mojom
. Note that the sandbox is only applied if the interface is launched out-of-process usingcontent::ServiceProcessHost::Launch()
.
As a last resort, dynamic or feature based mapping to an underlying platform sandbox can be achieved but requires plumbing through ContentBrowserClient (e.g.ShouldSandboxNetworkService()
).
We define an explicit mojom interface with a persistent connection between a renderer's frame object and the correspondingRenderFrameHostImpl
in the browser process. This interface is calledBrowserInterfaceBroker
and is fairly easy to work with: you add a new method onRenderFrameHostImpl
:
voidRenderFrameHostImpl::GetGoatTeleporter( mojo::PendingReceiver<magic::mojom::GoatTeleporter> receiver){ goat_teleporter_receiver_.Bind(std::move(receiver));}
and register this method inPopulateFrameBinders
function inbrowser_interface_binders.cc
, which maps specific interfaces to their handlers in respective hosts:
// //content/browser/browser_interface_binders.ccvoidPopulateFrameBinders(RenderFrameHostImpl* host, mojo::BinderMap*map){...map->Add<magic::mojom::GoatTeleporter>(base::BindRepeating(&RenderFrameHostImpl::GetGoatTeleporter, base::Unretained(host)));}
It's also possible to bind an interface on a different sequence by specifying a task runner:
// //content/browser/browser_interface_binders.ccvoidPopulateFrameBinders(RenderFrameHostImpl* host, mojo::BinderMap*map){...map->Add<magic::mojom::GoatTeleporter>(base::BindRepeating(&RenderFrameHostImpl::GetGoatTeleporter, base::Unretained(host)),GetIOThreadTaskRunner({}));}
Workers also haveBrowserInterfaceBroker
connections between the renderer and the corresponding remote implementation in the browser process. Adding new worker-specific interfaces is similar to the steps detailed above for frames, with the following differences:
DedicatedWorkerHost
and register it inPopulateDedicatedWorkerBinders
SharedWorkerHost
and register it inPopulateSharedWorkerBinders
ServiceWorkerHost
and register it inPopulateServiceWorkerBinders
Interfaces can also be added at the process level using theBrowserInterfaceBroker
connection between the BlinkPlatform
object in the renderer and the correspondingRenderProcessHost
object in the browser process. This allows any thread (including frame and worker threads) in the renderer to access the interface, but comes with additional overhead because theBrowserInterfaceBroker
implementation used must be thread-safe. To add a new process-level interface, add a new method toRenderProcessHostImpl
and register it using a call toAddUIThreadInterface
inRenderProcessHostImpl::RegisterMojoInterfaces
. On the renderer side, usePlatform::GetBrowserInterfaceBroker
to retrieve the correspondingBrowserInterfaceBroker
object to callGetInterface
on.
For binding an embedder-specific document-scoped interface, overrideContentBrowserClient::RegisterBrowserInterfaceBindersForFrame()
and add the binders to the provided map.
ReportNoBinderForInterface()
on the relevant context host, which results in aReportBadMessage()
call on the host‘s receiver (one of the consequences is a termination of the renderer). To avoid this crash in tests (when content_shell doesn’t bind some Chrome-specific interfaces, but the renderer requests them anyway), use theEmptyBinderForFrame
helper inbrowser_interface_binders.cc
. However, it is recommended to have the renderer and browser sides consistent if possible.For cases where the ordering of messages from different frames is important, and when messages need to be ordered correctly with respect to the messages implementing navigation, navigation-associated interfaces can be used. Navigation-associated interfaces leverage connections from each frame to the correspondingRenderFrameHostImpl
object and send messages from each connection over the same FIFO pipe that's used for messages relating to navigation. As a result, messages sent after a navigation are guaranteed to arrive in the browser process after the navigation-related messages, and the ordering of messages sent from different frames of the same document is preserved as well.
To add a new navigation-associated interface, create a new method forRenderFrameHostImpl
and register it with a call toassociated_registry_->AddInterface
inRenderFrameHostImpl::SetUpMojoConnection
. From the renderer, useLocalFrame::GetRemoteNavigationAssociatedInterfaces
to get an object to callGetInterface
on (this call is similar toBrowserInterfaceBroker::GetInterface
except that it takes apending associated receiver instead of a pending receiver).
If this document was not helpful in some way, please post a message to your friendlychromium-mojo@chromium.org orservices-dev@chromium.org mailing list.