Adds lots of Mojo documentation

Adds documentation for Mojo IPC conversion and Mojo public system
libraries for C and C++. Also updates Service Manager and client
library documentation.

BUG=
[email protected],[email protected]

Review-Url: https://codereview.chromium.org/2783223004
Cr-Commit-Position: refs/heads/master@{#461306}
diff --git a/mojo/README.md b/mojo/README.md
index 237d1d4..e1e7583f 100644
--- a/mojo/README.md
+++ b/mojo/README.md
@@ -1,7 +1,142 @@
-Mojo
-====
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo
+This document is a subset of the [Mojo documentation](/mojo).
 
-[Mojo](https://www.chromium.org/developers/design-documents/mojo) is an IPC &
-binding mechanism for Chromium.
+[TOC]
 
-TODO(rockot): Describe the important subdirectories.
\ No newline at end of file
+## Getting Started With Mojo
+
+To get started using Mojo in applications which already support it (such as
+Chrome), the fastest path forward will be to look at the bindings documentation
+for your language of choice ([**C++**](#C_Bindings),
+[**JavaScript**](#JavaScript-Bindings), or [**Java**](#Java-Bindings)) as well
+as the documentation for the
+[**Mojom IDL and bindings generator**](/mojo/public/tools/bindings).
+
+If you're looking for information on creating and/or connecting to services, see
+the top-level [Services documentation](/services).
+
+For specific details regarding the conversion of old things to new things, check
+out [Converting Legacy Chrome IPC To Mojo](/ipc).
+
+## System Overview
+
+Mojo is a layered collection of runtime libraries providing a platform-agnostic
+abstraction of common IPC primitives, a message IDL format, and a bindings
+library with code generation for multiple target languages to facilitate
+convenient message passing across arbitrary inter- and intra-process boundaries.
+
+The documentation here is segmented according to the different isolated layers
+and libraries comprising the system. The basic hierarchy of features is as
+follows:
+
+![Mojo Library Layering: EDK on bottom, different language bindings on top, public system support APIs in the middle](https://docs.google.com/drawings/d/1aNbLfF-fejgzxCxH_b8xAaCVvftW8BGTH_EHD7nvU1w/pub?w=570&h=327)
+
+## Embedder Development Kit (EDK)
+Every process to be interconnected via Mojo IPC is called a **Mojo embedder**
+and needs to embed the
+[**Embedder Development Kit (EDK)**](/mojo/edk/embedder) library. The EDK
+exposes the means for an embedder to physically connect one process to another
+using any supported native IPC primitive (*e.g.,* a UNIX domain socket or
+Windows named pipe) on the host platform.
+
+Details regarding where and how an application process actually embeds and
+configures the EDK are generaly hidden from the rest of the application code,
+and applications instead use the public System and Bindings APIs to get things
+done within processes that embed Mojo.
+
+## C System API
+Once the EDK is initialized within a process, the public
+[**C System API**](/mojo/public/c/system) is usable on any thread for the
+remainder of the process's lifetime. This is a lightweight API with a relatively
+small (and eventually stable) ABI. Typically this API is not used directly, but
+it is the foundation upon which all remaining upper layers are built. It exposes
+the fundamental capabilities to create and interact with various types of Mojo
+handles including **message pipes**, **data pipes**, and **shared buffers**.
+
+## High-Level System APIs
+
+There is a relatively small, higher-level system API for each supported
+language, built upon the low-level C API. Like the C API, direct usage of these
+system APIs is rare compared to the bindings APIs, but it is sometimes desirable
+or necessary.
+
+### C++
+The [**C++ System API**](/mojo/public/cpp/system) provides a layer of
+C++ helper classes and functions to make safe System API usage easier:
+strongly-typed handle scopers, synchronous waiting operations, system handle
+wrapping and unwrapping helpers, common handle operations, and utilities for
+more easily watching handle state changes.
+
+### JavaScript
+The [**JavaScript APIs**](/mojo/public/js) are WIP. :)
+
+### Java
+The [**Java System API**](/mojo/public/java/system) provides helper classes for
+working with Mojo primitives, covering all basic functionality of the low-level
+C API.
+
+## High-Level Bindings APIs
+Typically developers do not use raw message pipe I/O directly, but instead
+define some set of interfaces which are used to generate code that message pipe
+usage feel like a more idiomatic method-calling interface in the target
+language of choice. This is the bindings layer.
+
+### Mojom IDL and Bindings Generator
+Interfaces are defined using the [**Mojom IDL**](/mojo/public/tools/bindings),
+which can be fed to the [**bindings generator**](/mojo/public/tools/bindings) to
+generate code in various supported languages. Generated code manages
+serialization and deserialization of messages between interface clients and
+implementations, simplifying the code -- and ultimately hiding the message pipe
+-- on either side of an interface connection.
+
+### C++ Bindings
+By far the most commonly used API defined by Mojo, the
+[**C++ Bindings API**](/mojo/public/cpp/bindings) exposes a robust set of
+features for interacting with message pipes via generated C++ bindings code,
+including support for sets of related bindings endpoints, associated interfaces,
+nested sync IPC, versioning, bad-message reporting, arbitrary message filter
+injection, and convenient test facilities.
+
+### JavaScript Bindings
+The [**JavaScript APIs**](/mojo/public/js) are WIP. :)
+
+### Java Bindings
+The [**Java Bindings API**](/mojo/public/java/bindings) provides helper classes
+for working with Java code emitted by the bindings generator.
+
+## FAQ
+
+### Why not protobuf? Why a new thing?
+There are number of potentially decent answers to this question, but the
+deal-breaker is that a useful IPC mechanism must support transfer of native
+object handles (*e.g.* file descriptors) across process boundaries. Other
+non-new IPC things that do support this capability (*e.g.* D-Bus) have their own
+substantial deficiencies.
+
+### Are message pipes expensive?
+No. As an implementation detail, creating a message pipe is essentially
+generating two random numbers and stuffing them into a hash table, along with a
+few tiny heap allocations.
+
+### So really, can I create like, thousands of them?
+Yes! Nobody will mind. Create millions if you like. (OK but maybe don't.)
+
+### Can I use in-process message pipes?
+Yes, and message pipe usage is identical regardless of whether the pipe actually
+crosses a process boundary -- in fact this detail is intentionally obscured.
+
+Message pipes which don't cross a process boundary are efficient: sent messages
+are never copied, and a write on one end will synchronously modify the message
+queue on the other end. When working with generated C++ bindings, for example,
+the net result is that an `InterfacePtr` on one thread sending a message to a
+`Binding` on another thread (or even the same thread) is effectively a
+`PostTask` to the `Binding`'s `TaskRunner` with the added -- but often small --
+costs of serialization, deserialization, validation, and some internal routing
+logic.
+
+### What about ____?
+
+Please post questions to
+[`[email protected]`](https://groups.google.com/a/chromium.org/forum/#!forum/chromium-mojo)!
+The list is quite responsive.
+
diff --git a/mojo/edk/embedder/README.md b/mojo/edk/embedder/README.md
index 6def874e1..fc53bece 100644
--- a/mojo/edk/embedder/README.md
+++ b/mojo/edk/embedder/README.md
@@ -1,4 +1,9 @@
-# Mojo Embedder Development Kit (EDK)
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo Embedder Development Kit (EDK)
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## Overview
 
 The Mojo EDK is a (binary-unstable) API which enables a process to use Mojo both
 internally and for IPC to other Mojo-embedding processes.
@@ -8,6 +13,12 @@
 this fact, you should never reference any of the headers in `mojo/edk/system`
 directly, as everything there is considered to be an internal detail of the EDK.
 
+**NOTE:** Unless you are introducing a new binary entry point into the system
+(*e.g.,* a new executable with a new `main()` definition), you probably don't
+need to know anything about the EDK API. Most processes defined in the Chrome
+repo today already fully initialize the EDK so that Mojo's other public APIs
+"just work" out of the box.
+
 ## Basic Initialization
 
 In order to use Mojo in a given process, it's necessary to call
@@ -320,8 +331,16 @@
 Once you've bootstrapped your process connection with a real mojom interface,
 you can avoid any further mucking around with EDK APIs or raw message pipe
 handles, as everything beyond this point - including the passing of other
-interface pipes - can be handled eloquently using public bindings APIs.
+interface pipes - can be handled eloquently using
+[public bindings APIs](/mojo#High-Level-Bindings-APIs).
 
-See [additional Mojo documentation](
-    https://www.chromium.org/developers/design-documents/mojo) for more
-information.
+## Setting System Properties
+
+The public Mojo C System API exposes a
+[**`MojoGetProperty`**](/mojo/public/c/system#MojoGetProperty) function for
+querying global, embedder-defined property values. These can be set by calling:
+
+```
+mojo::edk::SetProperty(MojoPropertyType type, const void* value)
+```
+
diff --git a/mojo/edk/system/dispatcher.h b/mojo/edk/system/dispatcher.h
index 175c112..db1f1f1 100644
--- a/mojo/edk/system/dispatcher.h
+++ b/mojo/edk/system/dispatcher.h
@@ -54,7 +54,6 @@
     DATA_PIPE_PRODUCER,
     DATA_PIPE_CONSUMER,
     SHARED_BUFFER,
-    WAIT_SET,
     WATCHER,
 
     // "Private" types (not exposed via the public interface):
diff --git a/mojo/public/README.md b/mojo/public/README.md
deleted file mode 100644
index dd91742d..0000000
--- a/mojo/public/README.md
+++ /dev/null
@@ -1,43 +0,0 @@
-Mojo Public API
-===============
-
-The Mojo Public API is a binary stable API to the Mojo system.
-
-It consists of support for a number of programming languages (with a directory
-for each support language), some "build" tools and build-time requirements, and
-interface definitions for Mojo services (specified using an IDL).
-
-Note that there are various subdirectories named tests/. These contain tests of
-the code in the enclosing directory, and are not meant for use by Mojo
-applications.
-
-C/CPP/JS
---------
-
-The c/, cpp/, js/ subdirectories define the API for C, C++, and JavaScript,
-respectively.
-
-The basic principle for these directories is that they consist of the source
-files that one needs at build/deployment/run time (as appropriate for the
-language), organized in a natural way for the particular language.
-
-Interfaces
-----------
-
-The interfaces/ subdirectory contains Mojo IDL (a.k.a. .mojom) descriptions of
-standard Mojo services.
-
-Platform
---------
-
-The platform/ subdirectory contains any build-time requirements (e.g., static
-libraries) that may be needed to produce a Service library for certain
-platforms, such as a native shared library or as a NaCl binary.
-
-Tools
------
-
-The tools/ subdirectory contains tools that are useful/necessary at
-build/deployment time. These tools may be needed (as a practical necessity) to
-use the API in any given language, e.g., to generate bindings from Mojo IDL
-files.
diff --git a/mojo/public/c/README.md b/mojo/public/c/README.md
deleted file mode 100644
index 223c205e..0000000
--- a/mojo/public/c/README.md
+++ /dev/null
@@ -1,22 +0,0 @@
-Mojo Public C API
-=================
-
-This directory contains C language bindings for the Mojo Public API.
-
-System
-------
-
-The system/ subdirectory provides definitions of the basic low-level API used by
-all Services (whether directly or indirectly). These consist primarily
-of the IPC primitives used to communicate with Mojo services.
-
-Though the message protocol is stable, the implementation of the transport is
-not, and access to the IPC mechanisms must be via the primitives defined in this
-directory.
-
-Test Support
-------------
-
-This directory contains a C API for running tests. This API is only available
-under special, specific test conditions. It is not meant for general use by Mojo
-applications.
diff --git a/mojo/public/c/system/README.md b/mojo/public/c/system/README.md
new file mode 100644
index 0000000..2abe80ff
--- /dev/null
+++ b/mojo/public/c/system/README.md
@@ -0,0 +1,869 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo C System API
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## Overview
+The Mojo C System API is a lightweight API (with an eventually-stable ABI) upon
+which all higher layers of the Mojo system are built.
+
+This API exposes the fundamental capabilities to: create, read from, and write
+to **message pipes**; create, read from, and write to **data pipes**; create
+**shared buffers** and generate sharable handles to them; wrap platform-specific
+handle objects (such as **file descriptors**, **Windows handles**, and
+**Mach ports**) for seamless transit over message pipes; and efficiently watch
+handles for various types of state transitions.
+
+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/c/system](https://cs.chromium.org/chromium/src/mojo/public/c/system/).
+
+### A Note About Multithreading
+
+The Mojo C System API is entirely thread-agnostic. This means that all functions
+may be called from any thread in a process, and there are no restrictions on how
+many threads can use the same object at the same time.
+
+Of course this does not mean you can completely ignore potential concurrency
+issues -- such as a handle being closed on one thread while another thread is
+trying to perform an operation on the same handle -- but there is nothing
+fundamentally incorrect about using any given API or handle from multiple
+threads.
+
+### A Note About Synchronization
+
+Every Mojo API call is non-blocking and synchronously yields some kind of status
+result code, but the call's side effects -- such as affecting the state of
+one or more handles in the system -- may or may not occur asynchronously.
+
+Mojo objects can be observed for interesting state changes in a way that is
+thread-agnostic and in some ways similar to POSIX signal handlers: *i.e.*
+user-provided notification handlers may be invoked at any time on arbitrary
+threads in the process. It is entirely up to the API user to take appropriate
+measures to synchronize operations against other application state.
+
+The higher level [system](/mojo#High-Level-System-APIs) and
+[bindings](/mojo#High-Level-Bindings-APIs) APIs provide helpers to simplify Mojo
+usage in this regard, at the expense of some flexibility.
+
+## Result Codes
+
+Most API functions return a value of type `MojoResult`. This is an integral
+result code used to convey some meaningful level of detail about the result of a
+requested operation.
+
+See [//mojo/public/c/system/types.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/types.h)
+for different possible values. See documentation for individual API calls for
+more specific contextual meaning of various result codes.
+
+## Handles
+
+Every Mojo IPC primitive is identified by a generic, opaque integer handle of
+type `MojoHandle`. Handles can be acquired by creating new objects using various
+API calls, or by reading messages which contain attached handles.
+
+A `MojoHandle` can represent a message pipe endpoint, a data pipe consumer,
+a data pipe producer, a shared buffer reference, a wrapped native platform
+handle such as a POSIX file descriptor or a Windows system handle, or a watcher
+object (see [Signals & Watchers](#Signals-Watchers) below.)
+
+All types of handles except for watchers (which are an inherently local concept)
+can be attached to messages and sent over message pipes.
+
+Any `MojoHandle` may be closed by calling `MojoClose`:
+
+``` c
+MojoHandle x = DoSomethingToGetAValidHandle();
+MojoResult result = MojoClose(x);
+```
+
+If the handle passed to `MojoClose` was a valid handle, it will be closed and
+`MojoClose` returns `MOJO_RESULT_OK`. Otherwise it returns
+`MOJO_RESULT_INVALID_ARGUMENT`.
+
+Similar to native system handles on various popular platforms, `MojoHandle`
+values may be reused over time. Thus it is important to avoid logical errors
+which lead to misplaced handle ownership, double-closes, *etc.*
+
+## Message Pipes
+
+A message pipe is a bidirectional messaging channel which can carry arbitrary
+unstructured binary messages with zero or more `MojoHandle` attachments to be
+transferred from one end of a pipe to the other. Message pipes work seamlessly
+across process boundaries or within a single process.
+
+The [Embedder Development Kit (EDK)](/mojo/edk/embedder) provides the means to
+bootstrap one or more primordial cross-process message pipes, and it's up to
+Mojo embedders to expose this capability in some useful way. Once such a pipe is
+established, additional handles -- including other message pipe handles -- may
+be sent to a remote process using that pipe (or in turn, over other pipes sent
+over that pipe, or pipes sent over *that* pipe, and so on...)
+
+The public C System API exposes the ability to read and write messages on pipes
+and to create new message pipes.
+
+See [//mojo/public/c/system/message_pipe.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/message_pipe.h)
+for detailed message pipe API documentation.
+
+### Creating Message Pipes
+
+`MojoCreateMessagePipe` can be used to create a new message pipe:
+
+``` c
+MojoHandle a, b;
+MojoResult result = MojoCreateMessagePipe(NULL, &a, &b);
+```
+
+After this snippet, `result` should be `MOJO_RESULT_OK` (it's really hard for
+this to fail!), and `a` and `b` will contain valid Mojo handles, one for each
+end of the new message pipe.
+
+Any messages written to `a` are eventually readable from `b`, and any messages
+written to `b` are eventually readable from `a`. If `a` is closed at any point,
+`b` will eventually become aware of this fact; likewise if `b` is closed, `a`
+will become aware of that.
+
+The state of these conditions can be queried and watched asynchronously as
+described in the [Signals & Watchers](#Signals-Watchers) section below.
+
+### Allocating Messages
+
+In order to avoid redundant internal buffer copies, Mojo would like to allocate
+your message storage buffers for you. This is easy:
+
+``` c
+MojoMessageHandle message;
+MojoResult result = MojoAllocMessage(6, NULL, 0, MOJO_ALLOC_MESSAGE_FLAG_NONE,
+                                     &message);
+```
+
+Note that we have a special `MojoMessageHandle` type for message objects.
+
+The code above allocates a buffer for a message payload of 6 bytes with no
+handles attached.
+
+If we change our mind and decide not to send this message, we can delete it:
+
+``` c
+MojoResult result = MojoFreeMessage(message);
+```
+
+If we instead decide to send our newly allocated message, we first need to fill
+in the payload data with something interesting. How about a pleasant greeting:
+
+``` c
+void* buffer = NULL;
+MojoResult result = MojoGetMessageBuffer(message, &buffer);
+memcpy(buffer, "hello", 6);
+```
+
+Now we can write the message to a pipe. Note that attempting to write a message
+transfers ownership of the message object (and any attached handles) into the
+target pipe and there is therefore no need to subsequently call
+`MojoFreeMessage` on that message.
+
+### Writing Messages
+
+``` c
+result = MojoWriteMessageNew(a, message, MOJO_WRITE_MESSAGE_FLAG_NONE);
+```
+
+`MojoWriteMessage` is a *non-blocking* call: it always returns
+immediately. If its return code is `MOJO_RESULT_OK` the message will eventually
+find its way to the other end of the pipe -- assuming that end isn't closed
+first, of course. If the return code is anything else, the message is deleted
+and not transferred.
+
+In this case since we know `b` is still open, we also know the message will
+eventually arrive at `b`. `b` can be queried or watched to become aware of when
+the message arrives, but we'll ignore that complexity for now. See
+[Signals & Watchers](#Signals-Watchers) below for more information.
+
+*** aside
+**NOTE**: Although this is an implementation detail and not strictly guaranteed by the
+System API, it is true in the current implementation that the message will
+arrive at `b` before the above `MojoWriteMessage` call even returns, because `b`
+is in the same process as `a` and has never been transferred over another pipe.
+***
+
+### Reading Messages
+
+We can read a new message object from a pipe:
+
+``` c
+MojoMessageHandle message;
+uint32_t num_bytes;
+MojoResult result = MojoReadMessageNew(b, &message, &num_bytes, NULL, NULL,
+                                       MOJO_READ_MESSAGE_FLAG_NONE);
+```
+
+and map its buffer to retrieve the contents:
+
+``` c
+void* buffer = NULL;
+MojoResult result = MojoGetMessageBuffer(message, &buffer);
+printf("Pipe says: %s", (const char*)buffer);
+```
+
+`result` should be `MOJO_RESULT_OK` and this snippet should write `"hello"` to
+`stdout`.
+
+If we try were to try reading again now that there are no messages on `b`:
+
+``` c
+MojoMessageHandle message;
+MojoResult result = MojoReadMessageNew(b, &message, NULL, NULL, NULL,
+                                       MOJO_READ_MESSAGE_FLAG_NONE);
+```
+
+We'll get a `result` of `MOJO_RESULT_SHOULD_WAIT`, indicating that the pipe is
+not yet readable.
+
+### Messages With Handles
+
+Probably the most useful feature of Mojo IPC is that message pipes can carry
+arbitrary Mojo handles, including other message pipes. This is also
+straightforward.
+
+Here's an example which creates two pipes, using the first pipe to transfer
+one end of the second pipe. If you have a good imagination you can pretend the
+first pipe spans a process boundary, which makes the example more practically
+interesting:
+
+``` c
+MojoHandle a, b;
+MojoHandle c, d;
+MojoMessage message;
+
+// Allocate a message with an empty payload and handle |c| attached. Note that
+// this takes ownership of |c|, effectively invalidating its handle value.
+MojoResult result = MojoAllocMessage(0, &c, 1, MOJO_ALLOC_MESSAGE_FLAG_NONE,
+                                     message);
+
+result = MojoWriteMessageNew(a, message, MOJO_WRITE_MESSAGE_FLAG_NONE);
+
+// Some time later...
+uint32_t num_bytes;
+MojoHandle e;
+uint32_t num_handles = 1;
+MojoResult result = MojoReadMessageNew(b, &message, &num_bytes, &e,
+                                       &num_handles,
+                                       MOJO_READ_MESSAGE_FLAG_NONE);
+```
+
+At this point the handle in `e` is now referencing the same message pipe
+endpoint which was originally referenced by `c`.
+
+Note that `num_handles` above is initialized to 1 before we pass its address to
+`MojoReadMessageNew`. This is to indicate how much `MojoHandle` storage is
+available at the output buffer we gave it (`&e` above).
+
+If we didn't know how many handles to expect in an incoming message -- which is
+often the case -- we can use `MojoReadMessageNew` to query for this information
+first:
+
+``` c
+MojoMessageHandle message;
+uint32_t num_bytes = 0;
+uint32_t num_handles = 0;
+MojoResult result = MojoReadMessageNew(b, &message, &num_bytes, NULL,
+                                       &num_handles,
+                                       MOJO_READ_MESSAGE_FLAG_NONE);
+```
+
+If in this case there were a received message on `b` with some nonzero number
+of handles, `result` would be `MOJO_RESULT_RESOURCE_EXHAUSTED`, and both
+`num_bytes` and `num_handles` would be updated to reflect the payload size and
+number of attached handles on the next available message.
+
+It's also worth noting that if there did happen to be a message available with
+no payload and no handles (*i.e.* an empty message), this would actually return
+`MOJO_RESULT_OK`.
+
+## Data Pipes
+
+Data pipes provide an efficient unidirectional channel for moving large amounts
+of unframed data between two endpoints. Every data pipe has a fixed
+**element size** and **capacity**. Reads and writes must be done in sizes that
+are a multiple of the element size, and writes to the pipe can only be queued
+up to the pipe's capacity before reads must be done to make more space
+available.
+
+Every data pipe has a single **producer** handle used to write data into the
+pipe and a single **consumer** handle used to read data out of the pipe.
+
+Finally, data pipes support both immediate I/O -- reading into and writing out
+from user-supplied buffers -- as well as two-phase I/O, allowing callers to
+temporarily lock some portion of the data pipe in order to read or write its
+contents directly.
+
+See [//mojo/public/c/system/data_pipe.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/data_pipe.h)
+for detailed data pipe API documentation.
+
+### Creating Data Pipes
+
+Use `MojoCreateDataPipe` to create a new data pipe. The
+`MojoCreateDataPipeOptions` structure is used to configure the new pipe, but
+this can be omitted to assume the default options of a single-byte element size
+and an implementation-defined default capacity (64 kB at the time of this
+writing.)
+
+``` c
+MojoHandle producer, consumer;
+MojoResult result = MojoCreateDataPipe(NULL, &producer, &consumer);
+```
+
+### Immediate I/O
+
+Data can be written into or read out of a data pipe using buffers provided by
+the caller. This is generally more convenient than two-phase I/O but is
+also less efficient due to extra copying.
+
+``` c
+uint32_t num_bytes = 12;
+MojoResult result = MojoWriteData(producer, "datadatadata", &num_bytes,
+                                  MOJO_WRITE_DATA_FLAG_NONE);
+```
+
+The above snippet will attempt to write 12 bytes into the data pipe, which
+should succeed and return `MOJO_RESULT_OK`. If the available capacity on the
+pipe was less than the amount requested (the input value of `*num_bytes`) this
+will copy what it can into the pipe and return the number of bytes written in
+`*num_bytes`. If no data could be copied this will instead return
+`MOJO_RESULT_SHOULD_WAIT`.
+
+Reading from the consumer is a similar operation.
+
+``` c
+char buffer[64];
+uint32_t num_bytes = 64;
+MojoResult result = MojoReadData(consumer, buffer, &num_bytes,
+                                 MOJO_READ_DATA_FLAG_NONE);
+```
+
+This will attempt to read up to 64 bytes, returning the actual number of bytes
+read in `*num_bytes`.
+
+`MojoReadData` supports a number of interesting flags to change the behavior:
+you can peek at the data (copy bytes out without removing them from the pipe),
+query the number of bytes available without doing any actual reading of the
+contents, or discard data from the pipe without bothering to copy it anywhere.
+
+This also supports a `MOJO_READ_DATA_FLAG_ALL_OR_NONE` which ensures that the
+call succeeds **only** if the exact number of bytes requested could be read.
+Otherwise such a request will fail with `MOJO_READ_DATA_OUT_OF_RANGE`.
+
+### Two-Phase I/O
+
+Data pipes also support two-phase I/O operations, allowing a caller to
+temporarily lock a portion of the data pipe's storage for direct memory access.
+
+``` c
+void* buffer;
+uint32_t num_bytes = 1024;
+MojoResult result = MojoBeginWriteData(producer, &buffer, &num_bytes,
+                                       MOJO_WRITE_DATA_FLAG_NONE);
+```
+
+This requests write access to a region of up to 1024 bytes of the data pipe's
+next available capacity. Upon success, `buffer` will point to the writable
+storage and `num_bytes` will indicate the size of the buffer there.
+
+The caller should then write some data into the memory region and release it
+ASAP, indicating the number of bytes actually written:
+
+``` c
+memcpy(buffer, "hello", 6);
+MojoResult result = MojoEndWriteData(producer, 6);
+```
+
+Two-phase reads look similar:
+
+``` c
+void* buffer;
+uint32_t num_bytes = 1024;
+MojoResult result = MojoBeginReadData(consumer, &buffer, &num_bytes,
+                                      MOJO_READ_DATA_FLAG_NONE);
+// result should be MOJO_RESULT_OK, since there is some data available.
+
+printf("Pipe says: %s", (const char*)buffer);  // Should say "hello".
+
+result = MojoEndReadData(consumer, 1);  // Say we only consumed one byte.
+
+num_bytes = 1024;
+result = MojoBeginReadData(consumer, &buffer, &num_bytes,
+                           MOJO_READ_DATA_FLAG_NONE);
+printf("Pipe says: %s", (const char*)buffer);  // Should say "ello".
+result = MojoEndReadData(consumer, 5);
+```
+
+## Shared Buffers
+
+Shared buffers are chunks of memory which can be mapped simultaneously by
+multiple processes. Mojo provides a simple API to make these available to
+applications.
+
+See [//mojo/public/c/system/buffer.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/buffer.h)
+for detailed shared buffer API documentation.
+
+### Creating Buffer Handles
+
+Usage is straightforward. You can create a new buffer:
+
+``` c
+// Allocate a shared buffer of 4 kB.
+MojoHandle buffer;
+MojoResult result = MojoCreateSharedBuffer(NULL, 4096, &buffer);
+```
+
+You can also duplicate an existing shared buffer handle:
+
+``` c
+MojoHandle another_name_for_buffer;
+MojoResult result = MojoDuplicateBufferHandle(buffer, NULL,
+                                              &another_name_for_buffer);
+```
+
+This is useful if you want to retain a handle to the buffer while also sharing
+handles with one or more other clients. The allocated buffer remains valid as
+long as at least one shared buffer handle exists to reference it.
+
+### Mapping Buffers
+
+You can map (and later unmap) a specified range of the buffer to get direct
+memory access to its contents:
+
+``` c
+void* data;
+MojoResult result = MojoMapBuffer(buffer, 0, 64, &data,
+                                  MOJO_MAP_BUFFER_FLAG_NONE);
+
+*(int*)data = 42;
+result = MojoUnmapBuffer(data);
+```
+
+A buffer may have any number of active mappings at a time, in any number of
+processes.
+
+### Read-Only Handles
+
+An option can also be specified on `MojoDuplicateBufferHandle` to ensure
+that the newly duplicated handle can only be mapped to read-only memory:
+
+``` c
+MojoHandle read_only_buffer;
+MojoDuplicateBufferHandleOptions options;
+options.struct_size = sizeof(options);
+options.flags = MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY;
+MojoResult result = MojoDuplicateBufferHandle(buffer, &options,
+                                              &read_only_buffer);
+
+// Attempt to map and write to the buffer using the read-only handle:
+void* data;
+result = MojoMapBuffer(read_only_buffer, 0, 64, &data,
+                       MOJO_MAP_BUFFER_FLAG_NONE);
+*(int*)data = 42;  // CRASH
+```
+
+*** note
+**NOTE:** One important limitation of the current implementation is that
+read-only handles can only be produced from a handle that was originally created
+by `MojoCreateSharedBuffer` (*i.e.*, you cannot create a read-only duplicate
+from a non-read-only duplicate), and the handle cannot have been transferred
+over a message pipe first.
+***
+
+## Native Platform Handles (File Descriptors, Windows Handles, *etc.*)
+
+Native platform handles to system objects can be wrapped as Mojo handles for
+seamless transit over message pipes. Mojo currently supports wrapping POSIX
+file descriptors, Windows handles, and Mach ports.
+
+See [//mojo/public/c/system/platform_handle.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/platform_handle.h)
+for detailed platform handle API documentation.
+
+### Wrapping Basic Handle Types
+
+Wrapping a POSIX file descriptor is simple:
+
+``` c
+MojoPlatformHandle platform_handle;
+platform_handle.struct_size = sizeof(platform_handle);
+platform_handle.type = MOJO_PLATFORM_HANDLE_TYPE_FILE_DESCRIPTOR;
+platform_handle.value = (uint64_t)fd;
+MojoHandle handle;
+MojoResult result = MojoWrapPlatformHandle(&platform_handle, &handle);
+```
+
+Note that at this point `handle` effectively owns the file descriptor
+and if you were to call `MojoClose(handle)`, the file descriptor would be closed
+too; but we're not going to close it here! We're going to pretend we've sent it
+over a message pipe, and now we want to unwrap it on the other side:
+
+``` c
+MojoPlatformHandle platform_handle;
+platform_handle.struct_size = sizeof(platform_handle);
+MojoResult result = MojoUnwrapPlatformHandle(handle, &platform_handle);
+int fd = (int)platform_handle.value;
+```
+
+The situation looks nearly identical for wrapping and unwrapping Windows handles
+and Mach ports.
+
+### Wrapping Shared Buffer Handles
+
+Unlike other handle types, shared buffers have special meaning in Mojo, and it
+may be desirable to wrap a native platform handle -- along with some extra
+metadata -- such that be treated like a real Mojo shared buffer handle.
+Conversely it can also be useful to unpack a Mojo shared buffer handle into
+a native platform handle which references the buffer object. Both of these
+things can be done using the `MojoWrapPlatformSharedBuffer` and
+`MojoUnwrapPlatformSharedBuffer` APIs.
+
+On Windows, the wrapped platform handle must always be a Windows handle to
+a file mapping object.
+
+On OS X, the wrapped platform handle must be a memory-object send right.
+
+On all other POSIX systems, the wrapped platform handle must be a file
+descriptor for a shared memory object.
+
+## Signals & Watchers
+
+Message pipe and data pipe (producer and consumer) handles can change state in
+ways that may be interesting to a Mojo API user. For example, you may wish to
+know when a message pipe handle has messages available to be read or when its
+peer has been closed. Such states are reflected by a fixed set of boolean
+signals on each pipe handle.
+
+### Signals
+
+Every message pipe and data pipe handle maintains a notion of
+**signaling state** which may be queried at any time. For example:
+
+``` c
+MojoHandle a, b;
+MojoCreateMessagePipe(NULL, &a, &b);
+
+MojoHandleSignalsState state;
+MojoResult result = MojoQueryHandleSignalsState(a, &state);
+```
+
+The `MojoHandleSignalsState` structure exposes two fields: `satisfied_signals`
+and `satisfiable_signals`. Both of these are bitmasks of the type
+`MojoHandleSignals` (see [//mojo/public/c/system/types.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/types.h)
+for more details.)
+
+The `satisfied_signals` bitmask indicates signals which were satisfied on the
+handle at the time of the call, while the `satisfiable_signals` bitmask
+indicates signals which were still possible to satisfy at the time of the call.
+It is thus by definition always true that:
+
+``` c
+(satisfied_signals | satisfiable_signals) == satisfiable_signals
+```
+
+In other words a signal obviously cannot be satisfied if it is no longer
+satisfiable. Furthermore once a signal is unsatisfiable, *i.e.* is no longer
+set in `sastisfiable_signals`, it can **never** become satisfiable again.
+
+To illustrate this more clearly, consider the message pipe created above. Both
+ends of the pipe are still open and neither has been written to yet. Thus both
+handles start out with the same signaling state:
+
+| Field                 | State |
+|-----------------------|-------|
+| `satisfied_signals`   | `MOJO_HANDLE_SIGNAL_WRITABLE`
+| `satisfiable_signals` | `MOJO_HANDLE_SIGNAL_READABLE + MOJO_HANDLE_SIGNAL_WRITABLE + MOJO_HANDLE_SIGNAL_PEER_CLOSED`
+
+Writing a message to handle `b` will eventually alter the signaling state of `a`
+such that `MOJO_HANDLE_SIGNAL_READABLE` also becomes satisfied. If we were to
+then close `b`, the signaling state of `a` would look like:
+
+| Field                 | State |
+|-----------------------|-------|
+| `satisfied_signals`   | `MOJO_HANDLE_SIGNAL_READABLE + MOJO_HANDLE_SIGNAL_PEER_CLOSED`
+| `satisfiable_signals` | `MOJO_HANDLE_SIGNAL_READABLE + MOJO_HANDLE_SIGNAL_PEER_CLOSED`
+
+Note that even though `a`'s peer is known to be closed (hence making `a`
+permanently unwritable) it remains readable because there's still an unread
+received message waiting to be read from `a`.
+
+Finally if we read the last message from `a` its signaling state becomes:
+
+| Field                 | State |
+|-----------------------|-------|
+| `satisfied_signals`   | `MOJO_HANDLE_SIGNAL_PEER_CLOSED`
+| `satisfiable_signals` | `MOJO_HANDLE_SIGNAL_PEER_CLOSED`
+
+and we know definitively that `a` can never be read from again.
+
+### Watching Signals
+
+The ability to query a handle's signaling state can be useful, but it's not
+sufficient to support robust and efficient pipe usage. Mojo watchers empower
+users with the ability to **watch** a handle's signaling state for interesting
+changes and automatically invoke a notification handler in response.
+
+When a watcher is created it must be bound to a function pointer matching
+the following signature, defined in
+[//mojo/public/c/system/watcher.h](https://cs.chromium.org/chromium/src/mojo/public/c/system/watcher.h):
+
+``` c
+typedef void (*MojoWatcherNotificationCallback)(
+    uintptr_t context,
+    MojoResult result,
+    MojoHandleSignalsState signals_state,
+    MojoWatcherNotificationFlags flags);
+```
+
+The `context` argument corresponds to a specific handle being watched by the
+watcher (read more below), and the remaining arguments provide details regarding
+the specific reason for the notification. It's important to be aware that a
+watcher's registered handler may be called **at any time** and
+**on any thread**.
+
+It's also helpful to understand a bit about the mechanism by which the handler
+can be invoked. Essentially, any Mojo C System API call may elicit a handle
+state change of some kind. If such a change is relevant to conditions watched by
+a watcher, and that watcher is in a state which allows it raise a corresponding
+notification, its notification handler will be invoked synchronously some time
+before the outermost System API call on the current thread's stack returns.
+
+Handle state changes can also occur as a result of incoming IPC from an external
+process. If a pipe in the current process is connected to an endpoint in another
+process and the internal Mojo system receives an incoming message bound for the
+local endpoint, the arrival of that message will trigger a state change on the
+receiving handle and may thus invoke one or more watchers' notification handlers
+as a result.
+
+The `MOJO_WATCHER_NOTIFICATION_FLAG_FROM_SYSTEM` flag on the notification
+handler's `flags` argument is used to indicate whether the handler was invoked
+due to such an internal system IPC event (if the flag is set), or if it was
+invoked synchronously due to some local API call (if the flag is unset.)
+This distinction can be useful to make in certain cases to *e.g.* avoid
+accidental reentrancy in user code.
+
+### Creating a Watcher
+
+Creating a watcher is simple:
+
+``` c
+
+void OnNotification(uintptr_t context,
+                    MojoResult result,
+                    MojoHandleSignalsState signals_state,
+                    MojoWatcherNotificationFlags flags) {
+  // ...
+}
+
+MojoHandle w;
+MojoResult result = MojoCreateWatcher(&OnNotification, &w);
+```
+
+Like all other `MojoHandle` types, watchers may be destroyed by closing them
+with `MojoClose`. Unlike other `MojoHandle` types, watcher handles are **not**
+transferrable across message pipes.
+
+In order for a watcher to be useful, it has to watch at least one handle.
+
+### Adding a Handle to a Watcher
+
+Any given watcher can watch any given (message or data pipe) handle for some set
+of signaling conditions. A handle may be watched simultaneously by multiple
+watchers, and a single watcher can watch multiple different handles
+simultaneously.
+
+``` c
+MojoHandle a, b;
+MojoCreateMessagePipe(NULL, &a, &b);
+
+// Watch handle |a| for readability.
+const uintptr_t context = 1234;
+MojoResult result = MojoWatch(w, a, MOJO_HANDLE_SIGNAL_READABLE, context);
+```
+
+We've successfully instructed watcher `w` to begin watching pipe handle `a` for
+readability. However, our recently created watcher is still in a **disarmed**
+state, meaning that it will never fire a notification pertaining to this watched
+signaling condition. It must be **armed** before that can happen.
+
+### Arming a Watcher
+
+In order for a watcher to invoke its notification handler in response to a
+relevant signaling state change on a watched handle, it must first be armed. A
+watcher may only be armed if none of its watched handles would elicit a
+notification immediately once armed.
+
+In this case `a` is clearly not yet readable, so arming should succeed:
+
+``` c
+MojoResult result = MojoArmWatcher(w, NULL, NULL, NULL, NULL);
+```
+
+Now we can write to `b` to make `a` readable:
+
+``` c
+MojoWriteMessage(b, NULL, 0, NULL, 0, MOJO_WRITE_MESSAGE_NONE);
+```
+
+Eventually -- and in practice possibly before `MojoWriteMessage` even
+returns -- this will cause `OnNotification` to be invoked on the calling thread
+with the `context` value (*i.e.* 1234) that was given when the handle was added
+to the watcher.
+
+The `result` parameter will be `MOJO_RESULT_OK` to indicate that the watched
+signaling condition has been *satisfied*. If the watched condition had instead
+become permanently *unsatisfiable* (*e.g.*, if `b` were instead closed), `result`
+would instead indicate `MOJO_RESULT_FAILED_PRECONDITION`.
+
+**NOTE:** Immediately before a watcher decides to invoke its notification
+handler, it automatically disarms itself to prevent another state change from
+eliciting another notification. Therefore a watcher must be repeatedly rearmed
+in order to continue dispatching signaling notifications.
+
+As noted above, arming a watcher may fail if any of the watched conditions for
+a handle are already partially satisfied or fully unsatisfiable. In that case
+the caller may provide buffers for `MojoArmWatcher` to store information about
+a subset of the relevant watches which caused it to fail:
+
+``` c
+// Provide some storage for information about watches that are already ready.
+uint32_t num_ready_contexts = 4;
+uintptr_t ready_contexts[4];
+MojoResult ready_results[4];
+struct MojoHandleSignalsStates ready_states[4];
+MojoResult result = MojoArmWatcher(w, &num_ready_contexts, ready_contexts,
+                                   ready_results, ready_states);
+```
+
+Because `a` is still readable this operation will fail with
+`MOJO_RESULT_FAILED_PRECONDITION`. The input value of `num_ready_contexts`
+informs `MojoArmWatcher` that it may store information regarding up to 4 watches
+which currently prevent arming. In this case of course there is only one active
+watch, so upon return we will see:
+
+* `num_ready_contexts` is `1`.
+* `ready_contexts[0]` is `1234`.
+* `ready_results[0]` is `MOJO_RESULT_OK`
+* `ready_states[0]` is the last known signaling state of handle `a`.
+
+In other words the stored information mirrors what would have been the
+notification handler's arguments if the watcher were allowed to arm and thus
+notify immediately.
+
+### Cancelling a Watch
+
+There are three ways a watch can be cancelled:
+
+* The watched handle is closed
+* The watcher handle is closed (in which case all of its watches are cancelled.)
+* `MojoCancelWatch` is explicitly called for a given `context`.
+
+In the above example this means any of the following operations will cancel the
+watch on `a`:
+
+``` c
+// Close the watched handle...
+MojoClose(a);
+
+// OR close the watcher handle...
+MojoClose(w);
+
+// OR explicitly cancel.
+MojoResult result = MojoCancelWatch(w, 1234);
+```
+
+In every case the watcher's notification handler is invoked for the cancelled
+watch(es) regardless of whether or not the watcher is or was armed at the time.
+The notification handler receives a `result` of `MOJO_RESULT_CANCELLED` for
+these notifications, and this is guaranteed to be the final notification for any
+given watch context.
+
+### Practical Watch Context Usage
+
+It is common and probably wise to treat a watch's `context` value as an opaque
+pointer to some thread-safe state associated in some way with the handle being
+watched. Here's a small example which uses a single watcher to watch both ends
+of a message pipe and accumulate a count of messages received at each end.
+
+``` c
+// NOTE: For the sake of simplicity this example code is not in fact
+// thread-safe. As long as there's only one thread running in the process and
+// no external process connections, this is fine.
+
+struct WatchedHandleState {
+  MojoHandle watcher;
+  MojoHandle handle;
+  int message_count;
+};
+
+void OnNotification(uintptr_t context,
+                    MojoResult result,
+                    MojoHandleSignalsState signals_state,
+                    MojoWatcherNotificationFlags flags) {
+  struct WatchedHandleState* state = (struct WatchedHandleState*)(context);
+  MojoResult rv;
+
+  if (result == MOJO_RESULT_CANCELLED) {
+    // Cancellation is always the last notification and is guaranteed to
+    // eventually happen for every context, assuming no handles are leaked. We
+    // treat this as an opportunity to free the WatchedHandleState.
+    free(state);
+    return;
+  }
+
+  if (result == MOJO_RESULT_FAILED_PRECONDITION) {
+    // No longer readable, i.e. the other handle must have been closed. Better
+    // cancel. Note that we could also just call MojoClose(state->watcher) here
+    // since we know |context| is its only registered watch.
+    MojoCancelWatch(state->watcher, context);
+    return;
+  }
+
+  // This is the only handle watched by the watcher, so as long as we can't arm
+  // the watcher we know something's up with this handle. Try to read messages
+  // until we can successfully arm again or something goes terribly wrong.
+  while (MojoArmWatcher(state->watcher, NULL, NULL, NULL, NULL) ==
+         MOJO_RESULT_FAILED_PRECONDITION) {
+    rv = MojoReadMessageNew(state->handle, NULL, NULL, NULL,
+                            MOJO_READ_MESSAGE_FLAG_MAY_DISCARD);
+    if (rv == MOJO_RESULT_OK) {
+      state->message_count++;
+    } else if (rv == MOJO_RESULT_FAILED_PRECONDITION) {
+      MojoCancelWatch(state->watcher, context);
+      return;
+    }
+  }
+}
+
+MojoHandle a, b;
+MojoCreateMessagePipe(NULL, &a, &b);
+
+MojoHandle a_watcher, b_watcher;
+MojoCreateWatcher(&OnNotification, &a_watcher);
+MojoCreateWatcher(&OnNotification, &b_watcher)
+
+struct WatchedHandleState* a_state = malloc(sizeof(struct WatchedHandleState));
+a_state->watcher = a_watcher;
+a_state->handle = a;
+a_state->message_count = 0;
+
+struct WatchedHandleState* b_state = malloc(sizeof(struct WatchedHandleState));
+b_state->watcher = b_watcher;
+b_state->handle = b;
+b_state->message_count = 0;
+
+MojoWatch(a_watcher, a, MOJO_HANDLE_SIGNAL_READABLE, (uintptr_t)a_state);
+MojoWatch(b_watcher, b, MOJO_HANDLE_SIGNAL_READABLE, (uintptr_t)b_state);
+
+MojoArmWatcher(a_watcher, NULL, NULL, NULL, NULL);
+MojoArmWatcher(b_watcher, NULL, NULL, NULL, NULL);
+```
+
+Now any writes to `a` will increment `message_count` in `b_state`, and any
+writes to `b` will increment `message_count` in `a_state`.
+
+If either `a` or `b` is closed, both watches will be cancelled - one because
+watch cancellation is implicit in handle closure, and the other because its
+watcher will eventually detect that the handle is no longer readable.
diff --git a/mojo/public/c/system/buffer.h b/mojo/public/c/system/buffer.h
index 0f02737..285e0d7b 100644
--- a/mojo/public/c/system/buffer.h
+++ b/mojo/public/c/system/buffer.h
@@ -2,10 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-// This file contains types/constants and functions specific to buffers (and in
-// particular shared buffers).
-// TODO(vtl): Reorganize this file (etc.) to separate general buffer functions
-// from (shared) buffer creation.
+// This file contains types/constants and functions specific to shared buffers.
 //
 // Note: This header should be compilable as C.
 
@@ -20,15 +17,13 @@
 
 // |MojoCreateSharedBufferOptions|: Used to specify creation parameters for a
 // shared buffer to |MojoCreateSharedBuffer()|.
+//
 //   |uint32_t struct_size|: Set to the size of the
 //       |MojoCreateSharedBufferOptions| struct. (Used to allow for future
 //       extensions.)
+//
 //   |MojoCreateSharedBufferOptionsFlags flags|: Reserved for future use.
 //       |MOJO_CREATE_SHARED_BUFFER_OPTIONS_FLAG_NONE|: No flags; default mode.
-//
-// TODO(vtl): Maybe add a flag to indicate whether the memory should be
-// executable or not?
-// TODO(vtl): Also a flag for discardable (ashmem-style) buffers.
 
 typedef uint32_t MojoCreateSharedBufferOptionsFlags;
 
@@ -50,17 +45,21 @@
 
 // |MojoDuplicateBufferHandleOptions|: Used to specify parameters in duplicating
 // access to a shared buffer to |MojoDuplicateBufferHandle()|.
+//
 //   |uint32_t struct_size|: Set to the size of the
 //       |MojoDuplicateBufferHandleOptions| struct. (Used to allow for future
 //       extensions.)
-//   |MojoDuplicateBufferHandleOptionsFlags flags|: Reserved for future use.
-//       |MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE|: No flags; default
-//       mode.
-//       |MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY|: The duplicate
-//       shared buffer can only be mapped read-only. A read-only duplicate can
-//       only be created before the buffer is passed over a message pipe.
 //
-// TODO(vtl): Add flags to remove writability (and executability)? Also, COW?
+//   |MojoDuplicateBufferHandleOptionsFlags flags|: Flags to control the
+//       behavior of |MojoDuplicateBufferHandle()|. May be some combination of
+//       the following:
+//
+//       |MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE|: No flags; default
+//           mode.
+//       |MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY|: The duplicate
+//           shared buffer can only be mapped read-only. A read-only duplicate
+//           may only be created before any handles to the buffer are passed
+//           over a message pipe.
 
 typedef uint32_t MojoDuplicateBufferHandleOptionsFlags;
 
@@ -102,18 +101,15 @@
 // label for pointer parameters.
 
 // Creates a buffer of size |num_bytes| bytes that can be shared between
-// applications (by duplicating the handle -- see |MojoDuplicateBufferHandle()|
-// -- and passing it over a message pipe). To access the buffer, one must call
-// |MojoMapBuffer()|.
+// processes. The returned handle may be duplicated any number of times by
+// |MojoDuplicateBufferHandle()|.
+//
+// To access the buffer's storage, one must call |MojoMapBuffer()|.
 //
 // |options| may be set to null for a shared buffer with the default options.
 //
 // On success, |*shared_buffer_handle| will be set to the handle for the shared
-// buffer. (On failure, it is not modified.)
-//
-// Note: While more than |num_bytes| bytes may apparently be
-// available/visible/readable/writable, trying to use those extra bytes is
-// undefined behavior.
+// buffer. On failure it is not modified.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
@@ -128,17 +124,14 @@
     uint64_t num_bytes,                                   // In.
     MojoHandle* shared_buffer_handle);                    // Out.
 
-// Duplicates the handle |buffer_handle| to a buffer. This creates another
-// handle (returned in |*new_buffer_handle| on success), which can then be sent
-// to another application over a message pipe, while retaining access to the
-// |buffer_handle| (and any mappings that it may have).
+// Duplicates the handle |buffer_handle| as a new shared buffer handle. On
+// success this returns the new handle in |*new_buffer_handle|. A shared buffer
+// remains allocated as long as there is at least one shared buffer handle
+// referencing it in at least one process in the system.
 //
 // |options| may be set to null to duplicate the buffer handle with the default
 // options.
 //
-// On success, |*shared_buffer_handle| will be set to the handle for the new
-// buffer handle. (On failure, it is not modified.)
-//
 // Returns:
 //   |MOJO_RESULT_OK| on success.
 //   |MOJO_RESULT_INVALID_ARGUMENT| if some argument was invalid (e.g.,
@@ -152,17 +145,16 @@
 // Maps the part (at offset |offset| of length |num_bytes|) of the buffer given
 // by |buffer_handle| into memory, with options specified by |flags|. |offset +
 // num_bytes| must be less than or equal to the size of the buffer. On success,
-// |*buffer| points to memory with the requested part of the buffer. (On
-// failure, it is not modified.)
+// |*buffer| points to memory with the requested part of the buffer. On
+// failure |*buffer| it is not modified.
 //
-// A single buffer handle may have multiple active mappings (possibly depending
-// on the buffer type). The permissions (e.g., writable or executable) of the
-// returned memory may depend on the properties of the buffer and properties
-// attached to the buffer handle as well as |flags|.
+// A single buffer handle may have multiple active mappings The permissions
+// (e.g., writable or executable) of the returned memory depend on th
+// properties of the buffer and properties attached to the buffer handle, as
+// well as |flags|.
 //
-// Note: Though data outside the specified range may apparently be
-// available/visible/readable/writable, trying to use those extra bytes is
-// undefined behavior.
+// A mapped buffer must eventually be unmapped by calling |MojoUnmapBuffer()|
+// with the value of |*buffer| returned by this function.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
@@ -179,8 +171,9 @@
 
 // Unmaps a buffer pointer that was mapped by |MojoMapBuffer()|. |buffer| must
 // have been the result of |MojoMapBuffer()| (not some other pointer inside
-// the mapped memory), and the entire mapping will be removed (partial unmapping
-// is not supported). A mapping may only be unmapped once.
+// the mapped memory), and the entire mapping will be removed.
+//
+// A mapping may only be unmapped once.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
diff --git a/mojo/public/c/system/data_pipe.h b/mojo/public/c/system/data_pipe.h
index 4a7dcef..f51e36c 100644
--- a/mojo/public/c/system/data_pipe.h
+++ b/mojo/public/c/system/data_pipe.h
@@ -17,14 +17,19 @@
 
 // |MojoCreateDataPipeOptions|: Used to specify creation parameters for a data
 // pipe to |MojoCreateDataPipe()|.
+//
 //   |uint32_t struct_size|: Set to the size of the |MojoCreateDataPipeOptions|
 //       struct. (Used to allow for future extensions.)
+//
 //   |MojoCreateDataPipeOptionsFlags flags|: Used to specify different modes of
-//       operation.
-//     |MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE|: No flags; default mode.
+//       operation. May be some combination of the following values:
+//
+//       |MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE|: No flags; default mode.
+//
 //   |uint32_t element_num_bytes|: The size of an element, in bytes. All
 //       transactions and buffers will consist of an integral number of
 //       elements. Must be nonzero.
+//
 //   |uint32_t capacity_num_bytes|: The capacity of the data pipe, in number of
 //       bytes; must be a multiple of |element_num_bytes|. The data pipe will
 //       always be able to queue AT LEAST this much data. Set to zero to opt for
@@ -52,10 +57,11 @@
                    "MojoCreateDataPipeOptions has wrong size");
 
 // |MojoWriteDataFlags|: Used to specify different modes to |MojoWriteData()|
-// and |MojoBeginWriteData()|.
+// and |MojoBeginWriteData()|. May be some combination of the following values:
+//
 //   |MOJO_WRITE_DATA_FLAG_NONE| - No flags; default mode.
 //   |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| - Write either all the elements
-//       requested or none of them.
+//      requested or none of them.
 
 typedef uint32_t MojoWriteDataFlags;
 
@@ -68,10 +74,12 @@
 #endif
 
 // |MojoReadDataFlags|: Used to specify different modes to |MojoReadData()| and
-// |MojoBeginReadData()|.
+// |MojoBeginReadData()|. May be some combination of the following values:
+//
 //   |MOJO_READ_DATA_FLAG_NONE| - No flags; default mode.
 //   |MOJO_READ_DATA_FLAG_ALL_OR_NONE| - Read (or discard) either the requested
-//        number of elements or none.
+//        number of elements or none. NOTE: This flag is not currently supported
+//        by |MojoBeginReadData()|.
 //   |MOJO_READ_DATA_FLAG_DISCARD| - Discard (up to) the requested number of
 //        elements.
 //   |MOJO_READ_DATA_FLAG_QUERY| - Query the number of elements available to
@@ -106,9 +114,10 @@
 // label for pointer parameters.
 
 // Creates a data pipe, which is a unidirectional communication channel for
-// unframed data, with the given options. Data is unframed, but must come as
-// (multiples of) discrete elements, of the size given in |options|. See
-// |MojoCreateDataPipeOptions| for a description of the different options
+// unframed data. Data must be read and written in multiples of discrete
+// discrete elements of size given in |options|.
+//
+// See |MojoCreateDataPipeOptions| for a description of the different options
 // available for data pipes.
 //
 // |options| may be set to null for a data pipe with the default options (which
@@ -117,7 +126,7 @@
 //
 // On success, |*data_pipe_producer_handle| will be set to the handle for the
 // producer and |*data_pipe_consumer_handle| will be set to the handle for the
-// consumer. (On failure, they are not modified.)
+// consumer. On failure they are not modified.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
@@ -132,29 +141,22 @@
     MojoHandle* data_pipe_producer_handle,            // Out.
     MojoHandle* data_pipe_consumer_handle);           // Out.
 
-// Writes the given data to the data pipe producer given by
-// |data_pipe_producer_handle|. |elements| points to data of size |*num_bytes|;
-// |*num_bytes| should be a multiple of the data pipe's element size. If
+// Writes the data pipe producer given by |data_pipe_producer_handle|.
+//
+// |elements| points to data of size |*num_bytes|; |*num_bytes| must be a
+// multiple of the data pipe's element size. If
 // |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| is set in |flags|, either all the data
-// will be written or none is.
+// is written (if enough write capacity is available) or none is.
 //
-// On success, |*num_bytes| is set to the amount of data that was actually
-// written.
-//
-// Note: If the data pipe has the "may discard" option flag (specified on
-// creation), this will discard as much data as required to write the given
-// data, starting with the earliest written data that has not been consumed.
-// However, even with "may discard", if |*num_bytes| is greater than the data
-// pipe's capacity (and |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| is not set), this
-// will write the maximum amount possible (namely, the data pipe's capacity) and
-// set |*num_bytes| to that amount. It will *not* discard data from |elements|.
+// On success |*num_bytes| is set to the amount of data that was actually
+// written. On failure it is unmodified.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
 //   |MOJO_RESULT_INVALID_ARGUMENT| if some argument was invalid (e.g.,
 //       |data_pipe_producer_dispatcher| is not a handle to a data pipe
 //       producer or |*num_bytes| is not a multiple of the data pipe's element
-//       size).
+//       size.)
 //   |MOJO_RESULT_FAILED_PRECONDITION| if the data pipe consumer handle has been
 //       closed.
 //   |MOJO_RESULT_OUT_OF_RANGE| if |flags| has
@@ -166,8 +168,6 @@
 //   |MOJO_RESULT_SHOULD_WAIT| if no data can currently be written (and the
 //       consumer is still open) and |flags| does *not* have
 //       |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| set.
-//
-// TODO(vtl): Should there be a way of querying how much data can be written?
 MOJO_SYSTEM_EXPORT MojoResult
     MojoWriteData(MojoHandle data_pipe_producer_handle,
                   const void* elements,
@@ -175,40 +175,26 @@
                   MojoWriteDataFlags flags);
 
 // Begins a two-phase write to the data pipe producer given by
-// |data_pipe_producer_handle|. On success, |*buffer| will be a pointer to which
-// the caller can write |*buffer_num_bytes| bytes of data. If flags has
-// |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| set, then the output value
-// |*buffer_num_bytes| will be at least as large as its input value, which must
-// also be a multiple of the element size (if |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE|
-// is not set, the input value of |*buffer_num_bytes| is ignored).
+// |data_pipe_producer_handle|. On success |*buffer| will be a pointer to which
+// the caller can write up to |*buffer_num_bytes| bytes of data.
 //
 // During a two-phase write, |data_pipe_producer_handle| is *not* writable.
-// E.g., if another thread tries to write to it, it will get |MOJO_RESULT_BUSY|;
-// that thread can then wait for |data_pipe_producer_handle| to become writable
-// again.
+// If another caller tries to write to it by calling |MojoWriteData()| or
+// |MojoBeginWriteData()|, their request will fail with |MOJO_RESULT_BUSY|.
 //
-// When |MojoBeginWriteData()| returns MOJO_RESULT_OK, and the caller has
-// finished writing data to |*buffer|, it should call |MojoEndWriteData()| to
-// specify the amount written and to complete the two-phase write.
-// |MojoEndWriteData()| need not be called for other return values.
-//
-// Note: If the data pipe has the "may discard" option flag (specified on
-// creation) and |flags| has |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| set, this may
-// discard some data.
+// If |MojoBeginWriteData()| returns MOJO_RESULT_OK and once the caller has
+// finished writing data to |*buffer|, |MojoEndWriteData()| must be called to
+// indicate the amount of data actually written and to complete the two-phase
+// write operation. |MojoEndWriteData()| need not be called when
+// |MojoBeginWriteData()| fails.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
 //   |MOJO_RESULT_INVALID_ARGUMENT| if some argument was invalid (e.g.,
 //       |data_pipe_producer_handle| is not a handle to a data pipe producer or
-//       flags has |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| set and
-//       |*buffer_num_bytes| is not a multiple of the element size).
+//       flags has |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| set.
 //   |MOJO_RESULT_FAILED_PRECONDITION| if the data pipe consumer handle has been
 //       closed.
-//   |MOJO_RESULT_OUT_OF_RANGE| if |flags| has
-//       |MOJO_WRITE_DATA_FLAG_ALL_OR_NONE| set and the required amount of data
-//       (specified by |*buffer_num_bytes|) cannot be written contiguously at
-//       this time. (Note that there may be space available for the required
-//       amount of data, but the "next" write position may not be large enough.)
 //   |MOJO_RESULT_BUSY| if there is already a two-phase write ongoing with
 //       |data_pipe_producer_handle| (i.e., |MojoBeginWriteData()| has been
 //       called, but not yet the matching |MojoEndWriteData()|).
@@ -220,17 +206,16 @@
                        uint32_t* buffer_num_bytes,  // In/out.
                        MojoWriteDataFlags flags);
 
-// Ends a two-phase write to the data pipe producer given by
-// |data_pipe_producer_handle| that was begun by a call to
-// |MojoBeginWriteData()| on the same handle. |num_bytes_written| should
-// indicate the amount of data actually written; it must be less than or equal
-// to the value of |*buffer_num_bytes| output by |MojoBeginWriteData()| and must
-// be a multiple of the element size. The buffer given by |*buffer| from
-// |MojoBeginWriteData()| must have been filled with exactly |num_bytes_written|
-// bytes of data.
+// Ends a two-phase write that was previously initiated by
+// |MojoBeginWriteData()| for the same |data_pipe_producer_handle|.
+//
+// |num_bytes_written| must indicate the number of bytes actually written into
+// the two-phase write buffer. It must be less than or equal to the value of
+// |*buffer_num_bytes| output by |MojoBeginWriteData()|, and it must be a
+// multiple of the data pipe's element size.
 //
 // On failure, the two-phase write (if any) is ended (so the handle may become
-// writable again, if there's space available) but no data written to |*buffer|
+// writable again if there's space available) but no data written to |*buffer|
 // is "put into" the data pipe.
 //
 // Returns:
@@ -297,36 +282,27 @@
 
 // Begins a two-phase read from the data pipe consumer given by
 // |data_pipe_consumer_handle|. On success, |*buffer| will be a pointer from
-// which the caller can read |*buffer_num_bytes| bytes of data. If flags has
-// |MOJO_READ_DATA_FLAG_ALL_OR_NONE| set, then the output value
-// |*buffer_num_bytes| will be at least as large as its input value, which must
-// also be a multiple of the element size (if |MOJO_READ_DATA_FLAG_ALL_OR_NONE|
-// is not set, the input value of |*buffer_num_bytes| is ignored). |flags| must
-// not have |MOJO_READ_DATA_FLAG_DISCARD|, |MOJO_READ_DATA_FLAG_QUERY|, or
-// |MOJO_READ_DATA_FLAG_PEEK| set.
+// which the caller can read up to |*buffer_num_bytes| bytes of data.
 //
 // During a two-phase read, |data_pipe_consumer_handle| is *not* readable.
-// E.g., if another thread tries to read from it, it will get
-// |MOJO_RESULT_BUSY|; that thread can then wait for |data_pipe_consumer_handle|
-// to become readable again.
+// If another caller tries to read from it by calling |MojoReadData()| or
+// |MojoBeginReadData()|, their request will fail with |MOJO_RESULT_BUSY|.
 //
-// Once the caller has finished reading data from |*buffer|, it should call
-// |MojoEndReadData()| to specify the amount read and to complete the two-phase
-// read.
+// Once the caller has finished reading data from |*buffer|, |MojoEndReadData()|
+// must be called to indicate the number of bytes read and to complete the
+// two-phase read operation.
+//
+// |flags| must not have |MOJO_READ_DATA_FLAG_DISCARD|,
+// |MOJO_READ_DATA_FLAG_QUERY|, |MOJO_READ_DATA_FLAG_PEEK|, or
+// |MOJO_READ_DATA_FLAG_ALL_OR_NONE| set.
 //
 // Returns:
 //   |MOJO_RESULT_OK| on success.
 //   |MOJO_RESULT_INVALID_ARGUMENT| if some argument was invalid (e.g.,
 //       |data_pipe_consumer_handle| is not a handle to a data pipe consumer,
-//       |flags| has |MOJO_READ_DATA_FLAG_ALL_OR_NONE| set and
-//       |*buffer_num_bytes| is not a multiple of the element size, or |flags|
-//       has invalid flags set).
+//       or |flags| has invalid flags set.)
 //   |MOJO_RESULT_FAILED_PRECONDITION| if the data pipe producer handle has been
 //       closed.
-//   |MOJO_RESULT_OUT_OF_RANGE| if |flags| has |MOJO_READ_DATA_FLAG_ALL_OR_NONE|
-//       set and the required amount of data (specified by |*buffer_num_bytes|)
-//       cannot be read from a contiguous buffer at this time. (Note that there
-//       may be the required amount of data, but it may not be contiguous.)
 //   |MOJO_RESULT_BUSY| if there is already a two-phase read ongoing with
 //       |data_pipe_consumer_handle| (i.e., |MojoBeginReadData()| has been
 //       called, but not yet the matching |MojoEndReadData()|).
diff --git a/mojo/public/c/system/platform_handle.h b/mojo/public/c/system/platform_handle.h
index 0b02357..7449c2e 100644
--- a/mojo/public/c/system/platform_handle.h
+++ b/mojo/public/c/system/platform_handle.h
@@ -45,12 +45,16 @@
 #define MOJO_PLATFORM_HANDLE_TYPE_WINDOWS_HANDLE ((MojoPlatformHandleType)3)
 #endif
 
-// |MojoPlatformHandle|: A handle to an OS object.
+// |MojoPlatformHandle|: A handle to a native platform object.
+//
 //     |uint32_t struct_size|: The size of this structure. Used for versioning
 //         to allow for future extensions.
+//
 //     |MojoPlatformHandleType type|: The type of handle stored in |value|.
+//
 //     |uint64_t value|: The value of this handle. Ignored if |type| is
-//         MOJO_PLATFORM_HANDLE_TYPE_INVALID.
+//         MOJO_PLATFORM_HANDLE_TYPE_INVALID. Otherwise the meaning of this
+//         value depends on the value of |type|.
 //
 
 struct MOJO_ALIGNAS(8) MojoPlatformHandle {
@@ -84,8 +88,9 @@
     ((MojoPlatformSharedBufferHandleFlags)1 << 0)
 #endif
 
-// Wraps a generic platform handle as a Mojo handle which can be transferred
-// over a message pipe. Takes ownership of the underlying platform object.
+// Wraps a native platform handle as a Mojo handle which can be transferred
+// over a message pipe. Takes ownership of the underlying native platform
+// object.
 //
 // |platform_handle|: The platform handle to wrap.
 //
@@ -103,12 +108,12 @@
 MojoWrapPlatformHandle(const struct MojoPlatformHandle* platform_handle,
                        MojoHandle* mojo_handle);  // Out
 
-// Unwraps a generic platform handle from a Mojo handle. If this call succeeds,
-// ownership of the underlying platform object is bound to the returned platform
-// handle and becomes the caller's responsibility. The Mojo handle is always
-// closed regardless of success or failure.
+// Unwraps a native platform handle from a Mojo handle. If this call succeeds,
+// ownership of the underlying platform object is assumed by the caller. The
+// The Mojo handle is always closed regardless of success or failure.
 //
-// |mojo_handle|: The Mojo handle from which to unwrap the platform handle.
+// |mojo_handle|: The Mojo handle from which to unwrap the native platform
+//     handle.
 //
 // Returns:
 //     |MOJO_RESULT_OK| if the handle was successfully unwrapped. In this case
@@ -119,11 +124,13 @@
 MojoUnwrapPlatformHandle(MojoHandle mojo_handle,
                          struct MojoPlatformHandle* platform_handle);  // Out
 
-// Wraps a platform shared buffer handle as a Mojo shared buffer handle which
-// can be transferred over a message pipe. Takes ownership of the platform
-// shared buffer handle.
+// Wraps a native platform shared buffer handle as a Mojo shared buffer handle
+// which can be used exactly like a shared buffer handle created by
+// |MojoCreateSharedBuffer()| or |MojoDuplicateBufferHandle()|.
 //
-// |platform_handle|: The platform handle to wrap. Must be a handle to a
+// Takes ownership of the native platform shared buffer handle.
+//
+// |platform_handle|: The platform handle to wrap. Must be a native handle to a
 //     shared buffer object.
 // |num_bytes|: The size of the shared buffer in bytes.
 // |flags|: Flags which influence the treatment of the shared buffer object. See
@@ -148,11 +155,11 @@
     MojoPlatformSharedBufferHandleFlags flags,
     MojoHandle* mojo_handle);  // Out
 
-// Unwraps a platform shared buffer handle from a Mojo shared buffer handle.
-// If this call succeeds, ownership of the underlying shared buffer object is
-// bound to the returned platform handle and becomes the caller's
-// responsibility. The Mojo handle is always closed regardless of success or
-// failure.
+// Unwraps a native platform shared buffer handle from a Mojo shared buffer
+// handle. If this call succeeds, ownership of the underlying shared buffer
+// object is assumed by the caller.
+//
+// The Mojo handle is always closed regardless of success or failure.
 //
 // |mojo_handle|: The Mojo shared buffer handle to unwrap.
 //
diff --git a/mojo/public/c/system/types.h b/mojo/public/c/system/types.h
index 8af5320..15813b6b 100644
--- a/mojo/public/c/system/types.h
+++ b/mojo/public/c/system/types.h
@@ -14,9 +14,6 @@
 
 #include "mojo/public/c/system/macros.h"
 
-// TODO(vtl): Notes: Use of undefined flags will lead to undefined behavior
-// (typically they'll be ignored), not necessarily an error.
-
 // |MojoTimeTicks|: A time delta, in microseconds, the meaning of which is
 // source-dependent.
 
@@ -84,8 +81,6 @@
 //
 // The codes from |MOJO_RESULT_OK| to |MOJO_RESULT_DATA_LOSS| come from
 // Google3's canonical error codes.
-//
-// TODO(vtl): Add a |MOJO_RESULT_UNSATISFIABLE|?
 
 typedef uint32_t MojoResult;
 
diff --git a/mojo/public/cpp/README.md b/mojo/public/cpp/README.md
deleted file mode 100644
index d0f1238..0000000
--- a/mojo/public/cpp/README.md
+++ /dev/null
@@ -1,38 +0,0 @@
-Mojo Public C++ API
-===================
-
-This directory contains C++ language bindings for the Mojo Public API.
-
-A number of subdirectories provide wrappers for the lower-level C APIs (in
-subdirectories of the same name, under mojo/public/c/). Typically, these
-wrappers provide increased convenience and/or type-safety.
-
-Other subdirectories provide support (static) libraries of various sorts. In
-this case, the organization is to have the public interface for the library
-defined in header files in the subdirectory itself and the implementation of the
-library at a lower level, under a lib (sub)subdirectory. A developer should be
-able to substitute their own implementation of any such support library, and
-expect other support libraries, which may depend on that library, to work
-properly.
-
-Bindings
---------
-
-The bindings/ subdirectory contains a support (static) library needed by the
-code generated by the bindings generator tool (in mojo/public/tools/bindings/),
-which translates Mojo IDL (.mojom) files into idiomatic C++ (among other
-languages).
-
-System
-------
-
-The system/ subdirectory contains C++ wrappers (and some additional helpers) of
-the API defined in mojo/public/c/system/, which defines the basic, "core" API,
-especially used to communicate with Mojo services.
-
-Test Support
-------------
-
-The test_support/ subdirectory contains C++ wrappers of the test-only API
-defined in mojo/public/c/test_support/. It is not meant for general use by Mojo
-applications.
diff --git a/mojo/public/cpp/bindings/README.md b/mojo/public/cpp/bindings/README.md
new file mode 100644
index 0000000..b37267a
--- /dev/null
+++ b/mojo/public/cpp/bindings/README.md
@@ -0,0 +1,1231 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo C++ Bindings API
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## Overview
+The Mojo C++ Bindings API leverages the
+[C++ System API](/mojo/public/cpp/system) to provide a more natural set of
+primitives for communicating over Mojo message pipes. Combined with generated
+code from the [Mojom IDL and bindings generator](/mojo/public/tools/bindings),
+users can easily connect interface clients and implementations across arbitrary
+intra- and inter-process bounaries.
+
+This document provides a detailed guide to bindings API usage with example code
+snippets. For a detailed API references please consult the headers in
+[//mojo/public/cpp/bindings](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/).
+
+## Getting Started
+
+When a Mojom IDL file is processed by the bindings generator, C++ code is
+emitted in a series of `.h` and `.cc` files with names based on the input
+`.mojom` file. Suppose we create the following Mojom file at
+`//services/db/public/interfaces/db.mojom`:
+
+```
+module db.mojom;
+
+interface Table {
+  AddRow(int32 key, string data);
+};
+
+interface Database {
+  CreateTable(Table& table);
+};
+```
+
+And a GN target to generate the bindings in
+`//services/db/public/interfaces/BUILD.gn`:
+
+```
+import("//mojo/public/tools/bindings/mojom.gni")
+
+mojom("interfaces") {
+  sources = [
+    "db.mojom",
+  ]
+}
+```
+
+If we then build this target:
+
+```
+ninja -C out/r services/db/public/interfaces
+```
+
+This will produce several generated source files, some of which are relevant to
+C++ bindings. Two of these files are:
+
+```
+out/gen/services/business/public/interfaces/factory.mojom.cc
+out/gen/services/business/public/interfaces/factory.mojom.h
+```
+
+You can include the above generated header in your sources in order to use the
+definitions therein:
+
+``` cpp
+#include "services/business/public/interfaces/factory.mojom.h"
+
+class TableImpl : public db::mojom::Table {
+  // ...
+};
+```
+
+This document covers the different kinds of definitions generated by Mojom IDL
+for C++ consumers and how they can effectively be used to communicate across
+message pipes.
+
+*** note
+**NOTE:** Using C++ bindings from within Blink code is typically subject to
+special constraints which require the use of a different generated header.
+For details, see [Blink Type Mapping](#Blink-Type-Mapping).
+***
+
+## Interfaces
+
+Mojom IDL interfaces are translated to corresponding C++ (pure virtual) class
+interface definitions in the generated header, consisting of a single generated
+method signature for each request message on the interface. Internally there is
+also generated code for serialization and deserialization of messages, but this
+detail is hidden from bindings consumers.
+
+### Basic Usage
+
+Let's consider a new `//sample/logger.mojom` to define a simple logging
+interface which clients can use to log simple string messages:
+
+``` cpp
+module sample.mojom;
+
+interface Logger {
+  Log(string message);
+};
+```
+
+Running this through the bindings generator will produce a `logging.mojom.h`
+with the following definitions (modulo unimportant details):
+
+``` cpp
+namespace sample {
+namespace mojom {
+
+class Logger {
+  virtual ~Logger() {}
+
+  virtual void Log(const std::string& message) = 0;
+};
+
+using LoggerPtr = mojo::InterfacePtr<Logger>;
+using LoggerRequest = mojo::InterfaceRequest<Logger>;
+
+}  // namespace mojom
+}  // namespace sample
+```
+
+Makes sense. Let's take a closer look at those type aliases at the end.
+
+### InterfacePtr and InterfaceRequest
+
+You will notice the type aliases for `LoggerPtr` and
+`LoggerRequest` are using two of the most fundamental template types in the C++
+bindings library: **`InterfacePtr<T>`** and **`InterfaceRequest<T>`**.
+
+In the world of Mojo bindings libraries these are effectively strongly-typed
+message pipe endpoints. If an `InterfacePtr<T>` is bound to a message pipe
+endpoint, it can be dereferenced to make calls on an opaque `T` interface. These
+calls immediately serialize their arguments (using generated code) and write a
+corresponding message to the pipe.
+
+An `InterfaceRequest<T>` is essentially just a typed container to hold the other
+end of an `InterfacePtr<T>`'s pipe -- the receiving end -- until it can be
+routed to some implementation which will **bind** it. The `InterfaceRequest<T>`
+doesn't actually *do* anything other than hold onto a pipe endpoint and carry
+useful compile-time type information.
+
+![Diagram illustrating InterfacePtr and InterfaceRequest on either end of a message pipe](https://docs.google.com/drawings/d/17d5gvErbQ6DthEBMS7I1WhCh9bz0n12pvNjydzuRfTI/pub?w=600&h=100)
+
+So how do we create a strongly-typed message pipe?
+
+### Creating Interface Pipes
+
+One way to do this is by manually creating a pipe and binding each end:
+
+``` cpp
+#include "sample/logger.mojom.h"
+
+mojo::MessagePipe pipe;
+sample::mojom::LoggerPtr logger;
+sample::mojom::LoggerRequest request;
+
+logger.Bind(sample::mojom::LoggerPtrInfo(std::move(pipe.handle0), 0u));
+request.Bind(std::move(pipe.handle1));
+```
+
+That's pretty verbose, but the C++ Bindings library provides more convenient
+ways to accomplish the same thing. [interface_request.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/interface_request.h)
+defines a `MakeRequest` function:
+
+``` cpp
+sample::mojom::LoggerPtr logger;
+sample::mojom::LoggerRequest request = mojo::MakeRequest(&logger);
+```
+
+and the `InterfaceRequest<T>` constructor can also take an explicit
+`InterfacePtr<T>*` output argument:
+
+``` cpp
+sample::mojom::LoggerPtr logger;
+sample::mojom::LoggerRequest request(&logger);
+```
+
+Both of these last two snippets are equivalent to the first one.
+
+*** note
+**NOTE:** In the first example above you may notice usage of the `LoggerPtrInfo`
+type, which is a generated alias for `mojo::InterfacePtrInfo<Logger>`. This is
+similar to an `InterfaceRequest<T>` in that it merely holds onto a pipe handle
+and cannot actually read or write messages on the pipe. Both this type and
+`InterfaceRequest<T>` are safe to move freely from thread to thread, whereas a
+bound `InterfacePtr<T>` is bound to a single thread.
+
+An `InterfacePtr<T>` may be unbound by calling its `PassInterface()` method,
+which returns a new `InterfacePtrInfo<T>`. Conversely, an `InterfacePtr<T>` may
+bind (and thus take ownership of) an `InterfacePtrInfo<T>` so that interface
+calls can be made on the pipe.
+
+The thread-bound nature of `InterfacePtr<T>` is necessary to support safe
+dispatch of its [message responses](#Receiving-Responses) and
+[connection error notifications](#Connection-Errors).
+***
+
+Once the `LoggerPtr` is bound we can immediately begin calling `Logger`
+interface methods on it, which will immediately write messages into the pipe.
+These messages will stay queued on the receiving end of the pipe until someone
+binds to it and starts reading them.
+
+``` cpp
+logger->Log("Hello!");
+```
+
+This actually writes a `Log` message to the pipe.
+
+![Diagram illustrating a message traveling on a pipe from LoggerPtr to LoggerRequest](https://docs.google.com/a/google.com/drawings/d/1jWEc6jJIP2ed77Gg4JJ3EVC7hvnwcImNqQJywFwpT8g/pub?w=648&h=123)
+
+But as mentioned above, `InterfaceRequest` *doesn't actually do anything*, so
+that message will just sit on the pipe forever. We need a way to read messages
+off the other end of the pipe and dispatch them. We have to
+**bind the interface request**.
+
+### Binding an Interface Request
+
+There are many different helper classes in the bindings library for binding the
+receiving end of a message pipe. The most primitive among them is the aptly
+named `mojo::Binding<T>`. A `mojo::Binding<T>` bridges an implementation of `T`
+with a single bound message pipe endpoint (via a `mojo::InterfaceRequest<T>`),
+which it continuously watches for readability.
+
+Any time the bound pipe becomes readable, the `Binding` will schedule a task to
+read, deserialize (using generated code), and dispatch all available messages to
+the bound `T` implementation. Below is a sample implementation of the `Logger`
+interface. Notice that the implementation itself owns a `mojo::Binding`. This is
+a common pattern, since a bound implementation must outlive any `mojo::Binding`
+which binds it.
+
+``` cpp
+#include "base/logging.h"
+#include "base/macros.h"
+#include "sample/logger.mojom.h"
+
+class LoggerImpl : public sample::mojom::Logger {
+ public:
+  // NOTE: A common pattern for interface implementations which have one
+  // instance per client is to take an InterfaceRequest in the constructor.
+
+  explicit LoggerImpl(sample::mojom::LoggerRequest request)
+      : binding_(this, std::move(request)) {}
+  ~Logger() override {}
+
+  // sample::mojom::Logger:
+  void Log(const std::string& message) override {
+    LOG(ERROR) << "[Logger] " << message;
+  }
+
+ private:
+  mojo::Binding<sample::mojom::Logger> binding_;
+
+  DISALLOW_COPY_AND_ASSIGN(LoggerImpl);
+};
+```
+
+Now we can construct a `LoggerImpl` over our pending `LoggerRequest`, and the
+previously queued `Log` message will be dispatched ASAP on the `LoggerImpl`'s
+thread:
+
+``` cpp
+LoggerImpl impl(std::move(request));
+```
+
+The diagram below illustrates the following sequence of events, all set in
+motion by the above line of code:
+
+1. The `LoggerImpl` constructor is called, passing the `LoggerRequest` along
+   to the `Binding`.
+2. The `Binding` takes ownership of the `LoggerRequest`'s pipe endpoint and
+   begins watching it for readability. The pipe is readable immediately, so a
+   task is scheduled to read the pending `Log` message from the pipe ASAP.
+3. The `Log` message is read and deserialized, causing the `Binding` to invoke
+   the `Logger::Log` implementation on its bound `LoggerImpl`.
+
+![Diagram illustrating the progression of binding a request, reading a pending message, and dispatching it](https://docs.google.com/drawings/d/1c73-PegT4lmjfHoxhWrHTQXRvzxgb0wdeBa35WBwZ3Q/pub?w=550&h=500)
+
+As a result, our implementation will eventually log the client's `"Hello!"`
+message via `LOG(ERROR)`.
+
+*** note
+**NOTE:** Messages will only be read and dispatched from a pipe as long as the
+object which binds it (*i.e.* the `mojo::Binding` in the above example) remains
+alive.
+***
+
+### Receiving Responses
+
+Some Mojom interface methods expect a response. Suppose we modify our `Logger`
+interface so that the last logged line can be queried like so:
+
+``` cpp
+module sample.mojom;
+
+interface Logger {
+  Log(string message);
+  GetTail() => (string message);
+};
+```
+
+The generated C++ interface will now look like:
+
+``` cpp
+namespace sample {
+namespace mojom {
+
+class Logger {
+ public:
+  virtual ~Logger() {}
+
+  virtual void Log(const std::string& message) = 0;
+
+  using GetTailCallback = base::Callback<void(const std::string& message)>;
+
+  virtual void GetTail(const GetTailCallback& callback) = 0;
+}
+
+}  // namespace mojom
+}  // namespace sample
+```
+
+As before, both clients and implementations of this interface use the same
+signature for the `GetTail` method: implementations use the `callback` argument
+to *respond* to the request, while clients pass a `callback` argument to
+asynchronously `receive` the response. Here's an updated implementation:
+
+```cpp
+class LoggerImpl : public sample::mojom::Logger {
+ public:
+  // NOTE: A common pattern for interface implementations which have one
+  // instance per client is to take an InterfaceRequest in the constructor.
+
+  explicit LoggerImpl(sample::mojom::LoggerRequest request)
+      : binding_(this, std::move(request)) {}
+  ~Logger() override {}
+
+  // sample::mojom::Logger:
+  void Log(const std::string& message) override {
+    LOG(ERROR) << "[Logger] " << message;
+    lines_.push_back(message);
+  }
+
+  void GetTail(const GetTailCallback& callback) override {
+    callback.Run(lines_.back());
+  }
+
+ private:
+  mojo::Binding<sample::mojom::Logger> binding_;
+  std::vector<std::string> lines_;
+
+  DISALLOW_COPY_AND_ASSIGN(LoggerImpl);
+};
+```
+
+And an updated client call:
+
+``` cpp
+void OnGetTail(const std::string& message) {
+  LOG(ERROR) << "Tail was: " << message;
+}
+
+logger->GetTail(base::Bind(&OnGetTail));
+```
+
+Behind the scenes, the implementation-side callback is actually serializing the
+response arguments and writing them onto the pipe for delivery back to the
+client. Meanwhile the client-side callback is invoked by some internal logic
+which watches the pipe for an incoming response message, reads and deserializes
+it once it arrives, and then invokes the callback with the deserialized
+parameters.
+
+### Connection Errors
+
+If there are no remaining messages available on a pipe and the remote end has
+been closed, a connection error will be triggered on the local end. Connection
+errors may also be triggered by automatic forced local pipe closure due to
+*e.g.* a validation error when processing a received message.
+
+Regardless of the underlying cause, when a connection error is encountered on
+a binding endpoint, that endpoint's **connection error handler** (if set) is
+invoked. This handler is a simple `base::Closure` and may only be invoked
+*once* as long as the endpoint is bound to the same pipe. Typically clients and
+implementations use this handler to do some kind of cleanup or -- particuarly if
+the error was unexpected -- create a new pipe and attempt to establish a new
+connection with it.
+
+All message pipe-binding C++ objects (*e.g.*, `mojo::Binding<T>`,
+`mojo::InterfacePtr<T>`, *etc.*) support setting their connection error handler
+via a `set_connection_error_handler` method.
+
+We can set up another end-to-end `Logger` example to demonstrate error handler
+invocation:
+
+``` cpp
+sample::mojom::LoggerPtr logger;
+LoggerImpl impl(mojo::MakeRequest(&logger));
+impl.set_connection_error_handler(base::Bind([] { LOG(ERROR) << "Bye."; }));
+logger->Log("OK cool");
+logger.reset();  // Closes the client end.
+```
+
+As long as `impl` stays alive here, it will eventually receive the `Log` message
+followed immediately by an invocation of the bound callback which outputs
+`"Bye."`. Like all other bindings callbacks, a connection error handler will
+**never** be invoked once its corresponding binding object has been destroyed.
+
+In fact, suppose instead that `LoggerImpl` had set up the following error
+handler within its constructor:
+
+``` cpp
+LoggerImpl::LoggerImpl(sample::mojom::LoggerRequest request)
+    : binding_(this, std::move(request)) {
+  binding_.set_connection_error_handler(
+      base::Bind(&LoggerImpl::OnError, base::Unretained(this)));
+}
+
+void LoggerImpl::OnError() {
+  LOG(ERROR) << "Client disconnected! Purging log lines.";
+  lines_.clear();
+}
+```
+
+The use of `base::Unretained` is *safe* because the error handler will never be
+invoked beyond the lifetime of `binding_`, and `this` owns `binding_`.
+
+### A Note About Ordering
+
+As mentioned in the previous section, closing one end of a pipe will eventually
+trigger a connection error on the other end. However it's important to note that
+this event is itself ordered with respect to any other event (*e.g.* writing a
+message) on the pipe.
+
+This means that it's safe to write something contrived like:
+
+``` cpp
+void GoBindALogger(sample::mojom::LoggerRequest request) {
+  LoggerImpl impl(std::move(request));
+  base::RunLoop loop;
+  impl.set_connection_error_handler(loop.QuitClosure());
+  loop.Run();
+}
+
+void LogSomething() {
+  sample::mojom::LoggerPtr logger;
+  bg_thread->task_runner()->PostTask(
+      FROM_HERE, base::BindOnce(&GoBindALogger, mojo::MakeRequest(&logger)));
+  logger->Log("OK Computer");
+}
+```
+
+When `logger` goes out of scope it immediately closes its end of the message
+pipe, but the impl-side won't notice this until it receives the sent `Log`
+message. Thus the `impl` above will first log our message and *then* see a
+connection error and break out of the run loop.
+
+### Sending Interfaces Over Interfaces
+
+Now we know how to create interface pipes and use their Ptr and Request
+endpoints in some interesting ways. This still doesn't add up to interesting
+IPC! The bread and butter of Mojo IPC is the ability to transfer interface
+endpoints across other interfaces, so let's take a look at how to accomplish
+that.
+
+#### Sending Interface Requests
+
+Consider a new example Mojom in `//sample/db.mojom`:
+
+``` cpp
+module db.mojom;
+
+interface Table {
+  void AddRow(int32 key, string data);
+};
+
+interface Database {
+  AddTable(Table& table);
+};
+```
+
+As noted in the
+[Mojom IDL documentation](/mojo/public/tools/bindings#Primitive-Types),
+the `Table&` syntax denotes a `Table` interface request. This corresponds
+precisely to the `InterfaceRequest<T>` type discussed in the sections above, and
+in fact the generated code for these interfaces is approximately:
+
+``` cpp
+namespace db {
+namespace mojom {
+
+class Table {
+ public:
+  virtual ~Table() {}
+
+  virtual void AddRow(int32_t key, const std::string& data) = 0;
+}
+
+using TablePtr = mojo::InterfacePtr<Table>;
+using TableRequest = mojo::InterfaceRequest<Table>;
+
+class Database {
+ public:
+  virtual ~Database() {}
+
+  virtual void AddTable(TableRequest table);
+};
+
+using DatabasePtr = mojo::InterfacePtr<Database>;
+using DatabaseRequest = mojo::InterfaceRequest<Database>;
+
+}  // namespace mojom
+}  // namespace db
+```
+
+We can put this all together now with an implementation of `Table` and
+`Database`:
+
+``` cpp
+#include "sample/db.mojom.h"
+
+class TableImpl : public db::mojom:Table {
+ public:
+  explicit TableImpl(db::mojom::TableRequest request)
+      : binding_(this, std::move(request)) {}
+  ~TableImpl() override {}
+
+  // db::mojom::Table:
+  void AddRow(int32_t key, const std::string& data) override {
+    rows_.insert({key, data});
+  }
+
+ private:
+  mojo::Binding<db::mojom::Table> binding_;
+  std::map<int32_t, std::string> rows_;
+};
+
+class DatabaseImpl : public db::mojom::Database {
+ public:
+  explicit DatabaseImpl(db::mojom::DatabaseRequest request)
+      : binding_(this, std::move(request)) {}
+  ~DatabaseImpl() override {}
+
+  // db::mojom::Database:
+  void AddTable(db::mojom::TableRequest table) {
+    tables_.emplace_back(base::MakeUnique<TableImpl>(std::move(table)));
+  }
+
+ private:
+  mojo::Binding<db::mojom::Database> binding_;
+  std::vector<std::unique_ptr<TableImpl>> tables_;
+};
+```
+
+Pretty straightforward. The `Table&` Mojom paramter to `AddTable` translates to
+a C++ `db::mojom::TableRequest`, aliased from
+`mojo::InterfaceRequest<db::mojom::Table>`, which we know is just a
+strongly-typed message pipe handle. When `DatabaseImpl` gets an `AddTable` call,
+it constructs a new `TableImpl` and binds it to the received `TableRequest`.
+
+Let's see how this can be used.
+
+``` cpp
+db::mojom::DatabasePtr database;
+DatabaseImpl db_impl(mojo::MakeRequest(&database));
+
+db::mojom::TablePtr table1, table2;
+database->AddTable(mojo::MakeRequest(&table1));
+database->AddTable(mojo::MakeRequest(&table2));
+
+table1->AddRow(1, "hiiiiiiii");
+table2->AddRow(2, "heyyyyyy");
+```
+
+Notice that we can again start using the new `Table` pipes immediately, even
+while their `TableRequest` endpoints are still in transit.
+
+#### Sending InterfacePtrs
+
+Of course we can also send `InterfacePtr`s:
+
+``` cpp
+interface TableListener {
+  OnRowAdded(int32 key, string data);
+};
+
+interface Table {
+  AddRow(int32 key, string data);
+
+  AddListener(TableListener listener);
+};
+```
+
+This would generate a `Table::AddListener` signature like so:
+
+``` cpp
+  virtual void AddListener(TableListenerPtr listener) = 0;
+```
+
+and this could be used like so:
+
+``` cpp
+db::mojom::TableListenerPtr listener;
+TableListenerImpl impl(mojo::MakeRequest(&listener));
+table->AddListener(std::move(listener));
+```
+
+## Other Interface Binding Types
+
+The [Interfaces](#Interfaces) section above covers basic usage of the most
+common bindings object types: `InterfacePtr`, `InterfaceRequest`, and `Binding`.
+While these types are probably the most commonly used in practice, there are
+several other ways of binding both client- and implementation-side interface
+pipes.
+
+### Strong Bindings
+
+A **strong binding** exists as a standalone object which owns its interface
+implementation and automatically cleans itself up when its bound interface
+endpoint detects an error. The
+[**`MakeStrongBinding`**](https://cs.chromim.org/chromium/src//mojo/public/cpp/bindings/strong_binding.h)
+function is used to create such a binding.
+.
+
+``` cpp
+class LoggerImpl : public sample::mojom::Logger {
+ public:
+  LoggerImpl() {}
+  ~LoggerImpl() override {}
+
+  // sample::mojom::Logger:
+  void Log(const std::string& message) override {
+    LOG(ERROR) << "[Logger] " << message;
+  }
+
+ private:
+  // NOTE: This doesn't own any Binding object!
+};
+
+db::mojom::LoggerPtr logger;
+mojo::MakeStrongBinding(base::MakeUnique<DatabaseImpl>(),
+                        mojo::MakeRequest(&logger));
+
+logger->Log("NOM NOM NOM MESSAGES");
+```
+
+Now as long as `logger` remains open somewhere in the system, the bound
+`DatabaseImpl` on the other end will remain alive.
+
+### Binding Sets
+
+Sometimes it's useful to share a single implementation instance with multiple
+clients. [**`BindingSet`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/binding_set.h)
+makes this easy. Consider the Mojom:
+
+``` cpp
+module system.mojom;
+
+interface Logger {
+  Log(string message);
+};
+
+interface LoggerProvider {
+  GetLogger(Logger& logger);
+};
+```
+
+We can use `BindingSet` to bind multiple `Logger` requests to a single
+implementation instance:
+
+``` cpp
+class LogManager : public system::mojom::LoggerProvider,
+                   public system::mojom::Logger {
+ public:
+  explicit LogManager(system::mojom::LoggerProviderRequest request)
+      : provider_binding_(this, std::move(request)) {}
+  ~LogManager() {}
+
+  // system::mojom::LoggerProvider:
+  void GetLogger(LoggerRequest request) override {
+    logger_bindings_.AddBinding(this, std::move(request));
+  }
+
+  // system::mojom::Logger:
+  void Log(const std::string& message) override {
+    LOG(ERROR) << "[Logger] " << message;
+  }
+
+ private:
+  mojo::Binding<system::mojom::LoggerProvider> provider_binding_;
+  mojo::BindingSet<system::mojom::Logger> logger_bindings_;
+};
+
+```
+
+
+### InterfacePtr Sets
+
+Similar to the `BindingSet` above, sometimes it's useful to maintain a set of
+`InterfacePtr`s for *e.g.* a set of clients observing some event.
+[**`InterfacePtrSet`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/interface_ptr_set.h)
+is here to help. Take the Mojom:
+
+``` cpp
+module db.mojom;
+
+interface TableListener {
+  OnRowAdded(int32 key, string data);
+};
+
+interface Table {
+  AddRow(int32 key, string data);
+  AddListener(TableListener listener);
+};
+```
+
+An implementation of `Table` might look something like like this:
+
+``` cpp
+class TableImpl : public db::mojom::Table {
+ public:
+  TableImpl() {}
+  ~TableImpl() override {}
+
+  // db::mojom::Table:
+  void AddRow(int32_t key, const std::string& data) override {
+    rows_.insert({key, data});
+    listeners_.ForEach([key, &data](db::mojom::TableListener* listener) {
+      listener->OnRowAdded(key, data);
+    });
+  }
+
+  void AddListener(db::mojom::TableListenerPtr listener) {
+    listeners_.AddPtr(std::move(listener));
+  }
+
+ private:
+  mojo::InterfacePtrSet<db::mojom::Table> listeners_;
+  std::map<int32_t, std::string> rows_;
+};
+```
+
+## Associated Interfaces
+
+See [this document](https://www.chromium.org/developers/design-documents/mojo/associated-interfaces).
+
+TODO: Move the above doc into the repository markdown docs.
+
+## Synchronous Calls
+
+See [this document](https://www.chromium.org/developers/design-documents/mojo/synchronous-calls)
+
+TODO: Move the above doc into the repository markdown docs.
+
+## Type Mapping
+
+In many instances you might prefer that your generated C++ bindings use a more
+natural type to represent certain Mojom types in your interface methods. For one
+example consider a Mojom struct such as the `Rect` below:
+
+``` cpp
+module gfx.mojom;
+
+struct Rect {
+  int32 x;
+  int32 y;
+  int32 width;
+  int32 height;
+};
+
+interface Canvas {
+  void FillRect(Rect rect);
+};
+```
+
+The `Canvas` Mojom interface would normally generate a C++ interface like:
+
+``` cpp
+class Canvas {
+ public:
+  virtual void FillRect(RectPtr rect) = 0;
+};
+```
+
+However, the Chromium tree already defines a native
+[`gfx::Rect`](https://cs.chromium.org/chromium/src/ui/gfx/geometry/rect.h) which
+is equivalent in meaning but which also has useful helper methods. Instead of
+manually converting between a `gfx::Rect` and the Mojom-generated `RectPtr` at
+every message boundary, wouldn't it be nice if the Mojom bindings generator
+could instead generate:
+
+``` cpp
+class Canvas {
+ public:
+  virtual void FillRect(const gfx::Rect& rect) = 0;
+}
+```
+
+The correct answer is, "Yes! That would be nice!" And fortunately, it can!
+
+### Global Configuration
+
+While this feature is quite powerful, it introduces some unavoidable complexity
+into build system. This stems from the fact that type-mapping is an inherently
+viral concept: if `gfx::mojom::Rect` is mapped to `gfx::Rect` anywhere, the
+mapping needs to apply *everywhere*.
+
+For this reason we have a few global typemap configurations defined in
+[chromium_bindings_configuration.gni](https://cs.chromium.com/chromium/src/mojo/public/tools/bindings/chromium_bindings_configuration.gni)
+and
+[blink_bindings_configuration.gni](https://cs.chromium.com/chromium/src/mojo/public/tools/bindings/blink_bindings_configuration.gni). These configure the two supported [variants](#Variants) of Mojom generated
+bindings in the repository. Read more on this in the sections that follow.
+
+For now, let's take a look at how to express the mapping from `gfx::mojom::Rect`
+to `gfx::Rect`.
+
+### Defining `StructTraits`
+
+In order to teach generated bindings code how to serialize an arbitrary native
+type `T` as an arbitrary Mojom type `mojom::U`, we need to define an appropriate
+specialization of the
+[`mojo::StructTraits`](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/struct_traits.h)
+template.
+
+A valid specialization of `StructTraits` MUST define the following static
+methods:
+
+* A single static accessor for every field of the Mojom struct, with the exact
+  same name as the struct field. These accessors must all take a const ref to
+  an object of the native type, and must return a value compatible with the
+  Mojom struct field's type. This is used to safely and consistently extract
+  data from the native type during message serialization without incurring extra
+  copying costs.
+
+* A single static `Read` method which initializes an instance of the the native
+  type given a serialized representation of the Mojom struct. The `Read` method
+  must return a `bool` to indicate whether the incoming data is accepted
+  (`true`) or rejected (`false`).
+
+There are other methods a `StructTraits` specialization may define to satisfy
+some less common requirements. See
+[Advanced StructTraits Usage](#Advanced-StructTraits-Usage) for details.
+
+In order to define the mapping for `gfx::Rect`, we want the following
+`StructTraits` specialization, which we'll define in
+`//ui/gfx/geometry/mojo/geometry_struct_traits.h`:
+
+``` cpp
+#include "mojo/public/cpp/bindings/struct_traits.h"
+#include "ui/gfx/geometry/rect.h"
+#include "ui/gfx/geometry/mojo/geometry.mojom.h"
+
+namespace mojo {
+
+template <>
+class StructTraits<gfx::mojom::RectDataView, gfx::Rect> {
+ public:
+  static int32_t x(const gfx::Rect& r) { return r.x(); }
+  static int32_t y(const gfx::Rect& r) { return r.y(); }
+  static int32_t width(const gfx::Rect& r) { return r.width(); }
+  static int32_t height(const gfx::Rect& r) { return r.height(); }
+
+  static bool Read(gfx::mojom::RectDataView data, gfx::Rect* out_rect);
+};
+
+}  // namespace mojo
+```
+
+And in `//ui/gfx/geometry/mojo/geometry_struct_traits.cc`:
+
+``` cpp
+#include "ui/gfx/geometry/mojo/geometry_struct_traits.h"
+
+namespace mojo {
+
+// static
+template <>
+bool StructTraits<gfx::mojom::RectDataView, gfx::Rect>::Read(
+    gfx::mojom::RectDataView data,
+  gfx::Rect* out_rect) {
+  if (data.width() < 0 || data.height() < 0)
+    return false;
+
+  out_rect->SetRect(data.x(), data.y(), data.width(), data.height());
+  return true;
+};
+
+}  // namespace mojo
+```
+
+Note that the `Read()` method returns `false` if either the incoming `width` or
+`height` fields are negative. This acts as a validation step during
+deserialization: if a client sends a `gfx::Rect` with a negative width or
+height, its message will be rejected and the pipe will be closed. In this way,
+type mapping can serve to enable custom validation logic in addition to making
+callsites and interface implemention more convenient.
+
+### Enabling a New Type Mapping
+
+We've defined the `StructTraits` necessary, but we still need to teach the
+bindings generator (and hence the build system) about the mapping. To do this we
+must create a **typemap** file, which uses familiar GN syntax to describe the
+new type mapping.
+
+Let's place this `geometry.typemap` file alongside our Mojom file:
+
+```
+mojom = "//ui/gfx/geometry/mojo/geometry.mojom"
+public_headers = [ "//ui/gfx/geometry/rect.h" ]
+traits_headers = [ "//ui/gfx/geometry/mojo/geometry_struct_traits.h" ]
+sources = [ "//ui/gfx/geometry/mojo/geometry_struct_traits.cc" ]
+public_deps = [ "//ui/gfx/geometry" ]
+type_mappings = [
+  "gfx.mojom.Rect=gfx::Rect",
+]
+```
+
+Let's look at each of the variables above:
+
+* `mojom`: Specifies the `mojom` file to which the typemap applies. Many
+  typemaps may apply to the same `mojom` file, but any given typemap may only
+  apply to a single `mojom` file.
+* `public_headers`: Additional headers required by any code which would depend
+  on the Mojom definition of `gfx.mojom.Rect` now that the typemap is applied.
+  Any headers required for the native target type definition should be listed
+  here.
+* `traits_headers`: Headers which contain the relevant `StructTraits`
+  specialization(s) for any type mappings described by this file.
+* `sources`: Any private implementation sources needed for the `StructTraits`
+  definition.
+* `public_deps`: Target dependencies exposed by the `public_headers` and
+  `traits_headers`.
+* `deps`: Target dependencies exposed by `sources` but not already covered by
+  `public_deps`.
+* `type_mappings`: A list of type mappings to be applied for this typemap. The
+  strings in this list are of the format `"MojomType=CppType"`, where
+  `MojomType` must be a fully qualified Mojom typename and `CppType` must be a
+  fully qualified C++ typename. Additional attributes may be specified in square
+  brackets following the `CppType`:
+    * `move_only`: The `CppType` is move-only and should be passed by value
+      in any generated method signatures. Note that `move_only` is transitive,
+      so containers of `MojomType` will translate to containers of `CppType`
+      also passed by value.
+    * `copyable_pass_by_value`: Forces values of type `CppType` to be passed by
+      value without moving them. Unlike `move_only`, this is not transitive.
+    * `nullable_is_same_type`: By default a non-nullable `MojomType` will be
+      mapped to `CppType` while a nullable `MojomType?` will be mapped to
+      `base::Optional<CppType>`. If this attribute is set, the `base::Optional`
+      wrapper is omitted for nullable `MojomType?` values, but the
+      `StructTraits` definition for this type mapping must define additional
+      `IsNull` and `SetToNull` methods. See
+      [Specializing Nullability](#Specializing-Nullability) below.
+
+
+Now that we have the typemap file we need to add it to a local list of typemaps
+that can be added to the global configuration. We create a new
+`//ui/gfx/typemaps.gni` file with the following contents:
+
+```
+typemaps = [
+  "//ui/gfx/geometry/mojo/geometry.typemap",
+]
+```
+
+And finally we can reference this file in the global default (Chromium) bindings
+configuration by adding it to `_typemap_imports` in
+[chromium_bindings_configuration.gni](https://cs.chromium.com/chromium/src/mojo/public/tools/bindings/chromium_bindings_configuration.gni):
+
+```
+_typemap_imports = [
+  ...,
+  "//ui/gfx/typemaps.gni",
+  ...,
+]
+```
+
+### StructTraits Reference
+
+Each of a `StructTraits` specialization's static getter methods -- one per
+struct field -- must return a type which can be used as a data source for the
+field during serialization. This is a quick reference mapping Mojom field type
+to valid getter return types:
+
+| Mojom Field Type             | C++ Getter Return Type |
+|------------------------------|------------------------|
+| `bool`                       | `bool`
+| `int8`                       | `int8_t`
+| `uint8`                      | `uint8_t`
+| `int16`                      | `int16_t`
+| `uint16`                     | `uint16_t`
+| `int32`                      | `int32_t`
+| `uint32`                     | `uint32_t`
+| `int64`                      | `int64_t`
+| `uint64`                     | `uint64_t`
+| `float`                      | `float`
+| `double`                     | `double`
+| `handle`                     | `mojo::ScopedHandle`
+| `handle<message_pipe>`       | `mojo::ScopedMessagePipeHandle`
+| `handle<data_pipe_consumer>` | `mojo::ScopedDataPipeConsumerHandle`
+| `handle<data_pipe_producer>` | `mojo::ScopedDataPipeProducerHandle`
+| `handle<shared_buffer>`      | `mojo::ScopedSharedBufferHandle`
+| `FooInterface`               | `FooInterfacePtr`
+| `FooInterface&`              | `FooInterfaceRequest`
+| `associated FooInterface`    | `FooAssociatedInterfacePtr`
+| `associated FooInterface&`   | `FooAssociatedInterfaceRequest`
+| `string`                     | Value or reference to any type `T` that has a `mojo::StringTraits` specialization defined. By default this includes `std::string`, `base::StringPiece`, and `WTF::String` (Blink).
+| `array<T>`                   | Value or reference to any type `T` that has a `mojo::ArrayTraits` specialization defined. By default this includes `std::vector<T>`, `mojo::CArray<T>`, and `WTF::Vector<T>` (Blink).
+| `map<K, V>`                  | Value or reference to any type `T` that has a `mojo::MapTraits` specialization defined. By default this includes `std::map<T>`, `mojo::unordered_map<T>`, and `WTF::HashMap<T>` (Blink).
+| `FooEnum`                    | Value of any type that has an appropriate `EnumTraits` specialization defined. By default this inlcudes only the generated `FooEnum` type.
+| `FooStruct`                  | Value or reference to any type that has an appropriate `StructTraits` specialization defined. By default this includes only the generated `FooStructPtr` type.
+| `FooUnion`                   | Value of reference to any type that has an appropriate `UnionTraits` specialization defined. By default this includes only the generated `FooUnionPtr` type.
+
+### Using Generated DataView Types
+
+Static `Read` methods on `StructTraits` specializations get a generated
+`FooDataView` argument (such as the `RectDataView` in the example above) which
+exposes a direct view of the serialized Mojom structure within an incoming
+message's contents. In order to make this as easy to work with as possible, the
+generated `FooDataView` types have a generated method corresponding to every
+struct field:
+
+* For POD field types (*e.g.* bools, floats, integers) these are simple accessor
+  methods with names identical to the field name. Hence in the `Rect` example we
+  can access things like `data.x()` and `data.width()`. The return types
+  correspond exactly to the mappings listed in the table above, under
+  [StructTraits Reference](#StructTraits-Reference).
+
+* For handle and interface types (*e.g* `handle` or `FooInterface&`) these
+  are named `TakeFieldName` (for a field named `field_name`) and they return an
+  appropriate move-only handle type by value. The return types correspond
+  exactly to the mappings listed in the table above, under
+  [StructTraits Reference](#StructTraits-Reference).
+
+* For all other field types (*e.g.*, enums, strings, arrays, maps, structs)
+  these are named `ReadFieldName` (for a field named `field_name`) and they
+  return a `bool` (to indicate success or failure in reading). On success they
+  fill their output argument with the deserialized field value. The output
+  argument may be a pointer to any type with an appropriate `StructTraits`
+  specialization defined, as mentioned in the table above, under
+  [StructTraits Reference](#StructTraits-Reference).
+
+An example would be useful here. Suppose we introduced a new Mojom struct:
+
+``` cpp
+struct RectPair {
+  Rect left;
+  Rect right;
+};
+```
+
+and a corresponding C++ type:
+
+``` cpp
+class RectPair {
+ public:
+  RectPair() {}
+
+  const gfx::Rect& left() const { return left_; }
+  const gfx::Rect& right() const { return right_; }
+
+  void Set(const gfx::Rect& left, const gfx::Rect& right) {
+    left_ = left;
+    right_ = right;
+  }
+
+  // ... some other stuff
+
+ private:
+  gfx::Rect left_;
+  gfx::Rect right_;
+};
+```
+
+Our traits to map `gfx::mojom::RectPair` to `gfx::RectPair` might look like
+this:
+
+``` cpp
+namespace mojo {
+
+template <>
+class StructTraits
+ public:
+  static const gfx::Rect& left(const gfx::RectPair& pair) {
+    return pair.left();
+  }
+
+  static const gfx::Rect& right(const gfx::RectPair& pair) {
+    return pair.right();
+  }
+
+  static bool Read(gfx::mojom::RectPairDataView data, gfx::RectPair* out_pair) {
+    gfx::Rect left, right;
+    if (!data.ReadLeft(&left) || !data.ReadRight(&right))
+      return false;
+    out_pair->Set(left, right);
+    return true;
+  }
+}  // namespace mojo
+```
+
+Generated `ReadFoo` methods always convert `multi_word_field_name` fields to
+`ReadMultiWordFieldName` methods.
+
+### Variants
+
+By now you may have noticed that additional C++ sources are generated when a
+Mojom is processed. These exist due to type mapping, and the source files we
+refer to throughout this docuemnt (namely `foo.mojom.cc` and `foo.mojom.h`) are
+really only one **variant** (the *default* or *chromium* variant) of the C++
+bindings for a given Mojom file.
+
+The only other variant currently defined in the tree is the *blink* variant,
+which produces a few additional files:
+
+```
+out/gen/sample/db.mojom-blink.cc
+out/gen/sample/db.mojom-blink.h
+```
+
+These files mirror the definitions in the default variant but with different
+C++ types in place of certain builtin field and parameter types. For example,
+Mojom strings are represented by `WTF::String` instead of `std::string`. To
+avoid symbol collisions, the variant's symbols are nested in an extra inner
+namespace, so Blink consumer of the interface might write something like:
+
+```
+#include "sample/db.mojom-blink.h"
+
+class TableImpl : public db::mojom::blink::Table {
+ public:
+  void AddRow(int32_t key, const WTF::String& data) override {
+    // ...
+  }
+};
+```
+
+In addition to using different C++ types for builtin strings, arrays, and maps,
+the global typemap configuration for default and "blink" variants are completely
+separate. To add a typemap for the Blink configuration, you can modify
+[blink_bindings_configuration.gni](https://cs.chromium.org/chromium/src/mojo/public/tools/bindings/blink_bindings_configuration.gni).
+
+All variants share some definitions which are unaffected by differences in the
+type mapping configuration (enums, for example). These definitions are generated
+in *shared* sources:
+
+```
+out/gen/sample/db.mojom-shared.cc
+out/gen/sample/db.mojom-shared.h
+out/gen/sample/db.mojom-shared-internal.h
+```
+
+Including either variant's header (`db.mojom.h` or `db.mojom-blink.h`)
+implicitly includes the shared header, but you have on some occasions wish to
+include *only* the shared header in some instances.
+
+Finally, note that for `mojom` GN targets, there is implicitly a corresponding
+`mojom_{variant}` target defined for any supported bindings configuration. So
+for example if you've defined in `//sample/BUILD.gn`:
+
+```
+import("mojo/public/tools/bindings/mojom.gni")
+
+mojom("interfaces") {
+  sources = [
+    "db.mojom",
+  ]
+}
+```
+
+Code in Blink which wishes to use the generated Blink-variant definitions must
+depend on `"//sample:interfaces_blink"`.
+
+## Versioning Considerations
+
+For general documentation of versioning in the Mojom IDL see
+[Versioning](/mojo/public/tools/bindings#Versioning).
+
+This section briefly discusses some C++-specific considerations relevant to
+versioned Mojom types.
+
+### Querying Interface Versions
+
+`InterfacePtr` defines the following methods to query or assert remote interface
+version:
+
+```cpp
+void QueryVersion(const base::Callback<void(uint32_t)>& callback);
+```
+
+This queries the remote endpoint for the version number of its binding. When a
+response is received `callback` is invoked with the remote version number. Note
+that this value is cached by the `InterfacePtr` instance to avoid redundant
+queries.
+
+```cpp
+void RequireVersion(uint32_t version);
+```
+
+Informs the remote endpoint that a minimum version of `version` is required by
+the client. If the remote endpoint cannot support that version, it will close
+its end of the pipe immediately, preventing any other requests from being
+received.
+
+### Versioned Enums
+
+For convenience, every extensible enum has a generated helper function to
+determine whether a received enum value is known by the implementation's current
+version of the enum definition. For example:
+
+```cpp
+[Extensible]
+enum Department {
+  SALES,
+  DEV,
+  RESEARCH,
+};
+```
+
+generates the function in the same namespace as the generated C++ enum type:
+
+```cpp
+inline bool IsKnownEnumValue(Department value);
+```
+
+### Additional Documentation
+
+[Calling Mojo From Blink](https://www.chromium.org/developers/design-documents/mojo/calling-mojo-from-blink)
+:    A brief overview of what it looks like to use Mojom C++ bindings from
+     within Blink code.
diff --git a/mojo/public/cpp/system/README.md b/mojo/public/cpp/system/README.md
new file mode 100644
index 0000000..782744f0
--- /dev/null
+++ b/mojo/public/cpp/system/README.md
@@ -0,0 +1,396 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo C++ System API
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## 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](/mojo/public/c/system) (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](https://cs.chromium.org/chromium/src/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: `MessagePipeHandle`, `SharedBufferHandle`,
+`DataPipeConsumerHandle`, `DataPipeProducerHandle`, and `WatcherHandle`.
+
+Each of these also has a corresponding, move-only, scoped type for safer usage:
+`ScopedMessagePipeHandle`, `ScopedSharedBufferHandle`, 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:
+
+``` cpp
+mojo::MessagePipe pipe;
+
+// NOTE: Because pipes are bi-directional there is no implicit semantic
+// difference between |handle0| or |handle1| here. They're just two ends of a
+// pipe. The choice to treat one as a "client" and one as a "server" is entirely
+// a the API user's decision.
+mojo::ScopedMessagePipeHandle client = std::move(pipe.handle0);
+mojo::ScopedMessagePipeHandle server = std::move(pipe.handle1);
+```
+
+or you may call `CreateMessagePipe`:
+
+``` cpp
+mojo::ScopedMessagePipeHandle client;
+mojo::ScopedMessagePipeHandle server;
+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:
+
+``` cpp
+mojo::ScopedMessageHandle message;
+mojo::AllocMessage(6, nullptr, 0, MOJO_ALLOC_MESSAGE_FLAG_NONE, &message);
+
+void *buffer;
+mojo::GetMessageBuffer(message.get(), &buffer);
+
+const std::string kMessage = "hello";
+std::copy(kMessage.begin(), kMessage.end(), static_cast<char*>(buffer));
+
+mojo::WriteMessageNew(client.get(), std::move(message),
+                      MOJO_WRITE_MESSAGE_FLAG_NONE);
+
+// Some time later...
+
+mojo::ScopedMessageHandle received_message;
+uint32_t num_bytes;
+mojo::ReadMessageNew(server.get(), &received_message, &num_bytes, nullptr,
+                     nullptr, MOJO_READ_MESSAGE_FLAG_NONE);
+```
+
+See [message_pipe.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/message_pipe.h)
+for detailed C++ message pipe API documentation.
+
+## Data Pipes
+
+Similar to [Message Pipes](#Message-Pipes), the C++ library has some simple
+helpers for more strongly-typed data pipe usage:
+
+``` cpp
+mojo::DataPipe pipe;
+mojo::ScopedDataPipeProducerHandle producer = std::move(pipe.producer);
+mojo::ScopedDataPipeConsumerHandle consumer = std::move(pipe.consumer);
+
+// Or alternatively:
+mojo::ScopedDataPipeProducerHandle producer;
+mojo::ScopedDataPipeConsumerHandle consumer;
+mojo::CreateDataPipe(null, &producer, &consumer);
+```
+
+// Reads from a data pipe. See |MojoReadData()| for complete documentation.
+inline MojoResult ReadDataRaw(DataPipeConsumerHandle data_pipe_consumer,
+                              void* elements,
+                              uint32_t* num_bytes,
+                              MojoReadDataFlags flags) {
+  return MojoReadData(data_pipe_consumer.value(), elements, num_bytes, flags);
+}
+
+// Begins a two-phase read
+C++ helpers which correspond directly to the
+[Data Pipe C API](/mojo/public/c/system#Data-Pipes) for immediate and two-phase
+I/O are provided as well. For example:
+
+``` cpp
+uint32_t num_bytes = 7;
+mojo::WriteDataRaw(producer.get(), "hihihi",
+                   &num_bytes, MOJO_WRITE_DATA_FLAG_NONE);
+
+// Some time later...
+
+char buffer[64];
+uint32_t num_bytes = 64;
+mojo::ReadDataRaw(consumer.get(), buffer, &num_bytes, MOJO_READ_DATA_FLAG_NONE);
+```
+
+See [data_pipe.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/data_pipe.h)
+for detailed C++ data pipe API documentation.
+
+## Shared Buffers
+
+A new shared buffers can be allocated like so:
+
+``` cpp
+mojo::ScopedSharedBufferHandle buffer =
+    mojo::ScopedSharedBufferHandle::Create(4096);
+```
+
+This new handle can be cloned arbitrarily many times by using the underlying
+handle's `Clone` method:
+
+``` cpp
+mojo::ScopedSharedBufferHandle another_handle = buffer->Clone();
+mojo::ScopedSharedBufferHandle read_only_handle =
+    buffer->Clone(mojo::SharedBufferHandle::AccessMode::READ_ONLY);
+```
+
+And finally the library also provides a scoper for mapping the shared buffer's
+memory:
+
+``` cpp
+mojo::ScopedSharedBufferMapping mapping = buffer->Map(64);
+static_cast<int*>(mapping.get()) = 42;
+
+mojo::ScopedSharedBufferMapping another_mapping = buffer->MapAtOffset(64, 4);
+static_cast<int*>(mapping.get()) = 43;
+```
+
+When `mapping` and `another_mapping` are destroyed, they automatically unmap
+their respective memory regions.
+
+See [buffer.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/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::PlatformFile` and `base::SharedMemoryHandle`. See
+[platform_handle.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/platform_handle.h)
+for detailed C++ platform handle API documentation.
+
+## Signals & Watchers
+
+For an introduction to the concepts of handle signals and watchers, check out
+the C API's documentation on [Signals & Watchers](/mojo/public/c/system#Signals-Watchers).
+
+### Querying Signals
+
+Any C++ handle type's last known signaling state can be queried by calling the
+`QuerySignalsState` method on the handle:
+
+``` cpp
+mojo::MessagePipe message_pipe;
+mojo::DataPipe data_pipe;
+mojo::HandleSignalsState a = message_pipe.handle0->QuerySignalsState();
+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:
+
+``` c
+struct MojoHandleSignalsState state;
+MojoQueryHandleSignalsState(handle0, &state);
+if (state.satisfied_signals & MOJO_HANDLE_SIGNAL_READABLE) {
+  // ...
+}
+```
+
+the C++ API equivalent would be:
+
+``` cpp
+if (message_pipe.handle0->QuerySignalsState().readable()) {
+  // ...
+}
+```
+
+### Watching Handles
+
+The [`mojo::SimpleWatcher`](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/simple_watcher.h)
+class serves as a convenient helper for using the [low-level watcher API](/mojo/public/c/system#Signals-Watchers)
+to watch a handle for signaling state changes. A `SimpleWatcher` is bound to a
+single thread and always dispatches its notifications on a
+`base::SingleThreadTaskRunner`.
+
+`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 Watcher](/mojo/public/c/system#Arming-a-Watcher) 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:
+
+``` cpp
+class PipeReader {
+ public:
+  PipeReader(mojo::ScopedMessagePipeHandle pipe)
+      : pipe_(std::move(pipe)),
+        watcher_(mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC) {
+    // NOTE: base::Unretained is safe because the callback can never be run
+    // after SimpleWatcher destruction.
+    watcher_.Watch(pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE,
+                   base::Bind(&PipeReader::OnReadable, base::Unretained(this)));
+  }
+
+  ~PipeReader() {}
+
+ private:
+  void OnReadable(MojoResult result) {
+    while (result == MOJO_RESULT_OK) {
+      mojo::ScopedMessageHandle message;
+      uint32_t num_bytes;
+      result = mojo::ReadMessageNew(pipe_.get(), &message, &num_bytes, nullptr,
+                                    nullptr, MOJO_READ_MESSAGE_FLAG_NONE);
+      DCHECK_EQ(result, MOJO_RESULT_OK);
+      messages_.emplace_back(std::move(message));
+    }
+  }
+
+  mojo::ScopedMessagePipeHandle pipe_;
+  mojo::SimpleWatcher watcher_;
+  std::vector<mojo::ScopedMessageHandle> messages_;
+};
+
+mojo::MessagePipe pipe;
+PipeReader reader(std::move(pipe.handle0));
+
+// Written messages will asynchronously end up in |reader.messages_|.
+WriteABunchOfStuff(pipe.handle1.get());
+```
+
+## Synchronous Waiting
+
+The C++ System API defines some utilities to block a calling thread while
+waiting for one or more handles to change signaling state in an interesting way.
+These threads combine usage of the [low-level Watcher API](/mojo/public/c/system#Signals-Watchers)
+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](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/wait.h)
+and [wait_set.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/wait_set.h)
+for a more detailed API reference.
+
+### Waiting On a Single Handle
+
+The `mojo::Wait` function simply blocks the calling thread until a given signal
+mask is either partially satisfied or fully unsatisfiable on a given handle.
+
+``` cpp
+mojo::MessagePipe pipe;
+mojo::WriteMessageRaw(pipe.handle0.get(), "hey", 3, nullptr, nullptr,
+                      MOJO_WRITE_MESSAGE_FLAG_NONE);
+MojoResult result = mojo::Wait(pipe.handle1.get(), MOJO_HANDLE_SIGNAL_READABLE);
+DCHECK_EQ(result, MOJO_RESULT_OK);
+
+// Guaranteed to succeed because we know |handle1| is readable now.
+mojo::ScopedMessageHandle message;
+uint32_t num_bytes;
+mojo::ReadMessageNew(pipe.handle1.get(), &num_bytes, nullptr, nullptr,
+                     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.
+
+``` cpp
+mojo::MessagePipe a, b;
+GoDoSomethingWithPipes(std:move(a.handle1), std::move(b.handle1));
+
+mojo::MessagePipeHandle handles[2] = {a.handle0.get(), b.handle0.get()};
+MojoHandleSignals signals[2] = {MOJO_HANDLE_SIGNAL_READABLE,
+                                MOJO_HANDLE_SIGNAL_READABLE};
+size_t ready_index;
+MojoResult result = mojo::WaitMany(handles, signals, 2, &ready_index);
+if (ready_index == 0) {
+  // a.handle0 was ready.
+} else {
+  // b.handle0 was ready.
+}
+```
+
+Similar to `mojo::Wait`, `mojo::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`](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/wait_set.h)
+is designed with these conditions in mind. A `WaitSet` maintains a persistent
+set of (not-owned) Mojo handles and `base::WaitableEvent`s, 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
+thread 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:
+
+``` cpp
+base::WaitableEvent timeout_event(
+    base::WaitableEvent::ResetPolicy::MANUAL,
+    base::WaitableEvent::InitialState::NOT_SIGNALED);
+mojo::MessagePipe a, b;
+
+GoDoStuffWithPipes(std::move(a.handle1), std::move(b.handle1));
+
+mojo::WaitSet wait_set;
+wait_set.AddHandle(a.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE);
+wait_set.AddHandle(b.handle0.get(), MOJO_HANDLE_SIGNAL_READABLE);
+wait_set.AddEvent(&timeout_event);
+
+// Ensure the Wait() lasts no more than 5 seconds.
+bg_thread->task_runner()->PostDelayedTask(
+    FROM_HERE,
+    base::Bind([](base::WaitableEvent* e) { e->Signal(); }, &timeout_event);
+    base::TimeDelta::FromSeconds(5));
+
+base::WaitableEvent* ready_event = nullptr;
+size_t num_ready_handles = 1;
+mojo::Handle ready_handle;
+MojoResult ready_result;
+wait_set.Wait(&ready_event, &num_ready_handles, &ready_handle, &ready_result);
+
+// The apex of thread-safety.
+bg_thread->Stop();
+
+if (ready_event) {
+  // The event signaled...
+}
+
+if (num_ready_handles > 0) {
+  // At least one of the handles signaled...
+  // NOTE: This and the above condition are not mutually exclusive. If handle
+  // signaling races with timeout, both things might be true.
+}
+```
diff --git a/mojo/public/java/bindings/README.md b/mojo/public/java/bindings/README.md
new file mode 100644
index 0000000..821a230e
--- /dev/null
+++ b/mojo/public/java/bindings/README.md
@@ -0,0 +1,12 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo Java Bindings API
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## Overview
+
+This document provides a brief guide to API usage with example code snippets.
+For a detailed API references please consult the class definitions in
+[this directory](https://cs.chromium.org/chromium/src/mojo/public/java/bindings/src/org/chromium/mojo/bindings/)
+
+TODO: Make the contents of this document less non-existent.
diff --git a/mojo/public/java/system/README.md b/mojo/public/java/system/README.md
new file mode 100644
index 0000000..3213e4c
--- /dev/null
+++ b/mojo/public/java/system/README.md
@@ -0,0 +1,25 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo Java System API
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## Overview
+
+This document provides a brief guide to Java Mojo bindings usage with example
+code snippets.
+
+For a detailed API references please consult the class definitions in
+[this directory](https://cs.chromium.org/chromium/src/mojo/public/java/system/src/org/chromium/mojo/system/).
+
+*TODO: Make the contents of this document less non-existent.*
+
+## Message Pipes
+
+## Data Pipes
+
+## Shared Buffers
+
+## Native Platform Handles (File Descriptors, Windows Handles, *etc.*)
+
+## Watchers
+
diff --git a/mojo/public/js/README.md b/mojo/public/js/README.md
new file mode 100644
index 0000000..b6eafe9c
--- /dev/null
+++ b/mojo/public/js/README.md
@@ -0,0 +1,7 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojo JavaScript System and Bindings APIs
+This document is a subset of the [Mojo documentation](/mojo).
+
+**NOTE:** The JavaScript APIs are currently in flux and will stabilize soon.
+More info forthcoming ASAP!
+
+TODO: Make the contents of this document less non-existent.
diff --git a/mojo/public/tools/bindings/README.md b/mojo/public/tools/bindings/README.md
new file mode 100644
index 0000000..737c7e6
--- /dev/null
+++ b/mojo/public/tools/bindings/README.md
@@ -0,0 +1,749 @@
+# ![Mojo Graphic](https://goo.gl/6CdlbH) Mojom IDL and Bindings Generator
+This document is a subset of the [Mojo documentation](/mojo).
+
+[TOC]
+
+## Overview
+
+Mojom is the IDL for Mojo bindings interfaces. Given a `.mojom` file, the
+[bindings generator](https://cs.chromium.org/chromium/src/mojo/public/tools/bindings)
+outputs bindings for all supported languages: **C++**, **JavaScript**, and
+**Java**.
+
+For a trivial example consider the following hypothetical Mojom file we write to
+`//services/widget/public/interfaces/frobinator.mojom`:
+
+```
+module widget.mojom;
+
+interface Frobinator {
+  Frobinate();
+};
+```
+
+This defines a single [interface](#Interfaces) named `Frobinator` in a
+[module](#Modules) named `widget.mojom` (and thus fully qualified in Mojom as
+`widget.mojom.Frobinator`.) Note that many interfaces and/or other types of
+definitions may be included in a single Mojom file.
+
+If we add a corresponding GN target to
+`//services/widget/public/interfaces/BUILD.gn`:
+
+```
+import("mojo/public/tools/bindings/mojom.gni")
+
+mojom("interfaces") {
+  sources = [
+    "frobinator.mojom",
+  ]
+}
+```
+
+and then build this target:
+
+```
+ninja -C out/r services/widget/public/interfaces
+```
+
+we'll find several generated sources in our output directory:
+
+```
+out/r/gen/services/widget/public/interfaces/frobinator.mojom.cc
+out/r/gen/services/widget/public/interfaces/frobinator.mojom.h
+out/r/gen/services/widget/public/interfaces/frobinator.mojom.js
+out/r/gen/services/widget/public/interfaces/frobinator.mojom.srcjar
+...
+```
+
+Each of these generated source modules includes a set of definitions
+representing the Mojom contents within the target language. For more details
+regarding the generated outputs please see
+[documentation for individual target languages](#Generated-Code-For-Target-Languages).
+
+## Mojom Syntax
+
+Mojom IDL allows developers to define **structs**, **unions**, **interfaces**,
+**constants**, and **enums**, all within the context of a **module**. These
+definitions are used to generate code in the supported target languages at build
+time.
+
+Mojom files may **import** other Mojom files in order to reference their
+definitions.
+
+### Primitive Types
+Mojom supports a few basic data types which may be composed into structs or used
+for message parameters.
+
+| Type                          | Description
+|-------------------------------|-------------------------------------------------------|
+| `bool`                        | Boolean type (`true` or `false`.)
+| `int8`, `uint8`               | Signed or unsigned 8-bit integer.
+| `int16`, `uint16`             | Signed or unsigned 16-bit integer.
+| `int32`, `uint32`             | Signed or unsigned 32-bit integer.
+| `int64`, `uint64`             | Signed or unsigned 64-bit integer.
+| `float`, `double`             | 32- or 64-bit floating point number.
+| `string`                      | UTF-8 encoded string.
+| `array<T>`                    | Array of any Mojom type *T*; for example, `array<uint8>` or `array<array<string>>`.
+| `array<T, N>`                 | Fixed-length array of any Mojom type *T*. The parameter *N* must be an integral constant.
+| `map<S, T>`                   | Associated array maping values of type *S* to values of type *T*. *S* may be a `string`, `enum`, or numeric type.
+| `handle`                      | Generic Mojo handle. May be any type of handle, including a wrapped native platform handle.
+| `handle<message_pipe>`        | Generic message pipe handle.
+| `handle<shared_buffer>`       | Shared buffer handle.
+| `handle<data_pipe_producer>`  | Data pipe producer handle.
+| `handle<data_pipe_consumer>`  | Data pipe consumer handle.
+| *`InterfaceType`*             | Any user-defined Mojom interface type. This is sugar for a strongly-typed message pipe handle which should eventually be used to make outgoing calls on the interface.
+| *`InterfaceType&`*            | An interface request for any user-defined Mojom interface type. This is sugar for a more strongly-typed message pipe handle which is expected to receive request messages and should therefore eventually be bound to an implementation of the interface.
+| *`associated InterfaceType`*  | An associated interface handle. See [Associated Interfaces](#Associated-Interfaces)
+| *`associated InterfaceType&`* | An associated interface request. See [Associated Interfaces](#Associated-Interfaces)
+| *T*?                          | An optional (nullable) value. Primitive numeric types (integers, floats, booleans, and enums) are not nullable. All other types are nullable.
+
+### Modules
+
+Every Mojom file may optionally specify a single **module** to which it belongs.
+
+This is used strictly for aggregaging all defined symbols therein within a
+common Mojom namespace. The specific impact this has on generated binidngs code
+varies for each target language. For example, if the following Mojom is used to
+generate bindings:
+
+```
+module business.stuff;
+
+interface MoneyGenerator {
+  GenerateMoney();
+};
+```
+
+Generated C++ bindings will define a class interface `MoneyGenerator` in the
+`business::stuff` namespace, while Java bindings will define an interface
+`MoneyGenerator` in the `org.chromium.business.stuff` package. JavaScript
+bindings at this time are unaffected by module declarations.
+
+**NOTE:** By convention in the Chromium codebase, **all** Mojom files should
+declare a module name with at least (and preferrably exactly) one top-level name
+as well as an inner `mojom` module suffix. *e.g.*, `chrome.mojom`,
+`business.mojom`, *etc.*
+
+This convention makes it easy to tell which symbols are generated by Mojom when
+reading non-Mojom code, and it also avoids namespace collisions in the fairly
+common scenario where you have a real C++ or Java `Foo` along with a
+corresponding Mojom `Foo` for its serialized representation.
+
+### Imports
+
+If your Mojom references definitions from other Mojom files, you must **import**
+those files. Import syntax is as follows:
+
+```
+import "services/widget/public/interfaces/frobinator.mojom";
+```
+
+Import paths are always relative to the top-level directory.
+
+Note that circular imports are **not** supported.
+
+### Structs
+
+Structs are defined using the **struct** keyword, and they provide a way to
+group related fields together:
+
+``` cpp
+struct StringPair {
+  string first;
+  string second;
+};
+```
+
+Struct fields may be comprised of any of the types listed above in the
+[Primitive Types](#Primitive-Types) section.
+
+Default values may be specified as long as they are constant:
+
+``` cpp
+struct Request {
+  int32 id = -1;
+  string details;
+};
+```
+
+What follows is a fairly
+comprehensive example using the supported field types:
+
+``` cpp
+struct StringPair {
+  string first;
+  string second;
+};
+
+enum AnEnum {
+  YES,
+  NO
+};
+
+interface SampleInterface {
+  DoStuff();
+};
+
+struct AllTheThings {
+  // Note that these types can never be marked nullable!
+  bool boolean_value;
+  int8 signed_8bit_value = 42;
+  uint8 unsigned_8bit_value;
+  int16 signed_16bit_value;
+  uint16 unsigned_16bit_value;
+  int32 signed_32bit_value;
+  uint32 unsigned_32bit_value;
+  int64 signed_64bit_value;
+  uint64 unsigned_64bit_value;
+  float float_value_32bit;
+  double float_value_64bit;
+  AnEnum enum_value = AnEnum.YES;
+
+  // Strings may be nullable.
+  string? maybe_a_string_maybe_not;
+
+  // Structs may contain other structs. These may also be nullable.
+  StringPair some_strings;
+  StringPair? maybe_some_more_strings;
+
+  // In fact structs can also be nested, though in practice you must always make
+  // such fields nullable -- otherwise messages would need to be infinitely long
+  // in order to pass validation!
+  AllTheThings? more_things;
+
+  // Arrays may be templated over any Mojom type, and are always nullable:
+  array<int32> numbers;
+  array<int32>? maybe_more_numbers;
+
+  // Arrays of arrays of arrays... are fine.
+  array<array<array<AnEnum>>> this_works_but_really_plz_stop;
+
+  // The element type may be nullable if it's a type which is allowed to be
+  // nullable.
+  array<AllTheThings?> more_maybe_things;
+
+  // Fixed-size arrays get some extra validation on the receiving end to ensure
+  // that the correct number of elements is always received.
+  array<uint64, 2> uuid;
+
+  // Maps follow many of the same rules as arrays. Key types may be any
+  // non-handle, non-collection type, and value types may be any supported
+  // struct field type. Maps may also be nullable.
+  map<string, int32> one_map;
+  map<AnEnum, string>? maybe_another_map;
+  map<StringPair, AllTheThings?>? maybe_a_pretty_weird_but_valid_map;
+  map<StringPair, map<int32, array<map<string, string>?>?>?> ridiculous;
+
+  // And finally, all handle types are valid as struct fields and may be
+  // nullable. Note that interfaces and interface requests (the "Foo" and
+  // "Foo&" type syntax respectively) are just strongly-typed message pipe
+  // handles.
+  handle generic_handle;
+  handle<data_pipe_consumer> reader;
+  handle<data_pipe_producer>? maybe_writer;
+  handle<shared_buffer> dumping_ground;
+  handle<message_pipe> raw_message_pipe;
+  SampleInterface? maybe_a_sample_interface_client_pipe;
+  SampleInterface& non_nullable_sample_interface_request;
+  SampleInterface&? nullable_sample_interface_request;
+  associated SampleInterface associated_interface_client;
+  associated SampleInterface& associated_interface_request;
+  assocaited SampleInterface&? maybe_another_associated_request;
+};
+```
+
+For details on how all of these different types translate to usable generated
+code, see
+[documentation for individual target languages](#Generated-Code-For-Target-Languages).
+
+### Enumeration Types
+
+Enumeration types may be defined using the **enum** keyword either directly
+within a module or within the namespace of some struct or interface:
+
+```
+module business.mojom;
+
+enum Department {
+  SALES = 0,
+  DEV,
+};
+
+struct Employee {
+  enum Type {
+    FULL_TIME,
+    PART_TIME,
+  };
+
+  Type type;
+  // ...
+};
+```
+
+That that similar to C-style enums, individual values may be explicitly assigned
+within an enum definition. By default values are based at zero and incremenet by
+1 sequentially.
+
+The effect of nested definitions on generated bindings varies depending on the
+target language. See [documentation for individual target languages](#Generated-Code-For-Target-Languages)
+
+### Constants
+
+Constants may be defined using the **const** keyword either directly within a
+module or within the namespace of some struct or interface:
+
+```
+module business.mojom;
+
+const string kServiceName = "business";
+
+struct Employee {
+  const uint64 kInvalidId = 0;
+
+  enum Type {
+    FULL_TIME,
+    PART_TIME,
+  };
+
+  uint64 id = kInvalidId;
+  Type type;
+};
+```
+
+The effect of nested definitions on generated bindings varies depending on the
+target language. See [documentation for individual target languages](#Generated-Code-For-Target-Languages)
+
+### Interfaces
+
+An **interface** is a logical bundle of parameterized request messages. Each
+request message may optionally define a parameterized response message. Here's
+syntax to define an interface `Foo` with various kinds of requests:
+
+```
+interface Foo {
+  // A request which takes no arguments and expects no response.
+  MyMessage();
+
+  // A request which has some arguments and expects no response.
+  MyOtherMessage(string name, array<uint8> bytes);
+
+  // A request which expects a single-argument response.
+  MyMessageWithResponse(string command) => (bool success);
+
+  // A request which expects a response with multiple arguments.
+  MyMessageWithMoarResponse(string a, string b) => (int8 c, int8 d);
+};
+```
+
+Anything which is a valid struct field type (see [Structs](#Structs)) is also a
+valid request or response argument type. The type notation is the same for both.
+
+### Attributes
+
+Mojom definitions may have their meaning altered by **attributes**, specified
+with a syntax similar to Java or C# attributes. There are a handle of
+interesting attributes supported today.
+
+**`[Sync]`**
+:   The `Sync` attribute may be specified for any interface method which expects
+    a response. This makes it so that callers of the method can wait
+    synchronously for a response. See
+    [Synchronous Calls](/mojo/public/cpp/bindings#Synchronous-Calls) in the C++
+    bindings documentation. Note that sync calls are not currently supported in
+    other target languages.
+
+**`[Extensible]`**
+:   The `Extensible` attribute may be specified for any enum definition. This
+    essentially disables builtin range validation when receiving values of the
+    enum type in a message, allowing older bindings to tolerate unrecognized
+    values from newer versions of the enum.
+
+**`[Native]`**
+:   The `Native` attribute may be specified for an empty struct declaration to
+    provide a nominal bridge between Mojo IPC and legacy `IPC::ParamTraits` or
+    `IPC_STRUCT_TRAITS*` macros.
+    See [Using Legacy IPC Traits](/ipc#Using-Legacy-IPC-Traits) for more
+    details. Note support for this attribute is strictly limited to C++ bindings
+    generation.
+
+**`[MinVersion=N]`**
+:   The `MinVersion` attribute is used to specify the version at which a given
+    field, enum value, interface method, or method parameter was introduced.
+    See [Versioning](#Versioning) for more details.
+
+## Generated Code For Target Languages
+
+When the bindings generator successfully processes an input Mojom file, it emits
+corresponding code for each supported target language. For more details on how
+Mojom concepts translate to a given target langauge, please refer to the
+bindings API documentation for that language:
+
+* [C++ Bindings](/mojo/public/cpp/bindings)
+* [JavaScript Bindings](/mojo/public/js)
+* [Java Bindings](/mojo/public/java/bindings)
+
+## Message Validation
+
+Regardless of target language, all interface messages are validated during
+deserialization before they are dispatched to a receiving implementation of the
+interface. This helps to ensure consitent validation across interfaces without
+leaving the burden to developers and security reviewers every time a new message
+is added.
+
+If a message fails validation, it is never dispatched. Instead a **connection
+error** is raised on the binding object (see
+[C++ Connection Errors](/mojo/public/cpp/bindings#Connection-Errors),
+[Java Connection Errors](/mojo/public/java/bindings#Connection-Errors), or
+[JavaScript Connection Errors](/mojo/public/js#Connection-Errors) for details.)
+
+Some baseline level of validation is done automatically for primitive Mojom
+types.
+
+### Non-Nullable Objects
+
+Mojom fields or parameter values (*e.g.*, structs, interfaces, arrays, *etc.*)
+may be marked nullable in Mojom definitions (see
+[Primitive Types](#Primitive-Types).) If a field or parameter is **not** marked
+nullable but a message is received with a null value in its place, that message
+will fail validation.
+
+### Enums
+
+Enums declared in Mojom are automatically validated against the range of legal
+values. For example if a Mojom declares the enum:
+
+``` cpp
+enum AdvancedBoolean {
+  TRUE = 0,
+  FALSE = 1,
+  FILE_NOT_FOUND = 2,
+};
+```
+
+and a message is received with the integral value 3 (or anything other than 0,
+1, or 2) in place of some `AdvancedBoolean` field or parameter, the message will
+fail validation.
+
+*** note
+NOTE: It's possible to avoid this type of validation error by explicitly marking
+an enum as [Extensible](#Attributes) if you anticipate your enum being exchanged
+between two different versions of the binding interface. See
+[Versioning](#Versioning).
+***
+
+### Other failures
+
+There are a  host of internal validation errors that may occur when a malformed
+message is received, but developers should not be concerned with these
+specifically; in general they can only result from internal bindings bugs,
+compromised processes, or some remote endpoint making a dubious effort to
+manually encode their own bindings messages.
+
+### Custom Validation
+
+It's also possible for developers to define custom validation logic for specific
+Mojom struct types by exploiting the
+[type mapping](/mojo/public/cpp/bindings#Type-Mapping) system for C++ bindings.
+Messages rejected by custom validation logic trigger the same validation failure
+behavior as the built-in type validation routines.
+
+## Associated Interfaces
+
+As mentioned in the [Primitive Types](#Primitive-Types) section above, interface
+and interface request fields and parameters may be marked as `associated`. This
+essentially means that they are piggy-backed on some other interface's message
+pipe.
+
+Because individual interface message pipes operate independently there can be no
+relative ordering guarantees among them. Associated interfaces are useful when
+one interface needs to guarantee strict FIFO ordering with respect to one or
+more other interfaces, as they allow interfaces to share a single pipe.
+
+Currenly associated interfaces are only supported in generated C++ bindings.
+See the documentation for
+[C++ Associated Interfaces](/mojo/public/cpp/bindings#Associated-Interfaces).
+
+## Versioning
+
+### Overview
+
+*** note
+**NOTE:** You don't need to worry about versioning if you don't care about
+backwards compatibility. Specifically, all parts of Chrome are updated
+atomically today and there is not yet any possibility of any two Chrome
+processes communicating with two different versions of any given Mojom
+interface.
+***
+
+Services extend their interfaces to support new features over time, and clients
+want to use those new features when they are available. If services and clients
+are not updated at the same time, it's important for them to be able to
+communicate with each other using different snapshots (versions) of their
+interfaces.
+
+This document shows how to extend Mojom interfaces in a backwards-compatible
+way. Changing interfaces in a non-backwards-compatible way is not discussed,
+because in that case communication between different interface versions is
+impossible anyway.
+
+### Versioned Structs
+
+You can use the `MinVersion` [attribute](#Attributes) to indicate from which
+version a struct field is introduced. Assume you have the following struct:
+
+``` cpp
+struct Employee {
+  uint64 employee_id;
+  string name;
+};
+```
+
+and you would like to add a birthday field. You can do:
+
+``` cpp
+struct Employee {
+  uint64 employee_id;
+  string name;
+  [MinVersion=1] Date? birthday;
+};
+```
+
+By default, fields belong to version 0. New fields must be appended to the
+struct definition (*i.e*., existing fields must not change **ordinal value**)
+with the `MinVersion` attribute set to a number greater than any previous
+existing versions.
+
+**Ordinal value** refers to the relative positional layout of a struct's fields
+(and an interface's methods) when encoded in a message. Implicitly, ordinal
+numbers are assigned to fields according to lexical position. In the example
+above, `employee_id` has an ordinal value of 0 and `name` has an ordinal value
+of 1.
+
+Ordinal values can be specified explicitly using `**@**` notation, subject to
+the following hard constraints:
+
+* For any given struct or interface, if any field or method explicitly specifies
+    an ordinal value, all fields or methods must explicitly specify an ordinal
+    value.
+* For an *N*-field struct or *N*-method interface, the set of explicitly
+    assigned ordinal values must be limited to the range *[0, N-1]*.
+
+You may reorder fields, but you must ensure that the ordinal values of existing
+fields remain unchanged. For example, the following struct remains
+backwards-compatible:
+
+``` cpp
+struct Employee {
+  uint64 employee_id@0;
+  [MinVersion=1] Date? birthday@2;
+  string name@1;
+};
+```
+
+*** note
+**NOTE:** Newly added fields of Mojo object or handle types MUST be nullable.
+See [Primitive Types](#Primitive-Types).
+***
+
+### Versioned Interfaces
+
+There are two dimensions on which an interface can be extended
+
+**Appending New Parameters To Existing Methods**
+:   Parameter lists are treated as structs internally, so all the rules of
+    versioned structs apply to method parameter lists. The only difference is
+    that the version number is scoped to the whole interface rather than to any
+    individual parameter list.
+
+    Please note that adding a response to a message which did not previously
+    expect a response is a not a backwards-compatible change.
+
+**Appending New Methods**
+:   Similarly, you can reorder methods with explicit ordinal values as long as
+    the ordinal values of existing methods are unchanged.
+
+For example:
+
+``` cpp
+// Old version:
+interface HumanResourceDatabase {
+  AddEmployee(Employee employee) => (bool success);
+  QueryEmployee(uint64 id) => (Employee? employee);
+};
+
+// New version:
+interface HumanResourceDatabase {
+  AddEmployee(Employee employee) => (bool success);
+
+  QueryEmployee(uint64 id, [MinVersion=1] bool retrieve_finger_print)
+      => (Employee? employee,
+          [MinVersion=1] array<uint8>? finger_print);
+
+  [MinVersion=1]
+  AttachFingerPrint(uint64 id, array<uint8> finger_print)
+      => (bool success);
+};
+```
+
+Similar to [versioned structs](#Versioned-Structs), when you pass the parameter
+list of a request or response method to a destination using an older version of
+an interface, unrecognized fields are silently discarded. However, if the method
+call itself is not recognized, it is considered a validation error and the
+receiver will close its end of the interface pipe. For example, if a client on
+version 1 of the above interface sends an `AttachFingerPrint` request to an
+implementation of version 0, the client will be disconnected.
+
+Bindings target languages that support versioning expose means to query or
+assert the remote version from a client handle (*e.g.*, an
+`InterfacePtr<T>` in C++ bindings.)
+
+See
+[C++ Versioning Considerations](/mojo/public/cpp/bindings#Versioning-Considerations)
+and [Java Versioning Considerations](/mojo/public/java/bindings#Versioning-Considerations)
+
+### Versioned Enums
+
+**By default, enums are non-extensible**, which means that generated message
+validation code does not expect to see new values in the future. When an unknown
+value is seen for a non-extensible enum field or parameter, a validation error
+is raised.
+
+If you want an enum to be extensible in the future, you can apply the
+`[Extensible]` [attribute](#Attributes):
+
+``` cpp
+[Extensible]
+enum Department {
+  SALES,
+  DEV,
+};
+```
+
+And later you can extend this enum without breaking backwards compatibility:
+
+``` cpp
+[Extensible]
+enum Department {
+  SALES,
+  DEV,
+  [MinVersion=1] RESEARCH,
+};
+```
+
+*** note
+**NOTE:** For versioned enum definitions, the use of a `[MinVersion]` attribute
+is strictly for documentation purposes. It has no impact on the generated code.
+***
+
+With extensible enums, bound interface implementations may receive unknown enum
+values and will need to deal with them gracefully. See
+[C++ Versioning Considerations](/mojo/public/cpp/bindings#Versioning-Considerations)
+for details.
+
+## Grammar Reference
+
+Below is the (BNF-ish) context-free grammar of the Mojom language:
+
+```
+MojomFile = StatementList
+StatementList = Statement StatementList | Statement
+Statement = ModuleStatement | ImportStatement | Definition
+
+ModuleStatement = AttributeSection "module" Identifier ";"
+ImportStatement = "import" StringLiteral ";"
+Definition = Struct Union Interface Enum Const
+
+AttributeSection = "[" AttributeList "]"
+AttributeList = <empty> | NonEmptyAttributeList
+NonEmptyAttributeList = Attribute
+                      | Attribute "," NonEmptyAttributeList
+Attribute = Name
+          | Name "=" Name
+          | Name "=" Literal
+
+Struct = AttributeSection "struct" Name "{" StructBody "}" ";"
+       | AttributeSection "struct" Name ";"
+StructBody = <empty>
+           | StructBody Const
+           | StructBody Enum
+           | StructBody StructField
+StructField = AttributeSection TypeSpec Name Orginal Default ";"
+
+Union = AttributeSection "union" Name "{" UnionBody "}" ";"
+UnionBody = <empty> | UnionBody UnionField
+UnionField = AttributeSection TypeSpec Name Ordinal ";"
+
+Interface = AttributeSection "interface" Name "{" InterfaceBody "}" ";"
+InterfaceBody = <empty>
+              | InterfaceBody Const
+              | InterfaceBody Enum
+              | InterfaceBody Method
+Method = AttributeSection Name Ordinal "(" ParamterList ")" Response ";"
+ParameterList = <empty> | NonEmptyParameterList
+NonEmptyParameterList = Parameter
+                      | Parameter "," NonEmptyParameterList
+Parameter = AttributeSection TypeSpec Name Ordinal
+Response = <empty> | "=>" "(" ParameterList ")"
+
+TypeSpec = TypeName "?" | TypeName
+TypeName = BasicTypeName
+         | Array
+         | FixedArray
+         | Map
+         | InterfaceRequest
+BasicTypeName = Identifier | "associated" Identifier | HandleType | NumericType
+NumericType = "bool" | "int8" | "uint8" | "int16" | "uint16" | "int32"
+            | "uint32" | "int64" | "uint64" | "float" | "double"
+HandleType = "handle" | "handle" "<" SpecificHandleType ">"
+SpecificHandleType = "message_pipe"
+                   | "shared_buffer"
+                   | "data_pipe_consumer"
+                   | "data_pipe_producer"
+Array = "array" "<" TypeSpec ">"
+FixedArray = "array" "<" TypeSpec "," IntConstDec ">"
+Map = "map" "<" Identifier "," TypeSpec ">"
+InterfaceRequest = Identifier "&" | "associated" Identifier "&"
+
+Ordinal = <empty> | OrdinalValue
+
+Default = <empty> | "=" Constant
+
+Enum = AttributeSection "enum" Name "{" NonEmptyEnumValueList "}" ";"
+     | AttributeSection "enum" Name "{" NonEmptyEnumValueList "," "}" ";"
+NonEmptyEnumValueList = EnumValue | NonEmptyEnumValueList "," EnumValue
+EnumValue = AttributeSection Name
+          | AttributeSection Name "=" Integer
+          | AttributeSection Name "=" Identifier
+
+Const = "const" TypeSpec Name "=" Constant ";"
+
+Constant = Literal | Identifier ";"
+
+Identifier = Name | Name "." Identifier
+
+Literal = Integer | Float | "true" | "false" | "default" | StringLiteral
+
+Integer = IntConst | "+" IntConst | "-" IntConst
+IntConst = IntConstDec | IntConstHex
+
+Float = FloatConst | "+" FloatConst | "-" FloatConst
+
+; The rules below are for tokens matched strictly according to the given regexes
+
+Identifier = /[a-zA-Z_][0-9a-zA-Z_]*/
+IntConstDec = /0|(1-9[0-9]*)/
+IntConstHex = /0[xX][0-9a-fA-F]+/
+OrdinalValue = /@(0|(1-9[0-9]*))/
+FloatConst = ... # Imagine it's close enough to C-style float syntax.
+StringLiteral = ... # Imagine it's close enough to C-style string literals, including escapes.
+```
+
+## Additional Documentation
+
+[Mojom Message Format](https://docs.google.com/document/d/13pv9cFh5YKuBggDBQ1-AL8VReF-IYpFOFpRfvWFrwio/edit)
+:    Describes the wire format used by Mojo bindings interfaces over message
+     pipes.
+
+[Input Format of Mojom Message Validation Tests](https://docs.google.com/document/d/1-y-2IYctyX2NPaLxJjpJfzVNWCC2SR2MJAD9MpIytHQ/edit)
+:    Describes a text format used to facilitate bindings message validation
+     tests.