chrome services and mojom

  • 客户端:

使用mojom,两个配对出现:一个remote,一个根据remote生成的receiver。

remote是远程接口。另外一个根据remote生成个 pendingReceiver. 这个receiver最终传递给实现端。pipe就建立好了。

// src/third_party/blink/example/public/pingable.h
mojo::Remote<example::mojom::Pingable> pingable;
mojo::PendingReceiver<example::mojom::Pingable> receiver =
    pingable.BindNewPipeAndPassReceiver();

利用已有连接RenderFrame。让它去找对应的实现:

RenderFrame* my_frame = GetMyFrame();
my_frame->GetBrowserInterfaceBroker().GetInterface(std::move(receiver)); //GetBrowserInterfaceBroker 是远程方法。

BrowserInterfaceBroker 位于renderer进程的浏览器接口代理。broker代理在对应的RenderFrameHost端有实现,是个工厂方法,通过GetInterface 去找到这个其他远程接口对应的实现。就连接上了。(所以服务端肯定需要加上,去注册上GetPingable接口实现对象

  • 对应服务端

也需要有实现,注册到broker上:

初始化时放到RenderFrameHostImpl的map里面:GetPingable创建接口实现对象

map->Add<example::mojom::Pingable>(base::BindRepeating( &RenderFrameHostImpl::GetPingable, base::Unretained(host)));

GetInterface会找到上面注册的接口,调用bind好的GetPingable:它会创建个PingableImpl的对象。

  ...
  void GetPingable(mojo::PendingReceiver<example::mojom::Pingable> receiver);
  ...
 private:
  ...
  std::unique_ptr<PingableImpl> pingable_;
  ...
};

// render_frame_host_impl.cc
void RenderFrameHostImpl::GetPingable(
    mojo::PendingReceiver<example::mojom::Pingable> receiver) {
  pingable_ = std::make_unique<PingableImpl>(std::move(receiver));
}

 

RenderFrame和它的host方便的绑定:

一种bind就是添加到 ReceiverSet中。另一种是最终进入DocumentService,生成 一个receiver对象
void RenderFrameHostImpl::GetAudioContextManager(
    mojo::PendingReceiver<blink::mojom::AudioContextManager> receiver) {
  AudioContextManagerImpl::Create(this, std::move(receiver));
}//这里通过 receiver_(this, std::move(pending_receiver)); this是DocumentService : public Interface

void RenderFrameHostImpl::GetFileSystemManager(
    mojo::PendingReceiver<blink::mojom::FileSystemManager> receiver) {
  // This is safe because file_system_manager_ is deleted on the IO thread
  GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&FileSystemManagerImpl::BindReceiver,
                                base::Unretained(file_system_manager_.get()),
                                storage_key(), std::move(receiver)));
}//   mojo::ReceiverSet<blink::mojom::FileSystemManager, blink::StorageKey>
 //     receivers_;
//    receivers_.Add(this, std::move(receiver), storage_key);

void RenderFrameHostImpl::GetGeolocationService(
    mojo::PendingReceiver<blink::mojom::GeolocationService> receiver) {
  if (!geolocation_service_) {
    auto* geolocation_context = delegate_->GetGeolocationContext();
    if (!geolocation_context)
      return;
    geolocation_service_ =
        std::make_unique<GeolocationServiceImpl>(geolocation_context, this);
  }
  geolocation_service_->Bind(std::move(receiver));
}//  std::unique_ptr<GeolocationServiceImpl> geolocation_service_;
// Bind的实现也是 receiverSets:
// receiver_set_.Add(this, std::move(receiver),
//                    std::make_unique<GeolocationServiceImplContext>());
//其中类impl也是个mojom接口:class GeolocationServiceImpl: public blink::mojom::GeolocationService

 


ppt

 

 

 

 

关于urlLoader举例:

 

之间关系:

 

 

 

 


Intro to Mojo & Services

[TOC]

Overview

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 other Mojo & Services documentation for introductory guides, API references, and more.

Mojo Terminology

message pipe is a pair of endpoints. 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.

mojom file describes interfaces, which are strongly-typed collections of messages. 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 a Remote and is used to send messages described by the interface. The other endpoint can be designated as a Receiver and is used to receive interface messages.

*** aside NOTE: The above generalization is a bit oversimplified. Remember that the message pipe is still bidirectional, and it's possible for a mojom message to expect a reply. Replies are sent from the Receiver endpoint and received by the Remote endpoint.


The Receiver endpoint must be associated with (i.e. bound to) an implementation 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 that Remote makes calls on a remote implementation of its interface associated with a corresponding remote Receiver.

这里的 remote ,就是指一个远程接口。客户端声明一个 远程接口,就可以调用远程方法(即发消息);receiver,是服务端,是对接口的实现。(其实pipe是双工的)

mojom就是对信息的格式化Typed。

Example: Defining a New Frame Interface

Let's apply this to Chrome. Suppose we want to send a "Ping" message from a render frame to its corresponding RenderFrameHostImpl 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.

示例是从render进程要调用一个实现在browser进程的跨进程调用。所以render方需要一个浏览器方代理: BrowserInterfaceBroker

Defining the Interface

The first step involves creating a new .mojom file with an interface definition, like so:

// src/example/public/mojom/pingable.mojom
module example.mojom;

interface Pingable {
  // 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.gn
import("//mojo/public/tools/bindings/mojom.gni")
mojom("mojom") {
  sources = [ "pingable.mojom" ]
}

Creating the Pipe

Now let's create a message pipe to use this interface.

*** aside As a general rule and as a matter of convenience when using Mojo, the client of an interface (i.e. the Remote side) is typically the party who creates a new pipe. This is convenient because the Remote may be used to start sending messages immediately without waiting for the InterfaceRequest endpoint to be transferred or bound anywhere.

render进程声明是客户端接口,即remote方。客户端remote是可以创建一个新pipe的一方。这样做的原因是为了pipe创建后就可以使用,而不用等待知道pipe真正绑定到一个通道上。


This code would be placed somewhere in the renderer:

// src/third_party/blink/example/public/pingable.h
mojo::Remote<example::mojom::Pingable> pingable;
mojo::PendingReceiver<example::mojom::Pingable> receiver =
    pingable.BindNewPipeAndPassReceiver();

In this example, pingable is the Remote, and receiver is a PendingReceiver, which is a Receiver precursor that will eventually be turned into a ReceiverBindNewPipeAndPassReceiver is the most common way to create a message pipe: it yields the PendingReceiver as the return value.

*** aside NOTE: A PendingReceiver doesn't actually do 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 a Receiver of the same interface type.

pingable 是个remote接口,receiver 是个PendingReceiver,因为它最终会转变成真正的绑定到管道上的Receiver,但还没到时候 not yet。

PendingReceiver是通过 BindNewPipeAndPassReceiver 产生,其他它什么也没有做。

PendingReceiver的存在只是说明它是个通道的一端,在编译期间是强类型的,并且最终期望会绑定到相同类型Receiver上。


Sending a Message

Finally, we can call the Ping() method on our Remote to send a message:

// src/third_party/blink/example/public/pingable.h
pingable->Ping(base::BindOnce(&OnPong));

*** aside IMPORTANT: If we want to receive the response, we must keep the pingable object alive until OnPong 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.

已经可以发出远程调用了,虽然目前还没有通道,是pending状态。

OnPong的实现是接受返回值的,可以实现成:

void OnPong(int i){
//dosomething
}

上面的函数参数i就是Ping函数返回值:int32 random。 

   Ping() => (int32 random);


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 the receiver object from above and pass it to the browser process somehow where it can be turned into a Receiver that dispatches its received messages.

Sending a PendingReceiver to the Browser

It's worth noting that PendingReceivers (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 a PendingReceiver 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's RenderFrameImpl and its corresponding RenderFrameHostImpl in the browser is BrowserInterfaceBroker. This interface is a factory for acquiring other interfaces. Its GetInterface method takes a GenericPendingReceiver, which allows passing arbitrary interface receivers.

interface BrowserInterfaceBroker {
  GetInterface(mojo_base.mojom.GenericPendingReceiver receiver);
}

Since GenericPendingReceiver can be implicitly constructed from any specific PendingReceiver, it can call this method with the receiver object it created earlier via BindNewPipeAndPassReceiver:

RenderFrame* my_frame = GetMyFrame();
my_frame->GetBrowserInterfaceBroker().GetInterface(std::move(receiver));

This will transfer the PendingReceiver endpoint to the browser process where it will be received by the corresponding BrowserInterfaceBroker implementation. More on that below.

PendingReceiver也无非是一个可以在通道中发送的消息。为了让他找到服务端变成receiver,简单的方法就是利用已有通道,送到那里。render进程已经有个远程接口my_frame->GetBrowserInterfaceBroker(),获取到remote接口BrowserInterfaceBroker,这个工厂有个方法可以获取到其他的接口:GetInterface 。这个调用将最终传送 PendingReceiver 至 BrowserInterfaceBroker 工厂,通过 GetInterface 找到远程 Pingable的实现。

Implementing the Interface

Finally, we need a browser-side implementation of our Pingable interface.

#include "example/public/mojom/pingable.mojom.h"

class PingableImpl : example::mojom::Pingable {
 public:
  explicit PingableImpl(mojo::PendingReceiver<example::mojom::Pingable> receiver)
      : receiver_(this, std::move(receiver)) {}
  PingableImpl(const PingableImpl&) = delete;
  PingableImpl& operator=(const PingableImpl&) = delete;

  // example::mojom::Pingable:
  void Ping(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 of BrowserInterfaceBroker. When this implementation receives a GetInterface method call, it calls the handler previously registered for this specific interface.

RenderFrameHostImpl 实现了 BrowserInterfaceBroker. 当 GetInterface 被调用时,它调用对这个特定接口的handler处理方法。通过PopulateFrameBinders将对Pingable的处理方法放入map中。以后有人调用GetInterface(Pingable)获取远程接口时,就会从map中找到对应的闭包方法 RenderFrameHostImpl::GetPingable。这个方法实现创建真正的PingableImpl实例。

// render_frame_host_impl.h
class RenderFrameHostImpl
  ...
  void GetPingable(mojo::PendingReceiver<example::mojom::Pingable> receiver);
  ...
 private:
  ...
  std::unique_ptr<PingableImpl> pingable_;
  ...
};

// render_frame_host_impl.cc
void RenderFrameHostImpl::GetPingable(
    mojo::PendingReceiver<example::mojom::Pingable> receiver) {
  pingable_ = std::make_unique<PingableImpl>(std::move(receiver));
}

// browser_interface_binders.cc
void PopulateFrameBinders(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 our pingable object alive in the renderer long enough, we would eventually see its OnPong callback invoked with the totally random value of 4, as defined by the browser-side implementation above.

Services Overview & Terminology

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.

service is a self-contained library of code which implements one or more related features or behaviors and whose interaction with outside code is done exclusively 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.

现在的chrome使用service,实现一些特性。与外界交互只通过mojo接口。由browser进程创建service实例,运行在browser进程。由brower进程去代理这些接口。

Example: Building a Simple Out-of-Process Service

There are multiple steps typically involved to get a new service up and running in Chromium:

  • Define the main service interface and implementation
  • Hook up the implementation in out-of-process code
  • Write some browser logic to launch a service process

This section walks through these steps with some brief explanations. For more thorough documentation of the concepts and APIs used herein, see the Mojo documentation.

Defining the Service

Typically service definitions are placed in a services 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.mojom
module math.mojom;

interface MathService {
  Divide(int32 dividend, int32 divisor) => (int32 quotient);
};
# src/chrome/services/math/public/mojom/BUILD.gn
import("//mojo/public/tools/bindings/mojom.gni")

mojom("mojom") {
  sources = [
    "math_service.mojom",
  ]
}

Then the actual MathService implementation:

// src/chrome/services/math/math_service.h
#include "chrome/services/math/public/mojom/math_service.mojom.h"

namespace math {

class MathService : public mojom::MathService {
 public:
  explicit MathService(mojo::PendingReceiver<mojom::MathService> receiver);
  MathService(const MathService&) = delete;
  MathService& operator=(const MathService&) = delete;
  ~MathService() override;

 private:
  // mojom::MathService:
  void Divide(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;

void MathService::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.gn

source_set("math") {
  sources = [
    "math_service.cc",
    "math_service.h",
  ]

  deps = [
    "//base",
    "//chrome/services/math/public/mojom",
  ]
}

Now we have a fully defined MathService implementation that we can make available in- or out-of-process.

Hooking Up the Service Implementation

For an out-of-process Chrome service, we simply register a factory function in //chrome/utility/services.cc.

auto RunMathService(mojo::PendingReceiver<math::mojom::MathService> receiver) {
  return std::make_unique<math::MathService>(std::move(receiver));
}

void RegisterMainThreadServices(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.

Launching the Service

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.

服务service位于同一进程的话,可以像普通对象创建那样访问,也可以像跨进程那样用Remote接口访问。

To launch an out-of-process service instance after the hookup performed in the previous section, use Content's ServiceProcessHost 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 as math_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; }));

*** aside NOTE: To ensure the execution of the response callback, the mojo::Remote<math::mojom::MathService> object must be kept alive (see this section and this note from an earlier section).


Specifying a sandbox

All services must specify a sandbox. Ideally services will run inside the kService 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 with security-dev@chromium.org.

The preferred way to define the sandbox for your interface is by specifying a [ServiceSandbox=type] attribute on your interface {} 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 using content::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. ShouldEnableNetworkServiceSandbox()).

Content-Layer Services Overview

Interface Brokers

在renderer的进程中的 frame对象对应的browser进程的 RenderFrameHostImpl 连接的远程接口是BrowserInterfaceBroker 。它是显示的永久连接。

We define an explicit mojom interface with a persistent connection between a renderer's frame object and the corresponding RenderFrameHostImpl in the browser process. This interface is called BrowserInterfaceBroker and is fairly easy to work with: you add a new method on RenderFrameHostImpl:

void RenderFrameHostImpl::GetGoatTeleporter(
    mojo::PendingReceiver<magic::mojom::GoatTeleporter> receiver) {
  goat_teleporter_receiver_.Bind(std::move(receiver));
}

and register this method in PopulateFrameBinders function in browser_interface_binders.cc, which maps specific interfaces to their handlers in respective hosts:

// //content/browser/browser_interface_binders.cc
void PopulateFrameBinders(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.cc
void PopulateFrameBinders(RenderFrameHostImpl* host,
                          mojo::BinderMap* map) {
...
  map->Add<magic::mojom::GoatTeleporter>(base::BindRepeating(
      &RenderFrameHostImpl::GetGoatTeleporter, base::Unretained(host)),
      GetIOThreadTaskRunner({}));
}

Workers also have BrowserInterfaceBroker 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:

申明一个receiver:goat_teleporter_receiver_

增加个方法,让它关联传入的receiver参数。

然后将这个方法通过初始化方法注册进去(加入map):PopulateFrameBinders

上面的注册是针对RenderFrame与renderFrameHostImpl的连接BrowserInterfaceBroker 。对于其他worker,加函数和对应注册:

函数在DedicatedWorkerHost注册在 PopulateDedicatedWorkerBinders

其他还剩2种情况类似。

Interfaces can also be added at the process level using the BrowserInterfaceBroker connection between the Blink Platform object in the renderer and the corresponding RenderProcessHost 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 the BrowserInterfaceBroker implementation used must be thread-safe. To add a new process-level interface, add a new method to RenderProcessHostImpl and register it using a call to AddUIThreadInterface in RenderProcessHostImpl::RegisterMojoInterfaces. On the renderer side, use Platform::GetBrowserInterfaceBroker to retrieve the corresponding BrowserInterfaceBroker object to call GetInterface on.

render进程的Platform 对象与browser进程的RenderProcessHost 里面对应的方法,通过BrowserInterfaceBroker 接口,可以实现进程级别的连接。

这使得在render进程的线程(frame或者worker线程)可以访问接口,但比较重,因为BrowserInterfaceBroker 实现为线程安全的。

解决方法:服务端,为了加个进程级别的接口,在RenderProcessHostImpl 加个方法。通过RenderProcessHostImpl::RegisterMojoInterfaces 中调用AddUIThreadInterface 注册上。

在render进程客户端,使用Platform::GetBrowserInterfaceBroker 获取到对应的接口工厂BrowserInterfaceBroker 调用GetInterface 去取到远程接口。就可以调用远程方法

For binding an embedder-specific document-scoped interface, override ContentBrowserClient::RegisterBrowserInterfaceBindersForFrame() and add the binders to the provided map.

为了绑定个特定实现的文档范围接口(headless,chrome),需要覆盖ContentBrowserClient::RegisterBrowserInterfaceBindersForFrame(),并且追加绑定到map里面。

*** aside NOTE: if BrowserInterfaceBroker cannot find a binder for the requested interface, it will call ReportNoBinderForInterface() on the relevant context host, which results in a ReportBadMessage() 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 the EmptyBinderForFrame helper in browser_interface_binders.cc. However, it is recommended to have the renderer and browser sides consistent if possible.

参考 headless时一个超链接没有 visited变色 headless架构 - Bigben - 博客园 (cnblogs.com)

 

服务实现端:

RenderThreadImpl::Init初始化时,

建立个binder 列表
  mojo::BinderMap binders;
  InitializeWebKit(&binders);  

GetContentClient()->renderer()->RenderThreadStarted();

将列表中加入东西:
  ExposeRendererInterfacesToBrowser(weak_factory_.GetWeakPtr(), &binders);
  ExposeInterfacesToBrowser(std::move(binders));

把列表加到order相关的接口:

  GetAssociatedInterfaceRegistry()->AddInterface<mojom::Renderer>(
      base::BindRepeating(&RenderThreadImpl::OnRendererInterfaceReceiver,
                          base::Unretained(this)));

 

其中,这个来自content的方法ExposeRendererInterfacesToBrowser,最终走到

GetContentClient()->renderer()->ExposeInterfacesToBrowser(binders);

通过 ContentClinet类去拿位于renderer进程的具体实现,即 contentRendererClient。然后调用它的实现方法ExposeInterfacesToBrowser

具体headless和chrome都有不同的实现。

在headless的中:

    HeadlessContentRendererClient::HeadlessContentRendererClient()
        :visited_link_reader_(new visitedlink::VisitedLinkReader){}
   加了个 visited_link_reader_ 实例,初始化

void HeadlessContentRendererClient::ExposeInterfacesToBrowser(mojo::BinderMap* binders) {
    //将visited_link_reader_放到binder列表中
    binders->Add<visitedlink::mojom::VisitedLinkNotificationSink>(
        visited_link_reader_->GetBindCallback(),
        base::SequencedTaskRunner::GetCurrentDefault());
}

在VisitedLinkReader 的类中实现了上面的方法:

base::RepeatingCallback<
    void(mojo::PendingReceiver<mojom::VisitedLinkNotificationSink>)>
VisitedLinkReader::GetBindCallback() {
  return base::BindRepeating(&VisitedLinkReader::Bind, //这个bind实现在下面
                             weak_factory_.GetWeakPtr());
}

void VisitedLinkReader::Bind(
    mojo::PendingReceiver<mojom::VisitedLinkNotificationSink> receiver) {
  receiver_.Bind(std::move(receiver));
}

 服务端就做好了

客户端:

components/visitedlink/browser/visitedlink_event_listener.cc

mojo::Remote<mojom::VisitedLinkNotificationSink> sink_;

实例化时绑定:

class VisitedLinkUpdater {
 public:
  explicit VisitedLinkUpdater(int render_process_id)
      : 
        render_process_id_(render_process_id) {
    content::RenderProcessHost::FromID(render_process_id)
        ->BindReceiver(sink_.BindNewPipeAndPassReceiver());
  }

通过 RenderProcessHost 的 BindReceiver 是个虚方法,具体看实现:

  // Asks the renderer process to bind |receiver|. |receiver| arrives in the
  // renderer process and is carried through the following flow, stopping if any
  // step decides to bind it:
  //
  //   1. IO thread, |ChildProcessImpl::BindReceiver()| (child_thread_impl.cc)
  //   2. IO thread ,|ContentClient::BindChildProcessInterface()|
  //   3. Main thread, |ChildThreadImpl::OnBindReceiver()| (virtual)
  //   4. Possibly more steps, depending on the ChildThreadImpl subclass.
  virtual void BindReceiver(mojo::GenericPendingReceiver receiver) = 0;

这里是主线程 main thread,它的实现是:

void RenderProcessHostImpl::BindReceiver(
    mojo::GenericPendingReceiver receiver) {
  child_process_->BindReceiver(std::move(receiver));
}

 

发出调用:sink_->UpdateVisitedLinks(region->Duplicate());

 

mojom接口:支持共享内存mojo_base.mojom.ReadOnlySharedMemoryRegion

components/visitedlink/common/visitedlink.mojom
 module visitedlink.mojom;

import "mojo/public/mojom/base/shared_memory.mojom";

interface VisitedLinkNotificationSink {
  // Notification that the visited link database has been replaced. It has one
  // SharedMemoryHandle argument consisting of the table handle.
  UpdateVisitedLinks(mojo_base.mojom.ReadOnlySharedMemoryRegion table_region);

  // Notification that one or more links have been added and the link coloring
  // state for the given hashes must be re-calculated.
  AddVisitedLinks(array<uint64> link_hashes);

  // Notification that one or more history items have been deleted, which at
  // this point means that all link coloring state must be re-calculated.
  // |invalidate_cached_hashes| is used to inform renderer process to invalidate
  // cached visited links hashes. The flag is needed because the salt will
  // change after loading the visitedlink table from the database file.
  ResetVisitedLinks(bool invalidate_cached_hashes);
};

Navigation-Associated Interfaces

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 corresponding RenderFrameHostImpl 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 for RenderFrameHostImpl and register it with a call to associated_registry_->AddInterface in RenderFrameHostImpl::SetUpMojoConnection. From the renderer, use LocalFrame::GetRemoteNavigationAssociatedInterfaces to get an object to call GetInterface on (this call is similar to BrowserInterfaceBroker::GetInterface except that it takes a pending associated receiver instead of a pending receiver).

对于不同的frame发出的消息,比如导航,有顺序要求的,用Navigation-associated接口使用FIFO实现。确保消息顺序到达browser进程。顺序处理。加这个接口,对于browser进程服务端,在RenderFrameHostImpl::SetUpMojoConnectionassociated_registry_->AddInterface;对于renderer(远程接口端、客户端),从RemoteNavigationAssociatedInterfaces工厂获取 GetInterface 通过LocalFrame::GetRemoteNavigationAssociatedInterfaces。这个GetInterface 接收  pending associated receiver,而不是pendingReceiver。

 

Additional Support

If this document was not helpful in some way, please post a message to your friendly chromium-mojo@chromium.org or services-dev@chromium.org mailing list.

 


posted @ 2021-06-22 11:47  Bigben  阅读(883)  评论(0编辑  收藏  举报