This document is a subset of the Mojo documentation.

Overview

The Mojo C++ System API provides a convenient set of helper classes and functions for working with Mojo primitives. Unlike the low-level C API (upon which this is built) this library takes advantage of C++ language features and common STL and //base types to provide a slightly more idiomatic interface to the Mojo system layer, making it generally easier to use.

This document provides a brief guide to API usage with example code snippets. For a detailed API references please consult the headers in //mojo/public/cpp/system.

Note that all API symbols referenced in this document are implicitly in the top-level mojo namespace.

Scoped, Typed Handles

All types of Mojo handles in the C API are simply opaque, integral MojoHandle values. The C++ API has more strongly typed wrappers defined for different handle types: MessagePipeHandleSharedBufferHandleDataPipeConsumerHandleDataPipeProducerHandleTrapHandle, and InvitationHandle.

Each of these also has a corresponding, move-only, scoped type for safer usage: ScopedMessagePipeHandleScopedSharedBufferHandle, and so on. When a scoped handle type is destroyed, its handle is automatically closed via MojoClose. When working with raw handles you should always prefer to use one of the scoped types for ownership.

Similar to std::unique_ptr, scoped handle types expose a get() method to get at the underlying unscoped handle type as well as the ->operator to dereference the scoper and make calls directly on the underlying handle type.

Message Pipes

There are two ways to create a new message pipe using the C++ API. You may construct a MessagePipe object:

  1. mojo::MessagePipe pipe;
  2.  
  3. // NOTE: Because pipes are bi-directional there is no implicit semantic
  4. // difference between |handle0| or |handle1| here. They're just two ends of a
  5. // pipe. The choice to treat one as a "client" and one as a "server" is entirely
  6. // the API user's decision.
  7. mojo::ScopedMessagePipeHandle client = std::move(pipe.handle0);
  8. mojo::ScopedMessagePipeHandle server = std::move(pipe.handle1);

or you may call CreateMessagePipe:

  1. mojo::ScopedMessagePipeHandle client;
  2. mojo::ScopedMessagePipeHandle server;
  3. mojo::CreateMessagePipe(nullptr, &client, &server);

There are also some helper functions for constructing message objects and reading/writing them on pipes using the library's more strongly-typed C++ handles:

  1. mojo::ScopedMessageHandle message;
  2. mojo::AllocMessage(6, nullptr, 0, MOJO_ALLOC_MESSAGE_FLAG_NONE, &message);
  3.  
  4. void *buffer;
  5. mojo::GetMessageBuffer(message.get(), &buffer);
  6.  
  7. const std::string kMessage = "hello";
  8. std::copy(kMessage.begin(), kMessage.end(), static_cast<char*>(buffer));
  9.  
  10. mojo::WriteMessageNew(client.get(), std::move(message),
  11. MOJO_WRITE_MESSAGE_FLAG_NONE);
  12.  
  13. // Some time later...
  14.  
  15. mojo::ScopedMessageHandle received_message;
  16. uint32_t num_bytes;
  17. mojo::ReadMessageNew(server.get(), &received_message, &num_bytes, nullptr,
  18. nullptr, MOJO_READ_MESSAGE_FLAG_NONE);

See message_pipe.h for detailed C++ message pipe API documentation.

Data Pipes

Similar to Message Pipes, the C++ library has some simple helpers for more strongly-typed data pipe usage:

  1. mojo::DataPipe pipe;
  2. mojo::ScopedDataPipeProducerHandle producer = std::move(pipe.producer_handle);
  3. mojo::ScopedDataPipeConsumerHandle consumer = std::move(pipe.consumer_handle);
  4.  
  5. // Or alternatively:
  6. mojo::ScopedDataPipeProducerHandle producer;
  7. mojo::ScopedDataPipeConsumerHandle consumer;
  8. mojo::CreateDataPipe(null, &producer, &consumer);

C++ helpers which correspond directly to the Data Pipe C API for immediate and two-phase I/O are provided as well. For example:

  1. uint32_t num_bytes = 7;
  2. producer.WriteData("hihihi", &num_bytes, MOJO_WRITE_DATA_FLAG_NONE);
  3.  
  4. // Some time later...
  5.  
  6. char buffer[64];
  7. uint32_t num_bytes = 64;
  8. consumer.ReadData(buffer, &num_bytes, MOJO_READ_DATA_FLAG_NONE);

See data_pipe.h for detailed C++ data pipe API documentation.

Shared Buffers

A new shared buffer can be allocated like so:

  1. mojo::ScopedSharedBufferHandle buffer =
  2. mojo::SharedBufferHandle::Create(4096);

This new handle can be cloned arbitrarily many times by using the underlying handle's Clone method:

  1. mojo::ScopedSharedBufferHandle another_handle = buffer->Clone();
  2. mojo::ScopedSharedBufferHandle read_only_handle =
  3. buffer->Clone(mojo::SharedBufferHandle::AccessMode::READ_ONLY);

And finally the library also provides a scoper for mapping the shared buffer's memory:

  1. mojo::ScopedSharedBufferMapping mapping = buffer->Map(64);
  2. static_cast<int*>(mapping.get()) = 42;
  3.  
  4. mojo::ScopedSharedBufferMapping another_mapping = buffer->MapAtOffset(64, 4);
  5. static_cast<int*>(mapping.get()) = 43;

When mapping and another_mapping are destroyed, they automatically unmap their respective memory regions.

See buffer.h for detailed C++ shared buffer API documentation.

Native Platform Handles (File Descriptors, Windows Handles, etc.)

The C++ library provides several helpers for wrapping system handle types. These are specifically useful when working with a few //base types, namely base::PlatformFilebase::SharedMemoryHandle (deprecated), and various strongly-typed shared memory region types like base::ReadOnlySharedMemoryRegion. See platform_handle.h for detailed C++ platform handle API documentation.

Signals & Traps

For an introduction to the concepts of handle signals and traps, check out the C API's documentation on Signals & Traps.

Querying Signals

Any C++ handle type's last known signaling state can be queried by calling the QuerySignalsState method on the handle:

  1. mojo::MessagePipe message_pipe;
  2. mojo::DataPipe data_pipe;
  3. mojo::HandleSignalsState a = message_pipe.handle0->QuerySignalsState();
  4. mojo::HandleSignalsState b = data_pipe.consumer->QuerySignalsState();

The HandleSignalsState is a thin wrapper interface around the C API's MojoHandleSignalsState structure with convenient accessors for testing the signal bitmasks. Whereas when using the C API you might write:

  1. struct MojoHandleSignalsState state;
  2. MojoQueryHandleSignalsState(handle0, &state);
  3. if (state.satisfied_signals & MOJO_HANDLE_SIGNAL_READABLE) {
  4. // ...
  5. }

the C++ API equivalent would be:

  1. if (message_pipe.handle0->QuerySignalsState().readable()) {
  2. // ...
  3. }

Watching Handles

The mojo::SimpleWatcher class serves as a convenient helper for using the low-level traps API to watch a handle for signaling state changes. A SimpleWatcher is bound to a single sequence and always dispatches its notifications on a base::SequencedTaskRunner.

SimpleWatcher has two possible modes of operation, selected at construction time by the mojo::SimpleWatcher::ArmingPolicy enum:

  • MANUAL mode requires the user to manually call Arm and/or ArmOrNotify before any notifications will fire regarding the state of the watched handle. Every time the notification callback is run, the SimpleWatcher must be rearmed again before the next one can fire. See Arming a Trap and the documentation in SimpleWatcher's header.

  • AUTOMATIC mode ensures that the SimpleWatcher always either is armed or has a pending notification task queued for execution.

AUTOMATIC mode is more convenient but can result in redundant notification tasks, especially if the provided callback does not make a strong effort to return the watched handle to an uninteresting signaling state (by e.g., reading all its available messages when notified of readability.)

Example usage:

  1. class PipeReader {
  2. public:
  3. PipeReader(mojo::ScopedMessagePipeHandle pipe)
  4. : pipe_(std::move(pipe)),
  5. watcher_(mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC) {
  6. // NOTE: base::Unretained is safe because the callback can never be run
  7. // after SimpleWatcher destruction.
  8. watcher_.Watch(pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE,
  9. base::Bind(&PipeReader::OnReadable, base::Unretained(this)));
  10. }
  11.  
  12. ~PipeReader() {}
  13.  
  14. private:
  15. void OnReadable(MojoResult result) {
  16. while (result == MOJO_RESULT_OK) {
  17. mojo::ScopedMessageHandle message;
  18. uint32_t num_bytes;
  19. result = mojo::ReadMessageNew(pipe_.get(), &message, &num_bytes, nullptr,
  20. nullptr, MOJO_READ_MESSAGE_FLAG_NONE);
  21. DCHECK_EQ(result, MOJO_RESULT_OK);
  22. messages_.emplace_back(std::move(message));
  23. }
  24. }
  25.  
  26. mojo::ScopedMessagePipeHandle pipe_;
  27. mojo::SimpleWatcher watcher_;
  28. std::vector<mojo::ScopedMessageHandle> messages_;
  29. };
  30.  
  31. mojo::MessagePipe pipe;
  32. PipeReader reader(std::move(pipe.handle0));
  33.  
  34. // Written messages will asynchronously end up in |reader.messages_|.
  35. WriteABunchOfStuff(pipe.handle1.get());

Synchronous Waiting

The C++ System API defines some utilities to block a calling sequence while waiting for one or more handles to change signaling state in an interesting way. These threads combine usage of the low-level traps API with common synchronization primitives (namely base::WaitableEvent.)

While these API features should be used sparingly, they are sometimes necessary.

See the documentation in wait.h and wait_set.h for a more detailed API reference.

Waiting On a Single Handle

The mojo::Wait function simply blocks the calling sequence until a given signal mask is either partially satisfied or fully unsatisfiable on a given handle.

  1. mojo::MessagePipe pipe;
  2. mojo::WriteMessageRaw(pipe.handle0.get(), "hey", 3, nullptr, nullptr,
  3. MOJO_WRITE_MESSAGE_FLAG_NONE);
  4. MojoResult result = mojo::Wait(pipe.handle1.get(), MOJO_HANDLE_SIGNAL_READABLE);
  5. DCHECK_EQ(result, MOJO_RESULT_OK);
  6.  
  7. // Guaranteed to succeed because we know |handle1| is readable now.
  8. mojo::ScopedMessageHandle message;
  9. uint32_t num_bytes;
  10. mojo::ReadMessageNew(pipe.handle1.get(), &num_bytes, nullptr, nullptr,
  11. MOJO_READ_MESSAGE_FLAG_NONE);

mojo::Wait is most typically useful in limited testing scenarios.

Waiting On Multiple Handles

mojo::WaitMany provides a simple API to wait on multiple handles simultaneously, returning when any handle's given signal mask is either partially satisfied or fully unsatisfiable.

  1. mojo::MessagePipe a, b;
  2. GoDoSomethingWithPipes(std:move(a.handle1), std::move(b.handle1));
  3.  
  4. mojo::MessagePipeHandle handles[2] = {a.handle0.get(), b.handle0.get()};
  5. MojoHandleSignals signals[2] = {MOJO_HANDLE_SIGNAL_READABLE,
  6. MOJO_HANDLE_SIGNAL_READABLE};
  7. size_t ready_index;
  8. MojoResult result = mojo::WaitMany(handles, signals, 2, &ready_index);
  9. if (ready_index == 0) {
  10. // a.handle0 was ready.
  11. } else {
  12. // b.handle0 was ready.
  13. }

Similar to mojo::Waitmojo::WaitMany is primarily useful in testing. When waiting on multiple handles in production code, you should almost always instead use a more efficient and more flexible mojo::WaitSet as described in the next section.

Waiting On Handles and Events Simultaneously

Typically when waiting on one or more handles to signal, the set of handles and conditions being waited upon do not change much between consecutive blocking waits. It's also often useful to be able to interrupt the blocking operation as efficiently as possible.

mojo::WaitSet is designed with these conditions in mind. A WaitSet maintains a persistent set of (not-owned) Mojo handles and base::WaitableEvents, which may be explicitly added to or removed from the set at any time.

The WaitSet may be waited upon repeatedly, each time blocking the calling sequence until either one of the handles attains an interesting signaling state or one of the events is signaled. For example let's suppose we want to wait up to 5 seconds for either one of two handles to become readable:

  1. base::WaitableEvent timeout_event(
  2. base::WaitableEvent::ResetPolicy::MANUAL,
  3. base::WaitableEvent::InitialState::NOT_SIGNALED);
  4. mojo::MessagePipe a, b;
  5.  
  6. GoDoStuffWithPipes(std::move(a.handle1), std::move(b.handle1));
  7.  
  8. mojo::WaitSet wait_set;
  9. wait_set.AddHandle(a.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE);
  10. wait_set.AddHandle(b.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE);
  11. wait_set.AddEvent(&timeout_event);
  12.  
  13. // Ensure the Wait() lasts no more than 5 seconds.
  14. bg_thread->task_runner()->PostDelayedTask(
  15. FROM_HERE,
  16. base::Bind([](base::WaitableEvent* e) { e->Signal(); }, &timeout_event);
  17. base::TimeDelta::FromSeconds(5));
  18.  
  19. base::WaitableEvent* ready_event = nullptr;
  20. size_t num_ready_handles = 1;
  21. mojo::Handle ready_handle;
  22. MojoResult ready_result;
  23. wait_set.Wait(&ready_event, &num_ready_handles, &ready_handle, &ready_result);
  24.  
  25. // The apex of thread-safety.
  26. bg_thread->Stop();
  27.  
  28. if (ready_event) {
  29. // The event signaled...
  30. }
  31.  
  32. if (num_ready_handles > 0) {
  33. // At least one of the handles signaled...
  34. // NOTE: This and the above condition are not mutually exclusive. If handle
  35. // signaling races with timeout, both things might be true.
  36. }

Invitations

Invitations are the means by which two processes can have Mojo IPC bootstrapped between them. An invitation must be transmitted over some platform-specific IPC primitive (e.g. a Windows named pipe or UNIX domain socket), and the public platform support library provides some lightweight, cross-platform abstractions for those primitives.

For any two processes looking to be connected, one must send an OutgoingInvitation and the other must accept an IncomingInvitation. The sender can attach named message pipe handles to the OutgoingInvitation, and the receiver can extract them from its IncomingInvitation.

Basic usage might look something like this in the case where one process is responsible for launching the other.

  1. #include "base/command_line.h"
  2. #include "base/process/launch.h"
  3. #include "mojo/public/cpp/platform/platform_channel.h"
  4. #include "mojo/public/cpp/system/invitation.h"
  5. #include "mojo/public/cpp/system/message_pipe.h"
  6.  
  7. mojo::ScopedMessagePipeHandle LaunchAndConnectSomething() {
  8. // Under the hood, this is essentially always an OS pipe (domain socket pair,
  9. // Windows named pipe, Fuchsia channel, etc).
  10. mojo::PlatformChannel channel;
  11.  
  12. mojo::OutgoingInvitation invitation;
  13.  
  14. // Attach a message pipe to be extracted by the receiver. The other end of the
  15. // pipe is returned for us to use locally.
  16. mojo::ScopedMessagePipeHandle pipe =
  17. invitation->AttachMessagePipe("arbitrary pipe name");
  18.  
  19. base::LaunchOptions options;
  20. base::CommandLine command_line("some_executable")
  21. channel.PrepareToPassRemoteEndpoint(&options, &command_line);
  22. base::Process child_process = base::LaunchProcess(command_line, options);
  23. channel.RemoteProcessLaunchAttempted();
  24.  
  25. OutgoingInvitation::Send(std::move(invitation), child_process.Handle(),
  26. channel.TakeLocalEndpoint());
  27. return pipe;
  28. }

The launched process can in turn accept an IncomingInvitation:

  1. #include "base/command_line.h"
  2. #include "base/threading/thread.h"
  3. #include "mojo/core/embedder/embedder.h"
  4. #include "mojo/core/embedder/scoped_ipc_support.h"
  5. #include "mojo/public/cpp/platform/platform_channel.h"
  6. #include "mojo/public/cpp/system/invitation.h"
  7. #include "mojo/public/cpp/system/message_pipe.h"
  8.  
  9. int main(int argc, char** argv) {
  10. // Basic Mojo initialization for a new process.
  11. mojo::core::Init();
  12. base::Thread ipc_thread("ipc!");
  13. ipc_thread.StartWithOptions(
  14. base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
  15. mojo::core::ScopedIPCSupport ipc_support(
  16. ipc_thread.task_runner(),
  17. mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN);
  18.  
  19. // Accept an invitation.
  20. mojo::IncomingInvitation invitation = mojo::IncomingInvitation::Accept(
  21. mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
  22. *base::CommandLine::ForCurrentProcess()));
  23. mojo::ScopedMessagePipeHandle pipe =
  24. invitation->ExtractMessagePipe("arbitrary pipe name");
  25.  
  26. // etc...
  27. return GoListenForMessagesAndRunForever(std::move(pipe));
  28. }

Now we have IPC initialized between the two processes.

Also keep in mind that bindings interfaces are just message pipes with some semantic and syntactic sugar wrapping them, so you can use these primordial message pipe handles as mojom interfaces. For example:

  1. // Process A
  2. mojo::OutgoingInvitation invitation;
  3. auto pipe = invitation->AttachMessagePipe("x");
  4. mojo::Binding<foo::mojom::Bar> binding(
  5. &bar_impl,
  6. foo::mojom::BarRequest(std::move(pipe)));
  7.  
  8. // Process B
  9. auto invitation = mojo::IncomingInvitation::Accept(...);
  10. auto pipe = invitation->ExtractMessagePipe("x");
  11. foo::mojom::BarPtr bar(foo::mojom::BarPtrInfo(std::move(pipe), 0));
  12.  
  13. // Will asynchronously invoke bar_impl.DoSomething() in process A.
  14. bar->DoSomething();

And just to be sure, the usage here could be reversed: the invitation sender could just as well treat its pipe endpoint as a BarPtr while the receiver treats theirs as a BarRequest to be bound.

Process Networks

Accepting an invitation admits the accepting process into the sender‘s connected network of processes. Once this is done, it’s possible for the newly admitted process to establish communication with any other process in that network via normal message pipe passing.

This does not mean that the invited process can proactively locate and connect to other processes without assistance; rather it means that Mojo handles created by the process can safely be transferred to any other process in the network over established message pipes, and similarly that Mojo handles created by any other process in the network can be safely passed to the newly admitted process.

Invitation Restrictions

A process may only belong to a single network at a time.

Additionally, once a process has joined a network, it cannot join another for the remainder of its lifetime even if it has lost the connection to its original network. This restriction will soon be lifted, but for now developers must be mindful of it when authoring any long-running daemon process that will accept an incoming invitation.

Isolated Invitations

It is possible to have two independent networks of Mojo-connected processes; for example, a long-running system daemon which uses Mojo to talk to child processes of its own, as well as the Chrome browser process running with no common ancestor, talking to its own child processes.

In this scenario it may be desirable to have a process in one network talk to a process in the other network. Normal invitations cannot be used here since both processes already belong to a network. In this case, an isolated invitation can be used. These work just like regular invitations, except the sender must call OutgoingInvitation::SendIsolated and the receiver must call IncomingInvitation::AcceptIsolated.

Once a connection is established via isolated invitation, Mojo IPC can be used normally, with the exception that transitive process connections are not supported; that is, if process A sends a message pipe handle to process B via an isolated connection, process B cannot reliably send that pipe handle onward to another process in its own network. Isolated invitations therefore may only be used to facilitate direct 1:1 communication between two processes.

Mojo C++ System API的更多相关文章

  1. Mojo C++ Bindings API

    This document is a subset of the Mojo documentation. Contents Overview Getting Started Interfaces Ba ...

  2. Mojo Core Embedder API

    This document is a subset of the Mojo documentation. Contents Overview Basic Initialization IPC Init ...

  3. Mojo C++ Platform API

    Mojo C++ Platform API This document is a subset of the Mojo documentation. Contents Overview Platfor ...

  4. [Chromium文档转载,第002章]Mojo C++ Bindings API

    Mojo C++ Bindings API This document is a subset of the Mojo documentation. Contents Overview Getting ...

  5. HTML5之本地文件系统API - File System API

    HTML5之本地文件系统API - File System API 新的HTML5标准给我们带来了大量的新特性和惊喜,例如,画图的画布Canvas,多媒体的audio和video等等.除了上面我们提到 ...

  6. java hadoop file system API

    org.apache.hadoop.fs Class FileSystem java.lang.Object org.apache.hadoop.fs.FileSystem All Implement ...

  7. Linux System Account SSH Weak Password Detection Automatic By System API

    catalog . Linux弱口令攻击向量 . Linux登录验证步骤 . PAM . 弱口令风险基线检查 1. Linux弱口令攻击向量 0x1: SSH密码暴力破解 hydra -l root ...

  8. 极简 Node.js 入门 - 3.1 File System API 风格

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  9. Mojo Associated Interfaces

    Mojo Associated Interfaces yzshen@chromium.org 02/22/2017 Background Before associated interfaces ar ...

随机推荐

  1. jar文件配置冲突问题transformResourcesWithMergeJavaResForDebug

    先看本人AS报错异常 Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. > c ...

  2. deploy sql clr

    1, create strong signed key file 2, create asymmetric key

  3. 织梦Fatal error: Call to a member function GetInnerText()

    问题:织梦修改或者添加了自定义表单后在后台修改文章的时候出现如下错误:Fatal error: Call to a member function GetInnerText() on a non-ob ...

  4. struts2配置 匹配原则 配置各项默认

    struts开发流程 1,引入jar包 2,配置web.xml 3,开发action类 4,配置struts.xml   版本: 2.3 引入jar文件 commons-fileupload-1.2. ...

  5. css控制单行或者多行文本超出显示省略号

    1.单行文本 使用text-overflow:ellipsis属性 text-overflow: clip|ellipsis|string; clip:修剪文本. ellipsis:显示省略符号来代表 ...

  6. .net基础总复习(1)

    第一天 1.new关键字 (1) 创建对象 (2) 隐藏从父类那里继承过来的成员 2.访问修饰符 public: 公开的,公共的. private:私有的,只能在当前类的内部访问,类中的成员, 如果不 ...

  7. js异步队列之理解

    起因 最近看到一篇关于js异步执行顺序的解答,觉得有所收获,遂记录下来. marcotask和microtask js中异步队列可以分为两类,marcotask队列和microtask队列, marc ...

  8. tomcat 映射虚拟路径

    编辑server.xml   在  <Host></Host>中添加 <Context path="/renbao/img/" docBase=&qu ...

  9. xmllint命令

    xmllint是一个很方便的处理及验证xml的工具,linux下只要安装libxml2就可以使用这个命令,下面整理一些常用功能 1. --format 此参数用于格式化xml,使其具有良好的可读性. ...

  10. 命令行 对MYSQL导入sql

    1 use database name;  //选择使用的数据库 2 mysql>source d:\datafilename.sql  导入sql