Import Cobalt 24.master.0.1032472
diff --git a/.github/actions/on_host_test/action.yaml b/.github/actions/on_host_test/action.yaml
index a10a8bf..7df5e2f 100644
--- a/.github/actions/on_host_test/action.yaml
+++ b/.github/actions/on_host_test/action.yaml
@@ -60,11 +60,16 @@
       run: |
         echo "PYTHONPATH=$GITHUB_WORKSPACE" >> $GITHUB_ENV
         echo "TEST_RESULTS_DIR=${GITHUB_WORKSPACE}/unit-test-results" >> $GITHUB_ENV
+        echo "COVERAGE_DIR=${GITHUB_WORKSPACE}/coverage" >> $GITHUB_ENV
         echo "TEST_REPORT_FILE=${GITHUB_WORKSPACE}/${{matrix.platform}}-${{matrix.shard}}" >> $GITHUB_ENV
     - name: Run Tests
       shell: bash
       run: |
         set -x
+        # Starboard toolchains are downloaded to a different dir on github. Create a symlink to reassure our tooling that everything is fine.
+        if [ -d /root/starboard-toolchains ]; then
+          ln -s /root/starboard-toolchains /github/home/starboard-toolchains
+        fi
         loader_args=''
         if [ "${COBALT_BOOTLOADER}" != "null" ]; then
           loader_args="--loader_platform ${COBALT_BOOTLOADER} --loader_config ${{matrix.config}}"
@@ -77,6 +82,10 @@
           xvfb-run -a --server-args="-screen 0 1920x1080x24i +render +extension GLX -noreset" python3 $GITHUB_WORKSPACE/cobalt/black_box_tests/black_box_tests.py --platform ${{matrix.target_platform}} --config ${{matrix.config}} ${loader_args} --test_set wpt
         elif [[ "${{matrix.shard}}" == 'evergreen' ]]; then
           xvfb-run -a --server-args="-screen 0 1920x1080x24i +render +extension GLX -noreset" python3 $GITHUB_WORKSPACE/cobalt/evergreen_tests/evergreen_tests.py --platform ${{matrix.target_platform}} --config ${{matrix.config}} ${loader_args} --no-can_mount_tmpfs
+        elif [[ "${{matrix.shard}}" == 'evergreen-as-blackbox' ]]; then
+          xvfb-run -a --server-args="-screen 0 1920x1080x24i +render +extension GLX -noreset" python3 $GITHUB_WORKSPACE/cobalt/black_box_tests/black_box_tests.py --platform ${{matrix.target_platform}} --config ${{matrix.config}} ${loader_args} --test_set evergreen
+        elif [[ "${{matrix.shard}}" == 'coverage' ]]; then
+          xvfb-run -a --server-args="-screen 0 1920x1080x24i +render +extension GLX -noreset" python3 ${GITHUB_WORKSPACE}/starboard/tools/testing/test_runner.py --platform ${{matrix.target_platform}} --config ${{matrix.config}} -r ${loader_args} --xml_output_dir=${TEST_RESULTS_DIR} --coverage_dir=${COVERAGE_DIR} --coverage_report
         else
           if [[ "${{inputs.os}}" == 'windows' ]]; then
             python3 ${GITHUB_WORKSPACE}/starboard/tools/testing/test_runner.py --platform ${{matrix.target_platform}} --config ${{matrix.config}} -s ${{matrix.shard}} -r
@@ -97,3 +106,14 @@
       with:
         name: unit-test-reports
         path: ${{env.TEST_REPORT_FILE}}
+    - name: Upload coverage html report
+      if: success() && matrix.shard == 'coverage'
+      uses: actions/upload-artifact@v3
+      with:
+        name: coverage-report
+        path: ${{env.COVERAGE_DIR}}/html
+    - name: Upload to Codecov
+      if: success() && matrix.shard == 'coverage'
+      uses: codecov/codecov-action@v3
+      with:
+        files: ${{env.COVERAGE_DIR}}/report.txt
diff --git a/.github/config/evergreen-x64.json b/.github/config/evergreen-x64.json
index f3171ec..cd33d24 100644
--- a/.github/config/evergreen-x64.json
+++ b/.github/config/evergreen-x64.json
@@ -2,7 +2,16 @@
   "docker_service": "build-linux-evergreen",
   "on_host_test": true,
   "bootloader": "linux-x64x11",
-  "on_host_test_shards": ["0", "1", "2", "3", "blackbox", "wpt", "evergreen"],
+  "on_host_test_shards": [
+    "0",
+    "1",
+    "2",
+    "3",
+    "blackbox",
+    "wpt",
+    "evergreen",
+    "evergreen-as-blackbox"
+  ],
   "platforms": [
     "evergreen-x64",
     "evergreen-x64-sbversion-15",
diff --git a/.github/config/linux-coverage.json b/.github/config/linux-coverage.json
new file mode 100644
index 0000000..f4c9006
--- /dev/null
+++ b/.github/config/linux-coverage.json
@@ -0,0 +1,16 @@
+{
+  "docker_service": "build-linux",
+  "on_host_test": true,
+  "on_host_test_shards": ["coverage"],
+  "platforms": [
+    "linux-coverage"
+  ],
+  "includes": [
+    {
+      "name":"linux",
+      "platform":"linux-coverage",
+      "target_platform":"linux-x64x11",
+      "extra_gn_arguments":"use_clang_coverage=true"
+    }
+  ]
+}
diff --git a/.github/config/linux-modular.json b/.github/config/linux-modular.json
new file mode 100644
index 0000000..ee3f9b1
--- /dev/null
+++ b/.github/config/linux-modular.json
@@ -0,0 +1,16 @@
+{
+  "docker_service": "build-linux",
+  "on_host_test": true,
+  "on_host_test_shards": ["0", "1", "2", "3", "wpt"],
+  "platforms": [
+    "linux-x64x11-modular"
+  ],
+  "includes": [
+    {
+      "name":"modular",
+      "platform":"linux-x64x11-modular",
+      "target_platform":"linux-x64x11",
+      "extra_gn_arguments":"build_with_separate_cobalt_toolchain=true"
+    }
+  ]
+}
diff --git a/.github/workflows/android.yaml b/.github/workflows/android.yaml
index f94dc7e..4622201 100644
--- a/.github/workflows/android.yaml
+++ b/.github/workflows/android.yaml
@@ -2,7 +2,7 @@
 
 on:
   pull_request:
-    types: [ready_for_review, opened, reopened, synchronize, labeled]
+    types: [opened, reopened, synchronize, labeled]
     branches:
       - main
       - feature/*
diff --git a/.github/workflows/evergreen.yaml b/.github/workflows/evergreen.yaml
index ef12fdf..22e56e4 100644
--- a/.github/workflows/evergreen.yaml
+++ b/.github/workflows/evergreen.yaml
@@ -2,7 +2,7 @@
 
 on:
   pull_request:
-    types: [ready_for_review, opened, reopened, synchronize, labeled]
+    types: [opened, reopened, synchronize, labeled]
     branches:
       - main
       - feature/*
diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml
index cf18341..e15041d 100644
--- a/.github/workflows/linux.yaml
+++ b/.github/workflows/linux.yaml
@@ -2,7 +2,7 @@
 
 on:
   pull_request:
-    types: [ready_for_review, opened, reopened, synchronize, labeled]
+    types: [opened, reopened, synchronize, labeled]
     branches:
       - main
       - feature/*
@@ -46,3 +46,27 @@
     with:
       platform: linux-gcc-6-3
       nightly: ${{ github.event.inputs.nightly }}
+  # TODO(b/285632780): Enable blackbox tests for modular linux workflows.
+  linux-modular:
+    uses: ./.github/workflows/main.yaml
+    permissions:
+      packages: write
+      pull-requests: write
+    with:
+      platform: linux-modular
+      nightly: ${{ github.event.inputs.nightly }}
+      modular: true
+  linux-coverage:
+    # Run on main branch for pushes, PRs and manual invocations.
+    if: |
+     ${{ github.ref == 'refs/heads/main' &&
+         (github.event_name == 'push' ||
+         github.event_name == 'pull_request' ||
+         (github.event_name == 'workflow_dispatch' && inputs.nightly == 'false')) }}
+    uses: ./.github/workflows/main.yaml
+    permissions:
+      packages: write
+      pull-requests: write
+    with:
+      platform: linux-coverage
+      nightly: ${{ github.event.inputs.nightly }}
diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml
index d187bb5..b501c1d 100644
--- a/.github/workflows/main.yaml
+++ b/.github/workflows/main.yaml
@@ -24,6 +24,11 @@
         required: false
         type: string
         default: ""
+      modular:
+        description: 'Whether this is a modular build.'
+        required: false
+        type: boolean
+        default: false
 
 # Global env vars.
 env:
@@ -56,15 +61,12 @@
       GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
       GITHUB_PR_REPO_URL: ${{ github.event.pull_request.base.repo.url }}
       GITHUB_EVENT_NUMBER: ${{ github.event.number }}
-    # All triggers except draft PRs, unless PR is labeled with runtest
     if: |
-      github.event_name != 'pull_request' ||
+      github.event.action != 'labeled' ||
       (
-        github.event.pull_request.draft == false ||
-        (
-          github.event.action == 'labeled' &&
-          github.event.label.name == 'runtest'
-        )
+        github.event.action == 'labeled' &&
+        github.event.label.name == 'runtest' ||
+        github.event.label.name == 'on_device'
       )
     steps:
       - id: checkout
@@ -250,7 +252,7 @@
           type: ondevice
           os: linux
 
-  # Runs on-host integration and unit tests.
+  # Runs on-device integration and unit tests.
   on-device-test:
     needs: [initialize, build]
     # Run ODT when on_device label is applied on PR.
@@ -276,6 +278,7 @@
     env:
       COBALT_BOOTLOADER: ${{ needs.initialize.outputs.bootloader }}
       ON_DEVICE_TEST_ATTEMPTS: ${{ needs.initialize.outputs.on_device_test_attempts }}
+      MODULAR_BUILD: ${{ inputs.modular && 1 || 0 }}
     steps:
       - name: Checkout
         uses: kaidokert/checkout@v3.5.999
@@ -306,6 +309,7 @@
       # with permission denied error.
       HOME: /root
       COBALT_BOOTLOADER: ${{needs.initialize.outputs.bootloader}}
+      MODULAR_BUILD: ${{ inputs.modular && 1 || 0 }}
     steps:
       - name: Checkout
         uses: kaidokert/checkout@v3.5.999
diff --git a/.github/workflows/main_win.yaml b/.github/workflows/main_win.yaml
index 4827f3d..3285f1a 100644
--- a/.github/workflows/main_win.yaml
+++ b/.github/workflows/main_win.yaml
@@ -14,6 +14,11 @@
         required: true
         type: string
         default: 'false'
+      modular:
+        description: 'Whether this is a modular build.'
+        required: false
+        type: boolean
+        default: false
 
 # Global env vars.
 env:
@@ -49,13 +54,10 @@
       GITHUB_EVENT_NUMBER: ${{ github.event.number }}
     # All triggers except draft PRs, unless PR is labeled with runtest
     if: |
-      github.event_name != 'pull_request' ||
+      github.event.action != 'labeled' ||
       (
-        github.event.pull_request.draft == false ||
-        (
-          github.event.action == 'labeled' &&
-          github.event.label.name == 'runtest'
-        )
+        github.event.action == 'labeled' &&
+        github.event.label.name == 'runtest'
       )
     steps:
       - id: Checkout
@@ -171,6 +173,8 @@
         shard: ${{ fromJson(needs.initialize.outputs.on_host_test_shards) }}
         config: [devel]
         include: ${{ fromJson(needs.initialize.outputs.includes) }}
+    env:
+      MODULAR_BUILD: ${{ inputs.modular && 1 || 0 }}
     steps:
       - name: Checkout
         uses: kaidokert/checkout@v3.5.999
diff --git a/.github/workflows/raspi-2.yaml b/.github/workflows/raspi-2.yaml
index 62d0708..ac42ac8 100644
--- a/.github/workflows/raspi-2.yaml
+++ b/.github/workflows/raspi-2.yaml
@@ -2,7 +2,7 @@
 
 on:
   pull_request:
-    types: [ready_for_review, opened, reopened, synchronize, labeled]
+    types: [opened, reopened, synchronize, labeled]
     branches:
       - main
       - feature/*
diff --git a/.github/workflows/stub.yaml b/.github/workflows/stub.yaml
index c105a59..8c40a4e 100644
--- a/.github/workflows/stub.yaml
+++ b/.github/workflows/stub.yaml
@@ -2,7 +2,7 @@
 
 on:
   pull_request:
-    types: [ready_for_review, opened, reopened, synchronize, labeled]
+    types: [opened, reopened, synchronize, labeled]
     branches:
       - main
       - feature/*
diff --git a/.github/workflows/win32.yaml b/.github/workflows/win32.yaml
index 449a9d2..b522992 100644
--- a/.github/workflows/win32.yaml
+++ b/.github/workflows/win32.yaml
@@ -2,7 +2,7 @@
 
 on:
   pull_request:
-    types: [ready_for_review, opened, reopened, synchronize, labeled]
+    types: [opened, reopened, synchronize, labeled]
     branches:
       - main
       - feature/*
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 332d6ab..9b82749 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,64 +1,95 @@
-# Contributing to Cobalt
+# Contributing guidelines
 
-We'd love to hear about how you would like to contribute to Cobalt! It's worth
-reading through this modest document first, to understand the process and to
-make sure you know what to expect.
+## Pull Request Checklist
 
+Before sending your pull requests, make sure you do the following:
 
-## Before You Contribute
+-   Read the [contributing guidelines](CONTRIBUTING.md).
+-   Ensure you have signed the
+    [Contributor License Agreement (CLA)](https://cla.developers.google.com/).
+-   Check if your changes are consistent with the:
+    -   [General guidelines](#general-guidelines-and-philosophy-for-contribution).
+    -   [Coding Style](#coding-style).
+-   Run the [unit tests](#running-unit-tests).
 
-### As an Individual
+### Contributor License Agreements
 
-Before Cobalt can use your code, as an unaffiliated individual, you must sign
-the [Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual) (CLA), which you can do online.
+We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles.
 
-### As a Company
+Please fill out either the individual or corporate Contributor License Agreement (CLA).
 
-If you are a company that wishes to have one or more employees contribute to
-Cobalt on-the-clock, that is covered by a different agreement, the
-[Software Grant and Corporate Contributor License Agreement](https://cla.developers.google.com/about/google-corporate).
+  * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://code.google.com/legal/individual-cla-v1.0.html).
+  * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://code.google.com/legal/corporate-cla-v1.0.html).
 
-### What is a CLA?
+Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests.
 
-The Contributor License Agreement is necessary mainly because you own the
-copyright to your changes, even after your contribution becomes part of our
-codebase, so we need your permission to use and distribute your code. We also
-need to be sure of various other things — for instance that you'll tell us if
-you know that your code infringes on other people's patents. You don't have to
-sign the CLA until after you've submitted your code for review and a member has
-approved it, but you must do it before we can put your code into our codebase.
-Before you start working on a larger contribution, you should get in touch with
-us first with your idea so that we can help out and possibly guide
-you. Coordinating up front makes it much easier to avoid frustration later on.
+***NOTE***: Only original source code from you and other people that have signed the CLA can be accepted into the main repository.
 
+### Community Guidelines
 
-### Code Reviews
+This project follows
+[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
 
-All submissions, including submissions by project members, require review. We
-currently use [Gerrit Code Review](https://www.gerritcodereview.com/) for this
-purpose. Currently, team-member submissions go through private reviews, and
-external submissions go through public reviews.
+### Contributing code
 
+If you have improvements to Cobalt, send us your pull requests! For those
+just getting started, Github has a
+[how to](https://help.github.com/articles/using-pull-requests/).
 
-## Submission Process
+Cobalt team members will be assigned to review your pull requests. A team
+member will need to approve the workflow runs for each pull request. Once the
+pull requests are approved and pass *all* presubmit checks, a Cobalt
+team member will merge the pull request.
 
-We admit that this submission process is currently not completely optimized to
-make contributions easy, and we hope to make improvements to it in the
-future. It will always include some form of signing the CLA and submitting the
-code for review before merging changes into the Cobalt master tree.
+### Contribution guidelines and standards
 
-  1. Ensure you or your company have signed the appropriate CLA (see "Before You
-     Contribute" above).
-  1. Rebase your changes down into a single git commit.
-  1. Run `git clang-format HEAD~` to apply default C++ formatting rules,
-     followed by `git commit -a --amend` to squash any formatting changes
-     into your commit.
-  1. Run `git push origin HEAD:refs/for/master` to upload the review to
-     [Cobalt's Gerrit instance](https://cobalt-review.googlesource.com/).
-  1. Someone from the maintainers team will review the code, putting up comments
-     on any things that need to change for submission.
-  1. If you need to make changes, make them locally, test them, then `git commit
-     --amend` to add them to the *existing* commit. Then return to step 2.
-  1. If you do not need to make any more changes, a maintainer will integrate
-     the change into our private repository, and it will get pushed out to the
-     public repository after some time.
+Before sending your pull request for
+[review](https://github.com/tensorflow/tensorflow/pulls),
+make sure your changes are consistent with the guidelines and follow the
+Cobalt coding style.
+
+#### General guidelines and philosophy for contribution
+
+*   Include unit tests when you contribute new features, as they help to:
+    1.   Prove that your code works correctly
+    1.   Guard against future breaking changes to lower the maintenance cost.
+*   Bug fixes also generally require unit tests, because the presence of bugs
+    usually indicates insufficient test coverage.
+*   When you contribute a new feature to Cobalt, the maintenance burden is
+    (by default) transferred to the Cobalbt team. This means that the benefit
+    of the contribution must be compared against the cost of maintaining the
+    feature.
+*   As every PR requires several CPU/GPU hours of CI testing, we discourage
+    submitting PRs to fix one typo, one warning,etc. We recommend fixing the
+    same issue at the file level at least (e.g.: fix all typos in a file, fix
+    all compiler warning in a file, etc.)
+
+#### License
+
+Include a license at the top of new files. Check existing files for license examples.
+
+#### Coding style
+
+Cobalt follows the
+[Chromium style guide](https://chromium.googlesource.com/chromium/src/+/HEAD/styleguide/styleguide.md).
+
+Cobalt uses pre-commit to ensure good coding style. Create a python 3 virtual
+environment for working with Cobalt, then install `pre-commit` with:
+
+```bash
+$ pre-commit install -t post-checkout -t pre-commit -t pre-push --allow-missing-config
+```
+
+`pre-commit` will mostly run automatically, and can also be invoked manually.
+You can find documentation about it at https://pre-commit.com/.
+
+#### Running unit tests
+
+First, ensure Docker and docker-compose are installed on your system. Then,
+you can run unit tests for our linux reference implementation using:
+
+```bash
+$ docker-compose up --build --no-start linux-x64x11-unittest
+$ PLATFORM=linux-x64x11 CONFIG=devel TARGET=all docker-compose run linux-x64x11
+$ PLATFORM=linux-x64x11 CONFIG=devel docker-compose run linux-x64x11-unittest
+```
diff --git a/README.md b/README.md
index fcfe4a6..0a349a3 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,14 @@
-# Cobalt [![Build Status](https://img.shields.io/badge/-Build%20Status-blueviolet)](https://github.com/youtube/cobalt/blob/main/BUILD_STATUS.md)
+# Cobalt [![Build Matrix](https://img.shields.io/badge/-Build%20Matrix-blueviolet)](https://github.com/youtube/cobalt/blob/main/BUILD_STATUS.md)
+
+[![codecov](https://codecov.io/github/youtube/cobalt/branch/main/graph/badge.svg?token=RR6MKKNYNV)](https://codecov.io/github/youtube/cobalt)
+[![lint](https://github.com/youtube/cobalt/actions/workflows/lint.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/lint.yaml?query=event%3Apush+branch%3Amain)
+[![java](https://github.com/youtube/cobalt/actions/workflows/gradle.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/gradle.yaml?query=event%3Apush+branch%3Amain)
+[![python](https://github.com/youtube/cobalt/actions/workflows/pytest.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/pytest.yaml?query=event%3Apush+branch%3Amain) \
+[![android](https://github.com/youtube/cobalt/actions/workflows/android.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/android.yaml?query=event%3Apush+branch%3Amain)
+[![evergreen](https://github.com/youtube/cobalt/actions/workflows/evergreen.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/evergreen.yaml?query=event%3Apush+branch%3Amain)
+[![linux](https://github.com/youtube/cobalt/actions/workflows/linux.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/linux.yaml?query=event%3Apush+branch%3Amain)
+[![raspi-2](https://github.com/youtube/cobalt/actions/workflows/raspi-2.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/raspi-2.yaml?query=event%3Apush+branch%3Amain)
+[![win32](https://github.com/youtube/cobalt/actions/workflows/win32.yaml/badge.svg?branch=main&event=push)](https://github.com/youtube/cobalt/actions/workflows/win32.yaml?query=event%3Apush+branch%3Amain)
 
 ## Overview
 
diff --git a/base/BUILD.gn b/base/BUILD.gn
index 25759ac..b7cfe95 100644
--- a/base/BUILD.gn
+++ b/base/BUILD.gn
@@ -31,9 +31,9 @@
   import("//build/config/allocator.gni")
   import("//build/config/jumbo.gni")
   import("//build/timestamp.gni")
-  import("//testing/libfuzzer/fuzzer_test.gni")
-  import("//testing/test.gni")
 }
+import("//testing/libfuzzer/fuzzer_test.gni")
+import("//testing/test.gni")
 
 declare_args() {
   # Indicates if the Location object contains the source code information
diff --git a/base/sequenced_task_runner_unittest.cc b/base/sequenced_task_runner_unittest.cc
index 4dcc7e5..bec98e4 100644
--- a/base/sequenced_task_runner_unittest.cc
+++ b/base/sequenced_task_runner_unittest.cc
@@ -41,6 +41,7 @@
   DISALLOW_COPY_AND_ASSIGN(FlagOnDelete);
 };
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SequencedTaskRunnerTest);
 class SequencedTaskRunnerTest : public testing::Test {
  protected:
   SequencedTaskRunnerTest() : foreign_thread_("foreign") {}
diff --git a/base/single_thread_task_runner.cc b/base/single_thread_task_runner.cc
index d4baf23..3c1d832 100644
--- a/base/single_thread_task_runner.cc
+++ b/base/single_thread_task_runner.cc
@@ -12,6 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+#include "base/debug/stack_trace.h"
 #include "base/single_thread_task_runner.h"
 #include "base/message_loop/message_loop.h"
 #include "base/synchronization/waitable_event.h"
@@ -47,7 +48,17 @@
 
   if (task_may_run) {
     // Wait for the task to complete before proceeding.
-    task_finished.Wait();
+    do {
+      if (task_finished.TimedWait(base::TimeDelta::FromMilliseconds(1000))) {
+        break;
+      }
+#if !defined(COBALT_BUILD_TYPE_GOLD)
+      if (!SbSystemIsDebuggerAttached()) {
+        base::debug::StackTrace trace;
+        trace.PrintWithPrefix("[task runner deadlock]");
+      }
+#endif // !defined(COBALT_BUILD_TYPE_GOLD)
+    } while (true);
   }
 }
 #endif
diff --git a/base/test/gtest_util.h b/base/test/gtest_util.h
index 25610c6..4490713 100644
--- a/base/test/gtest_util.h
+++ b/base/test/gtest_util.h
@@ -33,6 +33,7 @@
 #else
 // DCHECK_IS_ON() && defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID)
 
+#if !GTEST_OS_STARBOARD
 // Macro copied from gtest-death-test-internal.h as it's (1) internal for now
 // and (2) only defined if !GTEST_HAS_DEATH_TEST which is only a subset of the
 // conditions in which it's needed here.
@@ -50,6 +51,7 @@
     terminator;                                                     \
   } else                                                            \
     ::testing::Message()
+#endif // !GTEST_OS_STARBOARD
 
 #define EXPECT_DCHECK_DEATH(statement) \
     GTEST_UNSUPPORTED_DEATH_TEST(statement, "Check failed", )
diff --git a/base/test/sequenced_task_runner_test_template.h b/base/test/sequenced_task_runner_test_template.h
index a510030..ff0061f 100644
--- a/base/test/sequenced_task_runner_test_template.h
+++ b/base/test/sequenced_task_runner_test_template.h
@@ -35,6 +35,7 @@
   Type type;
 };
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SequencedTaskTracker);
 // Utility class used in the tests below.
 class SequencedTaskTracker : public RefCountedThreadSafe<SequencedTaskTracker> {
  public:
@@ -112,6 +113,7 @@
 
 }  // namespace internal
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SequencedTaskRunnerTest);
 template <typename TaskRunnerTestDelegate>
 class SequencedTaskRunnerTest : public testing::Test {
  protected:
@@ -312,6 +314,7 @@
                            DelayedTaskAfterLongTask,
                            DelayedTaskAfterManyLongTasks);
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SequencedTaskRunnerDelayedTest);
 template <typename TaskRunnerTestDelegate>
 class SequencedTaskRunnerDelayedTest
     : public SequencedTaskRunnerTest<TaskRunnerTestDelegate> {};
diff --git a/base/test/task_runner_test_template.h b/base/test/task_runner_test_template.h
index 4670522..4175fd8 100644
--- a/base/test/task_runner_test_template.h
+++ b/base/test/task_runner_test_template.h
@@ -106,6 +106,7 @@
 
 }  // namespace test
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(TaskRunnerTest);
 template <typename TaskRunnerTestDelegate>
 class TaskRunnerTest : public testing::Test {
  protected:
@@ -179,6 +180,7 @@
 
 }  // namespace test
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(TaskRunnerAffinityTest);
 template <typename TaskRunnerTestDelegate>
 class TaskRunnerAffinityTest : public TaskRunnerTest<TaskRunnerTestDelegate> {};
 
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni
index 06c0702..75ab855 100644
--- a/build/config/android/internal_rules.gni
+++ b/build/config/android/internal_rules.gni
@@ -15,7 +15,7 @@
 import("//build/toolchain/kythe.gni")
 import("//build/util/generate_wrapper.gni")
 import("//build_overrides/build.gni")
-if (current_toolchain == default_toolchain) {
+if (is_starboardized_toolchain) {
   import("//build/toolchain/concurrent_links.gni")
 }
 assert(is_android)
diff --git a/build/config/coverage/BUILD.gn b/build/config/coverage/BUILD.gn
index 09c227d..fa0833e 100644
--- a/build/config/coverage/BUILD.gn
+++ b/build/config/coverage/BUILD.gn
@@ -30,5 +30,13 @@
       # TODO(crbug.com/1194301): Remove this flag.
       cflags += [ "-fno-use-cxa-atexit" ]
     }
+
+    if (using_old_compiler) {
+      # These compiler flags aren't supported by the older clang compiler.
+      cflags -= [
+        "-limited-coverage-experimental=true",
+        "-fno-use-cxa-atexit",
+      ]
+    }
   }
 }
diff --git a/build/config/win/BUILD.gn b/build/config/win/BUILD.gn
index 5003502..8f7c597 100644
--- a/build/config/win/BUILD.gn
+++ b/build/config/win/BUILD.gn
@@ -602,6 +602,8 @@
       cflags = [
         "/wd4800",
         "/wd4834",
+        "/wd4858",
+        "/wd5208"
       ]
     }
   }
diff --git a/build/config/win/visual_studio_version.gni b/build/config/win/visual_studio_version.gni
index 13ca252..11f5f02 100644
--- a/build/config/win/visual_studio_version.gni
+++ b/build/config/win/visual_studio_version.gni
@@ -41,7 +41,10 @@
     } else {
       _vis_std_year = "2017"
     }
-    _default_visual_studio_path = "C:/Program Files (x86)/Microsoft Visual Studio/$_vis_std_year/Professional"
+    _default_visual_studio_path = getenv("VS2022INSTALLDIR")
+    if (_default_visual_studio_path == "") {
+      _default_visual_studio_path = "C:/Program Files (x86)/Microsoft Visual Studio/$_vis_std_year/Professional"
+    }
   }
 
   declare_args() {
diff --git a/build/nocompile.gni b/build/nocompile.gni
index d36b5a1..4f17837 100644
--- a/build/nocompile.gni
+++ b/build/nocompile.gni
@@ -61,9 +61,7 @@
 import("//build/config/clang/clang.gni")
 import("//build/config/python.gni")
 import("//build/toolchain/toolchain.gni")
-if (!is_starboard) {
-  import("//testing/test.gni")
-}
+import("//testing/test.gni")
 
 declare_args() {
   # TODO(crbug.com/105388): make sure no-compile test is not flaky.
diff --git a/build/toolchain/BUILD.gn b/build/toolchain/BUILD.gn
index 6cf8f1b..00f3e11 100644
--- a/build/toolchain/BUILD.gn
+++ b/build/toolchain/BUILD.gn
@@ -11,7 +11,7 @@
   action_pool_depth = -1
 }
 
-if (current_toolchain == default_toolchain) {
+if (is_starboardized_toolchain) {
   if (action_pool_depth == -1 || (use_goma || use_rbe)) {
     action_pool_depth = exec_script("get_cpu_count.py", [], "value")
   }
diff --git a/build/toolchain/gcc_toolchain.gni b/build/toolchain/gcc_toolchain.gni
index 891cf34..df72296 100644
--- a/build/toolchain/gcc_toolchain.gni
+++ b/build/toolchain/gcc_toolchain.gni
@@ -116,6 +116,10 @@
 #      that the snarl tool will accept.
 template("gcc_toolchain") {
   toolchain(target_name) {
+    is_starboard_toolchain = target_name == "starboard"
+    if (!build_with_separate_cobalt_toolchain) {
+      not_needed(["is_starboard_toolchain"])
+    }
     assert(defined(invoker.ar), "gcc_toolchain() must specify a \"ar\" value")
     assert(defined(invoker.cc), "gcc_toolchain() must specify a \"cc\" value")
     assert(defined(invoker.cxx), "gcc_toolchain() must specify a \"cxx\" value")
@@ -145,6 +149,7 @@
     toolchain_args = {
       # Populate toolchain args from the invoker.
       forward_variables_from(invoker_toolchain_args, "*")
+      build_with_separate_cobalt_toolchain = build_with_separate_cobalt_toolchain
 
       # The host toolchain value computed by the default toolchain's setup
       # needs to be passed through unchanged to all secondary toolchains to
@@ -386,7 +391,7 @@
       # TODO(b/206642994): see if we can remove this condition. It's needed for
       # now to add cflags for evergreen platforms but we haven't yet decided
       # whether cflags should be added here for all platforms.
-      if (is_starboard && sb_is_evergreen) {
+      if (is_starboard && sb_is_evergreen && !is_starboard_toolchain) {
         command = "$asm -MMD -MF $depfile ${rebuild_string}{{defines}} {{include_dirs}} {{cflags}} {{asmflags}}${extra_asmflags} -c {{source}} -o {{output}}"
       } else {
         command = "$asm -MMD -MF $depfile ${rebuild_string}{{defines}} {{include_dirs}} {{asmflags}}${extra_asmflags} -c {{source}} -o {{output}}"
@@ -455,7 +460,7 @@
       # TODO(b/206642994): see if we can remove this condition. It's needed for
       # now because we use the ld.lld linker for evergreen platforms and need to
       # pass options as `option` instead of `-Wl,option`.
-      if (is_starboard && sb_is_evergreen) {
+      if (is_starboard && sb_is_evergreen && !is_starboard_toolchain) {
         link_command = "$ld -shared -soname=\"$soname\" {{ldflags}}${extra_ldflags} -o \"$unstripped_sofile\" @\"$rspfile\""
       } else {
         link_command = "$ld -shared -Wl,-soname=\"$soname\" {{ldflags}}${extra_ldflags} -o \"$unstripped_sofile\" @\"$rspfile\""
@@ -489,7 +494,7 @@
         # TODO(b/206642994): see if we can remove this condition. It's needed for
         # now because we use the ld.lld linker for evergreen platforms and need
         # to pass options as `option` instead of `-Wl,option`.
-      } else if (is_starboard && sb_is_evergreen) {
+      } else if (is_starboard && sb_is_evergreen && !is_starboard_toolchain) {
         rspfile_content = "--whole-archive {{inputs}} {{solibs}} --no-whole-archive {{libs}}$tail_lib_dependencies"
       } else {
         rspfile_content = "-Wl,--whole-archive {{inputs}} {{solibs}} -Wl,--no-whole-archive {{libs}}$tail_lib_dependencies"
diff --git a/build_overrides/gtest.gni b/build_overrides/gtest.gni
new file mode 100644
index 0000000..4498de5
--- /dev/null
+++ b/build_overrides/gtest.gni
@@ -0,0 +1,15 @@
+# Copyright 2023 The Cobalt Authors
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+# Exclude support for registering main function in multi-process tests.
+gtest_include_multiprocess = true
+
+# Exclude support for platform-specific operations across unit tests.
+gtest_include_platform_test = false
+
+# Exclude support for testing Objective C code on OS X and iOS.
+gtest_include_objc_support = true
+
+# Exclude support for flushing coverage files on iOS.
+gtest_include_ios_coverage = true
diff --git a/cobalt/BUILD.gn b/cobalt/BUILD.gn
index cecfe49..867f45e 100644
--- a/cobalt/BUILD.gn
+++ b/cobalt/BUILD.gn
@@ -18,6 +18,7 @@
     ":default",
     "//cobalt/bindings/testing:bindings_test",
     "//cobalt/browser:browser_test",
+    "//cobalt/browser/metrics:metrics_test",
     "//cobalt/cssom:cssom_test",
     "//cobalt/demos/simple_sandbox",
     "//cobalt/dom:dom_test",
@@ -79,8 +80,10 @@
       "//third_party/llvm-project/compiler-rt:compiler_rt",
       "//third_party/llvm-project/libcxx:cxx",
       "//third_party/llvm-project/libcxxabi:cxxabi",
-      "//third_party/llvm-project/libunwind:unwind_evergreen",
       "//third_party/musl:c",
     ]
+    if (!build_with_separate_cobalt_toolchain) {
+      deps += [ "//third_party/llvm-project/libunwind:unwind_evergreen" ]
+    }
   }
 }
diff --git a/cobalt/CHANGELOG.md b/cobalt/CHANGELOG.md
index 0a77358..c21f620 100644
--- a/cobalt/CHANGELOG.md
+++ b/cobalt/CHANGELOG.md
@@ -2,6 +2,12 @@
 
 This document records all notable changes made to Cobalt since the last release.
 
+## Version 24
+ - **Cobalt has experimental Web Assembly capability
+
+   Web Assembly is enabled as experimental capabality on android-arm and
+   development build configurations.
+
 ## Version 23
  - **Cobalt now uses GN (Generate Ninja) meta-build system**
 
diff --git a/cobalt/account/account_manager.cc b/cobalt/account/account_manager.cc
deleted file mode 100644
index bff7bf1..0000000
--- a/cobalt/account/account_manager.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2016 The Cobalt Authors. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include <memory>
-#include <string>
-
-#include "cobalt/account/account_manager.h"
-
-#include "starboard/user.h"
-
-namespace cobalt {
-namespace account {
-
-namespace {
-const int kMaxValueLength = 64 * 1024;
-
-std::string GetCurrentUserProperty(SbUserPropertyId property_id) {
-  SbUser user = SbUserGetCurrent();
-
-  if (!SbUserIsValid(user)) {
-    return "";
-  }
-
-  int size = SbUserGetPropertySize(user, property_id);
-  if (!size || size > kMaxValueLength) {
-    return "";
-  }
-
-  std::unique_ptr<char[]> value(new char[size]);
-  if (!SbUserGetProperty(user, property_id, value.get(), size)) {
-    return "";
-  }
-
-  std::string result = value.get();
-  return result;
-}
-
-}  // namespace
-
-AccountManager::AccountManager() {}
-
-std::string AccountManager::GetAvatarURL() {
-  return GetCurrentUserProperty(kSbUserPropertyAvatarUrl);
-}
-
-std::string AccountManager::GetUsername() {
-  return GetCurrentUserProperty(kSbUserPropertyUserName);
-}
-
-std::string AccountManager::GetUserId() {
-  return GetCurrentUserProperty(kSbUserPropertyUserId);
-}
-
-}  // namespace account
-}  // namespace cobalt
diff --git a/cobalt/account/account_manager.h b/cobalt/account/account_manager.h
deleted file mode 100644
index d3b9de3..0000000
--- a/cobalt/account/account_manager.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2015 The Cobalt Authors. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef COBALT_ACCOUNT_ACCOUNT_MANAGER_H_
-#define COBALT_ACCOUNT_ACCOUNT_MANAGER_H_
-
-#include <string>
-
-namespace cobalt {
-namespace account {
-
-// Glue for h5vcc to get properties for the current user.
-// The AccountManager will be owned by BrowserModule.
-class AccountManager {
- public:
-  AccountManager();
-  AccountManager(const AccountManager&) = delete;
-  AccountManager& operator=(const AccountManager&) = delete;
-
-  ~AccountManager() {}
-
-  // Get the avatar URL associated with the account, if any.
-  std::string GetAvatarURL();
-
-  // Get the username associated with the account. Due to restrictions on
-  // some platforms, this may return the user ID or an empty string.
-  std::string GetUsername();
-
-  // Get the user ID associated with the account.
-  std::string GetUserId();
-};
-
-}  // namespace account
-}  // namespace cobalt
-
-#endif  // COBALT_ACCOUNT_ACCOUNT_MANAGER_H_
diff --git a/cobalt/bindings/testing/serialize_script_value_interface.h b/cobalt/bindings/testing/serialize_script_value_interface.h
index 782edb2..9ee55db 100644
--- a/cobalt/bindings/testing/serialize_script_value_interface.h
+++ b/cobalt/bindings/testing/serialize_script_value_interface.h
@@ -35,24 +35,19 @@
  public:
   SerializeScriptValueInterface() = default;
 
-  size_t serialized_size() { return data_buffer_->size; }
-
   void SerializeTest(const script::ValueHandleHolder& value) {
-    data_buffer_ = std::move(script::SerializeScriptValue(value));
     isolate_ = script::GetIsolate(value);
+    structured_clone_ = std::make_unique<script::StructuredClone>(value);
   }
 
-  const script::ValueHandleHolder* DeserializeTest() {
-    deserialized_.reset(
-        script::DeserializeScriptValue(isolate_, *data_buffer_));
-    return deserialized_.get();
+  const script::Handle<script::ValueHandle> DeserializeTest() {
+    return structured_clone_->Deserialize(isolate_);
   }
 
   DEFINE_WRAPPABLE_TYPE(SerializeScriptValueInterface);
 
  private:
-  std::unique_ptr<script::DataBuffer> data_buffer_;
-  std::unique_ptr<script::ValueHandleHolder> deserialized_;
+  std::unique_ptr<script::StructuredClone> structured_clone_;
   v8::Isolate* isolate_;
 };
 
diff --git a/cobalt/bindings/testing/serialize_script_value_test.cc b/cobalt/bindings/testing/serialize_script_value_test.cc
index 96e0dc6..a9e4b09 100644
--- a/cobalt/bindings/testing/serialize_script_value_test.cc
+++ b/cobalt/bindings/testing/serialize_script_value_test.cc
@@ -36,10 +36,19 @@
 TEST_F(SerializeScriptValueTest, Serialize) {
   // Stores serialized result that is then used by |deserializeTest()|.
   EvaluateScript(R"(
-      test.serializeTest({a: ['something'], b: new Uint8Array([42])});
+window.arrayBuffer = new ArrayBuffer(2);
+window.sharedArrayBuffer = new SharedArrayBuffer(4);
+{
+  new Uint8Array(window.arrayBuffer).fill(10);
+  new Uint8Array(window.sharedArrayBuffer).fill(20);
+}
+test.serializeTest({
+  a: ['something'],
+  b: new Uint8Array([42]),
+  c: window.arrayBuffer,
+  d: window.sharedArrayBuffer,
+});
     )");
-  // Sanity check the serialized size.
-  EXPECT_EQ(32, test_mock().serialized_size());
   ExpectTrue("!(test.deserializeTest() instanceof Array)");
   ExpectTrue("test.deserializeTest() instanceof Object");
   ExpectTrue("test.deserializeTest().a instanceof Array");
@@ -48,6 +57,44 @@
   ExpectTrue("test.deserializeTest().b instanceof Uint8Array");
   ExpectTrue("!(test.deserializeTest().b instanceof Uint16Array)");
   ExpectTrue("42 === test.deserializeTest().b[0]");
+  ExpectTrue("test.deserializeTest().c instanceof ArrayBuffer");
+  ExpectTrue("test.deserializeTest().d instanceof SharedArrayBuffer");
+  EvaluateScript(R"(
+window.otherArrayBuffer = test.deserializeTest().c;
+window.otherSharedArrayBuffer = test.deserializeTest().d;
+const arrayBufferToString = arrayBuffer =>
+    new Uint8Array(arrayBuffer).toString();
+window.string = arrayBufferToString(window.arrayBuffer);
+window.otherString = arrayBufferToString(window.otherArrayBuffer);
+window.sharedString = arrayBufferToString(window.sharedArrayBuffer);
+window.otherSharedString = arrayBufferToString(window.otherSharedArrayBuffer);
+    )");
+  ExpectTrue("2 === window.arrayBuffer.byteLength");
+  ExpectTrue("2 === window.otherArrayBuffer.byteLength");
+  ExpectTrue("4 === window.sharedArrayBuffer.byteLength");
+  ExpectTrue("4 === window.otherSharedArrayBuffer.byteLength");
+  ExpectTrue("'10,10' === window.string");
+  ExpectTrue("'10,10' === window.otherString");
+  ExpectTrue("'20,20,20,20' === window.sharedString");
+  ExpectTrue("'20,20,20,20' === window.otherSharedString");
+  EvaluateScript(R"(
+const updateArrayBuffer = arrayBuffer => {
+ const view = new Uint8Array(arrayBuffer);
+ view.forEach((x, i) => {
+  view[i] = x + i * 10;
+ });
+};
+updateArrayBuffer(window.otherArrayBuffer);
+updateArrayBuffer(window.otherSharedArrayBuffer);
+window.string = arrayBufferToString(window.arrayBuffer);
+window.otherString = arrayBufferToString(window.otherArrayBuffer);
+window.sharedString = arrayBufferToString(window.sharedArrayBuffer);
+window.otherSharedString = arrayBufferToString(window.otherSharedArrayBuffer);
+    )");
+  ExpectTrue("'10,10' === window.string");
+  ExpectTrue("'10,20' === window.otherString");
+  ExpectTrue("'20,30,40,50' === window.sharedString");
+  ExpectTrue("'20,30,40,50' === window.otherSharedString");
 }
 
 }  // namespace testing
diff --git a/cobalt/black_box_tests/black_box_tests.py b/cobalt/black_box_tests/black_box_tests.py
index d8cea51..99b11c4 100755
--- a/cobalt/black_box_tests/black_box_tests.py
+++ b/cobalt/black_box_tests/black_box_tests.py
@@ -46,9 +46,7 @@
     # TODO(b/283788059): enable when there are GitHub jobs to run integration
     # and Black Box Tests on evergreen-arm-hardfp.
     #'evergreen-arm/devel',
-    # TODO(b/283144901): enable when the Starboard 16 binaries are released for
-    # Evergreen.
-    #'evergreen-x64/devel',
+    'evergreen-x64/devel',
 ]
 
 _PORT_SELECTION_RETRY_LIMIT = 10
@@ -87,6 +85,7 @@
     'service_worker_fetch_main_resource_test',
     'service_worker_fetch_test',
     'service_worker_message_test',
+    'service_worker_post_message_test',
     'service_worker_test',
     'service_worker_persist_test',
     'soft_mic_platform_service_test',
@@ -96,6 +95,7 @@
     'web_worker_test',
     'worker_csp_test',
     'worker_load_test',
+    'worker_post_message_test',
 ]
 # These are very different and require a custom config + proxy
 _WPT_TESTS = [
diff --git a/cobalt/black_box_tests/testdata/service_worker_controller_activation_test_worker.js b/cobalt/black_box_tests/testdata/service_worker_controller_activation_test_worker.js
index 4bda3e0..a1fab38 100644
--- a/cobalt/black_box_tests/testdata/service_worker_controller_activation_test_worker.js
+++ b/cobalt/black_box_tests/testdata/service_worker_controller_activation_test_worker.js
@@ -23,4 +23,5 @@
 
 self.onactivate = function (e) {
   console.log('onactivate event received', e);
+  self.clients.claim();
 }
diff --git a/cobalt/black_box_tests/testdata/service_worker_fetch_test.js b/cobalt/black_box_tests/testdata/service_worker_fetch_test.js
index 6b9ca7d..94eda59 100644
--- a/cobalt/black_box_tests/testdata/service_worker_fetch_test.js
+++ b/cobalt/black_box_tests/testdata/service_worker_fetch_test.js
@@ -35,7 +35,7 @@
 });
 
 let fetchEventCount = 0;
-let exceptScriptIntercepted = false;
+let expectScriptIntercepted = false;
 
 self.addEventListener('message', event => {
   if (event.data === 'start-test') {
@@ -58,21 +58,21 @@
       return;
     }
     shouldIntercept = true;
-    exceptScriptIntercepted = true;
+    expectScriptIntercepted = true;
     postMessage({test: 'check-script-intercepted'});
     return;
   }
   if (event.data === 'script-intercepted') {
-    if (!exceptScriptIntercepted) {
+    if (!expectScriptIntercepted) {
       postMessage('script-intercepted-unexpected');
     }
     shouldIntercept = false;
-    exceptScriptIntercepted = false;
+    expectScriptIntercepted = false;
     postMessage({test: 'check-script-not-intercepted'})
     return;
   }
   if (event.data === 'script-not-intercepted') {
-    if (exceptScriptIntercepted) {
+    if (expectScriptIntercepted) {
       postMessage('script-not-intercepted-unexpected');
       return;
     }
diff --git a/cobalt/black_box_tests/testdata/service_worker_post_message_test.html b/cobalt/black_box_tests/testdata/service_worker_post_message_test.html
new file mode 100644
index 0000000..d4fb512
--- /dev/null
+++ b/cobalt/black_box_tests/testdata/service_worker_post_message_test.html
@@ -0,0 +1,114 @@
+<!DOCTYPE html>
+<!--
+  Copyright 2023 The Cobalt Authors. All Rights Reserved.
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<!--
+  Tests postMessage() for service workers.
+-->
+
+<html>
+<head>
+  <title>Cobalt Service Worker postMessage() Test</title>
+  <script src='black_box_js_test_utils.js'></script>
+</head>
+<body>
+  <script>
+    h5vcc.storage.clearServiceWorkerCache();
+
+    const unregisterAll = () => navigator.serviceWorker.getRegistrations().then(registrations =>
+        Promise.all(registrations.map(r => r.unregister())));
+    const unregisterAndNotReached = () => unregisterAll().then(notReached);
+
+    const timeoutId = window.setTimeout(unregisterAndNotReached, 10000);
+    window.sharedArrayBufferFromWorker = null;
+    window.sharedArrayBufferFromWorkerView = null;
+    window.sharedArrayBufferFromWindow = new SharedArrayBuffer(4);
+    window.sharedArrayBufferFromWindowView = new Uint8Array(window.sharedArrayBufferFromWindow);
+    window.activeServiceWorker = null;
+    navigator.serviceWorker.onmessage = event => {
+      if (event.data.type === 'check-data') {
+        const data = event.data.data;
+        assertEqual(1, data.number);
+        assertEqual(2, data.array.length);
+        assertEqual(2, data.array[0]);
+        assertEqual(3, data.array[1]);
+        assertEqual('abc', data.string);
+        assertEqual(3, data.arrayBuffer.byteLength);
+        const arrayBufferView = new Uint8Array(data.arrayBuffer);
+        assertEqual(4, arrayBufferView[0]);
+        assertEqual(5, arrayBufferView[1]);
+        assertEqual(6, arrayBufferView[2]);
+        assertEqual(5, data.sharedArrayBuffer.byteLength);
+        window.sharedArrayBufferFromWorker = data.sharedArrayBuffer;
+        window.sharedArrayBufferFromWorkerView = new Uint8Array(window.sharedArrayBufferFromWorker);
+        window.activeServiceWorker.postMessage({
+          type: 'update-shared-array-buffers',
+          index: 1,
+          value: 42,
+        });
+        return;
+      }
+      if (event.data.type === 'update-shared-array-buffers-done') {
+        assertEqual(42, window.sharedArrayBufferFromWindowView[1]);
+        assertEqual(42, window.sharedArrayBufferFromWorkerView[1]);
+        window.sharedArrayBufferFromWindowView[0] = 47;
+        window.sharedArrayBufferFromWorkerView[0] = 47;
+        window.activeServiceWorker.postMessage({
+          type: 'check-shared-array-buffers',
+          index: 0,
+          value: 47,
+        })
+        return;
+      }
+      if (event.data.type === 'check-shared-array-buffers-done') {
+        unregisterAll().then(() => {
+          clearTimeout(timeoutId);
+          onEndTest();
+        });
+        return;
+      }
+      console.log(JSON.stringify(event.data));
+      unregisterAndNotReached();
+    };
+
+    navigator.serviceWorker.ready.then(registration => {
+      window.activeServiceWorker = registration.active;
+      const arrayBuffer = new ArrayBuffer(3);
+      const arrayBufferView = new Uint8Array(arrayBuffer);
+      arrayBufferView[0] = 4;
+      arrayBufferView[1] = 5;
+      arrayBufferView[2] = 6;
+      window.activeServiceWorker.postMessage({
+        type: 'check-data',
+        data: {
+          number: 1,
+          array: [2, 3],
+          string: 'abc',
+          arrayBuffer,
+          sharedArrayBuffer: sharedArrayBufferFromWindow,
+        },
+      });
+    });
+
+    unregisterAll().then(() => {
+      navigator.serviceWorker.register('service_worker_post_message_test.js').catch(() => {
+        unregisterAndNotReached();
+      });
+    });
+
+    setupFinished();
+  </script>
+</body>
+</html>
diff --git a/cobalt/black_box_tests/testdata/service_worker_post_message_test.js b/cobalt/black_box_tests/testdata/service_worker_post_message_test.js
new file mode 100644
index 0000000..01302a4
--- /dev/null
+++ b/cobalt/black_box_tests/testdata/service_worker_post_message_test.js
@@ -0,0 +1,93 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const postMessage = message => {
+  const options = {
+    includeUncontrolled: false, type: 'window'
+  };
+  self.clients.matchAll(options).then(clients => {
+    clients.forEach(c => {
+      c.postMessage(message);
+    });
+  });
+};
+
+self.addEventListener("install", event => {
+  self.skipWaiting();
+});
+
+self.addEventListener('activate', event => {
+  self.clients.claim();
+});
+
+const assertEqual = (expected, actual) => {
+  if (expected !== actual) {
+    postMessage(`${actual} does not equal expected ${expected}`);
+  }
+};
+
+const sharedArrayBufferFromWorker = new SharedArrayBuffer(5);
+const sharedArrayBufferFromWorkerView = new Uint8Array(sharedArrayBufferFromWorker);
+let sharedArrayBufferFromWindow = null;
+let sharedArrayBufferFromWindowView = null;
+
+self.addEventListener('message', event => {
+  if (event.data.type === 'check-data') {
+    const data = event.data.data;
+    assertEqual(1, data.number);
+    assertEqual(2, data.array.length);
+    assertEqual(2, data.array[0]);
+    assertEqual(3, data.array[1]);
+    assertEqual('abc', data.string);
+    assertEqual(3, data.arrayBuffer.byteLength);
+    const arrayBufferFromWindowView = new Uint8Array(data.arrayBuffer);
+    assertEqual(4, arrayBufferFromWindowView[0]);
+    assertEqual(5, arrayBufferFromWindowView[1]);
+    assertEqual(6, arrayBufferFromWindowView[2]);
+    assertEqual(4, data.sharedArrayBuffer.byteLength);
+    sharedArrayBufferFromWindow = data.sharedArrayBuffer;
+    sharedArrayBufferFromWindowView = new Uint8Array(sharedArrayBufferFromWindow);
+    const arrayBuffer = new ArrayBuffer(3);
+    const arrayBufferView = new Uint8Array(arrayBuffer);
+    arrayBufferView[0] = 4;
+    arrayBufferView[1] = 5;
+    arrayBufferView[2] = 6;
+    postMessage({
+      type: 'check-data',
+      data: {
+        number: 1,
+        array: [2, 3],
+        string: 'abc',
+        arrayBuffer,
+        sharedArrayBuffer: sharedArrayBufferFromWorker,
+      },
+    });
+    return;
+  }
+  if (event.data.type === 'update-shared-array-buffers') {
+    const {index, value} = event.data;
+    sharedArrayBufferFromWindowView[index] = value;
+    sharedArrayBufferFromWorkerView[index] = value;
+    postMessage({type: 'update-shared-array-buffers-done'});
+    return;
+  }
+  if (event.data.type === 'check-shared-array-buffers') {
+    const {index, value} = event.data;
+    assertEqual(value, sharedArrayBufferFromWindowView[index]);
+    assertEqual(value, sharedArrayBufferFromWorkerView[index]);
+    postMessage({type: 'check-shared-array-buffers-done'});
+    return;
+  }
+  postMessage(`Unexpected message ${JSON.stringify(event.data)}.`);
+});
diff --git a/cobalt/black_box_tests/testdata/worker_post_message_test.html b/cobalt/black_box_tests/testdata/worker_post_message_test.html
new file mode 100644
index 0000000..2c5f8d9
--- /dev/null
+++ b/cobalt/black_box_tests/testdata/worker_post_message_test.html
@@ -0,0 +1,99 @@
+<!DOCTYPE html>
+<!--
+  Copyright 2023 The Cobalt Authors. All Rights Reserved.
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<!--
+  Tests postMessage() for workers.
+-->
+
+<html>
+<head>
+  <title>Cobalt Worker postMessage() Test</title>
+  <script src='black_box_js_test_utils.js'></script>
+</head>
+<body>
+  <script>
+    const timeoutId = window.setTimeout(notReached, 10000);
+    window.sharedArrayBufferFromWorker = null;
+    window.sharedArrayBufferFromWorkerView = null;
+    window.sharedArrayBufferFromWindow = new SharedArrayBuffer(4);
+    window.sharedArrayBufferFromWindowView = new Uint8Array(window.sharedArrayBufferFromWindow);
+    const worker = new Worker('worker_post_message_test.js');
+    worker.addEventListener('message', event => {
+      if (event.data === 'ready') {
+        const arrayBuffer = new ArrayBuffer(3);
+        const arrayBufferView = new Uint8Array(arrayBuffer);
+        arrayBufferView[0] = 4;
+        arrayBufferView[1] = 5;
+        arrayBufferView[2] = 6;
+        worker.postMessage({
+          type: 'check-data',
+          data: {
+            number: 1,
+            array: [2, 3],
+            string: 'abc',
+            arrayBuffer,
+            sharedArrayBuffer: sharedArrayBufferFromWindow,
+          },
+        });
+        return;
+      }
+      if (event.data.type === 'check-data') {
+        const data = event.data.data;
+        assertEqual(1, data.number);
+        assertEqual(2, data.array.length);
+        assertEqual(2, data.array[0]);
+        assertEqual(3, data.array[1]);
+        assertEqual('abc', data.string);
+        assertEqual(3, data.arrayBuffer.byteLength);
+        const arrayBufferView = new Uint8Array(data.arrayBuffer);
+        assertEqual(4, arrayBufferView[0]);
+        assertEqual(5, arrayBufferView[1]);
+        assertEqual(6, arrayBufferView[2]);
+        assertEqual(5, data.sharedArrayBuffer.byteLength);
+        window.sharedArrayBufferFromWorker = data.sharedArrayBuffer;
+        window.sharedArrayBufferFromWorkerView = new Uint8Array(window.sharedArrayBufferFromWorker);
+        worker.postMessage({
+          type: 'update-shared-array-buffers',
+          index: 1,
+          value: 42,
+        });
+        return;
+      }
+      if (event.data.type === 'update-shared-array-buffers-done') {
+        assertEqual(42, window.sharedArrayBufferFromWindowView[1]);
+        assertEqual(42, window.sharedArrayBufferFromWorkerView[1]);
+        window.sharedArrayBufferFromWindowView[0] = 47;
+        window.sharedArrayBufferFromWorkerView[0] = 47;
+        worker.postMessage({
+          type: 'check-shared-array-buffers',
+          index: 0,
+          value: 47,
+        })
+        return;
+      }
+      if (event.data.type === 'check-shared-array-buffers-done') {
+        clearTimeout(timeoutId);
+        onEndTest();
+        return;
+      }
+      console.log(JSON.stringify(event.data));
+      notReached();
+    });
+
+    setupFinished();
+  </script>
+</body>
+</html>
diff --git a/cobalt/black_box_tests/testdata/worker_post_message_test.js b/cobalt/black_box_tests/testdata/worker_post_message_test.js
new file mode 100644
index 0000000..4207ec8
--- /dev/null
+++ b/cobalt/black_box_tests/testdata/worker_post_message_test.js
@@ -0,0 +1,76 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const assertEqual = (expected, actual) => {
+  if (expected !== actual) {
+    self.postMessage(`${actual} does not equal expected ${expected}`);
+  }
+};
+
+const sharedArrayBufferFromWorker = new SharedArrayBuffer(5);
+const sharedArrayBufferFromWorkerView = new Uint8Array(sharedArrayBufferFromWorker);
+let sharedArrayBufferFromWindow = null;
+let sharedArrayBufferFromWindowView = null;
+
+self.addEventListener('message', event => {
+  if (event.data.type === 'check-data') {
+    const data = event.data.data;
+    assertEqual(1, data.number);
+    assertEqual(2, data.array.length);
+    assertEqual(2, data.array[0]);
+    assertEqual(3, data.array[1]);
+    assertEqual('abc', data.string);
+    assertEqual(3, data.arrayBuffer.byteLength);
+    const arrayBufferFromWindowView = new Uint8Array(data.arrayBuffer);
+    assertEqual(4, arrayBufferFromWindowView[0]);
+    assertEqual(5, arrayBufferFromWindowView[1]);
+    assertEqual(6, arrayBufferFromWindowView[2]);
+    assertEqual(4, data.sharedArrayBuffer.byteLength);
+    sharedArrayBufferFromWindow = data.sharedArrayBuffer;
+    sharedArrayBufferFromWindowView = new Uint8Array(sharedArrayBufferFromWindow);
+    const arrayBuffer = new ArrayBuffer(3);
+    const arrayBufferView = new Uint8Array(arrayBuffer);
+    arrayBufferView[0] = 4;
+    arrayBufferView[1] = 5;
+    arrayBufferView[2] = 6;
+    self.postMessage({
+      type: 'check-data',
+      data: {
+        number: 1,
+        array: [2, 3],
+        string: 'abc',
+        arrayBuffer,
+        sharedArrayBuffer: sharedArrayBufferFromWorker,
+      },
+    });
+    return;
+  }
+  if (event.data.type === 'update-shared-array-buffers') {
+    const {index, value} = event.data;
+    sharedArrayBufferFromWindowView[index] = value;
+    sharedArrayBufferFromWorkerView[index] = value;
+    self.postMessage({type: 'update-shared-array-buffers-done'});
+    return;
+  }
+  if (event.data.type === 'check-shared-array-buffers') {
+    const {index, value} = event.data;
+    assertEqual(value, sharedArrayBufferFromWindowView[index]);
+    assertEqual(value, sharedArrayBufferFromWorkerView[index]);
+    self.postMessage({type: 'check-shared-array-buffers-done'});
+    return;
+  }
+  self.postMessage(`Unexpected message ${JSON.stringify(event.data)}.`);
+});
+
+self.postMessage('ready');
diff --git a/cobalt/black_box_tests/tests/service_worker_post_message_test.py b/cobalt/black_box_tests/tests/service_worker_post_message_test.py
new file mode 100644
index 0000000..c6f6cef
--- /dev/null
+++ b/cobalt/black_box_tests/tests/service_worker_post_message_test.py
@@ -0,0 +1,28 @@
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests Service Worker postMessage() functionality."""
+
+from cobalt.black_box_tests import black_box_tests
+from cobalt.black_box_tests.threaded_web_server import ThreadedWebServer
+
+
+class ServiceWorkerPostMessageTest(black_box_tests.BlackBoxTestCase):
+
+  def test_service_worker_post_message(self):
+    with ThreadedWebServer(binding_address=self.GetBindingAddress()) as server:
+      url = server.GetURL(
+          file_name='testdata/service_worker_post_message_test.html')
+      with self.CreateCobaltRunner(url=url) as runner:
+        runner.WaitForJSTestsSetup()
+        self.assertTrue(runner.JSTestsSucceeded())
diff --git a/cobalt/black_box_tests/tests/worker_post_message_test.py b/cobalt/black_box_tests/tests/worker_post_message_test.py
new file mode 100644
index 0000000..ecd5f3d
--- /dev/null
+++ b/cobalt/black_box_tests/tests/worker_post_message_test.py
@@ -0,0 +1,27 @@
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests Worker postMessage() functionality."""
+
+from cobalt.black_box_tests import black_box_tests
+from cobalt.black_box_tests.threaded_web_server import ThreadedWebServer
+
+
+class WorkerPostMessageTest(black_box_tests.BlackBoxTestCase):
+
+  def test_worker_post_message(self):
+    with ThreadedWebServer(binding_address=self.GetBindingAddress()) as server:
+      url = server.GetURL(file_name='testdata/worker_post_message_test.html')
+      with self.CreateCobaltRunner(url=url) as runner:
+        runner.WaitForJSTestsSetup()
+        self.assertTrue(runner.JSTestsSucceeded())
diff --git a/cobalt/browser/BUILD.gn b/cobalt/browser/BUILD.gn
index 0b66445..5b015e8 100644
--- a/cobalt/browser/BUILD.gn
+++ b/cobalt/browser/BUILD.gn
@@ -154,12 +154,13 @@
     ":browser_switches",
     ":generated_bindings",
     ":generated_types",
-    "//cobalt/account",
     "//cobalt/audio",
     "//cobalt/base",
     "//cobalt/browser/memory_settings:browser_memory_settings",
     "//cobalt/browser/memory_tracker:memory_tracker_tool",
+    "//cobalt/browser/metrics",
     "//cobalt/build:cobalt_build_id",
+    "//cobalt/build:cobalt_build_info",
     "//cobalt/cache",
     "//cobalt/configuration",
     "//cobalt/css_parser",
@@ -196,6 +197,8 @@
     "//cobalt/websocket",
     "//cobalt/worker",
     "//cobalt/xhr",
+    "//components/metrics",
+    "//components/metrics_services_manager",
     "//crypto",
     "//nb",
     "//net",
diff --git a/cobalt/browser/application.cc b/cobalt/browser/application.cc
index 3f5f413..69a52c0 100644
--- a/cobalt/browser/application.cc
+++ b/cobalt/browser/application.cc
@@ -24,6 +24,7 @@
 #include "base/lazy_instance.h"
 #include "base/logging.h"
 #include "base/metrics/statistics_recorder.h"
+#include "base/metrics/user_metrics.h"
 #include "base/optional.h"
 #include "base/path_service.h"
 #include "base/strings/string_number_conversions.h"
@@ -59,11 +60,13 @@
 #include "cobalt/browser/device_authentication.h"
 #include "cobalt/browser/memory_settings/auto_mem_settings.h"
 #include "cobalt/browser/memory_tracker/tool.h"
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager.h"
 #include "cobalt/browser/switches.h"
 #include "cobalt/browser/user_agent_platform_info.h"
 #include "cobalt/browser/user_agent_string.h"
 #include "cobalt/cache/cache.h"
 #include "cobalt/configuration/configuration.h"
+#include "cobalt/h5vcc/h5vcc_crash_log.h"
 #include "cobalt/loader/image/image_decoder.h"
 #include "cobalt/math/size.h"
 #include "cobalt/script/javascript_engine.h"
@@ -73,6 +76,7 @@
 #include "cobalt/system_window/input_event.h"
 #include "cobalt/trace_event/scoped_trace_to_file.h"
 #include "cobalt/watchdog/watchdog.h"
+#include "components/metrics/metrics_service.h"
 #include "starboard/common/device_type.h"
 #include "starboard/common/system_property.h"
 #include "starboard/configuration.h"
@@ -599,35 +603,28 @@
   }
 }
 
-void AddCrashHandlerApplicationState(base::ApplicationState state) {
-  auto crash_handler_extension =
-      static_cast<const CobaltExtensionCrashHandlerApi*>(
-          SbSystemGetExtension(kCobaltExtensionCrashHandlerName));
-  if (!crash_handler_extension) {
-    DLOG(INFO) << "No crash handler extension, not sending application state.";
-    return;
-  }
-
+void AddCrashLogApplicationState(base::ApplicationState state) {
   std::string application_state = std::string(GetApplicationStateString(state));
   application_state.push_back('\0');
 
-  if (crash_handler_extension->version > 1) {
-    if (crash_handler_extension->SetString("application_state",
-                                           application_state.c_str())) {
-      DLOG(INFO) << "Sent application state to crash handler.";
-      return;
+  auto crash_handler_extension =
+      static_cast<const CobaltExtensionCrashHandlerApi*>(
+          SbSystemGetExtension(kCobaltExtensionCrashHandlerName));
+  if (crash_handler_extension && crash_handler_extension->version >= 2) {
+    if (!crash_handler_extension->SetString("application_state",
+                                            application_state.c_str())) {
+      LOG(ERROR) << "Could not send application state to crash handler.";
     }
+    return;
   }
-  DLOG(ERROR) << "Could not send application state to crash handler.";
+
+  // Crash handler is not supported, fallback to crash log dictionary.
+  h5vcc::CrashLogDictionary::GetInstance()->SetString("application_state",
+                                                      application_state);
 }
 
 }  // namespace
 
-// Helper stub to disable histogram tracking in StatisticsRecorder
-struct RecordCheckerStub : public base::RecordHistogramChecker {
-  bool ShouldRecord(uint64_t) const override { return false; }
-};
-
 // Static user logs
 ssize_t Application::available_memory_ = 0;
 int64 Application::lifetime_in_ms_ = 0;
@@ -691,11 +688,6 @@
   std::string language = base::GetSystemLanguage();
   base::LocalizedStrings::GetInstance()->Initialize(language);
 
-  // Disable histogram tracking before TaskScheduler creates StatisticsRecorder
-  // instances.
-  auto record_checker = std::make_unique<RecordCheckerStub>();
-  base::StatisticsRecorder::SetRecordChecker(std::move(record_checker));
-
   // A one-per-process task scheduler is needed for usage of APIs in
   // base/post_task.h which will be used by some net APIs like
   // URLRequestContext;
@@ -706,6 +698,9 @@
       std::make_unique<persistent_storage::PersistentSettings>(
           kPersistentSettingsJson);
 
+  // Initialize telemetry/metrics.
+  InitMetrics();
+
   // Initializes Watchdog.
   watchdog::Watchdog* watchdog =
       watchdog::Watchdog::CreateInstance(persistent_settings_.get());
@@ -727,7 +722,6 @@
   unconsumed_deep_link_ = GetInitialDeepLink();
   DLOG(INFO) << "Initial deep link: " << unconsumed_deep_link_;
 
-  storage::StorageManager::Options storage_manager_options;
   network::NetworkModule::Options network_module_options;
   // Create the main components of our browser.
   BrowserModule::Options options;
@@ -764,7 +758,7 @@
 
 #if defined(ENABLE_DEBUG_COMMAND_LINE_SWITCHES)
   if (command_line->HasSwitch(browser::switches::kNullSavegame)) {
-    storage_manager_options.savegame_options.factory =
+    network_module_options.storage_manager_options.savegame_options.factory =
         &storage::SavegameFake::Create;
   }
 
@@ -798,14 +792,16 @@
   } else {
     partition_key = base::GetApplicationKey(initial_url);
   }
-  storage_manager_options.savegame_options.id = partition_key;
+  network_module_options.storage_manager_options.savegame_options.id =
+      partition_key;
 
   base::Optional<std::string> default_key =
       base::GetApplicationKey(GURL(kDefaultURL));
   if (command_line->HasSwitch(
           browser::switches::kForceMigrationForStoragePartitioning) ||
       partition_key == default_key) {
-    storage_manager_options.savegame_options.fallback_to_default_id = true;
+    network_module_options.storage_manager_options.savegame_options
+        .fallback_to_default_id = true;
   }
 
   // User can specify an extra search path entry for files loaded via file://.
@@ -906,15 +902,11 @@
   options.web_module_options.collect_unload_event_time_callback = base::Bind(
       &Application::CollectUnloadEventTimingInfo, base::Unretained(this));
 
-  account_manager_.reset(new account::AccountManager());
-
-  storage_manager_.reset(new storage::StorageManager(storage_manager_options));
-
   cobalt::browser::UserAgentPlatformInfo platform_info;
 
   network_module_.reset(new network::NetworkModule(
       CreateUserAgentString(platform_info), GetClientHintHeaders(platform_info),
-      storage_manager_.get(), &event_dispatcher_, network_module_options));
+      &event_dispatcher_, network_module_options));
 
   AddCrashHandlerAnnotations(platform_info);
 
@@ -938,15 +930,15 @@
                                                      update_check_delay_sec));
   }
 #endif
-  browser_module_.reset(new BrowserModule(
-      initial_url,
-      (should_preload ? base::kApplicationStateConcealed
-                      : base::kApplicationStateStarted),
-      &event_dispatcher_, account_manager_.get(), network_module_.get(),
+  browser_module_.reset(
+      new BrowserModule(initial_url,
+                        (should_preload ? base::kApplicationStateConcealed
+                                        : base::kApplicationStateStarted),
+                        &event_dispatcher_, network_module_.get(),
 #if SB_IS(EVERGREEN)
-      updater_module_.get(),
+                        updater_module_.get(),
 #endif
-      options));
+                        options));
 
   UpdateUserAgent();
 
@@ -1056,6 +1048,10 @@
   // for the debugger to land.
   watchdog::Watchdog::DeleteInstance();
 
+  // Explicitly delete the global metrics services manager here to give it
+  // an opportunity to clean up late logs and persist metrics.
+  metrics::CobaltMetricsServicesManager::DeleteInstance();
+
 #if defined(ENABLE_DEBUGGER) && defined(STARBOARD_ALLOWS_MEMORY_TRACKING)
   memory_tracker_tool_.reset(NULL);
 #endif  // defined(ENABLE_DEBUGGER) && defined(STARBOARD_ALLOWS_MEMORY_TRACKING)
@@ -1084,6 +1080,8 @@
   event_dispatcher_.RemoveEventCallback(
       base::DateTimeConfigurationChangedEvent::TypeId(),
       on_date_time_configuration_changed_event_callback_);
+  browser_module_.reset();
+  network_module_.reset();
 }
 
 void Application::Start(SbTimeMonotonic timestamp) {
@@ -1212,7 +1210,7 @@
     case kSbEventTypeStop:
       LOG(INFO) << "Got quit event.";
       if (watchdog) watchdog->UpdateState(base::kApplicationStateStopped);
-      AddCrashHandlerApplicationState(base::kApplicationStateStopped);
+      AddCrashLogApplicationState(base::kApplicationStateStopped);
       Quit();
       LOG(INFO) << "Finished quitting.";
       break;
@@ -1287,7 +1285,7 @@
       return;
   }
   if (watchdog) watchdog->UpdateState(browser_module_->GetApplicationState());
-  AddCrashHandlerApplicationState(browser_module_->GetApplicationState());
+  AddCrashLogApplicationState(browser_module_->GetApplicationState());
 }
 
 void Application::OnWindowSizeChangedEvent(const base::Event* event) {
@@ -1549,6 +1547,30 @@
   }
 }
 
+void Application::InitMetrics() {
+  // Must be called early as it initializes global state which is then read by
+  // all threads without synchronization.
+  // RecordAction task runner must be called before metric initialization.
+  base::SetRecordActionTaskRunner(base::ThreadTaskRunnerHandle::Get());
+  metrics_services_manager_ =
+      metrics::CobaltMetricsServicesManager::GetInstance();
+  // Before initializing metrics manager, set any persisted settings like if
+  // it's enabled or upload interval.
+  bool is_metrics_enabled = persistent_settings_->GetPersistentSettingAsBool(
+      metrics::kMetricEnabledSettingName, false);
+  metrics_services_manager_->SetUploadInterval(
+      persistent_settings_->GetPersistentSettingAsInt(
+          metrics::kMetricEventIntervalSettingName, 300));
+  metrics_services_manager_->ToggleMetricsEnabled(is_metrics_enabled);
+  // Metric recording state initialization _must_ happen before we bootstrap
+  // otherwise we crash.
+  metrics_services_manager_->GetMetricsService()
+      ->InitializeMetricsRecordingState();
+  // UpdateUploadPermissions bootstraps the whole metric reporting, scheduling,
+  // and uploading cycle.
+  metrics_services_manager_->UpdateUploadPermissions(is_metrics_enabled);
+}
+
 }  // namespace browser
 }  // namespace cobalt
 
diff --git a/cobalt/browser/application.h b/cobalt/browser/application.h
index 04a08ca..7ca2d5d 100644
--- a/cobalt/browser/application.h
+++ b/cobalt/browser/application.h
@@ -24,10 +24,10 @@
 #include "base/message_loop/message_loop.h"
 #include "base/synchronization/lock.h"
 #include "base/threading/thread_checker.h"
-#include "cobalt/account/account_manager.h"
 #include "cobalt/base/event_dispatcher.h"
 #include "cobalt/browser/browser_module.h"
 #include "cobalt/browser/memory_tracker/tool.h"
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager.h"
 #include "cobalt/network/network_module.h"
 #include "cobalt/persistent_storage/persistent_settings.h"
 #include "cobalt/system_window/system_window.h"
@@ -96,12 +96,6 @@
   // A conduit for system events.
   base::EventDispatcher event_dispatcher_;
 
-  // Account manager.
-  std::unique_ptr<account::AccountManager> account_manager_;
-
-  // Storage manager used by the network module below.
-  std::unique_ptr<storage::StorageManager> storage_manager_;
-
   // Sets up the network component for requesting internet resources.
   std::unique_ptr<network::NetworkModule> network_module_;
 
@@ -231,6 +225,15 @@
   void DispatchDeepLink(const char* link, SbTimeMonotonic timestamp);
   void DispatchDeepLinkIfNotConsumed();
 
+
+  // Initializes all code necessary to start telemetry/metrics gathering and
+  // reporting. See go/cobalt-telemetry.
+  void InitMetrics();
+
+  // Reference to the current metrics manager, the highest level control point
+  // for metrics/telemetry.
+  metrics::CobaltMetricsServicesManager* metrics_services_manager_;
+
   DISALLOW_COPY_AND_ASSIGN(Application);
 };
 
diff --git a/cobalt/browser/browser_module.cc b/cobalt/browser/browser_module.cc
index a4f3934..e8f1c28 100644
--- a/cobalt/browser/browser_module.cc
+++ b/cobalt/browser/browser_module.cc
@@ -214,7 +214,6 @@
 BrowserModule::BrowserModule(const GURL& url,
                              base::ApplicationState initial_application_state,
                              base::EventDispatcher* event_dispatcher,
-                             account::AccountManager* account_manager,
                              network::NetworkModule* network_module,
 #if SB_IS(EVERGREEN)
                              updater::UpdaterModule* updater_module,
@@ -226,7 +225,6 @@
       options_(options),
       self_message_loop_(base::MessageLoop::current()),
       event_dispatcher_(event_dispatcher),
-      account_manager_(account_manager),
       is_rendered_(false),
       is_web_module_rendered_(false),
       can_play_type_handler_(media::MediaModule::CreateCanPlayTypeHandler()),
@@ -459,7 +457,17 @@
   SbCoreDumpUnregisterHandler(BrowserModule::CoreDumpHandler, this);
 #endif
 
+#if defined(ENABLE_DEBUGGER)
+  if (debug_console_) {
+    lifecycle_observers_.RemoveObserver(debug_console_.get());
+  }
+  debug_console_.reset();
+#endif
+  DestroySplashScreen();
   // Make sure the WebModule is destroyed before the ServiceWorkerRegistry
+  if (web_module_) {
+    lifecycle_observers_.RemoveObserver(web_module_.get());
+  }
   web_module_.reset();
 }
 
@@ -544,7 +552,7 @@
   // Show a splash screen while we're waiting for the web page to load.
   const ViewportSize viewport_size = GetViewportSize();
 
-  DestroySplashScreen(base::TimeDelta());
+  DestroySplashScreen();
   if (options_.enable_splash_screen_on_reloads ||
       main_web_module_generation_ == 1) {
     base::Optional<std::string> topic = SetSplashScreenTopicFallback(url);
@@ -621,8 +629,8 @@
 
   options.web_options.web_settings = &web_settings_;
   options.web_options.network_module = network_module_;
-  options.web_options.service_worker_jobs =
-      service_worker_registry_->service_worker_jobs();
+  options.web_options.service_worker_context =
+      service_worker_registry_->service_worker_context();
   options.web_options.platform_info = platform_info_.get();
   web_module_.reset(new WebModule("MainWebModule"));
   // Wait for service worker to start if one exists.
@@ -799,7 +807,7 @@
   if (splash_screen_) {
     if (on_screen_keyboard_show_called_) {
       // Hide the splash screen as quickly as possible.
-      DestroySplashScreen(base::TimeDelta());
+      DestroySplashScreen();
     } else if (!splash_screen_->ShutdownSignaled()) {
       splash_screen_->Shutdown();
     }
@@ -947,7 +955,7 @@
   // Only inject shown events to the main WebModule.
   on_screen_keyboard_show_called_ = true;
   if (splash_screen_ && splash_screen_->ShutdownSignaled()) {
-    DestroySplashScreen(base::TimeDelta());
+    DestroySplashScreen();
   }
   if (web_module_) {
     web_module_->InjectOnScreenKeyboardShownEvent(event->ticket());
@@ -1364,7 +1372,7 @@
     }
     splash_screen_layer_->Reset();
     SubmitCurrentRenderTreeToRenderer();
-    splash_screen_.reset(NULL);
+    splash_screen_.reset();
   }
 }
 
@@ -1774,6 +1782,11 @@
   // First freeze all our web modules which implies that they will release
   // their resource provider and all resources created through it.
   FOR_EACH_OBSERVER(LifecycleObserver, lifecycle_observers_, Freeze(timestamp));
+
+  if (network_module_) {
+    // Synchronously wait for storage to flush before returning from freezing.
+    network_module_->storage_manager()->FlushSynchronous();
+  }
 }
 
 void BrowserModule::RevealInternal(SbTimeMonotonic timestamp) {
@@ -2072,7 +2085,6 @@
 #if SB_IS(EVERGREEN)
   h5vcc_settings.updater_module = updater_module_;
 #endif
-  h5vcc_settings.account_manager = account_manager_;
   h5vcc_settings.event_dispatcher = event_dispatcher_;
 
   h5vcc_settings.user_agent_data = settings->context()
diff --git a/cobalt/browser/browser_module.h b/cobalt/browser/browser_module.h
index 4b01a90..00fd5ce 100644
--- a/cobalt/browser/browser_module.h
+++ b/cobalt/browser/browser_module.h
@@ -26,7 +26,6 @@
 #include "base/synchronization/waitable_event.h"
 #include "base/threading/thread.h"
 #include "base/timer/timer.h"
-#include "cobalt/account/account_manager.h"
 #include "cobalt/base/accessibility_caption_settings_changed_event.h"
 #include "cobalt/base/application_state.h"
 #include "cobalt/base/date_time_configuration_changed_event.h"
@@ -66,7 +65,6 @@
 #include "cobalt/render_tree/resource_provider_stub.h"
 #include "cobalt/renderer/renderer_module.h"
 #include "cobalt/script/array_buffer.h"
-#include "cobalt/storage/storage_manager.h"
 #include "cobalt/system_window/system_window.h"
 #include "cobalt/ui_navigation/scroll_engine/scroll_engine.h"
 #include "cobalt/web/web_settings.h"
@@ -127,7 +125,6 @@
   BrowserModule(const GURL& url,
                 base::ApplicationState initial_application_state,
                 base::EventDispatcher* event_dispatcher,
-                account::AccountManager* account_manager,
                 network::NetworkModule* network_module,
 #if SB_IS(EVERGREEN)
                 updater::UpdaterModule* updater_module,
@@ -342,7 +339,7 @@
   bool TryURLHandlers(const GURL& url);
 
   // Destroys the splash screen, if currently displayed.
-  void DestroySplashScreen(base::TimeDelta close_time);
+  void DestroySplashScreen(base::TimeDelta close_time = base::TimeDelta());
 
   // Called when web module has received window.close().
   void OnWindowClose(base::TimeDelta close_time);
@@ -517,8 +514,6 @@
 
   base::EventDispatcher* event_dispatcher_;
 
-  account::AccountManager* account_manager_;
-
   // Whether the browser module has yet rendered anything. On the very first
   // render, we hide the system splash screen.
   bool is_rendered_;
diff --git a/cobalt/browser/client_hint_headers.cc b/cobalt/browser/client_hint_headers.cc
index 8dc7dcc..99794d5 100644
--- a/cobalt/browser/client_hint_headers.cc
+++ b/cobalt/browser/client_hint_headers.cc
@@ -43,10 +43,11 @@
     const UserAgentPlatformInfo& platform_info) {
   std::vector<std::string> headers;
 
-  AddHeader(headers, "Firmware-Version-Details",
-            platform_info.firmware_version_details());
+  AddHeader(headers, "Android-Build-Fingerprint",
+            platform_info.android_build_fingerprint());
 
-  AddHeader(headers, "OS-Experience", platform_info.os_experience());
+  AddHeader(headers, "Android-OS-Experience",
+            platform_info.android_os_experience());
 
   return headers;
 }
diff --git a/cobalt/browser/client_hint_headers_test.cc b/cobalt/browser/client_hint_headers_test.cc
index f96626a..7cb26e9 100644
--- a/cobalt/browser/client_hint_headers_test.cc
+++ b/cobalt/browser/client_hint_headers_test.cc
@@ -27,14 +27,14 @@
 
 TEST(ClientHintHeadersTest, GetClientHintHeaders) {
   UserAgentPlatformInfo platform_info;
-  platform_info.set_firmware_version_details("abc/def:123.456/xy-z");
-  platform_info.set_os_experience("Amati");
+  platform_info.set_android_build_fingerprint("abc/def:123.456/xy-z");
+  platform_info.set_android_os_experience("Amati");
 
   std::vector<std::string> headers = GetClientHintHeaders(platform_info);
   EXPECT_THAT(headers,
               UnorderedElementsAre(
-                  "Sec-CH-UA-Co-Firmware-Version-Details:abc/def:123.456/xy-z",
-                  "Sec-CH-UA-Co-OS-Experience:Amati"));
+                  "Sec-CH-UA-Co-Android-Build-Fingerprint:abc/def:123.456/xy-z",
+                  "Sec-CH-UA-Co-Android-OS-Experience:Amati"));
 }
 
 }  // namespace
diff --git a/cobalt/browser/idl_files.gni b/cobalt/browser/idl_files.gni
index b64086d..4663d09 100644
--- a/cobalt/browser/idl_files.gni
+++ b/cobalt/browser/idl_files.gni
@@ -162,6 +162,7 @@
   "//cobalt/h5vcc/h5vcc_audio_config_array.idl",
   "//cobalt/h5vcc/h5vcc_crash_log.idl",
   "//cobalt/h5vcc/h5vcc_deep_link_event_target.idl",
+  "//cobalt/h5vcc/h5vcc_metrics.idl",
   "//cobalt/h5vcc/h5vcc_platform_service.idl",
   "//cobalt/h5vcc/h5vcc_runtime.idl",
   "//cobalt/h5vcc/h5vcc_runtime_event_target.idl",
@@ -312,6 +313,7 @@
   "//cobalt/encoding/text_decoder_options.idl",
   "//cobalt/encoding/text_encoder_encode_into_result.idl",
   "//cobalt/h5vcc/h5vcc_crash_type.idl",
+  "//cobalt/h5vcc/h5vcc_metric_type.idl",
   "//cobalt/h5vcc/h5vcc_storage_resource_type_quota_bytes_dictionary.idl",
   "//cobalt/h5vcc/h5vcc_storage_set_quota_response.idl",
   "//cobalt/h5vcc/h5vcc_storage_write_test_response.idl",
diff --git a/cobalt/browser/lifecycle_console_commands.cc b/cobalt/browser/lifecycle_console_commands.cc
index 3784e29..0104971 100644
--- a/cobalt/browser/lifecycle_console_commands.cc
+++ b/cobalt/browser/lifecycle_console_commands.cc
@@ -23,24 +23,41 @@
 namespace cobalt {
 namespace browser {
 
-const char kPauseCommand[] = "pause";
-const char kPauseCommandShortHelp[] = "Sends a request to pause Cobalt.";
-const char kPauseCommandLongHelp[] =
-    "Sends a request to the platform to pause Cobalt, indicating that it is "
+const char kBlurCommand[] = "blur";
+const char kBlurCommandShortHelp[] = "Sends a request to blur Cobalt.";
+const char kBlurCommandLongHelp[] =
+    "Sends a request to the platform to blur Cobalt, indicating that it is "
     "not in focus and sending a blur event to the web application.";
 
-const char kUnpauseCommand[] = "unpause";
-const char kUnpauseCommandShortHelp[] = "Sends a request to unpause Cobalt.";
-const char kUnpauseCommandLongHelp[] =
-    "Sends a request to the platform to unpause Cobalt, resulting in a focus "
+const char kFocusCommand[] = "focus";
+const char kFocusCommandShortHelp[] = "Sends a request to focus Cobalt.";
+const char kFocusCommandLongHelp[] =
+    "Sends a request to the platform to focus Cobalt, resulting in a Focus "
     "event being sent to the web application.";
 
-const char kSuspendCommand[] = "suspend";
-const char kSuspendCommandShortHelp[] = "Sends a request to suspend Cobalt.";
-const char kSuspendCommandLongHelp[] =
-    "Sends a request to the platform to suspend Cobalt, indicating that it is "
+const char kConcealCommand[] = "conceal";
+const char kConcealCommandShortHelp[] = "Sends a request to conceal Cobalt.";
+const char kConcealCommandLongHelp[] =
+    "Sends a request to the platform to conceal Cobalt, indicating that it is "
     "not visible and sending a hidden event to the web application.  Note that "
-    "Cobalt may become unresponsive after this call and you will need to "
+    "Cobalt may become unresponsive after this call in which case you will "
+    "need to resume it in a platform-specific way.";
+
+const char kFreezeCommand[] = "freeze";
+const char kFreezeCommandShortHelp[] = "Sends a request to freeze Cobalt.";
+const char kFreezeCommandLongHelp[] =
+    "Sends a request to the platform to freeze Cobalt, indicating that it is "
+    "not visible, sending a hidden event to the web application, and halt "
+    "processing.  Note that Cobalt may become unresponsive after this call in "
+    "which case you will need to resume it in a platform-specific way.";
+
+const char kRevealCommand[] = "reveal";
+const char kRevealCommandShortHelp[] = "Sends a request to reveal Cobalt.";
+const char kRevealCommandLongHelp[] =
+    "Sends a request to the platform to reveal Cobalt, indicating that it is "
+    "visible but not focues, and sending a visible event to the web "
+    "application.  Note that "
+    "Cobalt may be unresponsive in which case you will need to "
     "resume it in a platform-specific way.";
 
 const char kQuitCommand[] = "quit";
@@ -50,31 +67,37 @@
     "ending the process (peacefully).";
 
 namespace {
-// This is temporary that will be changed in later CLs, for mapping Starboard
-// Concealed state support onto Cobalt without Concealed state support to be
-// able to test the former.
-void OnPause(const std::string& /*message*/) { SbSystemRequestBlur(); }
-
-void OnUnpause(const std::string& /*message*/) { SbSystemRequestFocus(); }
-
-void OnSuspend(const std::string& /*message*/) {
-  LOG(INFO) << "Concealing Cobalt through the console, but you will need to "
-            << "reveal Cobalt using a platform-specific method.";
+void OnBlur(const std::string&) { SbSystemRequestBlur(); }
+void OnFocus(const std::string&) { SbSystemRequestFocus(); }
+void OnConceal(const std::string&) {
+  LOG(WARNING)
+      << "Concealing Cobalt through the console.  Note that Cobalt may "
+         "become unresponsive after this call in which case you will "
+         "need to resume it in a platform-specific way.";
   SbSystemRequestConceal();
 }
-
+void OnFreeze(const std::string&) {
+  LOG(WARNING) << "Freezing Cobalt through the console.  Note that Cobalt may "
+                  "become unresponsive after this call in which case you will "
+                  "need to resume it in a platform-specific way.";
+  SbSystemRequestFreeze();
+}
+void OnReveal(const std::string&) { SbSystemRequestReveal(); }
 void OnQuit(const std::string& /*message*/) { SbSystemRequestStop(0); }
 }  // namespace
 
 LifecycleConsoleCommands::LifecycleConsoleCommands()
-    : pause_command_handler_(kPauseCommand, base::Bind(&OnPause),
-                             kPauseCommandShortHelp, kPauseCommandLongHelp),
-      unpause_command_handler_(kUnpauseCommand, base::Bind(OnUnpause),
-                               kUnpauseCommandShortHelp,
-                               kUnpauseCommandLongHelp),
-      suspend_command_handler_(kSuspendCommand, base::Bind(OnSuspend),
-                               kSuspendCommandShortHelp,
-                               kSuspendCommandLongHelp),
+    : blur_command_handler_(kBlurCommand, base::Bind(OnBlur),
+                            kBlurCommandShortHelp, kBlurCommandLongHelp),
+      focus_command_handler_(kFocusCommand, base::Bind(OnFocus),
+                             kFocusCommandShortHelp, kFocusCommandLongHelp),
+      conceal_command_handler_(kConcealCommand, base::Bind(OnConceal),
+                               kConcealCommandShortHelp,
+                               kConcealCommandLongHelp),
+      freeze_command_handler_(kFreezeCommand, base::Bind(OnFreeze),
+                              kFreezeCommandShortHelp, kFreezeCommandLongHelp),
+      reveal_command_handler_(kRevealCommand, base::Bind(OnReveal),
+                              kRevealCommandShortHelp, kRevealCommandLongHelp),
       quit_command_handler_(kQuitCommand, base::Bind(OnQuit),
                             kQuitCommandShortHelp, kQuitCommandLongHelp) {}
 
diff --git a/cobalt/browser/lifecycle_console_commands.h b/cobalt/browser/lifecycle_console_commands.h
index 3e8bac4..da2015b 100644
--- a/cobalt/browser/lifecycle_console_commands.h
+++ b/cobalt/browser/lifecycle_console_commands.h
@@ -29,11 +29,12 @@
   LifecycleConsoleCommands();
 
  private:
-  debug::console::ConsoleCommandManager::CommandHandler pause_command_handler_;
+  debug::console::ConsoleCommandManager::CommandHandler blur_command_handler_;
+  debug::console::ConsoleCommandManager::CommandHandler focus_command_handler_;
   debug::console::ConsoleCommandManager::CommandHandler
-      unpause_command_handler_;
-  debug::console::ConsoleCommandManager::CommandHandler
-      suspend_command_handler_;
+      conceal_command_handler_;
+  debug::console::ConsoleCommandManager::CommandHandler freeze_command_handler_;
+  debug::console::ConsoleCommandManager::CommandHandler reveal_command_handler_;
   debug::console::ConsoleCommandManager::CommandHandler quit_command_handler_;
 };
 
diff --git a/cobalt/browser/main.cc b/cobalt/browser/main.cc
index 7f87bc0..7d0d0a0 100644
--- a/cobalt/browser/main.cc
+++ b/cobalt/browser/main.cc
@@ -86,6 +86,7 @@
   LOG(INFO) << "Stopping application.";
   delete g_application;
   g_application = NULL;
+  LOG(INFO) << "Application stopped.";
 }
 
 void HandleStarboardEvent(const SbEvent* starboard_event) {
diff --git a/cobalt/browser/memory_settings/auto_mem.h b/cobalt/browser/memory_settings/auto_mem.h
index 8014e14..64ca1e1 100644
--- a/cobalt/browser/memory_settings/auto_mem.h
+++ b/cobalt/browser/memory_settings/auto_mem.h
@@ -26,7 +26,6 @@
 #include "cobalt/browser/memory_settings/auto_mem_settings.h"
 #include "cobalt/browser/memory_settings/memory_settings.h"
 #include "cobalt/math/size.h"
-#include "testing/gtest/include/gtest/gtest_prod.h"
 
 namespace cobalt {
 namespace browser {
diff --git a/cobalt/browser/metrics/BUILD.gn b/cobalt/browser/metrics/BUILD.gn
new file mode 100644
index 0000000..3f25f1a
--- /dev/null
+++ b/cobalt/browser/metrics/BUILD.gn
@@ -0,0 +1,65 @@
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http:#www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+static_library("metrics") {
+  sources = [
+    "cobalt_enabled_state_provider.cc",
+    "cobalt_enabled_state_provider.h",
+    "cobalt_metrics_log_uploader.cc",
+    "cobalt_metrics_log_uploader.h",
+    "cobalt_metrics_service_client.cc",
+    "cobalt_metrics_service_client.h",
+    "cobalt_metrics_services_manager.cc",
+    "cobalt_metrics_services_manager.h",
+    "cobalt_metrics_services_manager_client.cc",
+    "cobalt_metrics_services_manager_client.h",
+    "cobalt_metrics_uploader_callback.h",
+  ]
+
+  deps = [
+    "//base",
+    "//cobalt/browser:generated_types",
+    "//cobalt/h5vcc:metric_event_handler_wrapper",
+    "//components/metrics",
+    "//components/metrics_services_manager",
+    "//components/prefs",
+    "//third_party/metrics_proto",
+  ]
+}
+
+target(gtest_target_type, "metrics_test") {
+  testonly = true
+  has_pedantic_warnings = true
+
+  sources = [
+    "cobalt_metrics_log_uploader_test.cc",
+    "cobalt_metrics_service_client_test.cc",
+    "cobalt_metrics_services_manager_client_test.cc",
+  ]
+
+  deps = [
+    ":metrics",
+    "//base",
+    "//cobalt/browser:generated_types",
+    "//cobalt/h5vcc",
+    "//cobalt/h5vcc:metric_event_handler_wrapper",
+    "//cobalt/test:run_all_unittests",
+    "//components/metrics",
+    "//components/prefs:test_support",
+    "//testing/gmock",
+    "//testing/gtest",
+    "//third_party/metrics_proto",
+    "//third_party/zlib/google:compression_utils",
+  ]
+}
diff --git a/cobalt/browser/metrics/cobalt_enabled_state_provider.cc b/cobalt/browser/metrics/cobalt_enabled_state_provider.cc
new file mode 100644
index 0000000..ede4035
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_enabled_state_provider.cc
@@ -0,0 +1,41 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_enabled_state_provider.h"
+
+#include "components/metrics/enabled_state_provider.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+bool CobaltEnabledStateProvider::IsConsentGiven() const {
+  return is_consent_given_;
+}
+
+bool CobaltEnabledStateProvider::IsReportingEnabled() const {
+  return is_reporting_enabled_;
+}
+
+void CobaltEnabledStateProvider::SetConsentGiven(bool is_consent_given) {
+  is_consent_given_ = is_consent_given;
+}
+void CobaltEnabledStateProvider::SetReportingEnabled(
+    bool is_reporting_enabled) {
+  is_reporting_enabled_ = is_reporting_enabled;
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_enabled_state_provider.h b/cobalt/browser/metrics/cobalt_enabled_state_provider.h
new file mode 100644
index 0000000..2bac92f
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_enabled_state_provider.h
@@ -0,0 +1,62 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_BROWSER_METRICS_COBALT_ENABLED_STATE_PROVIDER_H_
+#define COBALT_BROWSER_METRICS_COBALT_ENABLED_STATE_PROVIDER_H_
+
+#include "components/metrics/enabled_state_provider.h"
+#include "components/prefs/pref_service.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+// A Cobalt implementation of EnabledStateProvider. This class is the primary
+// entry point into enabling/disabling metrics collection and uploading.
+class CobaltEnabledStateProvider : public ::metrics::EnabledStateProvider {
+ public:
+  explicit CobaltEnabledStateProvider(bool is_consent_given,
+                                      bool is_reporting_enabled)
+      : is_consent_given_(is_consent_given),
+        is_reporting_enabled_(is_reporting_enabled) {}
+
+  CobaltEnabledStateProvider(const CobaltEnabledStateProvider&) = delete;
+  CobaltEnabledStateProvider& operator=(const CobaltEnabledStateProvider&) =
+      delete;
+
+  ~CobaltEnabledStateProvider() override{};
+
+  // Indicates user consent to collect and report metrics. In Cobalt, consent
+  // is inherited through the web application, so this is usually true.
+  bool IsConsentGiven() const override;
+
+  // Whether metric collection is enabled. This is what controls
+  // recording/aggregation of metrics.
+  bool IsReportingEnabled() const override;
+
+  // Setters for consent and reporting controls.
+  void SetConsentGiven(bool is_consent_given);
+  void SetReportingEnabled(bool is_reporting_enabled);
+
+ private:
+  bool is_consent_given_ = false;
+  bool is_reporting_enabled_ = false;
+};
+
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
+
+#endif  // COBALT_BROWSER_METRICS_COBALT_ENABLED_STATE_PROVIDER_H_
diff --git a/cobalt/browser/metrics/cobalt_metrics_log_uploader.cc b/cobalt/browser/metrics/cobalt_metrics_log_uploader.cc
new file mode 100644
index 0000000..2076f6b
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_log_uploader.cc
@@ -0,0 +1,61 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_log_uploader.h"
+
+#include "base/logging.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "cobalt/h5vcc/h5vcc_metric_type.h"
+#include "components/metrics/log_decoder.h"
+#include "components/metrics/metrics_log_uploader.h"
+#include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
+#include "third_party/metrics_proto/reporting_info.pb.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+CobaltMetricsLogUploader::CobaltMetricsLogUploader(
+    ::metrics::MetricsLogUploader::MetricServiceType service_type,
+    const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete)
+    : service_type_(service_type), on_upload_complete_(on_upload_complete) {}
+
+void CobaltMetricsLogUploader::UploadLog(
+    const std::string& compressed_log_data, const std::string& log_hash,
+    const ::metrics::ReportingInfo& reporting_info) {
+  if (service_type_ == ::metrics::MetricsLogUploader::UMA) {
+    std::string uncompressed_serialized_proto;
+    ::metrics::DecodeLogData(compressed_log_data,
+                             &uncompressed_serialized_proto);
+    if (upload_handler_ != nullptr) {
+      upload_handler_->Run(h5vcc::H5vccMetricType::kH5vccMetricTypeUma,
+                           uncompressed_serialized_proto);
+    }
+  }
+
+  // Arguments to callback don't matter much here as we're not really doing
+  // anything but forwarding to the H5vcc API. Run(http response code, net
+  // code, and was https).
+  on_upload_complete_.Run(/*status*/ 200, /* error_code */ 0,
+                          /*was_https*/ true);
+}
+
+void CobaltMetricsLogUploader::SetOnUploadHandler(
+    const CobaltMetricsUploaderCallback* upload_handler) {
+  upload_handler_ = upload_handler;
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_log_uploader.h b/cobalt/browser/metrics/cobalt_metrics_log_uploader.h
new file mode 100644
index 0000000..fa71662
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_log_uploader.h
@@ -0,0 +1,68 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_BROWSER_METRICS_COBALT_METRICS_LOG_UPLOADER_H_
+#define COBALT_BROWSER_METRICS_COBALT_METRICS_LOG_UPLOADER_H_
+
+#include <string>
+
+#include "base/callback.h"
+#include "base/macros.h"
+#include "base/strings/string_piece.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "cobalt/h5vcc/metric_event_handler_wrapper.h"
+#include "components/metrics/metrics_log_uploader.h"
+#include "third_party/metrics_proto/reporting_info.pb.h"
+
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+class ReportingInfo;
+
+// A Cobalt implementation of MetricsLogUploader that intercepts metric's logs
+// when they're ready to be sent to the server and forwards them to the web
+// client via the H5vcc API.
+class CobaltMetricsLogUploader : public ::metrics::MetricsLogUploader {
+ public:
+  CobaltMetricsLogUploader(
+      ::metrics::MetricsLogUploader::MetricServiceType service_type,
+      const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete);
+
+  virtual ~CobaltMetricsLogUploader() {}
+
+  // Uploads a log with the specified |compressed_log_data| and |log_hash|.
+  // |log_hash| is expected to be the hex-encoded SHA1 hash of the log data
+  // before compression.
+  void UploadLog(const std::string& compressed_log_data,
+                 const std::string& log_hash,
+                 const ::metrics::ReportingInfo& reporting_info);
+
+  // Sets the event handler wrapper to be called when metrics are ready for
+  // upload. This should be the JavaScript H5vcc callback implementation.
+  void SetOnUploadHandler(
+      const CobaltMetricsUploaderCallback* metric_event_handler);
+
+ private:
+  const ::metrics::MetricsLogUploader::MetricServiceType service_type_;
+  const ::metrics::MetricsLogUploader::UploadCallback on_upload_complete_;
+  const CobaltMetricsUploaderCallback* upload_handler_ = nullptr;
+};
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
+
+#endif  // COBALT_BROWSER_METRICS_COBALT_METRICS_LOG_UPLOADER_H_
diff --git a/cobalt/browser/metrics/cobalt_metrics_log_uploader_test.cc b/cobalt/browser/metrics/cobalt_metrics_log_uploader_test.cc
new file mode 100644
index 0000000..21f2770
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_log_uploader_test.cc
@@ -0,0 +1,115 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_log_uploader.h"
+
+#include <memory>
+
+#include "base/test/mock_callback.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "cobalt/h5vcc/h5vcc_metrics.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
+#include "third_party/metrics_proto/reporting_info.pb.h"
+#include "third_party/zlib/google/compression_utils.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+using cobalt::h5vcc::H5vccMetrics;
+using cobalt::h5vcc::MetricEventHandler;
+using cobalt::h5vcc::MetricEventHandlerWrapper;
+using ::testing::_;
+using ::testing::Eq;
+using ::testing::StrEq;
+using ::testing::StrictMock;
+
+
+class CobaltMetricsLogUploaderTest : public ::testing::Test {
+ public:
+  void SetUp() override {
+    uploader_ = std::make_unique<CobaltMetricsLogUploader>(
+        ::metrics::MetricsLogUploader::MetricServiceType::UMA,
+        base::Bind(&CobaltMetricsLogUploaderTest::UploadCompleteCallback,
+                   base::Unretained(this)));
+  }
+
+  void TearDown() override {}
+
+  void UploadCompleteCallback(int response_code, int error_code,
+                              bool was_https) {
+    callback_count_++;
+  }
+
+ protected:
+  std::unique_ptr<CobaltMetricsLogUploader> uploader_;
+  int callback_count_ = 0;
+};
+
+TEST_F(CobaltMetricsLogUploaderTest, TriggersUploadHandler) {
+  base::MockCallback<CobaltMetricsUploaderCallback> mock_upload_handler;
+  const auto cb = mock_upload_handler.Get();
+  uploader_->SetOnUploadHandler(&cb);
+  ::metrics::ReportingInfo dummy_reporting_info;
+  ::metrics::ChromeUserMetricsExtension uma_log;
+  uma_log.set_session_id(1234);
+  uma_log.set_client_id(1234);
+  std::string compressed_message;
+  compression::GzipCompress(uma_log.SerializeAsString(), &compressed_message);
+  EXPECT_CALL(mock_upload_handler,
+              Run(Eq(h5vcc::H5vccMetricType::kH5vccMetricTypeUma),
+                  StrEq(uma_log.SerializeAsString())))
+      .Times(1);
+  uploader_->UploadLog(compressed_message, "fake_hash", dummy_reporting_info);
+  ASSERT_EQ(callback_count_, 1);
+
+  ::metrics::ChromeUserMetricsExtension uma_log2;
+  uma_log2.set_session_id(456);
+  uma_log2.set_client_id(567);
+  std::string compressed_message2;
+  compression::GzipCompress(uma_log2.SerializeAsString(), &compressed_message2);
+  EXPECT_CALL(mock_upload_handler,
+              Run(Eq(h5vcc::H5vccMetricType::kH5vccMetricTypeUma),
+                  StrEq(uma_log2.SerializeAsString())))
+      .Times(1);
+  uploader_->UploadLog(compressed_message2, "fake_hash", dummy_reporting_info);
+  ASSERT_EQ(callback_count_, 2);
+}
+
+TEST_F(CobaltMetricsLogUploaderTest, UnknownMetricTypeDoesntTriggerUpload) {
+  uploader_.reset(new CobaltMetricsLogUploader(
+      ::metrics::MetricsLogUploader::MetricServiceType::UKM,
+      base::Bind(&CobaltMetricsLogUploaderTest::UploadCompleteCallback,
+                 base::Unretained(this))));
+  base::MockCallback<CobaltMetricsUploaderCallback> mock_upload_handler;
+  const auto cb = mock_upload_handler.Get();
+  uploader_->SetOnUploadHandler(&cb);
+  ::metrics::ReportingInfo dummy_reporting_info;
+  ::metrics::ChromeUserMetricsExtension uma_log;
+  uma_log.set_session_id(1234);
+  uma_log.set_client_id(1234);
+  std::string compressed_message;
+  compression::GzipCompress(uma_log.SerializeAsString(), &compressed_message);
+  EXPECT_CALL(mock_upload_handler, Run(_, _)).Times(0);
+  uploader_->UploadLog(compressed_message, "fake_hash", dummy_reporting_info);
+  // Even though we don't upload this log, we still need to trigger the complete
+  // callback so the metric code can keep running.
+  ASSERT_EQ(callback_count_, 1);
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_service_client.cc b/cobalt/browser/metrics/cobalt_metrics_service_client.cc
new file mode 100644
index 0000000..2b4d21a
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_service_client.cc
@@ -0,0 +1,216 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_service_client.h"
+
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "base/callback.h"
+#include "base/memory/singleton.h"
+#include "base/strings/string16.h"
+#include "base/time/time.h"
+#include "cobalt/browser/metrics/cobalt_enabled_state_provider.h"
+#include "cobalt/browser/metrics/cobalt_metrics_log_uploader.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "components/metrics/enabled_state_provider.h"
+#include "components/metrics/metrics_log_uploader.h"
+#include "components/metrics/metrics_pref_names.h"
+#include "components/metrics/metrics_reporting_default_state.h"
+#include "components/metrics/metrics_service.h"
+#include "components/metrics/metrics_service_client.h"
+#include "components/metrics/metrics_state_manager.h"
+#include "components/prefs/in_memory_pref_store.h"
+#include "components/prefs/pref_registry_simple.h"
+#include "components/prefs/pref_service.h"
+#include "components/prefs/pref_service_factory.h"
+#include "third_party/metrics_proto/system_profile.pb.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+// The interval in between upload attempts. That is, every interval in which
+// we package up the new, unlogged, metrics and attempt uploading them. In
+// Cobalt's case, this is the shortest interval in which we'll call the H5vcc
+// Upload Handler.
+const int kStandardUploadIntervalSeconds = 5 * 60;  // 5 minutes.
+
+void CobaltMetricsServiceClient::SetOnUploadHandler(
+    const CobaltMetricsUploaderCallback* uploader_callback) {
+  upload_handler_ = uploader_callback;
+  if (log_uploader_) {
+    log_uploader_->SetOnUploadHandler(upload_handler_);
+  }
+}
+
+CobaltMetricsServiceClient::CobaltMetricsServiceClient(
+    ::metrics::MetricsStateManager* state_manager, PrefService* local_state)
+    : metrics_state_manager_(state_manager) {
+  metrics_service_ = std::make_unique<::metrics::MetricsService>(
+      metrics_state_manager_, this, local_state);
+}
+
+::metrics::MetricsService* CobaltMetricsServiceClient::GetMetricsService() {
+  return metrics_service_.get();
+}
+
+ukm::UkmService* CobaltMetricsServiceClient::GetUkmService() {
+  // TODO(b/284467142): UKM disabled in Cobalt currently, replace when UKM
+  // is supported.
+  return nullptr;
+}
+
+void CobaltMetricsServiceClient::SetMetricsClientId(
+    const std::string& client_id) {
+  // TODO(b/286066035): What to do with client id here?
+}
+
+// TODO(b/286884542): Audit all stub implementations in this class and reaffirm
+// they're not needed and/or add a reasonable implementation.
+int32_t CobaltMetricsServiceClient::GetProduct() {
+  // Note, Product is a Chrome concept and similar dimensions will get logged
+  // elsewhere downstream. This value doesn't matter.
+  return 0;
+}
+
+std::string CobaltMetricsServiceClient::GetApplicationLocale() {
+  // The locale will be populated by the web client, so return value is
+  // inconsequential.
+  return "en-US";
+}
+
+bool CobaltMetricsServiceClient::GetBrand(std::string* brand_code) {
+  // "false" means no brand code available. We set the brand when uploading
+  // via GEL.
+  return false;
+}
+
+::metrics::SystemProfileProto::Channel
+CobaltMetricsServiceClient::GetChannel() {
+  // We aren't Chrome and don't follow the same release channel concept.
+  // Return value here is unused in downstream logging.
+  return ::metrics::SystemProfileProto::CHANNEL_UNKNOWN;
+}
+
+std::string CobaltMetricsServiceClient::GetVersionString() {
+  // We assume the web client will log the Cobalt version along with its payload
+  // so this field is not that important.
+  return "1.0";
+}
+
+void CobaltMetricsServiceClient::OnEnvironmentUpdate(
+    std::string* serialized_environment) {
+  // Environment updates are serialized SystemProfileProto changes. All
+  // system info should be reported with the web client, so this is a no-op.
+}
+
+void CobaltMetricsServiceClient::CollectFinalMetricsForLog(
+    const base::Closure& done_callback) {
+  // Any hooks that should be called before each new log is uploaded, goes here.
+  // Chrome uses this to update memory histograms. Regardless, you must call
+  // done_callback when done else the uploader will never get invoked.
+  std::move(done_callback).Run();
+
+  // MetricsService will shut itself down if the app doesn't periodically tell
+  // it it's not idle. In Cobalt's case, we don't want this behavior. Watch
+  // sessions for LR can happen for extended periods of time with no action by
+  // the user. So, we always just set the app as "non-idle" immediately after
+  // each metric log is finalized.
+  GetMetricsService()->OnApplicationNotIdle();
+}
+
+std::string CobaltMetricsServiceClient::GetMetricsServerUrl() {
+  // Cobalt doesn't upload anything itself, so any URLs are no-ops.
+  return "";
+}
+
+std::string CobaltMetricsServiceClient::GetInsecureMetricsServerUrl() {
+  // Cobalt doesn't upload anything itself, so any URLs are no-ops.
+  return "";
+}
+
+std::unique_ptr<::metrics::MetricsLogUploader>
+CobaltMetricsServiceClient::CreateUploader(
+    base::StringPiece server_url, base::StringPiece insecure_server_url,
+    base::StringPiece mime_type,
+    ::metrics::MetricsLogUploader::MetricServiceType service_type,
+    const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete) {
+  auto uploader = std::make_unique<CobaltMetricsLogUploader>(
+      service_type, on_upload_complete);
+  log_uploader_ = uploader.get();
+  if (upload_handler_ != nullptr) {
+    log_uploader_->SetOnUploadHandler(upload_handler_);
+  }
+  return uploader;
+}
+
+base::TimeDelta CobaltMetricsServiceClient::GetStandardUploadInterval() {
+  return custom_upload_interval_ != UINT32_MAX
+             ? base::TimeDelta::FromSeconds(custom_upload_interval_)
+             : base::TimeDelta::FromSeconds(kStandardUploadIntervalSeconds);
+}
+
+bool CobaltMetricsServiceClient::IsReportingPolicyManaged() {
+  // Concept of "managed" reporting policy not applicable to Cobalt.
+  return false;
+}
+
+::metrics::EnableMetricsDefault
+CobaltMetricsServiceClient::GetMetricsReportingDefaultState() {
+  // Metrics always enabled for Cobalt, but this "default state" is unused,
+  // so it's only set to its semantically correct state (checked) out of
+  // principle.
+  return ::metrics::EnableMetricsDefault::OPT_OUT;
+}
+
+bool CobaltMetricsServiceClient::IsUMACellularUploadLogicEnabled() {
+  // Cobalt will never run in a special way for cellular connections.
+  return false;
+}
+
+bool CobaltMetricsServiceClient::SyncStateAllowsUkm() {
+  // UKM currently not used. Value doesn't matter here.
+  return false;
+}
+
+bool CobaltMetricsServiceClient::SyncStateAllowsExtensionUkm() {
+  // TODO(b/284467142): Revisit when enabling UKM.
+  // UKM currently not used. Value doesn't matter here.
+  return false;
+}
+
+bool CobaltMetricsServiceClient::
+    AreNotificationListenersEnabledOnAllProfiles() {
+  // Notification listeners currently unused.
+  return false;
+}
+
+std::string CobaltMetricsServiceClient::GetAppPackageName() {
+  // Android package name is logged elsewhere, this should always be empty.
+  return "";
+}
+
+void CobaltMetricsServiceClient::SetUploadInterval(uint32_t interval_seconds) {
+  if (interval_seconds > 0) {
+    custom_upload_interval_ = interval_seconds;
+  }
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_service_client.h b/cobalt/browser/metrics/cobalt_metrics_service_client.h
new file mode 100644
index 0000000..c7860f0
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_service_client.h
@@ -0,0 +1,180 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICE_CLIENT_H_
+#define COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICE_CLIENT_H_
+
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+
+#include "base/callback.h"
+#include "base/strings/string16.h"
+#include "base/time/time.h"
+#include "cobalt/browser/metrics/cobalt_enabled_state_provider.h"
+#include "cobalt/browser/metrics/cobalt_metrics_log_uploader.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "components/metrics/metrics_log_uploader.h"
+#include "components/metrics/metrics_reporting_default_state.h"
+#include "components/metrics/metrics_service.h"
+#include "components/metrics/metrics_service_client.h"
+#include "components/metrics/metrics_state_manager.h"
+#include "third_party/metrics_proto/system_profile.pb.h"
+
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+class MetricsLogUploader;
+class MetricsService;
+
+// A Cobalt-specific implementation of Metrics Service Client. This is the
+// primary interaction point to provide "embedder" specific implementations
+// to support the metric's service.
+class CobaltMetricsServiceClient : public ::metrics::MetricsServiceClient {
+ public:
+  ~CobaltMetricsServiceClient() override{};
+
+  // Sets the uploader handler to be called when metrics are ready for
+  // upload.
+  void SetOnUploadHandler(
+      const CobaltMetricsUploaderCallback* uploader_callback);
+
+  // Returns the MetricsService instance that this client is associated with.
+  // With the exception of testing contexts, the returned instance must be valid
+  // for the lifetime of this object (typically, the embedder's client
+  // implementation will own the MetricsService instance being returned).
+  ::metrics::MetricsService* GetMetricsService() override;
+
+  // Returns the UkmService instance that this client is associated with.
+  ukm::UkmService* GetUkmService() override;
+
+  // Registers the client id with other services (e.g. crash reporting), called
+  // when metrics recording gets enabled.
+  void SetMetricsClientId(const std::string& client_id) override;
+
+  // Returns the product value to use in uploaded reports, which will be used to
+  // set the ChromeUserMetricsExtension.product field. See comments on that
+  // field on why it's an int32_t rather than an enum.
+  int32_t GetProduct() override;
+
+  // Returns the current application locale (e.g. "en-US").
+  std::string GetApplicationLocale() override;
+
+  // Retrieves the brand code string associated with the install, returning
+  // false if no brand code is available.
+  bool GetBrand(std::string* brand_code) override;
+
+  // Returns the release channel (e.g. stable, beta, etc) of the application.
+  ::metrics::SystemProfileProto::Channel GetChannel() override;
+
+  // Returns the version of the application as a string.
+  std::string GetVersionString() override;
+
+  // Called by the metrics service when a new environment has been recorded.
+  // Takes the serialized environment as a parameter. The contents of
+  // |serialized_environment| are consumed by the call, but the caller maintains
+  // ownership.
+  void OnEnvironmentUpdate(std::string* serialized_environment) override;
+
+  // Called by the metrics service to record a clean shutdown.
+  void OnLogCleanShutdown() override {}
+
+  // Called prior to a metrics log being closed, allowing the client to
+  // collect extra histograms that will go in that log. Asynchronous API -
+  // the client implementation should call |done_callback| when complete.
+  void CollectFinalMetricsForLog(const base::Closure& done_callback) override;
+
+  // Get the URL of the metrics server.
+  std::string GetMetricsServerUrl() override;
+
+  // Get the fallback HTTP URL of the metrics server.
+  std::string GetInsecureMetricsServerUrl() override;
+
+  // Creates a MetricsLogUploader with the specified parameters (see comments on
+  // MetricsLogUploader for details).
+  std::unique_ptr<::metrics::MetricsLogUploader> CreateUploader(
+      base::StringPiece server_url, base::StringPiece insecure_server_url,
+      base::StringPiece mime_type,
+      ::metrics::MetricsLogUploader::MetricServiceType service_type,
+      const ::metrics::MetricsLogUploader::UploadCallback& on_upload_complete)
+      override;
+
+  // Returns the standard interval between upload attempts.
+  base::TimeDelta GetStandardUploadInterval() override;
+
+  // Called on plugin loading errors.
+  void OnPluginLoadingError(const base::FilePath& plugin_path) override {}
+
+  // Called on renderer crashes in some embedders (e.g., those that do not use
+  // //content and thus do not have //content's notification system available
+  // as a mechanism for observing renderer crashes).
+  void OnRendererProcessCrash() override {}
+
+  // Returns whether metrics reporting is managed by policy.
+  bool IsReportingPolicyManaged() override;
+
+  // Gets information about the default value for the metrics reporting checkbox
+  // shown during first-run.
+  ::metrics::EnableMetricsDefault GetMetricsReportingDefaultState() override;
+
+  // Returns whether cellular logic is enabled for metrics reporting.
+  bool IsUMACellularUploadLogicEnabled() override;
+
+  // Returns true iff sync is in a state that allows UKM to be enabled.
+  // See //components/ukm/observers/sync_disable_observer.h for details.
+  bool SyncStateAllowsUkm() override;
+
+  // Returns true iff sync is in a state that allows UKM to capture extensions.
+  // See //components/ukm/observers/sync_disable_observer.h for details.
+  bool SyncStateAllowsExtensionUkm() override;
+
+  // Returns whether UKM notification listeners were attached to all profiles.
+  bool AreNotificationListenersEnabledOnAllProfiles() override;
+
+  // Gets the Chrome package name for Android. Returns empty string for other
+  // platforms.
+  std::string GetAppPackageName() override;
+
+  // Setter to override the upload interval default
+  // (kStandardUploadIntervalSeconds).
+  void SetUploadInterval(uint32_t interval_seconds);
+
+  explicit CobaltMetricsServiceClient(
+      ::metrics::MetricsStateManager* state_manager, PrefService* local_state);
+
+ private:
+  // The MetricsStateManager, must outlive the Metrics Service.
+  ::metrics::MetricsStateManager* metrics_state_manager_;
+
+  // The MetricsService that |this| is a client of.
+  std::unique_ptr<::metrics::MetricsService> metrics_service_;
+
+  CobaltMetricsLogUploader* log_uploader_ = nullptr;
+
+  const CobaltMetricsUploaderCallback* upload_handler_ = nullptr;
+
+  uint32_t custom_upload_interval_ = UINT32_MAX;
+
+  DISALLOW_COPY_AND_ASSIGN(CobaltMetricsServiceClient);
+};
+
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
+
+#endif  // COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICE_CLIENT_H_
diff --git a/cobalt/browser/metrics/cobalt_metrics_service_client_test.cc b/cobalt/browser/metrics/cobalt_metrics_service_client_test.cc
new file mode 100644
index 0000000..544808e
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_service_client_test.cc
@@ -0,0 +1,125 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_service_client.h"
+
+#include <memory>
+
+#include "base/memory/scoped_refptr.h"
+#include "base/metrics/user_metrics.h"
+#include "base/test/test_simple_task_runner.h"
+#include "cobalt/browser/metrics/cobalt_enabled_state_provider.h"
+#include "cobalt/browser/metrics/cobalt_metrics_log_uploader.h"
+#include "components/metrics/client_info.h"
+#include "components/metrics/metrics_service.h"
+#include "components/metrics/metrics_state_manager.h"
+#include "components/prefs/testing_pref_service.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/metrics_proto/system_profile.pb.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+void TestStoreMetricsClientInfo(const ::metrics::ClientInfo& client_info) {
+  // ClientInfo is a way to get data into the metrics component, but goes unused
+  // in Cobalt. Do nothing with it for now.
+}
+
+std::unique_ptr<::metrics::ClientInfo> TestLoadMetricsClientInfo() {
+  // ClientInfo is a way to get data into the metrics component, but goes unused
+  // in Cobalt.
+  return nullptr;
+}
+
+class CobaltMetricsServiceClientTest : public ::testing::Test {
+ public:
+  CobaltMetricsServiceClientTest() {}
+  CobaltMetricsServiceClientTest(const CobaltMetricsServiceClientTest&) =
+      delete;
+  CobaltMetricsServiceClientTest& operator=(
+      const CobaltMetricsServiceClientTest&) = delete;
+
+  void SetUp() override {
+    task_runner_ = base::MakeRefCounted<base::TestSimpleTaskRunner>();
+    // Required by MetricsServiceClient.
+    base::SetRecordActionTaskRunner(task_runner_);
+    enabled_state_provider_ =
+        std::make_unique<CobaltEnabledStateProvider>(false, false);
+    ::metrics::MetricsService::RegisterPrefs(prefs_.registry());
+    metrics_state_manager_ = ::metrics::MetricsStateManager::Create(
+        &prefs_, enabled_state_provider_.get(), base::string16(),
+        base::BindRepeating(&TestStoreMetricsClientInfo),
+        base::BindRepeating(&TestLoadMetricsClientInfo));
+
+    client_ = std::make_unique<CobaltMetricsServiceClient>(
+        metrics_state_manager_.get(), &prefs_);
+  }
+
+  void TearDown() override {}
+
+
+ protected:
+  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
+  TestingPrefServiceSimple prefs_;
+  std::unique_ptr<CobaltMetricsServiceClient> client_;
+  std::unique_ptr<::metrics::MetricsStateManager> metrics_state_manager_;
+  std::unique_ptr<CobaltEnabledStateProvider> enabled_state_provider_;
+};
+
+TEST_F(CobaltMetricsServiceClientTest, UkmServiceConstructedProperly) {
+  // TODO(b/284467142): Add UKM tests when support is added.
+  ASSERT_EQ(client_->GetUkmService(), nullptr);
+  ASSERT_FALSE(client_->SyncStateAllowsUkm());
+  ASSERT_FALSE(client_->SyncStateAllowsExtensionUkm());
+}
+
+// TODO(b/286884542): If we add system profile info, update this test.
+TEST_F(CobaltMetricsServiceClientTest, TestStubbedSystemFields) {
+  ASSERT_EQ(client_->GetProduct(), 0);
+  ASSERT_EQ(client_->GetApplicationLocale(), "en-US");
+  std::string brand_code;
+  ASSERT_FALSE(client_->GetBrand(&brand_code));
+  ASSERT_EQ(brand_code.size(), 0);
+  ASSERT_EQ(client_->GetChannel(),
+            ::metrics::SystemProfileProto::CHANNEL_UNKNOWN);
+  ASSERT_EQ(client_->GetVersionString(), "1.0");
+  ASSERT_EQ(client_->GetMetricsServerUrl(), "");
+  ASSERT_EQ(client_->GetInsecureMetricsServerUrl(), "");
+  ASSERT_FALSE(client_->IsReportingPolicyManaged());
+  ASSERT_EQ(client_->GetMetricsReportingDefaultState(),
+            ::metrics::EnableMetricsDefault::OPT_OUT);
+  ASSERT_FALSE(client_->IsUMACellularUploadLogicEnabled());
+  ASSERT_FALSE(client_->AreNotificationListenersEnabledOnAllProfiles());
+  ASSERT_EQ(client_->GetAppPackageName(), "");
+}
+
+TEST_F(CobaltMetricsServiceClientTest, UploadIntervalCanBeOverriden) {
+  ASSERT_EQ(client_->GetStandardUploadInterval().InSeconds(), 300);
+  client_->SetUploadInterval(42);
+  ASSERT_EQ(client_->GetStandardUploadInterval().InSeconds(), 42);
+  client_->SetUploadInterval(UINT32_MAX);
+  // UINT32_MAX is the sentinel value to revert back to the default of 5 min.
+  ASSERT_EQ(client_->GetStandardUploadInterval().InSeconds(), 300);
+}
+
+TEST_F(CobaltMetricsServiceClientTest, UploadIntervalOfZeroIsIgnored) {
+  ASSERT_EQ(client_->GetStandardUploadInterval().InSeconds(), 300);
+  client_->SetUploadInterval(0);
+  ASSERT_EQ(client_->GetStandardUploadInterval().InSeconds(), 300);
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_services_manager.cc b/cobalt/browser/metrics/cobalt_metrics_services_manager.cc
new file mode 100644
index 0000000..3874d08
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_services_manager.cc
@@ -0,0 +1,98 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager.h"
+
+#include <memory>
+
+#include "cobalt/browser/metrics/cobalt_metrics_service_client.h"
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager_client.h"
+#include "components/metrics_services_manager/metrics_services_manager.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+CobaltMetricsServicesManager* CobaltMetricsServicesManager::instance_ = nullptr;
+
+CobaltMetricsServicesManager::CobaltMetricsServicesManager()
+    : task_runner_(base::ThreadTaskRunnerHandle::Get()),
+      metrics_services_manager::MetricsServicesManager(
+          std::make_unique<CobaltMetricsServicesManagerClient>()) {}
+
+
+// Static Singleton getter for metrics services manager.
+CobaltMetricsServicesManager* CobaltMetricsServicesManager::GetInstance() {
+  if (instance_ == nullptr) {
+    instance_ = new CobaltMetricsServicesManager();
+  }
+  return instance_;
+}
+
+void CobaltMetricsServicesManager::DeleteInstance() { delete instance_; }
+
+void CobaltMetricsServicesManager::SetOnUploadHandler(
+    const CobaltMetricsUploaderCallback* uploader_callback) {
+  instance_->task_runner_->PostTask(
+      FROM_HERE,
+      base::Bind(&CobaltMetricsServicesManager::SetOnUploadHandlerInternal,
+                 base::Unretained(instance_), uploader_callback));
+}
+
+void CobaltMetricsServicesManager::SetOnUploadHandlerInternal(
+    const CobaltMetricsUploaderCallback* uploader_callback) {
+  CobaltMetricsServiceClient* client =
+      static_cast<CobaltMetricsServiceClient*>(GetMetricsServiceClient());
+  DCHECK(client);
+  client->SetOnUploadHandler(uploader_callback);
+}
+
+void CobaltMetricsServicesManager::ToggleMetricsEnabled(bool is_enabled) {
+  instance_->task_runner_->PostTask(
+      FROM_HERE,
+      base::Bind(&CobaltMetricsServicesManager::ToggleMetricsEnabledInternal,
+                 base::Unretained(instance_), is_enabled));
+}
+void CobaltMetricsServicesManager::ToggleMetricsEnabledInternal(
+    bool is_enabled) {
+  CobaltMetricsServicesManagerClient* client =
+      static_cast<CobaltMetricsServicesManagerClient*>(
+          GetMetricsServicesManagerClient());
+  DCHECK(client);
+  client->GetEnabledStateProvider()->SetConsentGiven(is_enabled);
+  client->GetEnabledStateProvider()->SetReportingEnabled(is_enabled);
+  UpdateUploadPermissions(is_enabled);
+}
+
+void CobaltMetricsServicesManager::SetUploadInterval(
+    uint32_t interval_seconds) {
+  instance_->task_runner_->PostTask(
+      FROM_HERE,
+      base::Bind(&CobaltMetricsServicesManager::SetUploadIntervalInternal,
+                 base::Unretained(instance_), interval_seconds));
+}
+
+void CobaltMetricsServicesManager::SetUploadIntervalInternal(
+    uint32_t interval_seconds) {
+  browser::metrics::CobaltMetricsServiceClient* client =
+      static_cast<browser::metrics::CobaltMetricsServiceClient*>(
+          GetMetricsServiceClient());
+  DCHECK(client);
+  client->SetUploadInterval(interval_seconds);
+}
+
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_services_manager.h b/cobalt/browser/metrics/cobalt_metrics_services_manager.h
new file mode 100644
index 0000000..da31294
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_services_manager.h
@@ -0,0 +1,90 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICES_MANAGER_H_
+#define COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICES_MANAGER_H_
+
+#include <memory>
+
+#include "base//memory/scoped_refptr.h"
+#include "base/single_thread_task_runner.h"
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager_client.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "components/metrics_services_manager/metrics_services_manager.h"
+#include "components/metrics_services_manager/metrics_services_manager_client.h"
+
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+
+// Persistent setting name for the metric event/upload interval.
+constexpr char kMetricEventIntervalSettingName[] = "metricEventInterval";
+
+// Persistent setting name for whether metrics are enabled or disabled.
+constexpr char kMetricEnabledSettingName[] = "metricsEnabledState";
+
+// A static wrapper around CobaltMetricsServicesManager. We need a way
+// to provide a static instance of the "Cobaltified" MetricsServicesManager (and
+// its public APIs) to control metrics behavior outside of //cobalt/browser
+// (e.g., via H5vcc). Note, it's important that all public methods execute
+// on the same thread in which CobaltMetricsServicesManager was constructed.
+// This is a requirement of the metrics client code.
+class CobaltMetricsServicesManager
+    : public metrics_services_manager::MetricsServicesManager {
+ public:
+  CobaltMetricsServicesManager();
+
+  // Static Singleton getter for metrics services manager.
+  static CobaltMetricsServicesManager* GetInstance();
+
+  // Destructs the static instance of CobaltMetricsServicesManager.
+  static void DeleteInstance();
+
+  // Sets the upload handler onto the current static instance of
+  // CobaltMetricsServicesManager.
+  static void SetOnUploadHandler(
+      const CobaltMetricsUploaderCallback* uploader_callback);
+
+  // Toggles whether metric reporting is enabled via
+  // CobaltMetricsServicesManager.
+  static void ToggleMetricsEnabled(bool is_enabled);
+
+  // Sets the upload interval for metrics reporting. That is, how often are
+  // metrics snapshotted and attempted to upload.
+  static void SetUploadInterval(uint32_t interval_seconds);
+
+ private:
+  void SetOnUploadHandlerInternal(
+      const CobaltMetricsUploaderCallback* uploader_callback);
+
+  void ToggleMetricsEnabledInternal(bool is_enabled);
+
+  void SetUploadIntervalInternal(uint32_t interval_seconds);
+
+  static CobaltMetricsServicesManager* instance_;
+
+  // The task runner of the thread this class was constructed on. All logic
+  // interacting with containing metrics classes must be invoked on this
+  // task_runner thread.
+  scoped_refptr<base::SingleThreadTaskRunner> const task_runner_;
+};
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
+
+#endif  // COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICES_MANAGER_H_
diff --git a/cobalt/browser/metrics/cobalt_metrics_services_manager_client.cc b/cobalt/browser/metrics/cobalt_metrics_services_manager_client.cc
new file mode 100644
index 0000000..224490c
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_services_manager_client.cc
@@ -0,0 +1,112 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager_client.h"
+
+#include <memory>
+
+#include "base/callback_forward.h"
+#include "base/metrics/field_trial.h"
+#include "cobalt/browser/metrics/cobalt_metrics_service_client.h"
+#include "components/metrics/client_info.h"
+#include "components/metrics/metrics_service.h"
+#include "components/metrics/metrics_service_client.h"
+#include "components/metrics/metrics_state_manager.h"
+#include "components/metrics_services_manager/metrics_services_manager_client.h"
+#include "components/prefs/in_memory_pref_store.h"
+#include "components/prefs/pref_registry_simple.h"
+#include "components/prefs/pref_service.h"
+#include "components/prefs/pref_service_factory.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+std::unique_ptr<::metrics::MetricsServiceClient>
+CobaltMetricsServicesManagerClient::CreateMetricsServiceClient() {
+  InitializeMetricsStateManagerAndLocalState();
+  return std::make_unique<CobaltMetricsServiceClient>(
+      metrics_state_manager_.get(), local_state_.get());
+}
+
+std::unique_ptr<const base::FieldTrial::EntropyProvider>
+CobaltMetricsServicesManagerClient::CreateEntropyProvider() {
+  // Cobalt doesn't use FieldTrials, so this is a noop.
+  NOTIMPLEMENTED();
+  return nullptr;
+}
+
+// Returns whether metrics reporting is enabled.
+bool CobaltMetricsServicesManagerClient::IsMetricsReportingEnabled() {
+  return enabled_state_provider_->IsReportingEnabled();
+}
+
+// Returns whether metrics consent is given.
+bool CobaltMetricsServicesManagerClient::IsMetricsConsentGiven() {
+  return enabled_state_provider_->IsConsentGiven();
+}
+
+// If the user has forced metrics collection on via the override flag.
+bool CobaltMetricsServicesManagerClient::IsMetricsReportingForceEnabled() {
+  // TODO(b/286091096): Add support for metrics logging forcing.
+  return false;
+}
+
+
+void StoreMetricsClientInfo(const ::metrics::ClientInfo& client_info) {
+  // ClientInfo is a way to get data into the metrics component, but goes unused
+  // in Cobalt. Do nothing with it for now.
+}
+
+std::unique_ptr<::metrics::ClientInfo> LoadMetricsClientInfo() {
+  // ClientInfo is a way to get data into the metrics component, but goes unused
+  // in Cobalt.
+  return nullptr;
+}
+
+::metrics::MetricsStateManager*
+CobaltMetricsServicesManagerClient::GetMetricsStateManagerForTesting() {
+  return GetMetricsStateManager();
+}
+
+void CobaltMetricsServicesManagerClient::
+    InitializeMetricsStateManagerAndLocalState() {
+  if (!metrics_state_manager_) {
+    PrefServiceFactory pref_service_factory;
+    pref_service_factory.set_user_prefs(
+        base::MakeRefCounted<InMemoryPrefStore>());
+
+    auto pref_registry = base::MakeRefCounted<PrefRegistrySimple>();
+
+    // Note, we mainly create the Pref store here to appease metrics state
+    // manager. We don't really use it the same way Chromium does.
+    local_state_ = pref_service_factory.Create(pref_registry);
+    ::metrics::MetricsService::RegisterPrefs(pref_registry.get());
+
+    metrics_state_manager_ = ::metrics::MetricsStateManager::Create(
+        local_state_.get(), enabled_state_provider_.get(), base::string16(),
+        base::BindRepeating(&StoreMetricsClientInfo),
+        base::BindRepeating(&LoadMetricsClientInfo));
+  }
+}
+
+::metrics::MetricsStateManager*
+CobaltMetricsServicesManagerClient::GetMetricsStateManager() {
+  InitializeMetricsStateManagerAndLocalState();
+  return metrics_state_manager_.get();
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_services_manager_client.h b/cobalt/browser/metrics/cobalt_metrics_services_manager_client.h
new file mode 100644
index 0000000..01a2ae7
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_services_manager_client.h
@@ -0,0 +1,97 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICES_MANAGER_CLIENT_H_
+#define COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICES_MANAGER_CLIENT_H_
+
+#include <memory>
+
+#include "base/callback_forward.h"
+#include "base/metrics/field_trial.h"
+#include "cobalt/browser/metrics/cobalt_enabled_state_provider.h"
+#include "components/metrics/metrics_state_manager.h"
+#include "components/metrics_services_manager/metrics_services_manager_client.h"
+
+namespace metrics {
+class MetricsServiceClient;
+class EnabledStateProvider;
+}  // namespace metrics
+
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+// Cobalt implementation of MetricsServicesManagerClient. Top level manager
+// of metrics reporting state and uploading.
+class CobaltMetricsServicesManagerClient
+    : public metrics_services_manager::MetricsServicesManagerClient {
+ public:
+  CobaltMetricsServicesManagerClient()
+      : enabled_state_provider_(
+            std::make_unique<CobaltEnabledStateProvider>(false, false)) {}
+
+  ~CobaltMetricsServicesManagerClient() override {}
+
+  std::unique_ptr<::metrics::MetricsServiceClient> CreateMetricsServiceClient()
+      override;
+  std::unique_ptr<const base::FieldTrial::EntropyProvider>
+  CreateEntropyProvider() override;
+
+  // Returns whether metrics reporting is enabled.
+  bool IsMetricsReportingEnabled() override;
+
+  // Returns whether metrics consent is given.
+  bool IsMetricsConsentGiven() override;
+
+  // Returns whether there are any Incognito browsers/tabs open. Cobalt has no
+  // icognito mode.
+  bool IsIncognitoSessionActive() override { return false; }
+
+  // Update the running state of metrics services managed by the embedder, for
+  // example, crash reporting.
+  void UpdateRunningServices(bool may_record, bool may_upload) override {}
+
+  // If the user has forced metrics collection on via the override flag.
+  bool IsMetricsReportingForceEnabled() override;
+
+  CobaltEnabledStateProvider* GetEnabledStateProvider() {
+    return enabled_state_provider_.get();
+  }
+
+  // Testing getter for state manager.
+  ::metrics::MetricsStateManager* GetMetricsStateManagerForTesting();
+
+ private:
+  void InitializeMetricsStateManagerAndLocalState();
+
+  ::metrics::MetricsStateManager* GetMetricsStateManager();
+
+  // MetricsStateManager which is passed as a parameter to service constructors.
+  std::unique_ptr<::metrics::MetricsStateManager> metrics_state_manager_;
+
+  // EnabledStateProvider to communicate if the client has consented to metrics
+  // reporting, and if it's enabled.
+  std::unique_ptr<CobaltEnabledStateProvider> enabled_state_provider_;
+
+  // Any prefs/state specific to Cobalt Metrics.
+  std::unique_ptr<PrefService> local_state_;
+};
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
+
+#endif  // COBALT_BROWSER_METRICS_COBALT_METRICS_SERVICES_MANAGER_CLIENT_H_
diff --git a/cobalt/browser/metrics/cobalt_metrics_services_manager_client_test.cc b/cobalt/browser/metrics/cobalt_metrics_services_manager_client_test.cc
new file mode 100644
index 0000000..c6bf848
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_services_manager_client_test.cc
@@ -0,0 +1,87 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager_client.h"
+
+#include <memory>
+
+#include "base/memory/scoped_refptr.h"
+#include "base/metrics/user_metrics.h"
+#include "base/test/test_simple_task_runner.h"
+#include "components/metrics/metrics_service_client.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+
+class CobaltMetricsServicesManagerClientTest : public ::testing::Test {
+ public:
+  void SetUp() override {
+    task_runner_ = base::MakeRefCounted<base::TestSimpleTaskRunner>();
+    // Required by MetricsServiceClient.
+    base::SetRecordActionTaskRunner(task_runner_);
+    client_ = std::make_unique<CobaltMetricsServicesManagerClient>();
+  }
+
+  void TearDown() override {}
+
+
+ protected:
+  std::unique_ptr<CobaltMetricsServicesManagerClient> client_;
+  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
+};
+
+TEST_F(CobaltMetricsServicesManagerClientTest,
+       EnabledStateProviderStateIsPreserved) {
+  auto provider = client_->GetEnabledStateProvider();
+  provider->SetConsentGiven(true);
+  provider->SetReportingEnabled(true);
+  EXPECT_TRUE(client_->IsMetricsConsentGiven());
+  EXPECT_TRUE(client_->IsMetricsReportingEnabled());
+
+  provider->SetConsentGiven(false);
+  provider->SetReportingEnabled(false);
+  EXPECT_FALSE(client_->IsMetricsConsentGiven());
+  EXPECT_FALSE(client_->IsMetricsReportingEnabled());
+}
+
+TEST_F(CobaltMetricsServicesManagerClientTest, ForceEnabledStateIsCorrect) {
+  // TODO(b/286091096): Add tests for force enabling on the command-line.
+  EXPECT_FALSE(client_->IsMetricsReportingForceEnabled());
+}
+
+TEST_F(CobaltMetricsServicesManagerClientTest,
+       MetricsServiceClientAndStateManagerAreConstructedProperly) {
+  auto metrics_client = client_->CreateMetricsServiceClient();
+  ASSERT_NE(metrics_client, nullptr);
+
+  auto provider = client_->GetEnabledStateProvider();
+  provider->SetConsentGiven(true);
+  provider->SetReportingEnabled(true);
+
+  ASSERT_TRUE(
+      client_->GetMetricsStateManagerForTesting()->IsMetricsReportingEnabled());
+
+  provider->SetConsentGiven(false);
+  provider->SetReportingEnabled(false);
+
+  ASSERT_FALSE(
+      client_->GetMetricsStateManagerForTesting()->IsMetricsReportingEnabled());
+}
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
diff --git a/cobalt/browser/metrics/cobalt_metrics_uploader_callback.h b/cobalt/browser/metrics/cobalt_metrics_uploader_callback.h
new file mode 100644
index 0000000..db980c5
--- /dev/null
+++ b/cobalt/browser/metrics/cobalt_metrics_uploader_callback.h
@@ -0,0 +1,36 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_BROWSER_METRICS_COBALT_METRICS_UPLOADER_CALLBACK_H_
+#define COBALT_BROWSER_METRICS_COBALT_METRICS_UPLOADER_CALLBACK_H_
+
+#include <string>
+
+#include "base/callback.h"
+#include "cobalt/h5vcc/h5vcc_metric_type.h"
+
+namespace cobalt {
+namespace browser {
+namespace metrics {
+
+typedef base::RepeatingCallback<void(
+    const cobalt::h5vcc::H5vccMetricType& metric_type,
+    const std::string& serialized_proto)>
+    CobaltMetricsUploaderCallback;
+
+}  // namespace metrics
+}  // namespace browser
+}  // namespace cobalt
+
+#endif  // COBALT_BROWSER_METRICS_COBALT_METRICS_UPLOADER_CALLBACK_H_
diff --git a/cobalt/browser/service_worker_registry.cc b/cobalt/browser/service_worker_registry.cc
index 23a1a1c..f5dd468 100644
--- a/cobalt/browser/service_worker_registry.cc
+++ b/cobalt/browser/service_worker_registry.cc
@@ -22,7 +22,6 @@
 #include "base/threading/thread.h"
 #include "base/trace_event/trace_event.h"
 #include "cobalt/network/network_module.h"
-#include "cobalt/worker/service_worker_jobs.h"
 
 namespace cobalt {
 namespace browser {
@@ -34,7 +33,7 @@
 
 void ServiceWorkerRegistry::WillDestroyCurrentMessageLoop() {
   // Clear all member variables allocated from the thread.
-  service_worker_jobs_.reset();
+  service_worker_context_.reset();
 }
 
 ServiceWorkerRegistry::ServiceWorkerRegistry(
@@ -75,20 +74,20 @@
   destruction_observer_added_.Wait();
   DCHECK_NE(thread_.message_loop(), base::MessageLoop::current());
   thread_.Stop();
-  DCHECK(!service_worker_jobs_);
+  DCHECK(!service_worker_context_);
 }
 
 void ServiceWorkerRegistry::EnsureServiceWorkerStarted(
     const url::Origin& storage_key, const GURL& client_url,
     base::WaitableEvent* done_event) {
-  service_worker_jobs()->EnsureServiceWorkerStarted(storage_key, client_url,
-                                                    done_event);
+  service_worker_context()->EnsureServiceWorkerStarted(storage_key, client_url,
+                                                       done_event);
 }
 
-worker::ServiceWorkerJobs* ServiceWorkerRegistry::service_worker_jobs() {
+worker::ServiceWorkerContext* ServiceWorkerRegistry::service_worker_context() {
   // Ensure that the thread had a chance to allocate the object.
   destruction_observer_added_.Wait();
-  return service_worker_jobs_.get();
+  return service_worker_context_.get();
 }
 
 void ServiceWorkerRegistry::Initialize(
@@ -96,7 +95,7 @@
     web::UserAgentPlatformInfo* platform_info, const GURL& url) {
   TRACE_EVENT0("cobalt::browser", "ServiceWorkerRegistry::Initialize()");
   DCHECK_EQ(base::MessageLoop::current(), message_loop());
-  service_worker_jobs_.reset(new worker::ServiceWorkerJobs(
+  service_worker_context_.reset(new worker::ServiceWorkerContext(
       web_settings, network_module, platform_info, message_loop(), url));
 }
 
diff --git a/cobalt/browser/service_worker_registry.h b/cobalt/browser/service_worker_registry.h
index 8c37083..5b57118 100644
--- a/cobalt/browser/service_worker_registry.h
+++ b/cobalt/browser/service_worker_registry.h
@@ -22,7 +22,7 @@
 #include "base/threading/thread.h"
 #include "cobalt/network/network_module.h"
 #include "cobalt/web/web_settings.h"
-#include "cobalt/worker/service_worker_jobs.h"
+#include "cobalt/worker/service_worker_context.h"
 
 namespace cobalt {
 namespace browser {
@@ -48,7 +48,7 @@
                                   const GURL& client_url,
                                   base::WaitableEvent* done_event);
 
-  worker::ServiceWorkerJobs* service_worker_jobs();
+  worker::ServiceWorkerContext* service_worker_context();
 
  private:
   // Called by the constructor to perform any other initialization required on
@@ -69,7 +69,7 @@
       base::WaitableEvent::ResetPolicy::MANUAL,
       base::WaitableEvent::InitialState::NOT_SIGNALED};
 
-  std::unique_ptr<worker::ServiceWorkerJobs> service_worker_jobs_;
+  std::unique_ptr<worker::ServiceWorkerContext> service_worker_context_;
 };
 
 }  // namespace browser
diff --git a/cobalt/browser/user_agent_platform_info.cc b/cobalt/browser/user_agent_platform_info.cc
index 30b4b39..0284aa6 100644
--- a/cobalt/browser/user_agent_platform_info.cc
+++ b/cobalt/browser/user_agent_platform_info.cc
@@ -282,9 +282,9 @@
     result = platform_info_extension->GetFirmwareVersionDetails(
         value, kSystemPropertyMaxLength);
     if (result) {
-      info.set_firmware_version_details(value);
+      info.set_android_build_fingerprint(value);
     }
-    info.set_os_experience(platform_info_extension->GetOsExperience());
+    info.set_android_os_experience(platform_info_extension->GetOsExperience());
   }
 
   info.set_cobalt_version(COBALT_VERSION);
@@ -422,12 +422,12 @@
         } else if (!input.first.compare("evergreen_version")) {
           info.set_evergreen_version(input.second);
           LOG(INFO) << "Set evergreen version to " << input.second;
-        } else if (!input.first.compare("firmware_version_details")) {
-          info.set_firmware_version_details(input.second);
-          LOG(INFO) << "Set firmware version details to " << input.second;
-        } else if (!input.first.compare("os_experience")) {
-          info.set_os_experience(input.second);
-          LOG(INFO) << "Set os experience to " << input.second;
+        } else if (!input.first.compare("android_build_fingerprint")) {
+          info.set_android_build_fingerprint(input.second);
+          LOG(INFO) << "Set android build fingerprint to " << input.second;
+        } else if (!input.first.compare("android_os_experience")) {
+          info.set_android_os_experience(input.second);
+          LOG(INFO) << "Set android os experience to " << input.second;
         } else if (!input.first.compare("cobalt_version")) {
           info.set_cobalt_version(input.second);
           LOG(INFO) << "Set cobalt type to " << input.second;
@@ -542,15 +542,15 @@
   evergreen_version_ = Sanitize(evergreen_version, isTCHAR);
 }
 
-void UserAgentPlatformInfo::set_firmware_version_details(
-    const std::string& firmware_version_details) {
-  firmware_version_details_ =
-      Sanitize(firmware_version_details, isVCHARorSpace);
+void UserAgentPlatformInfo::set_android_build_fingerprint(
+    const std::string& android_build_fingerprint) {
+  android_build_fingerprint_ =
+      Sanitize(android_build_fingerprint, isVCHARorSpace);
 }
 
-void UserAgentPlatformInfo::set_os_experience(
-    const std::string& os_experience) {
-  os_experience_ = Sanitize(os_experience, isTCHAR);
+void UserAgentPlatformInfo::set_android_os_experience(
+    const std::string& android_os_experience) {
+  android_os_experience_ = Sanitize(android_os_experience, isTCHAR);
 }
 
 void UserAgentPlatformInfo::set_cobalt_version(
diff --git a/cobalt/browser/user_agent_platform_info.h b/cobalt/browser/user_agent_platform_info.h
index 26b0b64..e5768a4 100644
--- a/cobalt/browser/user_agent_platform_info.h
+++ b/cobalt/browser/user_agent_platform_info.h
@@ -76,10 +76,12 @@
   const std::string& evergreen_version() const override {
     return evergreen_version_;
   }
-  const std::string& firmware_version_details() const override {
-    return firmware_version_details_;
+  const std::string& android_build_fingerprint() const override {
+    return android_build_fingerprint_;
   }
-  const std::string& os_experience() const override { return os_experience_; }
+  const std::string& android_os_experience() const override {
+    return android_os_experience_;
+  }
   const std::string& cobalt_version() const override { return cobalt_version_; }
   const std::string& cobalt_build_version_number() const override {
     return cobalt_build_version_number_;
@@ -111,9 +113,9 @@
   void set_evergreen_type(const std::string& evergreen_type);
   void set_evergreen_file_type(const std::string& evergreen_file_type);
   void set_evergreen_version(const std::string& evergreen_version);
-  void set_firmware_version_details(
-      const std::string& firmware_version_details);
-  void set_os_experience(const std::string& os_experience);
+  void set_android_build_fingerprint(
+      const std::string& android_build_fingerprint);
+  void set_android_os_experience(const std::string& android_os_experience);
   void set_cobalt_version(const std::string& cobalt_version);
   void set_cobalt_build_version_number(
       const std::string& cobalt_build_version_number);
@@ -138,8 +140,8 @@
   std::string evergreen_type_;
   std::string evergreen_file_type_;
   std::string evergreen_version_;
-  std::string firmware_version_details_;  // Only via Client Hints
-  std::string os_experience_;             // Only via Client Hints
+  std::string android_build_fingerprint_;  // Only via Client Hints
+  std::string android_os_experience_;      // Only via Client Hints
 
   std::string cobalt_version_;
   std::string cobalt_build_version_number_;
diff --git a/cobalt/build/BUILD.gn b/cobalt/build/BUILD.gn
index 6c6e1e8..7b6a002 100644
--- a/cobalt/build/BUILD.gn
+++ b/cobalt/build/BUILD.gn
@@ -23,3 +23,9 @@
     cobalt_version,
   ]
 }
+
+action("cobalt_build_info") {
+  script = "build_info.py"
+  outputs = [ "$root_gen_dir/build_info.json" ]
+  args = [ rebase_path(outputs[0], root_build_dir) ]
+}
diff --git a/cobalt/build/build_info.py b/cobalt/build/build_info.py
new file mode 100755
index 0000000..2edcc52
--- /dev/null
+++ b/cobalt/build/build_info.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Generates a Cobalt Build Info json."""
+
+import datetime
+import json
+import os
+import re
+import subprocess
+import sys
+
+FILE_DIR = os.path.dirname(__file__)
+COMMIT_COUNT_BUILD_ID_OFFSET = 1000000
+
+_BUILD_ID_PATTERN = '^BUILD_NUMBER=([1-9][0-9]{6,})$'
+_GIT_REV_PATTERN = '^GitOrigin-RevId: ([0-9a-f]{40})$'
+
+
+def get_build_id_and_git_rev_from_commits(cwd):
+  # Build id and git rev must come from the same commit.
+  output = subprocess.check_output(
+      ['git', 'log', '--grep', _BUILD_ID_PATTERN, '-1', '-E', '--pretty=%b'],
+      cwd=cwd).decode()
+
+  # Gets build id.
+  compiled_build_id_pattern = re.compile(_BUILD_ID_PATTERN, flags=re.MULTILINE)
+  match_build_id = compiled_build_id_pattern.search(output)
+  if not match_build_id:
+    return None, None
+  build_id = match_build_id.group(1)
+
+  # Gets git rev.
+  compiled_git_rev_pattern = re.compile(_GIT_REV_PATTERN, flags=re.MULTILINE)
+  match_git_rev = compiled_git_rev_pattern.search(output)
+  if not match_git_rev:
+    git_rev = ''
+  else:
+    git_rev = match_git_rev.group(1)
+
+  return build_id, git_rev
+
+
+def get_build_id_from_commit_count(cwd):
+  output = subprocess.check_output(['git', 'rev-list', '--count', 'HEAD'],
+                                   cwd=cwd)
+  build_id = int(output.strip().decode()) + COMMIT_COUNT_BUILD_ID_OFFSET
+  return build_id
+
+
+def _get_last_commit_with_format(placeholder, cwd):
+  output = subprocess.check_output(
+      ['git', 'log', '-1', f'--pretty=format:{placeholder}'], cwd=cwd)
+  return output.strip().decode()
+
+
+def _get_hash_from_last_commit(cwd):
+  return _get_last_commit_with_format(r'%H', cwd=cwd)
+
+
+def _get_author_from_last_commit(cwd):
+  return _get_last_commit_with_format(r'%an', cwd=cwd)
+
+
+def _get_subject_from_last_commit(cwd):
+  return _get_last_commit_with_format(r'%s', cwd=cwd)
+
+
+def main(output_path, cwd=FILE_DIR):
+  """Writes a Cobalt build_info json file."""
+  build_rev = _get_hash_from_last_commit(cwd=cwd)
+  build_id, git_rev = get_build_id_and_git_rev_from_commits(cwd=cwd)
+  if build_id is None:
+    build_id = get_build_id_from_commit_count(cwd=cwd)
+    git_rev = build_rev
+  build_time = datetime.datetime.now().ctime()
+  author = _get_author_from_last_commit(cwd=cwd)
+  commit = _get_subject_from_last_commit(cwd=cwd)
+
+  info_json = {
+      'build_id': build_id,
+      'build_rev': build_rev,
+      'git_rev': git_rev,
+      'build_time': build_time,
+      'author': author,
+      'commit': commit
+  }
+
+  with open(output_path, 'w', encoding='utf-8') as f:
+    f.write(json.dumps(info_json, indent=4))
+
+  # Supports legacy build_info.txt.
+  output_text_path = os.path.join(
+      os.path.dirname(output_path), 'build_info.txt')
+  with open(output_text_path, 'w', encoding='utf-8') as f:
+    f.write(f'''\
+Build ID: {build_id}
+Build Rev: {build_rev}
+Git Rev: {git_rev}
+Build Time: {build_time}
+Author: {author}
+Commit: {commit}
+''')
+
+
+if __name__ == '__main__':
+  main(sys.argv[1])
diff --git a/cobalt/build/cobalt_configuration.py b/cobalt/build/cobalt_configuration.py
index adaa361..91b90a6 100644
--- a/cobalt/build/cobalt_configuration.py
+++ b/cobalt/build/cobalt_configuration.py
@@ -129,6 +129,7 @@
         'media_session_test',
         'media_stream_test',
         'memory_store_test',
+        'metrics_test',
         'nb_test',
         'net_unittests',
         'network_test',
diff --git a/cobalt/build/get_build_id.py b/cobalt/build/get_build_id.py
index 5e5c717..f48e30c 100755
--- a/cobalt/build/get_build_id.py
+++ b/cobalt/build/get_build_id.py
@@ -14,48 +14,13 @@
 # limitations under the License.
 """Prints out the Cobalt Build ID."""
 
-import os
-import re
-import subprocess
-
-_FILE_DIR = os.path.dirname(__file__)
-COMMIT_COUNT_BUILD_NUMBER_OFFSET = 1000000
-
-# Matches numbers > 1000000. The pattern is basic so git log --grep is able to
-# interpret it.
-GIT_BUILD_NUMBER_PATTERN = r'[1-9]' + r'[0-9]' * 6 + r'[0-9]*'
-BUILD_NUMBER_TAG_PATTERN = r'^BUILD_NUMBER={}$'
-
-# git log --grep can't handle capture groups.
-BUILD_NUBER_PATTERN_WITH_CAPTURE = f'({GIT_BUILD_NUMBER_PATTERN})'
+from cobalt.build import build_info
 
 
-def get_build_number_from_commits(cwd=_FILE_DIR):
-  full_pattern = BUILD_NUMBER_TAG_PATTERN.format(GIT_BUILD_NUMBER_PATTERN)
-  output = subprocess.check_output(
-      ['git', 'log', '--grep', full_pattern, '-1', '--pretty=%b'],
-      cwd=cwd).decode()
-
-  full_pattern_with_capture = re.compile(
-      BUILD_NUMBER_TAG_PATTERN.format(BUILD_NUBER_PATTERN_WITH_CAPTURE),
-      flags=re.MULTILINE)
-  match = full_pattern_with_capture.search(output)
-  return match.group(1) if match else None
-
-
-def get_build_number_from_commit_count(cwd=_FILE_DIR):
-  output = subprocess.check_output(['git', 'rev-list', '--count', 'HEAD'],
-                                   cwd=cwd)
-  build_number = int(output.strip().decode('utf-8'))
-  return build_number + COMMIT_COUNT_BUILD_NUMBER_OFFSET
-
-
-def main(cwd=_FILE_DIR):
-  build_number = get_build_number_from_commits(cwd=cwd)
-
+def main(cwd=build_info.FILE_DIR):
+  build_number, _ = build_info.get_build_id_and_git_rev_from_commits(cwd=cwd)
   if not build_number:
-    build_number = get_build_number_from_commit_count(cwd=cwd)
-
+    build_number = build_info.get_build_id_from_commit_count(cwd=cwd)
   return build_number
 
 
diff --git a/cobalt/build/get_build_id_test.py b/cobalt/build/get_build_id_test.py
index f9ea8c3..562179f 100644
--- a/cobalt/build/get_build_id_test.py
+++ b/cobalt/build/get_build_id_test.py
@@ -21,9 +21,10 @@
 import tempfile
 import unittest
 
+from cobalt.build import build_info
 from cobalt.build import get_build_id
 
-_TEST_BUILD_NUMBER = 1234 + get_build_id.COMMIT_COUNT_BUILD_NUMBER_OFFSET
+_TEST_BUILD_NUMBER = 1234 + build_info.COMMIT_COUNT_BUILD_ID_OFFSET
 
 
 # TODO(b/282040638): fix and re-enabled this
@@ -58,7 +59,7 @@
 
   def testGetBuildNumberFromCommitsSunnyDay(self):
     self.make_commit_with_build_number()
-    build_number = get_build_id.get_build_number_from_commits(
+    build_number, _ = build_info.get_build_id_and_git_rev_from_commits(
         cwd=self.test_dir.name)
     self.assertEqual(int(build_number), _TEST_BUILD_NUMBER)
 
@@ -66,17 +67,17 @@
     num_commits = 5
     for i in range(num_commits):
       self.make_commit_with_build_number(
-          get_build_id.COMMIT_COUNT_BUILD_NUMBER_OFFSET + i)
-    build_number = get_build_id.get_build_number_from_commits(
+          build_info.COMMIT_COUNT_BUILD_ID_OFFSET + i)
+    build_number, _ = build_info.get_build_id_and_git_rev_from_commits(
         cwd=self.test_dir.name)
     self.assertEqual(
         int(build_number),
-        num_commits + get_build_id.COMMIT_COUNT_BUILD_NUMBER_OFFSET - 1)
+        num_commits + build_info.COMMIT_COUNT_BUILD_ID_OFFSET - 1)
 
   def testGetBuildNumberFromCommitsRainyDayInvalidBuildNumber(self):
     self.make_commit()
     self.make_commit(f'BUILD_NUMBER={_TEST_BUILD_NUMBER}')
-    build_number = get_build_id.get_build_number_from_commits(
+    build_number, _ = build_info.get_build_id_and_git_rev_from_commits(
         cwd=self.test_dir.name)
     self.assertIsNone(build_number)
 
@@ -84,11 +85,10 @@
     num_commits = 5
     for _ in range(num_commits):
       self.make_commit()
-    build_number = get_build_id.get_build_number_from_commit_count(
+    build_number = build_info.get_build_id_from_commit_count(
         cwd=self.test_dir.name)
-    self.assertEqual(
-        build_number,
-        num_commits + get_build_id.COMMIT_COUNT_BUILD_NUMBER_OFFSET)
+    self.assertEqual(build_number,
+                     num_commits + build_info.COMMIT_COUNT_BUILD_ID_OFFSET)
 
   def testCommitsOutrankCommitCount(self):
     self.make_commit()
@@ -102,9 +102,8 @@
     for _ in range(num_commits):
       self.make_commit()
     build_number = get_build_id.main(cwd=self.test_dir.name)
-    self.assertEqual(
-        build_number,
-        num_commits + get_build_id.COMMIT_COUNT_BUILD_NUMBER_OFFSET)
+    self.assertEqual(build_number,
+                     num_commits + build_info.COMMIT_COUNT_BUILD_ID_OFFSET)
 
 
 if __name__ == '__main__':
diff --git a/cobalt/debug/BUILD.gn b/cobalt/debug/BUILD.gn
index 91c5586..2c48c85 100644
--- a/cobalt/debug/BUILD.gn
+++ b/cobalt/debug/BUILD.gn
@@ -17,6 +17,8 @@
   sources = [
     "backend/agent_base.cc",
     "backend/agent_base.h",
+    "backend/cobalt_agent.cc",
+    "backend/cobalt_agent.h",
     "backend/command_map.h",
     "backend/css_agent.cc",
     "backend/css_agent.h",
diff --git a/cobalt/debug/backend/cobalt_agent.cc b/cobalt/debug/backend/cobalt_agent.cc
new file mode 100644
index 0000000..63901c2
--- /dev/null
+++ b/cobalt/debug/backend/cobalt_agent.cc
@@ -0,0 +1,85 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/debug/backend/cobalt_agent.h"
+
+#include <set>
+#include <string>
+#include <utility>
+
+#include "base/bind.h"
+#include "base/values.h"
+#include "cobalt/debug/console/command_manager.h"
+#include "cobalt/debug/json_object.h"
+
+namespace cobalt {
+namespace debug {
+namespace backend {
+
+CobaltAgent::CobaltAgent(DebugDispatcher* dispatcher)
+    : AgentBase("Cobalt", dispatcher) {
+  commands_["getConsoleCommands"] =
+      base::Bind(&CobaltAgent::GetConsoleCommands, base::Unretained(this));
+  commands_["sendConsoleCommand"] =
+      base::Bind(&CobaltAgent::SendConsoleCommand, base::Unretained(this));
+  // dispatcher_->AddDomain(domain_, commands_.Bind());
+}
+
+void CobaltAgent::GetConsoleCommands(Command command) {
+  JSONObject response(new base::DictionaryValue());
+  JSONList list(new base::ListValue());
+
+  console::ConsoleCommandManager* command_manager =
+      console::ConsoleCommandManager::GetInstance();
+  DCHECK(command_manager);
+  if (command_manager) {
+    std::set<std::string> commands = command_manager->GetRegisteredCommands();
+    for (auto& command_name : commands) {
+      JSONObject console_command(new base::DictionaryValue());
+      console_command->SetString("command", command_name);
+      console_command->SetString("shortHelp",
+                                 command_manager->GetShortHelp(command_name));
+      console_command->SetString("longHelp",
+                                 command_manager->GetLongHelp(command_name));
+      list->Append(std::move(console_command));
+    }
+  }
+
+  JSONObject commands(new base::DictionaryValue());
+  commands->Set("commands", std::move(list));
+  response->Set("result", std::move(commands));
+  command.SendResponse(response);
+}
+
+void CobaltAgent::SendConsoleCommand(Command command) {
+  JSONObject params = JSONParse(command.GetParams());
+  if (params) {
+    std::string console_command;
+    if (params->GetString("command", &console_command)) {
+      std::string message;
+      params->GetString("message", &message);
+      console::ConsoleCommandManager* console_command_manager =
+          console::ConsoleCommandManager::GetInstance();
+      DCHECK(console_command_manager);
+      console_command_manager->HandleCommand(console_command, message);
+      command.SendResponse();
+      return;
+    }
+  }
+  command.SendErrorResponse(Command::kInvalidParams, "Missing command.");
+}
+
+}  // namespace backend
+}  // namespace debug
+}  // namespace cobalt
diff --git a/cobalt/debug/backend/cobalt_agent.h b/cobalt/debug/backend/cobalt_agent.h
new file mode 100644
index 0000000..27f8613
--- /dev/null
+++ b/cobalt/debug/backend/cobalt_agent.h
@@ -0,0 +1,47 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_DEBUG_BACKEND_COBALT_AGENT_H_
+#define COBALT_DEBUG_BACKEND_COBALT_AGENT_H_
+
+#include "cobalt/debug/backend/agent_base.h"
+#include "cobalt/debug/backend/debug_dispatcher.h"
+#include "cobalt/debug/command.h"
+#include "cobalt/debug/json_object.h"
+#include "cobalt/dom/window.h"
+
+namespace cobalt {
+namespace debug {
+namespace backend {
+
+// Implements a small part of the the "Runtime" inspector protocol domain with
+// just enough to support console input. When using the V8 JavaScript engine,
+// this class is not needed since the V8 inspector implements the Runtime domain
+// for us.
+//
+// https://chromedevtools.github.io/devtools-protocol/tot/Runtime
+class CobaltAgent : public AgentBase {
+ public:
+  explicit CobaltAgent(DebugDispatcher* dispatcher);
+
+ private:
+  void GetConsoleCommands(Command command);
+  void SendConsoleCommand(Command command);
+};
+
+}  // namespace backend
+}  // namespace debug
+}  // namespace cobalt
+
+#endif  // COBALT_DEBUG_BACKEND_COBALT_AGENT_H_
diff --git a/cobalt/debug/backend/debug_module.cc b/cobalt/debug/backend/debug_module.cc
index 56e8b26..ea767af 100644
--- a/cobalt/debug/backend/debug_module.cc
+++ b/cobalt/debug/backend/debug_module.cc
@@ -23,6 +23,7 @@
 namespace backend {
 
 namespace {
+constexpr char kCobaltAgent[] = "CobaltAgent";
 constexpr char kScriptDebuggerAgent[] = "ScriptDebuggerAgent";
 constexpr char kLogAgent[] = "LogAgent";
 constexpr char kDomAgent[] = "DomAgent";
@@ -140,6 +141,7 @@
   // directly handle one or more protocol domains.
   script_debugger_agent_.reset(
       new ScriptDebuggerAgent(debug_dispatcher_.get(), script_debugger_.get()));
+  cobalt_agent_.reset(new CobaltAgent(debug_dispatcher_.get()));
   log_agent_.reset(new LogAgent(debug_dispatcher_.get()));
   dom_agent_.reset(new DOMAgent(debug_dispatcher_.get()));
   css_agent_ = WrapRefCounted(new CSSAgent(debug_dispatcher_.get()));
@@ -178,6 +180,7 @@
   base::DictionaryValue* agents_state =
       data.debugger_state == nullptr ? nullptr
                                      : data.debugger_state->agents_state.get();
+  cobalt_agent_->Thaw(RemoveAgentState(kCobaltAgent, agents_state));
   script_debugger_agent_->Thaw(
       RemoveAgentState(kScriptDebuggerAgent, agents_state));
   log_agent_->Thaw(RemoveAgentState(kLogAgent, agents_state));
@@ -200,6 +203,7 @@
 
   debugger_state->agents_state.reset(new base::DictionaryValue());
   base::DictionaryValue* agents_state = debugger_state->agents_state.get();
+  StoreAgentState(agents_state, kCobaltAgent, cobalt_agent_->Freeze());
   StoreAgentState(agents_state, kScriptDebuggerAgent,
                   script_debugger_agent_->Freeze());
   StoreAgentState(agents_state, kLogAgent, log_agent_->Freeze());
diff --git a/cobalt/debug/backend/debug_module.h b/cobalt/debug/backend/debug_module.h
index da1778a..4736968 100644
--- a/cobalt/debug/backend/debug_module.h
+++ b/cobalt/debug/backend/debug_module.h
@@ -20,6 +20,7 @@
 
 #include "base/message_loop/message_loop.h"
 #include "cobalt/base/debugger_hooks.h"
+#include "cobalt/debug/backend/cobalt_agent.h"
 #include "cobalt/debug/backend/css_agent.h"
 #include "cobalt/debug/backend/debug_backend.h"
 #include "cobalt/debug/backend/debug_dispatcher.h"
@@ -134,6 +135,7 @@
 
   // Wrappable object providing native helpers for backend JavaScript.
   scoped_refptr<DebugBackend> debug_backend_;
+  std::unique_ptr<CobaltAgent> cobalt_agent_;
   std::unique_ptr<LogAgent> log_agent_;
   std::unique_ptr<DOMAgent> dom_agent_;
   scoped_refptr<CSSAgent> css_agent_;
diff --git a/cobalt/demos/content/multi-encrypted-video/multi-encrypted-video.html b/cobalt/demos/content/multi-encrypted-video/multi-encrypted-video.html
new file mode 100644
index 0000000..36e504f
--- /dev/null
+++ b/cobalt/demos/content/multi-encrypted-video/multi-encrypted-video.html
@@ -0,0 +1,71 @@
+<!DOCTYPE html>
+<!--
+ | Copyright 2023 The Cobalt Authors. All Rights Reserved.
+ |
+ | Licensed under the Apache License, Version 2.0 (the "License");
+ | you may not use this file except in compliance with the License.
+ | You may obtain a copy of the License at
+ |
+ |     http://www.apache.org/licenses/LICENSE-2.0
+ |
+ | Unless required by applicable law or agreed to in writing, software
+ | distributed under the License is distributed on an "AS IS" BASIS,
+ | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ | See the License for the specific language governing permissions and
+ | limitations under the License.
+ -->
+
+<html>
+  <head>
+    <title>Multi Encrypted Video</title>
+    <style>
+        body {
+          margin: 0;
+        }
+
+        #player-layer {
+          width: 100%;
+          height: 100%;
+        }
+
+        video {
+          width: 100%;
+          height: 100%;
+        }
+
+        #ui-layer {
+          position: absolute;
+          top: 15%;
+          height: 85%;
+          width: 100%;
+          background-color: rgba(33, 33, 33, .75);
+          padding: 24px;
+        }
+
+        .item {
+          width: 426px;
+          height: 240px;
+          display: inline-block;
+          margin: 24px;
+          vertical-align: middle;
+        }
+    </style>
+  </head>
+  <body>
+    <div id="player-layer">
+      <video class="primary" id="primary-video" muted="1" autoplay="1"></video>
+    </div>
+    <div id="ui-layer">
+      <div class="item" style="background-color: #D44">
+        <video class="secondary" id="secondary-video-1" muted="1" autoplay="1"></video>
+      </div>
+      <div class="item" style="background-color: #4D4">
+        <video class="secondary" id="secondary-video-2" muted="1" autoplay="1"></video>
+      </div>
+      <div class="item" style="background-color: #44D">
+        <video class="secondary" id="secondary-video-3" muted="1" autoplay="1"></video>
+      </div>
+    </div>
+    <script src="multi-encrypted-video.js"></script>
+  </body>
+</html>
diff --git a/cobalt/demos/content/multi-encrypted-video/multi-encrypted-video.js b/cobalt/demos/content/multi-encrypted-video/multi-encrypted-video.js
new file mode 100644
index 0000000..028d11c
--- /dev/null
+++ b/cobalt/demos/content/multi-encrypted-video/multi-encrypted-video.js
@@ -0,0 +1,116 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+function fetchArrayBuffer(method, url, body, callback) {
+  var xhr = new XMLHttpRequest();
+  xhr.responseType = 'arraybuffer';
+  xhr.addEventListener('load', function() {
+    callback(xhr.response);
+  });
+  xhr.open(method, url);
+  xhr.send(body);
+}
+
+function extractLicense(licenseArrayBuffer) {
+  var licenseArray = new Uint8Array(licenseArrayBuffer);
+  var licenseStartIndex = licenseArray.length - 2;
+  while (licenseStartIndex >= 0) {
+    if (licenseArray[licenseStartIndex] == 13 &&
+        licenseArray[licenseStartIndex + 1] == 10) {
+      licenseStartIndex += 2;
+      break;
+    }
+    --licenseStartIndex;
+  }
+
+  return licenseArray.subarray(licenseStartIndex);
+}
+
+var videoContentType = 'video/mp4; codecs="avc1.640028"';
+var audioContentType = 'audio/mp4; codecs="mp4a.40.2"';
+
+function play(videoElementId, keySystem) {
+  navigator.requestMediaKeySystemAccess(keySystem, [{
+    'initDataTypes': ['cenc'],
+    'videoCapabilities': [{'contentType': videoContentType}],
+    'audioCapabilities': [{'contentType': audioContentType}]
+  }]).then(function(mediaKeySystemAccess) {
+    return mediaKeySystemAccess.createMediaKeys();
+  }).then(function(mediaKeys) {
+    var videoElement = document.getElementById(videoElementId);
+
+    if (videoElementId != 'primary-video') {
+      videoElement.setMaxVideoCapabilities('width=1280; height=720');
+    }
+
+    if (mediaKeys.getMetrics) {
+      console.log('Found getMetrics(), calling it ...');
+      try {
+        mediaKeys.getMetrics();
+        console.log('Calling getMetrics() succeeded.');
+      } catch(e) {
+        console.log('Calling getMetrics() failed.');
+      }
+    }
+
+    videoElement.setMediaKeys(mediaKeys);
+
+    mediaKeySession = mediaKeys.createSession();
+    mediaKeySession.addEventListener('message', function(messageEvent) {
+      var licenseServerUrl = 'https://dash-mse-test.appspot.com/api/drm/widevine?drm_system=widevine&source=YOUTUBE&ip=0.0.0.0&ipbits=0&expire=19000000000&key=test_key1&sparams=ip,ipbits,expire,drm_system,source,video_id&video_id=03681262dc412c06&signature=9C4BE99E6F517B51FED1F0B3B31966D3C5DAB9D6.6A1F30BB35F3A39A4CA814B731450D4CBD198FFD';
+      fetchArrayBuffer('POST', licenseServerUrl, messageEvent.message,
+          function(licenseArrayBuffer) {
+            mediaKeySession.update(extractLicense(licenseArrayBuffer));
+          });
+    });
+
+    videoElement.addEventListener('encrypted', function(encryptedEvent) {
+      mediaKeySession.generateRequest(
+          encryptedEvent.initDataType, encryptedEvent.initData);
+    });
+
+    var mediaSource = new MediaSource();
+    mediaSource.addEventListener('sourceopen', function() {
+      var videoSourceBuffer = mediaSource.addSourceBuffer(videoContentType);
+      fetchArrayBuffer('GET',
+                      'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/oops_cenc-20121114-145-no-clear-start.mp4',
+                      null,
+                      function(videoArrayBuffer) {
+        videoSourceBuffer.appendBuffer(videoArrayBuffer);
+      });
+
+      var audioSourceBuffer = mediaSource.addSourceBuffer(audioContentType);
+      fetchArrayBuffer('GET',
+                      'http://yt-dash-mse-test.commondatastorage.googleapis.com/media/oops_cenc-20121114-148.mp4',
+                      null,
+                      function(audioArrayBuffer) {
+        audioSourceBuffer.appendBuffer(audioArrayBuffer);
+      });
+    });
+
+    videoElement.src = URL.createObjectURL(mediaSource);
+    videoElement.play();
+  });
+}
+
+play('primary-video', 'com.widevine.alpha');
+window.setTimeout(function() {
+  play('secondary-video-1', 'com.youtube.widevine.l3');
+}, 10000);
+window.setTimeout(function() {
+  play('secondary-video-2', 'com.youtube.widevine.l3');
+}, 20000);
+window.setTimeout(function() {
+  play('secondary-video-3', 'com.youtube.widevine.l3');
+}, 30000);
diff --git a/cobalt/demos/content/telemetry/index.html b/cobalt/demos/content/telemetry/index.html
new file mode 100644
index 0000000..d3744a8
--- /dev/null
+++ b/cobalt/demos/content/telemetry/index.html
@@ -0,0 +1,70 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <title>Cobalt Telemetry Demo</title>
+    <style>
+        body {
+            background-color: white;
+            font-family: Arial;
+            padding: 10px;
+        }
+
+        h1 {
+            font-size: 2em;
+            font-weight: bold;
+        }
+
+        #log {
+            color: blue;
+            font-size: 1em;
+            font-family: monospace;
+        }
+    </style>
+</head>
+
+<body>
+
+    <h1>LOG OUTPUT:</h1>
+    <div id="log"></div>
+
+    <script>
+        const LOG_CONTAINER = document.getElementById('log');
+        const EVENT_INTERVAL_SECS = 10;
+
+        function metricEventHandler(metricType, payload) {
+            log(`New metric payload received: metricType: ${metricType}, payload: ${payload}`);
+        }
+
+        function init() {
+            log('Initializing window.h5vcc.metrics.');
+            let timer = 0;
+            let interval = 10000;
+            setInterval(() => {
+                timer += interval;
+                log(`timer: ${timer / 1000}s`);
+            }, interval);
+
+            const metrics = window.h5vcc.metrics;
+            log(`Getting metrics enabled state metrics.isEnabled(): ${metrics.isEnabled()}`);
+            log('Enabling metrics reporting: metrics.enable()');
+            metrics.enable();
+            log(`Setting metric event interval: metrics.setMetricEventInterval(${EVENT_INTERVAL_SECS})`);
+            log(`Note that the first upload interval will always be 60 seconds, regardless of metricEventInterval.`);
+            metrics.setMetricEventInterval(EVENT_INTERVAL_SECS);
+            log('Binding metric event handler: metrics.onMetricEvent(metricEventHandler)');
+            metrics.onMetricEvent(metricEventHandler);
+            log(`Getting metrics enabled state metrics.isEnabled(): ${metrics.isEnabled()}`);
+        }
+
+        function log(logText) {
+            let log = document.createElement('div');
+            log.textContent = logText;
+            LOG_CONTAINER.appendChild(log);
+        }
+
+        init();
+    </script>
+</body>
+
+</html>
diff --git a/cobalt/doc/cvals.md b/cobalt/doc/cvals.md
index 47eb55a..6accd8f 100644
--- a/cobalt/doc/cvals.md
+++ b/cobalt/doc/cvals.md
@@ -75,7 +75,7 @@
 
 #### PublicCVals
 
-*   **Count.DOM.EventListeners** - The total number of EventListeners in
+*   **Count.WEB.EventListeners** - The total number of EventListeners in
     existence globally. This includes ones that are pending garbage collection.
 *   **Count.DOM.Nodes** - The total number of Nodes in existence globally. This
     includes ones that are pending garbage collection.
@@ -91,7 +91,7 @@
 
 #### DebugCVals
 
-*   **Count.DOM.ActiveJavaScriptEvents** - The number of JavaScript events that
+*   **Count.WEB.ActiveJavaScriptEvents** - The number of JavaScript events that
     are currently running.
 *   **Count.DOM.Attrs** - The total number of Attrs in existence globally. This
     includes ones that are pending garbage collection.
diff --git a/cobalt/doc/device_authentication.md b/cobalt/doc/device_authentication.md
index 6ef84a5..f90aa54 100644
--- a/cobalt/doc/device_authentication.md
+++ b/cobalt/doc/device_authentication.md
@@ -34,8 +34,17 @@
 function to sign the message using the secret key.  This method is preferred
 since it enables implementations where the key exists only in secure hardware
 and never enters the system's main memory.  A reference implementation, which
-depends on BoringSSL exists at
-[internal/starboard/linux/x64x11/internal/system_sign_with_certification_secret_key.cc](../../internal/starboard/linux/x64x11/internal/system_sign_with_certification_secret_key.cc).
+depends on BoringSSL, is as follows:
+
+```C++
+bool SbSystemSignWithCertificationSecretKey(
+    const uint8_t* message, size_t message_size_in_bytes,
+    uint8_t* digest, size_t digest_size_in_bytes) {
+  return starboard::shared::deviceauth::SignWithCertificationSecretKey(
+      kBase64EncodedCertificationSecret,
+      message, message_size_in_bytes, digest, digest_size_in_bytes);
+}
+```
 
 ### Cobalt signing
 
diff --git a/cobalt/dom/keyboard_event.cc b/cobalt/dom/keyboard_event.cc
index 892dad9..4879221 100644
--- a/cobalt/dom/keyboard_event.cc
+++ b/cobalt/dom/keyboard_event.cc
@@ -337,6 +337,10 @@
       return "MediaStop";
     case keycode::kMediaPlayPause:
       return "MediaPlayPause";
+#if SB_API_VERSION >= 15
+    case keycode::kMediaRecord:
+      return "MediaRecord";
+#endif
     case keycode::kMediaLaunchMail:
       return "LaunchMail";
     case keycode::kMediaLaunchMediaSelect:
diff --git a/cobalt/dom/keyboard_event_test.cc b/cobalt/dom/keyboard_event_test.cc
index ad1db1f..0f9843e 100644
--- a/cobalt/dom/keyboard_event_test.cc
+++ b/cobalt/dom/keyboard_event_test.cc
@@ -15,9 +15,9 @@
 #include "cobalt/dom/keyboard_event.h"
 
 #include "cobalt/base/tokens.h"
+#include "cobalt/dom/global_stats.h"
 #include "cobalt/dom/keyboard_event_init.h"
 #include "cobalt/dom/keycode.h"
-#include "cobalt/dom/global_stats.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace cobalt {
@@ -134,6 +134,15 @@
   EXPECT_EQ(keyboard_event_space->key_identifier(), " ");
   EXPECT_EQ(keyboard_event_space->key(), " ");
   EXPECT_EQ(keyboard_event_space->code(), "Space");
+
+#if SB_API_VERSION >= 15
+  init.set_key_code(keycode::kMediaRecord);
+  scoped_refptr<KeyboardEvent> keyboard_event_record =
+      new KeyboardEvent("keydown", init);
+  EXPECT_EQ(keyboard_event_record->key_identifier(), "MediaRecord");
+  EXPECT_EQ(keyboard_event_record->key(), "MediaRecord");
+  EXPECT_EQ(keyboard_event_record->code(), "MediaRecord");
+#endif
 }
 
 TEST_F(KeyboardEventTest, CanGetAltKey) {
diff --git a/cobalt/dom/keycode.h b/cobalt/dom/keycode.h
index 2dd2b2f..afda18f 100644
--- a/cobalt/dom/keycode.h
+++ b/cobalt/dom/keycode.h
@@ -200,6 +200,9 @@
   // Not present in Windows virtual key codes, but would be used by the client.
   kMediaRewind = 0xE3,
   kMediaFastForward = 0xE4,
+#if SB_API_VERSION >= 15
+  kMediaRecord = 0x1A0,
+#endif
 };
 
 }  // namespace keycode
diff --git a/cobalt/dom/local_storage_database.h b/cobalt/dom/local_storage_database.h
index ea8dfd3..36d959d 100644
--- a/cobalt/dom/local_storage_database.h
+++ b/cobalt/dom/local_storage_database.h
@@ -47,7 +47,7 @@
              const std::string& value);
   void Delete(const loader::Origin& origin, const std::string& key);
   void Clear(const loader::Origin& origin);
-  void Flush(const base::Closure& callback);
+  void Flush(const base::Closure& callback = base::Closure());
 
  private:
   void Init();
diff --git a/cobalt/dom/user_agent_data_test.cc b/cobalt/dom/user_agent_data_test.cc
index cd6886f..df0595a 100644
--- a/cobalt/dom/user_agent_data_test.cc
+++ b/cobalt/dom/user_agent_data_test.cc
@@ -40,11 +40,10 @@
 
     // Inject H5vcc interface to make it also accessible via Window
     h5vcc::H5vcc::Settings h5vcc_settings;
-    h5vcc_settings.network_module = NULL;
+    h5vcc_settings.network_module = nullptr;
 #if SB_IS(EVERGREEN)
-    h5vcc_settings.updater_module = NULL;
+    h5vcc_settings.updater_module = nullptr;
 #endif
-    h5vcc_settings.account_manager = NULL;
     h5vcc_settings.event_dispatcher = event_dispatcher();
     h5vcc_settings.user_agent_data = window()->navigator()->user_agent_data();
     h5vcc_settings.global_environment = global_environment();
diff --git a/cobalt/h5vcc/BUILD.gn b/cobalt/h5vcc/BUILD.gn
index 7ecc1ee..f081ce4 100644
--- a/cobalt/h5vcc/BUILD.gn
+++ b/cobalt/h5vcc/BUILD.gn
@@ -49,6 +49,8 @@
     "h5vcc_deep_link_event_target.cc",
     "h5vcc_deep_link_event_target.h",
     "h5vcc_event_listener_container.h",
+    "h5vcc_metrics.cc",
+    "h5vcc_metrics.h",
     "h5vcc_platform_service.cc",
     "h5vcc_platform_service.h",
     "h5vcc_runtime.cc",
@@ -69,9 +71,11 @@
   configs += [ ":h5vcc_internal_config" ]
   public_configs = [ ":h5vcc_external_config" ]
   deps = [
-    "//cobalt/account",
+    ":metric_event_handler_wrapper",
+    ":script_callback_wrapper",
     "//cobalt/base",
     "//cobalt/browser:browser_switches",
+    "//cobalt/browser/metrics",
     "//cobalt/build:cobalt_build_id",
     "//cobalt/cache",
     "//cobalt/configuration",
@@ -107,3 +111,19 @@
     deps += [ "//cobalt/updater" ]
   }
 }
+
+source_set("script_callback_wrapper") {
+  sources = [ "script_callback_wrapper.h" ]
+
+  deps = [ "//cobalt/script" ]
+}
+
+source_set("metric_event_handler_wrapper") {
+  sources = [ "metric_event_handler_wrapper.h" ]
+
+  deps = [
+    ":script_callback_wrapper",
+    "//cobalt/browser:generated_types",
+    "//cobalt/script",
+  ]
+}
diff --git a/cobalt/h5vcc/dial/dial_server.h b/cobalt/h5vcc/dial/dial_server.h
index 086b1c7..20e89ad 100644
--- a/cobalt/h5vcc/dial/dial_server.h
+++ b/cobalt/h5vcc/dial/dial_server.h
@@ -25,6 +25,7 @@
 #include "base/threading/thread_checker.h"
 #include "cobalt/h5vcc/dial/dial_http_request.h"
 #include "cobalt/h5vcc/dial/dial_http_response.h"
+#include "cobalt/h5vcc/script_callback_wrapper.h"
 #include "cobalt/script/callback_function.h"
 #include "cobalt/script/environment_settings.h"
 #include "cobalt/script/script_value.h"
@@ -35,17 +36,6 @@
 namespace h5vcc {
 namespace dial {
 
-// Template boilerplate for wrapping a script callback safely.
-template <typename T>
-class ScriptCallbackWrapper
-    : public base::RefCountedThreadSafe<ScriptCallbackWrapper<T> > {
- public:
-  typedef script::ScriptValue<T> ScriptValue;
-  ScriptCallbackWrapper(script::Wrappable* wrappable, const ScriptValue& func)
-      : callback(wrappable, func) {}
-  typename ScriptValue::Reference callback;
-};
-
 class DialServer : public script::Wrappable,
                    public base::SupportsWeakPtr<DialServer> {
  public:
diff --git a/cobalt/h5vcc/h5vcc.cc b/cobalt/h5vcc/h5vcc.cc
index fdc0893..8d957b8 100644
--- a/cobalt/h5vcc/h5vcc.cc
+++ b/cobalt/h5vcc/h5vcc.cc
@@ -19,6 +19,7 @@
 #include "cobalt/script/source_code.h"
 #endif
 
+#include "cobalt/h5vcc/h5vcc_metrics.h"
 #include "cobalt/persistent_storage/persistent_settings.h"
 
 namespace cobalt {
@@ -26,10 +27,11 @@
 
 H5vcc::H5vcc(const Settings& settings) {
   accessibility_ = new H5vccAccessibility(settings.event_dispatcher);
-  account_info_ = new H5vccAccountInfo(settings.account_manager);
+  account_info_ = new H5vccAccountInfo();
   audio_config_array_ = new H5vccAudioConfigArray();
   c_val_ = new dom::CValView();
   crash_log_ = new H5vccCrashLog();
+  metrics_ = new H5vccMetrics(settings.persistent_settings);
   runtime_ = new H5vccRuntime(settings.event_dispatcher);
   settings_ =
       new H5vccSettings(settings.set_web_setting_func, settings.media_module,
@@ -73,6 +75,7 @@
   tracer->Trace(audio_config_array_);
   tracer->Trace(c_val_);
   tracer->Trace(crash_log_);
+  tracer->Trace(metrics_);
   tracer->Trace(runtime_);
   tracer->Trace(settings_);
   tracer->Trace(storage_);
diff --git a/cobalt/h5vcc/h5vcc.h b/cobalt/h5vcc/h5vcc.h
index 7836da7..0d60a7c 100644
--- a/cobalt/h5vcc/h5vcc.h
+++ b/cobalt/h5vcc/h5vcc.h
@@ -25,6 +25,7 @@
 #include "cobalt/h5vcc/h5vcc_account_info.h"
 #include "cobalt/h5vcc/h5vcc_audio_config_array.h"
 #include "cobalt/h5vcc/h5vcc_crash_log.h"
+#include "cobalt/h5vcc/h5vcc_metrics.h"
 #include "cobalt/h5vcc/h5vcc_runtime.h"
 #include "cobalt/h5vcc/h5vcc_settings.h"
 #include "cobalt/h5vcc/h5vcc_storage.h"
@@ -51,7 +52,6 @@
 #if SB_IS(EVERGREEN)
           updater_module(NULL),
 #endif
-          account_manager(NULL),
           event_dispatcher(NULL),
           user_agent_data(NULL),
           global_environment(NULL) {
@@ -63,7 +63,6 @@
 #if SB_IS(EVERGREEN)
     updater::UpdaterModule* updater_module;
 #endif
-    account::AccountManager* account_manager;
     base::EventDispatcher* event_dispatcher;
     web::NavigatorUAData* user_agent_data;
     script::GlobalEnvironment* global_environment;
@@ -82,6 +81,7 @@
   }
   const scoped_refptr<dom::CValView>& c_val() const { return c_val_; }
   const scoped_refptr<H5vccCrashLog>& crash_log() const { return crash_log_; }
+  const scoped_refptr<H5vccMetrics>& metrics() const { return metrics_; }
   const scoped_refptr<H5vccRuntime>& runtime() const { return runtime_; }
   const scoped_refptr<H5vccSettings>& settings() const { return settings_; }
   const scoped_refptr<H5vccStorage>& storage() const { return storage_; }
@@ -102,6 +102,7 @@
   scoped_refptr<H5vccAudioConfigArray> audio_config_array_;
   scoped_refptr<dom::CValView> c_val_;
   scoped_refptr<H5vccCrashLog> crash_log_;
+  scoped_refptr<H5vccMetrics> metrics_;
   scoped_refptr<H5vccRuntime> runtime_;
   scoped_refptr<H5vccSettings> settings_;
   scoped_refptr<H5vccStorage> storage_;
diff --git a/cobalt/h5vcc/h5vcc.idl b/cobalt/h5vcc/h5vcc.idl
index 9201a36..188e66b 100644
--- a/cobalt/h5vcc/h5vcc.idl
+++ b/cobalt/h5vcc/h5vcc.idl
@@ -36,6 +36,7 @@
   readonly attribute H5vccAudioConfigArray audioConfig;
   readonly attribute H5vccCrashLog crashLog;
   readonly attribute CValView cVal;
+  readonly attribute H5vccMetrics metrics;
   readonly attribute H5vccRuntime runtime;
   readonly attribute H5vccSettings settings;
   readonly attribute H5vccStorage storage;
diff --git a/cobalt/h5vcc/h5vcc_account_info.cc b/cobalt/h5vcc/h5vcc_account_info.cc
index 705b488..c6b6303 100644
--- a/cobalt/h5vcc/h5vcc_account_info.cc
+++ b/cobalt/h5vcc/h5vcc_account_info.cc
@@ -14,27 +14,52 @@
 
 #include "cobalt/h5vcc/h5vcc_account_info.h"
 
-#include "cobalt/account/account_manager.h"
+#include <memory>
+#include <string>
+
+#include "starboard/user.h"
 
 namespace cobalt {
 namespace h5vcc {
 
-H5vccAccountInfo::H5vccAccountInfo(account::AccountManager* account_manager)
-    : account_manager_(account_manager) {}
+namespace {
+const int kMaxValueLength = 64 * 1024;
+
+std::string GetCurrentUserProperty(SbUserPropertyId property_id) {
+  SbUser user = SbUserGetCurrent();
+
+  if (!SbUserIsValid(user)) {
+    return "";
+  }
+
+  int size = SbUserGetPropertySize(user, property_id);
+  if (!size || size > kMaxValueLength) {
+    return "";
+  }
+
+  std::unique_ptr<char[]> value(new char[size]);
+  if (!SbUserGetProperty(user, property_id, value.get(), size)) {
+    return "";
+  }
+
+  std::string result = value.get();
+  return result;
+}
+
+}  // namespace
+
+H5vccAccountInfo::H5vccAccountInfo() {}
 
 std::string H5vccAccountInfo::avatar_url() const {
-  DCHECK(account_manager_);
-  return account_manager_->GetAvatarURL();
+  return GetCurrentUserProperty(kSbUserPropertyAvatarUrl);
 }
 
 std::string H5vccAccountInfo::username() const {
-  DCHECK(account_manager_);
-  return account_manager_->GetUsername();
+  return GetCurrentUserProperty(kSbUserPropertyUserName);
 }
 
 std::string H5vccAccountInfo::user_id() const {
-  DCHECK(account_manager_);
-  return account_manager_->GetUserId();
+  return GetCurrentUserProperty(kSbUserPropertyUserId);
 }
 
 }  // namespace h5vcc
diff --git a/cobalt/h5vcc/h5vcc_account_info.h b/cobalt/h5vcc/h5vcc_account_info.h
index c95e77c..6634217 100644
--- a/cobalt/h5vcc/h5vcc_account_info.h
+++ b/cobalt/h5vcc/h5vcc_account_info.h
@@ -17,7 +17,6 @@
 
 #include <string>
 
-#include "cobalt/account/account_manager.h"
 #include "cobalt/script/wrappable.h"
 
 namespace cobalt {
@@ -25,7 +24,7 @@
 
 class H5vccAccountInfo : public script::Wrappable {
  public:
-  explicit H5vccAccountInfo(account::AccountManager* account_manager);
+  H5vccAccountInfo();
   std::string avatar_url() const;
   std::string username() const;
   std::string user_id() const;
@@ -33,7 +32,6 @@
   DEFINE_WRAPPABLE_TYPE(H5vccAccountInfo);
 
  private:
-  account::AccountManager* account_manager_;
   DISALLOW_COPY_AND_ASSIGN(H5vccAccountInfo);
 };
 
diff --git a/cobalt/h5vcc/h5vcc_crash_log.cc b/cobalt/h5vcc/h5vcc_crash_log.cc
index 27c6981..baccbac 100644
--- a/cobalt/h5vcc/h5vcc_crash_log.cc
+++ b/cobalt/h5vcc/h5vcc_crash_log.cc
@@ -31,70 +31,49 @@
 namespace cobalt {
 namespace h5vcc {
 
-// We keep a global mapping of all registered logs.  When a crash occurs, we
-// will iterate through the mapping in this dictionary to extract all
-// logged entries and write them to the system's crash logger via Starboard.
-class CrashLogDictionary {
- public:
-  static CrashLogDictionary* GetInstance() {
-    return base::Singleton<CrashLogDictionary, base::DefaultSingletonTraits<
-                                                   CrashLogDictionary> >::get();
-  }
+CrashLogDictionary* CrashLogDictionary::GetInstance() {
+  return base::Singleton<CrashLogDictionary, base::DefaultSingletonTraits<
+                                                 CrashLogDictionary>>::get();
+}
 
-  void SetString(const std::string& key, const std::string& value) {
-    base::AutoLock lock(mutex_);
-    // While the lock prevents contention between other calls to SetString(),
-    // the atomics guard against OnCrash(), which doesn't acquire |mutex_|, from
-    // accessing the data at the same time.  In the case that OnCrash() is
-    // being called, we give up and skip adding the data.
-    if (base::subtle::Acquire_CompareAndSwap(&accessing_log_data_, 0, 1) == 0) {
-      string_log_map_[key] = value;
-      base::subtle::Release_Store(&accessing_log_data_, 0);
-    }
+void CrashLogDictionary::SetString(const std::string& key,
+                                   const std::string& value) {
+  base::AutoLock lock(mutex_);
+  // While the lock prevents contention between other calls to SetString(),
+  // the atomics guard against OnCrash(), which doesn't acquire |mutex_|, from
+  // accessing the data at the same time.  In the case that OnCrash() is
+  // being called, we give up and skip adding the data.
+  if (base::subtle::Acquire_CompareAndSwap(&accessing_log_data_, 0, 1) == 0) {
+    string_log_map_[key] = value;
+    base::subtle::Release_Store(&accessing_log_data_, 0);
   }
+}
 
- private:
-  CrashLogDictionary() : accessing_log_data_(0) {
+CrashLogDictionary::CrashLogDictionary() : accessing_log_data_(0) {
 #if SB_HAS(CORE_DUMP_HANDLER_SUPPORT)
-    SbCoreDumpRegisterHandler(&CoreDumpHandler, this);
+  SbCoreDumpRegisterHandler(&CoreDumpHandler, this);
 #endif
-  }
+}
 
-  static void CoreDumpHandler(void* context) {
-    CrashLogDictionary* crash_log_dictionary =
-        static_cast<CrashLogDictionary*>(context);
-    crash_log_dictionary->OnCrash();
-  }
+void CrashLogDictionary::CoreDumpHandler(void* context) {
+  CrashLogDictionary* crash_log_dictionary =
+      static_cast<CrashLogDictionary*>(context);
+  crash_log_dictionary->OnCrash();
+}
 
-  void OnCrash() {
+void CrashLogDictionary::OnCrash() {
 #if SB_HAS(CORE_DUMP_HANDLER_SUPPORT)
-    // Check that we're not already updating log data.  If we are, we just
-    // give up and skip recording any crash data, but hopefully this is rare.
-    if (base::subtle::Acquire_CompareAndSwap(&accessing_log_data_, 0, 1) == 0) {
-      for (StringMap::const_iterator iter = string_log_map_.begin();
-           iter != string_log_map_.end(); ++iter) {
-        SbCoreDumpLogString(iter->first.c_str(), iter->second.c_str());
-      }
-      base::subtle::Release_Store(&accessing_log_data_, 0);
+  // Check that we're not already updating log data.  If we are, we just
+  // give up and skip recording any crash data, but hopefully this is rare.
+  if (base::subtle::Acquire_CompareAndSwap(&accessing_log_data_, 0, 1) == 0) {
+    for (StringMap::const_iterator iter = string_log_map_.begin();
+         iter != string_log_map_.end(); ++iter) {
+      SbCoreDumpLogString(iter->first.c_str(), iter->second.c_str());
     }
-#endif
+    base::subtle::Release_Store(&accessing_log_data_, 0);
   }
-
-  friend struct base::DefaultSingletonTraits<CrashLogDictionary>;
-
-  base::subtle::Atomic32 accessing_log_data_;
-
-  // It is possible for multiple threads to call the H5VCC interface at the
-  // same time, and they will all forward to this global singleton, so we
-  // use this mutex to protect against concurrent access.
-  base::Lock mutex_;
-
-  typedef std::map<std::string, std::string> StringMap;
-  // Keeps track of all string values to be logged when a crash occurs.
-  StringMap string_log_map_;
-
-  DISALLOW_COPY_AND_ASSIGN(CrashLogDictionary);
-};
+#endif
+}
 
 bool H5vccCrashLog::SetString(const std::string& key,
                               const std::string& value) {
diff --git a/cobalt/h5vcc/h5vcc_crash_log.h b/cobalt/h5vcc/h5vcc_crash_log.h
index b85c0c5..bb20a48 100644
--- a/cobalt/h5vcc/h5vcc_crash_log.h
+++ b/cobalt/h5vcc/h5vcc_crash_log.h
@@ -15,8 +15,10 @@
 #ifndef COBALT_H5VCC_H5VCC_CRASH_LOG_H_
 #define COBALT_H5VCC_H5VCC_CRASH_LOG_H_
 
+#include <map>
 #include <string>
 
+#include "base/memory/singleton.h"
 #include "cobalt/h5vcc/h5vcc_crash_type.h"
 #include "cobalt/h5vcc/watchdog_replace.h"
 #include "cobalt/h5vcc/watchdog_state.h"
@@ -26,6 +28,38 @@
 namespace cobalt {
 namespace h5vcc {
 
+// We keep a global mapping of all registered logs.  When a crash occurs, we
+// will iterate through the mapping in this dictionary to extract all
+// logged entries and write them to the system's crash logger via Starboard.
+class CrashLogDictionary {
+ public:
+  static CrashLogDictionary* GetInstance();
+
+  void SetString(const std::string& key, const std::string& value);
+
+ private:
+  CrashLogDictionary();
+
+  static void CoreDumpHandler(void* context);
+
+  void OnCrash();
+
+  friend struct base::DefaultSingletonTraits<CrashLogDictionary>;
+
+  base::subtle::Atomic32 accessing_log_data_;
+
+  // It is possible for multiple threads to call the H5VCC interface at the
+  // same time, and they will all forward to this global singleton, so we
+  // use this mutex to protect against concurrent access.
+  base::Lock mutex_;
+
+  typedef std::map<std::string, std::string> StringMap;
+  // Keeps track of all string values to be logged when a crash occurs.
+  StringMap string_log_map_;
+
+  DISALLOW_COPY_AND_ASSIGN(CrashLogDictionary);
+};
+
 class H5vccCrashLog : public script::Wrappable {
  public:
   H5vccCrashLog() {}
diff --git a/cobalt/h5vcc/h5vcc_metric_type.idl b/cobalt/h5vcc/h5vcc_metric_type.idl
new file mode 100644
index 0000000..1a9ffc1
--- /dev/null
+++ b/cobalt/h5vcc/h5vcc_metric_type.idl
@@ -0,0 +1,23 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The various metric types we support to be published through the H5vccMetrics
+// API.
+enum H5vccMetricType {
+  // //third_party/metrics_proto/chrome_user_metrics_extension.proto
+  // ChromeUserMetricsExtension proto.
+  "UMA",
+  // //third_party/metrics_proto/ukm/report.proto Report proto.
+  "UKM"
+};
diff --git a/cobalt/h5vcc/h5vcc_metrics.cc b/cobalt/h5vcc/h5vcc_metrics.cc
new file mode 100644
index 0000000..0c9062a
--- /dev/null
+++ b/cobalt/h5vcc/h5vcc_metrics.cc
@@ -0,0 +1,84 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/h5vcc/h5vcc_metrics.h"
+
+#include <string>
+
+#include "base/values.h"
+#include "cobalt/browser/metrics/cobalt_metrics_service_client.h"
+#include "cobalt/browser/metrics/cobalt_metrics_services_manager.h"
+#include "cobalt/h5vcc/h5vcc_metric_type.h"
+#include "cobalt/h5vcc/metric_event_handler_wrapper.h"
+
+namespace cobalt {
+namespace h5vcc {
+
+void H5vccMetrics::OnMetricEvent(
+    const h5vcc::MetricEventHandlerWrapper::ScriptValue& event_handler) {
+  if (!uploader_callback_) {
+    run_event_handler_callback_ = std::make_unique<
+        cobalt::browser::metrics::CobaltMetricsUploaderCallback>(
+        base::BindRepeating(&H5vccMetrics::RunEventHandler,
+                            base::Unretained(this)));
+    browser::metrics::CobaltMetricsServicesManager::GetInstance()
+        ->SetOnUploadHandler(run_event_handler_callback_.get());
+  }
+
+  uploader_callback_ =
+      new h5vcc::MetricEventHandlerWrapper(this, event_handler);
+}
+
+void H5vccMetrics::RunEventHandler(
+    const cobalt::h5vcc::H5vccMetricType& metric_type,
+    const std::string& serialized_proto) {
+  task_runner_->PostTask(
+      FROM_HERE,
+      base::Bind(&H5vccMetrics::RunEventHandlerInternal, base::Unretained(this),
+                 metric_type, serialized_proto));
+}
+
+void H5vccMetrics::RunEventHandlerInternal(
+    const cobalt::h5vcc::H5vccMetricType& metric_type,
+    const std::string& serialized_proto) {
+  uploader_callback_->callback.value().Run(metric_type, serialized_proto);
+}
+
+void H5vccMetrics::Enable() { ToggleMetricsEnabled(true); }
+
+void H5vccMetrics::Disable() { ToggleMetricsEnabled(false); }
+
+void H5vccMetrics::ToggleMetricsEnabled(bool is_enabled) {
+  persistent_settings_->SetPersistentSetting(
+      browser::metrics::kMetricEnabledSettingName,
+      std::make_unique<base::Value>(is_enabled));
+  browser::metrics::CobaltMetricsServicesManager::GetInstance()
+      ->ToggleMetricsEnabled(is_enabled);
+}
+
+bool H5vccMetrics::IsEnabled() {
+  return browser::metrics::CobaltMetricsServicesManager::GetInstance()
+      ->IsMetricsReportingEnabled();
+}
+
+void H5vccMetrics::SetMetricEventInterval(uint32_t interval_seconds) {
+  persistent_settings_->SetPersistentSetting(
+      browser::metrics::kMetricEventIntervalSettingName,
+      std::make_unique<base::Value>(static_cast<int>(interval_seconds)));
+  browser::metrics::CobaltMetricsServicesManager::GetInstance()
+      ->SetUploadInterval(interval_seconds);
+}
+
+}  // namespace h5vcc
+}  // namespace cobalt
diff --git a/cobalt/h5vcc/h5vcc_metrics.h b/cobalt/h5vcc/h5vcc_metrics.h
new file mode 100644
index 0000000..a8f69ea
--- /dev/null
+++ b/cobalt/h5vcc/h5vcc_metrics.h
@@ -0,0 +1,97 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_H5VCC_H5VCC_METRICS_H_
+#define COBALT_H5VCC_H5VCC_METRICS_H_
+
+#include <memory>
+#include <string>
+
+#include "base/single_thread_task_runner.h"
+#include "base/threading/thread_task_runner_handle.h"
+#include "cobalt/browser/metrics/cobalt_metrics_uploader_callback.h"
+#include "cobalt/h5vcc/h5vcc_metric_type.h"
+#include "cobalt/h5vcc/metric_event_handler_wrapper.h"
+#include "cobalt/persistent_storage/persistent_settings.h"
+#include "cobalt/script/callback_function.h"
+#include "cobalt/script/script_value.h"
+#include "cobalt/script/wrappable.h"
+
+
+namespace cobalt {
+namespace h5vcc {
+
+// Implementation of the h5vcc_metrics.idl interface. Supports interactions
+// with the web client related to metrics logging.
+class H5vccMetrics : public script::Wrappable {
+ public:
+  // Required to put a typedef under the H5vccMetrics class as expected by the
+  // IDL definition. The "MetricEventHandler" typedef is explicitly separate
+  // so it can be used by other classes outside H5vcc without bringing H5vcc in
+  // its entirety.
+  typedef MetricEventHandler H5vccMetricEventHandler;
+
+  explicit H5vccMetrics(
+      persistent_storage::PersistentSettings* persistent_settings)
+      : task_runner_(base::ThreadTaskRunnerHandle::Get()),
+        persistent_settings_(persistent_settings) {}
+
+  H5vccMetrics(const H5vccMetrics&) = delete;
+  H5vccMetrics& operator=(const H5vccMetrics&) = delete;
+
+  // Binds an event handler that will be invoked every time Cobalt wants to
+  // upload a metrics payload.
+  void OnMetricEvent(
+      const MetricEventHandlerWrapper::ScriptValue& event_handler);
+
+  // Enable Cobalt metrics logging.
+  void Enable();
+
+  // Disable Cobalt metrics logging.
+  void Disable();
+
+  // Returns current enabled state of metrics logging/reporting.
+  bool IsEnabled();
+
+  // Sets the interval in which metrics will be aggregated and sent to the
+  // metric event handler.
+  void SetMetricEventInterval(uint32 interval_seconds);
+
+  DEFINE_WRAPPABLE_TYPE(H5vccMetrics);
+
+ private:
+  // Internal convenience method for toggling enabled/disabled state.
+  void ToggleMetricsEnabled(bool is_enabled);
+
+  void RunEventHandler(const cobalt::h5vcc::H5vccMetricType& metric_type,
+                       const std::string& serialized_proto);
+
+  void RunEventHandlerInternal(
+      const cobalt::h5vcc::H5vccMetricType& metric_type,
+      const std::string& serialized_proto);
+
+  scoped_refptr<h5vcc::MetricEventHandlerWrapper> uploader_callback_;
+
+  std::unique_ptr<cobalt::browser::metrics::CobaltMetricsUploaderCallback>
+      run_event_handler_callback_;
+
+  scoped_refptr<base::SingleThreadTaskRunner> const task_runner_;
+
+  persistent_storage::PersistentSettings* persistent_settings_;
+};
+
+}  // namespace h5vcc
+}  // namespace cobalt
+
+#endif  // COBALT_H5VCC_H5VCC_METRICS_H_
diff --git a/cobalt/h5vcc/h5vcc_metrics.idl b/cobalt/h5vcc/h5vcc_metrics.idl
new file mode 100644
index 0000000..29aa11f
--- /dev/null
+++ b/cobalt/h5vcc/h5vcc_metrics.idl
@@ -0,0 +1,62 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Defines an interface to support interactions with Cobalt metric logging.
+// For example, a callback API such that the web client can intercept and
+// process metrics sent from Cobalt.
+
+interface H5vccMetrics {
+  // Interface for web client to bind an event handler that will be invoked
+  // every time Cobalt wants to upload a metrics payload. Only one event
+  // handler callback can be registered at any time. Duplicate calls to
+  // onMetricEvent will override any previously registered callback.
+  //
+  // Example usage in JS:
+  //
+  //   window.h5vcc.metrics.onMetricEvent((metricType, payload) => {
+  //     if (metricType == 'UMA') {
+  //       // log UMA payload here...
+  //     }
+  //   });
+  void onMetricEvent(H5vccMetricEventHandler eventHandler);
+
+  // Enable Cobalt metrics logging. Metrics are disabled by default and should
+  // be enabled as soon as possible. When enabled, at regular intervals, the
+  // bound onMetricEvent callback will be called with telemetry payloads to
+  // be uploaded and logged on the server. Both the enable/disable settings
+  // are persistent or "sticky". That is, you only have to call them once
+  // and that setting will persist through multiple app lifecycles until the
+  // enable/disable APIs are explicitly called again.
+  void enable();
+
+  // Disable Cobalt metrics logging. If disabled, the metric event handler
+  // should never get called afterward.
+  void disable();
+
+  // Returns the current enabled state of metrics reporting.
+  boolean isEnabled();
+
+  // Sets the frequency in which Cobalt metrics will be snapshotted and sent to
+  // the metric event handler. Defaults to 5 minutes if not set. Must be > 0,
+  // else will be ignored. This setting is persistent. That is, it's "sticky"
+  // and will be persisted through multiple app lifetimes unless it's called
+  // again with a different value.
+  void setMetricEventInterval(unsigned long intervalSeconds);
+};
+
+// Callback invoked when a new metric payload is ready to be published. The
+// payload is a serialized protobuf and the metric type should give the consumer
+// a hint on how to deserialize it. See h5vcc_metric_type.idl for more info.
+callback H5vccMetricEventHandler =
+    void(H5vccMetricType metricType, DOMString metricPayload);
diff --git a/cobalt/h5vcc/h5vcc_runtime.cc b/cobalt/h5vcc/h5vcc_runtime.cc
index faf56ce..15f682b 100644
--- a/cobalt/h5vcc/h5vcc_runtime.cc
+++ b/cobalt/h5vcc/h5vcc_runtime.cc
@@ -91,7 +91,7 @@
     message_loop_->task_runner()->PostTask(
         FROM_HERE,
         base::Bind(&H5vccRuntime::OnDeepLinkEvent, base::Unretained(this),
-                   base::Passed(&deep_link_event)));
+                   base::Passed(std::move(deep_link_event))));
     return;
   }
   OnDeepLinkEvent(std::move(deep_link_event));
diff --git a/cobalt/h5vcc/h5vcc_settings.cc b/cobalt/h5vcc/h5vcc_settings.cc
index 574852d..4babfd9 100644
--- a/cobalt/h5vcc/h5vcc_settings.cc
+++ b/cobalt/h5vcc/h5vcc_settings.cc
@@ -95,7 +95,12 @@
     } else {
       persistent_settings_->SetPersistentSetting(
           network::kClientHintHeadersEnabledPersistentSettingsKey,
-          std::make_unique<base::Value>(value != 0));
+          std::make_unique<base::Value>(value));
+      // Tell NetworkModule (if exists) to re-query persistent settings.
+      if (network_module_) {
+        network_module_
+            ->SetEnableClientHintHeadersFlagsFromPersistentSettings();
+      }
       return true;
     }
   }
diff --git a/cobalt/h5vcc/h5vcc_storage.cc b/cobalt/h5vcc/h5vcc_storage.cc
index 0bb660c..2c1f332 100644
--- a/cobalt/h5vcc/h5vcc_storage.cc
+++ b/cobalt/h5vcc/h5vcc_storage.cc
@@ -128,10 +128,11 @@
 
 void H5vccStorage::Flush(const base::Optional<bool>& sync) {
   if (sync.value_or(false) == true) {
-    DLOG(WARNING) << "Synchronous flush is not supported.";
+    // Synchronously wait for storage to flush before returning.
+    network_module_->storage_manager()->FlushSynchronous();
+  } else {
+    network_module_->storage_manager()->FlushNow();
   }
-
-  network_module_->storage_manager()->FlushNow(base::Closure());
 }
 
 bool H5vccStorage::GetCookiesEnabled() {
diff --git a/cobalt/h5vcc/metric_event_handler_wrapper.h b/cobalt/h5vcc/metric_event_handler_wrapper.h
new file mode 100644
index 0000000..4948296
--- /dev/null
+++ b/cobalt/h5vcc/metric_event_handler_wrapper.h
@@ -0,0 +1,38 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_H5VCC_METRIC_EVENT_HANDLER_WRAPPER_H_
+#define COBALT_H5VCC_METRIC_EVENT_HANDLER_WRAPPER_H_
+
+#include <string>
+
+#include "cobalt/h5vcc/h5vcc_metric_type.h"
+#include "cobalt/h5vcc/script_callback_wrapper.h"
+#include "cobalt/script/callback_function.h"
+
+namespace cobalt {
+namespace h5vcc {
+
+// H5vccMetric callback function typedef.
+typedef script::CallbackFunction<void(const H5vccMetricType&,
+                                      const std::string&)>
+    MetricEventHandler;
+
+// Typedef for the ScriptCallbackWrapper callback.
+typedef ScriptCallbackWrapper<MetricEventHandler> MetricEventHandlerWrapper;
+
+}  // namespace h5vcc
+}  // namespace cobalt
+
+#endif  // COBALT_H5VCC_METRIC_EVENT_HANDLER_WRAPPER_H_
diff --git a/cobalt/h5vcc/script_callback_wrapper.h b/cobalt/h5vcc/script_callback_wrapper.h
new file mode 100644
index 0000000..5e3c693
--- /dev/null
+++ b/cobalt/h5vcc/script_callback_wrapper.h
@@ -0,0 +1,43 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_H5VCC_SCRIPT_CALLBACK_WRAPPER_H_
+#define COBALT_H5VCC_SCRIPT_CALLBACK_WRAPPER_H_
+
+#include <map>
+#include <memory>
+#include <string>
+
+#include "cobalt/script/script_value.h"
+#include "cobalt/script/wrappable.h"
+
+
+namespace cobalt {
+namespace h5vcc {
+
+// Template boilerplate for wrapping a script callback safely.
+template <typename T>
+class ScriptCallbackWrapper
+    : public base::RefCountedThreadSafe<ScriptCallbackWrapper<T> > {
+ public:
+  typedef script::ScriptValue<T> ScriptValue;
+  ScriptCallbackWrapper(script::Wrappable* wrappable, const ScriptValue& func)
+      : callback(wrappable, func) {}
+  typename ScriptValue::Reference callback;
+};
+
+}  // namespace h5vcc
+}  // namespace cobalt
+
+#endif  // COBALT_H5VCC_SCRIPT_CALLBACK_WRAPPER_H_
diff --git a/cobalt/layout/BUILD.gn b/cobalt/layout/BUILD.gn
index b95057e..7966365 100644
--- a/cobalt/layout/BUILD.gn
+++ b/cobalt/layout/BUILD.gn
@@ -146,6 +146,6 @@
     "//cobalt/math",
     "//cobalt/test:run_all_unittests",
     "//testing/gmock",
-    "//testing/gmock",
+    "//testing/gtest",
   ]
 }
diff --git a/cobalt/layout/topmost_event_target.cc b/cobalt/layout/topmost_event_target.cc
index d7ce92e..3981de4 100644
--- a/cobalt/layout/topmost_event_target.cc
+++ b/cobalt/layout/topmost_event_target.cc
@@ -57,7 +57,8 @@
   document->DoSynchronousLayout();
 
   html_element_ = document->html();
-  ConsiderElement(html_element_, coordinate);
+  bool consider_only_fixed_elements = false;
+  ConsiderElement(html_element_, coordinate, consider_only_fixed_elements);
   box_ = NULL;
   render_sequence_.clear();
   scoped_refptr<dom::HTMLElement> topmost_element;
@@ -178,8 +179,8 @@
   }
 };
 
-bool ShouldConsiderElementAndChildren(dom::Element* element,
-                                      math::Vector2dF* coordinate) {
+bool CanTargetElementAndChildren(dom::Element* element,
+                                 math::Vector2dF* coordinate) {
   LayoutBoxes* layout_boxes = GetLayoutBoxesIfNotEmpty(element);
   const Boxes boxes = layout_boxes->boxes();
   const Box* box = boxes.front();
@@ -434,17 +435,43 @@
   return complete_matrix;
 }
 
+bool LayoutBoxesAreFixed(LayoutBoxes* layout_boxes) {
+  const Boxes boxes = layout_boxes->boxes();
+  const Box* box = boxes.front();
+  if (!box->computed_style()) {
+    return false;
+  }
+
+  return box->computed_style()->position() == cssom::KeywordValue::GetFixed();
+}
+
+bool ShouldConsiderElementAndChildren(dom::Element* element,
+                                      math::Vector2dF* coordinate,
+                                      bool consider_only_fixed_elements) {
+  LayoutBoxes* layout_boxes = GetLayoutBoxesIfNotEmpty(element);
+  if (!layout_boxes) {
+    return false;
+  }
+
+  bool is_fixed_element = LayoutBoxesAreFixed(layout_boxes);
+  if (consider_only_fixed_elements && !is_fixed_element) {
+    return false;
+  }
+  return CanTargetElementAndChildren(element, coordinate);
+}
+
 }  // namespace
 
 void TopmostEventTarget::ConsiderElement(dom::Element* element,
-                                         const math::Vector2dF& coordinate) {
+                                         const math::Vector2dF& coordinate,
+                                         bool consider_only_fixed_elements) {
   if (!element) return;
   math::Vector2dF element_coordinate(coordinate);
   LayoutBoxes* layout_boxes = GetLayoutBoxesIfNotEmpty(element);
-  if (layout_boxes) {
-    if (!ShouldConsiderElementAndChildren(element, &element_coordinate)) {
-      return;
-    }
+  bool consider_element_and_children = ShouldConsiderElementAndChildren(
+      element, &element_coordinate, consider_only_fixed_elements);
+
+  if (consider_element_and_children) {
     scoped_refptr<dom::HTMLElement> html_element = element->AsHTMLElement();
     if (html_element && html_element->CanBeDesignatedByPointerIfDisplayed()) {
       ConsiderBoxes(html_element, layout_boxes, element_coordinate);
@@ -453,7 +480,8 @@
 
   for (dom::Element* child_element = element->first_element_child();
        child_element; child_element = child_element->next_element_sibling()) {
-    ConsiderElement(child_element, element_coordinate);
+    ConsiderElement(child_element, element_coordinate,
+                    !consider_element_and_children);
   }
 }
 
diff --git a/cobalt/layout/topmost_event_target.h b/cobalt/layout/topmost_event_target.h
index 1d1dd9b..2a8148a 100644
--- a/cobalt/layout/topmost_event_target.h
+++ b/cobalt/layout/topmost_event_target.h
@@ -51,8 +51,8 @@
   void CancelScrollsInParentNavItems(
       scoped_refptr<dom::HTMLElement> target_element);
 
-  void ConsiderElement(dom::Element* element,
-                       const math::Vector2dF& coordinate);
+  void ConsiderElement(dom::Element* element, const math::Vector2dF& coordinate,
+                       bool consider_only_fixed_elements);
   void ConsiderBoxes(const scoped_refptr<dom::HTMLElement>& html_element,
                      LayoutBoxes* layout_boxes,
                      const math::Vector2dF& coordinate);
diff --git a/cobalt/layout_tests/layout_snapshot.cc b/cobalt/layout_tests/layout_snapshot.cc
index a600395..db49e76 100644
--- a/cobalt/layout_tests/layout_snapshot.cc
+++ b/cobalt/layout_tests/layout_snapshot.cc
@@ -80,7 +80,7 @@
   browser::UserAgentPlatformInfo platform_info;
   network::NetworkModule network_module(
       browser::CreateUserAgentString(platform_info),
-      browser::GetClientHintHeaders(platform_info), NULL, NULL, net_options);
+      browser::GetClientHintHeaders(platform_info), nullptr, net_options);
 
   // Use 128M of image cache to minimize the effect of image loading.
   const size_t kImageCacheCapacity = 128 * 1024 * 1024;
diff --git a/cobalt/layout_tests/layout_tests.cc b/cobalt/layout_tests/layout_tests.cc
index 5c9d0f1..6679e3f 100644
--- a/cobalt/layout_tests/layout_tests.cc
+++ b/cobalt/layout_tests/layout_tests.cc
@@ -211,6 +211,7 @@
   RunTest(GetParam(), graphics_context_, pixel_tester_options);
 }
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(LayoutExact);
 // This test does an exact pixel compare with the expected output.
 class LayoutExact : public Layout {};
 TEST_P(LayoutExact, Test) {
diff --git a/cobalt/layout_tests/testdata/web-platform-tests/service-workers/web_platform_tests.txt b/cobalt/layout_tests/testdata/web-platform-tests/service-workers/web_platform_tests.txt
index 1132c15..f821df1 100644
--- a/cobalt/layout_tests/testdata/web-platform-tests/service-workers/web_platform_tests.txt
+++ b/cobalt/layout_tests/testdata/web-platform-tests/service-workers/web_platform_tests.txt
@@ -1,19 +1,29 @@
 # Service Worker API tests
 
+service-worker/activation-after-registration.https.html, PASS
+service-worker/activate-event-after-install-state-change.https.html, PASS
 service-worker/clients-matchall-on-evaluation.https.html, PASS
 service-worker/fetch-event-add-async.https.html, PASS
+service-worker/import-scripts-cross-origin.https.html, PASS
 service-worker/import-scripts-resource-map.https.html, PASS
 service-worker/import-scripts-updated-flag.https.html, PASS
+service-worker/multiple-update.https.html, PASS
 service-worker/register-default-scope.https.html, PASS
+service-worker/register-wait-forever-in-install-worker.https.html, PASS
 service-worker/registration-basic.https.html, PASS
 service-worker/registration-security-error.https.html, PASS
+service-worker/registration-service-worker-attributes.https.html, PASS
 service-worker/registration-script-url.https.html, PASS
 service-worker/rejections.https.html, PASS
+service-worker/serviceworkerobject-scripturl.https.html, PASS
 service-worker/service-worker-csp-default.https.html, PASS
 service-worker/service-worker-csp-connect.https.html, PASS
 service-worker/service-worker-csp-script.https.html, PASS
+service-worker/service-worker-header.https.html, PASS
 service-worker/Service-Worker-Allowed-header.https.html, PASS
 service-worker/skip-waiting-without-client.https.html, PASS
+service-worker/state.https.html, PASS
+service-worker/synced-state.https.html, PASS
 service-worker/uncontrolled-page.https.html, PASS
 service-worker/unregister.https.html, PASS
 service-worker/update-no-cache-request-headers.https.html, PASS
@@ -28,17 +38,7 @@
 service-worker/import-scripts-mime-types.https.html, DISABLE
 
 # b/234788479 Implement waiting for update worker state tasks in Install algorithm.
-service-worker/activation-after-registration.https.html, DISABLE
-service-worker/activate-event-after-install-state-change.https.html, DISABLE
-service-worker/import-scripts-cross-origin.https.html, DISABLE
 service-worker/import-scripts-redirect.https.html, DISABLE
-service-worker/multiple-update.https.html, DISABLE
-service-worker/register-wait-forever-in-install-worker.https.html, DISABLE
-service-worker/registration-service-worker-attributes.https.html, DISABLE
-service-worker/service-worker-header.https.html, DISABLE
-service-worker/state.https.html, DISABLE
-service-worker/synced-state.https.html, DISABLE
-service-worker/serviceworkerobject-scripturl.https.html, DISABLE
 
 # "Module" type of dedicated worker is supported in Cobalt
 service-worker/dedicated-worker-service-worker-interception.https.html, DISABLE
@@ -65,10 +65,10 @@
 # b/265841607 Unhandled rejection with value: object "TypeError"
 service-worker/same-site-cookies.https.html, DISABLE
 
-# b/265844662
+# b/265844662 Expected false, got true
 service-worker/interface-requirements-sw.https.html, DISABLE
 
-# b/265847846
+# b/265847846 SecurityError Reached unreachable code
 service-worker/navigate-window.https.html, DISABLE
 
 # b/267230419 Error type incorrect
diff --git a/cobalt/layout_tests/web_platform_tests.cc b/cobalt/layout_tests/web_platform_tests.cc
index 05c2376..455c37e 100644
--- a/cobalt/layout_tests/web_platform_tests.cc
+++ b/cobalt/layout_tests/web_platform_tests.cc
@@ -232,8 +232,8 @@
 
   web_module_options.web_options.web_settings = &web_settings;
   web_module_options.web_options.network_module = &network_module;
-  web_module_options.web_options.service_worker_jobs =
-      service_worker_registry->service_worker_jobs();
+  web_module_options.web_options.service_worker_context =
+      service_worker_registry->service_worker_context();
   web_module_options.web_options.platform_info = platform_info.get();
 
   // Prepare a slot for our results to be placed when ready.
diff --git a/cobalt/loader/cors_preflight.cc b/cobalt/loader/cors_preflight.cc
index 93f96d2..980f4d9 100644
--- a/cobalt/loader/cors_preflight.cc
+++ b/cobalt/loader/cors_preflight.cc
@@ -280,7 +280,8 @@
   url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::OPTIONS, this);
   url_fetcher_->SetRequestContext(
       network_module_->url_request_context_getter().get());
-  network_module_->AddClientHintHeaders(*url_fetcher_);
+  network_module_->AddClientHintHeaders(*url_fetcher_,
+                                        network::kCallTypePreflight);
   url_fetcher_->AddExtraRequestHeader(kOriginheadername + origin_);
   // 3. Let headers be the names of request's header list's headers,
   //    excluding CORS-safelisted request-headers and duplicates, sorted
diff --git a/cobalt/loader/net_fetcher.cc b/cobalt/loader/net_fetcher.cc
index d825fc4..872194a 100644
--- a/cobalt/loader/net_fetcher.cc
+++ b/cobalt/loader/net_fetcher.cc
@@ -135,7 +135,7 @@
         net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA;
     url_fetcher_->SetLoadFlags(kDisableCookiesLoadFlags);
   }
-  network_module->AddClientHintHeaders(*url_fetcher_);
+  network_module->AddClientHintHeaders(*url_fetcher_, network::kCallTypeLoader);
 
   // Delay the actual start until this function is complete. Otherwise we might
   // call handler's callbacks at an unexpected time- e.g. receiving OnError()
diff --git a/cobalt/media/BUILD.gn b/cobalt/media/BUILD.gn
index ee1625e..813baa2 100644
--- a/cobalt/media/BUILD.gn
+++ b/cobalt/media/BUILD.gn
@@ -48,6 +48,7 @@
     "base/sbplayer_interface.cc",
     "base/sbplayer_interface.h",
     "base/sbplayer_pipeline.cc",
+    "base/sbplayer_pipeline.h",
     "base/sbplayer_set_bounds_helper.cc",
     "base/sbplayer_set_bounds_helper.h",
     "decoder_buffer_allocator.cc",
diff --git a/cobalt/media/base/pipeline.h b/cobalt/media/base/pipeline.h
index b930107..d0f9175 100644
--- a/cobalt/media/base/pipeline.h
+++ b/cobalt/media/base/pipeline.h
@@ -92,23 +92,12 @@
       OnEncryptedMediaInitDataEncounteredCB;
 #endif  // SB_HAS(PLAYER_WITH_URL)
 
-  static scoped_refptr<Pipeline> Create(
-      SbPlayerInterface* interface, PipelineWindow window,
-      const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
-      const GetDecodeTargetGraphicsContextProviderFunc&
-          get_decode_target_graphics_context_provider_func,
-      bool allow_resume_after_suspend, bool allow_batched_sample_write,
-#if SB_API_VERSION >= 15
-      SbTime audio_write_duration_local, SbTime audio_write_duration_remote,
-#endif  // SB_API_VERSION >= 15
-      MediaLog* media_log, DecodeTargetProvider* decode_target_provider);
-
   virtual ~Pipeline() {}
 
-  virtual void Suspend() {}
+  virtual void Suspend() = 0;
   // TODO: This is temporary for supporting background media playback.
   //       Need to be removed with media refactor.
-  virtual void Resume(PipelineWindow window) {}
+  virtual void Resume(PipelineWindow window) = 0;
 
   // Build a pipeline to using the given filter collection to construct a filter
   // chain, executing |seek_cb| when the initial seek/preroll has completed.
@@ -231,10 +220,12 @@
   virtual PipelineStatistics GetStatistics() const = 0;
 
   // Get the SetBoundsCB used to set the bounds of the video frame.
-  virtual SetBoundsCB GetSetBoundsCB() { return SetBoundsCB(); }
+  virtual SetBoundsCB GetSetBoundsCB() = 0;
 
-  // Updates the player's preference for decode-to-texture versus punch through.
-  virtual void SetDecodeToTextureOutputMode(bool enabled) {}
+  // Cobalt by default doesn't have preference on the output mode used by
+  // SbPlayer.  Once called, this function explicitly sets the preferred output
+  // mode to decode-to-texture.
+  virtual void SetPreferredOutputModeToDecodeToTexture() = 0;
 };
 
 }  // namespace media
diff --git a/cobalt/media/base/sbplayer_bridge.cc b/cobalt/media/base/sbplayer_bridge.cc
index 1fb4c81..fad7fda 100644
--- a/cobalt/media/base/sbplayer_bridge.cc
+++ b/cobalt/media/base/sbplayer_bridge.cc
@@ -27,6 +27,7 @@
 #include "cobalt/base/statistics.h"
 #include "cobalt/media/base/format_support_query_metrics.h"
 #include "starboard/common/media.h"
+#include "starboard/common/player.h"
 #include "starboard/common/string.h"
 #include "starboard/configuration.h"
 #include "starboard/memory.h"
@@ -38,6 +39,8 @@
 
 namespace {
 
+using starboard::GetPlayerOutputModeName;
+
 class StatisticsWrapper {
  public:
   static StatisticsWrapper* GetInstance();
@@ -177,7 +180,7 @@
     const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
     const std::string& url, SbWindow window, Host* host,
     SbPlayerSetBoundsHelper* set_bounds_helper, bool allow_resume_after_suspend,
-    bool prefer_decode_to_texture,
+    SbPlayerOutputMode default_output_mode,
     const OnEncryptedMediaInitDataEncounteredCB&
         on_encrypted_media_init_data_encountered_cb,
     DecodeTargetProvider* const decode_target_provider,
@@ -200,7 +203,7 @@
   DCHECK(host_);
   DCHECK(set_bounds_helper_);
 
-  output_mode_ = ComputeSbUrlPlayerOutputMode(prefer_decode_to_texture);
+  output_mode_ = ComputeSbUrlPlayerOutputMode(default_output_mode);
 
   CreateUrlPlayer(url_);
 
@@ -220,7 +223,7 @@
     const VideoDecoderConfig& video_config, const std::string& video_mime_type,
     SbWindow window, SbDrmSystem drm_system, Host* host,
     SbPlayerSetBoundsHelper* set_bounds_helper, bool allow_resume_after_suspend,
-    bool prefer_decode_to_texture,
+    SbPlayerOutputMode default_output_mode,
     DecodeTargetProvider* const decode_target_provider,
     const std::string& max_video_capabilities, std::string pipeline_identifier)
     : sbplayer_interface_(interface),
@@ -261,7 +264,7 @@
     UpdateVideoConfig(video_config, video_mime_type);
   }
 
-  output_mode_ = ComputeSbPlayerOutputMode(prefer_decode_to_texture);
+  output_mode_ = ComputeSbPlayerOutputMode(default_output_mode);
 
   CreatePlayer();
 
@@ -1190,7 +1193,7 @@
 
 #if SB_HAS(PLAYER_WITH_URL)
 SbPlayerOutputMode SbPlayerBridge::ComputeSbUrlPlayerOutputMode(
-    bool prefer_decode_to_texture) {
+    SbPlayerOutputMode default_output_mode) {
   // Try to choose the output mode according to the passed in value of
   // |prefer_decode_to_texture|.  If the preferred output mode is unavailable
   // though, fallback to an output mode that is available.
@@ -1199,7 +1202,8 @@
           kSbPlayerOutputModePunchOut)) {
     output_mode = kSbPlayerOutputModePunchOut;
   }
-  if ((prefer_decode_to_texture || output_mode == kSbPlayerOutputModeInvalid) &&
+  if ((default_output_mode == kSbPlayerOutputModeDecodeToTexture ||
+       output_mode == kSbPlayerOutputModeInvalid) &&
       sbplayer_interface_->GetUrlPlayerOutputModeSupported(
           kSbPlayerOutputModeDecodeToTexture)) {
     output_mode = kSbPlayerOutputModeDecodeToTexture;
@@ -1211,9 +1215,10 @@
 #endif  // SB_HAS(PLAYER_WITH_URL)
 
 SbPlayerOutputMode SbPlayerBridge::ComputeSbPlayerOutputMode(
-    bool prefer_decode_to_texture) const {
+    SbPlayerOutputMode default_output_mode) const {
   SbPlayerCreationParam creation_param = {};
   creation_param.drm_system = drm_system_;
+
 #if SB_API_VERSION >= 15
   creation_param.audio_stream_info = audio_stream_info_;
   creation_param.video_stream_info = video_stream_info_;
@@ -1222,13 +1227,34 @@
   creation_param.video_sample_info = video_stream_info_;
 #endif  // SB_API_VERSION >= 15
 
-  // Try to choose |kSbPlayerOutputModeDecodeToTexture| when
-  // |prefer_decode_to_texture| is true.
-  if (prefer_decode_to_texture) {
-    creation_param.output_mode = kSbPlayerOutputModeDecodeToTexture;
-  } else {
-    creation_param.output_mode = kSbPlayerOutputModePunchOut;
+  if (default_output_mode != kSbPlayerOutputModeDecodeToTexture &&
+      video_stream_info_.codec != kSbMediaVideoCodecNone) {
+    SB_DCHECK(video_stream_info_.mime);
+    SB_DCHECK(video_stream_info_.max_video_capabilities);
+
+    // Set the `default_output_mode` to `kSbPlayerOutputModeDecodeToTexture` if
+    // any of the mime associated with it has `decode-to-texture=true` set.
+    // TODO(b/232559177): Make the check below more flexible, to work with
+    //                    other well formed inputs (e.g. with extra space).
+    bool is_decode_to_texture_preferred =
+        strstr(video_stream_info_.mime, "decode-to-texture=true") ||
+        strstr(video_stream_info_.max_video_capabilities,
+               "decode-to-texture=true");
+
+    if (is_decode_to_texture_preferred) {
+      SB_LOG(INFO) << "Setting `default_output_mode` from \""
+                   << GetPlayerOutputModeName(default_output_mode) << "\" to \""
+                   << GetPlayerOutputModeName(
+                          kSbPlayerOutputModeDecodeToTexture)
+                   << "\" because mime is set to \"" << video_stream_info_.mime
+                   << "\", and max_video_capabilities is set to \""
+                   << video_stream_info_.max_video_capabilities << "\"";
+      default_output_mode = kSbPlayerOutputModeDecodeToTexture;
+    }
   }
+
+  creation_param.output_mode = default_output_mode;
+
   auto output_mode =
       sbplayer_interface_->GetPreferredOutputMode(&creation_param);
   CHECK_NE(kSbPlayerOutputModeInvalid, output_mode);
diff --git a/cobalt/media/base/sbplayer_bridge.h b/cobalt/media/base/sbplayer_bridge.h
index ca7163e..a48e53c 100644
--- a/cobalt/media/base/sbplayer_bridge.h
+++ b/cobalt/media/base/sbplayer_bridge.h
@@ -72,7 +72,8 @@
                  const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
                  const std::string& url, SbWindow window, Host* host,
                  SbPlayerSetBoundsHelper* set_bounds_helper,
-                 bool allow_resume_after_suspend, bool prefer_decode_to_texture,
+                 bool allow_resume_after_suspend,
+                 SbPlayerOutputMode default_output_mode,
                  const OnEncryptedMediaInitDataEncounteredCB&
                      encrypted_media_init_data_encountered_cb,
                  DecodeTargetProvider* const decode_target_provider,
@@ -89,7 +90,8 @@
                  const std::string& video_mime_type, SbWindow window,
                  SbDrmSystem drm_system, Host* host,
                  SbPlayerSetBoundsHelper* set_bounds_helper,
-                 bool allow_resume_after_suspend, bool prefer_decode_to_texture,
+                 bool allow_resume_after_suspend,
+                 SbPlayerOutputMode default_output_mode,
                  DecodeTargetProvider* const decode_target_provider,
                  const std::string& max_video_capabilities,
                  std::string pipeline_identifier);
@@ -234,12 +236,12 @@
 
 #if SB_HAS(PLAYER_WITH_URL)
   SbPlayerOutputMode ComputeSbUrlPlayerOutputMode(
-      bool prefer_decode_to_texture);
+      SbPlayerOutputMode default_output_mode);
 #endif  // SB_HAS(PLAYER_WITH_URL)
   // Returns the output mode that should be used for a video with the given
   // specifications.
   SbPlayerOutputMode ComputeSbPlayerOutputMode(
-      bool prefer_decode_to_texture) const;
+      SbPlayerOutputMode default_output_mode) const;
 
   void LogStartupLatency() const;
 
diff --git a/cobalt/media/base/sbplayer_pipeline.cc b/cobalt/media/base/sbplayer_pipeline.cc
index 9523a9e..9459ebb 100644
--- a/cobalt/media/base/sbplayer_pipeline.cc
+++ b/cobalt/media/base/sbplayer_pipeline.cc
@@ -12,46 +12,23 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+#include "cobalt/media/base/sbplayer_pipeline.h"
+
 #include <algorithm>
-#include <memory>
-#include <string>
-#include <vector>
+#include <utility>
 
 #include "base/basictypes.h"  // For COMPILE_ASSERT
 #include "base/bind.h"
-#include "base/callback_helpers.h"
 #include "base/logging.h"
-#include "base/optional.h"
 #include "base/strings/stringprintf.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/task_runner.h"
-#include "base/time/time.h"
 #include "base/trace_event/trace_event.h"
 #include "cobalt/base/c_val.h"
 #include "cobalt/base/startup_timer.h"
-#include "cobalt/math/size.h"
-#include "cobalt/media/base/media_export.h"
-#include "cobalt/media/base/pipeline.h"
-#include "cobalt/media/base/playback_statistics.h"
-#include "cobalt/media/base/sbplayer_bridge.h"
-#include "cobalt/media/base/sbplayer_set_bounds_helper.h"
 #include "starboard/common/media.h"
 #include "starboard/common/string.h"
 #include "starboard/configuration_constants.h"
-#include "starboard/time.h"
-#include "third_party/chromium/media/base/audio_decoder_config.h"
 #include "third_party/chromium/media/base/bind_to_current_loop.h"
 #include "third_party/chromium/media/base/channel_layout.h"
-#include "third_party/chromium/media/base/decoder_buffer.h"
-#include "third_party/chromium/media/base/demuxer.h"
-#include "third_party/chromium/media/base/demuxer_stream.h"
-#include "third_party/chromium/media/base/media_log.h"
-#include "third_party/chromium/media/base/pipeline_status.h"
-#include "third_party/chromium/media/base/ranges.h"
-#include "third_party/chromium/media/base/video_decoder_config.h"
-#include "third_party/chromium/media/cobalt/ui/gfx/geometry/rect.h"
-#include "third_party/chromium/media/cobalt/ui/gfx/geometry/size.h"
 
 namespace cobalt {
 namespace media {
@@ -73,25 +50,6 @@
 
 unsigned int g_pipeline_identifier_counter = 0;
 
-// Used to post parameters to SbPlayerPipeline::StartTask() as the number of
-// parameters exceed what base::Bind() can support.
-struct StartTaskParameters {
-  Demuxer* demuxer;
-  SetDrmSystemReadyCB set_drm_system_ready_cb;
-  ::media::PipelineStatusCB ended_cb;
-  ErrorCB error_cb;
-  Pipeline::SeekCB seek_cb;
-  Pipeline::BufferingStateCB buffering_state_cb;
-  base::Closure duration_change_cb;
-  base::Closure output_mode_change_cb;
-  base::Closure content_size_change_cb;
-  std::string max_video_capabilities;
-#if SB_HAS(PLAYER_WITH_URL)
-  std::string source_url;
-  bool is_url_based;
-#endif  // SB_HAS(PLAYER_WITH_URL)
-};
-
 #if SB_API_VERSION >= 15
 bool HasRemoteAudioOutputs(
     const std::vector<SbMediaAudioConfiguration>& configurations) {
@@ -123,284 +81,7 @@
 }
 #endif  // SB_API_VERSION >= 15
 
-// SbPlayerPipeline is a PipelineBase implementation that uses the SbPlayer
-// interface internally.
-class MEDIA_EXPORT SbPlayerPipeline : public Pipeline,
-                                      public DemuxerHost,
-                                      public SbPlayerBridge::Host {
- public:
-  // Constructs a media pipeline that will execute on |task_runner|.
-  SbPlayerPipeline(
-      SbPlayerInterface* interface, PipelineWindow window,
-      const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
-      const GetDecodeTargetGraphicsContextProviderFunc&
-          get_decode_target_graphics_context_provider_func,
-      bool allow_resume_after_suspend, bool allow_batched_sample_write,
-#if SB_API_VERSION >= 15
-      SbTime audio_write_duration_local, SbTime audio_write_duration_remote,
-#endif  // SB_API_VERSION >= 15
-      MediaLog* media_log, DecodeTargetProvider* decode_target_provider);
-  ~SbPlayerPipeline() override;
-
-  void Suspend() override;
-  // TODO: This is temporary for supporting background media playback.
-  //       Need to be removed with media refactor.
-  void Resume(PipelineWindow window) override;
-
-  void Start(Demuxer* demuxer,
-             const SetDrmSystemReadyCB& set_drm_system_ready_cb,
-             const PipelineStatusCB& ended_cb, const ErrorCB& error_cb,
-             const SeekCB& seek_cb, const BufferingStateCB& buffering_state_cb,
-             const base::Closure& duration_change_cb,
-             const base::Closure& output_mode_change_cb,
-             const base::Closure& content_size_change_cb,
-             const std::string& max_video_capabilities) override;
-#if SB_HAS(PLAYER_WITH_URL)
-  void Start(const SetDrmSystemReadyCB& set_drm_system_ready_cb,
-             const OnEncryptedMediaInitDataEncounteredCB&
-                 encrypted_media_init_data_encountered_cb,
-             const std::string& source_url, const PipelineStatusCB& ended_cb,
-             const ErrorCB& error_cb, const SeekCB& seek_cb,
-             const BufferingStateCB& buffering_state_cb,
-             const base::Closure& duration_change_cb,
-             const base::Closure& output_mode_change_cb,
-             const base::Closure& content_size_change_cb) override;
-#endif  // SB_HAS(PLAYER_WITH_URL)
-
-  void Stop(const base::Closure& stop_cb) override;
-  void Seek(TimeDelta time, const SeekCB& seek_cb);
-  bool HasAudio() const override;
-  bool HasVideo() const override;
-
-  float GetPlaybackRate() const override;
-  void SetPlaybackRate(float playback_rate) override;
-  float GetVolume() const override;
-  void SetVolume(float volume) override;
-
-  TimeDelta GetMediaTime() override;
-  ::media::Ranges<TimeDelta> GetBufferedTimeRanges() override;
-  TimeDelta GetMediaDuration() const override;
-#if SB_HAS(PLAYER_WITH_URL)
-  TimeDelta GetMediaStartDate() const override;
-#endif  // SB_HAS(PLAYER_WITH_URL)
-  void GetNaturalVideoSize(gfx::Size* out_size) const override;
-  std::vector<std::string> GetAudioConnectors() const override;
-
-  bool DidLoadingProgress() const override;
-  PipelineStatistics GetStatistics() const override;
-  SetBoundsCB GetSetBoundsCB() override;
-  void SetDecodeToTextureOutputMode(bool enabled) override;
-
- private:
-  void StartTask(StartTaskParameters parameters);
-  void SetVolumeTask(float volume);
-  void SetPlaybackRateTask(float volume);
-  void SetDurationTask(TimeDelta duration);
-
-  // DemuxerHost implementation.
-  void OnBufferedTimeRangesChanged(
-      const ::media::Ranges<base::TimeDelta>& ranges) override;
-  void SetDuration(TimeDelta duration) override;
-  void OnDemuxerError(PipelineStatus error) override;
-
-#if SB_HAS(PLAYER_WITH_URL)
-  void CreateUrlPlayer(const std::string& source_url);
-  void SetDrmSystem(SbDrmSystem drm_system);
-#endif  // SB_HAS(PLAYER_WITH_URL)
-  void CreatePlayer(SbDrmSystem drm_system);
-
-  void OnDemuxerInitialized(PipelineStatus status);
-  void OnDemuxerSeeked(PipelineStatus status);
-  void OnDemuxerStopped();
-  void OnDemuxerStreamRead(
-      DemuxerStream::Type type, int max_number_buffers_to_read,
-      DemuxerStream::Status status,
-      const std::vector<scoped_refptr<DecoderBuffer>>& buffers);
-  // SbPlayerBridge::Host implementation.
-  void OnNeedData(DemuxerStream::Type type,
-                  int max_number_of_buffers_to_write) override;
-  void OnPlayerStatus(SbPlayerState state) override;
-  void OnPlayerError(SbPlayerError error, const std::string& message) override;
-
-  // Used to make a delayed call to OnNeedData() if |audio_read_delayed_| is
-  // true. If |audio_read_delayed_| is false, that means the delayed call has
-  // been cancelled due to a seek.
-  void DelayedNeedData(int max_number_of_buffers_to_write);
-
-  void UpdateDecoderConfig(DemuxerStream* stream);
-  void CallSeekCB(PipelineStatus status, const std::string& error_message);
-  void CallErrorCB(PipelineStatus status, const std::string& error_message);
-
-  void SuspendTask(base::WaitableEvent* done_event);
-  void ResumeTask(PipelineWindow window, base::WaitableEvent* done_event);
-
-  // Store the media time retrieved by GetMediaTime so we can cache it as an
-  // estimate and avoid calling SbPlayerGetInfo too frequently.
-  void StoreMediaTime(TimeDelta media_time);
-
-  // Retrieve the statistics as a string and append to message.
-  std::string AppendStatisticsString(const std::string& message) const;
-
-  // Get information on the time since app start and the time since the last
-  // playback resume.
-  std::string GetTimeInformation() const;
-
-  void RunSetDrmSystemReadyCB(DrmSystemReadyCB drm_system_ready_cb);
-
-  void SetReadInProgress(DemuxerStream::Type type, bool in_progress);
-  bool GetReadInProgress(DemuxerStream::Type type) const;
-
-  // An identifier string for the pipeline, used in CVal to identify multiple
-  // pipelines.
-  const std::string pipeline_identifier_;
-
-  // A wrapped interface of starboard player functions, which will be used in
-  // underlying SbPlayerBridge.
-  SbPlayerInterface* sbplayer_interface_;
-
-  // Message loop used to execute pipeline tasks.  It is thread-safe.
-  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
-
-  // Whether we should save DecoderBuffers for resume after suspend.
-  const bool allow_resume_after_suspend_;
-
-  // Whether we enable batched sample write functionality.
-  const bool allow_batched_sample_write_;
-
-  // The window this player associates with.  It should only be assigned in the
-  // dtor and accessed once by SbPlayerCreate().
-  PipelineWindow window_;
-
-  // Call to get the SbDecodeTargetGraphicsContextProvider for SbPlayerCreate().
-  const GetDecodeTargetGraphicsContextProviderFunc
-      get_decode_target_graphics_context_provider_func_;
-
-  // Lock used to serialize access for the following member variables.
-  mutable base::Lock lock_;
-
-  // Amount of available buffered data.  Set by filters.
-  ::media::Ranges<TimeDelta> buffered_time_ranges_;
-
-  // True when AddBufferedByteRange() has been called more recently than
-  // DidLoadingProgress().
-  mutable bool did_loading_progress_;
-
-  // Video's natural width and height.  Set by filters.
-  gfx::Size natural_size_;
-
-  // Current volume level (from 0.0f to 1.0f).  This value is set immediately
-  // via SetVolume() and a task is dispatched on the message loop to notify the
-  // filters.
-  base::CVal<float> volume_;
-
-  // Current playback rate (>= 0.0f).  This value is set immediately via
-  // SetPlaybackRate() and a task is dispatched on the message loop to notify
-  // the filters.
-  base::CVal<float> playback_rate_;
-
-  // The saved audio and video demuxer streams.  Note that it is safe to store
-  // raw pointers of the demuxer streams, as the Demuxer guarantees that its
-  // |DemuxerStream|s live as long as the Demuxer itself.
-  DemuxerStream* audio_stream_ = nullptr;
-  DemuxerStream* video_stream_ = nullptr;
-
-  mutable PipelineStatistics statistics_;
-
-  // The following member variables are only accessed by tasks posted to
-  // |task_runner_|.
-
-  // Temporary callback used for Stop().
-  base::Closure stop_cb_;
-
-  // Permanent callbacks passed in via Start().
-  SetDrmSystemReadyCB set_drm_system_ready_cb_;
-  PipelineStatusCB ended_cb_;
-  ErrorCB error_cb_;
-  BufferingStateCB buffering_state_cb_;
-  base::Closure duration_change_cb_;
-  base::Closure output_mode_change_cb_;
-  base::Closure content_size_change_cb_;
-  base::Optional<bool> decode_to_texture_output_mode_;
-#if SB_HAS(PLAYER_WITH_URL)
-  SbPlayerBridge::OnEncryptedMediaInitDataEncounteredCB
-      on_encrypted_media_init_data_encountered_cb_;
-#endif  //  SB_HAS(PLAYER_WITH_URL)
-
-  // Demuxer reference used for setting the preload value.
-  Demuxer* demuxer_ = nullptr;
-  bool audio_read_in_progress_ = false;
-  bool audio_read_delayed_ = false;
-  bool video_read_in_progress_ = false;
-  base::CVal<TimeDelta> duration_;
-
-#if SB_HAS(PLAYER_WITH_URL)
-  TimeDelta start_date_;
-  bool is_url_based_;
-#endif  // SB_HAS(PLAYER_WITH_URL)
-
-  scoped_refptr<SbPlayerSetBoundsHelper> set_bounds_helper_;
-
-  // The following member variables can be accessed from WMPI thread but all
-  // modifications to them happens on the pipeline thread.  So any access of
-  // them from the WMPI thread and any modification to them on the pipeline
-  // thread has to guarded by lock.  Access to them from the pipeline thread
-  // needn't to be guarded.
-
-  // Temporary callback used for Start() and Seek().
-  SeekCB seek_cb_;
-  TimeDelta seek_time_;
-  std::unique_ptr<SbPlayerBridge> player_bridge_;
-  bool is_initial_preroll_ = true;
-  base::CVal<bool> started_;
-  base::CVal<bool> suspended_;
-  base::CVal<bool> stopped_;
-  base::CVal<bool> ended_;
-  base::CVal<SbPlayerState> player_state_;
-
-  DecodeTargetProvider* decode_target_provider_;
-
-#if SB_API_VERSION >= 15
-  const SbTime audio_write_duration_local_;
-  const SbTime audio_write_duration_remote_;
-
-  // The two variables below should always contain the same value.  They are
-  // kept as separate variables so we can keep the existing implementation as
-  // is, which simplifies the implementation across multiple Starboard versions.
-  SbTime audio_write_duration_ = 0;
-  SbTime audio_write_duration_for_preroll_ = audio_write_duration_;
-#else   // SB_API_VERSION >= 15
-  // Read audio from the stream if |timestamp_of_last_written_audio_| is less
-  // than |seek_time_| + |audio_write_duration_for_preroll_|, this effectively
-  // allows 10 seconds of audio to be written to the SbPlayer after playback
-  // startup or seek.
-  SbTime audio_write_duration_for_preroll_ = 10 * kSbTimeSecond;
-  // Don't read audio from the stream more than |audio_write_duration_| ahead of
-  // the current media time during playing.
-  SbTime audio_write_duration_ = kSbTimeSecond;
-#endif  // SB_API_VERSION >= 15
-  // Only call GetMediaTime() from OnNeedData if it has been
-  // |kMediaTimeCheckInterval| since the last call to GetMediaTime().
-  static const SbTime kMediaTimeCheckInterval = 0.1 * kSbTimeSecond;
-  // Timestamp for the last written audio.
-  SbTime timestamp_of_last_written_audio_ = 0;
-
-  // Last media time reported by GetMediaTime().
-  base::CVal<SbTime> last_media_time_;
-  // Time when we last checked the media time.
-  SbTime last_time_media_time_retrieved_ = 0;
-  // Counter for retrograde media time.
-  size_t retrograde_media_time_counter_ = 0;
-  // The maximum video playback capabilities required for the playback.
-  base::CVal<std::string> max_video_capabilities_;
-
-  PlaybackStatistics playback_statistics_;
-
-  SbTimeMonotonic last_resume_time_ = -1;
-
-  SbTimeMonotonic set_drm_system_ready_cb_time_ = -1;
-
-  DISALLOW_COPY_AND_ASSIGN(SbPlayerPipeline);
-};
+}  // namespace
 
 SbPlayerPipeline::SbPlayerPipeline(
     SbPlayerInterface* interface, PipelineWindow window,
@@ -408,6 +89,7 @@
     const GetDecodeTargetGraphicsContextProviderFunc&
         get_decode_target_graphics_context_provider_func,
     bool allow_resume_after_suspend, bool allow_batched_sample_write,
+    bool force_punch_out_by_default,
 #if SB_API_VERSION >= 15
     SbTime audio_write_duration_local, SbTime audio_write_duration_remote,
 #endif  // SB_API_VERSION >= 15
@@ -464,6 +146,9 @@
                              pipeline_identifier_.c_str()),
           "", "The max video capabilities required for the media pipeline."),
       playback_statistics_(pipeline_identifier_) {
+  if (force_punch_out_by_default) {
+    default_output_mode_ = kSbPlayerOutputModePunchOut;
+  }
 #if SB_API_VERSION < 15
   SbMediaSetAudioWriteDuration(audio_write_duration_);
   LOG(INFO) << "Setting audio write duration to " << audio_write_duration_
@@ -887,15 +572,15 @@
   return base::Bind(&SbPlayerSetBoundsHelper::SetBounds, set_bounds_helper_);
 }
 
-void SbPlayerPipeline::SetDecodeToTextureOutputMode(bool enabled) {
-  TRACE_EVENT1("cobalt::media",
-               "SbPlayerPipeline::SetDecodeToTextureOutputMode", "mode",
-               enabled);
+void SbPlayerPipeline::SetPreferredOutputModeToDecodeToTexture() {
+  TRACE_EVENT0("cobalt::media",
+               "SbPlayerPipeline::SetPreferredOutputModeToDecodeToTexture");
 
   if (!task_runner_->BelongsToCurrentThread()) {
     task_runner_->PostTask(
-        FROM_HERE, base::Bind(&SbPlayerPipeline::SetDecodeToTextureOutputMode,
-                              this, enabled));
+        FROM_HERE,
+        base::Bind(&SbPlayerPipeline::SetPreferredOutputModeToDecodeToTexture,
+                   this));
     return;
   }
 
@@ -903,7 +588,7 @@
   // mode too late.
   DCHECK(!player_bridge_);
 
-  decode_to_texture_output_mode_ = enabled;
+  default_output_mode_ = kSbPlayerOutputModeDecodeToTexture;
 }
 
 void SbPlayerPipeline::StartTask(StartTaskParameters parameters) {
@@ -1017,9 +702,8 @@
     player_bridge_.reset(new SbPlayerBridge(
         sbplayer_interface_, task_runner_, source_url, window_, this,
         set_bounds_helper_.get(), allow_resume_after_suspend_,
-        *decode_to_texture_output_mode_,
-        on_encrypted_media_init_data_encountered_cb_, decode_target_provider_,
-        pipeline_identifier_));
+        default_output_mode_, on_encrypted_media_init_data_encountered_cb_,
+        decode_target_provider_, pipeline_identifier_));
     if (player_bridge_->IsValid()) {
       SetPlaybackRateTask(playback_rate_);
       SetVolumeTask(volume_);
@@ -1123,8 +807,8 @@
         get_decode_target_graphics_context_provider_func_, audio_config,
         audio_mime_type, video_config, video_mime_type, window_, drm_system,
         this, set_bounds_helper_.get(), allow_resume_after_suspend_,
-        *decode_to_texture_output_mode_, decode_target_provider_,
-        max_video_capabilities_, pipeline_identifier_));
+        default_output_mode_, decode_target_provider_, max_video_capabilities_,
+        pipeline_identifier_));
     if (player_bridge_->IsValid()) {
 #if SB_API_VERSION >= 15
       // TODO(b/267678497): When `player_bridge_->GetAudioConfigurations()`
@@ -1705,28 +1389,5 @@
   return video_read_in_progress_;
 }
 
-}  // namespace
-
-// static
-scoped_refptr<Pipeline> Pipeline::Create(
-    SbPlayerInterface* interface, PipelineWindow window,
-    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
-    const GetDecodeTargetGraphicsContextProviderFunc&
-        get_decode_target_graphics_context_provider_func,
-    bool allow_resume_after_suspend, bool allow_batched_sample_write,
-#if SB_API_VERSION >= 15
-    SbTime audio_write_duration_local, SbTime audio_write_duration_remote,
-#endif  // SB_API_VERSION >= 15
-    MediaLog* media_log, DecodeTargetProvider* decode_target_provider) {
-  return new SbPlayerPipeline(
-      interface, window, task_runner,
-      get_decode_target_graphics_context_provider_func,
-      allow_resume_after_suspend, allow_batched_sample_write,
-#if SB_API_VERSION >= 15
-      audio_write_duration_local, audio_write_duration_remote,
-#endif  // SB_API_VERSION >= 15
-      media_log, decode_target_provider);
-}
-
 }  // namespace media
 }  // namespace cobalt
diff --git a/cobalt/media/base/sbplayer_pipeline.h b/cobalt/media/base/sbplayer_pipeline.h
new file mode 100644
index 0000000..59e19e5
--- /dev/null
+++ b/cobalt/media/base/sbplayer_pipeline.h
@@ -0,0 +1,356 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_MEDIA_BASE_SBPLAYER_PIPELINE_H_
+#define COBALT_MEDIA_BASE_SBPLAYER_PIPELINE_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "base/callback_helpers.h"
+#include "base/optional.h"
+#include "base/synchronization/lock.h"
+#include "base/synchronization/waitable_event.h"
+#include "base/task_runner.h"
+#include "base/time/time.h"
+#include "cobalt/base/c_val.h"
+#include "cobalt/math/size.h"
+#include "cobalt/media/base/media_export.h"
+#include "cobalt/media/base/pipeline.h"
+#include "cobalt/media/base/playback_statistics.h"
+#include "cobalt/media/base/sbplayer_bridge.h"
+#include "cobalt/media/base/sbplayer_set_bounds_helper.h"
+#include "starboard/configuration_constants.h"
+#include "starboard/time.h"
+#include "third_party/chromium/media/base/audio_decoder_config.h"
+#include "third_party/chromium/media/base/decoder_buffer.h"
+#include "third_party/chromium/media/base/demuxer.h"
+#include "third_party/chromium/media/base/demuxer_stream.h"
+#include "third_party/chromium/media/base/media_log.h"
+#include "third_party/chromium/media/base/pipeline_status.h"
+#include "third_party/chromium/media/base/ranges.h"
+#include "third_party/chromium/media/base/video_decoder_config.h"
+#include "third_party/chromium/media/cobalt/ui/gfx/geometry/rect.h"
+#include "third_party/chromium/media/cobalt/ui/gfx/geometry/size.h"
+
+namespace cobalt {
+namespace media {
+
+// SbPlayerPipeline is a PipelineBase implementation that uses the SbPlayer
+// interface internally.
+class MEDIA_EXPORT SbPlayerPipeline : public Pipeline,
+                                      public ::media::DemuxerHost,
+                                      public SbPlayerBridge::Host {
+ public:
+  // Constructs a media pipeline that will execute on |task_runner|.
+  SbPlayerPipeline(
+      SbPlayerInterface* interface, PipelineWindow window,
+      const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
+      const GetDecodeTargetGraphicsContextProviderFunc&
+          get_decode_target_graphics_context_provider_func,
+      bool allow_resume_after_suspend, bool allow_batched_sample_write,
+      bool force_punch_out_by_default,
+#if SB_API_VERSION >= 15
+      SbTime audio_write_duration_local, SbTime audio_write_duration_remote,
+#endif  // SB_API_VERSION >= 15
+      MediaLog* media_log, DecodeTargetProvider* decode_target_provider);
+  ~SbPlayerPipeline() override;
+
+  void Suspend() override;
+  // TODO: This is temporary for supporting background media playback.
+  //       Need to be removed with media refactor.
+  void Resume(PipelineWindow window) override;
+
+  void Start(Demuxer* demuxer,
+             const SetDrmSystemReadyCB& set_drm_system_ready_cb,
+             const PipelineStatusCB& ended_cb, const ErrorCB& error_cb,
+             const SeekCB& seek_cb, const BufferingStateCB& buffering_state_cb,
+             const base::Closure& duration_change_cb,
+             const base::Closure& output_mode_change_cb,
+             const base::Closure& content_size_change_cb,
+             const std::string& max_video_capabilities) override;
+#if SB_HAS(PLAYER_WITH_URL)
+  void Start(const SetDrmSystemReadyCB& set_drm_system_ready_cb,
+             const OnEncryptedMediaInitDataEncounteredCB&
+                 encrypted_media_init_data_encountered_cb,
+             const std::string& source_url, const PipelineStatusCB& ended_cb,
+             const ErrorCB& error_cb, const SeekCB& seek_cb,
+             const BufferingStateCB& buffering_state_cb,
+             const base::Closure& duration_change_cb,
+             const base::Closure& output_mode_change_cb,
+             const base::Closure& content_size_change_cb) override;
+#endif  // SB_HAS(PLAYER_WITH_URL)
+
+  void Stop(const base::Closure& stop_cb) override;
+  void Seek(base::TimeDelta time, const SeekCB& seek_cb);
+  bool HasAudio() const override;
+  bool HasVideo() const override;
+
+  float GetPlaybackRate() const override;
+  void SetPlaybackRate(float playback_rate) override;
+  float GetVolume() const override;
+  void SetVolume(float volume) override;
+
+  base::TimeDelta GetMediaTime() override;
+  ::media::Ranges<base::TimeDelta> GetBufferedTimeRanges() override;
+  base::TimeDelta GetMediaDuration() const override;
+#if SB_HAS(PLAYER_WITH_URL)
+  base::TimeDelta GetMediaStartDate() const override;
+#endif  // SB_HAS(PLAYER_WITH_URL)
+  void GetNaturalVideoSize(gfx::Size* out_size) const override;
+  std::vector<std::string> GetAudioConnectors() const override;
+
+  bool DidLoadingProgress() const override;
+  PipelineStatistics GetStatistics() const override;
+  SetBoundsCB GetSetBoundsCB() override;
+  void SetPreferredOutputModeToDecodeToTexture() override;
+
+ private:
+  // Used to post parameters to SbPlayerPipeline::StartTask() as the number of
+  // parameters exceed what base::Bind() can support.
+  struct StartTaskParameters {
+    ::media::Demuxer* demuxer;
+    SetDrmSystemReadyCB set_drm_system_ready_cb;
+    ::media::PipelineStatusCB ended_cb;
+    ErrorCB error_cb;
+    Pipeline::SeekCB seek_cb;
+    Pipeline::BufferingStateCB buffering_state_cb;
+    base::Closure duration_change_cb;
+    base::Closure output_mode_change_cb;
+    base::Closure content_size_change_cb;
+    std::string max_video_capabilities;
+#if SB_HAS(PLAYER_WITH_URL)
+    std::string source_url;
+    bool is_url_based;
+#endif  // SB_HAS(PLAYER_WITH_URL)
+  };
+
+  void StartTask(StartTaskParameters parameters);
+  void SetVolumeTask(float volume);
+  void SetPlaybackRateTask(float volume);
+  void SetDurationTask(base::TimeDelta duration);
+
+  // DemuxerHost implementation.
+  void OnBufferedTimeRangesChanged(
+      const ::media::Ranges<base::TimeDelta>& ranges) override;
+  void SetDuration(base::TimeDelta duration) override;
+  void OnDemuxerError(PipelineStatus error) override;
+
+#if SB_HAS(PLAYER_WITH_URL)
+  void CreateUrlPlayer(const std::string& source_url);
+  void SetDrmSystem(SbDrmSystem drm_system);
+#endif  // SB_HAS(PLAYER_WITH_URL)
+  void CreatePlayer(SbDrmSystem drm_system);
+
+  void OnDemuxerInitialized(PipelineStatus status);
+  void OnDemuxerSeeked(PipelineStatus status);
+  void OnDemuxerStopped();
+  void OnDemuxerStreamRead(
+      ::media::DemuxerStream::Type type, int max_number_buffers_to_read,
+      ::media::DemuxerStream::Status status,
+      const std::vector<scoped_refptr<::media::DecoderBuffer>>& buffers);
+  // SbPlayerBridge::Host implementation.
+  void OnNeedData(::media::DemuxerStream::Type type,
+                  int max_number_of_buffers_to_write) override;
+  void OnPlayerStatus(SbPlayerState state) override;
+  void OnPlayerError(SbPlayerError error, const std::string& message) override;
+
+  // Used to make a delayed call to OnNeedData() if |audio_read_delayed_| is
+  // true. If |audio_read_delayed_| is false, that means the delayed call has
+  // been cancelled due to a seek.
+  void DelayedNeedData(int max_number_of_buffers_to_write);
+
+  void UpdateDecoderConfig(::media::DemuxerStream* stream);
+  void CallSeekCB(PipelineStatus status, const std::string& error_message);
+  void CallErrorCB(PipelineStatus status, const std::string& error_message);
+
+  void SuspendTask(base::WaitableEvent* done_event);
+  void ResumeTask(PipelineWindow window, base::WaitableEvent* done_event);
+
+  // Store the media time retrieved by GetMediaTime so we can cache it as an
+  // estimate and avoid calling SbPlayerGetInfo too frequently.
+  void StoreMediaTime(base::TimeDelta media_time);
+
+  // Retrieve the statistics as a string and append to message.
+  std::string AppendStatisticsString(const std::string& message) const;
+
+  // Get information on the time since app start and the time since the last
+  // playback resume.
+  std::string GetTimeInformation() const;
+
+  void RunSetDrmSystemReadyCB(DrmSystemReadyCB drm_system_ready_cb);
+
+  void SetReadInProgress(::media::DemuxerStream::Type type, bool in_progress);
+  bool GetReadInProgress(::media::DemuxerStream::Type type) const;
+
+  // An identifier string for the pipeline, used in CVal to identify multiple
+  // pipelines.
+  const std::string pipeline_identifier_;
+
+  // A wrapped interface of starboard player functions, which will be used in
+  // underlying SbPlayerBridge.
+  SbPlayerInterface* sbplayer_interface_;
+
+  // Message loop used to execute pipeline tasks.  It is thread-safe.
+  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
+
+  // Whether we should save DecoderBuffers for resume after suspend.
+  const bool allow_resume_after_suspend_;
+
+  // Whether we enable batched sample write functionality.
+  const bool allow_batched_sample_write_;
+
+  // The default output mode passed to `SbPlayerGetPreferredOutputMode()`.
+  SbPlayerOutputMode default_output_mode_ = kSbPlayerOutputModeInvalid;
+
+  // The window this player associates with.  It should only be assigned in the
+  // dtor and accessed once by SbPlayerCreate().
+  PipelineWindow window_;
+
+  // Call to get the SbDecodeTargetGraphicsContextProvider for SbPlayerCreate().
+  const GetDecodeTargetGraphicsContextProviderFunc
+      get_decode_target_graphics_context_provider_func_;
+
+  // Lock used to serialize access for the following member variables.
+  mutable base::Lock lock_;
+
+  // Amount of available buffered data.  Set by filters.
+  ::media::Ranges<base::TimeDelta> buffered_time_ranges_;
+
+  // True when AddBufferedByteRange() has been called more recently than
+  // DidLoadingProgress().
+  mutable bool did_loading_progress_;
+
+  // Video's natural width and height.  Set by filters.
+  gfx::Size natural_size_;
+
+  // Current volume level (from 0.0f to 1.0f).  This value is set immediately
+  // via SetVolume() and a task is dispatched on the message loop to notify the
+  // filters.
+  base::CVal<float> volume_;
+
+  // Current playback rate (>= 0.0f).  This value is set immediately via
+  // SetPlaybackRate() and a task is dispatched on the message loop to notify
+  // the filters.
+  base::CVal<float> playback_rate_;
+
+  // The saved audio and video demuxer streams.  Note that it is safe to store
+  // raw pointers of the demuxer streams, as the Demuxer guarantees that its
+  // |DemuxerStream|s live as long as the Demuxer itself.
+  ::media::DemuxerStream* audio_stream_ = nullptr;
+  ::media::DemuxerStream* video_stream_ = nullptr;
+
+  mutable PipelineStatistics statistics_;
+
+  // The following member variables are only accessed by tasks posted to
+  // |task_runner_|.
+
+  // Temporary callback used for Stop().
+  base::Closure stop_cb_;
+
+  // Permanent callbacks passed in via Start().
+  SetDrmSystemReadyCB set_drm_system_ready_cb_;
+  PipelineStatusCB ended_cb_;
+  ErrorCB error_cb_;
+  BufferingStateCB buffering_state_cb_;
+  base::Closure duration_change_cb_;
+  base::Closure output_mode_change_cb_;
+  base::Closure content_size_change_cb_;
+  base::Optional<bool> decode_to_texture_output_mode_;
+#if SB_HAS(PLAYER_WITH_URL)
+  SbPlayerBridge::OnEncryptedMediaInitDataEncounteredCB
+      on_encrypted_media_init_data_encountered_cb_;
+#endif  //  SB_HAS(PLAYER_WITH_URL)
+
+  // Demuxer reference used for setting the preload value.
+  Demuxer* demuxer_ = nullptr;
+  bool audio_read_in_progress_ = false;
+  bool audio_read_delayed_ = false;
+  bool video_read_in_progress_ = false;
+  base::CVal<base::TimeDelta> duration_;
+
+#if SB_HAS(PLAYER_WITH_URL)
+  base::TimeDelta start_date_;
+  bool is_url_based_;
+#endif  // SB_HAS(PLAYER_WITH_URL)
+
+  scoped_refptr<SbPlayerSetBoundsHelper> set_bounds_helper_;
+
+  // The following member variables can be accessed from WMPI thread but all
+  // modifications to them happens on the pipeline thread.  So any access of
+  // them from the WMPI thread and any modification to them on the pipeline
+  // thread has to guarded by lock.  Access to them from the pipeline thread
+  // needn't to be guarded.
+
+  // Temporary callback used for Start() and Seek().
+  SeekCB seek_cb_;
+  base::TimeDelta seek_time_;
+  std::unique_ptr<SbPlayerBridge> player_bridge_;
+  bool is_initial_preroll_ = true;
+  base::CVal<bool> started_;
+  base::CVal<bool> suspended_;
+  base::CVal<bool> stopped_;
+  base::CVal<bool> ended_;
+  base::CVal<SbPlayerState> player_state_;
+
+  DecodeTargetProvider* decode_target_provider_;
+
+#if SB_API_VERSION >= 15
+  const SbTime audio_write_duration_local_;
+  const SbTime audio_write_duration_remote_;
+
+  // The two variables below should always contain the same value.  They are
+  // kept as separate variables so we can keep the existing implementation as
+  // is, which simplifies the implementation across multiple Starboard versions.
+  SbTime audio_write_duration_ = 0;
+  SbTime audio_write_duration_for_preroll_ = audio_write_duration_;
+#else   // SB_API_VERSION >= 15
+  // Read audio from the stream if |timestamp_of_last_written_audio_| is less
+  // than |seek_time_| + |audio_write_duration_for_preroll_|, this effectively
+  // allows 10 seconds of audio to be written to the SbPlayer after playback
+  // startup or seek.
+  SbTime audio_write_duration_for_preroll_ = 10 * kSbTimeSecond;
+  // Don't read audio from the stream more than |audio_write_duration_| ahead of
+  // the current media time during playing.
+  SbTime audio_write_duration_ = kSbTimeSecond;
+#endif  // SB_API_VERSION >= 15
+  // Only call GetMediaTime() from OnNeedData if it has been
+  // |kMediaTimeCheckInterval| since the last call to GetMediaTime().
+  static const SbTime kMediaTimeCheckInterval = 0.1 * kSbTimeSecond;
+  // Timestamp for the last written audio.
+  SbTime timestamp_of_last_written_audio_ = 0;
+
+  // Last media time reported by GetMediaTime().
+  base::CVal<SbTime> last_media_time_;
+  // Time when we last checked the media time.
+  SbTime last_time_media_time_retrieved_ = 0;
+  // Counter for retrograde media time.
+  size_t retrograde_media_time_counter_ = 0;
+  // The maximum video playback capabilities required for the playback.
+  base::CVal<std::string> max_video_capabilities_;
+
+  PlaybackStatistics playback_statistics_;
+
+  SbTimeMonotonic last_resume_time_ = -1;
+
+  SbTimeMonotonic set_drm_system_ready_cb_time_ = -1;
+
+  DISALLOW_COPY_AND_ASSIGN(SbPlayerPipeline);
+};
+
+}  // namespace media
+}  // namespace cobalt
+
+#endif  // COBALT_MEDIA_BASE_SBPLAYER_PIPELINE_H_
diff --git a/cobalt/media/media_module.cc b/cobalt/media/media_module.cc
index 00db9fe..a952d2b 100644
--- a/cobalt/media/media_module.cc
+++ b/cobalt/media/media_module.cc
@@ -189,6 +189,11 @@
     LOG(INFO) << (allow_batched_sample_write_ ? "Enabling" : "Disabling")
               << " batched sample write.";
     return true;
+  } else if (name == "ForcePunchOutByDefault") {
+    force_punch_out_by_default_ = value;
+    LOG(INFO) << "Force punch out by default : "
+              << (force_punch_out_by_default_ ? "enabled" : "disabled");
+    return true;
   } else if (name == "EnableMetrics") {
     sbplayer_interface_->EnableCValStats(value);
     LOG(INFO) << (value ? "Enabling" : "Disabling")
@@ -207,6 +212,7 @@
     return true;
 #endif  // SB_API_VERSION >= 15
   }
+
   return false;
 }
 
@@ -223,7 +229,7 @@
       base::Bind(&MediaModule::GetSbDecodeTargetGraphicsContextProvider,
                  base::Unretained(this)),
       client, this, options_.allow_resume_after_suspend,
-      allow_batched_sample_write_,
+      allow_batched_sample_write_, force_punch_out_by_default_,
 #if SB_API_VERSION >= 15
       audio_write_duration_local_, audio_write_duration_remote_,
 #endif  // SB_API_VERSION >= 15
diff --git a/cobalt/media/media_module.h b/cobalt/media/media_module.h
index 59a753e..cc5db71 100644
--- a/cobalt/media/media_module.h
+++ b/cobalt/media/media_module.h
@@ -123,6 +123,14 @@
   bool suspended_ = false;
 
   bool allow_batched_sample_write_ = false;
+  // When set to `false` (the default value), Cobalt calls
+  // `SbPlayerGetPreferredOutputMode()` with `kSbPlayerOutputModeInvalid` when
+  // there is no preference on output mode.
+  // When set to `true` via `h5vcc.settings`, Cobalt calls
+  // `SbPlayerGetPreferredOutputMode()` with `kSbPlayerOutputModePunchOut` when
+  // there is no preference on output mode.  This allows us to fallback to the
+  // previous behavior.
+  bool force_punch_out_by_default_ = false;
 
 #if SB_API_VERSION >= 15
   SbTime audio_write_duration_local_ = kSbPlayerWriteDurationLocal;
diff --git a/cobalt/media/player/web_media_player_impl.cc b/cobalt/media/player/web_media_player_impl.cc
index b17f82e..8a121a6 100644
--- a/cobalt/media/player/web_media_player_impl.cc
+++ b/cobalt/media/player/web_media_player_impl.cc
@@ -22,6 +22,7 @@
 #include "base/trace_event/trace_event.h"
 #include "cobalt/base/instance_counter.h"
 #include "cobalt/media/base/drm_system.h"
+#include "cobalt/media/base/sbplayer_pipeline.h"
 #include "cobalt/media/player/web_media_player_proxy.h"
 #include "cobalt/media/progressive/data_source_reader.h"
 #include "cobalt/media/progressive/demuxer_extension_wrapper.h"
@@ -118,6 +119,7 @@
         get_decode_target_graphics_context_provider_func,
     WebMediaPlayerClient* client, WebMediaPlayerDelegate* delegate,
     bool allow_resume_after_suspend, bool allow_batched_sample_write,
+    bool force_punch_out_by_default,
 #if SB_API_VERSION >= 15
     SbTime audio_write_duration_local, SbTime audio_write_duration_remote,
 #endif  // SB_API_VERSION >= 15
@@ -130,6 +132,7 @@
       delegate_(delegate),
       allow_resume_after_suspend_(allow_resume_after_suspend),
       allow_batched_sample_write_(allow_batched_sample_write),
+      force_punch_out_by_default_(force_punch_out_by_default),
       proxy_(new WebMediaPlayerProxy(main_loop_->task_runner(), this)),
       media_log_(media_log),
       is_local_source_(false),
@@ -145,14 +148,15 @@
   media_log_->AddEvent<::media::MediaLogEvent::kWebMediaPlayerCreated>();
 
   pipeline_thread_.Start();
-  pipeline_ =
-      Pipeline::Create(interface, window, pipeline_thread_.task_runner(),
-                       get_decode_target_graphics_context_provider_func,
-                       allow_resume_after_suspend_, allow_batched_sample_write_,
+  pipeline_ = new SbPlayerPipeline(
+      interface, window, pipeline_thread_.task_runner(),
+      get_decode_target_graphics_context_provider_func,
+      allow_resume_after_suspend_, allow_batched_sample_write_,
+      force_punch_out_by_default_,
 #if SB_API_VERSION >= 15
-                       audio_write_duration_local, audio_write_duration_remote,
+      audio_write_duration_local, audio_write_duration_remote,
 #endif  // SB_API_VERSION >= 15
-                       media_log_, decode_target_provider_.get());
+      media_log_, decode_target_provider_.get());
 
   // Also we want to be notified of |main_loop_| destruction.
   main_loop_->AddDestructionObserver(this);
@@ -807,7 +811,9 @@
 
   state_.starting = true;
 
-  pipeline_->SetDecodeToTextureOutputMode(client_->PreferDecodeToTexture());
+  if (client_->PreferDecodeToTexture()) {
+    pipeline_->SetPreferredOutputModeToDecodeToTexture();
+  }
   pipeline_->Start(
       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::SetDrmSystemReadyCB),
       BIND_TO_RENDER_LOOP(
@@ -827,7 +833,9 @@
 
   state_.starting = true;
 
-  pipeline_->SetDecodeToTextureOutputMode(client_->PreferDecodeToTexture());
+  if (client_->PreferDecodeToTexture()) {
+    pipeline_->SetPreferredOutputModeToDecodeToTexture();
+  }
   pipeline_->Start(
       demuxer, BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::SetDrmSystemReadyCB),
       BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded),
diff --git a/cobalt/media/player/web_media_player_impl.h b/cobalt/media/player/web_media_player_impl.h
index 4f0c6a9..9db4419 100644
--- a/cobalt/media/player/web_media_player_impl.h
+++ b/cobalt/media/player/web_media_player_impl.h
@@ -110,6 +110,7 @@
                      WebMediaPlayerDelegate* delegate,
                      bool allow_resume_after_suspend,
                      bool allow_batched_sample_write,
+                     bool force_punch_out_by_default,
 #if SB_API_VERSION >= 15
                      SbTime audio_write_duration_local,
                      SbTime audio_write_duration_remote,
@@ -298,6 +299,7 @@
   WebMediaPlayerDelegate* const delegate_;
   const bool allow_resume_after_suspend_;
   const bool allow_batched_sample_write_;
+  const bool force_punch_out_by_default_;
   scoped_refptr<DecodeTargetProvider> decode_target_provider_;
 
   scoped_refptr<WebMediaPlayerProxy> proxy_;
diff --git a/cobalt/media/url_fetcher_data_source.cc b/cobalt/media/url_fetcher_data_source.cc
index a52e1fb..69cbf8b 100644
--- a/cobalt/media/url_fetcher_data_source.cc
+++ b/cobalt/media/url_fetcher_data_source.cc
@@ -340,7 +340,7 @@
       std::move(net::URLFetcher::Create(url_, net::URLFetcher::GET, this));
   fetcher_->SetRequestContext(
       network_module_->url_request_context_getter().get());
-  network_module_->AddClientHintHeaders(*fetcher_);
+  network_module_->AddClientHintHeaders(*fetcher_, network::kCallTypeMedia);
   std::unique_ptr<loader::URLFetcherStringWriter> download_data_writer(
       new loader::URLFetcherStringWriter());
   fetcher_->SaveResponseWithWriter(std::move(download_data_writer));
diff --git a/cobalt/network/net_poster.cc b/cobalt/network/net_poster.cc
index c2d1a1b..0e5b02f 100644
--- a/cobalt/network/net_poster.cc
+++ b/cobalt/network/net_poster.cc
@@ -49,7 +49,7 @@
   url_fetcher->SetStopOnRedirect(true);
   url_fetcher->SetRequestContext(
       network_module_->url_request_context_getter().get());
-  network_module_->AddClientHintHeaders(*url_fetcher);
+  network_module_->AddClientHintHeaders(*url_fetcher, network::kCallTypePost);
 
   if (data.size()) {
     url_fetcher->SetUploadData(content_type, data);
diff --git a/cobalt/network/network_module.cc b/cobalt/network/network_module.cc
index b358c11..15e3dbd 100644
--- a/cobalt/network/network_module.cc
+++ b/cobalt/network/network_module.cc
@@ -36,45 +36,49 @@
 #endif
 }  // namespace
 
-NetworkModule::NetworkModule(const Options& options)
-    : storage_manager_(NULL), options_(options) {
+NetworkModule::NetworkModule(const Options& options) : options_(options) {
   Initialize("Null user agent string.", NULL);
 }
 
 NetworkModule::NetworkModule(
     const std::string& user_agent_string,
     const std::vector<std::string>& client_hint_headers,
-    storage::StorageManager* storage_manager,
     base::EventDispatcher* event_dispatcher, const Options& options)
-    : client_hint_headers_(client_hint_headers),
-      storage_manager_(storage_manager),
-      options_(options) {
+    : client_hint_headers_(client_hint_headers), options_(options) {
   Initialize(user_agent_string, event_dispatcher);
 }
 
+void NetworkModule::WillDestroyCurrentMessageLoop() {
+#if defined(DIAL_SERVER)
+  dial_service_proxy_ = nullptr;
+  dial_service_.reset();
+#endif
+
+  cookie_jar_.reset();
+  net_poster_.reset();
+  url_request_context_.reset();
+  network_delegate_.reset();
+}
+
 NetworkModule::~NetworkModule() {
   // Order of destruction is important here.
   // URLRequestContext and NetworkDelegate must be destroyed on the IO thread.
   // The ObjectWatchMultiplexer must be destroyed last.  (The sockets owned
   // by URLRequestContext will destroy their ObjectWatchers, which need the
   // multiplexer.)
-  url_request_context_getter_ = NULL;
-#if defined(DIAL_SERVER)
-  dial_service_proxy_ = NULL;
-  task_runner()->DeleteSoon(FROM_HERE, dial_service_.release());
-#endif
+  url_request_context_getter_ = nullptr;
 
-  task_runner()->DeleteSoon(FROM_HERE, cookie_jar_.release());
-  task_runner()->DeleteSoon(FROM_HERE, net_poster_.release());
-  task_runner()->DeleteSoon(FROM_HERE, url_request_context_.release());
-  task_runner()->DeleteSoon(FROM_HERE, network_delegate_.release());
-
-  // This will run the above task, and then stop the thread.
-  thread_.reset(NULL);
+  if (thread_) {
+    // Wait for all previously posted tasks to finish.
+    thread_->message_loop()->task_runner()->WaitForFence();
+    // This will trigger a call to WillDestroyCurrentMessageLoop in the thread
+    // and wait for it to finish.
+    thread_.reset();
+  }
 #if !defined(STARBOARD)
-  object_watch_multiplexer_.reset(NULL);
+  object_watch_multiplexer_.reset();
 #endif
-  network_system_.reset(NULL);
+  network_system_.reset();
 }
 
 std::string NetworkModule::GetUserAgent() const {
@@ -101,8 +105,20 @@
                  base::Unretained(url_request_context_.get()), enable_quic));
 }
 
+void NetworkModule::SetEnableClientHintHeadersFlagsFromPersistentSettings() {
+  // Called on initialization and when the persistent setting is changed.
+  if (options_.persistent_settings != nullptr) {
+    enable_client_hint_headers_flags_.store(
+        options_.persistent_settings->GetPersistentSettingAsInt(
+            kClientHintHeadersEnabledPersistentSettingsKey, 0));
+  }
+}
+
 void NetworkModule::Initialize(const std::string& user_agent_string,
                                base::EventDispatcher* event_dispatcher) {
+  storage_manager_.reset(
+      new storage::StorageManager(options_.storage_manager_options));
+
   thread_.reset(new base::Thread("NetworkModule"));
 #if !defined(STARBOARD)
   object_watch_multiplexer_.reset(new base::ObjectWatchMultiplexer());
@@ -111,6 +127,8 @@
   http_user_agent_settings_.reset(new net::StaticHttpUserAgentSettings(
       options_.preferred_language, user_agent_string));
 
+  SetEnableClientHintHeadersFlagsFromPersistentSettings();
+
 #if defined(ENABLE_DEBUG_COMMAND_LINE_SWITCHES)
   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
 
@@ -174,15 +192,16 @@
 
 void NetworkModule::OnCreate(base::WaitableEvent* creation_event) {
   DCHECK(task_runner()->RunsTasksInCurrentSequence());
+  base::MessageLoopCurrent::Get()->AddDestructionObserver(this);
 
   net::NetLog* net_log = NULL;
 #if defined(ENABLE_NETWORK_LOGGING)
   net_log = net_log_.get();
 #endif
   url_request_context_.reset(
-      new URLRequestContext(storage_manager_, options_.custom_proxy, net_log,
-                            options_.ignore_certificate_errors, task_runner(),
-                            options_.persistent_settings));
+      new URLRequestContext(storage_manager_.get(), options_.custom_proxy,
+                            net_log, options_.ignore_certificate_errors,
+                            task_runner(), options_.persistent_settings));
   network_delegate_.reset(new NetworkDelegate(options_.cookie_policy,
                                               options_.https_requirement,
                                               options_.cors_policy));
@@ -201,11 +220,9 @@
   creation_event->Signal();
 }
 
-void NetworkModule::AddClientHintHeaders(net::URLFetcher& url_fetcher) const {
-  // Check if persistent setting is enabled before adding the headers.
-  if (options_.persistent_settings != nullptr &&
-      options_.persistent_settings->GetPersistentSettingAsBool(
-          kClientHintHeadersEnabledPersistentSettingsKey, false)) {
+void NetworkModule::AddClientHintHeaders(
+    net::URLFetcher& url_fetcher, ClientHintHeadersCallType call_type) const {
+  if (enable_client_hint_headers_flags_.load() & call_type) {
     for (const auto& header : client_hint_headers_) {
       url_fetcher.AddExtraRequestHeader(header);
     }
diff --git a/cobalt/network/network_module.h b/cobalt/network/network_module.h
index 1162cac..69f226d 100644
--- a/cobalt/network/network_module.h
+++ b/cobalt/network/network_module.h
@@ -30,6 +30,7 @@
 #include "cobalt/network/url_request_context.h"
 #include "cobalt/network/url_request_context_getter.h"
 #include "cobalt/persistent_storage/persistent_settings.h"
+#include "cobalt/storage/storage_manager.h"
 #include "net/base/static_cookie_policy.h"
 #include "url/gurl.h"
 #if defined(DIAL_SERVER)
@@ -38,26 +39,34 @@
 #include "net/dial/dial_service.h"
 #endif
 #include "net/url_request/http_user_agent_settings.h"
+#include "starboard/common/atomic.h"
 
 namespace base {
 class WaitableEvent;
 }  // namespace base
 
 namespace cobalt {
-
-namespace storage {
-class StorageManager;
-}  // namespace storage
-
 namespace network {
 
+// Used to differentiate type of network call for Client Hint Headers.
+// Values correspond to bit masks against |enable_client_hint_headers_flags_|.
+enum ClientHintHeadersCallType : int32_t {
+  kCallTypeLoader = (1u << 0),
+  kCallTypeMedia = (1u << 1),
+  kCallTypePost = (1u << 2),
+  kCallTypePreflight = (1u << 3),
+  kCallTypeUpdater = (1u << 4),
+  kCallTypeXHR = (1u << 5),
+};
+
+// Holds bit mask flag, read into |enable_client_hint_headers_flags_|.
 const char kClientHintHeadersEnabledPersistentSettingsKey[] =
     "clientHintHeadersEnabled";
 
 class NetworkSystem;
 // NetworkModule wraps various networking-related components such as
 // a URL request context. This is owned by BrowserModule.
-class NetworkModule {
+class NetworkModule : public base::MessageLoop::DestructionObserver {
  public:
   struct Options {
     Options()
@@ -76,6 +85,7 @@
     std::string custom_proxy;
     SbTime max_network_delay;
     persistent_storage::PersistentSettings* persistent_settings;
+    storage::StorageManager::Options storage_manager_options;
   };
 
   // Simple constructor intended to be used only by tests.
@@ -84,7 +94,6 @@
   // Constructor for production use.
   NetworkModule(const std::string& user_agent_string,
                 const std::vector<std::string>& client_hint_headers,
-                storage::StorageManager* storage_manager,
                 base::EventDispatcher* event_dispatcher,
                 const Options& options = Options());
   ~NetworkModule();
@@ -104,7 +113,9 @@
   scoped_refptr<base::SequencedTaskRunner> task_runner() const {
     return thread_->task_runner();
   }
-  storage::StorageManager* storage_manager() const { return storage_manager_; }
+  storage::StorageManager* storage_manager() const {
+    return storage_manager_.get();
+  }
   network_bridge::CookieJar* cookie_jar() const { return cookie_jar_.get(); }
   network_bridge::PostSender GetPostSender() const;
 #if defined(DIAL_SERVER)
@@ -116,9 +127,15 @@
 
   void SetEnableQuic(bool enable_quic);
 
-  // Adds the Client Hint Headers to the provided URLFetcher.
-  // It is conditional on kClientHintHeadersEnabledPersistentSettingsKey != 0.
-  void AddClientHintHeaders(net::URLFetcher& url_fetcher) const;
+  // Checks persistent settings to determine if Client Hint Headers are enabled.
+  void SetEnableClientHintHeadersFlagsFromPersistentSettings();
+
+  // Adds the Client Hint Headers to the provided URLFetcher if enabled.
+  void AddClientHintHeaders(net::URLFetcher& url_fetcher,
+                            ClientHintHeadersCallType call_type) const;
+
+  // From base::MessageLoop::DestructionObserver.
+  void WillDestroyCurrentMessageLoop() override;
 
  private:
   void Initialize(const std::string& user_agent_string,
@@ -127,7 +144,8 @@
   std::unique_ptr<network_bridge::NetPoster> CreateNetPoster();
 
   std::vector<std::string> client_hint_headers_;
-  storage::StorageManager* storage_manager_;
+  starboard::atomic_int32_t enable_client_hint_headers_flags_;
+  std::unique_ptr<storage::StorageManager> storage_manager_;
   std::unique_ptr<base::Thread> thread_;
   std::unique_ptr<URLRequestContext> url_request_context_;
   scoped_refptr<URLRequestContextGetter> url_request_context_getter_;
diff --git a/cobalt/persistent_storage/persistent_settings.cc b/cobalt/persistent_storage/persistent_settings.cc
index c4db368..ce64f97 100644
--- a/cobalt/persistent_storage/persistent_settings.cc
+++ b/cobalt/persistent_storage/persistent_settings.cc
@@ -23,19 +23,15 @@
 #include "starboard/common/file.h"
 #include "starboard/common/log.h"
 #include "starboard/configuration_constants.h"
+#include "starboard/system.h"
 
 namespace cobalt {
 namespace persistent_storage {
 
 namespace {
-
 // Protected persistent settings key indicating whether or not the persistent
 // settings file has been validated.
 const char kValidated[] = "validated";
-
-// Signals the given WaitableEvent.
-void SignalWaitableEvent(base::WaitableEvent* event) { event->Signal(); }
-
 }  // namespace
 
 void PersistentSettings::WillDestroyCurrentMessageLoop() {
@@ -69,22 +65,6 @@
   message_loop()->task_runner()->PostTask(
       FROM_HERE, base::Bind(&PersistentSettings::InitializeWriteablePrefStore,
                             base::Unretained(this)));
-
-  // Register as a destruction observer to shut down the Web Agent once all
-  // pending tasks have been executed and the message loop is about to be
-  // destroyed. This allows us to safely stop the thread, drain the task queue,
-  // then destroy the internal components before the message loop is reset.
-  // No posted tasks will be executed once the thread is stopped.
-  message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::Bind(&base::MessageLoop::AddDestructionObserver,
-                 base::Unretained(message_loop()), base::Unretained(this)));
-
-  // This works almost like a PostBlockingTask, except that any blocking that
-  // may be necessary happens when Stop() is called instead of right now.
-  message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::Bind(&SignalWaitableEvent,
-                            base::Unretained(&destruction_observer_added_)));
 }
 
 PersistentSettings::~PersistentSettings() {
@@ -96,11 +76,19 @@
   // the destruction observer to be notified.
   writeable_pref_store_initialized_.Wait();
   destruction_observer_added_.Wait();
+  // Wait for all previously posted tasks to finish.
+  thread_.message_loop()->task_runner()->WaitForFence();
   thread_.Stop();
 }
 
 void PersistentSettings::InitializeWriteablePrefStore() {
   DCHECK_EQ(base::MessageLoop::current(), message_loop());
+  // Register as a destruction observer to shut down the thread once all
+  // pending tasks have been executed and the message loop is about to be
+  // destroyed. This allows us to safely stop the thread, drain the task queue,
+  // then destroy the internal components before the message loop is reset.
+  // No posted tasks will be executed once the thread is stopped.
+  base::MessageLoopCurrent::Get()->AddDestructionObserver(this);
   {
     base::AutoLock auto_lock(pref_store_lock_);
     pref_store_ = base::MakeRefCounted<JsonPrefStore>(
@@ -114,6 +102,7 @@
   if (!validated_initial_settings_) {
     starboard::SbFileDeleteRecursive(persistent_settings_file_.c_str(), true);
   }
+  destruction_observer_added_.Signal();
 }
 
 void PersistentSettings::ValidatePersistentSettings() {
diff --git a/cobalt/renderer/backend/egl/BUILD.gn b/cobalt/renderer/backend/egl/BUILD.gn
index b9e2d8f..cf502f1 100644
--- a/cobalt/renderer/backend/egl/BUILD.gn
+++ b/cobalt/renderer/backend/egl/BUILD.gn
@@ -26,16 +26,12 @@
     "pbuffer_render_target.cc",
     "pbuffer_render_target.h",
     "render_target.h",
-    "resource_context.cc",
-    "resource_context.h",
     "texture.cc",
     "texture.h",
     "texture_data.cc",
     "texture_data.h",
     "texture_data_cpu.cc",
     "texture_data_cpu.h",
-    "texture_data_pbo.cc",
-    "texture_data_pbo.h",
     "utils.cc",
     "utils.h",
   ]
diff --git a/cobalt/renderer/backend/egl/graphics_context.cc b/cobalt/renderer/backend/egl/graphics_context.cc
index d46389d..ddaa597 100644
--- a/cobalt/renderer/backend/egl/graphics_context.cc
+++ b/cobalt/renderer/backend/egl/graphics_context.cc
@@ -12,12 +12,12 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+#include "cobalt/renderer/backend/egl/graphics_context.h"
+
 #include <algorithm>
 #include <memory>
 #include <utility>
 
-#include "cobalt/renderer/backend/egl/graphics_context.h"
-
 #include "base/debug/leak_annotations.h"
 #include "base/trace_event/trace_event.h"
 #include "cobalt/base/polymorphic_downcast.h"
@@ -53,15 +53,16 @@
 }  // namespace
 
 GraphicsContextEGL::GraphicsContextEGL(GraphicsSystem* parent_system,
-                                       EGLDisplay display, EGLConfig config,
-                                       ResourceContext* resource_context)
+                                       EGLDisplay display, EGLConfig config)
     : GraphicsContext(parent_system),
       display_(display),
       config_(config),
       is_current_(false) {
   // Create an OpenGL ES 2.0 context.
   EGLint context_attrib_list[] = {
-      EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE,
+      EGL_CONTEXT_CLIENT_VERSION,
+      2,
+      EGL_NONE,
   };
   context_ = EGL_CALL_SIMPLE(
       eglCreateContext(display, config, EGL_NO_CONTEXT, context_attrib_list));
diff --git a/cobalt/renderer/backend/egl/graphics_context.h b/cobalt/renderer/backend/egl/graphics_context.h
index 7c9e7c6..d7116ac 100644
--- a/cobalt/renderer/backend/egl/graphics_context.h
+++ b/cobalt/renderer/backend/egl/graphics_context.h
@@ -21,7 +21,6 @@
 #include "base/optional.h"
 #include "cobalt/base/polymorphic_downcast.h"
 #include "cobalt/renderer/backend/egl/render_target.h"
-#include "cobalt/renderer/backend/egl/resource_context.h"
 #include "cobalt/renderer/backend/egl/texture.h"
 #include "cobalt/renderer/backend/egl/texture_data.h"
 #include "cobalt/renderer/backend/graphics_context.h"  // nogncheck
@@ -38,7 +37,7 @@
 class GraphicsContextEGL : public GraphicsContext {
  public:
   GraphicsContextEGL(GraphicsSystem* parent_system, EGLDisplay display,
-                     EGLConfig config, ResourceContext* resource_context);
+                     EGLConfig config);
   ~GraphicsContextEGL() override;
 
   GraphicsSystemEGL* system_egl();
diff --git a/cobalt/renderer/backend/egl/graphics_system.cc b/cobalt/renderer/backend/egl/graphics_system.cc
index e23cf9c..f4ed70a 100644
--- a/cobalt/renderer/backend/egl/graphics_system.cc
+++ b/cobalt/renderer/backend/egl/graphics_system.cc
@@ -200,14 +200,15 @@
 }
 
 GraphicsSystemEGL::~GraphicsSystemEGL() {
-  resource_context_.reset();
-
+  LOG(INFO) << "GraphicsSystemEGL::~GraphicsSystemEGL()";
   if (window_surface_ != EGL_NO_SURFACE) {
     EGL_CALL_SIMPLE(eglDestroySurface(display_, window_surface_));
   }
 
   EGL_CALL_SIMPLE(eglTerminate(display_));
-  LOG(INFO) << "eglTerminate returned " << EGL_CALL_SIMPLE(eglGetError());
+  EGLint result = EGL_CALL_SIMPLE(eglGetError());
+  if (result != EGL_SUCCESS) LOG(INFO) << "eglTerminate returned " << result;
+  LOG(INFO) << "GraphicsSystemEGL::~GraphicsSystemEGL() done";
 }
 
 std::unique_ptr<Display> GraphicsSystemEGL::CreateDisplay(
@@ -234,9 +235,8 @@
   // that data from graphics contexts created through this method, we must
   // enable sharing between them and the resource context, which is why we
   // must pass it in here.
-  ResourceContext* resource_context = NULL;
   return std::unique_ptr<GraphicsContext>(
-      new GraphicsContextEGL(this, display_, config_, resource_context));
+      new GraphicsContextEGL(this, display_, config_));
 }
 
 std::unique_ptr<TextureDataEGL> GraphicsSystemEGL::AllocateTextureData(
diff --git a/cobalt/renderer/backend/egl/graphics_system.h b/cobalt/renderer/backend/egl/graphics_system.h
index 4920900..0445231 100644
--- a/cobalt/renderer/backend/egl/graphics_system.h
+++ b/cobalt/renderer/backend/egl/graphics_system.h
@@ -18,7 +18,6 @@
 #include <memory>
 
 #include "base/optional.h"
-#include "cobalt/renderer/backend/egl/resource_context.h"
 #include "cobalt/renderer/backend/egl/texture_data.h"
 #include "cobalt/renderer/backend/graphics_system.h"
 #include "cobalt/renderer/egl_and_gles.h"
@@ -61,10 +60,6 @@
   // can actually be used to create a surface.  If successful, we store the
   // created surface to avoid re-creating it when it is needed later.
   EGLSurface window_surface_;
-
-  // A special graphics context which is used exclusively for mapping/unmapping
-  // texture memory.
-  base::Optional<ResourceContext> resource_context_;
 };
 
 }  // namespace backend
diff --git a/cobalt/renderer/backend/egl/resource_context.cc b/cobalt/renderer/backend/egl/resource_context.cc
deleted file mode 100644
index a397e6d..0000000
--- a/cobalt/renderer/backend/egl/resource_context.cc
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2015 The Cobalt Authors. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include "starboard/configuration.h"
-
-#include "cobalt/renderer/backend/egl/resource_context.h"
-
-#include "base/bind.h"
-#include "base/synchronization/waitable_event.h"
-#include "cobalt/renderer/backend/egl/texture.h"
-#include "cobalt/renderer/backend/egl/utils.h"
-
-namespace cobalt {
-namespace renderer {
-namespace backend {
-
-ResourceContext::ResourceContext(EGLDisplay display, EGLConfig config)
-    : display_(display), config_(config), thread_("GLTextureResrc") {
-  context_ = CreateGLES3Context(display, config, EGL_NO_CONTEXT);
-
-  // Create a dummy EGLSurface object to be assigned as the target surface
-  // when we need to make OpenGL calls that do not depend on a surface (e.g.
-  // creating a texture).
-  EGLint null_surface_attrib_list[] = {
-      EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE,
-  };
-  null_surface_ = EGL_CALL_SIMPLE(
-      eglCreatePbufferSurface(display, config, null_surface_attrib_list));
-  CHECK_EQ(EGL_SUCCESS, EGL_CALL_SIMPLE(eglGetError()));
-
-  // Start the resource context thread and immediately make the resource context
-  // current on that thread, so that subsequent calls to
-  // RunSynchronouslyWithinResourceContext() can assume it is current already.
-  thread_.Start();
-  thread_.message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::Bind(&ResourceContext::MakeCurrent, base::Unretained(this)));
-}
-
-ResourceContext::~ResourceContext() {
-  thread_.message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::Bind(&ResourceContext::ShutdownOnResourceThread,
-                            base::Unretained(this)));
-}
-
-namespace {
-void RunAndSignal(const base::Closure& function, base::WaitableEvent* event) {
-  function.Run();
-  event->Signal();
-}
-}  // namespace
-
-void ResourceContext::RunSynchronouslyWithinResourceContext(
-    const base::Closure& function) {
-  DCHECK_NE(thread_.message_loop(), base::MessageLoop::current())
-      << "This method should not be called within the resource context thread.";
-
-  base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL,
-                            base::WaitableEvent::InitialState::NOT_SIGNALED);
-  thread_.message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::Bind(&RunAndSignal, function, &event));
-  event.Wait();
-}
-
-void ResourceContext::AssertWithinResourceContext() {
-  DCHECK_EQ(thread_.message_loop(), base::MessageLoop::current());
-}
-
-void ResourceContext::MakeCurrent() {
-  DCHECK_EQ(thread_.message_loop(), base::MessageLoop::current());
-  EGL_CALL(eglMakeCurrent(display_, null_surface_, null_surface_, context_));
-}
-
-void ResourceContext::ShutdownOnResourceThread() {
-  EGL_CALL(
-      eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
-
-  EGL_CALL(eglDestroySurface(display_, null_surface_));
-  EGL_CALL(eglDestroyContext(display_, context_));
-}
-
-}  // namespace backend
-}  // namespace renderer
-}  // namespace cobalt
diff --git a/cobalt/renderer/backend/egl/resource_context.h b/cobalt/renderer/backend/egl/resource_context.h
deleted file mode 100644
index ccbc073..0000000
--- a/cobalt/renderer/backend/egl/resource_context.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright 2015 The Cobalt Authors. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef COBALT_RENDERER_BACKEND_EGL_RESOURCE_CONTEXT_H_
-#define COBALT_RENDERER_BACKEND_EGL_RESOURCE_CONTEXT_H_
-
-#include <memory>
-#include "base/callback.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/thread.h"
-#include "cobalt/renderer/egl_and_gles.h"
-
-namespace cobalt {
-namespace renderer {
-namespace backend {
-
-class TextureData;
-class RawTextureMemory;
-
-// The ResourceContext class encapsulates a GL context and a private thread
-// upon which that GL context is always current.  The GL context is associated
-// with a dummy surface.  The GL context will be shared with all other contexts
-// created by the GraphicsSystem that owns this ResourceContext.  This class
-// is useful when one wishes to create and allocate pixel buffer data (e.g. for
-// a texture) from any thread, that can later be converted to a texture for
-// a specific graphics context.  Resource management GL operations can be
-// performed (from any thread) by calling the method
-// RunSynchronouslyWithinResourceContext() and passing a function which one
-// wishes to run under the resource management GL context.
-class ResourceContext {
- public:
-  ResourceContext(EGLDisplay display, EGLConfig config);
-  ~ResourceContext();
-
-  EGLContext context() const { return context_; }
-
-  // This method can be used to execute a function on the resource context
-  // thread, under which it can be assumed that the resource context is
-  // current.
-  void RunSynchronouslyWithinResourceContext(const base::Closure& function);
-
-  // When called, asserts that the current thread is the resource context
-  // thread, which is the only thread which has the resource context current.
-  void AssertWithinResourceContext();
-
- private:
-  // Called once upon construction on the resource context thread.
-  void MakeCurrent();
-
-  // Releases the current context from the resource context thread, and then
-  // destroys the resource context (and dummy surface).  This is intended to
-  // be called from the destructor.
-  void ShutdownOnResourceThread();
-
-  EGLDisplay display_;
-
-  // The EGL/OpenGL ES context hosted by this GraphicsContextEGL object.
-  EGLContext context_;
-  EGLConfig config_;
-
-  // Since this context will be used only for resource management, it will
-  // not need an output surface associated with it.  We create a dummy surface
-  // to satisfy EGL requirements.
-  EGLSurface null_surface_;
-
-  // A private thread on which all resource management GL operations can be
-  // performed.  The resource context will always be current on this thread.
-  base::Thread thread_;
-
-  friend class ScopedMakeCurrent;
-};
-
-}  // namespace backend
-}  // namespace renderer
-}  // namespace cobalt
-
-#endif  // COBALT_RENDERER_BACKEND_EGL_RESOURCE_CONTEXT_H_
diff --git a/cobalt/renderer/backend/egl/texture.cc b/cobalt/renderer/backend/egl/texture.cc
index 9039377..08b1e95 100644
--- a/cobalt/renderer/backend/egl/texture.cc
+++ b/cobalt/renderer/backend/egl/texture.cc
@@ -21,7 +21,6 @@
 #include "cobalt/renderer/backend/egl/framebuffer_render_target.h"
 #include "cobalt/renderer/backend/egl/graphics_context.h"
 #include "cobalt/renderer/backend/egl/pbuffer_render_target.h"
-#include "cobalt/renderer/backend/egl/resource_context.h"
 #include "cobalt/renderer/backend/egl/texture_data.h"
 #include "cobalt/renderer/backend/egl/texture_data_cpu.h"
 #include "cobalt/renderer/backend/egl/utils.h"
diff --git a/cobalt/renderer/backend/egl/texture_data_pbo.cc b/cobalt/renderer/backend/egl/texture_data_pbo.cc
deleted file mode 100644
index 916869f..0000000
--- a/cobalt/renderer/backend/egl/texture_data_pbo.cc
+++ /dev/null
@@ -1,288 +0,0 @@
-// Copyright 2015 The Cobalt Authors. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#if defined(GLES3_SUPPORTED)
-#error "Support for gles3 features has been deprecated."
-
-#include "cobalt/renderer/backend/egl/texture_data_pbo.h"
-
-#include <GLES2/gl2ext.h>
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "cobalt/renderer/backend/egl/graphics_context.h"
-#include "cobalt/renderer/backend/egl/utils.h"
-
-namespace cobalt {
-namespace renderer {
-namespace backend {
-
-TextureDataPBO::TextureDataPBO(ResourceContext* resource_context,
-                               const math::Size& size, GLenum format)
-    : resource_context_(resource_context),
-      size_(size),
-      format_(format),
-      mapped_data_(NULL),
-      error_(false) {
-  data_size_ = static_cast<int64>(GetPitchInBytes()) * size_.height();
-
-  resource_context_->RunSynchronouslyWithinResourceContext(
-      base::Bind(&TextureDataPBO::InitAndMapPBO, base::Unretained(this)));
-}
-
-void TextureDataPBO::InitAndMapPBO() {
-  resource_context_->AssertWithinResourceContext();
-
-  // Use the resource context to allocate a GL pixel unpack buffer with the
-  // specified size.
-  glGenBuffers(1, &pixel_buffer_);
-  if (glGetError() != GL_NO_ERROR) {
-    LOG(ERROR) << "Error creating new buffer.";
-    error_ = true;
-    return;
-  }
-
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-  glBufferData(GL_PIXEL_UNPACK_BUFFER, data_size_, 0, GL_STATIC_DRAW);
-  if (glGetError() != GL_NO_ERROR) {
-    LOG(ERROR) << "Error allocating PBO data for image.";
-    error_ = true;
-    GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-    GL_CALL(glDeleteBuffers(1, &pixel_buffer_));
-    return;
-  }
-
-  // Map the GL pixel buffer data to CPU addressable memory.  We pass the flags
-  // MAP_INVALIDATE_BUFFER_BIT | MAP_UNSYNCHRONIZED_BIT to tell GL that it
-  // we don't care about previous data in the buffer and it shouldn't try to
-  // synchronize existing draw calls with it, both things which should be
-  // implied anyways since this is a brand new buffer, but we specify just in
-  // case.
-  mapped_data_ = static_cast<GLubyte*>(
-      glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, data_size_,
-                       GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT |
-                           GL_MAP_UNSYNCHRONIZED_BIT));
-  if (glGetError() != GL_NO_ERROR || !mapped_data_) {
-    LOG(ERROR) << "Error mapping PBO buffer data.";
-    error_ = true;
-    GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-    GL_CALL(glDeleteBuffers(1, &pixel_buffer_));
-    return;
-  }
-
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-}
-
-TextureDataPBO::~TextureDataPBO() {
-  // mapped_data_ will be non-null if ConvertToTexture() was never called.
-  if (mapped_data_) {
-    // In the case that we still have valid mapped_data_, we must release it,
-    // and we do so on the resource context.
-    resource_context_->RunSynchronouslyWithinResourceContext(
-        base::Bind(&TextureDataPBO::UnmapAndDeletePBO, base::Unretained(this)));
-  }
-}
-
-void TextureDataPBO::UnmapAndDeletePBO() {
-  resource_context_->AssertWithinResourceContext();
-
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-  GL_CALL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER));
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-  GL_CALL(glDeleteBuffers(1, &pixel_buffer_));
-}
-
-GLuint TextureDataPBO::ConvertToTexture(GraphicsContextEGL* graphics_context,
-                                        bool bgra_supported) {
-  DCHECK(mapped_data_) << "ConvertToTexture() should only ever be called once.";
-
-  // Since we wish to create a texture within the specified graphics context,
-  // we do the texture creation work using that context.
-  GraphicsContextEGL::ScopedMakeCurrent scoped_make_current(graphics_context);
-
-  // Our texture data remains mapped until this method is called, so we begin
-  // by unmapping it.
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-  GL_CALL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER));
-
-  // Setup our texture.
-  GLuint texture_handle;
-  GL_CALL(glGenTextures(1, &texture_handle));
-  GL_CALL(glBindTexture(GL_TEXTURE_2D, texture_handle));
-  SetupInitialTextureParameters();
-
-  // Determine the texture's GL format.
-  if (format_ == GL_BGRA_EXT) {
-    DCHECK(bgra_supported);
-  }
-
-  // Create the texture.  Since a GL_PIXEL_UNPACK_BUFFER is currently bound,
-  // the "data" field passed to glTexImage2D will refer to an offset into that
-  // buffer.
-  GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH,
-                        GetPitchInBytes() / BytesPerPixelForGLFormat(format_)));
-  glTexImage2D(GL_TEXTURE_2D, 0, format_, size_.width(), size_.height(), 0,
-               format_, GL_UNSIGNED_BYTE, 0);
-  if (glGetError() != GL_NO_ERROR) {
-    LOG(ERROR) << "Error calling glTexImage2D(size = (" << size_.width() << ", "
-               << size_.height() << "))";
-    GL_CALL(glDeleteTextures(1, &texture_handle));
-    // 0 is considered by GL to be an invalid handle.
-    texture_handle = 0;
-  }
-
-  GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
-  GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-
-  // The buffer is now referenced by the texture, and we no longer need to
-  // explicitly reference it.
-  GL_CALL(glDeleteBuffers(1, &pixel_buffer_));
-  mapped_data_ = NULL;
-
-  return texture_handle;
-}
-
-bool TextureDataPBO::CreationError() { return error_; }
-
-RawTextureMemoryPBO::RawTextureMemoryPBO(ResourceContext* resource_context,
-                                         size_t size_in_bytes, size_t alignment)
-    : size_in_bytes_(size_in_bytes),
-      alignment_(alignment),
-      resource_context_(resource_context) {
-  resource_context_->RunSynchronouslyWithinResourceContext(
-      base::Bind(&RawTextureMemoryPBO::InitAndMapPBO, base::Unretained(this)));
-}
-
-void RawTextureMemoryPBO::InitAndMapPBO() {
-  resource_context_->AssertWithinResourceContext();
-
-  int size_to_allocate = size_in_bytes_ + alignment_;
-
-  // Allocate a GL pixel unpack buffer with the specified size, leaving enough
-  // room such that we can adjust for alignment.
-  GL_CALL(glGenBuffers(1, &pixel_buffer_));
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-  GL_CALL(glBufferData(GL_PIXEL_UNPACK_BUFFER, size_to_allocate, 0,
-                       GL_STATIC_DRAW));
-
-  // Map the GL pixel buffer data to CPU addressable memory.  We pass the flags
-  // MAP_INVALIDATE_BUFFER_BIT | MAP_UNSYNCHRONIZED_BIT to tell GL that it
-  // we don't care about previous data in the buffer and it shouldn't try to
-  // synchronize existing draw calls with it, both things which should be
-  // implied anyways since this is a brand new buffer, but we specify just in
-  // case.
-  mapped_data_ = static_cast<GLubyte*>(
-      glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, size_to_allocate,
-                       GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT |
-                           GL_MAP_UNSYNCHRONIZED_BIT));
-  DCHECK_EQ(GL_NO_ERROR, glGetError());
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-
-  // Finally, determine the offset within |mapped_data_| necessary to achieve
-  // the desired alignment.
-  intptr_t alignment_remainder =
-      reinterpret_cast<size_t>(mapped_data_) % alignment_;
-  alignment_offset_ =
-      alignment_remainder == 0 ? 0 : alignment_ - alignment_remainder;
-}
-
-RawTextureMemoryPBO::~RawTextureMemoryPBO() {
-  resource_context_->RunSynchronouslyWithinResourceContext(
-      base::Bind(&RawTextureMemoryPBO::DestroyPBO, base::Unretained(this)));
-}
-
-void RawTextureMemoryPBO::DestroyPBO() {
-  resource_context_->AssertWithinResourceContext();
-
-  if (mapped_data_) {
-    // mapped_data_ will be non-null if we never call MakeConst() on it, in
-    // which case we should unmap it before continuing.
-    GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-    GL_CALL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER));
-    GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-
-    mapped_data_ = NULL;
-  }
-
-  // Clear our reference to the specified pixel buffer.
-  GL_CALL(glDeleteBuffers(1, &pixel_buffer_));
-}
-
-void RawTextureMemoryPBO::MakeConst() {
-  DCHECK(mapped_data_) << "MakeConst() should only ever be called once.";
-
-  resource_context_->RunSynchronouslyWithinResourceContext(
-      base::Bind(&RawTextureMemoryPBO::UnmapPBO, base::Unretained(this)));
-}
-
-void RawTextureMemoryPBO::UnmapPBO() {
-  resource_context_->AssertWithinResourceContext();
-
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-  GL_CALL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER));
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-
-  mapped_data_ = NULL;
-}
-
-GLuint RawTextureMemoryPBO::CreateTexture(GraphicsContextEGL* graphics_context,
-                                          intptr_t offset,
-                                          const math::Size& size, GLenum format,
-                                          int pitch_in_bytes,
-                                          bool bgra_supported) const {
-  DCHECK(!mapped_data_)
-      << "MakeConst() should be called before calling CreateTexture().";
-
-  GLuint texture_handle;
-
-  // Since we wish to create a texture within the specified graphics context,
-  // we do the texture creation work using that context.
-  GraphicsContextEGL::ScopedMakeCurrent scoped_make_current(graphics_context);
-
-  // Our texture data remains mapped until this method is called, so we begin
-  // by unmapping it.
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixel_buffer_));
-
-  // Setup our texture.
-  GL_CALL(glGenTextures(1, &texture_handle));
-  GL_CALL(glBindTexture(GL_TEXTURE_2D, texture_handle));
-  SetupInitialTextureParameters();
-
-  // Determine the texture's GL format.
-  if (format == GL_BGRA_EXT) {
-    DCHECK(bgra_supported);
-  }
-
-  // Create the texture.  Since a GL_PIXEL_UNPACK_BUFFER is currently bound,
-  // the "data" field passed to glTexImage2D will refer to an offset into that
-  // buffer.
-  GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH,
-                        pitch_in_bytes / BytesPerPixelForGLFormat(format)));
-  GL_CALL(
-      glTexImage2D(GL_TEXTURE_2D, 0, format, size.width(), size.height(), 0,
-                   format, GL_UNSIGNED_BYTE,
-                   reinterpret_cast<const void*>(alignment_offset_ + offset)));
-  GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
-  GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
-  GL_CALL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
-
-  return texture_handle;
-}
-
-}  // namespace backend
-}  // namespace renderer
-}  // namespace cobalt
-
-#endif  // defined(GLES3_SUPPORTED)
diff --git a/cobalt/renderer/backend/egl/texture_data_pbo.h b/cobalt/renderer/backend/egl/texture_data_pbo.h
deleted file mode 100644
index fc86f88..0000000
--- a/cobalt/renderer/backend/egl/texture_data_pbo.h
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright 2015 The Cobalt Authors. All Rights Reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef COBALT_RENDERER_BACKEND_EGL_TEXTURE_DATA_PBO_H_
-#define COBALT_RENDERER_BACKEND_EGL_TEXTURE_DATA_PBO_H_
-
-#if defined(GLES3_SUPPORTED)
-#error "Support for gles3 features has been deprecated."
-
-#include <GLES3/gl3.h>
-
-#include <memory>
-#include "base/basictypes.h"
-#include "cobalt/math/size.h"
-#include "cobalt/renderer/backend/egl/resource_context.h"
-#include "cobalt/renderer/backend/egl/texture_data.h"
-#include "cobalt/renderer/backend/egl/utils.h"
-
-namespace cobalt {
-namespace renderer {
-namespace backend {
-
-// TextureDataPBOs make use of GLES 3.0 GL_PIXEL_UNPACK_BUFFERs to allocate
-// pixel memory through the GLES API, giving the driver the opportunity to
-// return to us GPU memory (though it must be also accessible via the CPU).
-// This allows us to reduce texture uploading when issuing glTexImage2d calls.
-class TextureDataPBO : public TextureDataEGL {
- public:
-  TextureDataPBO(ResourceContext* resource_context, const math::Size& size,
-                 GLenum format);
-  virtual ~TextureDataPBO();
-
-  const math::Size& GetSize() const override { return size_; }
-  GLenum GetFormat() const override { return format_; }
-
-  int GetPitchInBytes() const override {
-    return size_.width() * BytesPerPixelForGLFormat(format_);
-  }
-
-  uint8_t* GetMemory() override { return mapped_data_; }
-
-  GLuint ConvertToTexture(GraphicsContextEGL* graphics_context,
-                          bool bgra_supported);
-
-  bool CreationError() override;
-
- private:
-  // Private methods that are intended to run only on the resource context
-  // thread.
-  void InitAndMapPBO();
-  void UnmapAndDeletePBO();
-
-  ResourceContext* resource_context_;
-  math::Size size_;
-  GLenum format_;
-  GLuint pixel_buffer_;
-  int64 data_size_;
-  GLubyte* mapped_data_;
-  bool error_;
-};
-
-// Similar to TextureDataPBO, but this allows a bit more flexibility and less
-// structure in the memory that is allocated, though it still is allocated as
-// pixel buffer data (using GL_PIXEL_UNPACK_BUFFER).
-class RawTextureMemoryPBO : public RawTextureMemoryEGL {
- public:
-  RawTextureMemoryPBO(ResourceContext* resource_context, size_t size_in_bytes,
-                      size_t alignment);
-  virtual ~RawTextureMemoryPBO();
-
-  // Returns the allocated size of the texture memory.
-  size_t GetSizeInBytes() const override { return size_in_bytes_; }
-
-  // Returns a CPU-accessible pointer to the allocated memory.
-  uint8_t* GetMemory() override { return mapped_data_ + alignment_offset_; }
-
-  GLuint CreateTexture(GraphicsContextEGL* graphics_context, intptr_t offset,
-                       const math::Size& size, GLenum format,
-                       int pitch_in_bytes, bool bgra_supported) const override;
-
- protected:
-  void MakeConst() override;
-
- private:
-  // Private methods that are intended to run only on the resource context
-  // thread.
-  void InitAndMapPBO();
-  void DestroyPBO();
-  void UnmapPBO();
-
-  size_t size_in_bytes_;
-  size_t alignment_;
-  ResourceContext* resource_context_;
-  GLuint pixel_buffer_;
-  GLubyte* mapped_data_;
-
-  // The offset from the beginning of the mapped memory necessary to achieve
-  // the desired alignment.
-  intptr_t alignment_offset_;
-};
-
-}  // namespace backend
-}  // namespace renderer
-}  // namespace cobalt
-
-#endif  // defined(GLES3_SUPPORTED)
-
-#endif  // COBALT_RENDERER_BACKEND_EGL_TEXTURE_DATA_PBO_H_
diff --git a/cobalt/renderer/rasterizer/skia/hardware_mesh.cc b/cobalt/renderer/rasterizer/skia/hardware_mesh.cc
index 215cbce..29d4bd8 100644
--- a/cobalt/renderer/rasterizer/skia/hardware_mesh.cc
+++ b/cobalt/renderer/rasterizer/skia/hardware_mesh.cc
@@ -20,6 +20,7 @@
 #include <utility>
 #include <vector>
 
+#include "base/message_loop/message_loop.h"
 #include "base/threading/thread_task_runner_handle.h"
 #include "starboard/configuration.h"
 
diff --git a/cobalt/renderer/rasterizer/skia/hardware_mesh.h b/cobalt/renderer/rasterizer/skia/hardware_mesh.h
index 5aa0765..2ca9605 100644
--- a/cobalt/renderer/rasterizer/skia/hardware_mesh.h
+++ b/cobalt/renderer/rasterizer/skia/hardware_mesh.h
@@ -18,8 +18,10 @@
 #define COBALT_RENDERER_RASTERIZER_SKIA_HARDWARE_MESH_H_
 
 #include <memory>
+#include <utility>
 #include <vector>
 
+#include "base/single_thread_task_runner.h"
 #include "cobalt/render_tree/resource_provider.h"
 #include "cobalt/renderer/backend/egl/graphics_context.h"
 #include "cobalt/renderer/rasterizer/skia/vertex_buffer_object.h"
@@ -58,9 +60,9 @@
   const render_tree::Mesh::DrawMode GetDrawMode() const {
     return draw_mode_ == GL_TRIANGLE_FAN
                ? render_tree::Mesh::DrawMode::kDrawModeTriangleFan
-               : draw_mode_ == GL_TRIANGLE_STRIP
-                     ? render_tree::Mesh::DrawMode::kDrawModeTriangleStrip
-                     : render_tree::Mesh::DrawMode::kDrawModeTriangles;
+           : draw_mode_ == GL_TRIANGLE_STRIP
+               ? render_tree::Mesh::DrawMode::kDrawModeTriangleStrip
+               : render_tree::Mesh::DrawMode::kDrawModeTriangles;
   }
 
   // Obtains a vertex buffer object from this mesh. Called right before first
diff --git a/cobalt/script/v8c/v8c_global_environment.cc b/cobalt/script/v8c/v8c_global_environment.cc
index 2a56a4d..c3df50c 100644
--- a/cobalt/script/v8c/v8c_global_environment.cc
+++ b/cobalt/script/v8c/v8c_global_environment.cc
@@ -40,8 +40,30 @@
 
 namespace {
 
-std::string ExceptionToString(v8::Isolate* isolate,
-                              const v8::TryCatch& try_catch) {
+std::string ToStringOrNull(v8::Isolate* isolate, v8::Local<v8::Value> value) {
+  if (value.IsEmpty() || !value->IsString()) {
+    return "";
+  }
+  return *v8::String::Utf8Value(isolate, value.As<v8::String>());
+}
+
+uint32_t CreateJavaScriptCacheKey(const std::string& javascript_engine_version,
+                                  uint32_t cached_data_version_tag,
+                                  const std::string& source,
+                                  const std::string& origin) {
+  uint32_t res = starboard::MurmurHash2_32(javascript_engine_version.c_str(),
+                                           javascript_engine_version.size(),
+                                           cached_data_version_tag);
+  res = starboard::MurmurHash2_32(source.c_str(), source.size(), res);
+  res = starboard::MurmurHash2_32(origin.c_str(), origin.size(), res);
+  return res;
+}
+
+}  // namespace
+
+// static
+std::string V8cGlobalEnvironment::ExceptionToString(
+    v8::Isolate* isolate, const v8::TryCatch& try_catch) {
   v8::HandleScope handle_scope(isolate);
   v8::String::Utf8Value exception(isolate, try_catch.Exception());
   v8::Local<v8::Message> message(try_catch.Message());
@@ -65,27 +87,6 @@
   return string;
 }
 
-std::string ToStringOrNull(v8::Isolate* isolate, v8::Local<v8::Value> value) {
-  if (value.IsEmpty() || !value->IsString()) {
-    return "";
-  }
-  return *v8::String::Utf8Value(isolate, value.As<v8::String>());
-}
-
-uint32_t CreateJavaScriptCacheKey(const std::string& javascript_engine_version,
-                                  uint32_t cached_data_version_tag,
-                                  const std::string& source,
-                                  const std::string& origin) {
-  uint32_t res = starboard::MurmurHash2_32(javascript_engine_version.c_str(),
-                                           javascript_engine_version.size(),
-                                           cached_data_version_tag);
-  res = starboard::MurmurHash2_32(source.c_str(), source.size(), res);
-  res = starboard::MurmurHash2_32(origin.c_str(), origin.size(), res);
-  return res;
-}
-
-}  // namespace
-
 V8cGlobalEnvironment::V8cGlobalEnvironment(v8::Isolate* isolate)
     : isolate_(isolate),
       destruction_helper_(isolate),
diff --git a/cobalt/script/v8c/v8c_global_environment.h b/cobalt/script/v8c/v8c_global_environment.h
index ba9e063..265c2e1 100644
--- a/cobalt/script/v8c/v8c_global_environment.h
+++ b/cobalt/script/v8c/v8c_global_environment.h
@@ -53,6 +53,9 @@
         isolate->GetData(kIsolateDataIndex));
   }
 
+  static std::string ExceptionToString(v8::Isolate* isolate,
+                                       const v8::TryCatch& try_catch);
+
   explicit V8cGlobalEnvironment(v8::Isolate* isolate);
   ~V8cGlobalEnvironment() override;
 
diff --git a/cobalt/script/v8c/v8c_value_handle.cc b/cobalt/script/v8c/v8c_value_handle.cc
index d95d653..93bd376 100644
--- a/cobalt/script/v8c/v8c_value_handle.cc
+++ b/cobalt/script/v8c/v8c_value_handle.cc
@@ -12,14 +12,14 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+#include "cobalt/script/v8c/v8c_value_handle.h"
+
 #include <memory>
 #include <string>
 #include <unordered_map>
 #include <utility>
 #include <vector>
 
-#include "cobalt/script/v8c/v8c_value_handle.h"
-
 #include "base/memory/ref_counted.h"
 #include "cobalt/script/v8c/conversion_helpers.h"
 #include "cobalt/script/v8c/entry_scope.h"
@@ -122,39 +122,84 @@
   return v8_value_handle_holder->v8_value();
 }
 
-ValueHandleHolder* DeserializeScriptValue(v8::Isolate* isolate,
-                                          const DataBuffer& data_buffer) {
+StructuredClone::StructuredClone(const ValueHandleHolder& value) {
+  deserialize_failed_ = false;
+  isolate_ = GetIsolate(value);
+  v8c::EntryScope entry_scope(isolate_);
+  v8::Local<v8::Value> v8_value = GetV8Value(value);
+  v8::ValueSerializer serializer(isolate_, this);
+  bool wrote_value;
+  if (!serializer.WriteValue(isolate_->GetCurrentContext(), v8_value)
+           .To(&wrote_value) ||
+      !wrote_value) {
+    serialize_failed_ = true;
+    return;
+  }
+  std::pair<uint8_t*, size_t> pair = serializer.Release();
+  data_buffer_ =
+      std::make_unique<DataBuffer>(std::move(pair.first), pair.second);
+  serialize_failed_ = false;
+}
+
+Handle<ValueHandle> StructuredClone::Deserialize(v8::Isolate* isolate) {
+  if (!deserialized_.IsEmpty()) {
+    return deserialized_;
+  }
+  if (failed()) {
+    return Handle<ValueHandle>();
+  }
+  DCHECK(isolate);
+  DCHECK(data_buffer_);
+  if (!data_buffer_ || !isolate) {
+    return Handle<ValueHandle>();
+  }
   v8::EscapableHandleScope scope(isolate);
   v8::TryCatch try_catch(isolate);
   v8::Local<v8::Context> context = isolate->GetCurrentContext();
-
-  v8::ValueDeserializer deserializer(isolate, data_buffer.ptr.get(),
-                                     data_buffer.size);
+  v8::ValueDeserializer deserializer(isolate, data_buffer_->ptr.get(),
+                                     data_buffer_->size, this);
   v8::Local<v8::Value> value;
   if (!deserializer.ReadValue(context).ToLocal(&value)) {
-    return nullptr;
+    LOG(WARNING) << v8c::V8cGlobalEnvironment::ExceptionToString(isolate,
+                                                                 try_catch);
+    deserialize_failed_ = true;
+    return Handle<ValueHandle>();
   }
-  script::v8c::V8cExceptionState exception_state(isolate);
-  auto* holder = new script::v8c::V8cValueHandleHolder();
-  FromJSValue(isolate, scope.Escape(value), script::v8c::kNoConversionFlags,
-              &exception_state, holder);
-  return holder;
+  data_buffer_.reset();
+  backing_stores_.clear();
+  v8c::V8cExceptionState exception_state(isolate);
+  auto* deserialized = new v8c::V8cValueHandleHolder();
+  FromJSValue(isolate, scope.Escape(value), v8c::kNoConversionFlags,
+              &exception_state, deserialized);
+  if (exception_state.is_exception_set()) {
+    deserialize_failed_ = true;
+    return Handle<ValueHandle>();
+  }
+  deserialized_ = Handle<ValueHandle>(deserialized);
+  return deserialized_;
 }
 
-std::unique_ptr<DataBuffer> SerializeScriptValue(
-    const ValueHandleHolder& value) {
-  v8::Isolate* isolate = GetIsolate(value);
-  script::v8c::EntryScope entry_scope(isolate);
-  v8::Local<v8::Value> v8_value = GetV8Value(value);
-  v8::ValueSerializer serializer(isolate);
-  bool wrote_value;
-  if (!serializer.WriteValue(isolate->GetCurrentContext(), v8_value)
-           .To(&wrote_value) ||
-      !wrote_value) {
-    return nullptr;
+v8::Maybe<uint32_t> StructuredClone::GetSharedArrayBufferId(
+    v8::Isolate* isolate,
+    v8::Local<v8::SharedArrayBuffer> shared_array_buffer) {
+  auto backing_store = shared_array_buffer->GetBackingStore();
+  for (size_t index = 0; index < backing_stores_.size(); ++index) {
+    if (backing_stores_[index] == backing_store) {
+      return v8::Just<uint32_t>(static_cast<uint32_t>(index));
+    }
   }
-  std::pair<uint8_t*, size_t> pair = serializer.Release();
-  return std::make_unique<DataBuffer>(std::move(pair.first), pair.second);
+  backing_stores_.push_back(backing_store);
+  return v8::Just<uint32_t>(backing_stores_.size() - 1);
+}
+
+v8::MaybeLocal<v8::SharedArrayBuffer>
+StructuredClone::GetSharedArrayBufferFromId(v8::Isolate* isolate,
+                                            uint32_t clone_id) {
+  if (clone_id < backing_stores_.size()) {
+    return v8::SharedArrayBuffer::New(isolate,
+                                      std::move(backing_stores_.at(clone_id)));
+  }
+  return v8::MaybeLocal<v8::SharedArrayBuffer>();
 }
 
 }  // namespace script
diff --git a/cobalt/script/value_handle.h b/cobalt/script/value_handle.h
index f0c8cce..1b0fafa 100644
--- a/cobalt/script/value_handle.h
+++ b/cobalt/script/value_handle.h
@@ -18,6 +18,7 @@
 #include <memory>
 #include <string>
 #include <unordered_map>
+#include <vector>
 
 #include "base/memory/ref_counted.h"
 #include "cobalt/script/exception_state.h"
@@ -38,16 +39,48 @@
 
 typedef ScriptValue<ValueHandle> ValueHandleHolder;
 
-struct BufferDeleter {
-  void operator()(uint8_t* buffer) { SbMemoryDeallocate(buffer); }
-};
-using DataBufferPtr = std::unique_ptr<uint8_t[], BufferDeleter>;
 
-struct DataBuffer {
-  DataBufferPtr ptr;
-  size_t size;
+class StructuredClone : public v8::ValueSerializer::Delegate,
+                        public v8::ValueDeserializer::Delegate {
+ public:
+  explicit StructuredClone(const ValueHandleHolder& value);
 
-  DataBuffer(uint8_t* ptr, size_t size) : ptr(DataBufferPtr(ptr)), size(size) {}
+  // v8::ValueSerializer::Delegate
+  void ThrowDataCloneError(v8::Local<v8::String> message) override {
+    isolate_->ThrowException(v8::Exception::Error(message));
+  }
+  v8::Maybe<uint32_t> GetSharedArrayBufferId(
+      v8::Isolate* isolate,
+      v8::Local<v8::SharedArrayBuffer> shared_array_buffer) override;
+
+  // v8::ValueDeserializer::Delegate
+  v8::MaybeLocal<v8::SharedArrayBuffer> GetSharedArrayBufferFromId(
+      v8::Isolate* isolate, uint32_t clone_id) override;
+
+  Handle<ValueHandle> Deserialize(v8::Isolate* isolate);
+
+  bool failed() const { return serialize_failed_ || deserialize_failed_; }
+
+ private:
+  struct BufferDeleter {
+    void operator()(uint8_t* buffer) { SbMemoryDeallocate(buffer); }
+  };
+  using DataBufferPtr = std::unique_ptr<uint8_t[], BufferDeleter>;
+
+  struct DataBuffer {
+    DataBufferPtr ptr;
+    size_t size;
+
+    DataBuffer(uint8_t* ptr, size_t size)
+        : ptr(DataBufferPtr(ptr)), size(size) {}
+  };
+
+  v8::Isolate* isolate_;
+  Handle<ValueHandle> deserialized_;
+  std::unique_ptr<DataBuffer> data_buffer_;
+  bool serialize_failed_ = false;
+  bool deserialize_failed_ = false;
+  std::vector<std::shared_ptr<v8::BackingStore>> backing_stores_;
 };
 
 // Converts a "simple" object to a map of the object's properties. "Simple"
@@ -64,10 +97,6 @@
 
 v8::Isolate* GetIsolate(const ValueHandleHolder& value);
 v8::Local<v8::Value> GetV8Value(const ValueHandleHolder& value);
-ValueHandleHolder* DeserializeScriptValue(v8::Isolate* isolate,
-                                          const DataBuffer& data_buffer);
-std::unique_ptr<DataBuffer> SerializeScriptValue(
-    const ValueHandleHolder& value);
 
 }  // namespace script
 }  // namespace cobalt
diff --git a/cobalt/site/docs/gen/cobalt/doc/cvals.md b/cobalt/site/docs/gen/cobalt/doc/cvals.md
new file mode 100644
index 0000000..752fc7f
--- /dev/null
+++ b/cobalt/site/docs/gen/cobalt/doc/cvals.md
@@ -0,0 +1,437 @@
+---
+layout: doc
+title: "Cobalt CVals"
+---
+# Cobalt CVals
+
+## Overview
+
+CVals are globally accessible, thread-safe, key-value pairs within Cobalt, which
+are primarily used for monitoring state and tracking performance and memory.
+Each CVal is defined with a unique key and registered with the global
+CValManager. The CValManager can subsequently be queried for the current value
+of the key, which is returned as a string. CVals come in two varieties:
+
+*   **PublicCVals** - active in all builds.
+*   **DebugCVals** - only enabled in non-Gold builds.
+
+## Usage
+
+### Debug Console
+
+The debug console can be toggled between three modes (off, on, and hud) by
+pressing Ctrl-O. It displays the current values of registered CVals, updating
+them at 60 Hz. The initially displayed values are determined by
+`DEFAULT_ACTIVE_SET` in `debug_values/console_values.js`. However, this is
+modifiable in the debug console hud.
+
+The registered CVals can be viewed by entering `debug.cvalList()` into the debug
+console. Additional CVals can be registered via
+`debug.cvalAdd(substringToMatch)` and can be removed via
+`debug.cvalRemove(substringToMatch)`. The current registered list can be saved
+as a new set via `debug.cvalSave(set_key)`. At that point, the saved set can
+later be loaded as the active set via the command, `debug.cvalLoad(set_key)`.
+
+A full list of the commands available via the debug console is shown by entering
+`debug.help()`.
+
+### JavaScript
+
+CVals are exposed to JavaScript via the H5vccCVal object. This provides an
+interface for requesting all of the keys, which are returned as an array, and
+for retrieving a specific CVal value, which is returned as an optional string,
+via its CVal key. While the H5vccCVal object is usable in any build, only public
+CVals are queryable in Gold builds.
+
+Here are examples of its usage:
+
+```
+  > h5vcc.cVal.keys()
+  < H5vccCValKeyList[151]
+
+  > h5vcc.cVal.keys().length
+  < 151
+
+  > h5vcc.cVal.keys().item(8)
+  < "Count.MainWebModule.Layout.Box"
+
+  > h5vcc.cVal.getValue("Count.MainWebModule.Layout.Box")
+  < "463"
+```
+
+## Tracking Categories
+
+### Cobalt
+
+#### PublicCVals
+
+*   **Cobalt.Lifetime** - The total number of milliseconds that Cobalt has been
+    running.
+
+#### DebugCVals
+
+*   **Cobalt.Server.DevTools** - The IP address and port of the DevTools server,
+    if it is running.
+*   **Cobalt.Server.WebDriver** - The IP address and port of the Webdriver
+    server, if it is running.
+
+### Count
+
+#### PublicCVals
+
+*   **Count.DOM.EventListeners** - The total number of EventListeners in
+    existence globally. This includes ones that are pending garbage collection.
+*   **Count.DOM.Nodes** - The total number of Nodes in existence globally. This
+    includes ones that are pending garbage collection.
+*   **Count.MainWebModule.DOM.HtmlElement** - The total number of HtmlElements
+    in the MainWebModule. This includes elements that are not in the document
+    and ones that are pending garbage collection.
+*   **Count.MainWebModule.DOM.HtmlElement.Document** - The total number of
+    HtmlElements that are in the MainWebModule’s document.
+*   **Count.MainWebModule.DOM.HtmlScriptElement.Execute** - The total number of
+    HtmlScriptElement executions that have run since Cobalt started.
+*   **Count.MainWebModule.Layout.Box** - The total number of Boxes that are in
+    the MainWebModule’s current layout.
+
+#### DebugCVals
+
+*   **Count.DOM.ActiveJavaScriptEvents** - The number of JavaScript events that
+    are currently running.
+*   **Count.DOM.Attrs** - The total number of Attrs in existence globally. This
+    includes ones that are pending garbage collection.
+*   **Count.DOM.StringMaps** - The total number of StringMaps in existence
+    globally. This includes ones that are pending garbage collection.
+*   **Count.DOM.TokenLists** - The total number of TokenLists in existence
+    globally. This includes ones that are pending garbage collection.
+*   **Count.DOM.HtmlCollections** - The total number of HtmlCollections in
+    existence globally. This includes ones that are pending garbage collection.
+*   **Count.DOM.NodeLists** - The total number of NodeLists in existence
+    globally. This includes ones that are pending garbage collection.
+*   **Count.DOM.NodeMaps** - The total number of NodeMaps in existence globally.
+    This includes ones that are pending garbage collection.
+*   **Count.MainWebModule.[RESOURCE_CACHE_TYPE].PendingCallbacks** - The number
+    of loading completed resources that have pending callbacks.
+*   **Count.MainWebModule.[RESOURCE_CACHE_TYPE].Resource.Requested** - The total
+    number of resources that have ever been requested.
+*   **Count.MainWebModule.[RESOURCE_CACHE_TYPE].Resource.Loaded** - The total
+    number of resources that have ever been successfully loaded.
+*   **Count.MainWebModule.[RESOURCE_CACHE_TYPE].Resource.Loading** - The number
+    of resources that are currently loading.
+*   **Count.Renderer.Rasterize.NewRenderTree** - The total number of new render
+    trees that have been rasterized.
+*   **Count.VersionCompatibilityViolation** - The total number of Cobalt version
+    compatibility violations encountered.
+*   **Count.XHR** - The total number of xhr::XMLHttpRequest in existence
+    globally.
+
+### Event
+
+The Event category currently consists of counts and durations (in microseconds)
+for input events, which are tracked from when the event is first injected into
+the window, until a render tree is generated from it. Each event type is tracked
+separately; current event types are: *KeyDown*, *KeyUp*, *PointerDown*,
+*PointerUp*.
+
+#### PublicCVals
+
+*   **Event.MainWebModule.[EVENT_TYPE].ProducedRenderTree** - Whether or not the
+    event produced a render tree.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement** - The total
+    number of HTML elements after the event produces its first render tree.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.Created** - The
+    number of HTML elements created during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.Destroyed** - The
+    number of HTML elements destroyed during the event. NOTE: This number will
+    only be non-zero if GC occurs during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.Document** - The
+    number of HTML elements in the document after the event produces its first
+    render tree.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.Document.Added** -
+    The number of HTML elements added to the document during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.Document.Removed** -
+    The number of HTML elements removed from the document during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.UpdateMatchingRules** -
+    The number of HTML elements that had their matching rules updated during the
+    event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.UpdateComputedStyle** -
+    The number of HTML elements that had their computed style updated during the
+    event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.GenerateHtmlElementComputedStyle** -
+    The number of HTML elements that had their computed style fully generated
+    during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].DOM.HtmlElement.GeneratePseudoElementComputedStyle** -
+    The number of pseudo elements that had their computed style fully generated
+    during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].Layout.Box** - The total number of
+    Layout boxes after the event produces its first render tree.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].Layout.Box.Created** - The number
+    of Layout boxes that were created during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].Layout.Box.Destroyed** - The number
+    of Layout boxes that were destroyed during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].Layout.Box.UpdateSize** - The
+    number of times UpdateSize() is called during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].Layout.Box.RenderAndAnimate** - The
+    number of times RenderAndAnimate() is called during the event.
+*   **Event.Count.MainWebModule.[EVENT_TYPE].Layout.Box.UpdateCrossReferences** -
+    The number of times UpdateCrossReferences() is called during the event.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE]** - The total duration of the
+    event from the keypress being injected until the first render tree is
+    rendered. If the event does not trigger a re-layout, then it only includes
+    the event injection time.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].DOM.InjectEvent** - The time
+    taken to inject the event into the window object. This mainly consists of
+    JavaScript time.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].DOM.RunAnimationFrameCallbacks** -
+    The time taken to run animation frame callbacks during the event. This
+    mainly consists of JavaScript time.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].DOM.UpdateComputedStyle** - The
+    time taken to update the computed styles of all HTML elements (which also
+    includes updating their matching rules). This will track closely with the
+    event DOM counts.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].Layout.BoxTree** - The time
+    taken to fully lay out the box tree.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].Layout.BoxTree.BoxGeneration** -
+    The time taken to generate the boxes within the box tree. This will track
+    closely with the number of boxes created during the event. This is included
+    within the BoxTree time.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].Layout.BoxTree.UpdateUsedSizes** -
+    The time taken to update the sizes of the boxes within the box tree, which
+    is when all of the boxes are laid out. This is included within the BoxTree
+    time.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].Layout.RenderAndAnimate** - The
+    time taken to generate the render tree produced by the event.
+*   **Event.Duration.MainWebModule.[EVENT_TYPE].Renderer.Rasterize** - The time
+    taken to rasterize the event’s render tree after it is submitted to the
+    renderer.
+*   **Event.Duration.MainWebModule.DOM.VideoStartDelay** - The delay from the
+    start of the event until the start of a video. NOTE1: This is not set until
+    after the event completes, so it is not included in the value dictionary.
+    NOTE2: This is not tracked by event type, so each new event will reset this
+    value.
+*   **Event.Time.MainWebModule.[EVENT_TYPE].Start** - Time when the event
+    started.
+
+#### DebugCVals
+
+*   **Event.MainWebModule.IsProcessing** - Whether or not an event is currently
+    being processed.
+*   **Event.MainWebModule.[EVENT_TYPE].ValueDictionary** - All counts and
+    durations for this event as a JSON string. This is used by the
+    tv_testcase_event_recorder to minimize the number of CVal requests it makes
+    to retrieve all of the data for an event.
+
+### MainWebModule
+
+#### DebugCVals
+
+*   **MainWebModule.IsRenderTreeRasterizationPending** - Whether or not a render
+    tree has been produced but not yet rasterized.
+*   **MainWebModule.Layout.IsRenderTreePending** - Whether or not the layout is
+    scheduled to produce a new render tree.
+
+### Media
+
+#### PublicCVals
+
+We have various SbPlayer metrics available which need to be enabled first using:
+`h5vcc.settings.set("Media.EnableMetrics", 1)`
+
+*   **Media.SbPlayerCreateTime.Minimum**
+*   **Media.SbPlayerCreateTime.Median**
+*   **Media.SbPlayerCreateTime.Maximum**
+*   **Media.SbPlayerDestructionTime.Minimum**
+*   **Media.SbPlayerDestructionTime.Median**
+*   **Media.SbPlayerDestructionTime.Maximum**
+*   **Media.SbPlayerWriteSamplesTime.Minimum**
+*   **Media.SbPlayerWriteSamplesTime.Median**
+*   **Media.SbPlayerWriteSamplesTime.Maximum**
+
+#### DebugCVals
+
+Media Pipeline exposes many State values, however we support multiple pipelines
+at once, so we have to query for the current pipeline number to access them.
+This can be done with `h5vcc.cVal.keys().filter(key =>
+key.startsWith("Media.Pipeline.") && key.endsWith("MaxVideoCapabilities") &&
+h5vcc.cVal.getValue(key).length === 0)` (If a Pipeline has MaxVideoCapabilities,
+it implies that the Pipeline is a 10x player, i.e. a secondary small player, so
+if MaxVideoCapabilities.length is 0, then it must be the primary pipeline.)
+This will give back an answer like `Media.Pipeline.3.MaxVideoCapabilities` so
+the main pipeline in this example is `3`. With the current pipeline number you
+can then access (Switching out pipeline for the one returned from previous
+query):
+
+*   **Media.Pipeline.3.Started**
+*   **Media.Pipeline.3.Suspended**
+*   **Media.Pipeline.3.Stopped**
+*   **Media.Pipeline.3.Ended**
+*   **Media.Pipeline.3.PlayerState**
+*   **Media.Pipeline.3.Volume**
+*   **Media.Pipeline.3.PlaybackRate**
+*   **Media.Pipeline.3.Duration**
+*   **Media.Pipeline.3.LastMediaTime**
+*   **Media.Pipeline.3.MaxVideoCapabilities**
+*   **Media.Pipeline.3.SeekTime**
+*   **Media.Pipeline.3.FirstWrittenAudioTimestamp**
+*   **Media.Pipeline.3.FirstWrittenVideoTimestamp**
+*   **Media.Pipeline.3.LastWrittenAudioTimestamp**
+*   **Media.Pipeline.3.LastWrittenVideoTimestamp**
+*   **Media.Pipeline.3.VideoWidth**
+*   **Media.Pipeline.3.VideoHeight**
+*   **Media.Pipeline.3.IsAudioEosWritten**
+*   **Media.Pipeline.3.IsVideoEosWritten**
+*   **Media.Pipeline.3.PipelineStatus**
+*   **Media.Pipeline.3.CurrentCodec**
+*   **Media.Pipeline.3.ErrorMessage**
+
+### Memory
+
+#### PublicCVals
+
+*   **Memory.CPU.Free** - The total CPU memory (in bytes) potentially available
+    to this application minus the amount being used by the application.
+*   **Memory.CPU.Used** - The total physical CPU memory (in bytes) used by this
+    application.
+*   **Memory.GPU.Free** - The total GPU memory (in bytes) potentially available
+    to this application minus the amount being used by the application. NOTE: On
+    many platforms, GPU memory information is unavailable.
+*   **Memory.GPU.Used** - The total physical CPU memory (in bytes) used by this
+    application. NOTE: On many platforms, GPU memory information is unavailable.
+*   **Memory.JS** - The total memory being used by JavaScript.
+*   **Memory.Font.LocalTypefaceCache.Capacity** - The capacity in bytes of the
+    font cache for use with local typefaces. This is a hard cap that can never
+    be exceeded.
+*   **Memory.Font.LocalTypefaceCache.Size** - The current size in bytes of the
+    font cache for use with local typefaces.
+*   **Memory.MainWebModule.DOM.HtmlScriptElement.Execute** - The total size in
+    bytes of all scripts executed by HtmlScriptElements since Cobalt started.
+*   **Memory.MainWebModule.[RESOURCE_CACHE_TYPE].Capacity** - The capacity in
+    bytes of the resource cache specified by RESOURCE_CACHE_TYPE. When the
+    resource cache exceeds the capacity, unused resources being purged from it.
+*   **Memory.MainWebModule.[RESOURCE_CACHE_TYPE].Resource.Loaded** - The total
+    size in bytes of all resources ever loaded by the resource cache specified
+    by RESOURCE_CACHE_TYPE.
+*   **Memory.MainWebModule.[RESOURCE_CACHE_TYPE].Size** - The total number of
+    bytes currently used by the resource cache specified by RESOURCE_CACHE_TYPE.
+
+#### DebugCVals
+
+*   **Memory.XHR** - The total memory allocated to xhr::XMLHttpRequest objects.
+*   **Memory.CachedSoftwareRasterizer.CacheUsage** - Total memory occupied by
+    cached software-rasterized surfaces.
+*   **Memory.CachedSoftwareRasterizer.FrameCacheUsage** - Total memory occupied
+    by cache software-rasterizer surfaces that were referenced this frame.
+
+### Renderer
+
+#### PublicCVals
+
+*   **Renderer.HasActiveAnimations** - Whether or not the current render tree
+    has animations.
+*   **Renderer.Rasterize.DurationInterval.\*** - Tracks the duration of
+    intervals between rasterization calls during all animations and updates its
+    stats with a new set of entries every 60 calls. Given that it only updates
+    every 60 samples, it typically includes multiple animations. This provides
+    an accurate view of the framerate over those samples and is the value used
+    with the FPS overlay.
+    *   **Renderer.Rasterize.DurationInterval.Cnt** - The number of intervals
+        included in the stats. Should always be 60.
+    *   **Renderer.Rasterize.DurationInterval.Avg** - The average duration of
+        the intervals between the animation rasterizations included in the set.
+    *   **Renderer.Rasterize.DurationInterval.Min** - The minimum duration of
+        the intervals between the animation rasterizations included in the set.
+    *   **Renderer.Rasterize.DurationInterval.Max** - The maximum duration of
+        the intervals between the animation rasterizations included in the set.
+    *   **Renderer.Rasterize.DurationInterval.Pct.25th** - The 25th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.DurationInterval.Pct.50th** - The 50th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.DurationInterval.Pct.75th** - The 75th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.DurationInterval.Pct.95th** - The 95th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.DurationInterval.Std** - The standard deviation of
+        the intervals between the animation rasterizations included in the set.
+*   **Renderer.Rasterize.AnimationsInterval.\*** - Tracks the duration of
+    intervals between rasterization calls during a single animation and updates
+    its stats when the animation ends. The stats include all of the animation’s
+    rasterization intervals. This provides an accurate view of the framerate
+    during the animation.
+    *   **Renderer.Rasterize.AnimationsInterval.Cnt** - The number of intervals
+        included in the stats. Accounts for all rasterizations that occurred
+        during the animation.
+    *   **Renderer.Rasterize.AnimationsInterval.Avg** - The average duration of
+        the intervals between the animation rasterizations included in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Min** - The minimum duration of
+        the intervals between the animation rasterizations included in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Max** - The maximum duration of
+        the intervals between the animation rasterizations included in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Pct.25th** - The 25th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Pct.50th** - The 50th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Pct.75th** - The 75th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Pct.95th** - The 95th percentile
+        duration of the intervals between the animation rasterizations included
+        in the set.
+    *   **Renderer.Rasterize.AnimationsInterval.Std** - The standard deviation
+        of the intervals between the animation rasterizations included in the
+        set.
+
+#### DebugCVals
+
+*   **Renderer.SubmissionQueueSize** - The current size of the renderer
+    submission queue. Each item in the queue contains a render tree and
+    associated animations.
+*   **Renderer.ToSubmissionTime** - The current difference in milliseconds
+    between the layout's clock and the renderer's clock.
+*   **Renderer.Rasterize.Animations.\*** - Tracks the duration of each
+    rasterization call during a single animation and updates its stats when the
+    animation ends. The stats are drawn from all of the animation’s
+    rasterizations. Given that this only tracks the time spent in the
+    rasterizer, it does not provide as accurate a picture of the framerate as
+    DurationInterval and AnimationsInterval.
+    *   **Renderer.Rasterize.Animations.Cnt** - The number of rasterization
+        durations included in the stats. Accounts for all rasterizations that
+        occurred during the animation.
+    *   **Renderer.Rasterize.Animations.Avg** - The average duration of the
+        rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Min** - The minimum duration of the
+        rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Max** - The maximum duration of the
+        rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Pct.25th** - The 25th percentile
+        duration of the rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Pct.50th** - The 50th percentile
+        duration of the rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Pct.75th** - The 75th percentile
+        duration of the rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Pct.95th** - The 95th percentile
+        duration of the rasterizations included in the set.
+    *   **Renderer.Rasterize.Animations.Std** - The standard deviation of the
+        rasterization durations included in the set.
+
+### Time
+
+#### PublicCVals
+
+*   **Time.Cobalt.Start** - Time when Cobalt was launched.
+*   **Time.Browser.Navigate** - Time when the BrowserModule’s last Navigate
+    occurred.
+*   **Time.Browser.OnLoadEvent** - Time when the BrowserModule’s last
+    OnLoadEvent occurred.
+*   **Time.MainWebModule.DOM.HtmlScriptElement.Execute** - Time when an
+    HtmlScriptElement was last executed.
+*   **Time.Renderer.Rasterize.Animations.Start** - Time when the Renderer last
+    started playing animations.
+*   **Time.Renderer.Rasterize.Animations.End** - Time when the Renderer last
+    stopped playing animations.
+*   **Time.Renderer.Rasterize.NewRenderTree** - Time when the most recent render
+    tree was first rasterized.
diff --git a/cobalt/site/docs/gen/cobalt/doc/device_authentication.md b/cobalt/site/docs/gen/cobalt/doc/device_authentication.md
index f1513a9..c7dcb7c 100644
--- a/cobalt/site/docs/gen/cobalt/doc/device_authentication.md
+++ b/cobalt/site/docs/gen/cobalt/doc/device_authentication.md
@@ -38,8 +38,17 @@
 function to sign the message using the secret key.  This method is preferred
 since it enables implementations where the key exists only in secure hardware
 and never enters the system's main memory.  A reference implementation, which
-depends on BoringSSL exists at
-[starboard/linux/x64x11/internal/system_sign_with_certification_secret_key.cc](../../starboard/linux/x64x11/internal/system_sign_with_certification_secret_key.cc).
+depends on BoringSSL, is as follows:
+
+```C++
+bool SbSystemSignWithCertificationSecretKey(
+    const uint8_t* message, size_t message_size_in_bytes,
+    uint8_t* digest, size_t digest_size_in_bytes) {
+  return starboard::shared::deviceauth::SignWithCertificationSecretKey(
+      kBase64EncodedCertificationSecret,
+      message, message_size_in_bytes, digest, digest_size_in_bytes);
+}
+```
 
 ### Cobalt signing
 
diff --git a/cobalt/site/docs/gen/cobalt/doc/docker_build.md b/cobalt/site/docs/gen/cobalt/doc/docker_build.md
index 450693f..9f49f2d 100644
--- a/cobalt/site/docs/gen/cobalt/doc/docker_build.md
+++ b/cobalt/site/docs/gen/cobalt/doc/docker_build.md
@@ -58,7 +58,19 @@
 
 ## Pre-built images
 
-Note: Pre-built images from a public container registry are not yet available.
+Pre-built images are available at https://github.com/orgs/youtube/packages?repo_name=cobalt
+
+For example, a container for building Android platform from main branch can be pulled as follows:
+
+```
+docker pull ghcr.io/youtube/cobalt/cobalt-build-android:main
+```
+
+Similarly, from LTS branch for Evergreen platform:
+
+```
+docker pull ghcr.io/youtube/cobalt/cobalt-build-evergreen:23.lts
+```
 
 ## Troubleshooting
 
@@ -67,4 +79,4 @@
 
   `docker-compose run linux-x64x11 /bin/bash`
 
-and try to build cobalt [with the usual `gyp / ninja` flow](../../README.md#building-and-running-the-code).
+and try to build cobalt [with the usual `gn / ninja` flow](../../README.md#building-and-running-the-code).
diff --git a/cobalt/site/docs/gen/cobalt/doc/voice_search.md b/cobalt/site/docs/gen/cobalt/doc/voice_search.md
index 717e3cc..503428f 100644
--- a/cobalt/site/docs/gen/cobalt/doc/voice_search.md
+++ b/cobalt/site/docs/gen/cobalt/doc/voice_search.md
@@ -4,16 +4,11 @@
 ---
 # Enabling voice search in Cobalt
 
-Cobalt enables voice search through either:
+Cobalt enables voice search through a subset of the
+[MediaRecorder Web API](https://www.w3.org/TR/mediastream-recording/#mediarecorder-api)
 
-1. A subset of the [MediaRecorder Web API](https://www.w3.org/TR/mediastream-recording/#mediarecorder-api)
-2. A subset of the [Speech Recognition Web API](https://w3c.github.io/speech-api/#speechreco-section)
-
-Only one or the other can be used, and we recommend that the MediaRecorder API
-is followed, as the Speech Recognition API is deprecated as of Starboard 13.
-
-In both approaches, in order to check whether to enable voice control or not,
-web apps will call the [MediaDevices.enumerateDevices()](https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-enumeratedevices%28%29)
+In order to check whether to enable voice control or not, web apps will call the
+[MediaDevices.enumerateDevices()](https://www.w3.org/TR/mediacapture-streams/#dom-mediadevices-enumeratedevices%28%29)
 Web API function within which Cobalt will in turn call a subset of the
 [Starboard SbMicrophone API](../../starboard/microphone.h).
 
@@ -23,48 +18,7 @@
 ## MediaRecorder API
 
 To enable the MediaRecorder API in Cobalt, the complete
-[SbMicrophone API](../../starboard/microphone.h) must be implemented, and
-`SbSpeechRecognizerIsSupported()` must return `false`.
-
-## Speech Recognition API - Deprecated
-
-**The Speech Recognition API is deprecated as of Starboard 13.**
-
-In order to provide support for using this API, platforms must implement the
-[Starboard SbSpeechRecognizer API](../../starboard/speech_recognizer.h) as well
-as a subset of the [SbMicrophone API](../../starboard/microphone.h).
-
-### Specific instructions to enable voice search
-
-1. Implement `SbSpeechRecognizerIsSupported()` to return `true`, and implement
-   the [SbSpeechRecognizer API](../../starboard/speech_recognizer.h).
-2. Implement the following subset of the
-   [SbMicrophone API](../../starboard/microphone.h):
-    - `SbMicrophoneGetAvailable()`
-    - `SbMicrophoneCreate()`
-    - `SbMicrophoneDestroy()`
-
-   In particular, SbMicrophoneCreate() must return a valid microphone.  It is
-   okay to stub out the other functions, e.g. have `SbMicrophoneOpen()`
-   return `false`.
-3. The YouTube app will display the mic icon on the search page when it detects
-   valid microphone input devices using `MediaDevices.enumerateDevices()`.
-4. With `SbSpeechRecognizerIsSupported()` implemented to return `true`, Cobalt
-   will use the platform's
-   [Starboard SbSpeechRecognizer API](../../starboard/speech_recognizer.h)
-   implementation, and it will not actually read directly from the microphone
-   via the [Starboard SbMicrophone API](../../starboard/microphone.h).
-
-### Differences from versions of Cobalt <= 11
-
-In previous versions of Cobalt, there was no way to dynamically disable
-speech support besides modifying common Cobalt code to dynamically stub out the
-Speech Recognition API when the platform does not support microphone input.
-This is no longer necessary, web apps should now rely on
-`MediaDevices.enumerateDevices()` to determine whether voice support is enabled
-or not.
-
-### Speech Recognition API is deprecated in Starboard 13 ###
+[SbMicrophone API](../../starboard/microphone.h) must be implemented.
 
 Web applications are expected to use the MediaRecorder API. This in turn relies
 on the SbMicrophone API as detailed above.
diff --git a/cobalt/site/docs/gen/starboard/build/doc/migration_changes.md b/cobalt/site/docs/gen/starboard/build/doc/migration_changes.md
index 83f3dfa..468de10 100644
--- a/cobalt/site/docs/gen/starboard/build/doc/migration_changes.md
+++ b/cobalt/site/docs/gen/starboard/build/doc/migration_changes.md
@@ -24,7 +24,6 @@
 `sb_evergreen` (0/1)                      | `sb_is_evergreen` (true/false)                       | `//starboard/build/config/base_configuration.gni`
 `sb_evergreen_compatible` (0/1)           | `sb_is_evergreen_compatible` (true/false)            | `//starboard/build/config/base_configuration.gni`
 `sb_evergreen_compatible_libunwind` (0/1) | `sb_evergreen_compatible_use_libunwind` (true/false) | `//starboard/build/config/base_configuration.gni`
-`sb_evergreen_compatible_lite` (0/1)      | `sb_evergreen_compatible_enable_lite` (true/false)   | `//starboard/build/config/base_configuration.gni`
 `sb_disable_cpp14_audit`                  | (none)                                               |
 `sb_disable_microphone_idl`               | (none)                                               |
 `starboard_path`                          | (none)                                               |
diff --git a/cobalt/site/docs/gen/starboard/doc/abstract-toolchain.md b/cobalt/site/docs/gen/starboard/doc/abstract-toolchain.md
deleted file mode 100644
index caaba83..0000000
--- a/cobalt/site/docs/gen/starboard/doc/abstract-toolchain.md
+++ /dev/null
@@ -1,57 +0,0 @@
----
-layout: doc
-title: "Abstract Toolchain"
----
-# Abstract Toolchain
-
-## Motivation
-
-The aim of implementing an Abstract Toolchain is to allow porters to add
-new toolchains or customize existing ones without the need of modifying
-common code.
-
-Initially all targets were defined in one common shared file,
-`src/tools/gyp/pylib/gyp/generator/ninja.py`.
-Modifications to this file were required for replacing any of the toolchain
-components, adding platform-specific tooling, adding new toolchains, or
-accommodating platform-specific flavor of reference tool. Doing this in a
-shared file does not scale with the number of ports.
-
-## Overview
-
-The solution implemented to solve toolchain abstraction consists of adding two
-new functions to the platform specific `gyp_configuration.py` file found under:
-
-`starboard/<PLATFORM>/gyp_configuration.py`
-
-The functions to implement are:
-
-`GetHostToolchain` and `GetTargetToolchain`
-
-## Example
-
-The simplest complete GCC based toolchain, where a target and host are the same,
-and all tools are in the PATH:
-
-  class ExamplePlatformConfig(starboard.PlatformConfig)
-    # ...
-
-    def GetTargetToolchain(self):
-      return [
-        starboard.toolchains.gnu.CCompiler(),
-        starboard.toolchains.gnu.CPlusPlusCompiler(),
-        starboard.toolchains.gnu.Assembler(),
-        starboard.toolchains.gnu.StaticLinker(),
-        starboard.toolchains.gnu.DynamicLinker(),
-        starboard.toolchains.gnu.Bison(),
-        starboard.toolchains.gnu.Stamp(),
-        starboard.toolchains.gnu.Copy(),
-      ]
-
-    def GetHostToolchain(self):
-      return self.GetTargetToolchain()
-
-You can find real examples of this in the Open Source repo:
-[Linux x8611](https://cobalt.googlesource.com/cobalt/+/refs/heads/21.lts.1+/src/starboard/linux/x64x11/gyp_configuration.py)
-
-[Raspberry Pi 2](https://cobalt.googlesource.com/cobalt/+/refs/heads/21.lts.1+/src/starboard/raspi/shared/gyp_configuration.py)
diff --git a/cobalt/site/docs/gen/starboard/doc/evergreen/cobalt_evergreen_overview.md b/cobalt/site/docs/gen/starboard/doc/evergreen/cobalt_evergreen_overview.md
index 37024ea..98de330 100644
--- a/cobalt/site/docs/gen/starboard/doc/evergreen/cobalt_evergreen_overview.md
+++ b/cobalt/site/docs/gen/starboard/doc/evergreen/cobalt_evergreen_overview.md
@@ -557,6 +557,15 @@
 [`suspend_signals.cc`](../../shared/signal/suspend_signals.cc)
 for an example.
 
+### Cleaning up after uninstall
+When the application is uninstalled the updates should be cleanup by calling the
+application with the `--reset_evergreen_update` flag. This would remove all files
+under `kSbSystemPathStorageDirectory` and exit the app.
+
+```
+  loader_app --reset_evergreen_update
+```
+
 ### Multi-App Support
 Evergreen can support multiple apps that share a Cobalt binary. This is a very
 common way to save space and keep all your Cobalt apps using the latest version
diff --git a/cobalt/site/docs/gen/starboard/doc/evergreen/evergreen_binary_compression.md b/cobalt/site/docs/gen/starboard/doc/evergreen/evergreen_binary_compression.md
new file mode 100644
index 0000000..3d37997
--- /dev/null
+++ b/cobalt/site/docs/gen/starboard/doc/evergreen/evergreen_binary_compression.md
@@ -0,0 +1,114 @@
+---
+layout: doc
+title: "Evergreen Binary Compression"
+---
+# Evergreen Binary Compression
+
+## What is Evergreen Binary Compression?
+
+Evergreen Binary Compression is a feature that reduces the amount of space used
+on-device to store Cobalt Core binaries. The binaries are stored compressed,
+using the
+[LZ4 Frame Format](https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md),
+and decompressed when they are loaded and run. This optional feature is off by
+default but partners can enable it by following the instructions below.
+
+## Storage Savings
+
+Across all reference devices tested, including Raspberry Pi 2, we have seen
+compression ratios just above 2.0. We therefore expect that partners can halve
+the space used for Cobalt binary storage by enabling the feature for all
+installation slots: the system image slot and the writable slots.
+
+## Caveats
+
+### Performance Costs
+
+Because the Cobalt Core shared library must be decompressed before it's loaded,
+there is necessarily some effect on startup latency and CPU memory usage. Based
+on our analysis across a range of devices these effects are relatively small.
+
+For startup latency, we measured an increase in `libcobalt` load time in the
+hundreds of milliseconds for the low-powered Raspberry Pi 2 and in the tens of
+milliseconds for more representative, higher-powered devices. This increase is
+small in the context of overall app load time.
+
+For CPU memory usage, `libcobalt.lz4` is decompressed to an in-memory ELF file
+before the program is loaded. We therefore expect CPU memory usage to
+temporarily increase by roughly the size of the uncompressed `libcobalt` and
+then to return to a normal level once the library is loaded. And this is exactly
+what we've seen in our analysis.
+
+### Incompatibilities
+
+This feature is incompatible with the Memory Mapped file feature that is
+controlled by the `--loader_use_mmap_file` switch. With compression, we lose the
+required 1:1 mapping between the file and virtual memory. So,
+`--loader_use_mmap_file` should not be set if compression is enabled for any
+installation slots (next section).
+
+## Enabling Binary Compression
+
+Separate steps are required in order for a partner to enable compression for a)
+the system image slot and b) (Evergreen-Full only) the 2+ writable slots on a
+device.
+
+Compression for the system image slot is enabled by installing `libcobalt.lz4`
+instead of `libcobalt.so` in the read-only system image slot (i.e., SLOT_0).
+Starting with a to be determined Cobalt 23 release, the open-source releases on
+[GitHub](https://github.com/youtube/cobalt/releases) include separate CRX
+packages, denoted by a "compressed" suffix, that contain the pre-built and
+LZ4-compressed Cobalt Core binary.
+
+Compression for the writable slots is enabled by configuring Cobalt to launch
+with the `--use_compressed_updates` flag:
+
+```
+$ ./loader_app --use_compressed_updates
+```
+
+This flag instructs the Cobalt Updater to request, download, and install
+packages containing compressed Cobalt Core binaries from Google Update and
+Google Downloads. As a result, the device ends up with `libcobalt.lz4` instead
+of `libcobalt.so` in the relevant slot after its next update.
+
+Note that the system image slot is independent from the writable slots with
+respect to the compression feature: the feature can be enabled for the system
+image slot but disabled for the writable slots, or vice versa. However, we
+expect that partners will typically enable the feature for all slots in order to
+take full advantage of the storage reduction.
+
+## Disabling Binary Compression
+
+The compression feature is turned off by default. Once enabled, though, it can
+be disabled by undoing the steps required for enablement.
+
+Compression for the system image slot is disabled by installing the uncompressed
+`libcobalt.so` instead of `libcobalt.lz4` in the read-only system image slot.
+
+Compression for the writable slots is disabled by configuring Cobalt to launch
+**without** the `--use_compressed_updates` flag. The Cobalt Updater will then be
+instructed to request, download, and install packages containing the
+uncompressed Cobalt Core binaries.
+
+Note that disabling compression for the writable slots is eventual in the sense
+that the compressed Cobalt Core binaries in these slots will remain and continue
+to be used until newer versions of Cobalt Core are available on Google Update
+and Google Downloads.
+
+## FAQ
+
+### Should multiple apps that share binaries also share compression settings?
+
+The [Cobalt Evergreen Overview doc](cobalt_evergreen_overview.md) describes
+multi-app support, where multiple Cobalt-based applications share Cobalt Core
+binaries (i.e., they share the same installation slot(s)). When multi-app
+support is used then, yes, the apps should also share compression settings.
+
+For the system image slot, this means that either `libcobalt.lz4` or
+`libcobalt.so` is installed in the one, shared slot.
+
+For the writable slots, this means that the loader app is either launched with
+`--use_compressed_updates` set for all apps or launched without it for all apps.
+Otherwise, the different apps would compete with respect to whether the writable
+slots are upgraded to compressed or uncompressed binaries.
diff --git a/cobalt/site/docs/reference/starboard/configuration-public.md b/cobalt/site/docs/reference/starboard/configuration-public.md
index 94dab4e..285f90e 100644
--- a/cobalt/site/docs/reference/starboard/configuration-public.md
+++ b/cobalt/site/docs/reference/starboard/configuration-public.md
@@ -65,11 +65,9 @@
 
 ## Media Configuration
 
- After a seek is triggered, the default behavior is to append video frames from the last key frame before the seek time and append audio frames from the seek time because usually all audio frames are key frames.  On platforms that cannot decode video frames without displaying them, this will cause the video being played without audio for several seconds after seeking.  When the following macro is defined, the app will append audio frames start from the timestamp that is before the timestamp of the video key frame being appended.
-
 | Properties |
 | :--- |
-| **`SB_HAS_QUIRK_SUPPORT_INT16_AUDIO_SAMPLES`**<br><br> The implementation is allowed to support kSbMediaAudioSampleTypeInt16 only when this macro is defined.<br><br>By default, this property is undefined. |
+| **`SB_HAS_QUIRK_SUPPORT_INT16_AUDIO_SAMPLES`**<br><br>The implementation is allowed to support kSbMediaAudioSampleTypeInt16 only when this macro is defined.<br><br>By default, this property is undefined. |
 
 
 ## Memory Configuration
diff --git a/cobalt/site/docs/reference/starboard/gn-configuration.md b/cobalt/site/docs/reference/starboard/gn-configuration.md
index a0bbde6..18db1ee 100644
--- a/cobalt/site/docs/reference/starboard/gn-configuration.md
+++ b/cobalt/site/docs/reference/starboard/gn-configuration.md
@@ -19,11 +19,13 @@
 | **`gtest_target_type`**<br><br> The target type for test targets. Allows changing the target type on platforms where the native code may require an additional packaging step (ex. Android).<br><br>The default value is `"executable"`. |
 | **`has_platform_targets`**<br><br> Whether the platform has platform-specific targets to depend on.<br><br>The default value is `false`. |
 | **`install_target_path`**<br><br> The path to the gni file containing the install_target template which defines how the build should produce the install/ directory.<br><br>The default value is `"//starboard/build/install/no_install.gni"`. |
+| **`is_clang_16`**<br><br> Enable when using clang 16.<br><br>The default value is `false`. |
 | **`loadable_module_configs`**<br><br> Target-specific configurations for loadable_module targets.<br><br>The default value is `[]`. |
-| **`path_to_yasm`**<br><br> Where yasm can be found on the host device.<br><br>The default value is `"yasm"`. |
+| **`nasm_exists`**<br><br> Enables the nasm compiler to be used to compile .asm files.<br><br>The default value is `false`. |
+| **`path_to_nasm`**<br><br> Where yasm can be found on the host device.<br><br>The default value is `"nasm"`. |
 | **`platform_tests_path`**<br><br> Set to the starboard_platform_tests target if the platform implements them.<br><br>The default value is `""`. |
 | **`sabi_path`**<br><br> Where the Starboard ABI file for this platform can be found.<br><br>The default value is `"starboard/sabi/default/sabi.json"`. |
-| **`sb_api_version`**<br><br> The Starboard API version of the current build configuration. The default value is meant to be overridden by a Starboard ABI file.<br><br>The default value is `15`. |
+| **`sb_api_version`**<br><br> The Starboard API version of the current build configuration. The default value is meant to be overridden by a Starboard ABI file.<br><br>The default value is `16`. |
 | **`sb_enable_benchmark`**<br><br> Used to enable benchmarks.<br><br>The default value is `false`. |
 | **`sb_enable_cpp17_audit`**<br><br> Enables an NPLB audit of C++17 support.<br><br>The default value is `true`. |
 | **`sb_enable_lib`**<br><br> Enables embedding Cobalt as a shared library within another app. This requires a 'lib' starboard implementation for the corresponding platform.<br><br>The default value is `false`. |
@@ -39,8 +41,10 @@
 | **`separate_install_targets_for_bundling`**<br><br> Set to true to separate install target directories.<br><br>The default value is `false`. |
 | **`shared_library_configs`**<br><br> Target-specific configurations for shared_library targets.<br><br>The default value is `[]`. |
 | **`source_set_configs`**<br><br> Target-specific configurations for source_set targets.<br><br>The default value is `[]`. |
+| **`starboard_level_final_executable_type`**<br><br>The default value is `"executable"`. |
+| **`starboard_level_gtest_target_type`**<br><br>The default value is `"executable"`. |
 | **`static_library_configs`**<br><br> Target-specific configurations for static_library targets.<br><br>The default value is `[]`. |
 | **`use_skia_next`**<br><br> Flag to use a future version of Skia, currently not available.<br><br>The default value is `false`. |
 | **`use_thin_archive`**<br><br> Whether or not to link with thin archives.<br><br>The default value is `true`. |
 | **`v8_enable_pointer_compression_override`**<br><br> Set to true to enable pointer compression for v8.<br><br>The default value is `true`. |
-| **`yasm_exists`**<br><br> Enables the yasm compiler to be used to compile .asm files.<br><br>The default value is `false`. |
+| **`v8_enable_webassembly`**<br><br> Enable WASM and install WebAssembly global.<br><br>The default value is `false`. |
diff --git a/cobalt/site/docs/reference/starboard/modules/12/character.md b/cobalt/site/docs/reference/starboard/modules/12/character.md
deleted file mode 100644
index 432dcae..0000000
--- a/cobalt/site/docs/reference/starboard/modules/12/character.md
+++ /dev/null
@@ -1,104 +0,0 @@
----
-layout: doc
-title: "Starboard Module Reference: character.h"
----
-
-Provides functions for interacting with characters.
-
-## Functions ##
-
-### SbCharacterIsAlphanumeric ###
-
-Indicates whether the given 8-bit character `c` (as an int) is alphanumeric in
-the current locale.
-
-`c`: The character to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbCharacterIsAlphanumeric(int c)
-```
-
-### SbCharacterIsDigit ###
-
-Indicates whether the given 8-bit character `c` (as an int) is a decimal digit
-in the current locale.
-
-`c`: The character to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbCharacterIsDigit(int c)
-```
-
-### SbCharacterIsHexDigit ###
-
-Indicates whether the given 8-bit character `c` (as an int) is a hexadecimal in
-the current locale.
-
-`c`: The character to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbCharacterIsHexDigit(int c)
-```
-
-### SbCharacterIsSpace ###
-
-Indicates whether the given 8-bit character `c` (as an int) is a space in the
-current locale.
-
-`c`: The character to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbCharacterIsSpace(int c)
-```
-
-### SbCharacterIsUpper ###
-
-Indicates whether the given 8-bit character `c` (as an int) is uppercase in the
-current locale.
-
-`c`: The character to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbCharacterIsUpper(int c)
-```
-
-### SbCharacterToLower ###
-
-Converts the given 8-bit character (as an int) to lowercase in the current
-locale and returns an 8-bit character. If there is no lowercase version of the
-character, or the character is already lowercase, the function just returns the
-character as-is.
-
-`c`: The character to be converted.
-
-#### Declaration ####
-
-```
-int SbCharacterToLower(int c)
-```
-
-### SbCharacterToUpper ###
-
-Converts the given 8-bit character (as an int) to uppercase in the current
-locale and returns an 8-bit character. If there is no uppercase version of the
-character, or the character is already uppercase, the function just returns the
-character as-is.
-
-`c`: The character to be converted.
-
-#### Declaration ####
-
-```
-int SbCharacterToUpper(int c)
-```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/double.md b/cobalt/site/docs/reference/starboard/modules/12/double.md
deleted file mode 100644
index 6667b50..0000000
--- a/cobalt/site/docs/reference/starboard/modules/12/double.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-layout: doc
-title: "Starboard Module Reference: double.h"
----
-
-Provides double-precision floating point helper functions.
-
-## Functions ##
-
-### SbDoubleAbsolute ###
-
-Returns the absolute value of the given double-precision floating-point number
-`d`, preserving `NaN` and infinity.
-
-`d`: The number to be adjusted.
-
-#### Declaration ####
-
-```
-double SbDoubleAbsolute(const double d)
-```
-
-### SbDoubleExponent ###
-
-Returns `base` taken to the power of `exponent`.
-
-`base`: The number to be adjusted. `exponent`: The power to which the `base`
-number should be raised.
-
-#### Declaration ####
-
-```
-double SbDoubleExponent(const double base, const double exponent)
-```
-
-### SbDoubleFloor ###
-
-Floors double-precision floating-point number `d` to the nearest integer.
-
-`d`: The number to be floored.
-
-#### Declaration ####
-
-```
-double SbDoubleFloor(const double d)
-```
-
-### SbDoubleIsFinite ###
-
-Determines whether double-precision floating-point number `d` represents a
-finite number.
-
-`d`: The number to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbDoubleIsFinite(const double d)
-```
-
-### SbDoubleIsNan ###
-
-Determines whether double-precision floating-point number `d` represents "Not a
-Number."
-
-`d`: The number to be evaluated.
-
-#### Declaration ####
-
-```
-bool SbDoubleIsNan(const double d)
-```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/speech_recognizer.md b/cobalt/site/docs/reference/starboard/modules/12/speech_recognizer.md
deleted file mode 100644
index 0a1dc6b..0000000
--- a/cobalt/site/docs/reference/starboard/modules/12/speech_recognizer.md
+++ /dev/null
@@ -1,269 +0,0 @@
----
-layout: doc
-title: "Starboard Module Reference: speech_recognizer.h"
----
-
-Defines a streaming speech recognizer API. It provides access to the platform
-speech recognition service.
-
-Note that there can be only one speech recognizer. Attempting to create a second
-speech recognizer without destroying the first one will result in undefined
-behavior.
-
-`SbSpeechRecognizerCreate`, `SbSpeechRecognizerStart`, `SbSpeechRecognizerStop`,
-`SbSpeechRecognizerCancel` and `SbSpeechRecognizerDestroy` should be called from
-a single thread. Callbacks defined in `SbSpeechRecognizerHandler` will happen on
-another thread, so calls back into the SbSpeechRecognizer from the callback
-thread are disallowed.
-
-## Macros ##
-
-### kSbSpeechRecognizerInvalid ###
-
-Well-defined value for an invalid speech recognizer handle.
-
-## Enums ##
-
-### SbSpeechRecognizerError ###
-
-Indicates what has gone wrong with the recognition.
-
-#### Values ####
-
-*   `kSbNoSpeechError`
-
-    No speech was detected. Speech timed out.
-*   `kSbAborted`
-
-    Speech input was aborted somehow.
-*   `kSbAudioCaptureError`
-
-    Audio capture failed.
-*   `kSbNetworkError`
-
-    Some network communication that was required to complete the recognition
-    failed.
-*   `kSbNotAllowed`
-
-    The implementation is not allowing any speech input to occur for reasons of
-    security, privacy or user preference.
-*   `kSbServiceNotAllowed`
-
-    The implementation is not allowing the application requested speech service,
-    but would allow some speech service, to be used either because the
-    implementation doesn't support the selected one or because of reasons of
-    security, privacy or user preference.
-*   `kSbBadGrammar`
-
-    There was an error in the speech recognition grammar or semantic tags, or
-    the grammar format or semantic tag format is supported.
-*   `kSbLanguageNotSupported`
-
-    The language was not supported.
-
-## Typedefs ##
-
-### SbSpeechRecognizer ###
-
-An opaque handle to an implementation-private structure that represents a speech
-recognizer.
-
-#### Definition ####
-
-```
-typedef struct SbSpeechRecognizerPrivate* SbSpeechRecognizer
-```
-
-### SbSpeechRecognizerErrorFunction ###
-
-A function to notify that a speech recognition error occurred. `error`: The
-occurred speech recognition error.
-
-#### Definition ####
-
-```
-typedef void(* SbSpeechRecognizerErrorFunction) (void *context, SbSpeechRecognizerError error)
-```
-
-### SbSpeechRecognizerResultsFunction ###
-
-A function to notify that the recognition results are ready. `results`: the list
-of recognition results. `results_size`: the number of `results`. `is_final`:
-indicates if the `results` is final.
-
-#### Definition ####
-
-```
-typedef void(* SbSpeechRecognizerResultsFunction) (void *context, SbSpeechResult *results, int results_size, bool is_final)
-```
-
-### SbSpeechRecognizerSpeechDetectedFunction ###
-
-A function to notify that the user has started to speak or stops speaking.
-`detected`: true if the user has started to speak, and false if the user stops
-speaking.
-
-#### Definition ####
-
-```
-typedef void(* SbSpeechRecognizerSpeechDetectedFunction) (void *context, bool detected)
-```
-
-## Structs ##
-
-### SbSpeechConfiguration ###
-
-#### Members ####
-
-*   `bool continuous`
-
-    When the continuous value is set to false, the implementation MUST return no
-    more than one final result in response to starting recognition. When the
-    continuous attribute is set to true, the implementation MUST return zero or
-    more final results representing multiple consecutive recognitions in
-    response to starting recognition. This attribute setting does not affect
-    interim results.
-*   `bool interim_results`
-
-    Controls whether interim results are returned. When set to true, interim
-    results SHOULD be returned. When set to false, interim results MUST NOT be
-    returned. This value setting does not affect final results.
-*   `int max_alternatives`
-
-    This sets the maximum number of SbSpeechResult in
-    `SbSpeechRecognizerOnResults` callback.
-
-### SbSpeechRecognizerHandler ###
-
-Allows receiving notifications from the device when recognition related events
-occur.
-
-The void* context is passed to every function.
-
-#### Members ####
-
-*   `SbSpeechRecognizerSpeechDetectedFunction on_speech_detected`
-
-    Function to notify the beginning/end of the speech.
-*   `SbSpeechRecognizerErrorFunction on_error`
-
-    Function to notify the speech error.
-*   `SbSpeechRecognizerResultsFunction on_results`
-
-    Function to notify that the recognition results are available.
-*   `void * context`
-
-    This is passed to handler functions as first argument.
-
-### SbSpeechResult ###
-
-The recognition response that is received from the recognizer.
-
-#### Members ####
-
-*   `char * transcript`
-
-    The raw words that the user spoke.
-*   `float confidence`
-
-    A numeric estimate between 0 and 1 of how confident the recognition system
-    is that the recognition is correct. A higher number means the system is more
-    confident. NaN represents an unavailable confidence score.
-
-## Functions ##
-
-### SbSpeechRecognizerCancel ###
-
-Cancels speech recognition. The speech recognizer stops listening to audio and
-does not return any information. When `SbSpeechRecognizerCancel` is called, the
-implementation MUST NOT collect additional audio, MUST NOT continue to listen to
-the user, and MUST stop recognizing. This is important for privacy reasons. If
-`SbSpeechRecognizerCancel` is called on a speech recognizer which is already
-stopped or cancelled, the implementation MUST ignore the call.
-
-#### Declaration ####
-
-```
-void SbSpeechRecognizerCancel(SbSpeechRecognizer recognizer)
-```
-
-### SbSpeechRecognizerCreate ###
-
-Creates a speech recognizer with a speech recognizer handler.
-
-If the system has a speech recognition service available, this function returns
-the newly created handle.
-
-If no speech recognition service is available on the device, this function
-returns `kSbSpeechRecognizerInvalid`.
-
-`SbSpeechRecognizerCreate` does not expect the passed SbSpeechRecognizerHandler
-structure to live after `SbSpeechRecognizerCreate` is called, so the
-implementation must copy the contents if necessary.
-
-#### Declaration ####
-
-```
-SbSpeechRecognizer SbSpeechRecognizerCreate(const SbSpeechRecognizerHandler *handler)
-```
-
-### SbSpeechRecognizerDestroy ###
-
-Destroys the given speech recognizer. If the speech recognizer is in the started
-state, it is first stopped and then destroyed.
-
-#### Declaration ####
-
-```
-void SbSpeechRecognizerDestroy(SbSpeechRecognizer recognizer)
-```
-
-### SbSpeechRecognizerIsSupported ###
-
-Returns whether the platform supports SbSpeechRecognizer.
-
-#### Declaration ####
-
-```
-bool SbSpeechRecognizerIsSupported()
-```
-
-### SbSpeechRecognizerIsValid ###
-
-Indicates whether the given speech recognizer is valid.
-
-#### Declaration ####
-
-```
-static bool SbSpeechRecognizerIsValid(SbSpeechRecognizer recognizer)
-```
-
-### SbSpeechRecognizerStart ###
-
-Starts listening to audio and recognizing speech with the specified speech
-configuration. If `SbSpeechRecognizerStart` is called on an already started
-speech recognizer, the implementation MUST ignore the call and return false.
-
-Returns whether the speech recognizer is started successfully.
-
-#### Declaration ####
-
-```
-bool SbSpeechRecognizerStart(SbSpeechRecognizer recognizer, const SbSpeechConfiguration *configuration)
-```
-
-### SbSpeechRecognizerStop ###
-
-Stops listening to audio and returns a result using just the audio that it has
-already received. Once `SbSpeechRecognizerStop` is called, the implementation
-MUST NOT collect additional audio and MUST NOT continue to listen to the user.
-This is important for privacy reasons. If `SbSpeechRecognizerStop` is called on
-a speech recognizer which is already stopped or being stopped, the
-implementation MUST ignore the call.
-
-#### Declaration ####
-
-```
-void SbSpeechRecognizerStop(SbSpeechRecognizer recognizer)
-```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/string.md b/cobalt/site/docs/reference/starboard/modules/12/string.md
deleted file mode 100644
index eece136..0000000
--- a/cobalt/site/docs/reference/starboard/modules/12/string.md
+++ /dev/null
@@ -1,510 +0,0 @@
----
-layout: doc
-title: "Starboard Module Reference: string.h"
----
-
-Defines functions for interacting with c-style strings.
-
-## Functions ##
-
-### SbStringAToI ###
-
-Parses a string into a base-10 integer. This is a shorthand replacement for
-`atoi`.
-
-`value`: The string to be converted.
-
-#### Declaration ####
-
-```
-static int SbStringAToI(const char *value)
-```
-
-### SbStringAToL ###
-
-Parses a string into a base-10, long integer. This is a shorthand replacement
-for `atol`.
-
-`value`: The string to be converted. NOLINTNEXTLINE(runtime/int)
-
-#### Declaration ####
-
-```
-static long SbStringAToL(const char *value)
-```
-
-### SbStringCompare ###
-
-Compares the first `count` characters of two 8-bit character strings. The return
-value is:
-
-*   `< 0` if `string1` is ASCII-betically lower than `string2`.
-
-*   `0` if the two strings are equal.
-
-*   `> 0` if `string1` is ASCII-betically higher than `string2`.
-
-This function is meant to be a drop-in replacement for `strncmp`.
-
-`string1`: The first 8-bit character string to compare. `string2`: The second
-8-bit character string to compare. `count`: The number of characters to compare.
-
-#### Declaration ####
-
-```
-int SbStringCompare(const char *string1, const char *string2, size_t count)
-```
-
-### SbStringCompareAll ###
-
-Compares two entire 8-bit character strings. The return value is:
-
-*   `< 0` if `string1` is ASCII-betically lower than `string2`.
-
-*   `0` if the two strings are equal.
-
-*   `> 0` if `string1` is ASCII-betically higher than `string2`.
-
-This function is meant to be a drop-in replacement for `strcmp`.
-
-`string1`: The first 8-bit character string to compare. `string2`: The second
-8-bit character string to compare.
-
-#### Declaration ####
-
-```
-int SbStringCompareAll(const char *string1, const char *string2)
-```
-
-### SbStringCompareNoCase ###
-
-Compares two strings, ignoring differences in case. The return value is:
-
-*   `< 0` if `string1` is ASCII-betically lower than `string2`.
-
-*   `0` if the two strings are equal.
-
-*   `> 0` if `string1` is ASCII-betically higher than `string2`.
-
-This function is meant to be a drop-in replacement for `strcasecmp`.
-
-`string1`: The first string to compare. `string2`: The second string to compare.
-
-#### Declaration ####
-
-```
-int SbStringCompareNoCase(const char *string1, const char *string2)
-```
-
-### SbStringCompareNoCaseN ###
-
-Compares the first `count` characters of two strings, ignoring differences in
-case. The return value is:
-
-*   `< 0` if `string1` is ASCII-betically lower than `string2`.
-
-*   `0` if the two strings are equal.
-
-*   `> 0` if `string1` is ASCII-betically higher than `string2`.
-
-This function is meant to be a drop-in replacement for `strncasecmp`.
-
-`string1`: The first string to compare. `string2`: The second string to compare.
-`count`: The number of characters to compare.
-
-#### Declaration ####
-
-```
-int SbStringCompareNoCaseN(const char *string1, const char *string2, size_t count)
-```
-
-### SbStringCompareWide ###
-
-Compares the first `count` characters of two 16-bit character strings. The
-return value is:
-
-*   `< 0` if `string1` is ASCII-betically lower than `string2`.
-
-*   `0` if the two strings are equal.
-
-*   `> 0` if `string1` is ASCII-betically higher than `string2`.
-
-This function is meant to be a drop-in replacement for `wcsncmp`.
-
-`string1`: The first 16-bit character string to compare.weird `string2`: The
-second 16-bit character string to compare. `count`: The number of characters to
-compare.
-
-#### Declaration ####
-
-```
-int SbStringCompareWide(const wchar_t *string1, const wchar_t *string2, size_t count)
-```
-
-### SbStringConcat ###
-
-Appends `source` to `out_destination` as long as `out_destination` has enough
-storage space to hold the concatenated string.
-
-This function is meant to be a drop-in replacement for `strlcat`. Also note that
-this function's signature is NOT compatible with `strncat`.
-
-`out_destination`: The string to which the `source` string is appended.
-`source`: The string to be appended to the destination string.
-`destination_size`: The amount of storage space available for the concatenated
-string.
-
-#### Declaration ####
-
-```
-int SbStringConcat(char *out_destination, const char *source, int destination_size)
-```
-
-### SbStringConcatUnsafe ###
-
-An inline wrapper for an unsafe SbStringConcat that assumes that the
-`out_destination` provides enough storage space for the concatenated string.
-Note that this function's signature is NOT compatible with `strcat`.
-
-`out_destination`: The string to which the `source` string is appended.
-`source`: The string to be appended to the destination string.
-
-#### Declaration ####
-
-```
-static int SbStringConcatUnsafe(char *out_destination, const char *source)
-```
-
-### SbStringConcatWide ###
-
-Identical to SbStringCat, but for wide characters.
-
-`out_destination`: The string to which the `source` string is appended.
-`source`: The string to be appended to the destination string.
-`destination_size`: The amount of storage space available for the concatenated
-string.
-
-#### Declaration ####
-
-```
-int SbStringConcatWide(wchar_t *out_destination, const wchar_t *source, int destination_size)
-```
-
-### SbStringCopy ###
-
-Copies as much of a `source` string as possible and null-terminates it, given
-that `destination_size` characters of storage are available. This function is
-meant to be a drop-in replacement for `strlcpy`.
-
-The return value specifies the length of `source`.
-
-`out_destination`: The location to which the string is copied. `source`: The
-string to be copied. `destination_size`: The amount of the source string to
-copy.
-
-#### Declaration ####
-
-```
-int SbStringCopy(char *out_destination, const char *source, int destination_size)
-```
-
-### SbStringCopyUnsafe ###
-
-An inline wrapper for an unsafe SbStringCopy that assumes that the destination
-provides enough storage space for the entire string. The return value is a
-pointer to the destination string. This function is meant to be a drop-in
-replacement for `strcpy`.
-
-`out_destination`: The location to which the string is copied. `source`: The
-string to be copied.
-
-#### Declaration ####
-
-```
-static char* SbStringCopyUnsafe(char *out_destination, const char *source)
-```
-
-### SbStringCopyWide ###
-
-Identical to SbStringCopy, but for wide characters.
-
-`out_destination`: The location to which the string is copied. `source`: The
-string to be copied. `destination_size`: The amount of the source string to
-copy.
-
-#### Declaration ####
-
-```
-int SbStringCopyWide(wchar_t *out_destination, const wchar_t *source, int destination_size)
-```
-
-### SbStringDuplicate ###
-
-Copies `source` into a buffer that is allocated by this function and that can be
-freed with SbMemoryDeallocate. This function is meant to be a drop-in
-replacement for `strdup`.
-
-`source`: The string to be copied.
-
-#### Declaration ####
-
-```
-char* SbStringDuplicate(const char *source)
-```
-
-### SbStringFindCharacter ###
-
-Finds the first occurrence of a `character` in `str`. The return value is a
-pointer to the found character in the given string or `NULL` if the character is
-not found. Note that this function's signature does NOT match that of the
-`strchr` function.
-
-`str`: The string to search for the character. `character`: The character to
-find in the string.
-
-#### Declaration ####
-
-```
-const char* SbStringFindCharacter(const char *str, char character)
-```
-
-### SbStringFindLastCharacter ###
-
-Finds the last occurrence of a specified character in a string. The return value
-is a pointer to the found character in the given string or `NULL` if the
-character is not found. Note that this function's signature does NOT match that
-of the `strrchr` function.
-
-`str`: The string to search for the character. `character`: The character to
-find in the string.
-
-#### Declaration ####
-
-```
-const char* SbStringFindLastCharacter(const char *str, char character)
-```
-
-### SbStringFindString ###
-
-Finds the first occurrence of `str2` in `str1`. The return value is a pointer to
-the beginning of the found string or `NULL` if the string is not found. This
-function is meant to be a drop-in replacement for `strstr`.
-
-`str1`: The string in which to search for the presence of `str2`. `str2`: The
-string to locate in `str1`.
-
-#### Declaration ####
-
-```
-const char* SbStringFindString(const char *str1, const char *str2)
-```
-
-### SbStringFormat ###
-
-Produces a string formatted with `format` and `arguments`, placing as much of
-the result that will fit into `out_buffer`. The return value specifies the
-number of characters that the format would produce if `buffer_size` were
-infinite.
-
-This function is meant to be a drop-in replacement for `vsnprintf`.
-
-`out_buffer`: The location where the formatted string is stored. `buffer_size`:
-The size of `out_buffer`. `format`: A string that specifies how the data should
-be formatted. `arguments`: Variable arguments used in the string.
-
-#### Declaration ####
-
-```
-int SbStringFormat(char *out_buffer, size_t buffer_size, const char *format, va_list arguments) SB_PRINTF_FORMAT(3
-```
-
-### SbStringFormatF ###
-
-An inline wrapper of SbStringFormat that converts from ellipsis to va_args. This
-function is meant to be a drop-in replacement for `snprintf`.
-
-`out_buffer`: The location where the formatted string is stored. `buffer_size`:
-The size of `out_buffer`. `format`: A string that specifies how the data should
-be formatted. `...`: Arguments used in the string.
-
-#### Declaration ####
-
-```
-int static int static int SbStringFormatF(char *out_buffer, size_t buffer_size, const char *format,...) SB_PRINTF_FORMAT(3
-```
-
-### SbStringFormatUnsafeF ###
-
-An inline wrapper of SbStringFormat that is meant to be a drop-in replacement
-for the unsafe but commonly used `sprintf`.
-
-`out_buffer`: The location where the formatted string is stored. `format`: A
-string that specifies how the data should be formatted. `...`: Arguments used in
-the string.
-
-#### Declaration ####
-
-```
-static int static int SbStringFormatUnsafeF(char *out_buffer, const char *format,...) SB_PRINTF_FORMAT(2
-```
-
-### SbStringFormatWide ###
-
-This function is identical to SbStringFormat, but is for wide characters. It is
-meant to be a drop-in replacement for `vswprintf`.
-
-`out_buffer`: The location where the formatted string is stored. `buffer_size`:
-The size of `out_buffer`. `format`: A string that specifies how the data should
-be formatted. `arguments`: Variable arguments used in the string.
-
-#### Declaration ####
-
-```
-int SbStringFormatWide(wchar_t *out_buffer, size_t buffer_size, const wchar_t *format, va_list arguments)
-```
-
-### SbStringFormatWideF ###
-
-An inline wrapper of SbStringFormatWide that converts from ellipsis to
-`va_args`.
-
-`out_buffer`: The location where the formatted string is stored. `buffer_size`:
-The size of `out_buffer`. `format`: A string that specifies how the data should
-be formatted. `...`: Arguments used in the string.
-
-#### Declaration ####
-
-```
-static int SbStringFormatWideF(wchar_t *out_buffer, size_t buffer_size, const wchar_t *format,...)
-```
-
-### SbStringGetLength ###
-
-Returns the length, in characters, of `str`.
-
-`str`: A zero-terminated ASCII string.
-
-#### Declaration ####
-
-```
-size_t SbStringGetLength(const char *str)
-```
-
-### SbStringGetLengthWide ###
-
-Returns the length of a wide character string. (This function is the same as
-SbStringGetLength, but for a string comprised of wide characters.) This function
-assumes that there are no multi-element characters.
-
-`str`: A zero-terminated ASCII string.
-
-#### Declaration ####
-
-```
-size_t SbStringGetLengthWide(const wchar_t *str)
-```
-
-### SbStringParseDouble ###
-
-Extracts a string that represents an integer from the beginning of `start` into
-a double.
-
-This function is meant to be a drop-in replacement for `strtod`, except that it
-is explicitly declared to return a double.
-
-`start`: The string that begins with the number to be converted. `out_end`: If
-provided, the function places a pointer to the end of the consumed portion of
-the string into `out_end`.
-
-#### Declaration ####
-
-```
-double SbStringParseDouble(const char *start, char **out_end)
-```
-
-### SbStringParseSignedInteger ###
-
-Extracts a string that represents an integer from the beginning of `start` into
-a signed integer in the given `base`. This function is meant to be a drop-in
-replacement for `strtol`.
-
-`start`: The string that begins with the number to be converted. `out_end`: If
-provided, the function places a pointer to the end of the consumed portion of
-the string into `out_end`. `base`: The base into which the number will be
-converted. The value must be between `2` and `36`, inclusive.
-NOLINTNEXTLINE(runtime/int)
-
-#### Declaration ####
-
-```
-long SbStringParseSignedInteger(const char *start, char **out_end, int base)
-```
-
-### SbStringParseUInt64 ###
-
-Extracts a string that represents an integer from the beginning of `start` into
-an unsigned 64-bit integer in the given `base`.
-
-This function is meant to be a drop-in replacement for `strtoull`, except that
-it is explicitly declared to return `uint64_t`.
-
-`start`: The string that begins with the number to be converted. `out_end`: If
-provided, the function places a pointer to the end of the consumed portion of
-the string into `out_end`. `base`: The base into which the number will be
-converted. The value must be between `2` and `36`, inclusive.
-
-#### Declaration ####
-
-```
-uint64_t SbStringParseUInt64(const char *start, char **out_end, int base)
-```
-
-### SbStringParseUnsignedInteger ###
-
-Extracts a string that represents an integer from the beginning of `start` into
-an unsigned integer in the given `base`. This function is meant to be a drop-in
-replacement for `strtoul`.
-
-`start`: The string that begins with the number to be converted. `out_end`: If
-provided, the function places a pointer to the end of the consumed portion of
-the string into `out_end`. `base`: The base into which the number will be
-converted. The value must be between `2` and `36`, inclusive.
-NOLINTNEXTLINE(runtime/int)
-
-#### Declaration ####
-
-```
-unsigned long SbStringParseUnsignedInteger(const char *start, char **out_end, int base)
-```
-
-### SbStringScan ###
-
-Scans `buffer` for `pattern`, placing the extracted values in `arguments`. The
-return value specifies the number of successfully matched items, which may be
-`0`.
-
-This function is meant to be a drop-in replacement for `vsscanf`.
-
-`buffer`: The string to scan for the pattern. `pattern`: The string to search
-for in `buffer`. `arguments`: Values matching `pattern` that were extracted from
-`buffer`.
-
-#### Declaration ####
-
-```
-int SbStringScan(const char *buffer, const char *pattern, va_list arguments)
-```
-
-### SbStringScanF ###
-
-An inline wrapper of SbStringScan that converts from ellipsis to `va_args`. This
-function is meant to be a drop-in replacement for `sscanf`. `buffer`: The string
-to scan for the pattern. `pattern`: The string to search for in `buffer`. `...`:
-Values matching `pattern` that were extracted from `buffer`.
-
-#### Declaration ####
-
-```
-static int SbStringScanF(const char *buffer, const char *pattern,...)
-```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/audio_sink.md b/cobalt/site/docs/reference/starboard/modules/13/audio_sink.md
index 8cf2329..b0e652f 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/audio_sink.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/audio_sink.md
@@ -72,6 +72,53 @@
 
 ## Functions ##
 
+### SbAudioSinkCreate ###
+
+Creates an audio sink for the specified `channels` and `sampling_frequency_hz`,
+acquires all resources needed to operate the audio sink, and returns an opaque
+handle to the audio sink.
+
+If the particular platform doesn't support the requested audio sink, the
+function returns `kSbAudioSinkInvalid` without calling any of the callbacks. If
+there is a platform limitation on how many audio sinks can coexist
+simultaneously, then calls made to this function that attempt to exceed that
+limit must return `kSbAudioSinkInvalid`. Multiple calls to SbAudioSinkCreate
+must not cause a crash.
+
+`channels`: The number of audio channels, such as left and right channels in
+stereo audio. `sampling_frequency_hz`: The sample frequency of the audio data
+being streamed. For example, 22,000 Hz means 22,000 sample elements represents
+one second of audio data. `audio_sample_type`: The type of each sample of the
+audio data – `int16`, `float32`, etc. `audio_frame_storage_type`: Indicates
+whether frames are interleaved or planar. `frame_buffers`: An array of pointers
+to sample data.
+
+*   If the sink is operating in interleaved mode, the array contains only one
+    element, which is an array containing (`frames_per_channel` * `channels`)
+    samples.
+
+*   If the sink is operating in planar mode, the number of elements in the array
+    is the same as `channels`, and each element is an array of
+    `frames_per_channel` samples. The caller has to ensure that `frame_buffers`
+    is valid until SbAudioSinkDestroy is called. `frames_per_channel`: The size
+    of the frame buffers, in units of the number of samples per channel. The
+    frame, in this case, represents a group of samples at the same media time,
+    one for each channel. `update_source_status_func`: The audio sink calls this
+    function on an internal thread to query the status of the source. It is
+    called immediately after SbAudioSinkCreate is called, even before it
+    returns. The caller has to ensure that the callback functions above return
+    meaningful values in this case. The value cannot be NULL.
+    `consume_frames_func`: The audio sink calls this function on an internal
+    thread to report consumed frames. The value cannot be NULL. `context`: A
+    value that is passed back to all callbacks and is generally used to point at
+    a class or struct that contains state associated with the audio sink.
+
+#### Declaration ####
+
+```
+SbAudioSink SbAudioSinkCreate(int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, SbMediaAudioFrameStorageType audio_frame_storage_type, SbAudioSinkFrameBuffers frame_buffers, int frames_per_channel, SbAudioSinkUpdateSourceStatusFunc update_source_status_func, SbAudioSinkConsumeFramesFunc consume_frames_func, void *context)
+```
+
 ### SbAudioSinkDestroy ###
 
 Destroys `audio_sink`, freeing all associated resources. Before returning, the
@@ -165,4 +212,3 @@
 ```
 bool SbAudioSinkIsValid(SbAudioSink audio_sink)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/decode_target.md b/cobalt/site/docs/reference/starboard/modules/13/decode_target.md
index 2e61c1e..23ed59d 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/decode_target.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/decode_target.md
@@ -327,8 +327,10 @@
 
 ### SbDecodeTargetGetInfo ###
 
-Writes all information about `decode_target` into `out_info`. Returns false if
-the provided `out_info` structure is not zero initialized.
+Writes all information about `decode_target` into `out_info`. The
+`decode_target` must not be kSbDecodeTargetInvalid. The `out_info` pointer must
+not be NULL. Returns false if the provided `out_info` structure is not zero
+initialized.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/13/drm.md b/cobalt/site/docs/reference/starboard/modules/13/drm.md
index beb65c9..fbb92f9 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/drm.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/drm.md
@@ -238,6 +238,8 @@
 
 Clear any internal states/resources related to the specified `session_id`.
 
+`drm_system` must not be `kSbDrmSystemInvalid`. `session_id` must not be NULL.
+
 #### Declaration ####
 
 ```
@@ -254,7 +256,7 @@
 result, if this function is called from a callback that is passed to
 SbDrmCreateSystem(), a deadlock will occur.
 
-`drm_system`: The DRM system to be destroyed.
+`drm_system`: The DRM system to be destroyed. Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -281,7 +283,7 @@
 
 `drm_system`: The DRM system that defines the key system used for the session
 update request payload as well as the callback function that is called as a
-result of the function being called.
+result of the function being called. Must not be `kSbDrmSystemInvalid`.
 
 `ticket`: The opaque ID that allows to distinguish callbacks from multiple
 concurrent calls to SbDrmGenerateSessionUpdateRequest(), which will be passed to
@@ -289,10 +291,10 @@
 establish ticket uniqueness, issuing multiple requests with the same ticket may
 result in undefined behavior. The value `kSbDrmTicketInvalid` must not be used.
 
-`type`: The case-sensitive type of the session update request payload.
-`initialization_data`: The data for which the session update request payload is
-created. `initialization_data_size`: The size of the session update request
-payload.
+`type`: The case-sensitive type of the session update request payload. Must not
+be NULL. `initialization_data`: The data for which the session update request
+payload is created. Must not be NULL. `initialization_data_size`: The size of
+the session update request payload.
 
 #### Declaration ####
 
@@ -322,7 +324,7 @@
 It should return NULL when there is no metrics support in the underlying drm
 system, or when the drm system implementation fails to retrieve the metrics.
 
-The caller will never set `size` to NULL.
+`drm_system` must not be `kSbDrmSystemInvalid`. `size` must not be NULL.
 
 #### Declaration ####
 
@@ -337,6 +339,7 @@
 the life time of `drm_system`.
 
 `drm_system`: The DRM system to check if its server certificate is updatable.
+Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -371,14 +374,15 @@
 a previous call is called. Note that this function should only be called after
 `SbDrmIsServerCertificateUpdatable` is called first and returned true.
 
-`drm_system`: The DRM system whose server certificate is being updated.
-`ticket`: The opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateServerCertificate(), which will be passed to
-`server_certificate_updated_callback` as-is. It is the responsibility of the
-caller to establish ticket uniqueness, issuing multiple requests with the same
-ticket may result in undefined behavior. The value `kSbDrmTicketInvalid` must
-not be used. `certificate`: Pointer to the server certificate data.
-`certificate_size`: Size of the server certificate data.
+`drm_system`: The DRM system whose server certificate is being updated. Must not
+be `kSbDrmSystemInvalid`. `ticket`: The opaque ID that allows to distinguish
+callbacks from multiple concurrent calls to SbDrmUpdateServerCertificate(),
+which will be passed to `server_certificate_updated_callback` as-is. It is the
+responsibility of the caller to establish ticket uniqueness, issuing multiple
+requests with the same ticket may result in undefined behavior. The value
+`kSbDrmTicketInvalid` must not be used. `certificate`: Pointer to the server
+certificate data. Must not be NULL. `certificate_size`: Size of the server
+certificate data.
 
 #### Declaration ####
 
@@ -391,22 +395,23 @@
 Update session with `key`, in `drm_system`'s key system, from the license server
 response. Calls `session_updated_callback` with `context` and whether the update
 succeeded. `context` may be used to route callbacks back to an object instance.
+The `key` must not be NULL.
 
-`ticket` is the opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateSession(), which will be passed to
-`session_updated_callback` as-is. It is the responsibility of the caller to
-establish ticket uniqueness, issuing multiple calls with the same ticket may
-result in undefined behavior.
+`drm_system` must not be `kSbDrmSystemInvalid`. `ticket` is the opaque ID that
+allows to distinguish callbacks from multiple concurrent calls to
+SbDrmUpdateSession(), which will be passed to `session_updated_callback` as-is.
+It is the responsibility of the caller to establish ticket uniqueness, issuing
+multiple calls with the same ticket may result in undefined behavior.
 
 Once the session is successfully updated, an SbPlayer or SbDecoder associated
 with that DRM key system will be able to decrypt encrypted samples.
 
 `drm_system`'s `session_updated_callback` may called either from the current
-thread before this function returns or from another thread.
+thread before this function returns or from another thread. The `session_id`
+must not be NULL.
 
 #### Declaration ####
 
 ```
 void SbDrmUpdateSession(SbDrmSystem drm_system, int ticket, const void *key, int key_size, const void *session_id, int session_id_size)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/event.md b/cobalt/site/docs/reference/starboard/modules/13/event.md
index 8d20c6f..01a9d24 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/event.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/event.md
@@ -3,10 +3,6 @@
 title: "Starboard Module Reference: event.h"
 ---
 
-For SB_API_VERSION >= 13
-
-Module Overview: Starboard Event module
-
 Defines the event system that wraps the Starboard main loop and entry point.
 
 ## The Starboard Application Lifecycle ##
@@ -82,75 +78,6 @@
 Note that the application is always expected to transition through `BLURRED`,
 `CONCEALED` to `FROZEN` before receiving `Stop` or being killed.
 
-For SB_API_VERSION < 13
-
-Module Overview: Starboard Event module
-
-Defines the event system that wraps the Starboard main loop and entry point.
-
-## The Starboard Application Lifecycle ##
-
-```
-    ---------- *
-   |           |
-   |        Preload
-   |           |
-   |           V
- Start   [ PRELOADING ] ------------
-   |           |                    |
-   |         Start                  |
-   |           |                    |
-   |           V                    |
-    ----> [ STARTED ] <----         |
-               |           |        |
-             Pause       Unpause    |
-               |           |     Suspend
-               V           |        |
-    -----> [ PAUSED ] -----         |
-   |           |                    |
-Resume      Suspend                 |
-   |           |                    |
-   |           V                    |
-    ---- [ SUSPENDED ] <------------
-               |
-              Stop
-               |
-               V
-          [ STOPPED ]
-
-```
-
-The first event that a Starboard application receives is either `Start`
-(`kSbEventTypeStart`) or `Preload` (`kSbEventTypePreload`). `Start` puts the
-application in the `STARTED` state, whereas `Preload` puts the application in
-the `PRELOADING` state.
-
-`PRELOADING` can only happen as the first application state. In this state, the
-application should start and run as normal, but will not receive any input, and
-should not try to initialize graphics resources via GL. In `PRELOADING`, the
-application can receive `Start` or `Suspend` events. `Start` will receive the
-same data that was passed into `Preload`.
-
-In the `STARTED` state, the application is in the foreground and can expect to
-do all of the normal things it might want to do. Once in the `STARTED` state, it
-may receive a `Pause` event, putting the application into the `PAUSED` state.
-
-In the `PAUSED` state, the application is still visible, but has lost focus, or
-it is partially obscured by a modal dialog, or it is on its way to being shut
-down. The application should pause activity in this state. In this state, it can
-receive `Unpause` to be brought back to the foreground state (`STARTED`), or
-`Suspend` to be pushed further in the background to the `SUSPENDED` state.
-
-In the `SUSPENDED` state, the application is generally not visible. It should
-immediately release all graphics and video resources, and shut down all
-background activity (timers, rendering, etc). Additionally, the application
-should flush storage to ensure that if the application is killed, the storage
-will be up-to-date. The application may be killed at this point, but will
-ideally receive a `Stop` event for a more graceful shutdown.
-
-Note that the application is always expected to transition through `PAUSED` to
-`SUSPENDED` before receiving `Stop` or being killed.
-
 ## Enums ##
 
 ### SbEventType ###
@@ -465,10 +392,10 @@
 may be called from any thread, but `callback` is always called from the main
 Starboard thread, queued with other pending events.
 
-`callback`: The callback function to be called. `context`: The context that is
-passed to the `callback` function. `delay`: The minimum number of microseconds
-to wait before calling the `callback` function. Set `delay` to `0` to call the
-callback as soon as possible.
+`callback`: The callback function to be called. Must not be NULL. `context`: The
+context that is passed to the `callback` function. `delay`: The minimum number
+of microseconds to wait before calling the `callback` function. Set `delay` to
+`0` to call the callback as soon as possible.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/13/image.md b/cobalt/site/docs/reference/starboard/modules/13/image.md
index 3050953..1427d39 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/image.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/image.md
@@ -24,7 +24,7 @@
   return;
 }
 
-SbDecodeTarget result_target = SbDecodeImage(provider, data, data_size,
+SbDecodeTarget result_target = SbImageDecode(provider, data, data_size,
                                              mime_type, format);
 ```
 
@@ -48,13 +48,13 @@
     called, and the implementation will proceed to decoding however it desires.
 
 1.  The provider is not required and is not passed in. The implementation will
-    proceed forward.
-
-Thus, it is NOT safe for clients of this API to assume that the `provider` it
-passes in will be called. Finally, if the decode succeeds, a new SbDecodeTarget
-will be allocated. If `mime_type` image decoding for the requested format is not
-supported or the decode fails, kSbDecodeTargetInvalid will be returned, with any
-intermediate allocations being cleaned up in the implementation.
+    proceed forward. The `data` pointer must not be NULL. The `mime_type` string
+    must not be NULL. Thus, it is NOT safe for clients of this API to assume
+    that the `provider` it passes in will be called. Finally, if the decode
+    succeeds, a new SbDecodeTarget will be allocated. If `mime_type` image
+    decoding for the requested format is not supported or the decode fails,
+    kSbDecodeTargetInvalid will be returned, with any intermediate allocations
+    being cleaned up in the implementation.
 
 #### Declaration ####
 
@@ -65,9 +65,10 @@
 ### SbImageIsDecodeSupported ###
 
 Whether the current platform supports hardware accelerated decoding an image of
-mime type `mime_type` into SbDecodeTargetFormat `format`. The result of this
-function must not change over the course of the program, which means that the
-results of this function may be cached indefinitely.
+mime type `mime_type` into SbDecodeTargetFormat `format`. The `mime_type` must
+not be NULL. The result of this function must not change over the course of the
+program, which means that the results of this function may be cached
+indefinitely.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/13/log.md b/cobalt/site/docs/reference/starboard/modules/13/log.md
index 1ad6c24..42de513 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/log.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/log.md
@@ -30,10 +30,10 @@
 `priority`: The SbLogPriority at which the message should be logged. Note that
 passing `kSbLogPriorityFatal` does not terminate the program. Such a policy must
 be enforced at the application level. In fact, `priority` may be completely
-ignored on many platforms. `message`: The message to be logged. No formatting is
-required to be done on the value, including newline termination. That said,
-platforms can adjust the message to be more suitable for their output method by
-wrapping the text, stripping unprintable characters, etc.
+ignored on many platforms. `message`: The message to be logged. Must not be
+NULL. No formatting is required to be done on the value, including newline
+termination. That said, platforms can adjust the message to be more suitable for
+their output method by wrapping the text, stripping unprintable characters, etc.
 
 #### Declaration ####
 
@@ -70,7 +70,7 @@
 #### Declaration ####
 
 ```
-void static void void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
 
 ### SbLogIsTty ###
@@ -89,7 +89,7 @@
 an asynchronous signal handler (e.g. a `SIGSEGV` handler). It should not do any
 additional formatting.
 
-`message`: The message to be logged.
+`message`: The message to be logged. Must not be NULL.
 
 #### Declaration ####
 
@@ -132,6 +132,5 @@
 #### Declaration ####
 
 ```
-void static void void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/player.md b/cobalt/site/docs/reference/starboard/modules/13/player.md
index d6910e2..3fd955d 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/player.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/player.md
@@ -231,7 +231,7 @@
 
 ### SbPlayerSampleInfo ###
 
-Information about the samples to be written into SbPlayerWriteSample2.
+Information about the samples to be written into SbPlayerWriteSamples().
 
 #### Members ####
 
@@ -297,7 +297,7 @@
 
 *   It is not allowed to pass `player` into any other `SbPlayer` function once
     SbPlayerDestroy has been called on that player. `player`: The player to be
-    destroyed.
+    destroyed. Must not be `kSbPlayerInvalid`.
 
 #### Declaration ####
 
@@ -315,26 +315,14 @@
 with an output mode other than kSbPlayerOutputModeDecodeToTexture,
 kSbDecodeTargetInvalid is returned.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
 SbDecodeTarget SbPlayerGetCurrentFrame(SbPlayer player)
 ```
 
-### SbPlayerGetInfo2 ###
-
-Gets a snapshot of the current player state and writes it to `out_player_info`.
-This function may be called very frequently and is expected to be inexpensive.
-
-`player`: The player about which information is being retrieved.
-`out_player_info`: The information retrieved for the player.
-
-#### Declaration ####
-
-```
-void SbPlayerGetInfo2(SbPlayer player, SbPlayerInfo2 *out_player_info2)
-```
-
 ### SbPlayerGetMaximumNumberOfSamplesPerWrite ###
 
 Writes a single sample of the given media type to `player`'s input stream. Its
@@ -371,7 +359,7 @@
 the call. Note that it is not the responsibility of this function to verify
 whether the video described by `creation_param` can be played on the platform,
 and the implementation should try its best effort to return a valid output mode.
-`creation_param` will never be NULL.
+`creation_param` must not be NULL.
 
 #### Declaration ####
 
@@ -403,12 +391,12 @@
 implementors should take care to avoid related performance concerns with such
 frequent calls.
 
-`player`: The player that is being resized. `z_index`: The z-index of the
-player. When the bounds of multiple players are overlapped, the one with larger
-z-index will be rendered on top of the ones with smaller z-index. `x`: The
-x-coordinate of the upper-left corner of the player. `y`: The y-coordinate of
-the upper-left corner of the player. `width`: The width of the player, in
-pixels. `height`: The height of the player, in pixels.
+`player`: The player that is being resized. Must not be `kSbPlayerInvalid`.
+`z_index`: The z-index of the player. When the bounds of multiple players are
+overlapped, the one with larger z-index will be rendered on top of the ones with
+smaller z-index. `x`: The x-coordinate of the upper-left corner of the player.
+`y`: The y-coordinate of the upper-left corner of the player. `width`: The width
+of the player, in pixels. `height`: The height of the player, in pixels.
 
 #### Declaration ####
 
@@ -429,6 +417,8 @@
 unchanged, this can happen when `playback_rate` is negative or if it is too high
 to support.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
@@ -439,10 +429,10 @@
 
 Sets the player's volume.
 
-`player`: The player in which the volume is being adjusted. `volume`: The new
-player volume. The value must be between `0.0` and `1.0`, inclusive. A value of
-`0.0` means that the audio should be muted, and a value of `1.0` means that it
-should be played at full volume.
+`player`: The player in which the volume is being adjusted. Must not be
+`kSbPlayerInvalid`. `volume`: The new player volume. The value must be between
+`0.0` and `1.0`, inclusive. A value of `0.0` means that the audio should be
+muted, and a value of `1.0` means that it should be played at full volume.
 
 #### Declaration ####
 
@@ -468,24 +458,14 @@
 
 ### SbPlayerWriteSample2 ###
 
-Writes samples of the given media type to `player`'s input stream. The lifetime
-of `sample_infos`, and the members of its elements like `buffer`,
-`video_sample_info`, and `drm_info` (as well as member `subsample_mapping`
-contained inside it) are not guaranteed past the call to SbPlayerWriteSample2.
-That means that before returning, the implementation must synchronously copy any
-information it wants to retain from those structures.
-
-SbPlayerWriteSample2 allows writing of multiple samples in one call.
-
-`player`: The player to which the sample is written. `sample_type`: The type of
-sample being written. See the `SbMediaType` enum in media.h. `sample_infos`: A
-pointer to an array of SbPlayerSampleInfo with `number_of_sample_infos`
-elements, each holds the data for an sample, i.e. a sequence of whole NAL Units
-for video, or a complete audio frame. `sample_infos` cannot be assumed to live
-past the call into SbPlayerWriteSample2(), so it must be copied if its content
-will be used after SbPlayerWriteSample2() returns. `number_of_sample_infos`:
-Specify the number of samples contained inside `sample_infos`. It has to be at
-least one, and less than the return value of
+`sample_type`: The type of sample being written. See the `SbMediaType` enum in
+media.h. `sample_infos`: A pointer to an array of SbPlayerSampleInfo with
+`number_of_sample_infos` elements, each holds the data for an sample, i.e. a
+sequence of whole NAL Units for video, or a complete audio frame. `sample_infos`
+cannot be assumed to live past the call into SbPlayerWriteSamples(), so it must
+be copied if its content will be used after SbPlayerWriteSamples() returns.
+`number_of_sample_infos`: Specify the number of samples contained inside
+`sample_infos`. It has to be at least one, and less than the return value of
 SbPlayerGetMaximumNumberOfSamplesPerWrite().
 
 #### Declaration ####
@@ -493,4 +473,3 @@
 ```
 void SbPlayerWriteSample2(SbPlayer player, SbMediaType sample_type, const SbPlayerSampleInfo *sample_infos, int number_of_sample_infos)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/socket.md b/cobalt/site/docs/reference/starboard/modules/13/socket.md
index 548f57d..9e0f81b 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/socket.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/socket.md
@@ -417,8 +417,8 @@
 the address is unnecessary, but allowed.
 
 `socket`: The SbSocket from which data is read. `out_data`: The data read from
-the socket. `data_size`: The number of bytes to read. `out_source`: The source
-address of the packet.
+the socket. Must not be NULL. `data_size`: The number of bytes to read.
+`out_source`: The source address of the packet.
 
 #### Declaration ####
 
@@ -456,10 +456,10 @@
 SbSocketGetLastError returns `kSbSocketPending` to make it a best-effort write
 (but still only up to not blocking, unless you want to spin).
 
-`socket`: The SbSocket to use to write data. `data`: The data read from the
-socket. `data_size`: The number of bytes of `data` to write. `destination`: The
-location to which data is written. This value must be `NULL` for TCP
-connections, which can only have a single endpoint.
+`socket`: The SbSocket to use to write data. `data`: The data written to the
+socket. Must not be NULL. `data_size`: The number of bytes of `data` to write.
+`destination`: The location to which data is written. This value must be `NULL`
+for TCP connections, which can only have a single endpoint.
 
 The primary use of `destination` is to send datagram packets, which can go out
 to multiple sources from a single UDP server socket. TCP has two endpoints
@@ -583,4 +583,3 @@
 ```
 bool SbSocketSetTcpWindowScaling(SbSocket socket, bool value)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/speech_recognizer.md b/cobalt/site/docs/reference/starboard/modules/13/speech_recognizer.md
index 0a1dc6b..2a40f19 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/speech_recognizer.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/speech_recognizer.md
@@ -266,4 +266,3 @@
 ```
 void SbSpeechRecognizerStop(SbSpeechRecognizer recognizer)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/13/system.md b/cobalt/site/docs/reference/starboard/modules/13/system.md
index dd71ecf..b02dc01 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/system.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/system.md
@@ -114,9 +114,10 @@
     Full path to the executable file.
 *   `kSbSystemPathStorageDirectory`
 
-    Path to a directory for permanent file storage. Both read and write access
-    is required. This is where an app may store its persistent settings. The
-    location should be user agnostic if possible.
+    Path to the directory dedicated for Evergreen Full permanent file storage.
+    Both read and write access is required. The directory should be used only
+    for storing the updates. See
+    starboard/doc/evergreen/cobalt_evergreen_overview.md
 
 ### SbSystemPlatformErrorResponse ###
 
@@ -301,7 +302,8 @@
 ### SbSystemGetExtension ###
 
 Returns pointer to a constant global struct implementing the extension named
-`name`, if it is implemented. Otherwise return NULL.
+`name`, if it is implemented. Otherwise return NULL. The `name` string must not
+be NULL.
 
 Extensions are used to implement behavior which is specific to the combination
 of application & platform. An extension relies on a header file in the
@@ -684,7 +686,7 @@
 ### SbSystemSignWithCertificationSecretKey ###
 
 Computes a HMAC-SHA256 digest of `message` into `digest` using the application's
-certification secret.
+certification secret. The `message` and the `digest` pointers must not be NULL.
 
 The output will be written into `digest`. `digest_size_in_bytes` must be 32 (or
 greater), since 32-bytes will be written into it. Returns false in the case of
diff --git a/cobalt/site/docs/reference/starboard/modules/13/ui_navigation.md b/cobalt/site/docs/reference/starboard/modules/13/ui_navigation.md
index e5f533b..a0ecfb1 100644
--- a/cobalt/site/docs/reference/starboard/modules/13/ui_navigation.md
+++ b/cobalt/site/docs/reference/starboard/modules/13/ui_navigation.md
@@ -101,8 +101,10 @@
     This is used to manually force focus on a navigation item of type
     kSbUiNavItemTypeFocus. Any previously focused navigation item should receive
     the blur event. If the item is not transitively a content of the root item,
-    then this does nothing. Specifying kSbUiNavItemInvalid should remove focus
-    from the UI navigation system.
+    then this does nothing.
+
+    Specifying kSbUiNavItemInvalid should remove focus from the UI navigation
+    system.
 *   `void(*set_item_enabled)(SbUiNavItem item, bool enabled)`
 
     This is used to enable or disable user interaction with the specified
@@ -116,7 +118,9 @@
 
     This specifies directionality for container items. Containers within
     containers do not inherit directionality. Directionality must be specified
-    for each container explicitly. This should work even if `item` is disabled.
+    for each container explicitly.
+
+    This should work even if `item` is disabled.
 *   `void(*set_item_focus_duration)(SbUiNavItem item, float seconds)`
 
     Set the minimum amount of time the focus item should remain focused once it
@@ -158,13 +162,16 @@
 
     This attaches the given navigation item (which must be a container) to the
     specified window. Navigation items are only interactable if they are
-    transitively attached to a window.The native UI engine should never change
-    this navigation item's content offset. It is assumed to be used as a proxy
-    for the system window.A navigation item may only have a SbUiNavItem or
-    SbWindow as its direct container. The navigation item hierarchy is
-    established using set_item_container_item() with the root container attached
-    to a SbWindow using set_item_container_window() to enable interaction with
-    all enabled items in the hierarchy.
+    transitively attached to a window.
+
+    The native UI engine should never change this navigation item's content
+    offset. It is assumed to be used as a proxy for the system window.
+
+    A navigation item may only have a SbUiNavItem or SbWindow as its direct
+    container. The navigation item hierarchy is established using
+    set_item_container_item() with the root container attached to a SbWindow
+    using set_item_container_window() to enable interaction with all enabled
+    items in the hierarchy.
 
     If `item` is already registered with a different window, then this will
     unregister it from that window then attach it to the given `window`. It is
@@ -195,13 +202,14 @@
     drawn at position (5,15).
 
     Essentially, content items should be drawn at: [container position] +
-    [content position] - [container content offset] Content items may overlap
-    within a container. This can cause obscured items to be unfocusable. The
-    only rule that needs to be followed is that contents which are focus items
-    can obscure other contents which are containers, but not vice versa. The
-    caller must ensure that content focus items do not overlap other content
-    focus items and content container items do not overlap other content
-    container items.
+    [content position] - [container content offset]
+
+    Content items may overlap within a container. This can cause obscured items
+    to be unfocusable. The only rule that needs to be followed is that contents
+    which are focus items can obscure other contents which are containers, but
+    not vice versa. The caller must ensure that content focus items do not
+    overlap other content focus items and content container items do not overlap
+    other content container items.
 *   `void(*set_item_content_offset)(SbUiNavItem item, float content_offset_x,
     float content_offset_y)`
 
@@ -211,17 +219,19 @@
     Essentially, a content item should be drawn at: [container position] +
     [content position] - [container content offset] If `item` is not a
     container, then this does nothing. By default, the content offset is (0,0).
+
     This should update the values returned by get_item_content_offset() even if
     the `item` is disabled.
 *   `void(*get_item_content_offset)(SbUiNavItem item, float
     *out_content_offset_x, float *out_content_offset_y)`
 
     Retrieve the current content offset for the navigation item. If `item` is
-    not a container, then the content offset is (0,0). The native UI engine
-    should not change the content offset of a container unless one of its
-    contents (possibly recursively) is focused. This is to allow seamlessly
-    disabling then re-enabling focus items without having their containers
-    change offsets.
+    not a container, then the content offset is (0,0).
+
+    The native UI engine should not change the content offset of a container
+    unless one of its contents (possibly recursively) is focused. This is to
+    allow seamlessly disabling then re-enabling focus items without having their
+    containers change offsets.
 *   `void(*do_batch_update)(void(*update_function)(void *), void *context)`
 
     Call `update_function` with `context` to perform a series of UI navigation
@@ -252,7 +262,7 @@
 ///     | Negative position. | Positive position. | Positive position. |
 ///     +--------------------+--------------------+--------------------+
 ///                          ^
-///                  Content Offset X = 0. 
+///                  Content Offset X = 0.
 ```
 
 ```
@@ -271,7 +281,7 @@
 
 ```
 ///   | a b tx |
-///   | c d ty | 
+///   | c d ty |
 ```
 
 #### Members ####
@@ -292,7 +302,8 @@
 
 Retrieve the platform's UI navigation implementation. If the platform does not
 provide one, then return false without modifying `out_interface`. Otherwise,
-initialize all members of `out_interface` and return true.
+initialize all members of `out_interface` and return true. The `out_interface`
+pointer must not be NULL.
 
 #### Declaration ####
 
@@ -309,4 +320,3 @@
 ```
 static bool SbUiNavItemIsValid(SbUiNavItem item)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/14/audio_sink.md b/cobalt/site/docs/reference/starboard/modules/14/audio_sink.md
index 3b3789a..b0e652f 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/audio_sink.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/audio_sink.md
@@ -72,6 +72,53 @@
 
 ## Functions ##
 
+### SbAudioSinkCreate ###
+
+Creates an audio sink for the specified `channels` and `sampling_frequency_hz`,
+acquires all resources needed to operate the audio sink, and returns an opaque
+handle to the audio sink.
+
+If the particular platform doesn't support the requested audio sink, the
+function returns `kSbAudioSinkInvalid` without calling any of the callbacks. If
+there is a platform limitation on how many audio sinks can coexist
+simultaneously, then calls made to this function that attempt to exceed that
+limit must return `kSbAudioSinkInvalid`. Multiple calls to SbAudioSinkCreate
+must not cause a crash.
+
+`channels`: The number of audio channels, such as left and right channels in
+stereo audio. `sampling_frequency_hz`: The sample frequency of the audio data
+being streamed. For example, 22,000 Hz means 22,000 sample elements represents
+one second of audio data. `audio_sample_type`: The type of each sample of the
+audio data – `int16`, `float32`, etc. `audio_frame_storage_type`: Indicates
+whether frames are interleaved or planar. `frame_buffers`: An array of pointers
+to sample data.
+
+*   If the sink is operating in interleaved mode, the array contains only one
+    element, which is an array containing (`frames_per_channel` * `channels`)
+    samples.
+
+*   If the sink is operating in planar mode, the number of elements in the array
+    is the same as `channels`, and each element is an array of
+    `frames_per_channel` samples. The caller has to ensure that `frame_buffers`
+    is valid until SbAudioSinkDestroy is called. `frames_per_channel`: The size
+    of the frame buffers, in units of the number of samples per channel. The
+    frame, in this case, represents a group of samples at the same media time,
+    one for each channel. `update_source_status_func`: The audio sink calls this
+    function on an internal thread to query the status of the source. It is
+    called immediately after SbAudioSinkCreate is called, even before it
+    returns. The caller has to ensure that the callback functions above return
+    meaningful values in this case. The value cannot be NULL.
+    `consume_frames_func`: The audio sink calls this function on an internal
+    thread to report consumed frames. The value cannot be NULL. `context`: A
+    value that is passed back to all callbacks and is generally used to point at
+    a class or struct that contains state associated with the audio sink.
+
+#### Declaration ####
+
+```
+SbAudioSink SbAudioSinkCreate(int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, SbMediaAudioFrameStorageType audio_frame_storage_type, SbAudioSinkFrameBuffers frame_buffers, int frames_per_channel, SbAudioSinkUpdateSourceStatusFunc update_source_status_func, SbAudioSinkConsumeFramesFunc consume_frames_func, void *context)
+```
+
 ### SbAudioSinkDestroy ###
 
 Destroys `audio_sink`, freeing all associated resources. Before returning, the
diff --git a/cobalt/site/docs/reference/starboard/modules/14/decode_target.md b/cobalt/site/docs/reference/starboard/modules/14/decode_target.md
index 0e912d5..a237ad9 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/decode_target.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/decode_target.md
@@ -332,8 +332,10 @@
 
 ### SbDecodeTargetGetInfo ###
 
-Writes all information about `decode_target` into `out_info`. Returns false if
-the provided `out_info` structure is not zero initialized.
+Writes all information about `decode_target` into `out_info`. The
+`decode_target` must not be kSbDecodeTargetInvalid. The `out_info` pointer must
+not be NULL. Returns false if the provided `out_info` structure is not zero
+initialized.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/14/drm.md b/cobalt/site/docs/reference/starboard/modules/14/drm.md
index c7f487e..fbb92f9 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/drm.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/drm.md
@@ -238,6 +238,8 @@
 
 Clear any internal states/resources related to the specified `session_id`.
 
+`drm_system` must not be `kSbDrmSystemInvalid`. `session_id` must not be NULL.
+
 #### Declaration ####
 
 ```
@@ -254,7 +256,7 @@
 result, if this function is called from a callback that is passed to
 SbDrmCreateSystem(), a deadlock will occur.
 
-`drm_system`: The DRM system to be destroyed.
+`drm_system`: The DRM system to be destroyed. Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -281,7 +283,7 @@
 
 `drm_system`: The DRM system that defines the key system used for the session
 update request payload as well as the callback function that is called as a
-result of the function being called.
+result of the function being called. Must not be `kSbDrmSystemInvalid`.
 
 `ticket`: The opaque ID that allows to distinguish callbacks from multiple
 concurrent calls to SbDrmGenerateSessionUpdateRequest(), which will be passed to
@@ -289,10 +291,10 @@
 establish ticket uniqueness, issuing multiple requests with the same ticket may
 result in undefined behavior. The value `kSbDrmTicketInvalid` must not be used.
 
-`type`: The case-sensitive type of the session update request payload.
-`initialization_data`: The data for which the session update request payload is
-created. `initialization_data_size`: The size of the session update request
-payload.
+`type`: The case-sensitive type of the session update request payload. Must not
+be NULL. `initialization_data`: The data for which the session update request
+payload is created. Must not be NULL. `initialization_data_size`: The size of
+the session update request payload.
 
 #### Declaration ####
 
@@ -322,7 +324,7 @@
 It should return NULL when there is no metrics support in the underlying drm
 system, or when the drm system implementation fails to retrieve the metrics.
 
-The caller will never set `size` to NULL.
+`drm_system` must not be `kSbDrmSystemInvalid`. `size` must not be NULL.
 
 #### Declaration ####
 
@@ -337,6 +339,7 @@
 the life time of `drm_system`.
 
 `drm_system`: The DRM system to check if its server certificate is updatable.
+Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -371,14 +374,15 @@
 a previous call is called. Note that this function should only be called after
 `SbDrmIsServerCertificateUpdatable` is called first and returned true.
 
-`drm_system`: The DRM system whose server certificate is being updated.
-`ticket`: The opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateServerCertificate(), which will be passed to
-`server_certificate_updated_callback` as-is. It is the responsibility of the
-caller to establish ticket uniqueness, issuing multiple requests with the same
-ticket may result in undefined behavior. The value `kSbDrmTicketInvalid` must
-not be used. `certificate`: Pointer to the server certificate data.
-`certificate_size`: Size of the server certificate data.
+`drm_system`: The DRM system whose server certificate is being updated. Must not
+be `kSbDrmSystemInvalid`. `ticket`: The opaque ID that allows to distinguish
+callbacks from multiple concurrent calls to SbDrmUpdateServerCertificate(),
+which will be passed to `server_certificate_updated_callback` as-is. It is the
+responsibility of the caller to establish ticket uniqueness, issuing multiple
+requests with the same ticket may result in undefined behavior. The value
+`kSbDrmTicketInvalid` must not be used. `certificate`: Pointer to the server
+certificate data. Must not be NULL. `certificate_size`: Size of the server
+certificate data.
 
 #### Declaration ####
 
@@ -391,18 +395,20 @@
 Update session with `key`, in `drm_system`'s key system, from the license server
 response. Calls `session_updated_callback` with `context` and whether the update
 succeeded. `context` may be used to route callbacks back to an object instance.
+The `key` must not be NULL.
 
-`ticket` is the opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateSession(), which will be passed to
-`session_updated_callback` as-is. It is the responsibility of the caller to
-establish ticket uniqueness, issuing multiple calls with the same ticket may
-result in undefined behavior.
+`drm_system` must not be `kSbDrmSystemInvalid`. `ticket` is the opaque ID that
+allows to distinguish callbacks from multiple concurrent calls to
+SbDrmUpdateSession(), which will be passed to `session_updated_callback` as-is.
+It is the responsibility of the caller to establish ticket uniqueness, issuing
+multiple calls with the same ticket may result in undefined behavior.
 
 Once the session is successfully updated, an SbPlayer or SbDecoder associated
 with that DRM key system will be able to decrypt encrypted samples.
 
 `drm_system`'s `session_updated_callback` may called either from the current
-thread before this function returns or from another thread.
+thread before this function returns or from another thread. The `session_id`
+must not be NULL.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/14/event.md b/cobalt/site/docs/reference/starboard/modules/14/event.md
index 8d20c6f..01a9d24 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/event.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/event.md
@@ -3,10 +3,6 @@
 title: "Starboard Module Reference: event.h"
 ---
 
-For SB_API_VERSION >= 13
-
-Module Overview: Starboard Event module
-
 Defines the event system that wraps the Starboard main loop and entry point.
 
 ## The Starboard Application Lifecycle ##
@@ -82,75 +78,6 @@
 Note that the application is always expected to transition through `BLURRED`,
 `CONCEALED` to `FROZEN` before receiving `Stop` or being killed.
 
-For SB_API_VERSION < 13
-
-Module Overview: Starboard Event module
-
-Defines the event system that wraps the Starboard main loop and entry point.
-
-## The Starboard Application Lifecycle ##
-
-```
-    ---------- *
-   |           |
-   |        Preload
-   |           |
-   |           V
- Start   [ PRELOADING ] ------------
-   |           |                    |
-   |         Start                  |
-   |           |                    |
-   |           V                    |
-    ----> [ STARTED ] <----         |
-               |           |        |
-             Pause       Unpause    |
-               |           |     Suspend
-               V           |        |
-    -----> [ PAUSED ] -----         |
-   |           |                    |
-Resume      Suspend                 |
-   |           |                    |
-   |           V                    |
-    ---- [ SUSPENDED ] <------------
-               |
-              Stop
-               |
-               V
-          [ STOPPED ]
-
-```
-
-The first event that a Starboard application receives is either `Start`
-(`kSbEventTypeStart`) or `Preload` (`kSbEventTypePreload`). `Start` puts the
-application in the `STARTED` state, whereas `Preload` puts the application in
-the `PRELOADING` state.
-
-`PRELOADING` can only happen as the first application state. In this state, the
-application should start and run as normal, but will not receive any input, and
-should not try to initialize graphics resources via GL. In `PRELOADING`, the
-application can receive `Start` or `Suspend` events. `Start` will receive the
-same data that was passed into `Preload`.
-
-In the `STARTED` state, the application is in the foreground and can expect to
-do all of the normal things it might want to do. Once in the `STARTED` state, it
-may receive a `Pause` event, putting the application into the `PAUSED` state.
-
-In the `PAUSED` state, the application is still visible, but has lost focus, or
-it is partially obscured by a modal dialog, or it is on its way to being shut
-down. The application should pause activity in this state. In this state, it can
-receive `Unpause` to be brought back to the foreground state (`STARTED`), or
-`Suspend` to be pushed further in the background to the `SUSPENDED` state.
-
-In the `SUSPENDED` state, the application is generally not visible. It should
-immediately release all graphics and video resources, and shut down all
-background activity (timers, rendering, etc). Additionally, the application
-should flush storage to ensure that if the application is killed, the storage
-will be up-to-date. The application may be killed at this point, but will
-ideally receive a `Stop` event for a more graceful shutdown.
-
-Note that the application is always expected to transition through `PAUSED` to
-`SUSPENDED` before receiving `Stop` or being killed.
-
 ## Enums ##
 
 ### SbEventType ###
@@ -465,10 +392,10 @@
 may be called from any thread, but `callback` is always called from the main
 Starboard thread, queued with other pending events.
 
-`callback`: The callback function to be called. `context`: The context that is
-passed to the `callback` function. `delay`: The minimum number of microseconds
-to wait before calling the `callback` function. Set `delay` to `0` to call the
-callback as soon as possible.
+`callback`: The callback function to be called. Must not be NULL. `context`: The
+context that is passed to the `callback` function. `delay`: The minimum number
+of microseconds to wait before calling the `callback` function. Set `delay` to
+`0` to call the callback as soon as possible.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/14/image.md b/cobalt/site/docs/reference/starboard/modules/14/image.md
index 3050953..1427d39 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/image.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/image.md
@@ -24,7 +24,7 @@
   return;
 }
 
-SbDecodeTarget result_target = SbDecodeImage(provider, data, data_size,
+SbDecodeTarget result_target = SbImageDecode(provider, data, data_size,
                                              mime_type, format);
 ```
 
@@ -48,13 +48,13 @@
     called, and the implementation will proceed to decoding however it desires.
 
 1.  The provider is not required and is not passed in. The implementation will
-    proceed forward.
-
-Thus, it is NOT safe for clients of this API to assume that the `provider` it
-passes in will be called. Finally, if the decode succeeds, a new SbDecodeTarget
-will be allocated. If `mime_type` image decoding for the requested format is not
-supported or the decode fails, kSbDecodeTargetInvalid will be returned, with any
-intermediate allocations being cleaned up in the implementation.
+    proceed forward. The `data` pointer must not be NULL. The `mime_type` string
+    must not be NULL. Thus, it is NOT safe for clients of this API to assume
+    that the `provider` it passes in will be called. Finally, if the decode
+    succeeds, a new SbDecodeTarget will be allocated. If `mime_type` image
+    decoding for the requested format is not supported or the decode fails,
+    kSbDecodeTargetInvalid will be returned, with any intermediate allocations
+    being cleaned up in the implementation.
 
 #### Declaration ####
 
@@ -65,9 +65,10 @@
 ### SbImageIsDecodeSupported ###
 
 Whether the current platform supports hardware accelerated decoding an image of
-mime type `mime_type` into SbDecodeTargetFormat `format`. The result of this
-function must not change over the course of the program, which means that the
-results of this function may be cached indefinitely.
+mime type `mime_type` into SbDecodeTargetFormat `format`. The `mime_type` must
+not be NULL. The result of this function must not change over the course of the
+program, which means that the results of this function may be cached
+indefinitely.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/14/log.md b/cobalt/site/docs/reference/starboard/modules/14/log.md
index 7edfe19..42de513 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/log.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/log.md
@@ -30,10 +30,10 @@
 `priority`: The SbLogPriority at which the message should be logged. Note that
 passing `kSbLogPriorityFatal` does not terminate the program. Such a policy must
 be enforced at the application level. In fact, `priority` may be completely
-ignored on many platforms. `message`: The message to be logged. No formatting is
-required to be done on the value, including newline termination. That said,
-platforms can adjust the message to be more suitable for their output method by
-wrapping the text, stripping unprintable characters, etc.
+ignored on many platforms. `message`: The message to be logged. Must not be
+NULL. No formatting is required to be done on the value, including newline
+termination. That said, platforms can adjust the message to be more suitable for
+their output method by wrapping the text, stripping unprintable characters, etc.
 
 #### Declaration ####
 
@@ -70,7 +70,7 @@
 #### Declaration ####
 
 ```
-void static void void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
 
 ### SbLogIsTty ###
@@ -89,7 +89,7 @@
 an asynchronous signal handler (e.g. a `SIGSEGV` handler). It should not do any
 additional formatting.
 
-`message`: The message to be logged.
+`message`: The message to be logged. Must not be NULL.
 
 #### Declaration ####
 
@@ -132,5 +132,5 @@
 #### Declaration ####
 
 ```
-void static void void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
diff --git a/cobalt/site/docs/reference/starboard/modules/14/player.md b/cobalt/site/docs/reference/starboard/modules/14/player.md
index 7acb9ae..3fd955d 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/player.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/player.md
@@ -231,7 +231,7 @@
 
 ### SbPlayerSampleInfo ###
 
-Information about the samples to be written into SbPlayerWriteSample2.
+Information about the samples to be written into SbPlayerWriteSamples().
 
 #### Members ####
 
@@ -297,7 +297,7 @@
 
 *   It is not allowed to pass `player` into any other `SbPlayer` function once
     SbPlayerDestroy has been called on that player. `player`: The player to be
-    destroyed.
+    destroyed. Must not be `kSbPlayerInvalid`.
 
 #### Declaration ####
 
@@ -315,26 +315,14 @@
 with an output mode other than kSbPlayerOutputModeDecodeToTexture,
 kSbDecodeTargetInvalid is returned.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
 SbDecodeTarget SbPlayerGetCurrentFrame(SbPlayer player)
 ```
 
-### SbPlayerGetInfo2 ###
-
-Gets a snapshot of the current player state and writes it to `out_player_info`.
-This function may be called very frequently and is expected to be inexpensive.
-
-`player`: The player about which information is being retrieved.
-`out_player_info`: The information retrieved for the player.
-
-#### Declaration ####
-
-```
-void SbPlayerGetInfo2(SbPlayer player, SbPlayerInfo2 *out_player_info2)
-```
-
 ### SbPlayerGetMaximumNumberOfSamplesPerWrite ###
 
 Writes a single sample of the given media type to `player`'s input stream. Its
@@ -371,7 +359,7 @@
 the call. Note that it is not the responsibility of this function to verify
 whether the video described by `creation_param` can be played on the platform,
 and the implementation should try its best effort to return a valid output mode.
-`creation_param` will never be NULL.
+`creation_param` must not be NULL.
 
 #### Declaration ####
 
@@ -403,12 +391,12 @@
 implementors should take care to avoid related performance concerns with such
 frequent calls.
 
-`player`: The player that is being resized. `z_index`: The z-index of the
-player. When the bounds of multiple players are overlapped, the one with larger
-z-index will be rendered on top of the ones with smaller z-index. `x`: The
-x-coordinate of the upper-left corner of the player. `y`: The y-coordinate of
-the upper-left corner of the player. `width`: The width of the player, in
-pixels. `height`: The height of the player, in pixels.
+`player`: The player that is being resized. Must not be `kSbPlayerInvalid`.
+`z_index`: The z-index of the player. When the bounds of multiple players are
+overlapped, the one with larger z-index will be rendered on top of the ones with
+smaller z-index. `x`: The x-coordinate of the upper-left corner of the player.
+`y`: The y-coordinate of the upper-left corner of the player. `width`: The width
+of the player, in pixels. `height`: The height of the player, in pixels.
 
 #### Declaration ####
 
@@ -429,6 +417,8 @@
 unchanged, this can happen when `playback_rate` is negative or if it is too high
 to support.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
@@ -439,10 +429,10 @@
 
 Sets the player's volume.
 
-`player`: The player in which the volume is being adjusted. `volume`: The new
-player volume. The value must be between `0.0` and `1.0`, inclusive. A value of
-`0.0` means that the audio should be muted, and a value of `1.0` means that it
-should be played at full volume.
+`player`: The player in which the volume is being adjusted. Must not be
+`kSbPlayerInvalid`. `volume`: The new player volume. The value must be between
+`0.0` and `1.0`, inclusive. A value of `0.0` means that the audio should be
+muted, and a value of `1.0` means that it should be played at full volume.
 
 #### Declaration ####
 
@@ -468,24 +458,14 @@
 
 ### SbPlayerWriteSample2 ###
 
-Writes samples of the given media type to `player`'s input stream. The lifetime
-of `sample_infos`, and the members of its elements like `buffer`,
-`video_sample_info`, and `drm_info` (as well as member `subsample_mapping`
-contained inside it) are not guaranteed past the call to SbPlayerWriteSample2.
-That means that before returning, the implementation must synchronously copy any
-information it wants to retain from those structures.
-
-SbPlayerWriteSample2 allows writing of multiple samples in one call.
-
-`player`: The player to which the sample is written. `sample_type`: The type of
-sample being written. See the `SbMediaType` enum in media.h. `sample_infos`: A
-pointer to an array of SbPlayerSampleInfo with `number_of_sample_infos`
-elements, each holds the data for an sample, i.e. a sequence of whole NAL Units
-for video, or a complete audio frame. `sample_infos` cannot be assumed to live
-past the call into SbPlayerWriteSample2(), so it must be copied if its content
-will be used after SbPlayerWriteSample2() returns. `number_of_sample_infos`:
-Specify the number of samples contained inside `sample_infos`. It has to be at
-least one, and less than the return value of
+`sample_type`: The type of sample being written. See the `SbMediaType` enum in
+media.h. `sample_infos`: A pointer to an array of SbPlayerSampleInfo with
+`number_of_sample_infos` elements, each holds the data for an sample, i.e. a
+sequence of whole NAL Units for video, or a complete audio frame. `sample_infos`
+cannot be assumed to live past the call into SbPlayerWriteSamples(), so it must
+be copied if its content will be used after SbPlayerWriteSamples() returns.
+`number_of_sample_infos`: Specify the number of samples contained inside
+`sample_infos`. It has to be at least one, and less than the return value of
 SbPlayerGetMaximumNumberOfSamplesPerWrite().
 
 #### Declaration ####
diff --git a/cobalt/site/docs/reference/starboard/modules/14/socket.md b/cobalt/site/docs/reference/starboard/modules/14/socket.md
index d30bc22..9e0f81b 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/socket.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/socket.md
@@ -417,8 +417,8 @@
 the address is unnecessary, but allowed.
 
 `socket`: The SbSocket from which data is read. `out_data`: The data read from
-the socket. `data_size`: The number of bytes to read. `out_source`: The source
-address of the packet.
+the socket. Must not be NULL. `data_size`: The number of bytes to read.
+`out_source`: The source address of the packet.
 
 #### Declaration ####
 
@@ -456,10 +456,10 @@
 SbSocketGetLastError returns `kSbSocketPending` to make it a best-effort write
 (but still only up to not blocking, unless you want to spin).
 
-`socket`: The SbSocket to use to write data. `data`: The data read from the
-socket. `data_size`: The number of bytes of `data` to write. `destination`: The
-location to which data is written. This value must be `NULL` for TCP
-connections, which can only have a single endpoint.
+`socket`: The SbSocket to use to write data. `data`: The data written to the
+socket. Must not be NULL. `data_size`: The number of bytes of `data` to write.
+`destination`: The location to which data is written. This value must be `NULL`
+for TCP connections, which can only have a single endpoint.
 
 The primary use of `destination` is to send datagram packets, which can go out
 to multiple sources from a single UDP server socket. TCP has two endpoints
diff --git a/cobalt/site/docs/reference/starboard/modules/14/system.md b/cobalt/site/docs/reference/starboard/modules/14/system.md
index b4800a6..5e4e076 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/system.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/system.md
@@ -98,9 +98,10 @@
     Full path to the executable file.
 *   `kSbSystemPathStorageDirectory`
 
-    Path to a directory for permanent file storage. Both read and write access
-    is required. This is where an app may store its persistent settings. The
-    location should be user agnostic if possible.
+    Path to the directory dedicated for Evergreen Full permanent file storage.
+    Both read and write access is required. The directory should be used only
+    for storing the updates. See
+    starboard/doc/evergreen/cobalt_evergreen_overview.md
 
 ### SbSystemPlatformErrorResponse ###
 
@@ -284,7 +285,8 @@
 ### SbSystemGetExtension ###
 
 Returns pointer to a constant global struct implementing the extension named
-`name`, if it is implemented. Otherwise return NULL.
+`name`, if it is implemented. Otherwise return NULL. The `name` string must not
+be NULL.
 
 Extensions are used to implement behavior which is specific to the combination
 of application & platform. An extension relies on a header file in the
@@ -667,7 +669,7 @@
 ### SbSystemSignWithCertificationSecretKey ###
 
 Computes a HMAC-SHA256 digest of `message` into `digest` using the application's
-certification secret.
+certification secret. The `message` and the `digest` pointers must not be NULL.
 
 The output will be written into `digest`. `digest_size_in_bytes` must be 32 (or
 greater), since 32-bytes will be written into it. Returns false in the case of
diff --git a/cobalt/site/docs/reference/starboard/modules/14/ui_navigation.md b/cobalt/site/docs/reference/starboard/modules/14/ui_navigation.md
index d868c64..a0ecfb1 100644
--- a/cobalt/site/docs/reference/starboard/modules/14/ui_navigation.md
+++ b/cobalt/site/docs/reference/starboard/modules/14/ui_navigation.md
@@ -101,8 +101,10 @@
     This is used to manually force focus on a navigation item of type
     kSbUiNavItemTypeFocus. Any previously focused navigation item should receive
     the blur event. If the item is not transitively a content of the root item,
-    then this does nothing. Specifying kSbUiNavItemInvalid should remove focus
-    from the UI navigation system.
+    then this does nothing.
+
+    Specifying kSbUiNavItemInvalid should remove focus from the UI navigation
+    system.
 *   `void(*set_item_enabled)(SbUiNavItem item, bool enabled)`
 
     This is used to enable or disable user interaction with the specified
@@ -116,7 +118,9 @@
 
     This specifies directionality for container items. Containers within
     containers do not inherit directionality. Directionality must be specified
-    for each container explicitly. This should work even if `item` is disabled.
+    for each container explicitly.
+
+    This should work even if `item` is disabled.
 *   `void(*set_item_focus_duration)(SbUiNavItem item, float seconds)`
 
     Set the minimum amount of time the focus item should remain focused once it
@@ -158,13 +162,16 @@
 
     This attaches the given navigation item (which must be a container) to the
     specified window. Navigation items are only interactable if they are
-    transitively attached to a window.The native UI engine should never change
-    this navigation item's content offset. It is assumed to be used as a proxy
-    for the system window.A navigation item may only have a SbUiNavItem or
-    SbWindow as its direct container. The navigation item hierarchy is
-    established using set_item_container_item() with the root container attached
-    to a SbWindow using set_item_container_window() to enable interaction with
-    all enabled items in the hierarchy.
+    transitively attached to a window.
+
+    The native UI engine should never change this navigation item's content
+    offset. It is assumed to be used as a proxy for the system window.
+
+    A navigation item may only have a SbUiNavItem or SbWindow as its direct
+    container. The navigation item hierarchy is established using
+    set_item_container_item() with the root container attached to a SbWindow
+    using set_item_container_window() to enable interaction with all enabled
+    items in the hierarchy.
 
     If `item` is already registered with a different window, then this will
     unregister it from that window then attach it to the given `window`. It is
@@ -195,13 +202,14 @@
     drawn at position (5,15).
 
     Essentially, content items should be drawn at: [container position] +
-    [content position] - [container content offset] Content items may overlap
-    within a container. This can cause obscured items to be unfocusable. The
-    only rule that needs to be followed is that contents which are focus items
-    can obscure other contents which are containers, but not vice versa. The
-    caller must ensure that content focus items do not overlap other content
-    focus items and content container items do not overlap other content
-    container items.
+    [content position] - [container content offset]
+
+    Content items may overlap within a container. This can cause obscured items
+    to be unfocusable. The only rule that needs to be followed is that contents
+    which are focus items can obscure other contents which are containers, but
+    not vice versa. The caller must ensure that content focus items do not
+    overlap other content focus items and content container items do not overlap
+    other content container items.
 *   `void(*set_item_content_offset)(SbUiNavItem item, float content_offset_x,
     float content_offset_y)`
 
@@ -211,17 +219,19 @@
     Essentially, a content item should be drawn at: [container position] +
     [content position] - [container content offset] If `item` is not a
     container, then this does nothing. By default, the content offset is (0,0).
+
     This should update the values returned by get_item_content_offset() even if
     the `item` is disabled.
 *   `void(*get_item_content_offset)(SbUiNavItem item, float
     *out_content_offset_x, float *out_content_offset_y)`
 
     Retrieve the current content offset for the navigation item. If `item` is
-    not a container, then the content offset is (0,0). The native UI engine
-    should not change the content offset of a container unless one of its
-    contents (possibly recursively) is focused. This is to allow seamlessly
-    disabling then re-enabling focus items without having their containers
-    change offsets.
+    not a container, then the content offset is (0,0).
+
+    The native UI engine should not change the content offset of a container
+    unless one of its contents (possibly recursively) is focused. This is to
+    allow seamlessly disabling then re-enabling focus items without having their
+    containers change offsets.
 *   `void(*do_batch_update)(void(*update_function)(void *), void *context)`
 
     Call `update_function` with `context` to perform a series of UI navigation
@@ -292,7 +302,8 @@
 
 Retrieve the platform's UI navigation implementation. If the platform does not
 provide one, then return false without modifying `out_interface`. Otherwise,
-initialize all members of `out_interface` and return true.
+initialize all members of `out_interface` and return true. The `out_interface`
+pointer must not be NULL.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/12/accessibility.md b/cobalt/site/docs/reference/starboard/modules/15/accessibility.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/accessibility.md
rename to cobalt/site/docs/reference/starboard/modules/15/accessibility.md
index a6c8460..1a5adcb 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/accessibility.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/accessibility.md
@@ -251,4 +251,3 @@
 ```
 bool SbAccessibilitySetCaptionsEnabled(bool enabled)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/atomic.md b/cobalt/site/docs/reference/starboard/modules/15/atomic.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/atomic.md
rename to cobalt/site/docs/reference/starboard/modules/15/atomic.md
index 5f79990..9741f3c 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/atomic.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/atomic.md
@@ -108,4 +108,3 @@
 ```
 static SbAtomic8 SbAtomicRelease_CompareAndSwap8(volatile SbAtomic8 *ptr, SbAtomic8 old_value, SbAtomic8 new_value)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/audio_sink.md b/cobalt/site/docs/reference/starboard/modules/15/audio_sink.md
similarity index 64%
rename from cobalt/site/docs/reference/starboard/modules/12/audio_sink.md
rename to cobalt/site/docs/reference/starboard/modules/15/audio_sink.md
index 8cf2329..b0e652f 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/audio_sink.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/audio_sink.md
@@ -72,6 +72,53 @@
 
 ## Functions ##
 
+### SbAudioSinkCreate ###
+
+Creates an audio sink for the specified `channels` and `sampling_frequency_hz`,
+acquires all resources needed to operate the audio sink, and returns an opaque
+handle to the audio sink.
+
+If the particular platform doesn't support the requested audio sink, the
+function returns `kSbAudioSinkInvalid` without calling any of the callbacks. If
+there is a platform limitation on how many audio sinks can coexist
+simultaneously, then calls made to this function that attempt to exceed that
+limit must return `kSbAudioSinkInvalid`. Multiple calls to SbAudioSinkCreate
+must not cause a crash.
+
+`channels`: The number of audio channels, such as left and right channels in
+stereo audio. `sampling_frequency_hz`: The sample frequency of the audio data
+being streamed. For example, 22,000 Hz means 22,000 sample elements represents
+one second of audio data. `audio_sample_type`: The type of each sample of the
+audio data – `int16`, `float32`, etc. `audio_frame_storage_type`: Indicates
+whether frames are interleaved or planar. `frame_buffers`: An array of pointers
+to sample data.
+
+*   If the sink is operating in interleaved mode, the array contains only one
+    element, which is an array containing (`frames_per_channel` * `channels`)
+    samples.
+
+*   If the sink is operating in planar mode, the number of elements in the array
+    is the same as `channels`, and each element is an array of
+    `frames_per_channel` samples. The caller has to ensure that `frame_buffers`
+    is valid until SbAudioSinkDestroy is called. `frames_per_channel`: The size
+    of the frame buffers, in units of the number of samples per channel. The
+    frame, in this case, represents a group of samples at the same media time,
+    one for each channel. `update_source_status_func`: The audio sink calls this
+    function on an internal thread to query the status of the source. It is
+    called immediately after SbAudioSinkCreate is called, even before it
+    returns. The caller has to ensure that the callback functions above return
+    meaningful values in this case. The value cannot be NULL.
+    `consume_frames_func`: The audio sink calls this function on an internal
+    thread to report consumed frames. The value cannot be NULL. `context`: A
+    value that is passed back to all callbacks and is generally used to point at
+    a class or struct that contains state associated with the audio sink.
+
+#### Declaration ####
+
+```
+SbAudioSink SbAudioSinkCreate(int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, SbMediaAudioFrameStorageType audio_frame_storage_type, SbAudioSinkFrameBuffers frame_buffers, int frames_per_channel, SbAudioSinkUpdateSourceStatusFunc update_source_status_func, SbAudioSinkConsumeFramesFunc consume_frames_func, void *context)
+```
+
 ### SbAudioSinkDestroy ###
 
 Destroys `audio_sink`, freeing all associated resources. Before returning, the
@@ -165,4 +212,3 @@
 ```
 bool SbAudioSinkIsValid(SbAudioSink audio_sink)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/byte_swap.md b/cobalt/site/docs/reference/starboard/modules/15/byte_swap.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/byte_swap.md
rename to cobalt/site/docs/reference/starboard/modules/15/byte_swap.md
index 580bc5d..c83927d 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/byte_swap.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/byte_swap.md
@@ -73,4 +73,3 @@
 ```
 uint64_t SbByteSwapU64(uint64_t value)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/condition_variable.md b/cobalt/site/docs/reference/starboard/modules/15/condition_variable.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/condition_variable.md
rename to cobalt/site/docs/reference/starboard/modules/15/condition_variable.md
index 836c4b8..e58e106 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/condition_variable.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/condition_variable.md
@@ -138,4 +138,3 @@
 ```
 SbConditionVariableResult SbConditionVariableWaitTimed(SbConditionVariable *condition, SbMutex *mutex, SbTime timeout_duration)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/configuration.md b/cobalt/site/docs/reference/starboard/modules/15/configuration.md
similarity index 96%
rename from cobalt/site/docs/reference/starboard/modules/12/configuration.md
rename to cobalt/site/docs/reference/starboard/modules/15/configuration.md
index 0cb5c19..630f1cf 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/configuration.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/configuration.md
@@ -53,11 +53,6 @@
 SB_DEPRECATED_EXTERNAL(...) annotates the function as deprecated for external
 clients, but not deprecated for starboard.
 
-### SB_DISALLOW_COPY_AND_ASSIGN(TypeName) ###
-
-A macro to disallow the copy constructor and operator= functions This should be
-used in the private: declarations for a class
-
 ### SB_EXPERIMENTAL_API_VERSION ###
 
 The API version that is currently open for changes, and therefore is not stable
diff --git a/cobalt/site/docs/reference/starboard/modules/12/configuration_constants.md b/cobalt/site/docs/reference/starboard/modules/15/configuration_constants.md
similarity index 97%
rename from cobalt/site/docs/reference/starboard/modules/12/configuration_constants.md
rename to cobalt/site/docs/reference/starboard/modules/15/configuration_constants.md
index b380f62..99d92f8 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/configuration_constants.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/configuration_constants.md
@@ -50,10 +50,6 @@
 
 The string form of SB_FILE_SEP_CHAR.
 
-### kSbHasAc3Audio ###
-
-Allow ac3 and ec3 support
-
 ### kSbHasMediaWebmVp9Support ###
 
 Specifies whether this platform has webm/vp9 support. This should be set to non-
@@ -67,6 +63,10 @@
 
 Determines the alignment that allocations should have on this platform.
 
+### kSbMaxSystemPathCacheDirectorySize ###
+
+The maximum size the cache directory is allowed to use in bytes.
+
 ### kSbMaxThreadLocalKeys ###
 
 The maximum number of thread local storage keys supported by this platform. This
diff --git a/cobalt/site/docs/reference/starboard/modules/12/cpu_features.md b/cobalt/site/docs/reference/starboard/modules/15/cpu_features.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/cpu_features.md
rename to cobalt/site/docs/reference/starboard/modules/15/cpu_features.md
index e939881..7a4bcc0 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/cpu_features.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/cpu_features.md
@@ -87,6 +87,9 @@
 *   `bool has_vfp3`
 
     VFP version 3
+*   `bool has_vfp4`
+
+    VFP version 4
 *   `bool has_vfp3_d32`
 
     VFP version 3 with 32 D-registers.
@@ -256,4 +259,3 @@
 ```
 bool SbCPUFeaturesGet(SbCPUFeatures *features)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/decode_target.md b/cobalt/site/docs/reference/starboard/modules/15/decode_target.md
similarity index 96%
rename from cobalt/site/docs/reference/starboard/modules/12/decode_target.md
rename to cobalt/site/docs/reference/starboard/modules/15/decode_target.md
index 2e61c1e..a237ad9 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/decode_target.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/decode_target.md
@@ -117,6 +117,11 @@
 
     A decoder target format consisting of 10bit Y, U, and V planes, in that
     order. Each pixel is stored in 16 bits.
+*   `kSbDecodeTargetFormat3Plane10BitYUVI420Compact`
+
+    A decoder target format consisting of 10bit Y, U, and V planes, in that
+    order. The plane data is stored in a compact format. Every three 10-bit
+    pixels are packed into 32 bits.
 *   `kSbDecodeTargetFormat1PlaneUYVY`
 
     A decoder target format consisting of a single plane with pixels laid out in
@@ -327,8 +332,10 @@
 
 ### SbDecodeTargetGetInfo ###
 
-Writes all information about `decode_target` into `out_info`. Returns false if
-the provided `out_info` structure is not zero initialized.
+Writes all information about `decode_target` into `out_info`. The
+`decode_target` must not be kSbDecodeTargetInvalid. The `out_info` pointer must
+not be NULL. Returns false if the provided `out_info` structure is not zero
+initialized.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/12/directory.md b/cobalt/site/docs/reference/starboard/modules/15/directory.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/directory.md
rename to cobalt/site/docs/reference/starboard/modules/15/directory.md
index d46c9a1..dcdf48a 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/directory.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/directory.md
@@ -115,4 +115,3 @@
 ```
 SbDirectory SbDirectoryOpen(const char *path, SbFileError *out_error)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/drm.md b/cobalt/site/docs/reference/starboard/modules/15/drm.md
similarity index 88%
rename from cobalt/site/docs/reference/starboard/modules/12/drm.md
rename to cobalt/site/docs/reference/starboard/modules/15/drm.md
index beb65c9..fbb92f9 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/drm.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/drm.md
@@ -238,6 +238,8 @@
 
 Clear any internal states/resources related to the specified `session_id`.
 
+`drm_system` must not be `kSbDrmSystemInvalid`. `session_id` must not be NULL.
+
 #### Declaration ####
 
 ```
@@ -254,7 +256,7 @@
 result, if this function is called from a callback that is passed to
 SbDrmCreateSystem(), a deadlock will occur.
 
-`drm_system`: The DRM system to be destroyed.
+`drm_system`: The DRM system to be destroyed. Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -281,7 +283,7 @@
 
 `drm_system`: The DRM system that defines the key system used for the session
 update request payload as well as the callback function that is called as a
-result of the function being called.
+result of the function being called. Must not be `kSbDrmSystemInvalid`.
 
 `ticket`: The opaque ID that allows to distinguish callbacks from multiple
 concurrent calls to SbDrmGenerateSessionUpdateRequest(), which will be passed to
@@ -289,10 +291,10 @@
 establish ticket uniqueness, issuing multiple requests with the same ticket may
 result in undefined behavior. The value `kSbDrmTicketInvalid` must not be used.
 
-`type`: The case-sensitive type of the session update request payload.
-`initialization_data`: The data for which the session update request payload is
-created. `initialization_data_size`: The size of the session update request
-payload.
+`type`: The case-sensitive type of the session update request payload. Must not
+be NULL. `initialization_data`: The data for which the session update request
+payload is created. Must not be NULL. `initialization_data_size`: The size of
+the session update request payload.
 
 #### Declaration ####
 
@@ -322,7 +324,7 @@
 It should return NULL when there is no metrics support in the underlying drm
 system, or when the drm system implementation fails to retrieve the metrics.
 
-The caller will never set `size` to NULL.
+`drm_system` must not be `kSbDrmSystemInvalid`. `size` must not be NULL.
 
 #### Declaration ####
 
@@ -337,6 +339,7 @@
 the life time of `drm_system`.
 
 `drm_system`: The DRM system to check if its server certificate is updatable.
+Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -371,14 +374,15 @@
 a previous call is called. Note that this function should only be called after
 `SbDrmIsServerCertificateUpdatable` is called first and returned true.
 
-`drm_system`: The DRM system whose server certificate is being updated.
-`ticket`: The opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateServerCertificate(), which will be passed to
-`server_certificate_updated_callback` as-is. It is the responsibility of the
-caller to establish ticket uniqueness, issuing multiple requests with the same
-ticket may result in undefined behavior. The value `kSbDrmTicketInvalid` must
-not be used. `certificate`: Pointer to the server certificate data.
-`certificate_size`: Size of the server certificate data.
+`drm_system`: The DRM system whose server certificate is being updated. Must not
+be `kSbDrmSystemInvalid`. `ticket`: The opaque ID that allows to distinguish
+callbacks from multiple concurrent calls to SbDrmUpdateServerCertificate(),
+which will be passed to `server_certificate_updated_callback` as-is. It is the
+responsibility of the caller to establish ticket uniqueness, issuing multiple
+requests with the same ticket may result in undefined behavior. The value
+`kSbDrmTicketInvalid` must not be used. `certificate`: Pointer to the server
+certificate data. Must not be NULL. `certificate_size`: Size of the server
+certificate data.
 
 #### Declaration ####
 
@@ -391,22 +395,23 @@
 Update session with `key`, in `drm_system`'s key system, from the license server
 response. Calls `session_updated_callback` with `context` and whether the update
 succeeded. `context` may be used to route callbacks back to an object instance.
+The `key` must not be NULL.
 
-`ticket` is the opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateSession(), which will be passed to
-`session_updated_callback` as-is. It is the responsibility of the caller to
-establish ticket uniqueness, issuing multiple calls with the same ticket may
-result in undefined behavior.
+`drm_system` must not be `kSbDrmSystemInvalid`. `ticket` is the opaque ID that
+allows to distinguish callbacks from multiple concurrent calls to
+SbDrmUpdateSession(), which will be passed to `session_updated_callback` as-is.
+It is the responsibility of the caller to establish ticket uniqueness, issuing
+multiple calls with the same ticket may result in undefined behavior.
 
 Once the session is successfully updated, an SbPlayer or SbDecoder associated
 with that DRM key system will be able to decrypt encrypted samples.
 
 `drm_system`'s `session_updated_callback` may called either from the current
-thread before this function returns or from another thread.
+thread before this function returns or from another thread. The `session_id`
+must not be NULL.
 
 #### Declaration ####
 
 ```
 void SbDrmUpdateSession(SbDrmSystem drm_system, int ticket, const void *key, int key_size, const void *session_id, int session_id_size)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/egl.md b/cobalt/site/docs/reference/starboard/modules/15/egl.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/egl.md
rename to cobalt/site/docs/reference/starboard/modules/15/egl.md
index b1e120b..c8c2120 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/egl.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/egl.md
@@ -144,4 +144,3 @@
     config, void *native_pixmap, const SbEglAttrib *attrib_list)`
 *   `SbEglBoolean(*eglWaitSync)(SbEglDisplay dpy, SbEglSync sync, SbEglInt32
     flags)`
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/event.md b/cobalt/site/docs/reference/starboard/modules/15/event.md
similarity index 67%
rename from cobalt/site/docs/reference/starboard/modules/12/event.md
rename to cobalt/site/docs/reference/starboard/modules/15/event.md
index cd85db6..58cb1f4 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/event.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/event.md
@@ -3,10 +3,6 @@
 title: "Starboard Module Reference: event.h"
 ---
 
-For SB_API_VERSION >= 13
-
-Module Overview: Starboard Event module
-
 Defines the event system that wraps the Starboard main loop and entry point.
 
 ## The Starboard Application Lifecycle ##
@@ -82,75 +78,6 @@
 Note that the application is always expected to transition through `BLURRED`,
 `CONCEALED` to `FROZEN` before receiving `Stop` or being killed.
 
-For SB_API_VERSION < 13
-
-Module Overview: Starboard Event module
-
-Defines the event system that wraps the Starboard main loop and entry point.
-
-## The Starboard Application Lifecycle ##
-
-```
-    ---------- *
-   |           |
-   |        Preload
-   |           |
-   |           V
- Start   [ PRELOADING ] ------------
-   |           |                    |
-   |         Start                  |
-   |           |                    |
-   |           V                    |
-    ----> [ STARTED ] <----         |
-               |           |        |
-             Pause       Unpause    |
-               |           |     Suspend
-               V           |        |
-    -----> [ PAUSED ] -----         |
-   |           |                    |
-Resume      Suspend                 |
-   |           |                    |
-   |           V                    |
-    ---- [ SUSPENDED ] <------------
-               |
-              Stop
-               |
-               V
-          [ STOPPED ]
-
-```
-
-The first event that a Starboard application receives is either `Start`
-(`kSbEventTypeStart`) or `Preload` (`kSbEventTypePreload`). `Start` puts the
-application in the `STARTED` state, whereas `Preload` puts the application in
-the `PRELOADING` state.
-
-`PRELOADING` can only happen as the first application state. In this state, the
-application should start and run as normal, but will not receive any input, and
-should not try to initialize graphics resources via GL. In `PRELOADING`, the
-application can receive `Start` or `Suspend` events. `Start` will receive the
-same data that was passed into `Preload`.
-
-In the `STARTED` state, the application is in the foreground and can expect to
-do all of the normal things it might want to do. Once in the `STARTED` state, it
-may receive a `Pause` event, putting the application into the `PAUSED` state.
-
-In the `PAUSED` state, the application is still visible, but has lost focus, or
-it is partially obscured by a modal dialog, or it is on its way to being shut
-down. The application should pause activity in this state. In this state, it can
-receive `Unpause` to be brought back to the foreground state (`STARTED`), or
-`Suspend` to be pushed further in the background to the `SUSPENDED` state.
-
-In the `SUSPENDED` state, the application is generally not visible. It should
-immediately release all graphics and video resources, and shut down all
-background activity (timers, rendering, etc). Additionally, the application
-should flush storage to ensure that if the application is killed, the storage
-will be up-to-date. The application may be killed at this point, but will
-ideally receive a `Stop` event for a more graceful shutdown.
-
-Note that the application is always expected to transition through `PAUSED` to
-`SUSPENDED` before receiving `Stop` or being killed.
-
 ## Enums ##
 
 ### SbEventType ###
@@ -163,65 +90,68 @@
 
 *   `kSbEventTypePreload`
 
-    Applications should perform initialization and prepare to react to
-    subsequent events, but must not initialize any graphics resources through
-    GL. The intent of this event is to allow the application to do as much work
-    as possible ahead of time, so that when the application is first brought to
-    the foreground, it's as fast as a resume.
-
-    The `kSbEventTypeStart` event may be sent at any time, regardless of
-    initialization state. Input events will not be sent in the `PRELOADING`
-    state. This event will only be sent once for a given process launch.
-    SbEventStartData is passed as the data argument.
-
-    The system may send `kSbEventTypeSuspend` in `PRELOADING` if it wants to
-    push the app into a lower resource consumption state. Applications can also
-    call SbSystemRequestSuspend() when they are done preloading to request this.
+    The system may send `kSbEventTypePreload` in `UNSTARTED` if it wants to push
+    the app into a lower resource consumption state. Applications will also call
+    SbSystemRequestConceal() when they request this. The only events that should
+    be dispatched after a Preload event are Reveal or Freeze. No data argument.
 *   `kSbEventTypeStart`
 
     The first event that an application receives on startup when starting
-    normally (i.e. not being preloaded). Applications should perform
-    initialization, start running, and prepare to react to subsequent events.
-    Applications that wish to run and then exit must call
-    `SbSystemRequestStop()` to terminate. This event will only be sent once for
-    a given process launch. `SbEventStartData` is passed as the data argument.
-    In case of preload, the `SbEventStartData` will be the same as what was
-    passed to `kSbEventTypePreload`.
-*   `kSbEventTypePause`
+    normally. Applications should perform initialization, start running, and
+    prepare to react to subsequent events. Applications that wish to run and
+    then exit must call `SbSystemRequestStop()` to terminate. This event will
+    only be sent once for a given process launch. `SbEventStartData` is passed
+    as the data argument.
+*   `kSbEventTypeBlur`
 
     A dialog will be raised or the application will otherwise be put into a
-    background-but-visible or partially-obscured state (PAUSED). Graphics and
-    video resources will still be available, but the application should pause
+    background-but-visible or partially-obscured state (BLURRED). Graphics and
+    video resources will still be available, but the application could pause
     foreground activity like animations and video playback. Can only be received
-    after a Start event. The only events that should be dispatched after a Pause
-    event are Unpause or Suspend. No data argument.
-*   `kSbEventTypeUnpause`
+    after a Start event. The only events that should be dispatched after a Blur
+    event are Focus or Conceal. No data argument.
+*   `kSbEventTypeFocus`
 
     The application is returning to the foreground (STARTED) after having been
-    put in the PAUSED (e.g. partially-obscured) state. The application should
-    unpause foreground activity like animations and video playback. Can only be
-    received after a Pause or Resume event. No data argument.
-*   `kSbEventTypeSuspend`
+    put in the BLURRED (e.g. partially-obscured) state. The application should
+    resume foreground activity like animations and video playback. Can only be
+    received after a Blur or Reveal event. No data argument.
+*   `kSbEventTypeConceal`
 
-    The operating system will put the application into a Suspended state after
+    The operating system will put the application into the Concealed state after
+    this event is handled. The application is expected to be made invisible, but
+    background tasks can still be running, such as audio playback, or updating
+    of recommendations. Can only be received after a Blur or Reveal event. The
+    only events that should be dispatched after a Conceal event are Freeze or
+    Reveal. On some platforms, the process may also be killed after Conceal
+    without a Freeze event.
+*   `kSbEventTypeReveal`
+
+    The operating system will restore the application to the BLURRED state from
+    the CONCEALED state. This is the first event the application will receive
+    coming out of CONCEALED, and it can be received after a Conceal or Unfreeze
+    event. The application will now be in the BLURRED state. No data argument.
+*   `kSbEventTypeFreeze`
+
+    The operating system will put the application into the Frozen state after
     this event is handled. The application is expected to stop periodic
     background work, release ALL graphics and video resources, and flush any
     pending SbStorage writes. Some platforms will terminate the application if
-    work is done or resources are retained after suspension. Can only be
-    received after a Pause event. The only events that should be dispatched
-    after a Suspend event are Resume or Stop. On some platforms, the process may
-    also be killed after Suspend without a Stop event. No data argument.
-*   `kSbEventTypeResume`
+    work is done or resources are retained after freezing. Can be received after
+    a Conceal or Unfreeze event. The only events that should be dispatched after
+    a Freeze event are Unfreeze or Stop. On some platforms, the process may also
+    be killed after Freeze without a Stop event. No data argument.
+*   `kSbEventTypeUnfreeze`
 
-    The operating system has restored the application to the PAUSED state from
-    the SUSPENDED state. This is the first event the application will receive
-    coming out of SUSPENDED, and it will only be received after a Suspend event.
-    The application will now be in the PAUSED state. No data argument.
+    The operating system has restored the application to the CONCEALED state
+    from the FROZEN state. This is the first event the application will receive
+    coming out of FROZEN, and it will only be received after a Freeze event. The
+    application will now be in the CONCEALED state. NO data argument.
 *   `kSbEventTypeStop`
 
     The operating system will shut the application down entirely after this
-    event is handled. Can only be received after a Suspend event, in the
-    SUSPENDED state. No data argument.
+    event is handled. Can only be received after a Freeze event, in the FROZEN
+    state. No data argument.
 *   `kSbEventTypeInput`
 
     A user input event, including keyboard, mouse, gesture, or something else.
@@ -249,7 +179,7 @@
     response to an application call to SbEventSchedule(), and it will call the
     callback directly, so SbEventHandle should never receive this event
     directly. The data type is an internally-defined structure.
-*   `kSbEventTypeAccessiblitySettingsChanged`
+*   `kSbEventTypeAccessibilitySettingsChanged`
 
     The platform's accessibility settings have changed. The application should
     query the accessibility settings using the appropriate APIs to get the new
@@ -321,9 +251,27 @@
 
     One or more of the fields returned by SbAccessibilityGetCaptionSettings has
     changed.
-*   `kSbEventTypeAccessiblityTextToSpeechSettingsChanged`
+*   `kSbEventTypeAccessibilityTextToSpeechSettingsChanged`
 
     The platform's text-to-speech settings have changed.
+*   `kSbEventTypeOsNetworkDisconnected`
+
+    The platform has detected a network disconnection. There are likely to be
+    cases where the platform cannot detect the disconnection but the platform
+    should make a best effort to send an event of this type when the network
+    disconnects. This event is used to implement window.onoffline DOM event.
+*   `kSbEventTypeOsNetworkConnected`
+
+    The platform has detected a network connection. There are likely to be cases
+    where the platform cannot detect the connection but the platform should make
+    a best effort to send an event of this type when the device is just
+    connected to the internet. This event is used to implement window.ononline
+    DOM event.
+*   `kSbEventDateTimeConfigurationChanged`
+
+    The platform has detected a date and/or time configuration change (such as a
+    change in the timezone setting). This should trigger the application to re-
+    query the relevant APIs to update the date and time.
 
 ## Typedefs ##
 
@@ -366,6 +314,7 @@
 #### Members ####
 
 *   `SbEventType type`
+*   `SbTimeMonotonic timestamp`
 *   `void * data`
 
 ### SbEventStartData ###
@@ -424,7 +373,7 @@
 #### Declaration ####
 
 ```
-SB_IMPORT void SbEventHandle(const SbEvent *event)
+SB_EXPORT_PLATFORM void SbEventHandle(const SbEvent *event)
 ```
 
 ### SbEventIsIdValid ###
@@ -443,13 +392,24 @@
 may be called from any thread, but `callback` is always called from the main
 Starboard thread, queued with other pending events.
 
-`callback`: The callback function to be called. `context`: The context that is
-passed to the `callback` function. `delay`: The minimum number of microseconds
-to wait before calling the `callback` function. Set `delay` to `0` to call the
-callback as soon as possible.
+`callback`: The callback function to be called. Must not be NULL. `context`: The
+context that is passed to the `callback` function. `delay`: The minimum number
+of microseconds to wait before calling the `callback` function. Set `delay` to
+`0` to call the callback as soon as possible.
 
 #### Declaration ####
 
 ```
 SbEventId SbEventSchedule(SbEventCallback callback, void *context, SbTime delay)
 ```
+
+### SbRunStarboardMain ###
+
+Serves as the entry point in the Starboard library for running the Starboard
+event loop with the application event handler.
+
+#### Declaration ####
+
+```
+int SbRunStarboardMain(int argc, char **argv, SbEventHandleCallback callback)
+```
diff --git a/cobalt/site/docs/reference/starboard/modules/12/export.md b/cobalt/site/docs/reference/starboard/modules/15/export.md
similarity index 100%
rename from cobalt/site/docs/reference/starboard/modules/12/export.md
rename to cobalt/site/docs/reference/starboard/modules/15/export.md
diff --git a/cobalt/site/docs/reference/starboard/modules/12/file.md b/cobalt/site/docs/reference/starboard/modules/15/file.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/file.md
rename to cobalt/site/docs/reference/starboard/modules/15/file.md
index e22edeb..56eb415 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/file.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/file.md
@@ -402,4 +402,3 @@
 ```
 static int SbFileWriteAll(SbFile file, const char *data, int size)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/gles.md b/cobalt/site/docs/reference/starboard/modules/15/gles.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/gles.md
rename to cobalt/site/docs/reference/starboard/modules/15/gles.md
index 7a9108a..163d8d7 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/gles.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/gles.md
@@ -459,4 +459,3 @@
     internalformat, SbGlSizei width, SbGlSizei height, SbGlSizei depth)`
 *   `void(*glGetInternalformativ)(SbGlEnum target, SbGlEnum internalformat,
     SbGlEnum pname, SbGlSizei bufSize, SbGlInt32 *params)`
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/image.md b/cobalt/site/docs/reference/starboard/modules/15/image.md
similarity index 73%
rename from cobalt/site/docs/reference/starboard/modules/12/image.md
rename to cobalt/site/docs/reference/starboard/modules/15/image.md
index 3050953..1427d39 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/image.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/image.md
@@ -24,7 +24,7 @@
   return;
 }
 
-SbDecodeTarget result_target = SbDecodeImage(provider, data, data_size,
+SbDecodeTarget result_target = SbImageDecode(provider, data, data_size,
                                              mime_type, format);
 ```
 
@@ -48,13 +48,13 @@
     called, and the implementation will proceed to decoding however it desires.
 
 1.  The provider is not required and is not passed in. The implementation will
-    proceed forward.
-
-Thus, it is NOT safe for clients of this API to assume that the `provider` it
-passes in will be called. Finally, if the decode succeeds, a new SbDecodeTarget
-will be allocated. If `mime_type` image decoding for the requested format is not
-supported or the decode fails, kSbDecodeTargetInvalid will be returned, with any
-intermediate allocations being cleaned up in the implementation.
+    proceed forward. The `data` pointer must not be NULL. The `mime_type` string
+    must not be NULL. Thus, it is NOT safe for clients of this API to assume
+    that the `provider` it passes in will be called. Finally, if the decode
+    succeeds, a new SbDecodeTarget will be allocated. If `mime_type` image
+    decoding for the requested format is not supported or the decode fails,
+    kSbDecodeTargetInvalid will be returned, with any intermediate allocations
+    being cleaned up in the implementation.
 
 #### Declaration ####
 
@@ -65,9 +65,10 @@
 ### SbImageIsDecodeSupported ###
 
 Whether the current platform supports hardware accelerated decoding an image of
-mime type `mime_type` into SbDecodeTargetFormat `format`. The result of this
-function must not change over the course of the program, which means that the
-results of this function may be cached indefinitely.
+mime type `mime_type` into SbDecodeTargetFormat `format`. The `mime_type` must
+not be NULL. The result of this function must not change over the course of the
+program, which means that the results of this function may be cached
+indefinitely.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/12/input.md b/cobalt/site/docs/reference/starboard/modules/15/input.md
similarity index 93%
rename from cobalt/site/docs/reference/starboard/modules/12/input.md
rename to cobalt/site/docs/reference/starboard/modules/15/input.md
index 3554af6..ec86793 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/input.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/input.md
@@ -94,13 +94,6 @@
 
 #### Members ####
 
-*   `SbTimeMonotonic timestamp`
-
-    The time that should be reported for this event. This is intended to
-    facilitate calculation of time-sensitive information (e.g. velocity for
-    kSbInputEventTypeMove). This may be set to 0 to have the relevant systems
-    automatically set the timestamp. However, this may happen at a later time,
-    so the relative time between events may not be preserved.
 *   `SbWindow window`
 
     The window in which the input was generated.
@@ -175,4 +168,3 @@
 
 *   `float x`
 *   `float y`
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/key.md b/cobalt/site/docs/reference/starboard/modules/15/key.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/key.md
rename to cobalt/site/docs/reference/starboard/modules/15/key.md
index 16be3c1..2835b20 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/key.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/key.md
@@ -196,6 +196,7 @@
 *   `kSbKeyGreen`
 *   `kSbKeyYellow`
 *   `kSbKeyBlue`
+*   `kSbKeyRecord`
 *   `kSbKeyChannelUp`
 *   `kSbKeyChannelDown`
 *   `kSbKeySubtitle`
@@ -290,4 +291,3 @@
 *   `kSbKeyModifiersPointerButtonMiddle`
 *   `kSbKeyModifiersPointerButtonBack`
 *   `kSbKeyModifiersPointerButtonForward`
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/log.md b/cobalt/site/docs/reference/starboard/modules/15/log.md
similarity index 85%
rename from cobalt/site/docs/reference/starboard/modules/12/log.md
rename to cobalt/site/docs/reference/starboard/modules/15/log.md
index 1ad6c24..42de513 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/log.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/log.md
@@ -30,10 +30,10 @@
 `priority`: The SbLogPriority at which the message should be logged. Note that
 passing `kSbLogPriorityFatal` does not terminate the program. Such a policy must
 be enforced at the application level. In fact, `priority` may be completely
-ignored on many platforms. `message`: The message to be logged. No formatting is
-required to be done on the value, including newline termination. That said,
-platforms can adjust the message to be more suitable for their output method by
-wrapping the text, stripping unprintable characters, etc.
+ignored on many platforms. `message`: The message to be logged. Must not be
+NULL. No formatting is required to be done on the value, including newline
+termination. That said, platforms can adjust the message to be more suitable for
+their output method by wrapping the text, stripping unprintable characters, etc.
 
 #### Declaration ####
 
@@ -70,7 +70,7 @@
 #### Declaration ####
 
 ```
-void static void void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
 
 ### SbLogIsTty ###
@@ -89,7 +89,7 @@
 an asynchronous signal handler (e.g. a `SIGSEGV` handler). It should not do any
 additional formatting.
 
-`message`: The message to be logged.
+`message`: The message to be logged. Must not be NULL.
 
 #### Declaration ####
 
@@ -132,6 +132,5 @@
 #### Declaration ####
 
 ```
-void static void void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/media.md b/cobalt/site/docs/reference/starboard/modules/15/media.md
similarity index 89%
rename from cobalt/site/docs/reference/starboard/modules/12/media.md
rename to cobalt/site/docs/reference/starboard/modules/15/media.md
index a9baced..132166c 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/media.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/media.md
@@ -30,6 +30,10 @@
 *   `kSbMediaAudioCodecEac3`
 *   `kSbMediaAudioCodecOpus`
 *   `kSbMediaAudioCodecVorbis`
+*   `kSbMediaAudioCodecMp3`
+*   `kSbMediaAudioCodecFlac`
+*   `kSbMediaAudioCodecPcm`
+*   `kSbMediaAudioCodecIamf`
 
 ### SbMediaAudioCodingType ###
 
@@ -55,11 +59,20 @@
 
 #### Values ####
 
-*   `kSbMediaAudioConnectorNone`
+*   `kSbMediaAudioConnectorUnknown`
 *   `kSbMediaAudioConnectorAnalog`
 *   `kSbMediaAudioConnectorBluetooth`
+*   `kSbMediaAudioConnectorBuiltIn`
 *   `kSbMediaAudioConnectorHdmi`
-*   `kSbMediaAudioConnectorNetwork`
+*   `kSbMediaAudioConnectorRemoteWired`
+
+    A wired remote audio output, like a remote speaker via Ethernet.
+*   `kSbMediaAudioConnectorRemoteWireless`
+
+    A wireless remote audio output, like a remote speaker via Wi-Fi.
+*   `kSbMediaAudioConnectorRemoteOther`
+
+    A remote audio output cannot be classified into other existing types.
 *   `kSbMediaAudioConnectorSpdif`
 *   `kSbMediaAudioConnectorUsb`
 
@@ -170,13 +183,10 @@
 
 #### Members ####
 
-*   `int index`
-
-    The platform-defined index of the associated audio output.
 *   `SbMediaAudioConnector connector`
 
-    The type of audio connector. Will be the empty `kSbMediaAudioConnectorNone`
-    if this device cannot provide this information.
+    The type of audio connector. Will be `kSbMediaAudioConnectorUnknown` if this
+    device cannot provide this information.
 *   `SbTime latency`
 
     The expected latency of audio over this output, in microseconds, or `0` if
@@ -192,13 +202,19 @@
 
 ### SbMediaAudioSampleInfo ###
 
-An audio sample info, which is a description of a given audio sample. This acts
-as a set of instructions to the audio decoder.
+The set of information required by the decoder or player for each audio sample.
 
-The audio sample info consists of information found in the `WAVEFORMATEX`
-structure, as well as other information for the audio decoder, including the
-Audio-specific configuration field. The `WAVEFORMATEX` structure is specified at
-[http://msdn.microsoft.com/en-us/library/dd390970(v=vs.85).aspx](http://msdn.microsoft.com/en-us/library/dd390970(v=vs.85).aspx)x) .
+#### Members ####
+
+*   `SbMediaAudioStreamInfo stream_info`
+
+    The set of information of the video stream associated with this sample.
+*   `SbTime discarded_duration_from_front`
+*   `SbTime discarded_duration_from_back`
+
+### SbMediaAudioStreamInfo ###
+
+The set of information required by the decoder or player for each audio stream.
 
 #### Members ####
 
@@ -210,21 +226,12 @@
     The mime of the audio stream when `codec` isn't kSbMediaAudioCodecNone. It
     may point to an empty string if the mime is not available, and it can only
     be set to NULL when `codec` is kSbMediaAudioCodecNone.
-*   `uint16_t format_tag`
-
-    The waveform-audio format type code.
 *   `uint16_t number_of_channels`
 
     The number of audio channels in this format. `1` for mono, `2` for stereo.
 *   `uint32_t samples_per_second`
 
     The sampling rate.
-*   `uint32_t average_bytes_per_second`
-
-    The number of bytes per second expected with this format.
-*   `uint16_t block_alignment`
-
-    Byte block alignment, e.g, 4.
 *   `uint16_t bits_per_sample`
 
     The bit depth for the stream this represents, e.g. `8` or `16`.
@@ -373,6 +380,20 @@
 
 #### Members ####
 
+*   `SbMediaVideoStreamInfo stream_info`
+
+    The set of information of the video stream associated with this sample.
+*   `bool is_key_frame`
+
+    Indicates whether the associated sample is a key frame (I-frame). Avc video
+    key frames must always start with SPS and PPS NAL units.
+
+### SbMediaVideoStreamInfo ###
+
+The set of information required by the decoder or player for each video stream.
+
+#### Members ####
+
 *   `SbMediaVideoCodec codec`
 
     The video codec of this sample.
@@ -393,10 +414,6 @@
     second higher than 15 fps. When the maximums are unknown, this will be set
     to an empty string. It can only be set to NULL when `codec` is
     kSbMediaVideoCodecNone.
-*   `bool is_key_frame`
-
-    Indicates whether the associated sample is a key frame (I-frame). Video key
-    frames must always start with SPS and PPS NAL units.
 *   `int frame_width`
 
     The frame width of this sample, in pixels. Also could be parsed from the
@@ -517,13 +534,12 @@
 ### SbMediaGetBufferAlignment ###
 
 The media buffer will be allocated using the returned alignment. Set this to a
-larger value may increase the memory consumption of media buffers.`type`: the
-media type of the stream (audio or video).
+larger value may increase the memory consumption of media buffers.
 
 #### Declaration ####
 
 ```
-int SbMediaGetBufferAlignment(SbMediaType type)
+int SbMediaGetBufferAlignment()
 ```
 
 ### SbMediaGetBufferAllocationUnit ###
@@ -561,12 +577,12 @@
 
 Extra bytes allocated at the end of a media buffer to ensure that the buffer can
 be use optimally by specific instructions like SIMD. Set to 0 to remove any
-padding.`type`: the media type of the stream (audio or video).
+padding.
 
 #### Declaration ####
 
 ```
-int SbMediaGetBufferPadding(SbMediaType type)
+int SbMediaGetBufferPadding()
 ```
 
 ### SbMediaGetBufferStorageType ###
@@ -683,39 +699,3 @@
 ```
 bool SbMediaIsBufferUsingMemoryPool()
 ```
-
-### SbMediaIsSupported ###
-
-Indicates whether this platform supports decoding `video_codec` and
-`audio_codec` along with decrypting using `key_system`. If `video_codec` is
-`kSbMediaVideoCodecNone` or if `audio_codec` is `kSbMediaAudioCodecNone`, this
-function should return `true` as long as `key_system` is supported on the
-platform to decode any supported input formats.
-
-`video_codec`: The `SbMediaVideoCodec` being checked for platform compatibility.
-`audio_codec`: The `SbMediaAudioCodec` being checked for platform compatibility.
-`key_system`: The key system being checked for platform compatibility.
-
-#### Declaration ####
-
-```
-bool SbMediaIsSupported(SbMediaVideoCodec video_codec, SbMediaAudioCodec audio_codec, const char *key_system)
-```
-
-### SbMediaSetAudioWriteDuration ###
-
-Communicate to the platform how far past `current_playback_position` the app
-will write audio samples. The app will write all samples between
-`current_playback_position` and `current_playback_position` + `duration`, as
-soon as they are available. The app may sometimes write more samples than that,
-but the app only guarantees to write `duration` past `current_playback_position`
-in general. The platform is responsible for guaranteeing that when only
-`duration` audio samples are written at a time, no playback issues occur (such
-as transient or indefinite hanging). The platform may assume `duration` >= 0.5
-seconds.
-
-#### Declaration ####
-
-```
-void SbMediaSetAudioWriteDuration(SbTime duration)
-```
diff --git a/cobalt/site/docs/reference/starboard/modules/12/memory.md b/cobalt/site/docs/reference/starboard/modules/15/memory.md
similarity index 72%
rename from cobalt/site/docs/reference/starboard/modules/12/memory.md
rename to cobalt/site/docs/reference/starboard/modules/15/memory.md
index 7ea1c5b..2fbf7dc 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/memory.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/memory.md
@@ -46,16 +46,6 @@
 
 ## Functions ##
 
-### SbMemoryAlignToPageSize ###
-
-Rounds `size` up to kSbMemoryPageSize.
-
-#### Declaration ####
-
-```
-static size_t SbMemoryAlignToPageSize(size_t size)
-```
-
 ### SbMemoryAllocate ###
 
 Allocates and returns a chunk of memory of at least `size` bytes. This function
@@ -168,46 +158,6 @@
 static void* SbMemoryCalloc(size_t count, size_t size)
 ```
 
-### SbMemoryCompare ###
-
-Compares the contents of the first `count` bytes of `buffer1` and `buffer2`.
-This function returns:
-
-*   `-1` if `buffer1` is "less-than" `buffer2`
-
-*   `0` if `buffer1` and `buffer2` are equal
-
-*   `1` if `buffer1` is "greater-than" `buffer2`.
-
-This function is meant to be a drop-in replacement for `memcmp`.
-
-`buffer1`: The first buffer to be compared. `buffer2`: The second buffer to be
-compared. `count`: The number of bytes to be compared.
-
-#### Declaration ####
-
-```
-int SbMemoryCompare(const void *buffer1, const void *buffer2, size_t count)
-```
-
-### SbMemoryCopy ###
-
-Copies `count` sequential bytes from `source` to `destination`, without support
-for the `source` and `destination` regions overlapping. This function is meant
-to be a drop-in replacement for `memcpy`.
-
-The function's behavior is undefined if `destination` or `source` are NULL, and
-the function is a no-op if `count` is 0. The return value is `destination`.
-
-`destination`: The destination of the copied memory. `source`: The source of the
-copied memory. `count`: The number of sequential bytes to be copied.
-
-#### Declaration ####
-
-```
-void* SbMemoryCopy(void *destination, const void *source, size_t count)
-```
-
 ### SbMemoryDeallocate ###
 
 Frees a previously allocated chunk of memory. If `memory` is NULL, then the
@@ -244,18 +194,6 @@
 void SbMemoryDeallocateNoReport(void *memory)
 ```
 
-### SbMemoryFindByte ###
-
-Finds the lower 8-bits of `value` in the first `count` bytes of `buffer` and
-returns either a pointer to the first found occurrence or `NULL` if the value is
-not found. This function is meant to be a drop-in replacement for `memchr`.
-
-#### Declaration ####
-
-```
-const void* SbMemoryFindByte(const void *buffer, int value, size_t count)
-```
-
 ### SbMemoryFlush ###
 
 Flushes any data in the given virtual address range that is cached locally in
@@ -295,39 +233,6 @@
 void SbMemoryFreeAligned(void *memory)
 ```
 
-### SbMemoryGetStackBounds ###
-
-Gets the stack bounds for the current thread.
-
-`out_high`: The highest addressable byte + 1 for the current thread. `out_low`:
-The lowest addressable byte for the current thread.
-
-#### Declaration ####
-
-```
-void SbMemoryGetStackBounds(void **out_high, void **out_low)
-```
-
-### SbMemoryIsAligned ###
-
-Checks whether `memory` is aligned to `alignment` bytes.
-
-#### Declaration ####
-
-```
-static bool SbMemoryIsAligned(const void *memory, size_t alignment)
-```
-
-### SbMemoryIsZero ###
-
-Returns true if the first `count` bytes of `buffer` are set to zero.
-
-#### Declaration ####
-
-```
-static bool SbMemoryIsZero(const void *buffer, size_t count)
-```
-
 ### SbMemoryMap ###
 
 Allocates `size_bytes` worth of physical memory pages and maps them into an
@@ -349,24 +254,6 @@
 void* SbMemoryMap(int64_t size_bytes, int flags, const char *name)
 ```
 
-### SbMemoryMove ###
-
-Copies `count` sequential bytes from `source` to `destination`, with support for
-the `source` and `destination` regions overlapping. This function is meant to be
-a drop-in replacement for `memmove`.
-
-The function's behavior is undefined if `destination` or `source` are NULL, and
-the function is a no-op if `count` is 0. The return value is `destination`.
-
-`destination`: The destination of the copied memory. `source`: The source of the
-copied memory. `count`: The number of sequential bytes to be copied.
-
-#### Declaration ####
-
-```
-void* SbMemoryMove(void *destination, const void *source, size_t count)
-```
-
 ### SbMemoryProtect ###
 
 Change the protection of `size_bytes` of memory regions, starting from
@@ -430,24 +317,6 @@
 void* SbMemoryReallocateUnchecked(void *memory, size_t size)
 ```
 
-### SbMemorySet ###
-
-Fills `count` sequential bytes starting at `destination`, with the unsigned char
-coercion of `byte_value`. This function is meant to be a drop-in replacement for
-`memset`.
-
-The function's behavior is undefined if `destination` is NULL, and the function
-is a no-op if `count` is 0. The return value is `destination`.
-
-`destination`: The destination of the copied memory. `count`: The number of
-sequential bytes to be set.
-
-#### Declaration ####
-
-```
-void* SbMemorySet(void *destination, int byte_value, size_t count)
-```
-
 ### SbMemoryUnmap ###
 
 Unmap `size_bytes` of physical pages starting from `virtual_address`, returning
@@ -463,4 +332,3 @@
 ```
 bool SbMemoryUnmap(void *virtual_address, int64_t size_bytes)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/memory_reporter.md b/cobalt/site/docs/reference/starboard/modules/15/memory_reporter.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/memory_reporter.md
rename to cobalt/site/docs/reference/starboard/modules/15/memory_reporter.md
index 4b4a539..d67ef1a 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/memory_reporter.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/memory_reporter.md
@@ -101,4 +101,3 @@
 ```
 bool SbMemorySetReporter(struct SbMemoryReporter *tracker)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/microphone.md b/cobalt/site/docs/reference/starboard/modules/15/microphone.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/microphone.md
rename to cobalt/site/docs/reference/starboard/modules/15/microphone.md
index 1379f86..d760e1e 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/microphone.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/microphone.md
@@ -260,4 +260,3 @@
 ```
 int SbMicrophoneRead(SbMicrophone microphone, void *out_audio_data, int audio_data_size)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/mutex.md b/cobalt/site/docs/reference/starboard/modules/15/mutex.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/mutex.md
rename to cobalt/site/docs/reference/starboard/modules/15/mutex.md
index 58f1907..05dd810 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/mutex.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/mutex.md
@@ -125,4 +125,3 @@
 ```
 bool SbMutexRelease(SbMutex *mutex)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/once.md b/cobalt/site/docs/reference/starboard/modules/15/once.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/once.md
rename to cobalt/site/docs/reference/starboard/modules/15/once.md
index ce3c4d6..2ad1959 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/once.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/once.md
@@ -55,4 +55,3 @@
 ```
 bool SbOnce(SbOnceControl *once_control, SbOnceInitRoutine init_routine)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/player.md b/cobalt/site/docs/reference/starboard/modules/15/player.md
similarity index 73%
rename from cobalt/site/docs/reference/starboard/modules/12/player.md
rename to cobalt/site/docs/reference/starboard/modules/15/player.md
index d6910e2..8039f6b 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/player.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/player.md
@@ -22,6 +22,14 @@
 
 Well-defined value for an invalid player.
 
+### kSbPlayerWriteDurationLocal ###
+
+The audio write duration when all the audio connectors are local.
+
+### kSbPlayerWriteDurationRemote ###
+
+The audio write duration when at least one of the audio connectors are remote.
+
 ## Enums ##
 
 ### SbPlayerDecoderState ###
@@ -159,15 +167,15 @@
     Provides an appropriate DRM system if the media stream has encrypted
     portions. It will be `kSbDrmSystemInvalid` if the stream does not have
     encrypted portions.
-*   `SbMediaAudioSampleInfo audio_sample_info`
+*   `SbMediaAudioStreamInfo audio_stream_info`
 
-    Contains a populated SbMediaAudioSampleInfo if `audio_sample_info.codec`
-    isn't `kSbMediaAudioCodecNone`. When `audio_sample_info.codec` is
+    Contains a populated SbMediaAudioStreamInfo if `audio_stream_info.codec`
+    isn't `kSbMediaAudioCodecNone`. When `audio_stream_info.codec` is
     `kSbMediaAudioCodecNone`, the video doesn't have an audio track.
-*   `SbMediaVideoSampleInfo video_sample_info`
+*   `SbMediaVideoStreamInfo video_stream_info`
 
-    Contains a populated SbMediaVideoSampleInfo if `video_sample_info.codec`
-    isn't `kSbMediaVideoCodecNone`. When `video_sample_info.codec` is
+    Contains a populated SbMediaVideoStreamInfo if `video_stream_info.codec`
+    isn't `kSbMediaVideoCodecNone`. When `video_stream_info.codec` is
     `kSbMediaVideoCodecNone`, the video is audio only.
 *   `SbPlayerOutputMode output_mode`
 
@@ -178,7 +186,7 @@
     should be made available for the application to pull via calls to
     SbPlayerGetCurrentFrame().
 
-### SbPlayerInfo2 ###
+### SbPlayerInfo ###
 
 Information about the current media playback state.
 
@@ -231,7 +239,7 @@
 
 ### SbPlayerSampleInfo ###
 
-Information about the samples to be written into SbPlayerWriteSample2.
+Information about the samples to be written into SbPlayerWriteSamples().
 
 #### Members ####
 
@@ -297,7 +305,7 @@
 
 *   It is not allowed to pass `player` into any other `SbPlayer` function once
     SbPlayerDestroy has been called on that player. `player`: The player to be
-    destroyed.
+    destroyed. Must not be `kSbPlayerInvalid`.
 
 #### Declaration ####
 
@@ -305,6 +313,70 @@
 void SbPlayerDestroy(SbPlayer player)
 ```
 
+### SbPlayerGetAudioConfiguration ###
+
+Returns the audio configurations used by `player`.
+
+Returns true when `out_audio_configuration` is filled with the information of
+the configuration of the audio output devices used by `player`. Returns false
+for `index` 0 to indicate that there is no audio output for this `player`.
+Returns false for `index` greater than 0 to indicate that there are no more
+audio output configurations other than the ones already returned.
+
+The app will use the information returned to determine audio related behaviors,
+like:
+
+Audio Write Duration: Audio write duration is how far past the current playback
+position the app will write audio samples. The app will write all samples
+between `current_playback_position` and `current_playback_position` +
+`audio_write_duration`, as soon as they are available.
+
+`audio_write_duration` will be to `kSbPlayerWriteDurationLocal`
+kSbPlayerWriteDurationLocal when all audio configurations linked to `player` is
+local, or if there isn't any audio output. It will be set to
+`kSbPlayerWriteDurationRemote` kSbPlayerWriteDurationRemote for remote or
+wireless audio outputs, i.e. one of `kSbMediaAudioConnectorBluetooth`
+kSbMediaAudioConnectorBluetooth or `kSbMediaAudioConnectorRemote*`
+kSbMediaAudioConnectorRemote* .
+
+The app only guarantees to write `audio_write_duration` past
+`current_playback_position`, but the app is free to write more samples than
+that. So the platform shouldn't rely on this for flow control. The platform
+should achieve flow control by sending `kSbPlayerDecoderStateNeedsData`
+kSbPlayerDecoderStateNeedsData less frequently.
+
+The platform is responsible for guaranteeing that when only
+`audio_write_duration` audio samples are written at a time, no playback issues
+occur (such as transient or indefinite hanging).
+
+The audio configurations should be available as soon as possible, and they have
+to be available when the `player` is at `kSbPlayerStatePresenting`
+kSbPlayerStatePresenting , unless the audio codec is `kSbMediaAudioCodecNone` or
+there's no written audio inputs.
+
+The app will set `audio_write_duration` to `kSbPlayerWriteDurationLocal`
+kSbPlayerWriteDurationLocal when the audio configuration isn't available (i.e.
+the function returns false when index is 0). The platform has to make the audio
+configuration available immediately after the SbPlayer is created, if it expects
+the app to treat the platform as using wireless audio outputs.
+
+Once at least one audio configurations are returned, the return values and their
+orders shouldn't change during the life time of `player`. The platform may
+inform the app of any changes by sending `kSbPlayerErrorCapabilityChanged`
+kSbPlayerErrorCapabilityChanged to request a playback restart.
+
+`player`: The player about which information is being retrieved. Must not be
+`kSbPlayerInvalid`. `index`: The index of the audio output configuration. Must
+be greater than or equal to 0. `out_audio_configuration`: The information about
+the audio output, refer to `SbMediaAudioConfiguration` for more details. Must
+not be NULL.
+
+#### Declaration ####
+
+```
+bool SbPlayerGetAudioConfiguration(SbPlayer player, int index, SbMediaAudioConfiguration *out_audio_configuration)
+```
+
 ### SbPlayerGetCurrentFrame ###
 
 Given a player created with the kSbPlayerOutputModeDecodeToTexture output mode,
@@ -315,26 +387,14 @@
 with an output mode other than kSbPlayerOutputModeDecodeToTexture,
 kSbDecodeTargetInvalid is returned.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
 SbDecodeTarget SbPlayerGetCurrentFrame(SbPlayer player)
 ```
 
-### SbPlayerGetInfo2 ###
-
-Gets a snapshot of the current player state and writes it to `out_player_info`.
-This function may be called very frequently and is expected to be inexpensive.
-
-`player`: The player about which information is being retrieved.
-`out_player_info`: The information retrieved for the player.
-
-#### Declaration ####
-
-```
-void SbPlayerGetInfo2(SbPlayer player, SbPlayerInfo2 *out_player_info2)
-```
-
 ### SbPlayerGetMaximumNumberOfSamplesPerWrite ###
 
 Writes a single sample of the given media type to `player`'s input stream. Its
@@ -371,7 +431,7 @@
 the call. Note that it is not the responsibility of this function to verify
 whether the video described by `creation_param` can be played on the platform,
 and the implementation should try its best effort to return a valid output mode.
-`creation_param` will never be NULL.
+`creation_param` must not be NULL.
 
 #### Declaration ####
 
@@ -403,12 +463,12 @@
 implementors should take care to avoid related performance concerns with such
 frequent calls.
 
-`player`: The player that is being resized. `z_index`: The z-index of the
-player. When the bounds of multiple players are overlapped, the one with larger
-z-index will be rendered on top of the ones with smaller z-index. `x`: The
-x-coordinate of the upper-left corner of the player. `y`: The y-coordinate of
-the upper-left corner of the player. `width`: The width of the player, in
-pixels. `height`: The height of the player, in pixels.
+`player`: The player that is being resized. Must not be `kSbPlayerInvalid`.
+`z_index`: The z-index of the player. When the bounds of multiple players are
+overlapped, the one with larger z-index will be rendered on top of the ones with
+smaller z-index. `x`: The x-coordinate of the upper-left corner of the player.
+`y`: The y-coordinate of the upper-left corner of the player. `width`: The width
+of the player, in pixels. `height`: The height of the player, in pixels.
 
 #### Declaration ####
 
@@ -429,6 +489,8 @@
 unchanged, this can happen when `playback_rate` is negative or if it is too high
 to support.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
@@ -439,10 +501,10 @@
 
 Sets the player's volume.
 
-`player`: The player in which the volume is being adjusted. `volume`: The new
-player volume. The value must be between `0.0` and `1.0`, inclusive. A value of
-`0.0` means that the audio should be muted, and a value of `1.0` means that it
-should be played at full volume.
+`player`: The player in which the volume is being adjusted. Must not be
+`kSbPlayerInvalid`. `volume`: The new player volume. The value must be between
+`0.0` and `1.0`, inclusive. A value of `0.0` means that the audio should be
+muted, and a value of `1.0` means that it should be played at full volume.
 
 #### Declaration ####
 
@@ -466,31 +528,20 @@
 void SbPlayerWriteEndOfStream(SbPlayer player, SbMediaType stream_type)
 ```
 
-### SbPlayerWriteSample2 ###
+### SbPlayerWriteSamples ###
 
-Writes samples of the given media type to `player`'s input stream. The lifetime
-of `sample_infos`, and the members of its elements like `buffer`,
-`video_sample_info`, and `drm_info` (as well as member `subsample_mapping`
-contained inside it) are not guaranteed past the call to SbPlayerWriteSample2.
-That means that before returning, the implementation must synchronously copy any
-information it wants to retain from those structures.
-
-SbPlayerWriteSample2 allows writing of multiple samples in one call.
-
-`player`: The player to which the sample is written. `sample_type`: The type of
-sample being written. See the `SbMediaType` enum in media.h. `sample_infos`: A
-pointer to an array of SbPlayerSampleInfo with `number_of_sample_infos`
-elements, each holds the data for an sample, i.e. a sequence of whole NAL Units
-for video, or a complete audio frame. `sample_infos` cannot be assumed to live
-past the call into SbPlayerWriteSample2(), so it must be copied if its content
-will be used after SbPlayerWriteSample2() returns. `number_of_sample_infos`:
-Specify the number of samples contained inside `sample_infos`. It has to be at
-least one, and less than the return value of
+`sample_type`: The type of sample being written. See the `SbMediaType` enum in
+media.h. `sample_infos`: A pointer to an array of SbPlayerSampleInfo with
+`number_of_sample_infos` elements, each holds the data for an sample, i.e. a
+sequence of whole NAL Units for video, or a complete audio frame. `sample_infos`
+cannot be assumed to live past the call into SbPlayerWriteSamples(), so it must
+be copied if its content will be used after SbPlayerWriteSamples() returns.
+`number_of_sample_infos`: Specify the number of samples contained inside
+`sample_infos`. It has to be at least one, and less than the return value of
 SbPlayerGetMaximumNumberOfSamplesPerWrite().
 
 #### Declaration ####
 
 ```
-void SbPlayerWriteSample2(SbPlayer player, SbMediaType sample_type, const SbPlayerSampleInfo *sample_infos, int number_of_sample_infos)
+void SbPlayerWriteSamples(SbPlayer player, SbMediaType sample_type, const SbPlayerSampleInfo *sample_infos, int number_of_sample_infos)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/socket.md b/cobalt/site/docs/reference/starboard/modules/15/socket.md
similarity index 97%
rename from cobalt/site/docs/reference/starboard/modules/12/socket.md
rename to cobalt/site/docs/reference/starboard/modules/15/socket.md
index 548f57d..9e0f81b 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/socket.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/socket.md
@@ -417,8 +417,8 @@
 the address is unnecessary, but allowed.
 
 `socket`: The SbSocket from which data is read. `out_data`: The data read from
-the socket. `data_size`: The number of bytes to read. `out_source`: The source
-address of the packet.
+the socket. Must not be NULL. `data_size`: The number of bytes to read.
+`out_source`: The source address of the packet.
 
 #### Declaration ####
 
@@ -456,10 +456,10 @@
 SbSocketGetLastError returns `kSbSocketPending` to make it a best-effort write
 (but still only up to not blocking, unless you want to spin).
 
-`socket`: The SbSocket to use to write data. `data`: The data read from the
-socket. `data_size`: The number of bytes of `data` to write. `destination`: The
-location to which data is written. This value must be `NULL` for TCP
-connections, which can only have a single endpoint.
+`socket`: The SbSocket to use to write data. `data`: The data written to the
+socket. Must not be NULL. `data_size`: The number of bytes of `data` to write.
+`destination`: The location to which data is written. This value must be `NULL`
+for TCP connections, which can only have a single endpoint.
 
 The primary use of `destination` is to send datagram packets, which can go out
 to multiple sources from a single UDP server socket. TCP has two endpoints
@@ -583,4 +583,3 @@
 ```
 bool SbSocketSetTcpWindowScaling(SbSocket socket, bool value)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/socket_waiter.md b/cobalt/site/docs/reference/starboard/modules/15/socket_waiter.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/socket_waiter.md
rename to cobalt/site/docs/reference/starboard/modules/15/socket_waiter.md
index 738fafb..855dcf8 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/socket_waiter.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/socket_waiter.md
@@ -235,4 +235,3 @@
 ```
 void SbSocketWaiterWakeUp(SbSocketWaiter waiter)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/speech_synthesis.md b/cobalt/site/docs/reference/starboard/modules/15/speech_synthesis.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/speech_synthesis.md
rename to cobalt/site/docs/reference/starboard/modules/15/speech_synthesis.md
index e46a2ca..1622318 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/speech_synthesis.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/speech_synthesis.md
@@ -49,4 +49,3 @@
 ```
 void SbSpeechSynthesisSpeak(const char *text)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/storage.md b/cobalt/site/docs/reference/starboard/modules/15/storage.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/storage.md
rename to cobalt/site/docs/reference/starboard/modules/15/storage.md
index c98207b..db7e950 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/storage.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/storage.md
@@ -156,4 +156,3 @@
 ```
 bool SbStorageWriteRecord(SbStorageRecord record, const char *data, int64_t data_size)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/15/string.md b/cobalt/site/docs/reference/starboard/modules/15/string.md
new file mode 100644
index 0000000..685f5e8
--- /dev/null
+++ b/cobalt/site/docs/reference/starboard/modules/15/string.md
@@ -0,0 +1,174 @@
+---
+layout: doc
+title: "Starboard Module Reference: string.h"
+---
+
+Defines functions for interacting with c-style strings.
+
+## Functions ##
+
+### SbStringCompareNoCase ###
+
+Compares two strings, ignoring differences in case. The return value is:
+
+*   `< 0` if `string1` is ASCII-betically lower than `string2`.
+
+*   `0` if the two strings are equal.
+
+*   `> 0` if `string1` is ASCII-betically higher than `string2`.
+
+This function is meant to be a drop-in replacement for `strcasecmp`.
+
+`string1`: The first string to compare. `string2`: The second string to compare.
+
+#### Declaration ####
+
+```
+int SbStringCompareNoCase(const char *string1, const char *string2)
+```
+
+### SbStringCompareNoCaseN ###
+
+Compares the first `count` characters of two strings, ignoring differences in
+case. The return value is:
+
+*   `< 0` if `string1` is ASCII-betically lower than `string2`.
+
+*   `0` if the two strings are equal.
+
+*   `> 0` if `string1` is ASCII-betically higher than `string2`.
+
+This function is meant to be a drop-in replacement for `strncasecmp`.
+
+`string1`: The first string to compare. `string2`: The second string to compare.
+`count`: The number of characters to compare.
+
+#### Declaration ####
+
+```
+int SbStringCompareNoCaseN(const char *string1, const char *string2, size_t count)
+```
+
+### SbStringDuplicate ###
+
+Copies `source` into a buffer that is allocated by this function and that can be
+freed with SbMemoryDeallocate. This function is meant to be a drop-in
+replacement for `strdup`.
+
+`source`: The string to be copied.
+
+#### Declaration ####
+
+```
+char* SbStringDuplicate(const char *source)
+```
+
+### SbStringFormat ###
+
+Produces a string formatted with `format` and `arguments`, placing as much of
+the result that will fit into `out_buffer`. The return value specifies the
+number of characters that the format would produce if `buffer_size` were
+infinite.
+
+This function is meant to be a drop-in replacement for `vsnprintf`.
+
+`out_buffer`: The location where the formatted string is stored. `buffer_size`:
+The size of `out_buffer`. `format`: A string that specifies how the data should
+be formatted. `arguments`: Variable arguments used in the string.
+
+#### Declaration ####
+
+```
+int SbStringFormat(char *out_buffer, size_t buffer_size, const char *format, va_list arguments) SB_PRINTF_FORMAT(3
+```
+
+### SbStringFormatF ###
+
+An inline wrapper of SbStringFormat that converts from ellipsis to va_args. This
+function is meant to be a drop-in replacement for `snprintf`.
+
+`out_buffer`: The location where the formatted string is stored. `buffer_size`:
+The size of `out_buffer`. `format`: A string that specifies how the data should
+be formatted. `...`: Arguments used in the string.
+
+#### Declaration ####
+
+```
+int static int static int SbStringFormatF(char *out_buffer, size_t buffer_size, const char *format,...) SB_PRINTF_FORMAT(3
+```
+
+### SbStringFormatUnsafeF ###
+
+An inline wrapper of SbStringFormat that is meant to be a drop-in replacement
+for the unsafe but commonly used `sprintf`.
+
+`out_buffer`: The location where the formatted string is stored. `format`: A
+string that specifies how the data should be formatted. `...`: Arguments used in
+the string.
+
+#### Declaration ####
+
+```
+static int static int SbStringFormatUnsafeF(char *out_buffer, const char *format,...) SB_PRINTF_FORMAT(2
+```
+
+### SbStringFormatWide ###
+
+This function is identical to SbStringFormat, but is for wide characters. It is
+meant to be a drop-in replacement for `vswprintf`.
+
+`out_buffer`: The location where the formatted string is stored. `buffer_size`:
+The size of `out_buffer`. `format`: A string that specifies how the data should
+be formatted. `arguments`: Variable arguments used in the string.
+
+#### Declaration ####
+
+```
+int SbStringFormatWide(wchar_t *out_buffer, size_t buffer_size, const wchar_t *format, va_list arguments)
+```
+
+### SbStringFormatWideF ###
+
+An inline wrapper of SbStringFormatWide that converts from ellipsis to
+`va_args`.
+
+`out_buffer`: The location where the formatted string is stored. `buffer_size`:
+The size of `out_buffer`. `format`: A string that specifies how the data should
+be formatted. `...`: Arguments used in the string.
+
+#### Declaration ####
+
+```
+static int SbStringFormatWideF(wchar_t *out_buffer, size_t buffer_size, const wchar_t *format,...)
+```
+
+### SbStringScan ###
+
+Scans `buffer` for `pattern`, placing the extracted values in `arguments`. The
+return value specifies the number of successfully matched items, which may be
+`0`.
+
+This function is meant to be a drop-in replacement for `vsscanf`.
+
+`buffer`: The string to scan for the pattern. `pattern`: The string to search
+for in `buffer`. `arguments`: Values matching `pattern` that were extracted from
+`buffer`.
+
+#### Declaration ####
+
+```
+int SbStringScan(const char *buffer, const char *pattern, va_list arguments)
+```
+
+### SbStringScanF ###
+
+An inline wrapper of SbStringScan that converts from ellipsis to `va_args`. This
+function is meant to be a drop-in replacement for `sscanf`. `buffer`: The string
+to scan for the pattern. `pattern`: The string to search for in `buffer`. `...`:
+Values matching `pattern` that were extracted from `buffer`.
+
+#### Declaration ####
+
+```
+static int SbStringScanF(const char *buffer, const char *pattern,...)
+```
diff --git a/cobalt/site/docs/reference/starboard/modules/12/system.md b/cobalt/site/docs/reference/starboard/modules/15/system.md
similarity index 80%
rename from cobalt/site/docs/reference/starboard/modules/12/system.md
rename to cobalt/site/docs/reference/starboard/modules/15/system.md
index 1fe2ddb..32fd303 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/system.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/system.md
@@ -25,62 +25,6 @@
     Whether this system has the ability to report on GPU memory usage. If (and
     only if) a system has this capability will SbSystemGetTotalGPUMemory() and
     SbSystemGetUsedGPUMemory() be valid to call.
-*   `kSbSystemCapabilitySetsInputTimestamp`
-
-    Whether this system sets the `timestamp` field of SbInputData . If the
-    system does not set this field, then it will automatically be set; however,
-    the relative time between input events likely will not be preserved, so
-    time-related calculations (e.g. velocity for move events) will be incorrect.
-
-### SbSystemConnectionType ###
-
-Enumeration of network connection types.
-
-#### Values ####
-
-*   `kSbSystemConnectionTypeWired`
-
-    The system is on a wired connection.
-*   `kSbSystemConnectionTypeWireless`
-
-    The system is on a wireless connection.
-*   `kSbSystemConnectionTypeUnknown`
-
-    The system connection type is unknown.
-
-### SbSystemDeviceType ###
-
-Enumeration of device types.
-
-#### Values ####
-
-*   `kSbSystemDeviceTypeBlueRayDiskPlayer`
-
-    Blue-ray Disc Player (BDP).
-*   `kSbSystemDeviceTypeGameConsole`
-
-    A relatively high-powered TV device used primarily for playing games.
-*   `kSbSystemDeviceTypeOverTheTopBox`
-
-    Over the top (OTT) devices stream content via the Internet over another type
-    of network, e.g. cable or satellite.
-*   `kSbSystemDeviceTypeSetTopBox`
-
-    Set top boxes (STBs) stream content primarily over cable or satellite. Some
-    STBs can also stream OTT content via the Internet.
-*   `kSbSystemDeviceTypeTV`
-
-    A Smart TV is a TV that can directly run applications that stream OTT
-    content via the Internet.
-*   `kSbSystemDeviceTypeDesktopPC`
-
-    Desktop PC.
-*   `kSbSystemDeviceTypeAndroidTV`
-
-    An Android TV Device.
-*   `kSbSystemDeviceTypeUnknown`
-
-    Unknown device.
 
 ### SbSystemPathId ###
 
@@ -112,17 +56,15 @@
 *   `kSbSystemPathTempDirectory`
 
     Path to a directory where temporary files can be written.
-*   `kSbSystemPathTestOutputDirectory`
-
-    Path to a directory where test results can be written.
 *   `kSbSystemPathExecutableFile`
 
     Full path to the executable file.
 *   `kSbSystemPathStorageDirectory`
 
-    Path to a directory for permanent file storage. Both read and write access
-    is required. This is where an app may store its persistent settings. The
-    location should be user agnostic if possible.
+    Path to the directory dedicated for Evergreen Full permanent file storage.
+    Both read and write access is required. The directory should be used only
+    for storing the updates. See
+    starboard/doc/evergreen/cobalt_evergreen_overview.md
 
 ### SbSystemPlatformErrorResponse ###
 
@@ -158,10 +100,6 @@
 *   `kSbSystemPropertyCertificationScope`
 
     The certification scope that identifies a group of devices.
-*   `kSbSystemPropertyBase64EncodedCertificationSecret`
-
-    The HMAC-SHA256 base64 encoded symmetric key used to sign a subset of the
-    query parameters from the application startup URL.
 *   `kSbSystemPropertyChipsetModelNumber`
 
     The full model number of the main platform chipset, including any vendor-
@@ -204,6 +142,19 @@
 *   `kSbSystemPropertyUserAgentAuxField`
 
     A field that, if available, is appended to the user agent
+*   `kSbSystemPropertyAdvertisingId`
+
+    Advertising ID or IFA, typically a 128-bit UUID Please see [https://iabtechlab.com/OTT-IFA](https://iabtechlab.com/OTT-IFA) for
+    details. Corresponds to 'ifa' field. Note: `ifa_type` ifa_type field is not
+    provided.
+*   `kSbSystemPropertyLimitAdTracking`
+
+    Limit advertising tracking, treated as boolean. Set to nonzero to indicate a
+    true value. Corresponds to 'lmt' field.
+*   `kSbSystemPropertyDeviceType`
+
+    Type of the device, e.g. such as "TV", "STB", "OTT" Please see Youtube
+    Technical requirements for a full list of allowed values
 
 ## Typedefs ##
 
@@ -252,26 +203,6 @@
 
 ## Functions ##
 
-### SbSystemBinarySearch ###
-
-Binary searches a sorted table `base` of `element_count` objects, each element
-`element_width` bytes in size for an element that `comparator` compares equal to
-`key`.
-
-This function is meant to be a drop-in replacement for `bsearch`.
-
-`key`: The key to search for in the table. `base`: The sorted table of elements
-to be searched. `element_count`: The number of elements in the table.
-`element_width`: The size, in bytes, of each element in the table. `comparator`:
-A value that indicates how the element in the table should compare to the
-specified `key`.
-
-#### Declaration ####
-
-```
-void* SbSystemBinarySearch(const void *key, const void *base, size_t element_count, size_t element_width, SbSystemComparator comparator)
-```
-
 ### SbSystemBreakIntoDebugger ###
 
 Breaks the current program into the debugger, if a debugger is attached. If a
@@ -293,26 +224,6 @@
 void SbSystemClearLastError()
 ```
 
-### SbSystemGetConnectionType ###
-
-Returns the device's current network connection type.
-
-#### Declaration ####
-
-```
-SbSystemConnectionType SbSystemGetConnectionType()
-```
-
-### SbSystemGetDeviceType ###
-
-Returns the type of the device.
-
-#### Declaration ####
-
-```
-SbSystemDeviceType SbSystemGetDeviceType()
-```
-
 ### SbSystemGetErrorString ###
 
 Generates a human-readable string for an error. The return value specifies the
@@ -331,7 +242,8 @@
 ### SbSystemGetExtension ###
 
 Returns pointer to a constant global struct implementing the extension named
-`name`, if it is implemented. Otherwise return NULL.
+`name`, if it is implemented. Otherwise return NULL. The `name` string must not
+be NULL.
 
 Extensions are used to implement behavior which is specific to the combination
 of application & platform. An extension relies on a header file in the
@@ -564,6 +476,18 @@
 bool SbSystemIsDebuggerAttached()
 ```
 
+### SbSystemNetworkIsDisconnected ###
+
+Returns if the device is disconnected from network. "Disconnected" is chosen
+over connected because disconnection can be determined with more certainty than
+connection usually.
+
+#### Declaration ####
+
+```
+bool SbSystemNetworkIsDisconnected()
+```
+
 ### SbSystemRaisePlatformError ###
 
 Cobalt calls this function to notify the platform that an error has occurred in
@@ -592,20 +516,94 @@
 bool SbSystemRaisePlatformError(SbSystemPlatformErrorType type, SbSystemPlatformErrorCallback callback, void *user_data)
 ```
 
-### SbSystemRequestPause ###
+### SbSystemRequestBlur ###
 
-Requests that the application move into the Paused state at the next convenient
+Requests that the application move into the Blurred state at the next convenient
 point. This should roughly correspond to "unfocused application" in a
 traditional window manager, where the application may be partially visible.
 
-This function eventually causes a `kSbEventTypePause` event to be dispatched to
-the application. Before the `kSbEventTypePause` event is dispatched, some work
+This function eventually causes a `kSbEventTypeBlur` event to be dispatched to
+the application. Before the `kSbEventTypeBlur` event is dispatched, some work
 may continue to be done, and unrelated system events may be dispatched.
 
 #### Declaration ####
 
 ```
-void SbSystemRequestPause()
+void SbSystemRequestBlur()
+```
+
+### SbSystemRequestConceal ###
+
+Requests that the application move into the Concealed state at the next
+convenient point. This should roughly correspond to "minimization" in a
+traditional window manager, where the application is no longer visible. However,
+the background tasks can still be running.
+
+This function eventually causes a `kSbEventTypeConceal` event to be dispatched
+to the application. Before the `kSbEventTypeConceal` event is dispatched, some
+work may continue to be done, and unrelated system events may be dispatched.
+
+In the Concealed state, the application will be invisible, but probably still be
+running background tasks. The expectation is that an external system event will
+bring the application out of the Concealed state.
+
+#### Declaration ####
+
+```
+void SbSystemRequestConceal()
+```
+
+### SbSystemRequestFocus ###
+
+Requests that the application move into the Started state at the next convenient
+point. This should roughly correspond to a "focused application" in a
+traditional window manager, where the application is fully visible and the
+primary receiver of input events.
+
+This function eventually causes a `kSbEventTypeFocus` event to be dispatched to
+the application. Before `kSbEventTypeFocus` is dispatched, some work may
+continue to be done, and unrelated system events may be dispatched.
+
+#### Declaration ####
+
+```
+void SbSystemRequestFocus()
+```
+
+### SbSystemRequestFreeze ###
+
+Requests that the application move into the Frozen state at the next convenient
+point.
+
+This function eventually causes a `kSbEventTypeFreeze` event to be dispatched to
+the application. Before the `kSbEventTypeSuspend` event is dispatched, some work
+may continue to be done, and unrelated system events may be dispatched.
+
+In the Frozen state, the application will be resident, but probably not running.
+The expectation is that an external system event will bring the application out
+of the Frozen state.
+
+#### Declaration ####
+
+```
+void SbSystemRequestFreeze()
+```
+
+### SbSystemRequestReveal ###
+
+Requests that the application move into the Blurred state at the next convenient
+point. This should roughly correspond to a "focused application" in a
+traditional window manager, where the application is fully visible and the
+primary receiver of input events.
+
+This function eventually causes a `kSbEventTypeReveal` event to be dispatched to
+the application. Before the `kSbEventTypeReveal` event is dispatched, some work
+may continue to be done, and unrelated system events may be dispatched.
+
+#### Declaration ####
+
+```
+void SbSystemRequestReveal()
 ```
 
 ### SbSystemRequestStop ###
@@ -625,47 +623,10 @@
 void SbSystemRequestStop(int error_level)
 ```
 
-### SbSystemRequestSuspend ###
-
-Requests that the application move into the Suspended state at the next
-convenient point. This should roughly correspond to "minimization" in a
-traditional window manager, where the application is no longer visible.
-
-This function eventually causes a `kSbEventTypeSuspend` event to be dispatched
-to the application. Before the `kSbEventTypeSuspend` event is dispatched, some
-work may continue to be done, and unrelated system events may be dispatched.
-
-In the Suspended state, the application will be resident, but probably not
-running. The expectation is that an external system event will bring the
-application out of the Suspended state.
-
-#### Declaration ####
-
-```
-void SbSystemRequestSuspend()
-```
-
-### SbSystemRequestUnpause ###
-
-Requests that the application move into the Started state at the next convenient
-point. This should roughly correspond to a "focused application" in a
-traditional window manager, where the application is fully visible and the
-primary receiver of input events.
-
-This function eventually causes a `kSbEventTypeUnpause` event to be dispatched
-to the application. Before `kSbEventTypeUnpause` is dispatched, some work may
-continue to be done, and unrelated system events may be dispatched.
-
-#### Declaration ####
-
-```
-void SbSystemRequestUnpause()
-```
-
 ### SbSystemSignWithCertificationSecretKey ###
 
 Computes a HMAC-SHA256 digest of `message` into `digest` using the application's
-certification secret.
+certification secret. The `message` and the `digest` pointers must not be NULL.
 
 The output will be written into `digest`. `digest_size_in_bytes` must be 32 (or
 greater), since 32-bytes will be written into it. Returns false in the case of
@@ -678,23 +639,6 @@
 bool SbSystemSignWithCertificationSecretKey(const uint8_t *message, size_t message_size_in_bytes, uint8_t *digest, size_t digest_size_in_bytes)
 ```
 
-### SbSystemSort ###
-
-Sorts an array of elements `base`, with `element_count` elements of
-`element_width` bytes each, using `comparator` as the comparison function.
-
-This function is meant to be a drop-in replacement for `qsort`.
-
-`base`: The array of elements to be sorted. `element_count`: The number of
-elements in the array. `element_width`: The size, in bytes, of each element in
-the array. `comparator`: A value that indicates how the array should be sorted.
-
-#### Declaration ####
-
-```
-void SbSystemSort(void *base, size_t element_count, size_t element_width, SbSystemComparator comparator)
-```
-
 ### SbSystemSupportsResume ###
 
 Returns false if the platform doesn't need resume after suspend support. In such
diff --git a/cobalt/site/docs/reference/starboard/modules/12/thread.md b/cobalt/site/docs/reference/starboard/modules/15/thread.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/thread.md
rename to cobalt/site/docs/reference/starboard/modules/15/thread.md
index 8440477..1191e9a 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/thread.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/thread.md
@@ -531,4 +531,3 @@
 ```
 void SbThreadYield()
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/time.md b/cobalt/site/docs/reference/starboard/modules/15/time.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/time.md
rename to cobalt/site/docs/reference/starboard/modules/15/time.md
index 17ea6ad..19a7e4f 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/time.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/time.md
@@ -150,4 +150,3 @@
 ```
 static int64_t SbTimeToPosix(SbTime time)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/time_zone.md b/cobalt/site/docs/reference/starboard/modules/15/time_zone.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/time_zone.md
rename to cobalt/site/docs/reference/starboard/modules/15/time_zone.md
index 5768bc3..f9e3fcb 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/time_zone.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/time_zone.md
@@ -45,4 +45,3 @@
 ```
 const char* SbTimeZoneGetName()
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/types.md b/cobalt/site/docs/reference/starboard/modules/15/types.md
similarity index 100%
rename from cobalt/site/docs/reference/starboard/modules/12/types.md
rename to cobalt/site/docs/reference/starboard/modules/15/types.md
diff --git a/cobalt/site/docs/reference/starboard/modules/12/ui_navigation.md b/cobalt/site/docs/reference/starboard/modules/15/ui_navigation.md
similarity index 83%
rename from cobalt/site/docs/reference/starboard/modules/12/ui_navigation.md
rename to cobalt/site/docs/reference/starboard/modules/15/ui_navigation.md
index 23f8049..a0ecfb1 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/ui_navigation.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/ui_navigation.md
@@ -102,6 +102,9 @@
     kSbUiNavItemTypeFocus. Any previously focused navigation item should receive
     the blur event. If the item is not transitively a content of the root item,
     then this does nothing.
+
+    Specifying kSbUiNavItemInvalid should remove focus from the UI navigation
+    system.
 *   `void(*set_item_enabled)(SbUiNavItem item, bool enabled)`
 
     This is used to enable or disable user interaction with the specified
@@ -116,6 +119,15 @@
     This specifies directionality for container items. Containers within
     containers do not inherit directionality. Directionality must be specified
     for each container explicitly.
+
+    This should work even if `item` is disabled.
+*   `void(*set_item_focus_duration)(SbUiNavItem item, float seconds)`
+
+    Set the minimum amount of time the focus item should remain focused once it
+    becomes focused. This may be used to make important focus items harder to
+    navigate over. Focus may still be moved before `seconds` has elapsed by
+    using the set_focus() function. By default, item focus duration is 0
+    seconds.
 *   `void(*set_item_size)(SbUiNavItem item, float width, float height)`
 
     Set the interactable size of the specified navigation item. By default, an
@@ -150,11 +162,16 @@
 
     This attaches the given navigation item (which must be a container) to the
     specified window. Navigation items are only interactable if they are
-    transitively attached to a window.A navigation item may only have a
-    SbUiNavItem or SbWindow as its direct container. The navigation item
-    hierarchy is established using set_item_container_item() with the root
-    container attached to a SbWindow using set_item_container_window() to enable
-    interaction with all enabled items in the hierarchy.
+    transitively attached to a window.
+
+    The native UI engine should never change this navigation item's content
+    offset. It is assumed to be used as a proxy for the system window.
+
+    A navigation item may only have a SbUiNavItem or SbWindow as its direct
+    container. The navigation item hierarchy is established using
+    set_item_container_item() with the root container attached to a SbWindow
+    using set_item_container_window() to enable interaction with all enabled
+    items in the hierarchy.
 
     If `item` is already registered with a different window, then this will
     unregister it from that window then attach it to the given `window`. It is
@@ -186,6 +203,13 @@
 
     Essentially, content items should be drawn at: [container position] +
     [content position] - [container content offset]
+
+    Content items may overlap within a container. This can cause obscured items
+    to be unfocusable. The only rule that needs to be followed is that contents
+    which are focus items can obscure other contents which are containers, but
+    not vice versa. The caller must ensure that content focus items do not
+    overlap other content focus items and content container items do not overlap
+    other content container items.
 *   `void(*set_item_content_offset)(SbUiNavItem item, float content_offset_x,
     float content_offset_y)`
 
@@ -195,12 +219,24 @@
     Essentially, a content item should be drawn at: [container position] +
     [content position] - [container content offset] If `item` is not a
     container, then this does nothing. By default, the content offset is (0,0).
+
+    This should update the values returned by get_item_content_offset() even if
+    the `item` is disabled.
 *   `void(*get_item_content_offset)(SbUiNavItem item, float
     *out_content_offset_x, float *out_content_offset_y)`
 
     Retrieve the current content offset for the navigation item. If `item` is
     not a container, then the content offset is (0,0).
 
+    The native UI engine should not change the content offset of a container
+    unless one of its contents (possibly recursively) is focused. This is to
+    allow seamlessly disabling then re-enabling focus items without having their
+    containers change offsets.
+*   `void(*do_batch_update)(void(*update_function)(void *), void *context)`
+
+    Call `update_function` with `context` to perform a series of UI navigation
+    changes atomically before returning.
+
 ### SbUiNavItemDir ###
 
 Navigation items of type kSbUiNavItemTypeContainer have directionality. If
@@ -226,7 +262,7 @@
 ///     | Negative position. | Positive position. | Positive position. |
 ///     +--------------------+--------------------+--------------------+
 ///                          ^
-///                  Content Offset X = 0. 
+///                  Content Offset X = 0.
 ```
 
 ```
@@ -245,7 +281,7 @@
 
 ```
 ///   | a b tx |
-///   | c d ty | 
+///   | c d ty |
 ```
 
 #### Members ####
@@ -266,7 +302,8 @@
 
 Retrieve the platform's UI navigation implementation. If the platform does not
 provide one, then return false without modifying `out_interface`. Otherwise,
-initialize all members of `out_interface` and return true.
+initialize all members of `out_interface` and return true. The `out_interface`
+pointer must not be NULL.
 
 #### Declaration ####
 
@@ -283,4 +320,3 @@
 ```
 static bool SbUiNavItemIsValid(SbUiNavItem item)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/user.md b/cobalt/site/docs/reference/starboard/modules/15/user.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/user.md
rename to cobalt/site/docs/reference/starboard/modules/15/user.md
index a30cc95..406e695 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/user.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/user.md
@@ -131,4 +131,3 @@
 ```
 static bool SbUserIsValid(SbUser user)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/12/window.md b/cobalt/site/docs/reference/starboard/modules/15/window.md
similarity index 99%
rename from cobalt/site/docs/reference/starboard/modules/12/window.md
rename to cobalt/site/docs/reference/starboard/modules/15/window.md
index 53cda4a..915e254 100644
--- a/cobalt/site/docs/reference/starboard/modules/12/window.md
+++ b/cobalt/site/docs/reference/starboard/modules/15/window.md
@@ -328,4 +328,3 @@
 ```
 void SbWindowUpdateOnScreenKeyboardSuggestions(SbWindow window, const char *suggestions[], int num_suggestions, int ticket)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/audio_sink.md b/cobalt/site/docs/reference/starboard/modules/audio_sink.md
index 8cf2329..b0e652f 100644
--- a/cobalt/site/docs/reference/starboard/modules/audio_sink.md
+++ b/cobalt/site/docs/reference/starboard/modules/audio_sink.md
@@ -72,6 +72,53 @@
 
 ## Functions ##
 
+### SbAudioSinkCreate ###
+
+Creates an audio sink for the specified `channels` and `sampling_frequency_hz`,
+acquires all resources needed to operate the audio sink, and returns an opaque
+handle to the audio sink.
+
+If the particular platform doesn't support the requested audio sink, the
+function returns `kSbAudioSinkInvalid` without calling any of the callbacks. If
+there is a platform limitation on how many audio sinks can coexist
+simultaneously, then calls made to this function that attempt to exceed that
+limit must return `kSbAudioSinkInvalid`. Multiple calls to SbAudioSinkCreate
+must not cause a crash.
+
+`channels`: The number of audio channels, such as left and right channels in
+stereo audio. `sampling_frequency_hz`: The sample frequency of the audio data
+being streamed. For example, 22,000 Hz means 22,000 sample elements represents
+one second of audio data. `audio_sample_type`: The type of each sample of the
+audio data – `int16`, `float32`, etc. `audio_frame_storage_type`: Indicates
+whether frames are interleaved or planar. `frame_buffers`: An array of pointers
+to sample data.
+
+*   If the sink is operating in interleaved mode, the array contains only one
+    element, which is an array containing (`frames_per_channel` * `channels`)
+    samples.
+
+*   If the sink is operating in planar mode, the number of elements in the array
+    is the same as `channels`, and each element is an array of
+    `frames_per_channel` samples. The caller has to ensure that `frame_buffers`
+    is valid until SbAudioSinkDestroy is called. `frames_per_channel`: The size
+    of the frame buffers, in units of the number of samples per channel. The
+    frame, in this case, represents a group of samples at the same media time,
+    one for each channel. `update_source_status_func`: The audio sink calls this
+    function on an internal thread to query the status of the source. It is
+    called immediately after SbAudioSinkCreate is called, even before it
+    returns. The caller has to ensure that the callback functions above return
+    meaningful values in this case. The value cannot be NULL.
+    `consume_frames_func`: The audio sink calls this function on an internal
+    thread to report consumed frames. The value cannot be NULL. `context`: A
+    value that is passed back to all callbacks and is generally used to point at
+    a class or struct that contains state associated with the audio sink.
+
+#### Declaration ####
+
+```
+SbAudioSink SbAudioSinkCreate(int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, SbMediaAudioFrameStorageType audio_frame_storage_type, SbAudioSinkFrameBuffers frame_buffers, int frames_per_channel, SbAudioSinkUpdateSourceStatusFunc update_source_status_func, SbAudioSinkConsumeFramesFunc consume_frames_func, void *context)
+```
+
 ### SbAudioSinkDestroy ###
 
 Destroys `audio_sink`, freeing all associated resources. Before returning, the
@@ -165,4 +212,3 @@
 ```
 bool SbAudioSinkIsValid(SbAudioSink audio_sink)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/configuration_constants.md b/cobalt/site/docs/reference/starboard/modules/configuration_constants.md
index 51212e9..99d92f8 100644
--- a/cobalt/site/docs/reference/starboard/modules/configuration_constants.md
+++ b/cobalt/site/docs/reference/starboard/modules/configuration_constants.md
@@ -50,10 +50,6 @@
 
 The string form of SB_FILE_SEP_CHAR.
 
-### kSbHasAc3Audio ###
-
-Allow ac3 and ec3 support
-
 ### kSbHasMediaWebmVp9Support ###
 
 Specifies whether this platform has webm/vp9 support. This should be set to non-
diff --git a/cobalt/site/docs/reference/starboard/modules/decode_target.md b/cobalt/site/docs/reference/starboard/modules/decode_target.md
index 0e912d5..a237ad9 100644
--- a/cobalt/site/docs/reference/starboard/modules/decode_target.md
+++ b/cobalt/site/docs/reference/starboard/modules/decode_target.md
@@ -332,8 +332,10 @@
 
 ### SbDecodeTargetGetInfo ###
 
-Writes all information about `decode_target` into `out_info`. Returns false if
-the provided `out_info` structure is not zero initialized.
+Writes all information about `decode_target` into `out_info`. The
+`decode_target` must not be kSbDecodeTargetInvalid. The `out_info` pointer must
+not be NULL. Returns false if the provided `out_info` structure is not zero
+initialized.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/drm.md b/cobalt/site/docs/reference/starboard/modules/drm.md
index beb65c9..fbb92f9 100644
--- a/cobalt/site/docs/reference/starboard/modules/drm.md
+++ b/cobalt/site/docs/reference/starboard/modules/drm.md
@@ -238,6 +238,8 @@
 
 Clear any internal states/resources related to the specified `session_id`.
 
+`drm_system` must not be `kSbDrmSystemInvalid`. `session_id` must not be NULL.
+
 #### Declaration ####
 
 ```
@@ -254,7 +256,7 @@
 result, if this function is called from a callback that is passed to
 SbDrmCreateSystem(), a deadlock will occur.
 
-`drm_system`: The DRM system to be destroyed.
+`drm_system`: The DRM system to be destroyed. Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -281,7 +283,7 @@
 
 `drm_system`: The DRM system that defines the key system used for the session
 update request payload as well as the callback function that is called as a
-result of the function being called.
+result of the function being called. Must not be `kSbDrmSystemInvalid`.
 
 `ticket`: The opaque ID that allows to distinguish callbacks from multiple
 concurrent calls to SbDrmGenerateSessionUpdateRequest(), which will be passed to
@@ -289,10 +291,10 @@
 establish ticket uniqueness, issuing multiple requests with the same ticket may
 result in undefined behavior. The value `kSbDrmTicketInvalid` must not be used.
 
-`type`: The case-sensitive type of the session update request payload.
-`initialization_data`: The data for which the session update request payload is
-created. `initialization_data_size`: The size of the session update request
-payload.
+`type`: The case-sensitive type of the session update request payload. Must not
+be NULL. `initialization_data`: The data for which the session update request
+payload is created. Must not be NULL. `initialization_data_size`: The size of
+the session update request payload.
 
 #### Declaration ####
 
@@ -322,7 +324,7 @@
 It should return NULL when there is no metrics support in the underlying drm
 system, or when the drm system implementation fails to retrieve the metrics.
 
-The caller will never set `size` to NULL.
+`drm_system` must not be `kSbDrmSystemInvalid`. `size` must not be NULL.
 
 #### Declaration ####
 
@@ -337,6 +339,7 @@
 the life time of `drm_system`.
 
 `drm_system`: The DRM system to check if its server certificate is updatable.
+Must not be `kSbDrmSystemInvalid`.
 
 #### Declaration ####
 
@@ -371,14 +374,15 @@
 a previous call is called. Note that this function should only be called after
 `SbDrmIsServerCertificateUpdatable` is called first and returned true.
 
-`drm_system`: The DRM system whose server certificate is being updated.
-`ticket`: The opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateServerCertificate(), which will be passed to
-`server_certificate_updated_callback` as-is. It is the responsibility of the
-caller to establish ticket uniqueness, issuing multiple requests with the same
-ticket may result in undefined behavior. The value `kSbDrmTicketInvalid` must
-not be used. `certificate`: Pointer to the server certificate data.
-`certificate_size`: Size of the server certificate data.
+`drm_system`: The DRM system whose server certificate is being updated. Must not
+be `kSbDrmSystemInvalid`. `ticket`: The opaque ID that allows to distinguish
+callbacks from multiple concurrent calls to SbDrmUpdateServerCertificate(),
+which will be passed to `server_certificate_updated_callback` as-is. It is the
+responsibility of the caller to establish ticket uniqueness, issuing multiple
+requests with the same ticket may result in undefined behavior. The value
+`kSbDrmTicketInvalid` must not be used. `certificate`: Pointer to the server
+certificate data. Must not be NULL. `certificate_size`: Size of the server
+certificate data.
 
 #### Declaration ####
 
@@ -391,22 +395,23 @@
 Update session with `key`, in `drm_system`'s key system, from the license server
 response. Calls `session_updated_callback` with `context` and whether the update
 succeeded. `context` may be used to route callbacks back to an object instance.
+The `key` must not be NULL.
 
-`ticket` is the opaque ID that allows to distinguish callbacks from multiple
-concurrent calls to SbDrmUpdateSession(), which will be passed to
-`session_updated_callback` as-is. It is the responsibility of the caller to
-establish ticket uniqueness, issuing multiple calls with the same ticket may
-result in undefined behavior.
+`drm_system` must not be `kSbDrmSystemInvalid`. `ticket` is the opaque ID that
+allows to distinguish callbacks from multiple concurrent calls to
+SbDrmUpdateSession(), which will be passed to `session_updated_callback` as-is.
+It is the responsibility of the caller to establish ticket uniqueness, issuing
+multiple calls with the same ticket may result in undefined behavior.
 
 Once the session is successfully updated, an SbPlayer or SbDecoder associated
 with that DRM key system will be able to decrypt encrypted samples.
 
 `drm_system`'s `session_updated_callback` may called either from the current
-thread before this function returns or from another thread.
+thread before this function returns or from another thread. The `session_id`
+must not be NULL.
 
 #### Declaration ####
 
 ```
 void SbDrmUpdateSession(SbDrmSystem drm_system, int ticket, const void *key, int key_size, const void *session_id, int session_id_size)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/event.md b/cobalt/site/docs/reference/starboard/modules/event.md
index 8d20c6f..58cb1f4 100644
--- a/cobalt/site/docs/reference/starboard/modules/event.md
+++ b/cobalt/site/docs/reference/starboard/modules/event.md
@@ -3,10 +3,6 @@
 title: "Starboard Module Reference: event.h"
 ---
 
-For SB_API_VERSION >= 13
-
-Module Overview: Starboard Event module
-
 Defines the event system that wraps the Starboard main loop and entry point.
 
 ## The Starboard Application Lifecycle ##
@@ -82,75 +78,6 @@
 Note that the application is always expected to transition through `BLURRED`,
 `CONCEALED` to `FROZEN` before receiving `Stop` or being killed.
 
-For SB_API_VERSION < 13
-
-Module Overview: Starboard Event module
-
-Defines the event system that wraps the Starboard main loop and entry point.
-
-## The Starboard Application Lifecycle ##
-
-```
-    ---------- *
-   |           |
-   |        Preload
-   |           |
-   |           V
- Start   [ PRELOADING ] ------------
-   |           |                    |
-   |         Start                  |
-   |           |                    |
-   |           V                    |
-    ----> [ STARTED ] <----         |
-               |           |        |
-             Pause       Unpause    |
-               |           |     Suspend
-               V           |        |
-    -----> [ PAUSED ] -----         |
-   |           |                    |
-Resume      Suspend                 |
-   |           |                    |
-   |           V                    |
-    ---- [ SUSPENDED ] <------------
-               |
-              Stop
-               |
-               V
-          [ STOPPED ]
-
-```
-
-The first event that a Starboard application receives is either `Start`
-(`kSbEventTypeStart`) or `Preload` (`kSbEventTypePreload`). `Start` puts the
-application in the `STARTED` state, whereas `Preload` puts the application in
-the `PRELOADING` state.
-
-`PRELOADING` can only happen as the first application state. In this state, the
-application should start and run as normal, but will not receive any input, and
-should not try to initialize graphics resources via GL. In `PRELOADING`, the
-application can receive `Start` or `Suspend` events. `Start` will receive the
-same data that was passed into `Preload`.
-
-In the `STARTED` state, the application is in the foreground and can expect to
-do all of the normal things it might want to do. Once in the `STARTED` state, it
-may receive a `Pause` event, putting the application into the `PAUSED` state.
-
-In the `PAUSED` state, the application is still visible, but has lost focus, or
-it is partially obscured by a modal dialog, or it is on its way to being shut
-down. The application should pause activity in this state. In this state, it can
-receive `Unpause` to be brought back to the foreground state (`STARTED`), or
-`Suspend` to be pushed further in the background to the `SUSPENDED` state.
-
-In the `SUSPENDED` state, the application is generally not visible. It should
-immediately release all graphics and video resources, and shut down all
-background activity (timers, rendering, etc). Additionally, the application
-should flush storage to ensure that if the application is killed, the storage
-will be up-to-date. The application may be killed at this point, but will
-ideally receive a `Stop` event for a more graceful shutdown.
-
-Note that the application is always expected to transition through `PAUSED` to
-`SUSPENDED` before receiving `Stop` or being killed.
-
 ## Enums ##
 
 ### SbEventType ###
@@ -446,7 +373,7 @@
 #### Declaration ####
 
 ```
-SB_IMPORT void SbEventHandle(const SbEvent *event)
+SB_EXPORT_PLATFORM void SbEventHandle(const SbEvent *event)
 ```
 
 ### SbEventIsIdValid ###
@@ -465,13 +392,24 @@
 may be called from any thread, but `callback` is always called from the main
 Starboard thread, queued with other pending events.
 
-`callback`: The callback function to be called. `context`: The context that is
-passed to the `callback` function. `delay`: The minimum number of microseconds
-to wait before calling the `callback` function. Set `delay` to `0` to call the
-callback as soon as possible.
+`callback`: The callback function to be called. Must not be NULL. `context`: The
+context that is passed to the `callback` function. `delay`: The minimum number
+of microseconds to wait before calling the `callback` function. Set `delay` to
+`0` to call the callback as soon as possible.
 
 #### Declaration ####
 
 ```
 SbEventId SbEventSchedule(SbEventCallback callback, void *context, SbTime delay)
 ```
+
+### SbRunStarboardMain ###
+
+Serves as the entry point in the Starboard library for running the Starboard
+event loop with the application event handler.
+
+#### Declaration ####
+
+```
+int SbRunStarboardMain(int argc, char **argv, SbEventHandleCallback callback)
+```
diff --git a/cobalt/site/docs/reference/starboard/modules/image.md b/cobalt/site/docs/reference/starboard/modules/image.md
index 3050953..1427d39 100644
--- a/cobalt/site/docs/reference/starboard/modules/image.md
+++ b/cobalt/site/docs/reference/starboard/modules/image.md
@@ -24,7 +24,7 @@
   return;
 }
 
-SbDecodeTarget result_target = SbDecodeImage(provider, data, data_size,
+SbDecodeTarget result_target = SbImageDecode(provider, data, data_size,
                                              mime_type, format);
 ```
 
@@ -48,13 +48,13 @@
     called, and the implementation will proceed to decoding however it desires.
 
 1.  The provider is not required and is not passed in. The implementation will
-    proceed forward.
-
-Thus, it is NOT safe for clients of this API to assume that the `provider` it
-passes in will be called. Finally, if the decode succeeds, a new SbDecodeTarget
-will be allocated. If `mime_type` image decoding for the requested format is not
-supported or the decode fails, kSbDecodeTargetInvalid will be returned, with any
-intermediate allocations being cleaned up in the implementation.
+    proceed forward. The `data` pointer must not be NULL. The `mime_type` string
+    must not be NULL. Thus, it is NOT safe for clients of this API to assume
+    that the `provider` it passes in will be called. Finally, if the decode
+    succeeds, a new SbDecodeTarget will be allocated. If `mime_type` image
+    decoding for the requested format is not supported or the decode fails,
+    kSbDecodeTargetInvalid will be returned, with any intermediate allocations
+    being cleaned up in the implementation.
 
 #### Declaration ####
 
@@ -65,9 +65,10 @@
 ### SbImageIsDecodeSupported ###
 
 Whether the current platform supports hardware accelerated decoding an image of
-mime type `mime_type` into SbDecodeTargetFormat `format`. The result of this
-function must not change over the course of the program, which means that the
-results of this function may be cached indefinitely.
+mime type `mime_type` into SbDecodeTargetFormat `format`. The `mime_type` must
+not be NULL. The result of this function must not change over the course of the
+program, which means that the results of this function may be cached
+indefinitely.
 
 #### Declaration ####
 
diff --git a/cobalt/site/docs/reference/starboard/modules/key.md b/cobalt/site/docs/reference/starboard/modules/key.md
index 16be3c1..2835b20 100644
--- a/cobalt/site/docs/reference/starboard/modules/key.md
+++ b/cobalt/site/docs/reference/starboard/modules/key.md
@@ -196,6 +196,7 @@
 *   `kSbKeyGreen`
 *   `kSbKeyYellow`
 *   `kSbKeyBlue`
+*   `kSbKeyRecord`
 *   `kSbKeyChannelUp`
 *   `kSbKeyChannelDown`
 *   `kSbKeySubtitle`
@@ -290,4 +291,3 @@
 *   `kSbKeyModifiersPointerButtonMiddle`
 *   `kSbKeyModifiersPointerButtonBack`
 *   `kSbKeyModifiersPointerButtonForward`
-
diff --git a/cobalt/site/docs/reference/starboard/modules/log.md b/cobalt/site/docs/reference/starboard/modules/log.md
index 1ad6c24..42de513 100644
--- a/cobalt/site/docs/reference/starboard/modules/log.md
+++ b/cobalt/site/docs/reference/starboard/modules/log.md
@@ -30,10 +30,10 @@
 `priority`: The SbLogPriority at which the message should be logged. Note that
 passing `kSbLogPriorityFatal` does not terminate the program. Such a policy must
 be enforced at the application level. In fact, `priority` may be completely
-ignored on many platforms. `message`: The message to be logged. No formatting is
-required to be done on the value, including newline termination. That said,
-platforms can adjust the message to be more suitable for their output method by
-wrapping the text, stripping unprintable characters, etc.
+ignored on many platforms. `message`: The message to be logged. Must not be
+NULL. No formatting is required to be done on the value, including newline
+termination. That said, platforms can adjust the message to be more suitable for
+their output method by wrapping the text, stripping unprintable characters, etc.
 
 #### Declaration ####
 
@@ -70,7 +70,7 @@
 #### Declaration ####
 
 ```
-void static void void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
 
 ### SbLogIsTty ###
@@ -89,7 +89,7 @@
 an asynchronous signal handler (e.g. a `SIGSEGV` handler). It should not do any
 additional formatting.
 
-`message`: The message to be logged.
+`message`: The message to be logged. Must not be NULL.
 
 #### Declaration ####
 
@@ -132,6 +132,5 @@
 #### Declaration ####
 
 ```
-void static void void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
+void static void static void SbLogRawFormatF(const char *format,...) SB_PRINTF_FORMAT(1
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/media.md b/cobalt/site/docs/reference/starboard/modules/media.md
index d927473..132166c 100644
--- a/cobalt/site/docs/reference/starboard/modules/media.md
+++ b/cobalt/site/docs/reference/starboard/modules/media.md
@@ -59,11 +59,20 @@
 
 #### Values ####
 
-*   `kSbMediaAudioConnectorNone`
+*   `kSbMediaAudioConnectorUnknown`
 *   `kSbMediaAudioConnectorAnalog`
 *   `kSbMediaAudioConnectorBluetooth`
+*   `kSbMediaAudioConnectorBuiltIn`
 *   `kSbMediaAudioConnectorHdmi`
-*   `kSbMediaAudioConnectorNetwork`
+*   `kSbMediaAudioConnectorRemoteWired`
+
+    A wired remote audio output, like a remote speaker via Ethernet.
+*   `kSbMediaAudioConnectorRemoteWireless`
+
+    A wireless remote audio output, like a remote speaker via Wi-Fi.
+*   `kSbMediaAudioConnectorRemoteOther`
+
+    A remote audio output cannot be classified into other existing types.
 *   `kSbMediaAudioConnectorSpdif`
 *   `kSbMediaAudioConnectorUsb`
 
@@ -174,13 +183,10 @@
 
 #### Members ####
 
-*   `int index`
-
-    The platform-defined index of the associated audio output.
 *   `SbMediaAudioConnector connector`
 
-    The type of audio connector. Will be the empty `kSbMediaAudioConnectorNone`
-    if this device cannot provide this information.
+    The type of audio connector. Will be `kSbMediaAudioConnectorUnknown` if this
+    device cannot provide this information.
 *   `SbTime latency`
 
     The expected latency of audio over this output, in microseconds, or `0` if
@@ -196,13 +202,19 @@
 
 ### SbMediaAudioSampleInfo ###
 
-An audio sample info, which is a description of a given audio sample. This acts
-as a set of instructions to the audio decoder.
+The set of information required by the decoder or player for each audio sample.
 
-The audio sample info consists of information found in the `WAVEFORMATEX`
-structure, as well as other information for the audio decoder, including the
-Audio-specific configuration field. The `WAVEFORMATEX` structure is specified at
-[http://msdn.microsoft.com/en-us/library/dd390970(v=vs.85).aspx](http://msdn.microsoft.com/en-us/library/dd390970(v=vs.85).aspx)x) .
+#### Members ####
+
+*   `SbMediaAudioStreamInfo stream_info`
+
+    The set of information of the video stream associated with this sample.
+*   `SbTime discarded_duration_from_front`
+*   `SbTime discarded_duration_from_back`
+
+### SbMediaAudioStreamInfo ###
+
+The set of information required by the decoder or player for each audio stream.
 
 #### Members ####
 
@@ -214,21 +226,12 @@
     The mime of the audio stream when `codec` isn't kSbMediaAudioCodecNone. It
     may point to an empty string if the mime is not available, and it can only
     be set to NULL when `codec` is kSbMediaAudioCodecNone.
-*   `uint16_t format_tag`
-
-    The waveform-audio format type code.
 *   `uint16_t number_of_channels`
 
     The number of audio channels in this format. `1` for mono, `2` for stereo.
 *   `uint32_t samples_per_second`
 
     The sampling rate.
-*   `uint32_t average_bytes_per_second`
-
-    The number of bytes per second expected with this format.
-*   `uint16_t block_alignment`
-
-    Byte block alignment, e.g, 4.
 *   `uint16_t bits_per_sample`
 
     The bit depth for the stream this represents, e.g. `8` or `16`.
@@ -377,6 +380,20 @@
 
 #### Members ####
 
+*   `SbMediaVideoStreamInfo stream_info`
+
+    The set of information of the video stream associated with this sample.
+*   `bool is_key_frame`
+
+    Indicates whether the associated sample is a key frame (I-frame). Avc video
+    key frames must always start with SPS and PPS NAL units.
+
+### SbMediaVideoStreamInfo ###
+
+The set of information required by the decoder or player for each video stream.
+
+#### Members ####
+
 *   `SbMediaVideoCodec codec`
 
     The video codec of this sample.
@@ -397,10 +414,6 @@
     second higher than 15 fps. When the maximums are unknown, this will be set
     to an empty string. It can only be set to NULL when `codec` is
     kSbMediaVideoCodecNone.
-*   `bool is_key_frame`
-
-    Indicates whether the associated sample is a key frame (I-frame). Video key
-    frames must always start with SPS and PPS NAL units.
 *   `int frame_width`
 
     The frame width of this sample, in pixels. Also could be parsed from the
@@ -686,21 +699,3 @@
 ```
 bool SbMediaIsBufferUsingMemoryPool()
 ```
-
-### SbMediaSetAudioWriteDuration ###
-
-Communicate to the platform how far past `current_playback_position` the app
-will write audio samples. The app will write all samples between
-`current_playback_position` and `current_playback_position` + `duration`, as
-soon as they are available. The app may sometimes write more samples than that,
-but the app only guarantees to write `duration` past `current_playback_position`
-in general. The platform is responsible for guaranteeing that when only
-`duration` audio samples are written at a time, no playback issues occur (such
-as transient or indefinite hanging). The platform may assume `duration` >= 0.5
-seconds.
-
-#### Declaration ####
-
-```
-void SbMediaSetAudioWriteDuration(SbTime duration)
-```
diff --git a/cobalt/site/docs/reference/starboard/modules/player.md b/cobalt/site/docs/reference/starboard/modules/player.md
index d6910e2..8039f6b 100644
--- a/cobalt/site/docs/reference/starboard/modules/player.md
+++ b/cobalt/site/docs/reference/starboard/modules/player.md
@@ -22,6 +22,14 @@
 
 Well-defined value for an invalid player.
 
+### kSbPlayerWriteDurationLocal ###
+
+The audio write duration when all the audio connectors are local.
+
+### kSbPlayerWriteDurationRemote ###
+
+The audio write duration when at least one of the audio connectors are remote.
+
 ## Enums ##
 
 ### SbPlayerDecoderState ###
@@ -159,15 +167,15 @@
     Provides an appropriate DRM system if the media stream has encrypted
     portions. It will be `kSbDrmSystemInvalid` if the stream does not have
     encrypted portions.
-*   `SbMediaAudioSampleInfo audio_sample_info`
+*   `SbMediaAudioStreamInfo audio_stream_info`
 
-    Contains a populated SbMediaAudioSampleInfo if `audio_sample_info.codec`
-    isn't `kSbMediaAudioCodecNone`. When `audio_sample_info.codec` is
+    Contains a populated SbMediaAudioStreamInfo if `audio_stream_info.codec`
+    isn't `kSbMediaAudioCodecNone`. When `audio_stream_info.codec` is
     `kSbMediaAudioCodecNone`, the video doesn't have an audio track.
-*   `SbMediaVideoSampleInfo video_sample_info`
+*   `SbMediaVideoStreamInfo video_stream_info`
 
-    Contains a populated SbMediaVideoSampleInfo if `video_sample_info.codec`
-    isn't `kSbMediaVideoCodecNone`. When `video_sample_info.codec` is
+    Contains a populated SbMediaVideoStreamInfo if `video_stream_info.codec`
+    isn't `kSbMediaVideoCodecNone`. When `video_stream_info.codec` is
     `kSbMediaVideoCodecNone`, the video is audio only.
 *   `SbPlayerOutputMode output_mode`
 
@@ -178,7 +186,7 @@
     should be made available for the application to pull via calls to
     SbPlayerGetCurrentFrame().
 
-### SbPlayerInfo2 ###
+### SbPlayerInfo ###
 
 Information about the current media playback state.
 
@@ -231,7 +239,7 @@
 
 ### SbPlayerSampleInfo ###
 
-Information about the samples to be written into SbPlayerWriteSample2.
+Information about the samples to be written into SbPlayerWriteSamples().
 
 #### Members ####
 
@@ -297,7 +305,7 @@
 
 *   It is not allowed to pass `player` into any other `SbPlayer` function once
     SbPlayerDestroy has been called on that player. `player`: The player to be
-    destroyed.
+    destroyed. Must not be `kSbPlayerInvalid`.
 
 #### Declaration ####
 
@@ -305,6 +313,70 @@
 void SbPlayerDestroy(SbPlayer player)
 ```
 
+### SbPlayerGetAudioConfiguration ###
+
+Returns the audio configurations used by `player`.
+
+Returns true when `out_audio_configuration` is filled with the information of
+the configuration of the audio output devices used by `player`. Returns false
+for `index` 0 to indicate that there is no audio output for this `player`.
+Returns false for `index` greater than 0 to indicate that there are no more
+audio output configurations other than the ones already returned.
+
+The app will use the information returned to determine audio related behaviors,
+like:
+
+Audio Write Duration: Audio write duration is how far past the current playback
+position the app will write audio samples. The app will write all samples
+between `current_playback_position` and `current_playback_position` +
+`audio_write_duration`, as soon as they are available.
+
+`audio_write_duration` will be to `kSbPlayerWriteDurationLocal`
+kSbPlayerWriteDurationLocal when all audio configurations linked to `player` is
+local, or if there isn't any audio output. It will be set to
+`kSbPlayerWriteDurationRemote` kSbPlayerWriteDurationRemote for remote or
+wireless audio outputs, i.e. one of `kSbMediaAudioConnectorBluetooth`
+kSbMediaAudioConnectorBluetooth or `kSbMediaAudioConnectorRemote*`
+kSbMediaAudioConnectorRemote* .
+
+The app only guarantees to write `audio_write_duration` past
+`current_playback_position`, but the app is free to write more samples than
+that. So the platform shouldn't rely on this for flow control. The platform
+should achieve flow control by sending `kSbPlayerDecoderStateNeedsData`
+kSbPlayerDecoderStateNeedsData less frequently.
+
+The platform is responsible for guaranteeing that when only
+`audio_write_duration` audio samples are written at a time, no playback issues
+occur (such as transient or indefinite hanging).
+
+The audio configurations should be available as soon as possible, and they have
+to be available when the `player` is at `kSbPlayerStatePresenting`
+kSbPlayerStatePresenting , unless the audio codec is `kSbMediaAudioCodecNone` or
+there's no written audio inputs.
+
+The app will set `audio_write_duration` to `kSbPlayerWriteDurationLocal`
+kSbPlayerWriteDurationLocal when the audio configuration isn't available (i.e.
+the function returns false when index is 0). The platform has to make the audio
+configuration available immediately after the SbPlayer is created, if it expects
+the app to treat the platform as using wireless audio outputs.
+
+Once at least one audio configurations are returned, the return values and their
+orders shouldn't change during the life time of `player`. The platform may
+inform the app of any changes by sending `kSbPlayerErrorCapabilityChanged`
+kSbPlayerErrorCapabilityChanged to request a playback restart.
+
+`player`: The player about which information is being retrieved. Must not be
+`kSbPlayerInvalid`. `index`: The index of the audio output configuration. Must
+be greater than or equal to 0. `out_audio_configuration`: The information about
+the audio output, refer to `SbMediaAudioConfiguration` for more details. Must
+not be NULL.
+
+#### Declaration ####
+
+```
+bool SbPlayerGetAudioConfiguration(SbPlayer player, int index, SbMediaAudioConfiguration *out_audio_configuration)
+```
+
 ### SbPlayerGetCurrentFrame ###
 
 Given a player created with the kSbPlayerOutputModeDecodeToTexture output mode,
@@ -315,26 +387,14 @@
 with an output mode other than kSbPlayerOutputModeDecodeToTexture,
 kSbDecodeTargetInvalid is returned.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
 SbDecodeTarget SbPlayerGetCurrentFrame(SbPlayer player)
 ```
 
-### SbPlayerGetInfo2 ###
-
-Gets a snapshot of the current player state and writes it to `out_player_info`.
-This function may be called very frequently and is expected to be inexpensive.
-
-`player`: The player about which information is being retrieved.
-`out_player_info`: The information retrieved for the player.
-
-#### Declaration ####
-
-```
-void SbPlayerGetInfo2(SbPlayer player, SbPlayerInfo2 *out_player_info2)
-```
-
 ### SbPlayerGetMaximumNumberOfSamplesPerWrite ###
 
 Writes a single sample of the given media type to `player`'s input stream. Its
@@ -371,7 +431,7 @@
 the call. Note that it is not the responsibility of this function to verify
 whether the video described by `creation_param` can be played on the platform,
 and the implementation should try its best effort to return a valid output mode.
-`creation_param` will never be NULL.
+`creation_param` must not be NULL.
 
 #### Declaration ####
 
@@ -403,12 +463,12 @@
 implementors should take care to avoid related performance concerns with such
 frequent calls.
 
-`player`: The player that is being resized. `z_index`: The z-index of the
-player. When the bounds of multiple players are overlapped, the one with larger
-z-index will be rendered on top of the ones with smaller z-index. `x`: The
-x-coordinate of the upper-left corner of the player. `y`: The y-coordinate of
-the upper-left corner of the player. `width`: The width of the player, in
-pixels. `height`: The height of the player, in pixels.
+`player`: The player that is being resized. Must not be `kSbPlayerInvalid`.
+`z_index`: The z-index of the player. When the bounds of multiple players are
+overlapped, the one with larger z-index will be rendered on top of the ones with
+smaller z-index. `x`: The x-coordinate of the upper-left corner of the player.
+`y`: The y-coordinate of the upper-left corner of the player. `width`: The width
+of the player, in pixels. `height`: The height of the player, in pixels.
 
 #### Declaration ####
 
@@ -429,6 +489,8 @@
 unchanged, this can happen when `playback_rate` is negative or if it is too high
 to support.
 
+`player` must not be `kSbPlayerInvalid`.
+
 #### Declaration ####
 
 ```
@@ -439,10 +501,10 @@
 
 Sets the player's volume.
 
-`player`: The player in which the volume is being adjusted. `volume`: The new
-player volume. The value must be between `0.0` and `1.0`, inclusive. A value of
-`0.0` means that the audio should be muted, and a value of `1.0` means that it
-should be played at full volume.
+`player`: The player in which the volume is being adjusted. Must not be
+`kSbPlayerInvalid`. `volume`: The new player volume. The value must be between
+`0.0` and `1.0`, inclusive. A value of `0.0` means that the audio should be
+muted, and a value of `1.0` means that it should be played at full volume.
 
 #### Declaration ####
 
@@ -466,31 +528,20 @@
 void SbPlayerWriteEndOfStream(SbPlayer player, SbMediaType stream_type)
 ```
 
-### SbPlayerWriteSample2 ###
+### SbPlayerWriteSamples ###
 
-Writes samples of the given media type to `player`'s input stream. The lifetime
-of `sample_infos`, and the members of its elements like `buffer`,
-`video_sample_info`, and `drm_info` (as well as member `subsample_mapping`
-contained inside it) are not guaranteed past the call to SbPlayerWriteSample2.
-That means that before returning, the implementation must synchronously copy any
-information it wants to retain from those structures.
-
-SbPlayerWriteSample2 allows writing of multiple samples in one call.
-
-`player`: The player to which the sample is written. `sample_type`: The type of
-sample being written. See the `SbMediaType` enum in media.h. `sample_infos`: A
-pointer to an array of SbPlayerSampleInfo with `number_of_sample_infos`
-elements, each holds the data for an sample, i.e. a sequence of whole NAL Units
-for video, or a complete audio frame. `sample_infos` cannot be assumed to live
-past the call into SbPlayerWriteSample2(), so it must be copied if its content
-will be used after SbPlayerWriteSample2() returns. `number_of_sample_infos`:
-Specify the number of samples contained inside `sample_infos`. It has to be at
-least one, and less than the return value of
+`sample_type`: The type of sample being written. See the `SbMediaType` enum in
+media.h. `sample_infos`: A pointer to an array of SbPlayerSampleInfo with
+`number_of_sample_infos` elements, each holds the data for an sample, i.e. a
+sequence of whole NAL Units for video, or a complete audio frame. `sample_infos`
+cannot be assumed to live past the call into SbPlayerWriteSamples(), so it must
+be copied if its content will be used after SbPlayerWriteSamples() returns.
+`number_of_sample_infos`: Specify the number of samples contained inside
+`sample_infos`. It has to be at least one, and less than the return value of
 SbPlayerGetMaximumNumberOfSamplesPerWrite().
 
 #### Declaration ####
 
 ```
-void SbPlayerWriteSample2(SbPlayer player, SbMediaType sample_type, const SbPlayerSampleInfo *sample_infos, int number_of_sample_infos)
+void SbPlayerWriteSamples(SbPlayer player, SbMediaType sample_type, const SbPlayerSampleInfo *sample_infos, int number_of_sample_infos)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/socket.md b/cobalt/site/docs/reference/starboard/modules/socket.md
index 548f57d..9e0f81b 100644
--- a/cobalt/site/docs/reference/starboard/modules/socket.md
+++ b/cobalt/site/docs/reference/starboard/modules/socket.md
@@ -417,8 +417,8 @@
 the address is unnecessary, but allowed.
 
 `socket`: The SbSocket from which data is read. `out_data`: The data read from
-the socket. `data_size`: The number of bytes to read. `out_source`: The source
-address of the packet.
+the socket. Must not be NULL. `data_size`: The number of bytes to read.
+`out_source`: The source address of the packet.
 
 #### Declaration ####
 
@@ -456,10 +456,10 @@
 SbSocketGetLastError returns `kSbSocketPending` to make it a best-effort write
 (but still only up to not blocking, unless you want to spin).
 
-`socket`: The SbSocket to use to write data. `data`: The data read from the
-socket. `data_size`: The number of bytes of `data` to write. `destination`: The
-location to which data is written. This value must be `NULL` for TCP
-connections, which can only have a single endpoint.
+`socket`: The SbSocket to use to write data. `data`: The data written to the
+socket. Must not be NULL. `data_size`: The number of bytes of `data` to write.
+`destination`: The location to which data is written. This value must be `NULL`
+for TCP connections, which can only have a single endpoint.
 
 The primary use of `destination` is to send datagram packets, which can go out
 to multiple sources from a single UDP server socket. TCP has two endpoints
@@ -583,4 +583,3 @@
 ```
 bool SbSocketSetTcpWindowScaling(SbSocket socket, bool value)
 ```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/speech_recognizer.md b/cobalt/site/docs/reference/starboard/modules/speech_recognizer.md
deleted file mode 100644
index 0a1dc6b..0000000
--- a/cobalt/site/docs/reference/starboard/modules/speech_recognizer.md
+++ /dev/null
@@ -1,269 +0,0 @@
----
-layout: doc
-title: "Starboard Module Reference: speech_recognizer.h"
----
-
-Defines a streaming speech recognizer API. It provides access to the platform
-speech recognition service.
-
-Note that there can be only one speech recognizer. Attempting to create a second
-speech recognizer without destroying the first one will result in undefined
-behavior.
-
-`SbSpeechRecognizerCreate`, `SbSpeechRecognizerStart`, `SbSpeechRecognizerStop`,
-`SbSpeechRecognizerCancel` and `SbSpeechRecognizerDestroy` should be called from
-a single thread. Callbacks defined in `SbSpeechRecognizerHandler` will happen on
-another thread, so calls back into the SbSpeechRecognizer from the callback
-thread are disallowed.
-
-## Macros ##
-
-### kSbSpeechRecognizerInvalid ###
-
-Well-defined value for an invalid speech recognizer handle.
-
-## Enums ##
-
-### SbSpeechRecognizerError ###
-
-Indicates what has gone wrong with the recognition.
-
-#### Values ####
-
-*   `kSbNoSpeechError`
-
-    No speech was detected. Speech timed out.
-*   `kSbAborted`
-
-    Speech input was aborted somehow.
-*   `kSbAudioCaptureError`
-
-    Audio capture failed.
-*   `kSbNetworkError`
-
-    Some network communication that was required to complete the recognition
-    failed.
-*   `kSbNotAllowed`
-
-    The implementation is not allowing any speech input to occur for reasons of
-    security, privacy or user preference.
-*   `kSbServiceNotAllowed`
-
-    The implementation is not allowing the application requested speech service,
-    but would allow some speech service, to be used either because the
-    implementation doesn't support the selected one or because of reasons of
-    security, privacy or user preference.
-*   `kSbBadGrammar`
-
-    There was an error in the speech recognition grammar or semantic tags, or
-    the grammar format or semantic tag format is supported.
-*   `kSbLanguageNotSupported`
-
-    The language was not supported.
-
-## Typedefs ##
-
-### SbSpeechRecognizer ###
-
-An opaque handle to an implementation-private structure that represents a speech
-recognizer.
-
-#### Definition ####
-
-```
-typedef struct SbSpeechRecognizerPrivate* SbSpeechRecognizer
-```
-
-### SbSpeechRecognizerErrorFunction ###
-
-A function to notify that a speech recognition error occurred. `error`: The
-occurred speech recognition error.
-
-#### Definition ####
-
-```
-typedef void(* SbSpeechRecognizerErrorFunction) (void *context, SbSpeechRecognizerError error)
-```
-
-### SbSpeechRecognizerResultsFunction ###
-
-A function to notify that the recognition results are ready. `results`: the list
-of recognition results. `results_size`: the number of `results`. `is_final`:
-indicates if the `results` is final.
-
-#### Definition ####
-
-```
-typedef void(* SbSpeechRecognizerResultsFunction) (void *context, SbSpeechResult *results, int results_size, bool is_final)
-```
-
-### SbSpeechRecognizerSpeechDetectedFunction ###
-
-A function to notify that the user has started to speak or stops speaking.
-`detected`: true if the user has started to speak, and false if the user stops
-speaking.
-
-#### Definition ####
-
-```
-typedef void(* SbSpeechRecognizerSpeechDetectedFunction) (void *context, bool detected)
-```
-
-## Structs ##
-
-### SbSpeechConfiguration ###
-
-#### Members ####
-
-*   `bool continuous`
-
-    When the continuous value is set to false, the implementation MUST return no
-    more than one final result in response to starting recognition. When the
-    continuous attribute is set to true, the implementation MUST return zero or
-    more final results representing multiple consecutive recognitions in
-    response to starting recognition. This attribute setting does not affect
-    interim results.
-*   `bool interim_results`
-
-    Controls whether interim results are returned. When set to true, interim
-    results SHOULD be returned. When set to false, interim results MUST NOT be
-    returned. This value setting does not affect final results.
-*   `int max_alternatives`
-
-    This sets the maximum number of SbSpeechResult in
-    `SbSpeechRecognizerOnResults` callback.
-
-### SbSpeechRecognizerHandler ###
-
-Allows receiving notifications from the device when recognition related events
-occur.
-
-The void* context is passed to every function.
-
-#### Members ####
-
-*   `SbSpeechRecognizerSpeechDetectedFunction on_speech_detected`
-
-    Function to notify the beginning/end of the speech.
-*   `SbSpeechRecognizerErrorFunction on_error`
-
-    Function to notify the speech error.
-*   `SbSpeechRecognizerResultsFunction on_results`
-
-    Function to notify that the recognition results are available.
-*   `void * context`
-
-    This is passed to handler functions as first argument.
-
-### SbSpeechResult ###
-
-The recognition response that is received from the recognizer.
-
-#### Members ####
-
-*   `char * transcript`
-
-    The raw words that the user spoke.
-*   `float confidence`
-
-    A numeric estimate between 0 and 1 of how confident the recognition system
-    is that the recognition is correct. A higher number means the system is more
-    confident. NaN represents an unavailable confidence score.
-
-## Functions ##
-
-### SbSpeechRecognizerCancel ###
-
-Cancels speech recognition. The speech recognizer stops listening to audio and
-does not return any information. When `SbSpeechRecognizerCancel` is called, the
-implementation MUST NOT collect additional audio, MUST NOT continue to listen to
-the user, and MUST stop recognizing. This is important for privacy reasons. If
-`SbSpeechRecognizerCancel` is called on a speech recognizer which is already
-stopped or cancelled, the implementation MUST ignore the call.
-
-#### Declaration ####
-
-```
-void SbSpeechRecognizerCancel(SbSpeechRecognizer recognizer)
-```
-
-### SbSpeechRecognizerCreate ###
-
-Creates a speech recognizer with a speech recognizer handler.
-
-If the system has a speech recognition service available, this function returns
-the newly created handle.
-
-If no speech recognition service is available on the device, this function
-returns `kSbSpeechRecognizerInvalid`.
-
-`SbSpeechRecognizerCreate` does not expect the passed SbSpeechRecognizerHandler
-structure to live after `SbSpeechRecognizerCreate` is called, so the
-implementation must copy the contents if necessary.
-
-#### Declaration ####
-
-```
-SbSpeechRecognizer SbSpeechRecognizerCreate(const SbSpeechRecognizerHandler *handler)
-```
-
-### SbSpeechRecognizerDestroy ###
-
-Destroys the given speech recognizer. If the speech recognizer is in the started
-state, it is first stopped and then destroyed.
-
-#### Declaration ####
-
-```
-void SbSpeechRecognizerDestroy(SbSpeechRecognizer recognizer)
-```
-
-### SbSpeechRecognizerIsSupported ###
-
-Returns whether the platform supports SbSpeechRecognizer.
-
-#### Declaration ####
-
-```
-bool SbSpeechRecognizerIsSupported()
-```
-
-### SbSpeechRecognizerIsValid ###
-
-Indicates whether the given speech recognizer is valid.
-
-#### Declaration ####
-
-```
-static bool SbSpeechRecognizerIsValid(SbSpeechRecognizer recognizer)
-```
-
-### SbSpeechRecognizerStart ###
-
-Starts listening to audio and recognizing speech with the specified speech
-configuration. If `SbSpeechRecognizerStart` is called on an already started
-speech recognizer, the implementation MUST ignore the call and return false.
-
-Returns whether the speech recognizer is started successfully.
-
-#### Declaration ####
-
-```
-bool SbSpeechRecognizerStart(SbSpeechRecognizer recognizer, const SbSpeechConfiguration *configuration)
-```
-
-### SbSpeechRecognizerStop ###
-
-Stops listening to audio and returns a result using just the audio that it has
-already received. Once `SbSpeechRecognizerStop` is called, the implementation
-MUST NOT collect additional audio and MUST NOT continue to listen to the user.
-This is important for privacy reasons. If `SbSpeechRecognizerStop` is called on
-a speech recognizer which is already stopped or being stopped, the
-implementation MUST ignore the call.
-
-#### Declaration ####
-
-```
-void SbSpeechRecognizerStop(SbSpeechRecognizer recognizer)
-```
-
diff --git a/cobalt/site/docs/reference/starboard/modules/system.md b/cobalt/site/docs/reference/starboard/modules/system.md
index b4800a6..32fd303 100644
--- a/cobalt/site/docs/reference/starboard/modules/system.md
+++ b/cobalt/site/docs/reference/starboard/modules/system.md
@@ -26,43 +26,6 @@
     only if) a system has this capability will SbSystemGetTotalGPUMemory() and
     SbSystemGetUsedGPUMemory() be valid to call.
 
-### SbSystemDeviceType ###
-
-Enumeration of device types.
-
-#### Values ####
-
-*   `kSbSystemDeviceTypeBlueRayDiskPlayer`
-
-    Blue-ray Disc Player (BDP).
-*   `kSbSystemDeviceTypeGameConsole`
-
-    A relatively high-powered TV device used primarily for playing games.
-*   `kSbSystemDeviceTypeOverTheTopBox`
-
-    Over the top (OTT) devices stream content via the Internet over another type
-    of network, e.g. cable or satellite.
-*   `kSbSystemDeviceTypeSetTopBox`
-
-    Set top boxes (STBs) stream content primarily over cable or satellite. Some
-    STBs can also stream OTT content via the Internet.
-*   `kSbSystemDeviceTypeTV`
-
-    A Smart TV is a TV that can directly run applications that stream OTT
-    content via the Internet.
-*   `kSbSystemDeviceTypeDesktopPC`
-
-    Desktop PC.
-*   `kSbSystemDeviceTypeAndroidTV`
-
-    An Android TV Device.
-*   `kSbSystemDeviceTypeVideoProjector`
-
-    A wall video projector.
-*   `kSbSystemDeviceTypeUnknown`
-
-    Unknown device.
-
 ### SbSystemPathId ###
 
 Enumeration of special paths that the platform can define.
@@ -98,9 +61,10 @@
     Full path to the executable file.
 *   `kSbSystemPathStorageDirectory`
 
-    Path to a directory for permanent file storage. Both read and write access
-    is required. This is where an app may store its persistent settings. The
-    location should be user agnostic if possible.
+    Path to the directory dedicated for Evergreen Full permanent file storage.
+    Both read and write access is required. The directory should be used only
+    for storing the updates. See
+    starboard/doc/evergreen/cobalt_evergreen_overview.md
 
 ### SbSystemPlatformErrorResponse ###
 
@@ -187,6 +151,10 @@
 
     Limit advertising tracking, treated as boolean. Set to nonzero to indicate a
     true value. Corresponds to 'lmt' field.
+*   `kSbSystemPropertyDeviceType`
+
+    Type of the device, e.g. such as "TV", "STB", "OTT" Please see Youtube
+    Technical requirements for a full list of allowed values
 
 ## Typedefs ##
 
@@ -256,16 +224,6 @@
 void SbSystemClearLastError()
 ```
 
-### SbSystemGetDeviceType ###
-
-Returns the type of the device.
-
-#### Declaration ####
-
-```
-SbSystemDeviceType SbSystemGetDeviceType()
-```
-
 ### SbSystemGetErrorString ###
 
 Generates a human-readable string for an error. The return value specifies the
@@ -284,7 +242,8 @@
 ### SbSystemGetExtension ###
 
 Returns pointer to a constant global struct implementing the extension named
-`name`, if it is implemented. Otherwise return NULL.
+`name`, if it is implemented. Otherwise return NULL. The `name` string must not
+be NULL.
 
 Extensions are used to implement behavior which is specific to the combination
 of application & platform. An extension relies on a header file in the
@@ -667,7 +626,7 @@
 ### SbSystemSignWithCertificationSecretKey ###
 
 Computes a HMAC-SHA256 digest of `message` into `digest` using the application's
-certification secret.
+certification secret. The `message` and the `digest` pointers must not be NULL.
 
 The output will be written into `digest`. `digest_size_in_bytes` must be 32 (or
 greater), since 32-bytes will be written into it. Returns false in the case of
diff --git a/cobalt/site/docs/reference/starboard/modules/ui_navigation.md b/cobalt/site/docs/reference/starboard/modules/ui_navigation.md
index e5f533b..a0ecfb1 100644
--- a/cobalt/site/docs/reference/starboard/modules/ui_navigation.md
+++ b/cobalt/site/docs/reference/starboard/modules/ui_navigation.md
@@ -101,8 +101,10 @@
     This is used to manually force focus on a navigation item of type
     kSbUiNavItemTypeFocus. Any previously focused navigation item should receive
     the blur event. If the item is not transitively a content of the root item,
-    then this does nothing. Specifying kSbUiNavItemInvalid should remove focus
-    from the UI navigation system.
+    then this does nothing.
+
+    Specifying kSbUiNavItemInvalid should remove focus from the UI navigation
+    system.
 *   `void(*set_item_enabled)(SbUiNavItem item, bool enabled)`
 
     This is used to enable or disable user interaction with the specified
@@ -116,7 +118,9 @@
 
     This specifies directionality for container items. Containers within
     containers do not inherit directionality. Directionality must be specified
-    for each container explicitly. This should work even if `item` is disabled.
+    for each container explicitly.
+
+    This should work even if `item` is disabled.
 *   `void(*set_item_focus_duration)(SbUiNavItem item, float seconds)`
 
     Set the minimum amount of time the focus item should remain focused once it
@@ -158,13 +162,16 @@
 
     This attaches the given navigation item (which must be a container) to the
     specified window. Navigation items are only interactable if they are
-    transitively attached to a window.The native UI engine should never change
-    this navigation item's content offset. It is assumed to be used as a proxy
-    for the system window.A navigation item may only have a SbUiNavItem or
-    SbWindow as its direct container. The navigation item hierarchy is
-    established using set_item_container_item() with the root container attached
-    to a SbWindow using set_item_container_window() to enable interaction with
-    all enabled items in the hierarchy.
+    transitively attached to a window.
+
+    The native UI engine should never change this navigation item's content
+    offset. It is assumed to be used as a proxy for the system window.
+
+    A navigation item may only have a SbUiNavItem or SbWindow as its direct
+    container. The navigation item hierarchy is established using
+    set_item_container_item() with the root container attached to a SbWindow
+    using set_item_container_window() to enable interaction with all enabled
+    items in the hierarchy.
 
     If `item` is already registered with a different window, then this will
     unregister it from that window then attach it to the given `window`. It is
@@ -195,13 +202,14 @@
     drawn at position (5,15).
 
     Essentially, content items should be drawn at: [container position] +
-    [content position] - [container content offset] Content items may overlap
-    within a container. This can cause obscured items to be unfocusable. The
-    only rule that needs to be followed is that contents which are focus items
-    can obscure other contents which are containers, but not vice versa. The
-    caller must ensure that content focus items do not overlap other content
-    focus items and content container items do not overlap other content
-    container items.
+    [content position] - [container content offset]
+
+    Content items may overlap within a container. This can cause obscured items
+    to be unfocusable. The only rule that needs to be followed is that contents
+    which are focus items can obscure other contents which are containers, but
+    not vice versa. The caller must ensure that content focus items do not
+    overlap other content focus items and content container items do not overlap
+    other content container items.
 *   `void(*set_item_content_offset)(SbUiNavItem item, float content_offset_x,
     float content_offset_y)`
 
@@ -211,17 +219,19 @@
     Essentially, a content item should be drawn at: [container position] +
     [content position] - [container content offset] If `item` is not a
     container, then this does nothing. By default, the content offset is (0,0).
+
     This should update the values returned by get_item_content_offset() even if
     the `item` is disabled.
 *   `void(*get_item_content_offset)(SbUiNavItem item, float
     *out_content_offset_x, float *out_content_offset_y)`
 
     Retrieve the current content offset for the navigation item. If `item` is
-    not a container, then the content offset is (0,0). The native UI engine
-    should not change the content offset of a container unless one of its
-    contents (possibly recursively) is focused. This is to allow seamlessly
-    disabling then re-enabling focus items without having their containers
-    change offsets.
+    not a container, then the content offset is (0,0).
+
+    The native UI engine should not change the content offset of a container
+    unless one of its contents (possibly recursively) is focused. This is to
+    allow seamlessly disabling then re-enabling focus items without having their
+    containers change offsets.
 *   `void(*do_batch_update)(void(*update_function)(void *), void *context)`
 
     Call `update_function` with `context` to perform a series of UI navigation
@@ -252,7 +262,7 @@
 ///     | Negative position. | Positive position. | Positive position. |
 ///     +--------------------+--------------------+--------------------+
 ///                          ^
-///                  Content Offset X = 0. 
+///                  Content Offset X = 0.
 ```
 
 ```
@@ -271,7 +281,7 @@
 
 ```
 ///   | a b tx |
-///   | c d ty | 
+///   | c d ty |
 ```
 
 #### Members ####
@@ -292,7 +302,8 @@
 
 Retrieve the platform's UI navigation implementation. If the platform does not
 provide one, then return false without modifying `out_interface`. Otherwise,
-initialize all members of `out_interface` and return true.
+initialize all members of `out_interface` and return true. The `out_interface`
+pointer must not be NULL.
 
 #### Declaration ####
 
@@ -309,4 +320,3 @@
 ```
 static bool SbUiNavItemIsValid(SbUiNavItem item)
 ```
-
diff --git a/cobalt/storage/savegame_thread.cc b/cobalt/storage/savegame_thread.cc
index f645ca6..bb0d670 100644
--- a/cobalt/storage/savegame_thread.cc
+++ b/cobalt/storage/savegame_thread.cc
@@ -12,10 +12,11 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-#include <memory>
-
 #include "cobalt/storage/savegame_thread.h"
 
+#include <memory>
+#include <utility>
+
 #include "base/bind.h"
 #include "base/message_loop/message_loop.h"
 #include "base/trace_event/trace_event.h"
@@ -43,12 +44,14 @@
 
 SavegameThread::~SavegameThread() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  // Wait for all tasks to finish.
-  thread_->message_loop()->task_runner()->PostBlockingTask(
-      FROM_HERE,
-      base::Bind(&SavegameThread::ShutdownOnIOThread, base::Unretained(this)));
 
-  thread_.reset();
+  if (thread_) {
+    // Wait for all previously posted tasks to finish.
+    thread_->message_loop()->task_runner()->WaitForFence();
+    // This will trigger a call to WillDestroyCurrentMessageLoop in the thread
+    // and wait for it to finish.
+    thread_.reset();
+  }
 }
 
 std::unique_ptr<Savegame::ByteVector> SavegameThread::GetLoadedRawBytes() {
@@ -79,7 +82,8 @@
 
 void SavegameThread::InitializeOnIOThread() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK_EQ(thread_->message_loop(), base::MessageLoop::current());
+  DCHECK(thread_->message_loop()->task_runner()->RunsTasksInCurrentSequence());
+  base::MessageLoopCurrent::Get()->AddDestructionObserver(this);
 
   // Create a savegame object on the storage I/O thread.
   savegame_ = options_.CreateSavegame();
@@ -92,18 +96,18 @@
   initialized_.Signal();
 }
 
-void SavegameThread::ShutdownOnIOThread() {
+void SavegameThread::WillDestroyCurrentMessageLoop() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK_EQ(thread_->message_loop(), base::MessageLoop::current());
   // Ensure these objects are destroyed on the proper thread.
-  savegame_.reset(NULL);
+  savegame_.reset();
+  loaded_raw_bytes_.reset();
 }
 
 void SavegameThread::FlushOnIOThread(
     std::unique_ptr<Savegame::ByteVector> raw_bytes_ptr,
     const base::Closure& on_flush_complete) {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK_EQ(thread_->message_loop(), base::MessageLoop::current());
+  DCHECK(thread_->message_loop()->task_runner()->RunsTasksInCurrentSequence());
   if (raw_bytes_ptr->size() > 0) {
     bool ret = savegame_->Write(*raw_bytes_ptr);
     if (ret) {
diff --git a/cobalt/storage/savegame_thread.h b/cobalt/storage/savegame_thread.h
index c969c82..dc5249f 100644
--- a/cobalt/storage/savegame_thread.h
+++ b/cobalt/storage/savegame_thread.h
@@ -27,7 +27,7 @@
 
 // The SavegameThread wraps a Savegame object within its own thread in order to
 // enable asynchronous writes to the savegame object.
-class SavegameThread {
+class SavegameThread : public base::MessageLoop::DestructionObserver {
  public:
   explicit SavegameThread(const Savegame::Options& options);
   ~SavegameThread();
@@ -44,13 +44,12 @@
              const base::Closure& on_flush_complete);
 
  private:
+  // From base::MessageLoop::DestructionObserver.
+  void WillDestroyCurrentMessageLoop() override;
+
   // Run on the I/O thread to start loading the savegame.
   void InitializeOnIOThread();
 
-  // Called by the destructor, to ensure we destroy certain objects on the
-  // I/O thread.
-  void ShutdownOnIOThread();
-
   // Runs on the I/O thread to write the database to the savegame's persistent
   // storage.
   void FlushOnIOThread(std::unique_ptr<Savegame::ByteVector> raw_bytes_ptr,
diff --git a/cobalt/storage/storage_manager.cc b/cobalt/storage/storage_manager.cc
index b1a1889..e3a278e 100644
--- a/cobalt/storage/storage_manager.cc
+++ b/cobalt/storage/storage_manager.cc
@@ -38,7 +38,6 @@
 StorageManager::StorageManager(const Options& options)
     : options_(options),
       storage_thread_(new base::Thread("StorageManager")),
-      memory_store_(new MemoryStore()),
       loaded_database_version_(0),
       initialized_(false),
       flush_processing_(false),
@@ -47,38 +46,45 @@
                           base::WaitableEvent::InitialState::SIGNALED) {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
 
-  savegame_thread_.reset(new SavegameThread(options_.savegame_options));
-
   // Start the savegame load immediately.
   storage_thread_->Start();
   storage_task_runner_ = storage_thread_->task_runner();
   DCHECK(storage_task_runner_);
 
+  storage_task_runner_->PostTask(
+      FROM_HERE, base::Bind(&StorageManager::InitializeTaskInThread,
+                            base::Unretained(this)));
+}
+
+void StorageManager::InitializeTaskInThread() {
+  DCHECK(storage_task_runner_->RunsTasksInCurrentSequence());
+  base::MessageLoopCurrent::Get()->AddDestructionObserver(this);
+
+  memory_store_.reset(new MemoryStore());
+  savegame_thread_.reset(new SavegameThread(options_.savegame_options));
+
   flush_on_last_change_timer_.reset(new base::OneShotTimer());
   flush_on_change_max_delay_timer_.reset(new base::OneShotTimer());
 }
 
 StorageManager::~StorageManager() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(!storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(!storage_task_runner_->RunsTasksInCurrentSequence());
 
   // Wait for all I/O operations to complete.
   FinishIO();
 
-  // Destroy various objects on the proper thread.
-  storage_task_runner_->PostTask(
-      FROM_HERE,
-      base::Bind(&StorageManager::OnDestroy, base::Unretained(this)));
-
-  // Force all tasks to finish. Then we can safely let the rest of our
-  // member variables be destroyed.
+  // Wait for all previously posted tasks to finish.
+  storage_thread_->message_loop()->task_runner()->WaitForFence();
+  // This will trigger a call to WillDestroyCurrentMessageLoop in the thread and
+  // wait for it to finish.
   storage_thread_.reset();
 }
 
 void StorageManager::WithReadOnlyMemoryStore(
     const ReadOnlyMemoryStoreCallback& callback) {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  if (!storage_task_runner_->BelongsToCurrentThread()) {
+  if (!storage_task_runner_->RunsTasksInCurrentSequence()) {
     storage_task_runner_->PostTask(
         FROM_HERE, base::Bind(&StorageManager::WithReadOnlyMemoryStore,
                               base::Unretained(this), callback));
@@ -90,7 +96,7 @@
 
 void StorageManager::WithMemoryStore(const MemoryStoreCallback& callback) {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  if (!storage_task_runner_->BelongsToCurrentThread()) {
+  if (!storage_task_runner_->RunsTasksInCurrentSequence()) {
     storage_task_runner_->PostTask(
         FROM_HERE, base::Bind(&StorageManager::WithMemoryStore,
                               base::Unretained(this), callback));
@@ -104,7 +110,7 @@
 void StorageManager::FlushOnChange() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
   // Make sure this runs on the correct thread.
-  if (!storage_task_runner_->BelongsToCurrentThread()) {
+  if (!storage_task_runner_->RunsTasksInCurrentSequence()) {
     storage_task_runner_->PostTask(
         FROM_HERE,
         base::Bind(&StorageManager::FlushOnChange, base::Unretained(this)));
@@ -131,7 +137,7 @@
 void StorageManager::FlushNow(base::OnceClosure callback) {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
   // Make sure this runs on the correct thread.
-  if (!storage_task_runner_->BelongsToCurrentThread()) {
+  if (!storage_task_runner_->RunsTasksInCurrentSequence()) {
     storage_task_runner_->PostTask(
         FROM_HERE, base::Bind(&StorageManager::FlushNow, base::Unretained(this),
                               base::Passed(&callback)));
@@ -142,9 +148,21 @@
   QueueFlush(std::move(callback));
 }
 
+// Triggers a write to disk to happen immediately and doesn't return until the
+// I/O has completed.
+void StorageManager::FlushSynchronous() {
+  base::WaitableEvent flush_finished = {
+      base::WaitableEvent::ResetPolicy::MANUAL,
+      base::WaitableEvent::InitialState::NOT_SIGNALED};
+  FlushNow(base::Bind(
+      [](base::WaitableEvent* flush_finished) { flush_finished->Signal(); },
+      base::Unretained(&flush_finished)));
+  flush_finished.Wait();
+}
+
 void StorageManager::FinishInit() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(storage_task_runner_->RunsTasksInCurrentSequence());
   if (initialized_) {
     return;
   }
@@ -177,7 +195,7 @@
 
 void StorageManager::OnFlushOnChangeTimerFired() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(storage_task_runner_->RunsTasksInCurrentSequence());
 
   StopFlushOnChangeTimers();
   QueueFlush(base::Closure());
@@ -186,7 +204,7 @@
 void StorageManager::OnFlushIOCompletedCallback() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
   // Make sure this runs on the SQL message loop.
-  if (!storage_task_runner_->BelongsToCurrentThread()) {
+  if (!storage_task_runner_->RunsTasksInCurrentSequence()) {
     storage_task_runner_->PostTask(
         FROM_HERE, base::Bind(&StorageManager::OnFlushIOCompletedCallback,
                               base::Unretained(this)));
@@ -216,7 +234,7 @@
 
 void StorageManager::QueueFlush(base::OnceClosure callback) {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(storage_task_runner_->RunsTasksInCurrentSequence());
 
   if (!flush_processing_) {
     // If no flush is currently in progress, flush immediately.
@@ -237,7 +255,7 @@
 
 void StorageManager::FlushInternal() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(storage_task_runner_->RunsTasksInCurrentSequence());
   FinishInit();
 
   flush_processing_ = true;
@@ -259,7 +277,7 @@
 
 void StorageManager::FinishIO() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(!storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(!storage_task_runner_->RunsTasksInCurrentSequence());
 
   // Make sure that the on change timers fire if they're running.
   storage_task_runner_->PostTask(
@@ -286,7 +304,7 @@
 
 void StorageManager::FireRunningOnChangeTimers() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(storage_task_runner_->BelongsToCurrentThread());
+  DCHECK(storage_task_runner_->RunsTasksInCurrentSequence());
 
   if (flush_on_last_change_timer_->IsRunning() ||
       flush_on_change_max_delay_timer_->IsRunning()) {
@@ -294,10 +312,8 @@
   }
 }
 
-void StorageManager::OnDestroy() {
+void StorageManager::WillDestroyCurrentMessageLoop() {
   TRACE_EVENT0("cobalt::storage", __FUNCTION__);
-  DCHECK(storage_task_runner_->BelongsToCurrentThread());
-
   // Stop the savegame thread and have it wrap up any pending I/O operations.
   savegame_thread_.reset();
 
diff --git a/cobalt/storage/storage_manager.h b/cobalt/storage/storage_manager.h
index b9d63f1..ff49a6d 100644
--- a/cobalt/storage/storage_manager.h
+++ b/cobalt/storage/storage_manager.h
@@ -39,7 +39,7 @@
 // or WithMemoryStore(). The callback to will run on the store thread.
 // Operations on MemoryStore will block the store thread until the savegame
 // is loaded.
-class StorageManager {
+class StorageManager : public base::MessageLoop::DestructionObserver {
  public:
   struct Options {
     Savegame::Options savegame_options;
@@ -65,7 +65,11 @@
   // |callback|, if provided, will be called when the I/O has completed,
   // and will be run on the storage manager's IO thread.
   // This call returns immediately.
-  void FlushNow(base::OnceClosure callback);
+  void FlushNow(base::OnceClosure callback = base::Closure());
+
+  // Triggers a write to disk to happen immediately and doesn't return until the
+  // I/O has completed.
+  void FlushSynchronous();
 
   const Options& options() const { return options_; }
 
@@ -83,6 +87,10 @@
   virtual void QueueFlush(base::OnceClosure callback);
 
  private:
+  // Called by the constructor to create the private implementation object and
+  // perform any other initialization required on the dedicated thread.
+  void InitializeTaskInThread();
+
   // Give StorageManagerTest access, so we can more easily test some internals.
   friend class StorageManagerTest;
 
@@ -112,9 +120,9 @@
   // This function will immediately the on change timers if they are running.
   void FireRunningOnChangeTimers();
 
-  // Called by the destructor, to ensure we destroy certain objects on the
-  // store thread
-  void OnDestroy();
+  // Ensure that we destroy certain objects on the store thread.
+  // From base::MessageLoop::DestructionObserver.
+  void WillDestroyCurrentMessageLoop() override;
 
   // Configuration options for the Storage Manager.
   Options options_;
diff --git a/cobalt/updater/network_fetcher.cc b/cobalt/updater/network_fetcher.cc
index 2f0019e..0f4887e 100644
--- a/cobalt/updater/network_fetcher.cc
+++ b/cobalt/updater/network_fetcher.cc
@@ -189,7 +189,8 @@
 
   url_fetcher_->SetRequestContext(
       network_module_->url_request_context_getter().get());
-  network_module_->AddClientHintHeaders(*url_fetcher_);
+  network_module_->AddClientHintHeaders(*url_fetcher_,
+                                        network::kCallTypeUpdater);
 
   // Request mode is kCORSModeOmitCredentials.
   const uint32 kDisableCookiesAndCacheLoadFlags =
diff --git a/cobalt/updater/unzipper.cc b/cobalt/updater/unzipper.cc
index 1855b3a..22d6423 100644
--- a/cobalt/updater/unzipper.cc
+++ b/cobalt/updater/unzipper.cc
@@ -14,7 +14,9 @@
 
 #include "cobalt/updater/unzipper.h"
 
+#include <string>
 #include <utility>
+
 #include "base/callback.h"
 #include "base/files/file_path.h"
 #include "starboard/time.h"
@@ -40,6 +42,20 @@
     LOG(INFO) << "Unzip took " << time_unzip_took / kSbTimeMillisecond
               << " milliseconds.";
   }
+
+#if defined(IN_MEMORY_UPDATES)
+  void Unzip(const std::string& zip_str, const base::FilePath& output_path,
+             UnzipCompleteCallback callback) override {
+    SbTimeMonotonic time_before_unzip = SbTimeGetMonotonicNow();
+    std::move(callback).Run(zip::Unzip(zip_str, output_path));
+    SbTimeMonotonic time_unzip_took =
+        SbTimeGetMonotonicNow() - time_before_unzip;
+    LOG(INFO) << "Unzip from string";
+    LOG(INFO) << "output_path = " << output_path;
+    LOG(INFO) << "Unzip took " << time_unzip_took / kSbTimeMillisecond
+              << " milliseconds.";
+  }
+#endif
 };
 
 }  // namespace
diff --git a/cobalt/web/agent.cc b/cobalt/web/agent.cc
index 4341600..4efb0a4 100644
--- a/cobalt/web/agent.cc
+++ b/cobalt/web/agent.cc
@@ -38,7 +38,7 @@
 #include "cobalt/web/url.h"
 #include "cobalt/web/window_or_worker_global_scope.h"
 #include "cobalt/worker/service_worker.h"
-#include "cobalt/worker/service_worker_jobs.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_object.h"
 #include "cobalt/worker/service_worker_registration.h"
 #include "cobalt/worker/service_worker_registration_object.h"
@@ -91,8 +91,8 @@
     DCHECK(fetcher_factory_);
     return fetcher_factory_->network_module();
   }
-  worker::ServiceWorkerJobs* service_worker_jobs() const final {
-    return service_worker_jobs_;
+  worker::ServiceWorkerContext* service_worker_context() const final {
+    return service_worker_context_;
   }
 
   const std::string& name() const final { return name_; };
@@ -217,7 +217,7 @@
   std::map<worker::ServiceWorkerObject*, scoped_refptr<worker::ServiceWorker>>
       service_worker_object_map_;
 
-  worker::ServiceWorkerJobs* service_worker_jobs_;
+  worker::ServiceWorkerContext* service_worker_context_;
   const web::UserAgentPlatformInfo* platform_info_;
 
   // https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-active-service-worker
@@ -250,7 +250,7 @@
 Impl::Impl(const std::string& name, const Agent::Options& options)
     : name_(name), web_settings_(options.web_settings) {
   TRACE_EVENT0("cobalt::web", "Agent::Impl::Impl()");
-  service_worker_jobs_ = options.service_worker_jobs;
+  service_worker_context_ = options.service_worker_context;
   platform_info_ = options.platform_info;
   blob_registry_.reset(new Blob::Registry);
 
@@ -352,11 +352,9 @@
   }
 #endif
 
-  if (service_worker_jobs_) {
-    service_worker_jobs_->RegisterWebContext(this);
-  }
-  if (service_worker_jobs_) {
-    service_worker_jobs_->SetActiveWorker(environment_settings_.get());
+  if (service_worker_context_) {
+    service_worker_context_->RegisterWebContext(this);
+    service_worker_context_->SetActiveWorker(environment_settings_.get());
   }
 }
 
@@ -533,12 +531,14 @@
   DCHECK(message_loop());
   DCHECK(thread_.IsRunning());
 
-  if (context() && context()->service_worker_jobs()) {
-    context()->service_worker_jobs()->UnregisterWebContext(context());
+  if (context() && context()->service_worker_context()) {
+    context()->service_worker_context()->UnregisterWebContext(context());
   }
 
   // Ensure that the destruction observer got added before stopping the thread.
   destruction_observer_added_.Wait();
+  // Wait for all previously posted tasks to finish.
+  thread_.message_loop()->task_runner()->WaitForFence();
   // Stop the thread. This will cause the destruction observer to be notified.
   thread_.Stop();
 }
diff --git a/cobalt/web/agent.h b/cobalt/web/agent.h
index d57d526..091cee0 100644
--- a/cobalt/web/agent.h
+++ b/cobalt/web/agent.h
@@ -34,7 +34,7 @@
 
 namespace cobalt {
 namespace worker {
-class ServiceWorkerJobs;
+class ServiceWorkerContext;
 }
 namespace web {
 
@@ -69,7 +69,7 @@
     base::Callback<int(const std::string&, std::unique_ptr<char[]>*)>
         read_cache_callback;
 
-    worker::ServiceWorkerJobs* service_worker_jobs = nullptr;
+    worker::ServiceWorkerContext* service_worker_context = nullptr;
 
     const UserAgentPlatformInfo* platform_info = nullptr;
   };
diff --git a/cobalt/web/cobalt_ua_data_values.idl b/cobalt/web/cobalt_ua_data_values.idl
index 399651a..eef1fa0 100644
--- a/cobalt/web/cobalt_ua_data_values.idl
+++ b/cobalt/web/cobalt_ua_data_values.idl
@@ -22,8 +22,8 @@
   DOMString evergreenType;
   DOMString evergreenFileType;
   DOMString evergreenVersion;
-  DOMString firmwareVersionDetails;
-  DOMString osExperience;
+  DOMString androidBuildFingerprint;
+  DOMString androidOsExperience;
   DOMString starboardVersion;
   DOMString originalDesignManufacturer;
   DOMString deviceType;
diff --git a/cobalt/web/cobalt_ua_data_values_interface.cc b/cobalt/web/cobalt_ua_data_values_interface.cc
index 47e23dd..ac4a9c0 100644
--- a/cobalt/web/cobalt_ua_data_values_interface.cc
+++ b/cobalt/web/cobalt_ua_data_values_interface.cc
@@ -67,11 +67,11 @@
   if (init_dict.has_evergreen_version()) {
     evergreen_version_ = init_dict.evergreen_version();
   }
-  if (init_dict.has_firmware_version_details()) {
-    firmware_version_details_ = init_dict.firmware_version_details();
+  if (init_dict.has_android_build_fingerprint()) {
+    android_build_fingerprint_ = init_dict.android_build_fingerprint();
   }
-  if (init_dict.has_os_experience()) {
-    os_experience_ = init_dict.os_experience();
+  if (init_dict.has_android_os_experience()) {
+    android_os_experience_ = init_dict.android_os_experience();
   }
   if (init_dict.has_starboard_version()) {
     starboard_version_ = init_dict.starboard_version();
diff --git a/cobalt/web/cobalt_ua_data_values_interface.h b/cobalt/web/cobalt_ua_data_values_interface.h
index 81dcc70..22599ff 100644
--- a/cobalt/web/cobalt_ua_data_values_interface.h
+++ b/cobalt/web/cobalt_ua_data_values_interface.h
@@ -48,10 +48,12 @@
     return evergreen_file_type_;
   }
   const std::string& evergreen_version() const { return evergreen_version_; }
-  const std::string& firmware_version_details() const {
-    return firmware_version_details_;
+  const std::string& android_build_fingerprint() const {
+    return android_build_fingerprint_;
   }
-  const std::string& os_experience() const { return os_experience_; }
+  const std::string& android_os_experience() const {
+    return android_os_experience_;
+  }
   const std::string& starboard_version() const { return starboard_version_; }
   const std::string& original_design_manufacturer() const {
     return original_design_manufacturer_;
@@ -83,8 +85,8 @@
   std::string evergreen_type_;
   std::string evergreen_file_type_;
   std::string evergreen_version_;
-  std::string firmware_version_details_;
-  std::string os_experience_;
+  std::string android_build_fingerprint_;
+  std::string android_os_experience_;
   std::string starboard_version_;
   std::string original_design_manufacturer_;
   std::string device_type_;
diff --git a/cobalt/web/cobalt_ua_data_values_interface.idl b/cobalt/web/cobalt_ua_data_values_interface.idl
index fc670c2..b7ce634 100644
--- a/cobalt/web/cobalt_ua_data_values_interface.idl
+++ b/cobalt/web/cobalt_ua_data_values_interface.idl
@@ -32,8 +32,8 @@
   readonly attribute DOMString evergreenType;
   readonly attribute DOMString evergreenFileType;
   readonly attribute DOMString evergreenVersion;
-  readonly attribute DOMString firmwareVersionDetails;
-  readonly attribute DOMString osExperience;
+  readonly attribute DOMString androidBuildFingerprint;
+  readonly attribute DOMString androidOsExperience;
   readonly attribute DOMString starboardVersion;
   readonly attribute DOMString originalDesignManufacturer;
   readonly attribute DOMString deviceType;
diff --git a/cobalt/web/context.h b/cobalt/web/context.h
index 3fdf42c..b8fc450 100644
--- a/cobalt/web/context.h
+++ b/cobalt/web/context.h
@@ -36,7 +36,7 @@
 class ServiceWorkerRegistration;
 class ServiceWorkerRegistrationObject;
 class ServiceWorker;
-class ServiceWorkerJobs;
+class ServiceWorkerContext;
 class ServiceWorkerObject;
 }  // namespace worker
 namespace web {
@@ -65,7 +65,7 @@
   virtual Blob::Registry* blob_registry() const = 0;
   virtual web::WebSettings* web_settings() const = 0;
   virtual network::NetworkModule* network_module() const = 0;
-  virtual worker::ServiceWorkerJobs* service_worker_jobs() const = 0;
+  virtual worker::ServiceWorkerContext* service_worker_context() const = 0;
 
   virtual const std::string& name() const = 0;
   virtual void SetupEnvironmentSettings(EnvironmentSettings* settings) = 0;
diff --git a/cobalt/web/custom_event.h b/cobalt/web/custom_event.h
index f5107d5..2c08b72 100644
--- a/cobalt/web/custom_event.h
+++ b/cobalt/web/custom_event.h
@@ -33,11 +33,11 @@
  public:
   explicit CustomEvent(script::EnvironmentSettings* environment_settings,
                        const std::string& type)
-      : Event(type), environment_settings_(environment_settings) {}
+      : Event(type) {}
   CustomEvent(script::EnvironmentSettings* environment_settings,
               const std::string& type, const CustomEventInit& init_dict)
-      : Event(type, init_dict), environment_settings_(environment_settings) {
-    set_detail(init_dict.detail());
+      : Event(type, init_dict) {
+    set_detail(environment_settings, init_dict.detail());
   }
 
   // Creates an event with its "initialized flag" unset.
@@ -46,17 +46,18 @@
 
   // Web API: CustomEvent
   //
-  void InitCustomEvent(const std::string& type, bool bubbles, bool cancelable,
+  void InitCustomEvent(script::EnvironmentSettings* environment_settings,
+                       const std::string& type, bool bubbles, bool cancelable,
                        const script::ValueHandleHolder& detail) {
     InitEvent(type, bubbles, cancelable);
-    set_detail(&detail);
+    set_detail(environment_settings, &detail);
   }
 
-  void set_detail(const script::ValueHandleHolder* detail) {
+  void set_detail(script::EnvironmentSettings* environment_settings,
+                  const script::ValueHandleHolder* detail) {
     if (detail) {
-      auto* wrappable = environment_settings_
-                            ? get_global_wrappable(environment_settings_)
-                            : this;
+      DCHECK(environment_settings);
+      auto* wrappable = get_global_wrappable(environment_settings);
       detail_.reset(
           new script::ValueHandleHolder::Reference(wrappable, *detail));
     } else {
@@ -78,9 +79,6 @@
   ~CustomEvent() override {}
 
   std::unique_ptr<script::ValueHandleHolder::Reference> detail_;
-
- private:
-  script::EnvironmentSettings* environment_settings_;
 };
 
 }  // namespace web
diff --git a/cobalt/web/custom_event.idl b/cobalt/web/custom_event.idl
index 69b471d..ba54190 100644
--- a/cobalt/web/custom_event.idl
+++ b/cobalt/web/custom_event.idl
@@ -20,7 +20,7 @@
 ] interface CustomEvent : Event {
   readonly attribute any detail;
 
-  void initCustomEvent(DOMString type,
+  [CallWith=EnvironmentSettings] void initCustomEvent(DOMString type,
                        boolean bubbles,
                        boolean cancelable,
                        any detail);
diff --git a/cobalt/web/environment_settings_helper.cc b/cobalt/web/environment_settings_helper.cc
index 6e3110a..b42b446 100644
--- a/cobalt/web/environment_settings_helper.cc
+++ b/cobalt/web/environment_settings_helper.cc
@@ -23,6 +23,9 @@
 namespace web {
 
 Context* get_context(script::EnvironmentSettings* environment_settings) {
+  if (!environment_settings) {
+    return nullptr;
+  }
   auto* settings =
       base::polymorphic_downcast<EnvironmentSettings*>(environment_settings);
   return settings->context();
@@ -30,26 +33,46 @@
 
 script::GlobalEnvironment* get_global_environment(
     script::EnvironmentSettings* environment_settings) {
-  return get_context(environment_settings)->global_environment();
+  auto* context = get_context(environment_settings);
+  if (!context) {
+    return nullptr;
+  }
+  return context->global_environment();
 }
 
 v8::Isolate* get_isolate(script::EnvironmentSettings* environment_settings) {
-  return get_global_environment(environment_settings)->isolate();
+  auto* global_environment = get_global_environment(environment_settings);
+  if (!global_environment) {
+    return nullptr;
+  }
+  return global_environment->isolate();
 }
 
 script::Wrappable* get_global_wrappable(
     script::EnvironmentSettings* environment_settings) {
-  return get_global_environment(environment_settings)->global_wrappable();
+  auto* global_environment = get_global_environment(environment_settings);
+  if (!global_environment) {
+    return nullptr;
+  }
+  return global_environment->global_wrappable();
 }
 
 script::ScriptValueFactory* get_script_value_factory(
     script::EnvironmentSettings* environment_settings) {
-  return get_global_environment(environment_settings)->script_value_factory();
+  auto* global_environment = get_global_environment(environment_settings);
+  if (!global_environment) {
+    return nullptr;
+  }
+  return global_environment->script_value_factory();
 }
 
 base::MessageLoop* get_message_loop(
     script::EnvironmentSettings* environment_settings) {
-  return get_context(environment_settings)->message_loop();
+  auto* context = get_context(environment_settings);
+  if (!context) {
+    return nullptr;
+  }
+  return context->message_loop();
 }
 
 }  // namespace web
diff --git a/cobalt/web/message_event.cc b/cobalt/web/message_event.cc
index b38a1fe..262e231 100644
--- a/cobalt/web/message_event.cc
+++ b/cobalt/web/message_event.cc
@@ -25,6 +25,7 @@
 #include "cobalt/script/v8c/v8c_exception_state.h"
 #include "cobalt/web/context.h"
 #include "cobalt/web/environment_settings.h"
+#include "cobalt/web/environment_settings_helper.h"
 #include "starboard/common/string.h"
 #include "starboard/memory.h"
 #include "v8/include/v8.h"
@@ -44,7 +45,8 @@
                            const MessageEventInit& init_dict)
     : Event(type, init_dict), response_type_(kAny) {
   if (init_dict.has_data() && init_dict.data()) {
-    data_ = script::SerializeScriptValue(*(init_dict.data()));
+    structured_clone_ =
+        std::make_unique<script::StructuredClone>(*(init_dict.data()));
   }
   if (init_dict.has_origin()) {
     origin_ = init_dict.origin();
@@ -80,24 +82,12 @@
 }
 
 MessageEvent::Response MessageEvent::data(
-    script::EnvironmentSettings* settings) const {
-  if (!data_ && !data_io_buffer_) {
-    return Response(script::Handle<script::ValueHandle>());
-  }
-
-  script::GlobalEnvironment* global_environment = nullptr;
-  if (response_type_ == kBlob || response_type_ == kArrayBuffer ||
-      response_type_ == kAny) {
-    DCHECK(settings);
-    global_environment =
-        base::polymorphic_downcast<EnvironmentSettings*>(settings)
-            ->context()
-            ->global_environment();
-    DCHECK(global_environment);
-  }
-
+    script::EnvironmentSettings* settings) {
   switch (response_type_) {
     case kText: {
+      if (!data_io_buffer_) {
+        return Response(script::Handle<script::ValueHandle>());
+      }
       // TODO: Find a way to remove two copies of data here.
       std::string string_response(data_io_buffer_->data(),
                                   data_io_buffer_->size());
@@ -105,6 +95,10 @@
     }
     case kBlob:
     case kArrayBuffer: {
+      auto* global_environment = web::get_global_environment(settings);
+      if (!data_io_buffer_ || !global_environment) {
+        return Response(script::Handle<script::ValueHandle>());
+      }
       auto buffer_copy = script::ArrayBuffer::New(
           global_environment, data_io_buffer_->data(), data_io_buffer_->size());
       script::Handle<script::ArrayBuffer> response_buffer =
@@ -117,12 +111,12 @@
       return Response(response_buffer);
     }
     case kAny: {
-      v8::Isolate* isolate = global_environment->isolate();
+      if (!structured_clone_) {
+        return Response(script::Handle<script::ValueHandle>());
+      }
+      auto* isolate = web::get_isolate(settings);
       script::v8c::EntryScope entry_scope(isolate);
-      DCHECK(isolate);
-      DCHECK(data_);
-      return Response(script::Handle<script::ValueHandle>(
-          std::move(script::DeserializeScriptValue(isolate, *data_))));
+      return Response(structured_clone_->Deserialize(isolate));
     }
     default:
       NOTREACHED() << "Invalid response type.";
diff --git a/cobalt/web/message_event.h b/cobalt/web/message_event.h
index ba81c1f..b16aaac 100644
--- a/cobalt/web/message_event.h
+++ b/cobalt/web/message_event.h
@@ -55,14 +55,17 @@
       : Event(uninitialized_flag) {}
 
   explicit MessageEvent(const std::string& type) : Event(type) {}
-  MessageEvent(base::Token type, std::unique_ptr<script::DataBuffer> data)
-      : Event(type), response_type_(kAny), data_(std::move(data)) {}
+  MessageEvent(base::Token type,
+               std::unique_ptr<script::StructuredClone> structured_clone)
+      : Event(type),
+        response_type_(kAny),
+        structured_clone_(std::move(structured_clone)) {}
   MessageEvent(base::Token type, ResponseType response_type,
                const scoped_refptr<net::IOBufferWithSize>& data)
       : Event(type), response_type_(response_type), data_io_buffer_(data) {}
   MessageEvent(const std::string& type, const MessageEventInit& init_dict);
 
-  Response data(script::EnvironmentSettings* settings = nullptr) const;
+  Response data(script::EnvironmentSettings* settings = nullptr);
   const std::string& origin() const { return origin_; }
   const std::string& last_event_id() const { return last_event_id_; }
   const scoped_refptr<EventTarget>& source() const { return source_; }
@@ -88,7 +91,7 @@
  private:
   ResponseType response_type_ = kText;
   scoped_refptr<net::IOBufferWithSize> data_io_buffer_;
-  std::unique_ptr<script::DataBuffer> data_;
+  std::unique_ptr<script::StructuredClone> structured_clone_;
   std::string origin_;
   std::string last_event_id_;
   scoped_refptr<EventTarget> source_;
diff --git a/cobalt/web/message_event_test.cc b/cobalt/web/message_event_test.cc
index 93893b2..8f9ff89 100644
--- a/cobalt/web/message_event_test.cc
+++ b/cobalt/web/message_event_test.cc
@@ -23,6 +23,7 @@
 #include "cobalt/script/v8c/entry_scope.h"
 #include "cobalt/script/value_handle.h"
 #include "cobalt/web/blob.h"
+#include "cobalt/web/environment_settings_helper.h"
 #include "cobalt/web/message_event_init.h"
 #include "cobalt/web/testing/gtest_workarounds.h"
 #include "cobalt/web/testing/test_with_javascript.h"
@@ -148,13 +149,11 @@
 TEST_P(MessageEventTestWithJavaScript, ConstructorWithAny) {
   base::Optional<script::ValueHandleHolder::Reference> reference;
   EvaluateScript("'ConstructorWithAnyMessageData'", &reference);
-  std::unique_ptr<script::DataBuffer> data(
-      script::SerializeScriptValue(reference->referenced_value()));
-  EXPECT_NE(nullptr, data.get());
-  EXPECT_NE(nullptr, data->ptr);
-  EXPECT_GT(data->size, 0U);
+  auto* isolate = web::get_isolate(web_context()->environment_settings());
+  auto structured_clone =
+      std::make_unique<script::StructuredClone>(reference->referenced_value());
   scoped_refptr<MessageEvent> event =
-      new MessageEvent(base::Tokens::message(), std::move(data));
+      new MessageEvent(base::Tokens::message(), std::move(structured_clone));
 
   EXPECT_EQ("message", event->type());
   EXPECT_EQ(NULL, event->target().get());
@@ -166,6 +165,7 @@
   EXPECT_FALSE(event->IsBeingDispatched());
   EXPECT_FALSE(event->propagation_stopped());
   EXPECT_FALSE(event->immediate_propagation_stopped());
+  script::v8c::EntryScope entry_scope(isolate);
   MessageEvent::Response event_data =
       event->data(web_context()->environment_settings());
   EXPECT_TRUE(event_data.IsType<script::Handle<script::ValueHandle>>());
@@ -173,8 +173,6 @@
       event_data.AsType<script::Handle<script::ValueHandle>>().IsEmpty());
   auto script_value =
       event_data.AsType<script::Handle<script::ValueHandle>>().GetScriptValue();
-  auto* isolate = script::GetIsolate(*script_value);
-  script::v8c::EntryScope entry_scope(isolate);
   v8::Local<v8::Value> v8_value = script::GetV8Value(*script_value);
   std::string actual =
       *(v8::String::Utf8Value(isolate, v8_value.As<v8::String>()));
diff --git a/cobalt/web/message_port.cc b/cobalt/web/message_port.cc
index e0eb126..871874b 100644
--- a/cobalt/web/message_port.cc
+++ b/cobalt/web/message_port.cc
@@ -66,12 +66,12 @@
 }
 
 void MessagePort::PostMessage(const script::ValueHandleHolder& message) {
-  PostMessageSerialized(std::move(script::SerializeScriptValue(message)));
+  PostMessageSerialized(std::make_unique<script::StructuredClone>(message));
 }
 
 void MessagePort::PostMessageSerialized(
-    std::unique_ptr<script::DataBuffer> data_buffer) {
-  if (!event_target_ || !data_buffer) {
+    std::unique_ptr<script::StructuredClone> structured_clone) {
+  if (!event_target_ || !structured_clone) {
     return;
   }
   // TODO: Forward the location of the origating API call to the PostTask call.
@@ -85,13 +85,13 @@
   // TODO: Remove dependency of MessageEvent on net iobuffer (b/227665847)
   message_loop->task_runner()->PostTask(
       FROM_HERE, base::BindOnce(&MessagePort::DispatchMessage, AsWeakPtr(),
-                                std::move(data_buffer)));
+                                std::move(structured_clone)));
 }
 
 void MessagePort::DispatchMessage(
-    std::unique_ptr<script::DataBuffer> data_buffer) {
-  event_target_->DispatchEvent(
-      new web::MessageEvent(base::Tokens::message(), std::move(data_buffer)));
+    std::unique_ptr<script::StructuredClone> structured_clone) {
+  event_target_->DispatchEvent(new web::MessageEvent(
+      base::Tokens::message(), std::move(structured_clone)));
 }
 
 }  // namespace web
diff --git a/cobalt/web/message_port.h b/cobalt/web/message_port.h
index 68ae01e..cee5109 100644
--- a/cobalt/web/message_port.h
+++ b/cobalt/web/message_port.h
@@ -53,7 +53,8 @@
   // -> void PostMessage(const script::ValueHandleHolder& message,
   //                     script::Sequence<script::ValueHandle*> transfer) {}
   void PostMessage(const script::ValueHandleHolder& message);
-  void PostMessageSerialized(std::unique_ptr<script::DataBuffer> data_buffer);
+  void PostMessageSerialized(
+      std::unique_ptr<script::StructuredClone> structured_clone);
 
   void Start() {}
   void Close();
@@ -95,7 +96,8 @@
   DEFINE_WRAPPABLE_TYPE(MessagePort);
 
  private:
-  void DispatchMessage(std::unique_ptr<script::DataBuffer> data_buffer);
+  void DispatchMessage(
+      std::unique_ptr<script::StructuredClone> structured_clone);
 
   // The event target to dispatch events to.
   web::EventTarget* event_target_ = nullptr;
diff --git a/cobalt/web/navigator_ua_data.cc b/cobalt/web/navigator_ua_data.cc
index 4ca973c..7c4d258 100644
--- a/cobalt/web/navigator_ua_data.cc
+++ b/cobalt/web/navigator_ua_data.cc
@@ -60,9 +60,10 @@
       platform_info->evergreen_file_type());
   all_high_entropy_values_.set_evergreen_version(
       platform_info->evergreen_version());
-  all_high_entropy_values_.set_firmware_version_details(
-      platform_info->firmware_version_details());
-  all_high_entropy_values_.set_os_experience(platform_info->os_experience());
+  all_high_entropy_values_.set_android_build_fingerprint(
+      platform_info->android_build_fingerprint());
+  all_high_entropy_values_.set_android_os_experience(
+      platform_info->android_os_experience());
   all_high_entropy_values_.set_starboard_version(
       platform_info->starboard_version());
   all_high_entropy_values_.set_original_design_manufacturer(
diff --git a/cobalt/web/testing/mock_user_agent_platform_info.h b/cobalt/web/testing/mock_user_agent_platform_info.h
index 1ef4301..fca692f 100644
--- a/cobalt/web/testing/mock_user_agent_platform_info.h
+++ b/cobalt/web/testing/mock_user_agent_platform_info.h
@@ -75,10 +75,12 @@
   const std::string& evergreen_version() const override {
     return empty_string_;
   }
-  const std::string& firmware_version_details() const override {
+  const std::string& android_build_fingerprint() const override {
     return empty_string_;
   }
-  const std::string& os_experience() const override { return empty_string_; }
+  const std::string& android_os_experience() const override {
+    return empty_string_;
+  }
   const std::string& cobalt_version() const override { return empty_string_; }
   const std::string& cobalt_build_version_number() const override {
     return empty_string_;
diff --git a/cobalt/web/testing/stub_web_context.h b/cobalt/web/testing/stub_web_context.h
index 87268f0..487101b 100644
--- a/cobalt/web/testing/stub_web_context.h
+++ b/cobalt/web/testing/stub_web_context.h
@@ -110,7 +110,7 @@
     return network_module_.get();
   }
 
-  worker::ServiceWorkerJobs* service_worker_jobs() const final {
+  worker::ServiceWorkerContext* service_worker_context() const final {
     NOTREACHED();
     return nullptr;
   }
diff --git a/cobalt/web/user_agent_platform_info.h b/cobalt/web/user_agent_platform_info.h
index 6ee6e9c..d7b4ad1 100644
--- a/cobalt/web/user_agent_platform_info.h
+++ b/cobalt/web/user_agent_platform_info.h
@@ -47,8 +47,8 @@
   virtual const std::string& evergreen_type() const = 0;
   virtual const std::string& evergreen_file_type() const = 0;
   virtual const std::string& evergreen_version() const = 0;
-  virtual const std::string& firmware_version_details() const = 0;
-  virtual const std::string& os_experience() const = 0;
+  virtual const std::string& android_build_fingerprint() const = 0;
+  virtual const std::string& android_os_experience() const = 0;
 
   virtual const std::string& cobalt_version() const = 0;
   virtual const std::string& cobalt_build_version_number() const = 0;
diff --git a/cobalt/websocket/web_socket_impl_test.cc b/cobalt/websocket/web_socket_impl_test.cc
index a750436..1380f8d 100644
--- a/cobalt/websocket/web_socket_impl_test.cc
+++ b/cobalt/websocket/web_socket_impl_test.cc
@@ -113,7 +113,7 @@
   StrictMock<MockExceptionState> exception_state_;
 };
 
-TEST_F(WebSocketImplTest, NormalSizeRequest) {
+TEST_F(WebSocketImplTest, DISABLED_NormalSizeRequest) {
   // Normally the high watermark quota is given at websocket connection success.
   AddQuota(kDefaultSendQuotaHighWaterMark);
 
@@ -133,7 +133,7 @@
   websocket_impl_->SendText(data, k800KB, &buffered_amount, &error);
 }
 
-TEST_F(WebSocketImplTest, LargeRequest) {
+TEST_F(WebSocketImplTest, DISABLED_LargeRequest) {
   AddQuota(kDefaultSendQuotaHighWaterMark);
 
   // mock_channel_ is created and used on network thread.
@@ -153,7 +153,7 @@
                             &buffered_amount, &error);
 }
 
-TEST_F(WebSocketImplTest, OverLimitRequest) {
+TEST_F(WebSocketImplTest, DISABLED_OverLimitRequest) {
   AddQuota(kDefaultSendQuotaHighWaterMark);
 
   // mock_channel_ is created and used on network thread.
@@ -188,7 +188,7 @@
   AddQuota(kDefaultSendQuotaHighWaterMark);
 }
 
-TEST_F(WebSocketImplTest, ReuseSocketForLargeRequest) {
+TEST_F(WebSocketImplTest, DISABLED_ReuseSocketForLargeRequest) {
   AddQuota(kDefaultSendQuotaHighWaterMark);
 
   // mock_channel_ is created and used on network thread.
diff --git a/cobalt/worker/BUILD.gn b/cobalt/worker/BUILD.gn
index 24d8147..23aeaa1 100644
--- a/cobalt/worker/BUILD.gn
+++ b/cobalt/worker/BUILD.gn
@@ -40,6 +40,8 @@
     "service_worker_consts.h",
     "service_worker_container.cc",
     "service_worker_container.h",
+    "service_worker_context.cc",
+    "service_worker_context.h",
     "service_worker_global_scope.cc",
     "service_worker_global_scope.h",
     "service_worker_jobs.cc",
diff --git a/cobalt/worker/clients.cc b/cobalt/worker/clients.cc
index c78e12a..c32966d 100644
--- a/cobalt/worker/clients.cc
+++ b/cobalt/worker/clients.cc
@@ -33,8 +33,8 @@
 #include "cobalt/web/dom_exception.h"
 #include "cobalt/web/environment_settings.h"
 #include "cobalt/worker/client.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_global_scope.h"
-#include "cobalt/worker/service_worker_jobs.h"
 #include "cobalt/worker/service_worker_object.h"
 
 namespace cobalt {
@@ -72,12 +72,13 @@
           settings_->context()->GetWindowOrWorkerGlobalScope(), promise));
 
   // 2. Run these substeps in parallel:
-  ServiceWorkerJobs* jobs = settings_->context()->service_worker_jobs();
-  DCHECK(jobs);
-  jobs->message_loop()->task_runner()->PostTask(
+  ServiceWorkerContext* context =
+      settings_->context()->service_worker_context();
+  DCHECK(context);
+  context->message_loop()->task_runner()->PostTask(
       FROM_HERE,
-      base::BindOnce(&ServiceWorkerJobs::ClientsGetSubSteps,
-                     base::Unretained(jobs),
+      base::BindOnce(&ServiceWorkerContext::ClientsGetSubSteps,
+                     base::Unretained(context),
                      base::Unretained(settings_->context()),
                      base::Unretained(GetAssociatedServiceWorker(settings_)),
                      std::move(promise_reference), id));
@@ -101,12 +102,13 @@
       promise_reference(new script::ValuePromiseSequenceWrappable::Reference(
           settings_->context()->GetWindowOrWorkerGlobalScope(), promise));
   // 2. Run the following steps in parallel:
-  ServiceWorkerJobs* jobs = settings_->context()->service_worker_jobs();
-  DCHECK(jobs);
-  jobs->message_loop()->task_runner()->PostTask(
+  ServiceWorkerContext* context =
+      settings_->context()->service_worker_context();
+  DCHECK(context);
+  context->message_loop()->task_runner()->PostTask(
       FROM_HERE,
-      base::BindOnce(&ServiceWorkerJobs::ClientsMatchAllSubSteps,
-                     base::Unretained(jobs),
+      base::BindOnce(&ServiceWorkerContext::ClientsMatchAllSubSteps,
+                     base::Unretained(context),
                      base::Unretained(settings_->context()),
                      base::Unretained(GetAssociatedServiceWorker(settings_)),
                      std::move(promise_reference),
@@ -156,11 +158,13 @@
          service_worker->state() == kServiceWorkerStateActivating);
 
   // 3. Run the following substeps in parallel:
-  ServiceWorkerJobs* jobs = settings_->context()->service_worker_jobs();
-  DCHECK(jobs);
-  jobs->message_loop()->task_runner()->PostTask(
+  ServiceWorkerContext* context =
+      settings_->context()->service_worker_context();
+  DCHECK(context);
+  context->message_loop()->task_runner()->PostTask(
       FROM_HERE,
-      base::BindOnce(&ServiceWorkerJobs::ClaimSubSteps, base::Unretained(jobs),
+      base::BindOnce(&ServiceWorkerContext::ClaimSubSteps,
+                     base::Unretained(context),
                      base::Unretained(settings_->context()),
                      base::Unretained(GetAssociatedServiceWorker(settings_)),
                      std::move(promise_reference)));
diff --git a/cobalt/worker/dedicated_worker.cc b/cobalt/worker/dedicated_worker.cc
index 624dbec..489a987 100644
--- a/cobalt/worker/dedicated_worker.cc
+++ b/cobalt/worker/dedicated_worker.cc
@@ -97,8 +97,8 @@
   options.outside_event_target = this;
   options.outside_port = outside_port_.get();
   options.options = worker_options_;
-  options.web_options.service_worker_jobs =
-      options.outside_context->service_worker_jobs();
+  options.web_options.service_worker_context =
+      options.outside_context->service_worker_context();
   // Store the current source location as the construction location, to be used
   // in the error event if worker loading of initialization fails.
   auto stack_trace =
diff --git a/cobalt/worker/extendable_event.cc b/cobalt/worker/extendable_event.cc
index 87d48cb..5b285dc 100644
--- a/cobalt/worker/extendable_event.cc
+++ b/cobalt/worker/extendable_event.cc
@@ -72,14 +72,15 @@
     web::Context* context =
         base::polymorphic_downcast<web::EnvironmentSettings*>(settings)
             ->context();
-    ServiceWorkerJobs* jobs = context->service_worker_jobs();
-    DCHECK(jobs);
+    ServiceWorkerContext* worker_context = context->service_worker_context();
+    DCHECK(worker_context);
     // 5.2.1. Let registration be the current global object's associated
     //        service worker's containing service worker registration.
-    jobs->message_loop()->task_runner()->PostTask(
+    worker_context->message_loop()->task_runner()->PostTask(
         FROM_HERE,
         base::BindOnce(
-            &ServiceWorkerJobs::WaitUntilSubSteps, base::Unretained(jobs),
+            &ServiceWorkerContext::WaitUntilSubSteps,
+            base::Unretained(worker_context),
             base::Unretained(context->GetWindowOrWorkerGlobalScope()
                                  ->AsServiceWorker()
                                  ->service_worker_object()
diff --git a/cobalt/worker/extendable_event.h b/cobalt/worker/extendable_event.h
index fbd8136..5864eb0 100644
--- a/cobalt/worker/extendable_event.h
+++ b/cobalt/worker/extendable_event.h
@@ -35,8 +35,8 @@
 #include "cobalt/web/event.h"
 #include "cobalt/web/window_or_worker_global_scope.h"
 #include "cobalt/worker/extendable_event_init.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_global_scope.h"
-#include "cobalt/worker/service_worker_jobs.h"
 #include "cobalt/worker/service_worker_object.h"
 #include "cobalt/worker/service_worker_registration_object.h"
 #include "v8/include/v8.h"
diff --git a/cobalt/worker/extendable_message_event.cc b/cobalt/worker/extendable_message_event.cc
index 30a253c..00d0437 100644
--- a/cobalt/worker/extendable_message_event.cc
+++ b/cobalt/worker/extendable_message_event.cc
@@ -32,8 +32,8 @@
     const ExtendableMessageEventInit& init_dict)
     : ExtendableEvent(settings, type, init_dict) {
   if (init_dict.has_data() && init_dict.data()) {
-    DCHECK(init_dict.data());
-    data_ = script::SerializeScriptValue(*(init_dict.data()));
+    structured_clone_ =
+        std::make_unique<script::StructuredClone>(*(init_dict.data()));
   }
   if (init_dict.has_origin()) {
     origin_ = init_dict.origin();
@@ -50,19 +50,13 @@
 }
 
 script::Handle<script::ValueHandle> ExtendableMessageEvent::data(
-    script::EnvironmentSettings* settings) const {
-  if (!settings) return script::Handle<script::ValueHandle>();
-  script::GlobalEnvironment* global_environment =
-      base::polymorphic_downcast<web::EnvironmentSettings*>(settings)
-          ->context()
-          ->global_environment();
-  DCHECK(global_environment);
-  v8::Isolate* isolate = global_environment->isolate();
+    script::EnvironmentSettings* settings) {
+  if (!structured_clone_) {
+    return script::Handle<script::ValueHandle>();
+  }
+  auto* isolate = web::get_isolate(settings);
   script::v8c::EntryScope entry_scope(isolate);
-  DCHECK(isolate);
-  if (!data_) return script::Handle<script::ValueHandle>();
-  return script::Handle<script::ValueHandle>(
-      std::move(script::DeserializeScriptValue(isolate, *data_)));
+  return structured_clone_->Deserialize(isolate);
 }
 
 }  // namespace worker
diff --git a/cobalt/worker/extendable_message_event.h b/cobalt/worker/extendable_message_event.h
index c9b2fea..5838e4c 100644
--- a/cobalt/worker/extendable_message_event.h
+++ b/cobalt/worker/extendable_message_event.h
@@ -56,16 +56,16 @@
   ExtendableMessageEvent(script::EnvironmentSettings* settings,
                          base::Token type,
                          const ExtendableMessageEventInit& init_dict);
-  ExtendableMessageEvent(script::EnvironmentSettings* settings,
-                         base::Token type,
-                         const ExtendableMessageEventInit& init_dict,
-                         std::unique_ptr<script::DataBuffer> data)
+  ExtendableMessageEvent(
+      script::EnvironmentSettings* settings, base::Token type,
+      const ExtendableMessageEventInit& init_dict,
+      std::unique_ptr<script::StructuredClone> structured_clone)
       : ExtendableMessageEvent(settings, type, init_dict) {
-    data_ = std::move(data);
+    structured_clone_ = std::move(structured_clone);
   }
 
   script::Handle<script::ValueHandle> data(
-      script::EnvironmentSettings* settings = nullptr) const;
+      script::EnvironmentSettings* settings = nullptr);
 
   const std::string& origin() const { return origin_; }
   const std::string& last_event_id() const { return last_event_id_; }
@@ -92,7 +92,7 @@
   std::string last_event_id_;
   SourceType source_;
   script::Sequence<scoped_refptr<MessagePort>> ports_;
-  std::unique_ptr<script::DataBuffer> data_;
+  std::unique_ptr<script::StructuredClone> structured_clone_;
 };
 
 }  // namespace worker
diff --git a/cobalt/worker/extendable_message_event_test.cc b/cobalt/worker/extendable_message_event_test.cc
index 40591dd..5d464c0 100644
--- a/cobalt/worker/extendable_message_event_test.cc
+++ b/cobalt/worker/extendable_message_event_test.cc
@@ -74,14 +74,11 @@
 TEST_F(ExtendableMessageEventTestWithJavaScript, ConstructorWithAny) {
   base::Optional<script::ValueHandleHolder::Reference> reference;
   EvaluateScript("'ConstructorWithAnyMessageData'", &reference);
-  std::unique_ptr<script::DataBuffer> data(
-      script::SerializeScriptValue(reference->referenced_value()));
-  EXPECT_NE(nullptr, data.get());
-  EXPECT_NE(nullptr, data->ptr);
-  EXPECT_GT(data->size, 0U);
+  auto* isolate = web::get_isolate(web_context()->environment_settings());
   const ExtendableMessageEventInit init;
   scoped_refptr<ExtendableMessageEvent> event = new ExtendableMessageEvent(
-      environment_settings(), base::Tokens::message(), init, std::move(data));
+      environment_settings(), base::Tokens::message(), init,
+      std::make_unique<script::StructuredClone>(reference->referenced_value()));
 
   EXPECT_EQ("message", event->type());
   EXPECT_EQ(NULL, event->target().get());
@@ -93,12 +90,11 @@
   EXPECT_FALSE(event->IsBeingDispatched());
   EXPECT_FALSE(event->propagation_stopped());
   EXPECT_FALSE(event->immediate_propagation_stopped());
+  script::v8c::EntryScope entry_scope(isolate);
   script::Handle<script::ValueHandle> event_data =
       event->data(web_context()->environment_settings());
   EXPECT_FALSE(event_data.IsEmpty());
   auto script_value = event_data.GetScriptValue();
-  auto* isolate = script::GetIsolate(*script_value);
-  script::v8c::EntryScope entry_scope(isolate);
   v8::Local<v8::Value> v8_value = script::GetV8Value(*script_value);
   std::string actual =
       *(v8::String::Utf8Value(isolate, v8_value.As<v8::String>()));
diff --git a/cobalt/worker/service_worker.cc b/cobalt/worker/service_worker.cc
index bc67613..49cd005 100644
--- a/cobalt/worker/service_worker.cc
+++ b/cobalt/worker/service_worker.cc
@@ -21,10 +21,11 @@
 #include "cobalt/base/tokens.h"
 #include "cobalt/script/environment_settings.h"
 #include "cobalt/script/value_handle.h"
+#include "cobalt/web/environment_settings_helper.h"
 #include "cobalt/web/event_target.h"
 #include "cobalt/web/message_port.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_global_scope.h"
-#include "cobalt/worker/service_worker_jobs.h"
 #include "cobalt/worker/service_worker_object.h"
 #include "cobalt/worker/service_worker_state.h"
 
@@ -47,24 +48,24 @@
   // 4. Let serializeWithTransferResult be
   //    StructuredSerializeWithTransfer(message, options["transfer"]).
   //    Rethrow any exceptions.
-  std::unique_ptr<script::DataBuffer> serialize_result(
-      script::SerializeScriptValue(message));
-  if (!serialize_result) {
+  auto structured_clone = std::make_unique<script::StructuredClone>(message);
+  if (structured_clone->failed()) {
     return;
   }
   // 5. If the result of running the Should Skip Event algorithm with
   // "message" and serviceWorker is true, then return.
   if (service_worker->ShouldSkipEvent(base::Tokens::message())) return;
   // 6. Run these substeps in parallel:
-  ServiceWorkerJobs* jobs =
-      incumbent_settings->context()->service_worker_jobs();
-  DCHECK(jobs);
-  jobs->message_loop()->task_runner()->PostTask(
+  ServiceWorkerContext* worker_context =
+      incumbent_settings->context()->service_worker_context();
+  DCHECK(worker_context);
+  worker_context->message_loop()->task_runner()->PostTask(
       FROM_HERE,
-      base::BindOnce(&ServiceWorkerJobs::ServiceWorkerPostMessageSubSteps,
-                     base::Unretained(jobs), base::Unretained(service_worker),
+      base::BindOnce(&ServiceWorkerContext::ServiceWorkerPostMessageSubSteps,
+                     base::Unretained(worker_context),
+                     base::Unretained(service_worker),
                      base::Unretained(incumbent_settings->context()),
-                     std::move(serialize_result)));
+                     std::move(structured_clone)));
 }
 
 }  // namespace worker
diff --git a/cobalt/worker/service_worker_container.cc b/cobalt/worker/service_worker_container.cc
index b392f5c..268481d 100644
--- a/cobalt/worker/service_worker_container.cc
+++ b/cobalt/worker/service_worker_container.cc
@@ -80,11 +80,11 @@
   if (ready_promise->State() == script::PromiseState::kPending) {
     //    3.1. Let client by this's service worker client.
     web::Context* client = environment_settings()->context();
-    worker::ServiceWorkerJobs* jobs = client->service_worker_jobs();
-    jobs->message_loop()->task_runner()->PostTask(
+    ServiceWorkerContext* worker_context = client->service_worker_context();
+    worker_context->message_loop()->task_runner()->PostTask(
         FROM_HERE,
-        base::BindOnce(&ServiceWorkerJobs::MaybeResolveReadyPromiseSubSteps,
-                       base::Unretained(jobs), client));
+        base::BindOnce(&ServiceWorkerContext::MaybeResolveReadyPromiseSubSteps,
+                       base::Unretained(worker_context), client));
   }
   // 4. Return readyPromise.
   return ready_promise;
@@ -155,10 +155,10 @@
   //    creation URL, options["type"], and options["updateViaCache"].
   base::ThreadTaskRunnerHandle::Get()->PostTask(
       FROM_HERE,
-      base::BindOnce(&ServiceWorkerJobs::StartRegister,
-                     base::Unretained(client->service_worker_jobs()), scope_url,
-                     script_url, std::move(promise_reference), client,
-                     options.type(), options.update_via_cache()));
+      base::BindOnce(&ServiceWorkerContext::StartRegister,
+                     base::Unretained(client->service_worker_context()),
+                     scope_url, script_url, std::move(promise_reference),
+                     client, options.type(), options.update_via_cache()));
   // 7. Return p.
   return promise;
 }
@@ -237,12 +237,13 @@
 
   // 7. Let promise be a new promise.
   // 8. Run the following substeps in parallel:
-  worker::ServiceWorkerJobs* jobs = client->service_worker_jobs();
-  DCHECK(jobs);
-  jobs->message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::BindOnce(&ServiceWorkerJobs::GetRegistrationSubSteps,
-                                base::Unretained(jobs), storage_key, client_url,
-                                client, std::move(promise_reference)));
+  ServiceWorkerContext* worker_context = client->service_worker_context();
+  DCHECK(worker_context);
+  worker_context->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(&ServiceWorkerContext::GetRegistrationSubSteps,
+                     base::Unretained(worker_context), storage_key, client_url,
+                     client, std::move(promise_reference)));
 }
 
 script::HandlePromiseSequenceWrappable
@@ -268,13 +269,13 @@
         promise_reference) {
   auto* client = environment_settings()->context();
   // https://w3c.github.io/ServiceWorker/#navigator-service-worker-getRegistrations
-  worker::ServiceWorkerJobs* jobs =
-      environment_settings()->context()->service_worker_jobs();
+  ServiceWorkerContext* worker_context =
+      environment_settings()->context()->service_worker_context();
   url::Origin storage_key = environment_settings()->ObtainStorageKey();
-  jobs->message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::BindOnce(&ServiceWorkerJobs::GetRegistrationsSubSteps,
-                                base::Unretained(jobs), storage_key, client,
-                                std::move(promise_reference)));
+  worker_context->message_loop()->task_runner()->PostTask(
+      FROM_HERE, base::BindOnce(&ServiceWorkerContext::GetRegistrationsSubSteps,
+                                base::Unretained(worker_context), storage_key,
+                                client, std::move(promise_reference)));
 }
 
 void ServiceWorkerContainer::StartMessages() {}
diff --git a/cobalt/worker/service_worker_container.h b/cobalt/worker/service_worker_container.h
index 94679d6..3fc52ab 100644
--- a/cobalt/worker/service_worker_container.h
+++ b/cobalt/worker/service_worker_container.h
@@ -26,7 +26,7 @@
 #include "cobalt/web/event_target.h"
 #include "cobalt/web/event_target_listener_info.h"
 #include "cobalt/worker/registration_options.h"
-#include "cobalt/worker/service_worker_jobs.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_registration.h"
 
 namespace cobalt {
diff --git a/cobalt/worker/service_worker_context.cc b/cobalt/worker/service_worker_context.cc
new file mode 100644
index 0000000..3dc9a4e
--- /dev/null
+++ b/cobalt/worker/service_worker_context.cc
@@ -0,0 +1,1716 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "cobalt/worker/service_worker_context.h"
+
+#include <list>
+#include <utility>
+#include <vector>
+
+#include "base/bind.h"
+#include "base/message_loop/message_loop_current.h"
+#include "base/time/time.h"
+#include "base/trace_event/trace_event.h"
+#include "cobalt/web/dom_exception.h"
+#include "cobalt/web/environment_settings.h"
+#include "cobalt/worker/extendable_event.h"
+#include "cobalt/worker/extendable_message_event.h"
+#include "cobalt/worker/service_worker_container.h"
+#include "cobalt/worker/service_worker_jobs.h"
+#include "cobalt/worker/window_client.h"
+
+namespace cobalt {
+namespace worker {
+
+namespace {
+
+const base::TimeDelta kWaitForAsynchronousExtensionsTimeout =
+    base::TimeDelta::FromSeconds(3);
+
+const base::TimeDelta kShutdownWaitTimeoutSecs =
+    base::TimeDelta::FromSeconds(5);
+
+bool PathContainsEscapedSlash(const GURL& url) {
+  const std::string path = url.path();
+  return (path.find("%2f") != std::string::npos ||
+          path.find("%2F") != std::string::npos ||
+          path.find("%5c") != std::string::npos ||
+          path.find("%5C") != std::string::npos);
+}
+
+void ResolveGetClientPromise(
+    web::Context* client, web::Context* worker_context,
+    std::unique_ptr<script::ValuePromiseWrappable::Reference>
+        promise_reference) {
+  TRACE_EVENT0("cobalt::worker", "ResolveGetClientPromise()");
+  // Algorithm for Resolve Get Client Promise:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#resolve-get-client-promise
+
+  // 1. If client is an environment settings object, then:
+  // 1.1. If client is not a secure context, queue a task to reject promise with
+  //      a "SecurityError" DOMException, on promise’s relevant settings
+  //      object's responsible event loop using the DOM manipulation task
+  //      source, and abort these steps.
+  // 2. Else:
+  // 2.1. If client’s creation URL is not a potentially trustworthy URL, queue
+  //      a task to reject promise with a "SecurityError" DOMException, on
+  //      promise’s relevant settings object's responsible event loop using the
+  //      DOM manipulation task source, and abort these steps.
+  // In production, Cobalt requires https, therefore all clients are secure
+  // contexts.
+
+  // 3. If client is an environment settings object and is not a window client,
+  //    then:
+  if (!client->GetWindowOrWorkerGlobalScope()->IsWindow()) {
+    // 3.1. Let clientObject be the result of running Create Client algorithm
+    //      with client as the argument.
+    scoped_refptr<Client> client_object =
+        Client::Create(client->environment_settings());
+
+    // 3.2. Queue a task to resolve promise with clientObject, on promise’s
+    //      relevant settings object's responsible event loop using the DOM
+    //      manipulation task source, and abort these steps.
+    worker_context->message_loop()->task_runner()->PostTask(
+        FROM_HERE,
+        base::BindOnce(
+            [](std::unique_ptr<script::ValuePromiseWrappable::Reference>
+                   promise_reference,
+               scoped_refptr<Client> client_object) {
+              TRACE_EVENT0("cobalt::worker",
+                           "ResolveGetClientPromise() Resolve");
+              promise_reference->value().Resolve(client_object);
+            },
+            std::move(promise_reference), client_object));
+    return;
+  }
+  // 4. Else:
+  // 4.1. Let browsingContext be null.
+  // 4.2. If client is an environment settings object, set browsingContext to
+  //      client’s global object's browsing context.
+  // 4.3. Else, set browsingContext to client’s target browsing context.
+  // Note: Cobalt does not implement a distinction between environments and
+  // environment settings objects.
+  // 4.4. Queue a task to run the following steps on browsingContext’s event
+  //      loop using the user interaction task source:
+  // Note: The task below does not currently perform any actual
+  // functionality in the client context. It is included however to help future
+  // implementation for fetching values for WindowClient properties, with
+  // similar logic existing in ClientsMatchAllSubSteps.
+  client->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](web::Context* client, web::Context* worker_context,
+             std::unique_ptr<script::ValuePromiseWrappable::Reference>
+                 promise_reference) {
+            // 4.4.1. Let frameType be the result of running Get Frame Type with
+            //        browsingContext.
+            // Cobalt does not support nested or auxiliary browsing contexts.
+            // 4.4.2. Let visibilityState be browsingContext’s active document's
+            //        visibilityState attribute value.
+            // 4.4.3. Let focusState be the result of running the has focus
+            //        steps with browsingContext’s active document as the
+            //        argument.
+            // Handled in the WindowData constructor.
+            std::unique_ptr<WindowData> window_data(
+                new WindowData(client->environment_settings()));
+
+            // 4.4.4. Let ancestorOriginsList be the empty list.
+            // 4.4.5. If client is a window client, set ancestorOriginsList to
+            //        browsingContext’s active document's relevant global
+            //        object's Location object’s ancestor origins list's
+            //        associated list.
+            // Cobalt does not implement Location.ancestorOrigins.
+
+            // 4.4.6. Queue a task to run the following steps on promise’s
+            //        relevant settings object's responsible event loop using
+            //        the DOM manipulation task source:
+            worker_context->message_loop()->task_runner()->PostTask(
+                FROM_HERE,
+                base::BindOnce(
+                    [](std::unique_ptr<script::ValuePromiseWrappable::Reference>
+                           promise_reference,
+                       std::unique_ptr<WindowData> window_data) {
+                      // 4.4.6.1. If client’s discarded flag is set, resolve
+                      //          promise with undefined and abort these
+                      //          steps.
+                      // 4.4.6.2. Let windowClient be the result of running
+                      //          Create Window Client with client,
+                      //          frameType, visibilityState, focusState,
+                      //          and ancestorOriginsList.
+                      scoped_refptr<Client> window_client =
+                          WindowClient::Create(*window_data);
+                      // 4.4.6.3. Resolve promise with windowClient.
+                      promise_reference->value().Resolve(window_client);
+                    },
+                    std::move(promise_reference), std::move(window_data)));
+          },
+          client, worker_context, std::move(promise_reference)));
+  DCHECK_EQ(nullptr, promise_reference.get());
+}
+
+}  // namespace
+
+ServiceWorkerContext::ServiceWorkerContext(
+    web::WebSettings* web_settings, network::NetworkModule* network_module,
+    web::UserAgentPlatformInfo* platform_info, base::MessageLoop* message_loop,
+    const GURL& url)
+    : message_loop_(message_loop) {
+  DCHECK_EQ(message_loop_, base::MessageLoop::current());
+  jobs_ =
+      std::make_unique<ServiceWorkerJobs>(this, network_module, message_loop);
+
+  ServiceWorkerPersistentSettings::Options options(web_settings, network_module,
+                                                   platform_info, this, url);
+  scope_to_registration_map_.reset(new ServiceWorkerRegistrationMap(options));
+  DCHECK(scope_to_registration_map_);
+}
+
+ServiceWorkerContext::~ServiceWorkerContext() {
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  scope_to_registration_map_->HandleUserAgentShutdown(this);
+  scope_to_registration_map_->AbortAllActive();
+  scope_to_registration_map_.reset();
+  if (!web_context_registrations_.empty()) {
+    // Abort any Service Workers that remain.
+    for (auto& context : web_context_registrations_) {
+      DCHECK(context);
+      if (context->GetWindowOrWorkerGlobalScope()->IsServiceWorker()) {
+        ServiceWorkerGlobalScope* service_worker =
+            context->GetWindowOrWorkerGlobalScope()->AsServiceWorker();
+        if (service_worker && service_worker->service_worker_object()) {
+          service_worker->service_worker_object()->Abort();
+        }
+      }
+    }
+
+    // Wait for web context registrations to be cleared.
+    web_context_registrations_cleared_.TimedWait(kShutdownWaitTimeoutSecs);
+  }
+}
+
+void ServiceWorkerContext::StartRegister(
+    const base::Optional<GURL>& maybe_scope_url,
+    const GURL& script_url_with_fragment,
+    std::unique_ptr<script::ValuePromiseWrappable::Reference> promise_reference,
+    web::Context* client, const WorkerType& type,
+    const ServiceWorkerUpdateViaCache& update_via_cache) {
+  TRACE_EVENT2("cobalt::worker", "ServiceWorkerContext::StartRegister()",
+               "scope", maybe_scope_url.value_or(GURL()).spec(), "script",
+               script_url_with_fragment.spec());
+  DCHECK_NE(message_loop(), base::MessageLoop::current());
+  DCHECK_EQ(client->message_loop(), base::MessageLoop::current());
+  // Algorithm for Start Register:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#start-register-algorithm
+  // 1. If scriptURL is failure, reject promise with a TypeError and abort these
+  //    steps.
+  if (script_url_with_fragment.is_empty()) {
+    promise_reference->value().Reject(script::kTypeError);
+    return;
+  }
+
+  // 2. Set scriptURL’s fragment to null.
+  url::Replacements<char> replacements;
+  replacements.ClearRef();
+  GURL script_url = script_url_with_fragment.ReplaceComponents(replacements);
+  DCHECK(!script_url.has_ref() || script_url.ref().empty());
+  DCHECK(!script_url.is_empty());
+
+  // 3. If scriptURL’s scheme is not one of "http" and "https", reject promise
+  //    with a TypeError and abort these steps.
+  if (!script_url.SchemeIsHTTPOrHTTPS()) {
+    promise_reference->value().Reject(script::kTypeError);
+    return;
+  }
+
+  // 4. If any of the strings in scriptURL’s path contains either ASCII
+  //    case-insensitive "%2f" or ASCII case-insensitive "%5c", reject promise
+  //    with a TypeError and abort these steps.
+  if (PathContainsEscapedSlash(script_url)) {
+    promise_reference->value().Reject(script::kTypeError);
+    return;
+  }
+
+  DCHECK(client);
+  web::WindowOrWorkerGlobalScope* window_or_worker_global_scope =
+      client->GetWindowOrWorkerGlobalScope();
+  DCHECK(window_or_worker_global_scope);
+  web::CspDelegate* csp_delegate =
+      window_or_worker_global_scope->csp_delegate();
+  DCHECK(csp_delegate);
+  if (!csp_delegate->CanLoad(web::CspDelegate::kWorker, script_url,
+                             /* did_redirect*/ false)) {
+    promise_reference->value().Reject(new web::DOMException(
+        web::DOMException::kSecurityErr,
+        "Failed to register a ServiceWorker: The provided scriptURL ('" +
+            script_url.spec() + "') violates the Content Security Policy."));
+    return;
+  }
+
+  // 5. If scopeURL is null, set scopeURL to the result of parsing the string
+  //    "./" with scriptURL.
+  GURL scope_url = maybe_scope_url.value_or(script_url.Resolve("./"));
+
+  // 6. If scopeURL is failure, reject promise with a TypeError and abort these
+  //    steps.
+  if (scope_url.is_empty()) {
+    promise_reference->value().Reject(script::kTypeError);
+    return;
+  }
+
+  // 7. Set scopeURL’s fragment to null.
+  scope_url = scope_url.ReplaceComponents(replacements);
+  DCHECK(!scope_url.has_ref() || scope_url.ref().empty());
+  DCHECK(!scope_url.is_empty());
+
+  // 8. If scopeURL’s scheme is not one of "http" and "https", reject promise
+  //    with a TypeError and abort these steps.
+  if (!scope_url.SchemeIsHTTPOrHTTPS()) {
+    promise_reference->value().Reject(script::kTypeError);
+    return;
+  }
+
+  // 9. If any of the strings in scopeURL’s path contains either ASCII
+  //    case-insensitive "%2f" or ASCII case-insensitive "%5c", reject promise
+  //    with a TypeError and abort these steps.
+  if (PathContainsEscapedSlash(scope_url)) {
+    promise_reference->value().Reject(script::kTypeError);
+    return;
+  }
+
+  // 10. Let storage key be the result of running obtain a storage key given
+  //     client.
+  url::Origin storage_key = client->environment_settings()->ObtainStorageKey();
+
+  // 11. Let job be the result of running Create Job with register, storage key,
+  //     scopeURL, scriptURL, promise, and client.
+  std::unique_ptr<ServiceWorkerJobs::Job> job = jobs_->CreateJob(
+      ServiceWorkerJobs::kRegister, storage_key, scope_url, script_url,
+      ServiceWorkerJobs::JobPromiseType::Create(std::move(promise_reference)),
+      client);
+
+  // 12. Set job’s worker type to workerType.
+  // Cobalt only supports 'classic' worker type.
+
+  // 13. Set job’s update via cache mode to updateViaCache.
+  job->update_via_cache = update_via_cache;
+
+  // 14. Set job’s referrer to referrer.
+  // This is the same value as set in CreateJob().
+
+  // 15. Invoke Schedule Job with job.
+  jobs_->ScheduleJob(std::move(job));
+}
+
+void ServiceWorkerContext::SoftUpdate(
+    ServiceWorkerRegistrationObject* registration, bool force_bypass_cache) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::SoftUpdate()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  DCHECK(registration);
+  // Algorithm for SoftUpdate:
+  //    https://www.w3.org/TR/2022/CRD-service-workers-20220712/#soft-update
+  // 1. Let newestWorker be the result of running Get Newest Worker algorithm
+  // passing registration as its argument.
+  ServiceWorkerObject* newest_worker = registration->GetNewestWorker();
+
+  // 2. If newestWorker is null, abort these steps.
+  if (newest_worker == nullptr) {
+    return;
+  }
+
+  // 3. Let job be the result of running Create Job with update, registration’s
+  // storage key, registration’s scope url, newestWorker’s script url, null, and
+  // null.
+  std::unique_ptr<ServiceWorkerJobs::Job> job = jobs_->CreateJobWithoutPromise(
+      ServiceWorkerJobs::kUpdate, registration->storage_key(),
+      registration->scope_url(), newest_worker->script_url());
+
+  // 4. Set job’s worker type to newestWorker’s type.
+  // Cobalt only supports 'classic' worker type.
+
+  // 5. Set job’s force bypass cache flag if forceBypassCache is true.
+  job->force_bypass_cache_flag = force_bypass_cache;
+
+  // 6. Invoke Schedule Job with job.
+  message_loop()->task_runner()->PostTask(
+      FROM_HERE, base::BindOnce(&ServiceWorkerJobs::ScheduleJob,
+                                base::Unretained(jobs_.get()), std::move(job)));
+  DCHECK(!job.get());
+}
+
+void ServiceWorkerContext::EnsureServiceWorkerStarted(
+    const url::Origin& storage_key, const GURL& client_url,
+    base::WaitableEvent* done_event) {
+  if (message_loop() != base::MessageLoop::current()) {
+    message_loop()->task_runner()->PostTask(
+        FROM_HERE,
+        base::BindOnce(&ServiceWorkerContext::EnsureServiceWorkerStarted,
+                       base::Unretained(this), storage_key, client_url,
+                       done_event));
+    return;
+  }
+  base::ScopedClosureRunner signal_done(base::BindOnce(
+      [](base::WaitableEvent* done_event) { done_event->Signal(); },
+      done_event));
+  base::TimeTicks start = base::TimeTicks::Now();
+  auto registration =
+      scope_to_registration_map_->GetRegistration(storage_key, client_url);
+  if (!registration) {
+    return;
+  }
+  auto service_worker_object = registration->active_worker();
+  if (!service_worker_object || service_worker_object->is_running()) {
+    return;
+  }
+  service_worker_object->ObtainWebAgentAndWaitUntilDone();
+}
+
+std::string* ServiceWorkerContext::RunServiceWorker(ServiceWorkerObject* worker,
+                                                    bool force_bypass_cache) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::RunServiceWorker()");
+
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  DCHECK(worker);
+  // Algorithm for "Run Service Worker"
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#run-service-worker-algorithm
+
+  // 1. Let unsafeCreationTime be the unsafe shared current time.
+  auto unsafe_creation_time = base::TimeTicks::Now();
+  // 2. If serviceWorker is running, then return serviceWorker’s start status.
+  if (worker->is_running()) {
+    return worker->start_status();
+  }
+  // 3. If serviceWorker’s state is "redundant", then return failure.
+  if (worker->state() == kServiceWorkerStateRedundant) {
+    return nullptr;
+  }
+  // 4. Assert: serviceWorker’s start status is null.
+  DCHECK(worker->start_status() == nullptr);
+  // 5. Let script be serviceWorker’s script resource.
+  // 6. Assert: script is not null.
+  DCHECK(worker->HasScriptResource());
+  // 7. Let startFailed be false.
+  worker->store_start_failed(false);
+  // 8. Let agent be the result of obtaining a service worker agent, and run the
+  //    following steps in that context:
+  // 9. Wait for serviceWorker to be running, or for startFailed to be true.
+  worker->ObtainWebAgentAndWaitUntilDone();
+  // 10. If startFailed is true, then return failure.
+  if (worker->load_start_failed()) {
+    return nullptr;
+  }
+  // 11. Return serviceWorker’s start status.
+  return worker->start_status();
+}
+
+bool ServiceWorkerContext::WaitForAsynchronousExtensions(
+    const scoped_refptr<ServiceWorkerRegistrationObject>& registration) {
+  // TODO(b/240164388): Investigate a better approach for combining waiting
+  // for the ExtendableEvent while also allowing use of algorithms that run
+  // on the same thread from the event handler.
+  base::TimeTicks wait_start_time = base::TimeTicks::Now();
+  do {
+    if (registration->done_event()->TimedWait(
+            base::TimeDelta::FromMilliseconds(100)))
+      break;
+    base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
+    base::RunLoop().RunUntilIdle();
+  } while ((base::TimeTicks::Now() - wait_start_time) <
+           kWaitForAsynchronousExtensionsTimeout);
+  return registration->done_event()->IsSignaled();
+}
+
+bool ServiceWorkerContext::IsAnyClientUsingRegistration(
+    ServiceWorkerRegistrationObject* registration) {
+  bool any_client_is_using = false;
+  for (auto& context : web_context_registrations_) {
+    // When a service worker client is controlled by a service worker, it is
+    // said that the service worker client is using the service worker’s
+    // containing service worker registration.
+    //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-control
+    if (context->is_controlled_by(registration->active_worker())) {
+      any_client_is_using = true;
+      break;
+    }
+  }
+  return any_client_is_using;
+}
+
+void ServiceWorkerContext::TryActivate(
+    ServiceWorkerRegistrationObject* registration) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::TryActivate()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Algorithm for Try Activate:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-activate-algorithm
+
+  // 1. If registration’s waiting worker is null, return.
+  if (!registration) return;
+  if (!registration->waiting_worker()) return;
+
+  // 2. If registration’s active worker is not null and registration’s active
+  //    worker's state is "activating", return.
+  if (registration->active_worker() &&
+      (registration->active_worker()->state() == kServiceWorkerStateActivating))
+    return;
+
+  // 3. Invoke Activate with registration if either of the following is true:
+
+  //    - registration’s active worker is null.
+  bool invoke_activate = registration->active_worker() == nullptr;
+
+  if (!invoke_activate) {
+    //    - The result of running Service Worker Has No Pending Events with
+    //      registration’s active worker is true...
+    if (ServiceWorkerHasNoPendingEvents(registration->active_worker())) {
+      //      ... and no service worker client is using registration...
+      bool any_client_using = IsAnyClientUsingRegistration(registration);
+      invoke_activate = !any_client_using;
+      //      ... or registration’s waiting worker's skip waiting flag is
+      //      set.
+      if (!invoke_activate && registration->waiting_worker()->skip_waiting())
+        invoke_activate = true;
+    }
+  }
+
+  if (invoke_activate) Activate(registration);
+}
+
+void ServiceWorkerContext::Activate(
+    ServiceWorkerRegistrationObject* registration) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::Activate()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Algorithm for Activate:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#activation-algorithm
+
+  // 1. If registration’s waiting worker is null, abort these steps.
+  if (registration->waiting_worker() == nullptr) return;
+  // 2. If registration’s active worker is not null, then:
+  if (registration->active_worker()) {
+    // 2.1. Terminate registration’s active worker.
+    TerminateServiceWorker(registration->active_worker());
+    // 2.2. Run the Update Worker State algorithm passing registration’s active
+    //      worker and "redundant" as the arguments.
+    UpdateWorkerState(registration->active_worker(),
+                      kServiceWorkerStateRedundant);
+  }
+  // 3. Run the Update Registration State algorithm passing registration,
+  //    "active" and registration’s waiting worker as the arguments.
+  UpdateRegistrationState(registration, kActive,
+                          registration->waiting_worker());
+  // 4. Run the Update Registration State algorithm passing registration,
+  //    "waiting" and null as the arguments.
+  UpdateRegistrationState(registration, kWaiting, nullptr);
+  // 5. Run the Update Worker State algorithm passing registration’s active
+  //    worker and "activating" as the arguments.
+  UpdateWorkerState(registration->active_worker(),
+                    kServiceWorkerStateActivating);
+  // 6. Let matchedClients be a list of service worker clients whose creation
+  //    URL matches registration’s storage key and registration’s scope url.
+  std::list<web::Context*> matched_clients;
+  for (auto& context : web_context_registrations_) {
+    url::Origin context_storage_key =
+        url::Origin::Create(context->environment_settings()->creation_url());
+    scoped_refptr<ServiceWorkerRegistrationObject> matched_registration =
+        scope_to_registration_map_->MatchServiceWorkerRegistration(
+            context_storage_key, registration->scope_url());
+    if (matched_registration == registration) {
+      matched_clients.push_back(context);
+    }
+  }
+  // 7. For each client of matchedClients, queue a task on client’s  responsible
+  //    event loop, using the DOM manipulation task source, to run the following
+  //    substeps:
+  for (auto& client : matched_clients) {
+    // 7.1. Let readyPromise be client’s global object's
+    //      ServiceWorkerContainer object’s ready
+    //      promise.
+    // 7.2. If readyPromise is null, then continue.
+    // 7.3. If readyPromise is pending, resolve
+    //      readyPromise with the the result of getting
+    //      the service worker registration object that
+    //      represents registration in readyPromise’s
+    //      relevant settings object.
+    client->message_loop()->task_runner()->PostTask(
+        FROM_HERE,
+        base::BindOnce(&ServiceWorkerContainer::MaybeResolveReadyPromise,
+                       base::Unretained(client->GetWindowOrWorkerGlobalScope()
+                                            ->navigator_base()
+                                            ->service_worker()
+                                            .get()),
+                       base::Unretained(registration)));
+  }
+  // 8. For each client of matchedClients:
+  // 8.1. If client is a window client, unassociate client’s responsible
+  //      document from its application cache, if it has one.
+  // 8.2. Else if client is a shared worker client, unassociate client’s
+  //      global object from its application cache, if it has one.
+  // Cobalt doesn't implement 'application cache':
+  //   https://www.w3.org/TR/2011/WD-html5-20110525/offline.html#applicationcache
+  // 9. For each service worker client client who is using registration:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-use
+  for (const auto& client : web_context_registrations_) {
+    // When a service worker client is controlled by a service worker, it is
+    // said that the service worker client is using the service worker’s
+    // containing service worker registration.
+    //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-control
+    if (client->active_service_worker() &&
+        client->active_service_worker()
+                ->containing_service_worker_registration() == registration) {
+      // 9.1. Set client’s active worker to registration’s active worker.
+      client->set_active_service_worker(registration->active_worker());
+      // 9.2. Invoke Notify Controller Change algorithm with client as the
+      //      argument.
+      NotifyControllerChange(client);
+    }
+  }
+  // 10. Let activeWorker be registration’s active worker.
+  ServiceWorkerObject* active_worker = registration->active_worker();
+  bool activated = true;
+  // 11. If the result of running the Should Skip Event algorithm with
+  //     activeWorker and "activate" is false, then:
+  DCHECK(active_worker);
+  if (!active_worker->ShouldSkipEvent(base::Tokens::activate())) {
+    // 11.1. If the result of running the Run Service Worker algorithm with
+    //       activeWorker is not failure, then:
+    auto* run_result = RunServiceWorker(active_worker);
+    if (run_result) {
+      // 11.1.1. Queue a task task on activeWorker’s event loop using the DOM
+      //         manipulation task source to run the following steps:
+      DCHECK_EQ(active_worker->web_agent()->context(),
+                active_worker->worker_global_scope()
+                    ->environment_settings()
+                    ->context());
+      DCHECK(registration->done_event()->IsSignaled());
+      registration->done_event()->Reset();
+      active_worker->web_agent()
+          ->context()
+          ->message_loop()
+          ->task_runner()
+          ->PostBlockingTask(
+              FROM_HERE,
+              base::Bind(
+                  [](ServiceWorkerObject* active_worker,
+                     base::WaitableEvent* done_event) {
+                    auto done_callback =
+                        base::BindOnce([](base::WaitableEvent* done_event,
+                                          bool) { done_event->Signal(); },
+                                       done_event);
+                    auto* settings = active_worker->web_agent()
+                                         ->context()
+                                         ->environment_settings();
+                    scoped_refptr<ExtendableEvent> event(
+                        new ExtendableEvent(settings, base::Tokens::activate(),
+                                            std::move(done_callback)));
+                    // 11.1.1.1. Let e be the result of creating an event with
+                    //           ExtendableEvent.
+                    // 11.1.1.2. Initialize e’s type attribute to activate.
+                    // 11.1.1.3. Dispatch e at activeWorker’s global object.
+                    active_worker->worker_global_scope()->DispatchEvent(event);
+                    // 11.1.1.4. WaitForAsynchronousExtensions: Wait, in
+                    //           parallel, until e is not active.
+                    if (!event->IsActive()) {
+                      // If the event handler doesn't use waitUntil(), it will
+                      // already no longer be active, and there will never be a
+                      // callback to signal the done event.
+                      done_event->Signal();
+                    }
+                  },
+                  base::Unretained(active_worker), registration->done_event()));
+      // 11.1.2. Wait for task to have executed or been discarded.
+      // This waiting is done inside PostBlockingTask above.
+      // 11.1.3. Wait for the step labeled WaitForAsynchronousExtensions to
+      //         complete.
+      // TODO(b/240164388): Investigate a better approach for combining waiting
+      // for the ExtendableEvent while also allowing use of algorithms that run
+      // on the same thread from the event handler.
+      if (!WaitForAsynchronousExtensions(registration)) {
+        // Timeout
+        activated = false;
+      }
+    } else {
+      activated = false;
+    }
+  }
+  // 12. Run the Update Worker State algorithm passing registration’s active
+  //     worker and "activated" as the arguments.
+  if (activated && registration->active_worker()) {
+    UpdateWorkerState(registration->active_worker(),
+                      kServiceWorkerStateActivated);
+
+    // Persist registration since the waiting_worker has been updated to nullptr
+    // and the active_worker has been updated to the previous waiting_worker.
+    scope_to_registration_map_->PersistRegistration(registration->storage_key(),
+                                                    registration->scope_url());
+  }
+}
+
+void ServiceWorkerContext::NotifyControllerChange(web::Context* client) {
+  // Algorithm for Notify Controller Change:
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#notify-controller-change-algorithm
+  // 1. Assert: client is not null.
+  DCHECK(client);
+
+  // 2. If client is an environment settings object, queue a task to fire an
+  //    event named controllerchange at the ServiceWorkerContainer object that
+  //    client is associated with.
+  client->message_loop()->task_runner()->PostTask(
+      FROM_HERE, base::Bind(
+                     [](web::Context* client) {
+                       client->GetWindowOrWorkerGlobalScope()
+                           ->navigator_base()
+                           ->service_worker()
+                           ->DispatchEvent(new web::Event(
+                               base::Tokens::controllerchange()));
+                     },
+                     client));
+}
+
+bool ServiceWorkerContext::ServiceWorkerHasNoPendingEvents(
+    ServiceWorkerObject* worker) {
+  // Algorithm for Service Worker Has No Pending Events
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-has-no-pending-events
+  // TODO(b/240174245): Implement this using the 'set of extended events'.
+  NOTIMPLEMENTED();
+
+  // 1. For each event of worker’s set of extended events:
+  // 1.1. If event is active, return false.
+  // 2. Return true.
+  return true;
+}
+
+void ServiceWorkerContext::ClearRegistration(
+    ServiceWorkerRegistrationObject* registration) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::ClearRegistration()");
+  // Algorithm for Clear Registration:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clear-registration-algorithm
+  // 1. Run the following steps atomically.
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+
+  // 2. If registration’s installing worker is not null, then:
+  ServiceWorkerObject* installing_worker = registration->installing_worker();
+  if (installing_worker) {
+    // 2.1. Terminate registration’s installing worker.
+    TerminateServiceWorker(installing_worker);
+    // 2.2. Run the Update Worker State algorithm passing registration’s
+    //      installing worker and "redundant" as the arguments.
+    UpdateWorkerState(installing_worker, kServiceWorkerStateRedundant);
+    // 2.3. Run the Update Registration State algorithm passing registration,
+    //      "installing" and null as the arguments.
+    UpdateRegistrationState(registration, kInstalling, nullptr);
+  }
+
+  // 3. If registration’s waiting worker is not null, then:
+  ServiceWorkerObject* waiting_worker = registration->waiting_worker();
+  if (waiting_worker) {
+    // 3.1. Terminate registration’s waiting worker.
+    TerminateServiceWorker(waiting_worker);
+    // 3.2. Run the Update Worker State algorithm passing registration’s
+    //      waiting worker and "redundant" as the arguments.
+    UpdateWorkerState(waiting_worker, kServiceWorkerStateRedundant);
+    // 3.3. Run the Update Registration State algorithm passing registration,
+    //      "waiting" and null as the arguments.
+    UpdateRegistrationState(registration, kWaiting, nullptr);
+  }
+
+  // 4. If registration’s active worker is not null, then:
+  ServiceWorkerObject* active_worker = registration->active_worker();
+  if (active_worker) {
+    // 4.1. Terminate registration’s active worker.
+    TerminateServiceWorker(active_worker);
+    // 4.2. Run the Update Worker State algorithm passing registration’s
+    //      active worker and "redundant" as the arguments.
+    UpdateWorkerState(active_worker, kServiceWorkerStateRedundant);
+    // 4.3. Run the Update Registration State algorithm passing registration,
+    //      "active" and null as the arguments.
+    UpdateRegistrationState(registration, kActive, nullptr);
+  }
+
+  // Persist registration since the waiting_worker and active_worker have
+  // been updated to nullptr. This will remove any persisted registration
+  // if one exists.
+  scope_to_registration_map_->PersistRegistration(registration->storage_key(),
+                                                  registration->scope_url());
+}
+
+void ServiceWorkerContext::TryClearRegistration(
+    ServiceWorkerRegistrationObject* registration) {
+  TRACE_EVENT0("cobalt::worker",
+               "ServiceWorkerContext::TryClearRegistration()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Algorithm for Try Clear Registration:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-clear-registration-algorithm
+
+  // 1. Invoke Clear Registration with registration if no service worker client
+  // is using registration and all of the following conditions are true:
+  if (IsAnyClientUsingRegistration(registration)) return;
+
+  //    . registration’s installing worker is null or the result of running
+  //      Service Worker Has No Pending Events with registration’s installing
+  //      worker is true.
+  if (registration->installing_worker() &&
+      !ServiceWorkerHasNoPendingEvents(registration->installing_worker()))
+    return;
+
+  //    . registration’s waiting worker is null or the result of running
+  //      Service Worker Has No Pending Events with registration’s waiting
+  //      worker is true.
+  if (registration->waiting_worker() &&
+      !ServiceWorkerHasNoPendingEvents(registration->waiting_worker()))
+    return;
+
+  //    . registration’s active worker is null or the result of running
+  //      ServiceWorker Has No Pending Events with registration’s active worker
+  //      is true.
+  if (registration->active_worker() &&
+      !ServiceWorkerHasNoPendingEvents(registration->active_worker()))
+    return;
+
+  ClearRegistration(registration);
+}
+
+void ServiceWorkerContext::UpdateRegistrationState(
+    ServiceWorkerRegistrationObject* registration, RegistrationState target,
+    const scoped_refptr<ServiceWorkerObject>& source) {
+  TRACE_EVENT2("cobalt::worker",
+               "ServiceWorkerContext::UpdateRegistrationState()", "target",
+               target, "source", source);
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  DCHECK(registration);
+  // Algorithm for Update Registration State:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-registration-state-algorithm
+
+  // 1. Let registrationObjects be an array containing all the
+  //    ServiceWorkerRegistration objects associated with registration.
+  // This is implemented with a call to LookupServiceWorkerRegistration for each
+  // registered web context.
+
+  switch (target) {
+    // 2. If target is "installing", then:
+    case kInstalling: {
+      // 2.1. Set registration’s installing worker to source.
+      registration->set_installing_worker(source);
+      // 2.2. For each registrationObject in registrationObjects:
+      for (auto& context : web_context_registrations_) {
+        // 2.2.1. Queue a task to...
+        context->message_loop()->task_runner()->PostBlockingTask(
+            FROM_HERE,
+            base::Bind(
+                [](web::Context* context,
+                   ServiceWorkerRegistrationObject* registration) {
+                  // 2.2.1. ... set the installing attribute of
+                  //        registrationObject to null if registration’s
+                  //        installing worker is null, or the result of getting
+                  //        the service worker object that represents
+                  //        registration’s installing worker in
+                  //        registrationObject’s relevant settings object.
+                  auto registration_object =
+                      context->LookupServiceWorkerRegistration(registration);
+                  if (registration_object) {
+                    registration_object->set_installing(
+                        context->GetServiceWorker(
+                            registration->installing_worker()));
+                  }
+                },
+                context, base::Unretained(registration)));
+      }
+      break;
+    }
+    // 3. Else if target is "waiting", then:
+    case kWaiting: {
+      // 3.1. Set registration’s waiting worker to source.
+      registration->set_waiting_worker(source);
+      // 3.2. For each registrationObject in registrationObjects:
+      for (auto& context : web_context_registrations_) {
+        // 3.2.1. Queue a task to...
+        context->message_loop()->task_runner()->PostBlockingTask(
+            FROM_HERE,
+            base::Bind(
+                [](web::Context* context,
+                   ServiceWorkerRegistrationObject* registration) {
+                  // 3.2.1. ... set the waiting attribute of registrationObject
+                  //        to null if registration’s waiting worker is null, or
+                  //        the result of getting the service worker object that
+                  //        represents registration’s waiting worker in
+                  //        registrationObject’s relevant settings object.
+                  auto registration_object =
+                      context->LookupServiceWorkerRegistration(registration);
+                  if (registration_object) {
+                    registration_object->set_waiting(context->GetServiceWorker(
+                        registration->waiting_worker()));
+                  }
+                },
+                context, base::Unretained(registration)));
+      }
+      break;
+    }
+    // 4. Else if target is "active", then:
+    case kActive: {
+      // 4.1. Set registration’s active worker to source.
+      registration->set_active_worker(source);
+      // 4.2. For each registrationObject in registrationObjects:
+      for (auto& context : web_context_registrations_) {
+        // 4.2.1. Queue a task to...
+        context->message_loop()->task_runner()->PostBlockingTask(
+            FROM_HERE,
+            base::Bind(
+                [](web::Context* context,
+                   ServiceWorkerRegistrationObject* registration) {
+                  // 4.2.1. ... set the active attribute of registrationObject
+                  //        to null if registration’s active worker is null, or
+                  //        the result of getting the service worker object that
+                  //        represents registration’s active worker in
+                  //        registrationObject’s relevant settings object.
+                  auto registration_object =
+                      context->LookupServiceWorkerRegistration(registration);
+                  if (registration_object) {
+                    registration_object->set_active(context->GetServiceWorker(
+                        registration->active_worker()));
+                  }
+                },
+                context, base::Unretained(registration)));
+      }
+      break;
+    }
+    default:
+      NOTREACHED();
+  }
+}
+
+void ServiceWorkerContext::UpdateWorkerState(ServiceWorkerObject* worker,
+                                             ServiceWorkerState state) {
+  TRACE_EVENT1("cobalt::worker", "ServiceWorkerContext::UpdateWorkerState()",
+               "state", state);
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  DCHECK(worker);
+  if (!worker) {
+    return;
+  }
+  // Algorithm for Update Worker State:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-state-algorithm
+  // 1. Assert: state is not "parsed".
+  DCHECK_NE(kServiceWorkerStateParsed, state);
+  // 2. Set worker's state to state.
+  worker->set_state(state);
+  auto worker_origin = loader::Origin(worker->script_url());
+  // 3. Let settingsObjects be all environment settings objects whose origin is
+  //    worker's script url's origin.
+  // 4. For each settingsObject of settingsObjects...
+  for (auto& context : web_context_registrations_) {
+    if (context->environment_settings()->GetOrigin() == worker_origin) {
+      // 4. ... queue a task on
+      //    settingsObject's responsible event loop in the DOM manipulation task
+      //    source to run the following steps:
+      context->message_loop()->task_runner()->PostBlockingTask(
+          FROM_HERE, base::Bind(
+                         [](web::Context* context, ServiceWorkerObject* worker,
+                            ServiceWorkerState state) {
+                           DCHECK_EQ(context->message_loop(),
+                                     base::MessageLoop::current());
+                           // 4.1. Let objectMap be settingsObject's service
+                           // worker object
+                           //      map.
+                           // 4.2. If objectMap[worker] does not exist, then
+                           // abort these
+                           //      steps.
+                           // 4.3. Let  workerObj be objectMap[worker].
+                           auto worker_obj =
+                               context->LookupServiceWorker(worker);
+                           if (worker_obj) {
+                             // 4.4. Set workerObj's state to state.
+                             worker_obj->set_state(state);
+                             // 4.5. Fire an event named statechange at
+                             // workerObj.
+                             worker_obj->DispatchEvent(
+                                 new web::Event(base::Tokens::statechange()));
+                           }
+                         },
+                         context, base::Unretained(worker), state));
+    }
+  }
+}
+
+void ServiceWorkerContext::HandleServiceWorkerClientUnload(
+    web::Context* client) {
+  TRACE_EVENT0("cobalt::worker",
+               "ServiceWorkerContext::HandleServiceWorkerClientUnload()");
+  // Algorithm for Handle Servicer Worker Client Unload:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#on-client-unload-algorithm
+  DCHECK(client);
+  // 1. Run the following steps atomically.
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+
+  // 2. Let registration be the service worker registration used by client.
+  // 3. If registration is null, abort these steps.
+  ServiceWorkerObject* active_service_worker = client->active_service_worker();
+  if (!active_service_worker) return;
+  ServiceWorkerRegistrationObject* registration =
+      active_service_worker->containing_service_worker_registration();
+  if (!registration) return;
+
+  // 4. If any other service worker client is using registration, abort these
+  //    steps.
+  // Ensure the client is already removed from the registrations when this runs.
+  DCHECK(web_context_registrations_.end() ==
+         web_context_registrations_.find(client));
+  if (IsAnyClientUsingRegistration(registration)) return;
+
+  // 5. If registration is unregistered, invoke Try Clear Registration with
+  //    registration.
+  if (scope_to_registration_map_ &&
+      scope_to_registration_map_->IsUnregistered(registration)) {
+    TryClearRegistration(registration);
+  }
+
+  // 6. Invoke Try Activate with registration.
+  TryActivate(registration);
+}
+
+void ServiceWorkerContext::TerminateServiceWorker(ServiceWorkerObject* worker) {
+  TRACE_EVENT0("cobalt::worker",
+               "ServiceWorkerContext::TerminateServiceWorker()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Algorithm for Terminate Service Worker:
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#terminate-service-worker
+  // 1. Run the following steps in parallel with serviceWorker’s main loop:
+  // This runs in the ServiceWorkerRegistry thread.
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+
+  // 1.1. Let serviceWorkerGlobalScope be serviceWorker’s global object.
+  WorkerGlobalScope* service_worker_global_scope =
+      worker->worker_global_scope();
+
+  // 1.2. Set serviceWorkerGlobalScope’s closing flag to true.
+  if (service_worker_global_scope != nullptr)
+    service_worker_global_scope->set_closing_flag(true);
+
+  // 1.3. Remove all the items from serviceWorker’s set of extended events.
+  // TODO(b/240174245): Implement 'set of extended events'.
+
+  // 1.4. If there are any tasks, whose task source is either the handle fetch
+  //      task source or the handle functional event task source, queued in
+  //      serviceWorkerGlobalScope’s event loop’s task queues, queue them to
+  //      serviceWorker’s containing service worker registration’s corresponding
+  //      task queues in the same order using their original task sources, and
+  //      discard all the tasks (including tasks whose task source is neither
+  //      the handle fetch task source nor the handle functional event task
+  //      source) from serviceWorkerGlobalScope’s event loop’s task queues
+  //      without processing them.
+  // TODO(b/234787641): Queue tasks to the registration.
+
+  // Note: This step is not in the spec, but without this step the service
+  // worker object map will always keep an entry with a service worker instance
+  // for the terminated service worker, which besides leaking memory can lead to
+  // unexpected behavior when new service worker objects are created with the
+  // same key for the service worker object map (which in Cobalt's case
+  // happens when a new service worker object is constructed at the same
+  // memory address).
+  for (auto& context : web_context_registrations_) {
+    context->message_loop()->task_runner()->PostBlockingTask(
+        FROM_HERE, base::Bind(
+                       [](web::Context* context, ServiceWorkerObject* worker) {
+                         auto worker_obj = context->LookupServiceWorker(worker);
+                         if (worker_obj) {
+                           worker_obj->set_state(kServiceWorkerStateRedundant);
+                           worker_obj->DispatchEvent(
+                               new web::Event(base::Tokens::statechange()));
+                         }
+                         context->RemoveServiceWorker(worker);
+                       },
+                       context, base::Unretained(worker)));
+  }
+
+  // 1.5. Abort the script currently running in serviceWorker.
+  if (worker->is_running()) {
+    worker->Abort();
+  }
+
+  // 1.6. Set serviceWorker’s start status to null.
+  worker->set_start_status(nullptr);
+}
+
+void ServiceWorkerContext::MaybeResolveReadyPromiseSubSteps(
+    web::Context* client) {
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Algorithm for Sub steps of ServiceWorkerContainer.ready():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#navigator-service-worker-ready
+
+  //    3.1. Let client by this's service worker client.
+  //    3.2. Let storage key be the result of running obtain a storage
+  //         key given client.
+  url::Origin storage_key = client->environment_settings()->ObtainStorageKey();
+  //    3.3. Let registration be the result of running Match Service
+  //         Worker Registration given storage key and client’s
+  //         creation URL.
+  // TODO(b/234659851): Investigate whether this should use the creation URL
+  // directly instead.
+  const GURL& base_url = client->environment_settings()->creation_url();
+  GURL client_url = base_url.Resolve("");
+  scoped_refptr<ServiceWorkerRegistrationObject> registration =
+      scope_to_registration_map_->MatchServiceWorkerRegistration(storage_key,
+                                                                 client_url);
+  //    3.3. If registration is not null, and registration’s active
+  //         worker is not null, queue a task on readyPromise’s
+  //         relevant settings object's responsible event loop, using
+  //         the DOM manipulation task source, to resolve readyPromise
+  //         with the result of getting the service worker
+  //         registration object that represents registration in
+  //         readyPromise’s relevant settings object.
+  if (registration && registration->active_worker()) {
+    client->message_loop()->task_runner()->PostTask(
+        FROM_HERE,
+        base::BindOnce(&ServiceWorkerContainer::MaybeResolveReadyPromise,
+                       base::Unretained(client->GetWindowOrWorkerGlobalScope()
+                                            ->navigator_base()
+                                            ->service_worker()
+                                            .get()),
+                       registration));
+  }
+}
+
+void ServiceWorkerContext::GetRegistrationSubSteps(
+    const url::Origin& storage_key, const GURL& client_url,
+    web::Context* client,
+    std::unique_ptr<script::ValuePromiseWrappable::Reference>
+        promise_reference) {
+  TRACE_EVENT0("cobalt::worker",
+               "ServiceWorkerContext::GetRegistrationSubSteps()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Algorithm for Sub steps of ServiceWorkerContainer.getRegistration():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#navigator-service-worker-getRegistration
+
+  // 8.1. Let registration be the result of running Match Service Worker
+  //      Registration algorithm with clientURL as its argument.
+  scoped_refptr<ServiceWorkerRegistrationObject> registration =
+      scope_to_registration_map_->MatchServiceWorkerRegistration(storage_key,
+                                                                 client_url);
+  // 8.2. If registration is null, resolve promise with undefined and abort
+  //      these steps.
+  // 8.3. Resolve promise with the result of getting the service worker
+  //      registration object that represents registration in promise’s
+  //      relevant settings object.
+  client->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](web::Context* client,
+             std::unique_ptr<script::ValuePromiseWrappable::Reference> promise,
+             scoped_refptr<ServiceWorkerRegistrationObject> registration) {
+            TRACE_EVENT0(
+                "cobalt::worker",
+                "ServiceWorkerContext::GetRegistrationSubSteps() Resolve");
+            promise->value().Resolve(
+                client->GetServiceWorkerRegistration(registration));
+          },
+          client, std::move(promise_reference), registration));
+}
+
+void ServiceWorkerContext::GetRegistrationsSubSteps(
+    const url::Origin& storage_key, web::Context* client,
+    std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
+        promise_reference) {
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  std::vector<scoped_refptr<ServiceWorkerRegistrationObject>>
+      registration_objects =
+          scope_to_registration_map_->GetRegistrations(storage_key);
+  client->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](web::Context* client,
+             std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
+                 promise,
+             std::vector<scoped_refptr<ServiceWorkerRegistrationObject>>
+                 registration_objects) {
+            TRACE_EVENT0(
+                "cobalt::worker",
+                "ServiceWorkerContext::GetRegistrationSubSteps() Resolve");
+            script::Sequence<scoped_refptr<script::Wrappable>> registrations;
+            for (auto registration_object : registration_objects) {
+              registrations.push_back(scoped_refptr<script::Wrappable>(
+                  client->GetServiceWorkerRegistration(registration_object)
+                      .get()));
+            }
+            promise->value().Resolve(std::move(registrations));
+          },
+          client, std::move(promise_reference),
+          std::move(registration_objects)));
+}
+
+void ServiceWorkerContext::SkipWaitingSubSteps(
+    web::Context* worker_context, ServiceWorkerObject* service_worker,
+    std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::SkipWaitingSubSteps()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Check if the client web context is still active. This may trigger if
+  // skipWaiting() was called and service worker installation fails.
+  if (!IsWebContextRegistered(worker_context)) {
+    promise_reference.release();
+    return;
+  }
+
+  // Algorithm for Sub steps of ServiceWorkerGlobalScope.skipWaiting():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-serviceworkerglobalscope-skipwaiting
+
+  // 2.1. Set service worker's skip waiting flag.
+  service_worker->set_skip_waiting();
+
+  // 2.2. Invoke Try Activate with service worker's containing service worker
+  // registration.
+  TryActivate(service_worker->containing_service_worker_registration());
+
+  // 2.3. Resolve promise with undefined.
+  worker_context->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](std::unique_ptr<script::ValuePromiseVoid::Reference> promise) {
+            promise->value().Resolve();
+          },
+          std::move(promise_reference)));
+}
+
+void ServiceWorkerContext::WaitUntilSubSteps(
+    ServiceWorkerRegistrationObject* registration) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::WaitUntilSubSteps()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Sub steps for WaitUntil.
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-extendableevent-waituntil
+  // 5.2.2. If registration is unregistered, invoke Try Clear Registration
+  //        with registration.
+  if (scope_to_registration_map_->IsUnregistered(registration)) {
+    TryClearRegistration(registration);
+  }
+  // 5.2.3. If registration is not null, invoke Try Activate with
+  //        registration.
+  if (registration) {
+    TryActivate(registration);
+  }
+}
+
+void ServiceWorkerContext::ClientsGetSubSteps(
+    web::Context* worker_context,
+    ServiceWorkerObject* associated_service_worker,
+    std::unique_ptr<script::ValuePromiseWrappable::Reference> promise_reference,
+    const std::string& id) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::ClientsGetSubSteps()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Check if the client web context is still active. This may trigger if
+  // Clients.get() was called and service worker installation fails.
+  if (!IsWebContextRegistered(worker_context)) {
+    promise_reference.release();
+    return;
+  }
+  // Parallel sub steps (2) for algorithm for Clients.get(id):
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-get
+  // 2.1. For each service worker client client where the result of running
+  //      obtain a storage key given client equals the associated service
+  //      worker's containing service worker registration's storage key:
+  const url::Origin& storage_key =
+      associated_service_worker->containing_service_worker_registration()
+          ->storage_key();
+  for (auto& client : web_context_registrations_) {
+    url::Origin client_storage_key =
+        client->environment_settings()->ObtainStorageKey();
+    if (client_storage_key.IsSameOriginWith(storage_key)) {
+      // 2.1.1. If client’s id is not id, continue.
+      if (client->environment_settings()->id() != id) continue;
+
+      // 2.1.2. Wait for either client’s execution ready flag to be set or for
+      //        client’s discarded flag to be set.
+      // Web Contexts exist only in the web_context_registrations_ set when they
+      // are both execution ready and not discarded.
+
+      // 2.1.3. If client’s execution ready flag is set, then invoke Resolve Get
+      //        Client Promise with client and promise, and abort these steps.
+      ResolveGetClientPromise(client, worker_context,
+                              std::move(promise_reference));
+      return;
+    }
+  }
+  // 2.2. Resolve promise with undefined.
+  worker_context->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](std::unique_ptr<script::ValuePromiseWrappable::Reference>
+                 promise_reference) {
+            TRACE_EVENT0("cobalt::worker",
+                         "ServiceWorkerContext::ClientsGetSubSteps() Resolve");
+            promise_reference->value().Resolve(scoped_refptr<Client>());
+          },
+          std::move(promise_reference)));
+}
+
+void ServiceWorkerContext::ClientsMatchAllSubSteps(
+    web::Context* worker_context,
+    ServiceWorkerObject* associated_service_worker,
+    std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
+        promise_reference,
+    bool include_uncontrolled, ClientType type) {
+  TRACE_EVENT0("cobalt::worker",
+               "ServiceWorkerContext::ClientsMatchAllSubSteps()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  // Check if the worker web context is still active. This may trigger if
+  // Clients.matchAll() was called and service worker installation fails.
+  if (!IsWebContextRegistered(worker_context)) {
+    promise_reference.release();
+    return;
+  }
+
+  // Parallel sub steps (2) for algorithm for Clients.matchAll():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-matchall
+  // 2.1. Let targetClients be a new list.
+  std::list<web::Context*> target_clients;
+
+  // 2.2. For each service worker client client where the result of running
+  //      obtain a storage key given client equals the associated service
+  //      worker's containing service worker registration's storage key:
+  const url::Origin& storage_key =
+      associated_service_worker->containing_service_worker_registration()
+          ->storage_key();
+  for (auto& client : web_context_registrations_) {
+    url::Origin client_storage_key =
+        client->environment_settings()->ObtainStorageKey();
+    if (client_storage_key.IsSameOriginWith(storage_key)) {
+      // 2.2.1. If client’s execution ready flag is unset or client’s discarded
+      //        flag is set, continue.
+      // Web Contexts exist only in the web_context_registrations_ set when they
+      // are both execution ready and not discarded.
+
+      // 2.2.2. If client is not a secure context, continue.
+      // In production, Cobalt requires https, therefore all workers and their
+      // owners are secure contexts.
+
+      // 2.2.3. If options["includeUncontrolled"] is false, and if client’s
+      //        active service worker is not the associated service worker,
+      //        continue.
+      if (!include_uncontrolled &&
+          (client->active_service_worker() != associated_service_worker)) {
+        continue;
+      }
+
+      // 2.2.4. Add client to targetClients.
+      target_clients.push_back(client);
+    }
+  }
+
+  // 2.3. Let matchedWindowData be a new list.
+  std::unique_ptr<std::vector<WindowData>> matched_window_data(
+      new std::vector<WindowData>);
+
+  // 2.4. Let matchedClients be a new list.
+  std::unique_ptr<std::vector<web::Context*>> matched_clients(
+      new std::vector<web::Context*>);
+
+  // 2.5. For each service worker client client in targetClients:
+  for (auto* client : target_clients) {
+    auto* global_scope = client->GetWindowOrWorkerGlobalScope();
+
+    if ((type == kClientTypeWindow || type == kClientTypeAll) &&
+        (global_scope->IsWindow())) {
+      // 2.5.1. If options["type"] is "window" or "all", and client is not an
+      //        environment settings object or is a window client, then:
+
+      // 2.5.1.1. Let windowData be [ "client" -> client, "ancestorOriginsList"
+      //          -> a new list ].
+      WindowData window_data(client->environment_settings());
+
+      // 2.5.1.2. Let browsingContext be null.
+
+      // 2.5.1.3. Let isClientEnumerable be true.
+      // For Cobalt, isClientEnumerable is always true because the clauses that
+      // would set it to false in 2.5.1.6. do not apply to Cobalt.
+
+      // 2.5.1.4. If client is an environment settings object, set
+      //          browsingContext to client’s global object's browsing context.
+      // 2.5.1.5. Else, set browsingContext to client’s target browsing context.
+      web::Context* browsing_context = client;
+
+      // 2.5.1.6. Queue a task task to run the following substeps on
+      //          browsingContext’s event loop using the user interaction task
+      //          source:
+      // Note: The task below does not currently perform any actual
+      // functionality. It is included however to help future implementation for
+      // fetching values for WindowClient properties, with similar logic
+      // existing in ResolveGetClientPromise.
+      browsing_context->message_loop()->task_runner()->PostBlockingTask(
+          FROM_HERE, base::Bind(
+                         [](WindowData* window_data) {
+                           // 2.5.1.6.1. If browsingContext has been discarded,
+                           //            then set isClientEnumerable to false
+                           //            and abort these steps.
+                           // 2.5.1.6.2. If client is a window client and
+                           //            client’s responsible document is not
+                           //            browsingContext’s active document, then
+                           //            set isClientEnumerable to false and
+                           //            abort these steps.
+                           // In Cobalt, the document of a window browsing
+                           // context doesn't change: When a new document is
+                           // created, a new browsing context is created with
+                           // it.
+
+                           // 2.5.1.6.3. Set windowData["frameType"] to the
+                           //            result of running Get Frame Type with
+                           //            browsingContext.
+                           // Cobalt does not support nested or auxiliary
+                           // browsing contexts.
+                           // 2.5.1.6.4. Set windowData["visibilityState"] to
+                           //            browsingContext’s active document's
+                           //            visibilityState attribute value.
+                           // 2.5.1.6.5. Set windowData["focusState"] to the
+                           //            result of running the has focus steps
+                           //            with browsingContext’s active document
+                           //            as the argument.
+
+                           // 2.5.1.6.6. If client is a window client, then set
+                           //            windowData["ancestorOriginsList"] to
+                           //            browsingContext’s active document's
+                           //            relevant global object's Location
+                           //            object’s ancestor origins list's
+                           //            associated list.
+                           // Cobalt does not implement
+                           // Location.ancestorOrigins.
+                         },
+                         &window_data));
+
+      // 2.5.1.7. Wait for task to have executed.
+      // The task above is posted as a blocking task.
+
+      // 2.5.1.8. If isClientEnumerable is true, then:
+
+      // 2.5.1.8.1. Add windowData to matchedWindowData.
+      matched_window_data->emplace_back(window_data);
+
+      // 2.5.2. Else if options["type"] is "worker" or "all" and client is a
+      //        dedicated worker client, or options["type"] is "sharedworker" or
+      //        "all" and client is a shared worker client, then:
+    } else if (((type == kClientTypeWorker || type == kClientTypeAll) &&
+                global_scope->IsDedicatedWorker())) {
+      // Note: Cobalt does not support shared workers.
+      // 2.5.2.1. Add client to matchedClients.
+      matched_clients->emplace_back(client);
+    }
+  }
+
+  // 2.6. Queue a task to run the following steps on promise’s relevant
+  // settings object's responsible event loop using the DOM manipulation
+  // task source:
+  worker_context->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
+                 promise_reference,
+             std::unique_ptr<std::vector<WindowData>> matched_window_data,
+             std::unique_ptr<std::vector<web::Context*>> matched_clients) {
+            TRACE_EVENT0("cobalt::worker",
+                         "ServiceWorkerContext::ClientsMatchAllSubSteps() "
+                         "Resolve Promise");
+            // 2.6.1. Let clientObjects be a new list.
+            script::Sequence<scoped_refptr<script::Wrappable>> client_objects;
+
+            // 2.6.2. For each windowData in matchedWindowData:
+            for (auto& window_data : *matched_window_data) {
+              // 2.6.2.1. Let WindowClient be the result of running
+              //          Create Window Client algorithm with
+              //          windowData["client"],
+              //          windowData["frameType"],
+              //          windowData["visibilityState"],
+              //          windowData["focusState"], and
+              //          windowData["ancestorOriginsList"] as the
+              //          arguments.
+              // TODO(b/235838698): Implement WindowClient methods.
+              scoped_refptr<Client> window_client =
+                  WindowClient::Create(window_data);
+
+              // 2.6.2.2. Append WindowClient to clientObjects.
+              client_objects.push_back(window_client);
+            }
+
+            // 2.6.3. For each client in matchedClients:
+            for (auto& client : *matched_clients) {
+              // 2.6.3.1. Let clientObject be the result of running
+              //          Create Client algorithm with client as the
+              //          argument.
+              scoped_refptr<Client> client_object =
+                  Client::Create(client->environment_settings());
+
+              // 2.6.3.2. Append clientObject to clientObjects.
+              client_objects.push_back(client_object);
+            }
+            // 2.6.4. Sort clientObjects such that:
+            //        . WindowClient objects whose browsing context has been
+            //          focused are placed first, sorted in the most recently
+            //          focused order.
+            //        . WindowClient objects whose browsing context has never
+            //          been focused are placed next, sorted in their service
+            //          worker client's creation order.
+            //        . Client objects whose associated service worker client is
+            //          a worker client are placed next, sorted in their service
+            //          worker client's creation order.
+            // TODO(b/235876598): Implement sorting of clientObjects.
+
+            // 2.6.5. Resolve promise with a new frozen array of clientObjects
+            //        in promise’s relevant Realm.
+            promise_reference->value().Resolve(client_objects);
+          },
+          std::move(promise_reference), std::move(matched_window_data),
+          std::move(matched_clients)));
+}
+
+void ServiceWorkerContext::ClaimSubSteps(
+    web::Context* worker_context,
+    ServiceWorkerObject* associated_service_worker,
+    std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference) {
+  TRACE_EVENT0("cobalt::worker", "ServiceWorkerContext::ClaimSubSteps()");
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+
+  // Check if the client web context is still active. This may trigger if
+  // Clients.claim() was called and service worker installation fails.
+  if (!IsWebContextRegistered(worker_context)) {
+    promise_reference.release();
+    return;
+  }
+
+  // Parallel sub steps (3) for algorithm for Clients.claim():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-clients-claim
+  std::list<web::Context*> target_clients;
+
+  // 3.1. For each service worker client client where the result of running
+  //      obtain a storage key given client equals the service worker's
+  //      containing service worker registration's storage key:
+  const url::Origin& storage_key =
+      associated_service_worker->containing_service_worker_registration()
+          ->storage_key();
+  for (auto& client : web_context_registrations_) {
+    // Don't claim to be our own service worker.
+    if (client == worker_context) continue;
+    url::Origin client_storage_key =
+        client->environment_settings()->ObtainStorageKey();
+    if (client_storage_key.IsSameOriginWith(storage_key)) {
+      // 3.1.1. If client’s execution ready flag is unset or client’s discarded
+      //        flag is set, continue.
+      // Web Contexts exist only in the web_context_registrations_ set when they
+      // are both execution ready and not discarded.
+
+      // 3.1.2. If client is not a secure context, continue.
+      // In production, Cobalt requires https, therefore all clients are secure
+      // contexts.
+
+      // 3.1.3. Let storage key be the result of running obtain a storage key
+      //        given client.
+      // 3.1.4. Let registration be the result of running Match Service Worker
+      //        Registration given storage key and client’s creation URL.
+      // TODO(b/234659851): Investigate whether this should use the creation
+      // URL directly instead.
+      const GURL& base_url = client->environment_settings()->creation_url();
+      GURL client_url = base_url.Resolve("");
+      scoped_refptr<ServiceWorkerRegistrationObject> registration =
+          scope_to_registration_map_->MatchServiceWorkerRegistration(
+              client_storage_key, client_url);
+
+      // 3.1.5. If registration is not the service worker's containing service
+      //        worker registration, continue.
+      if (registration !=
+          associated_service_worker->containing_service_worker_registration()) {
+        continue;
+      }
+
+      // 3.1.6. If client’s active service worker is not the service worker,
+      //        then:
+      if (client->active_service_worker() != associated_service_worker) {
+        // 3.1.6.1. Invoke Handle Service Worker Client Unload with client as
+        //          the argument.
+        HandleServiceWorkerClientUnload(client);
+
+        // 3.1.6.2. Set client’s active service worker to service worker.
+        client->set_active_service_worker(associated_service_worker);
+
+        // 3.1.6.3. Invoke Notify Controller Change algorithm with client as the
+        //          argument.
+        NotifyControllerChange(client);
+      }
+    }
+  }
+  // 3.2. Resolve promise with undefined.
+  worker_context->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](std::unique_ptr<script::ValuePromiseVoid::Reference> promise) {
+            promise->value().Resolve();
+          },
+          std::move(promise_reference)));
+}
+
+void ServiceWorkerContext::ServiceWorkerPostMessageSubSteps(
+    ServiceWorkerObject* service_worker, web::Context* incumbent_client,
+    std::unique_ptr<script::StructuredClone> structured_clone) {
+  // Parallel sub steps (6) for algorithm for ServiceWorker.postMessage():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-postmessage-options
+  // 3. Let incumbentGlobal be incumbentSettings’s global object.
+  // Note: The 'incumbent' is the sender of the message.
+  // 6.1 If the result of running the Run Service Worker algorithm with
+  //     serviceWorker is failure, then return.
+  auto* run_result = RunServiceWorker(service_worker);
+  if (!run_result) return;
+  if (!structured_clone || structured_clone->failed()) return;
+
+  // 6.2 Queue a task on the DOM manipulation task source to run the following
+  //     steps:
+  incumbent_client->message_loop()->task_runner()->PostTask(
+      FROM_HERE,
+      base::BindOnce(
+          [](ServiceWorkerObject* service_worker,
+             web::Context* incumbent_client,
+             std::unique_ptr<script::StructuredClone> structured_clone) {
+            web::EventTarget* event_target =
+                service_worker->worker_global_scope();
+            if (!event_target) return;
+
+            web::WindowOrWorkerGlobalScope* incumbent_global =
+                incumbent_client->GetWindowOrWorkerGlobalScope();
+            DCHECK_EQ(incumbent_client->environment_settings(),
+                      incumbent_global->environment_settings());
+            base::TypeId incumbent_type = incumbent_global->GetWrappableType();
+            ServiceWorkerObject* incumbent_worker =
+                incumbent_global->IsServiceWorker()
+                    ? incumbent_global->AsServiceWorker()
+                          ->service_worker_object()
+                    : nullptr;
+            base::MessageLoop* message_loop =
+                event_target->environment_settings()->context()->message_loop();
+            if (!message_loop) {
+              return;
+            }
+            message_loop->task_runner()->PostTask(
+                FROM_HERE,
+                base::BindOnce(
+                    [](const base::TypeId& incumbent_type,
+                       ServiceWorkerObject* incumbent_worker,
+                       web::Context* incumbent_client,
+                       web::EventTarget* event_target,
+                       std::unique_ptr<script::StructuredClone>
+                           structured_clone) {
+                      ExtendableMessageEventInit init_dict;
+                      if (incumbent_type ==
+                          base::GetTypeId<ServiceWorkerGlobalScope>()) {
+                        // 6.2.1. Let source be determined by switching on the
+                        //        type of incumbentGlobal:
+                        //        . ServiceWorkerGlobalScope
+                        //          The result of getting the service worker
+                        //          object that represents incumbentGlobal’s
+                        //          service worker in the relevant settings
+                        //          object of serviceWorker’s global object.
+                        init_dict.set_source(ExtendableMessageEvent::SourceType(
+                            event_target->environment_settings()
+                                ->context()
+                                ->GetServiceWorker(incumbent_worker)));
+                      } else if (incumbent_type ==
+                                 base::GetTypeId<dom::Window>()) {
+                        //        . Window
+                        //          a new WindowClient object that represents
+                        //          incumbentGlobal’s relevant settings object.
+                        init_dict.set_source(ExtendableMessageEvent::SourceType(
+                            WindowClient::Create(WindowData(
+                                incumbent_client->environment_settings()))));
+                      } else {
+                        //        . Otherwise
+                        //          a new Client object that represents
+                        //          incumbentGlobal’s associated worker
+                        init_dict.set_source(
+                            ExtendableMessageEvent::SourceType(Client::Create(
+                                incumbent_client->environment_settings())));
+                      }
+
+                      event_target->DispatchEvent(
+                          new worker::ExtendableMessageEvent(
+                              event_target->environment_settings(),
+                              base::Tokens::message(), init_dict,
+                              std::move(structured_clone)));
+                    },
+                    incumbent_type, base::Unretained(incumbent_worker),
+                    // Note: These should probably be weak pointers for when
+                    // the message sender disappears before the recipient
+                    // processes the event, but since base::WeakPtr
+                    // dereferencing isn't thread-safe, that can't actually be
+                    // used here.
+                    base::Unretained(incumbent_client),
+                    base::Unretained(event_target),
+                    std::move(structured_clone)));
+          },
+          base::Unretained(service_worker), base::Unretained(incumbent_client),
+          std::move(structured_clone)));
+}
+
+void ServiceWorkerContext::RegisterWebContext(web::Context* context) {
+  DCHECK_NE(nullptr, context);
+  web_context_registrations_cleared_.Reset();
+  if (base::MessageLoop::current() != message_loop()) {
+    DCHECK(message_loop());
+    message_loop()->task_runner()->PostTask(
+        FROM_HERE, base::BindOnce(&ServiceWorkerContext::RegisterWebContext,
+                                  base::Unretained(this), context));
+    return;
+  }
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  DCHECK_EQ(0, web_context_registrations_.count(context));
+  web_context_registrations_.insert(context);
+}
+
+void ServiceWorkerContext::SetActiveWorker(web::EnvironmentSettings* client) {
+  if (!client) return;
+  if (base::MessageLoop::current() != message_loop()) {
+    DCHECK(message_loop());
+    message_loop()->task_runner()->PostTask(
+        FROM_HERE, base::Bind(&ServiceWorkerContext::SetActiveWorker,
+                              base::Unretained(this), client));
+    return;
+  }
+  DCHECK(scope_to_registration_map_);
+  scoped_refptr<ServiceWorkerRegistrationObject> client_registration =
+      scope_to_registration_map_->MatchServiceWorkerRegistration(
+          client->ObtainStorageKey(), client->creation_url());
+  if (client_registration.get() && client_registration->active_worker()) {
+    client->context()->set_active_service_worker(
+        client_registration->active_worker());
+  } else {
+    client->context()->set_active_service_worker(nullptr);
+  }
+}
+
+void ServiceWorkerContext::UnregisterWebContext(web::Context* context) {
+  DCHECK_NE(nullptr, context);
+  if (base::MessageLoop::current() != message_loop()) {
+    // Block to ensure that the context is unregistered before it is destroyed.
+    DCHECK(message_loop());
+    message_loop()->task_runner()->PostBlockingTask(
+        FROM_HERE, base::Bind(&ServiceWorkerContext::UnregisterWebContext,
+                              base::Unretained(this), context));
+    return;
+  }
+  DCHECK_EQ(message_loop(), base::MessageLoop::current());
+  DCHECK_EQ(1, web_context_registrations_.count(context));
+  web_context_registrations_.erase(context);
+  HandleServiceWorkerClientUnload(context);
+  PrepareForClientShutdown(context);
+  if (web_context_registrations_.empty()) {
+    web_context_registrations_cleared_.Signal();
+  }
+}
+
+void ServiceWorkerContext::PrepareForClientShutdown(web::Context* client) {
+  DCHECK(client);
+  if (!client) return;
+  DCHECK(base::MessageLoop::current() == message_loop());
+  // Note: This could be rewritten to use the decomposition declaration
+  // 'const auto& [scope, queue]' after switching to C++17.
+  jobs_->PrepareForClientShutdown(client);
+}
+
+}  // namespace worker
+}  // namespace cobalt
diff --git a/cobalt/worker/service_worker_context.h b/cobalt/worker/service_worker_context.h
new file mode 100644
index 0000000..1446fe8
--- /dev/null
+++ b/cobalt/worker/service_worker_context.h
@@ -0,0 +1,221 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef COBALT_WORKER_SERVICE_WORKER_CONTEXT_H_
+#define COBALT_WORKER_SERVICE_WORKER_CONTEXT_H_
+
+#include <memory>
+#include <set>
+#include <string>
+
+#include "base/memory/scoped_refptr.h"
+#include "base/message_loop/message_loop.h"
+#include "base/optional.h"
+#include "base/synchronization/waitable_event.h"
+#include "cobalt/network/network_module.h"
+#include "cobalt/script/promise.h"
+#include "cobalt/script/script_value.h"
+#include "cobalt/script/script_value_factory.h"
+#include "cobalt/web/context.h"
+#include "cobalt/web/web_settings.h"
+#include "cobalt/worker/client_query_options.h"
+#include "cobalt/worker/service_worker_object.h"
+#include "cobalt/worker/service_worker_registration_map.h"
+#include "cobalt/worker/service_worker_registration_object.h"
+#include "cobalt/worker/worker_type.h"
+#include "url/gurl.h"
+#include "url/origin.h"
+
+namespace cobalt {
+namespace worker {
+
+class ServiceWorkerJobs;
+
+// Algorithms for Service Workers.
+//   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#algorithms
+class ServiceWorkerContext {
+ public:
+  enum RegistrationState { kInstalling, kWaiting, kActive };
+
+  ServiceWorkerContext(web::WebSettings* web_settings,
+                       network::NetworkModule* network_module,
+                       web::UserAgentPlatformInfo* platform_info,
+                       base::MessageLoop* message_loop, const GURL& url);
+  ~ServiceWorkerContext();
+
+  base::MessageLoop* message_loop() { return message_loop_; }
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#start-register-algorithm
+  void StartRegister(const base::Optional<GURL>& scope_url,
+                     const GURL& script_url,
+                     std::unique_ptr<script::ValuePromiseWrappable::Reference>
+                         promise_reference,
+                     web::Context* client, const WorkerType& type,
+                     const ServiceWorkerUpdateViaCache& update_via_cache);
+
+  void MaybeResolveReadyPromiseSubSteps(web::Context* client);
+
+  // Sub steps (8) of ServiceWorkerContainer.getRegistration().
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#navigator-service-worker-getRegistration
+  void GetRegistrationSubSteps(
+      const url::Origin& storage_key, const GURL& client_url,
+      web::Context* client,
+      std::unique_ptr<script::ValuePromiseWrappable::Reference>
+          promise_reference);
+
+  void GetRegistrationsSubSteps(
+      const url::Origin& storage_key, web::Context* client,
+      std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
+          promise_reference);
+
+  // Sub steps (2) of ServiceWorkerGlobalScope.skipWaiting().
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-serviceworkerglobalscope-skipwaiting
+  void SkipWaitingSubSteps(
+      web::Context* worker_context, ServiceWorkerObject* service_worker,
+      std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference);
+
+  // Sub steps for ExtendableEvent.WaitUntil().
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-extendableevent-waituntil
+  void WaitUntilSubSteps(ServiceWorkerRegistrationObject* registration);
+
+  // Parallel sub steps (2) for algorithm for Clients.get(id):
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-get
+  void ClientsGetSubSteps(
+      web::Context* worker_context,
+      ServiceWorkerObject* associated_service_worker,
+      std::unique_ptr<script::ValuePromiseWrappable::Reference>
+          promise_reference,
+      const std::string& id);
+
+  // Parallel sub steps (2) for algorithm for Clients.matchAll():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-matchall
+  void ClientsMatchAllSubSteps(
+      web::Context* worker_context,
+      ServiceWorkerObject* associated_service_worker,
+      std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
+          promise_reference,
+      bool include_uncontrolled, ClientType type);
+
+  // Parallel sub steps (3) for algorithm for Clients.claim():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-clients-claim
+  void ClaimSubSteps(
+      web::Context* worker_context,
+      ServiceWorkerObject* associated_service_worker,
+      std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference);
+
+  // Parallel sub steps (6) for algorithm for ServiceWorker.postMessage():
+  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-postmessage-options
+  void ServiceWorkerPostMessageSubSteps(
+      ServiceWorkerObject* service_worker, web::Context* incumbent_client,
+      std::unique_ptr<script::StructuredClone> structured_clone);
+
+  // Registration of web contexts that may have service workers.
+  void RegisterWebContext(web::Context* context);
+  void UnregisterWebContext(web::Context* context);
+  bool IsWebContextRegistered(web::Context* context) {
+    DCHECK(base::MessageLoop::current() == message_loop());
+    return web_context_registrations_.end() !=
+           web_context_registrations_.find(context);
+  }
+
+  // Ensure no references are kept to JS objects for a client that is about to
+  // be shutdown.
+  void PrepareForClientShutdown(web::Context* client);
+
+  // Set the active worker for a client if there is a matching service worker.
+  void SetActiveWorker(web::EnvironmentSettings* client);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#activation-algorithm
+  void Activate(ServiceWorkerRegistrationObject* registration);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clear-registration-algorithm
+  void ClearRegistration(ServiceWorkerRegistrationObject* registration);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#soft-update
+  void SoftUpdate(ServiceWorkerRegistrationObject* registration,
+                  bool force_bypass_cache);
+
+  void EnsureServiceWorkerStarted(const url::Origin& storage_key,
+                                  const GURL& client_url,
+                                  base::WaitableEvent* done_event);
+
+  ServiceWorkerJobs* jobs() { return jobs_.get(); }
+  ServiceWorkerRegistrationMap* registration_map() {
+    return scope_to_registration_map_.get();
+  }
+  const std::set<web::Context*>& web_context_registrations() const {
+    return web_context_registrations_;
+  }
+
+ private:
+  friend class ServiceWorkerJobs;
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#run-service-worker-algorithm
+  // The return value is a 'Completion or failure'.
+  // A failure is signaled by returning nullptr. Otherwise, the returned string
+  // points to the value of the Completion returned by the script runner
+  // abstraction.
+  std::string* RunServiceWorker(ServiceWorkerObject* worker,
+                                bool force_bypass_cache = false);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-activate-algorithm
+  void TryActivate(ServiceWorkerRegistrationObject* registration);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-has-no-pending-events
+  bool ServiceWorkerHasNoPendingEvents(ServiceWorkerObject* worker);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-registration-state-algorithm
+  void UpdateRegistrationState(
+      ServiceWorkerRegistrationObject* registration, RegistrationState target,
+      const scoped_refptr<ServiceWorkerObject>& source);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-state-algorithm
+  void UpdateWorkerState(ServiceWorkerObject* worker, ServiceWorkerState state);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#on-client-unload-algorithm
+  void HandleServiceWorkerClientUnload(web::Context* client);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#terminate-service-worker
+  void TerminateServiceWorker(ServiceWorkerObject* worker);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#notify-controller-change-algorithm
+  void NotifyControllerChange(web::Context* client);
+
+  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-clear-registration-algorithm
+  void TryClearRegistration(ServiceWorkerRegistrationObject* registration);
+
+  bool IsAnyClientUsingRegistration(
+      ServiceWorkerRegistrationObject* registration);
+
+  // Returns false when the timeout is reached.
+  bool WaitForAsynchronousExtensions(
+      const scoped_refptr<ServiceWorkerRegistrationObject>& registration);
+
+  base::MessageLoop* message_loop_;
+
+  std::unique_ptr<ServiceWorkerRegistrationMap> scope_to_registration_map_;
+
+  std::unique_ptr<ServiceWorkerJobs> jobs_;
+
+  std::set<web::Context*> web_context_registrations_;
+
+  base::WaitableEvent web_context_registrations_cleared_ = {
+      base::WaitableEvent::ResetPolicy::MANUAL,
+      base::WaitableEvent::InitialState::NOT_SIGNALED};
+};
+
+}  // namespace worker
+}  // namespace cobalt
+
+#endif  // COBALT_WORKER_SERVICE_WORKER_CONTEXT_H_
diff --git a/cobalt/worker/service_worker_global_scope.cc b/cobalt/worker/service_worker_global_scope.cc
index 06b7dae..495046f 100644
--- a/cobalt/worker/service_worker_global_scope.cc
+++ b/cobalt/worker/service_worker_global_scope.cc
@@ -29,7 +29,7 @@
 #include "cobalt/worker/clients.h"
 #include "cobalt/worker/fetch_event.h"
 #include "cobalt/worker/fetch_event_init.h"
-#include "cobalt/worker/service_worker_jobs.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/worker_settings.h"
 
 namespace cobalt {
@@ -180,12 +180,12 @@
       new script::ValuePromiseVoid::Reference(this, promise));
 
   // 2. Run the following substeps in parallel:
-  worker::ServiceWorkerJobs* jobs =
-      environment_settings()->context()->service_worker_jobs();
-  jobs->message_loop()->task_runner()->PostTask(
+  ServiceWorkerContext* worker_context =
+      environment_settings()->context()->service_worker_context();
+  worker_context->message_loop()->task_runner()->PostTask(
       FROM_HERE,
-      base::BindOnce(&ServiceWorkerJobs::SkipWaitingSubSteps,
-                     base::Unretained(jobs),
+      base::BindOnce(&ServiceWorkerContext::SkipWaitingSubSteps,
+                     base::Unretained(worker_context),
                      base::Unretained(environment_settings()->context()),
                      base::Unretained(service_worker_object_.get()),
                      std::move(promise_reference)));
@@ -226,13 +226,13 @@
   auto* registration =
       service_worker_object_->containing_service_worker_registration();
   if (registration && (main_resource || registration->stale())) {
-    worker::ServiceWorkerJobs* jobs =
-        environment_settings()->context()->service_worker_jobs();
-    jobs->message_loop()->task_runner()->PostTask(
-        FROM_HERE,
-        base::BindOnce(&ServiceWorkerJobs::SoftUpdate, base::Unretained(jobs),
-                       base::Unretained(registration),
-                       /*force_bypass_cache=*/false));
+    ServiceWorkerContext* worker_context =
+        environment_settings()->context()->service_worker_context();
+    worker_context->message_loop()->task_runner()->PostTask(
+        FROM_HERE, base::BindOnce(&ServiceWorkerContext::SoftUpdate,
+                                  base::Unretained(worker_context),
+                                  base::Unretained(registration),
+                                  /*force_bypass_cache=*/false));
   }
 
   // TODO: handle the following steps in
diff --git a/cobalt/worker/service_worker_jobs.cc b/cobalt/worker/service_worker_jobs.cc
index 8288cf9..5c93575 100644
--- a/cobalt/worker/service_worker_jobs.cc
+++ b/cobalt/worker/service_worker_jobs.cc
@@ -14,71 +14,22 @@
 
 #include "cobalt/worker/service_worker_jobs.h"
 
-#include <list>
-#include <map>
-#include <memory>
-#include <queue>
-#include <string>
-#include <utility>
-#include <vector>
-
 #include "base/bind.h"
-#include "base/logging.h"
-#include "base/message_loop/message_loop.h"
 #include "base/message_loop/message_loop_current.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
-#include "base/synchronization/lock.h"
-#include "base/task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
 #include "base/time/time.h"
 #include "base/trace_event/trace_event.h"
 #include "cobalt/base/tokens.h"
-#include "cobalt/base/type_id.h"
-#include "cobalt/loader/script_loader_factory.h"
-#include "cobalt/network/network_module.h"
-#include "cobalt/script/promise.h"
-#include "cobalt/script/script_exception.h"
-#include "cobalt/script/script_value.h"
-#include "cobalt/web/context.h"
-#include "cobalt/web/dom_exception.h"
 #include "cobalt/web/environment_settings.h"
-#include "cobalt/web/event.h"
-#include "cobalt/web/window_or_worker_global_scope.h"
-#include "cobalt/worker/client.h"
-#include "cobalt/worker/client_query_options.h"
-#include "cobalt/worker/client_type.h"
 #include "cobalt/worker/extendable_event.h"
-#include "cobalt/worker/extendable_message_event.h"
-#include "cobalt/worker/frame_type.h"
-#include "cobalt/worker/service_worker.h"
-#include "cobalt/worker/service_worker_consts.h"
-#include "cobalt/worker/service_worker_container.h"
-#include "cobalt/worker/service_worker_global_scope.h"
-#include "cobalt/worker/service_worker_registration.h"
-#include "cobalt/worker/service_worker_registration_object.h"
-#include "cobalt/worker/service_worker_update_via_cache.h"
-#include "cobalt/worker/window_client.h"
-#include "cobalt/worker/worker_type.h"
 #include "net/base/mime_util.h"
 #include "net/base/url_util.h"
-#include "starboard/common/atomic.h"
-#include "url/gurl.h"
-#include "url/origin.h"
-
 
 namespace cobalt {
 namespace worker {
 
 namespace {
 
-const base::TimeDelta kWaitForAsynchronousExtensionsTimeout =
-    base::TimeDelta::FromSeconds(3);
-
-const base::TimeDelta kShutdownWaitTimeoutSecs =
-    base::TimeDelta::FromSeconds(5);
-
 bool PathContainsEscapedSlash(const GURL& url) {
   const std::string path = url.path();
   return (path.find("%2f") != std::string::npos ||
@@ -134,164 +85,22 @@
 bool PermitAnyNonRedirectedURL(const GURL&, bool did_redirect) {
   return !did_redirect;
 }
+
 }  // namespace
 
-ServiceWorkerJobs::ServiceWorkerJobs(web::WebSettings* web_settings,
-                                     network::NetworkModule* network_module,
-                                     web::UserAgentPlatformInfo* platform_info,
-                                     base::MessageLoop* message_loop,
-                                     const GURL& url)
-    : message_loop_(message_loop) {
+ServiceWorkerJobs::ServiceWorkerJobs(
+    ServiceWorkerContext* service_worker_context,
+    network::NetworkModule* network_module, base::MessageLoop* message_loop)
+    : service_worker_context_(service_worker_context),
+      message_loop_(message_loop) {
   DCHECK_EQ(message_loop_, base::MessageLoop::current());
   fetcher_factory_.reset(new loader::FetcherFactory(network_module));
-  DCHECK(fetcher_factory_);
 
   script_loader_factory_.reset(new loader::ScriptLoaderFactory(
       "ServiceWorkerJobs", fetcher_factory_.get()));
-  DCHECK(script_loader_factory_);
-
-  ServiceWorkerPersistentSettings::Options options(web_settings, network_module,
-                                                   platform_info, this, url);
-  scope_to_registration_map_.reset(new ServiceWorkerRegistrationMap(options));
-  DCHECK(scope_to_registration_map_);
 }
 
-ServiceWorkerJobs::~ServiceWorkerJobs() {
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  scope_to_registration_map_->HandleUserAgentShutdown(this);
-  scope_to_registration_map_->AbortAllActive();
-  scope_to_registration_map_.reset();
-  if (!web_context_registrations_.empty()) {
-    // Abort any Service Workers that remain.
-    for (auto& context : web_context_registrations_) {
-      DCHECK(context);
-      if (context->GetWindowOrWorkerGlobalScope()->IsServiceWorker()) {
-        ServiceWorkerGlobalScope* service_worker =
-            context->GetWindowOrWorkerGlobalScope()->AsServiceWorker();
-        if (service_worker && service_worker->service_worker_object()) {
-          service_worker->service_worker_object()->Abort();
-        }
-      }
-    }
-
-    // Wait for web context registrations to be cleared.
-    web_context_registrations_cleared_.TimedWait(kShutdownWaitTimeoutSecs);
-  }
-}
-
-void ServiceWorkerJobs::StartRegister(
-    const base::Optional<GURL>& maybe_scope_url,
-    const GURL& script_url_with_fragment,
-    std::unique_ptr<script::ValuePromiseWrappable::Reference> promise_reference,
-    web::Context* client, const WorkerType& type,
-    const ServiceWorkerUpdateViaCache& update_via_cache) {
-  TRACE_EVENT2("cobalt::worker", "ServiceWorkerJobs::StartRegister()", "scope",
-               maybe_scope_url.value_or(GURL()).spec(), "script",
-               script_url_with_fragment.spec());
-  DCHECK_NE(message_loop(), base::MessageLoop::current());
-  DCHECK_EQ(client->message_loop(), base::MessageLoop::current());
-  // Algorithm for Start Register:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#start-register-algorithm
-  // 1. If scriptURL is failure, reject promise with a TypeError and abort these
-  //    steps.
-  if (script_url_with_fragment.is_empty()) {
-    promise_reference->value().Reject(script::kTypeError);
-    return;
-  }
-
-  // 2. Set scriptURL’s fragment to null.
-  url::Replacements<char> replacements;
-  replacements.ClearRef();
-  GURL script_url = script_url_with_fragment.ReplaceComponents(replacements);
-  DCHECK(!script_url.has_ref() || script_url.ref().empty());
-  DCHECK(!script_url.is_empty());
-
-  // 3. If scriptURL’s scheme is not one of "http" and "https", reject promise
-  //    with a TypeError and abort these steps.
-  if (!script_url.SchemeIsHTTPOrHTTPS()) {
-    promise_reference->value().Reject(script::kTypeError);
-    return;
-  }
-
-  // 4. If any of the strings in scriptURL’s path contains either ASCII
-  //    case-insensitive "%2f" or ASCII case-insensitive "%5c", reject promise
-  //    with a TypeError and abort these steps.
-  if (PathContainsEscapedSlash(script_url)) {
-    promise_reference->value().Reject(script::kTypeError);
-    return;
-  }
-
-  DCHECK(client);
-  web::WindowOrWorkerGlobalScope* window_or_worker_global_scope =
-      client->GetWindowOrWorkerGlobalScope();
-  DCHECK(window_or_worker_global_scope);
-  web::CspDelegate* csp_delegate =
-      window_or_worker_global_scope->csp_delegate();
-  DCHECK(csp_delegate);
-  if (!csp_delegate->CanLoad(web::CspDelegate::kWorker, script_url,
-                             /* did_redirect*/ false)) {
-    promise_reference->value().Reject(new web::DOMException(
-        web::DOMException::kSecurityErr,
-        "Failed to register a ServiceWorker: The provided scriptURL ('" +
-            script_url.spec() + "') violates the Content Security Policy."));
-    return;
-  }
-
-  // 5. If scopeURL is null, set scopeURL to the result of parsing the string
-  //    "./" with scriptURL.
-  GURL scope_url = maybe_scope_url.value_or(script_url.Resolve("./"));
-
-  // 6. If scopeURL is failure, reject promise with a TypeError and abort these
-  //    steps.
-  if (scope_url.is_empty()) {
-    promise_reference->value().Reject(script::kTypeError);
-    return;
-  }
-
-  // 7. Set scopeURL’s fragment to null.
-  scope_url = scope_url.ReplaceComponents(replacements);
-  DCHECK(!scope_url.has_ref() || scope_url.ref().empty());
-  DCHECK(!scope_url.is_empty());
-
-  // 8. If scopeURL’s scheme is not one of "http" and "https", reject promise
-  //    with a TypeError and abort these steps.
-  if (!scope_url.SchemeIsHTTPOrHTTPS()) {
-    promise_reference->value().Reject(script::kTypeError);
-    return;
-  }
-
-  // 9. If any of the strings in scopeURL’s path contains either ASCII
-  //    case-insensitive "%2f" or ASCII case-insensitive "%5c", reject promise
-  //    with a TypeError and abort these steps.
-  if (PathContainsEscapedSlash(scope_url)) {
-    promise_reference->value().Reject(script::kTypeError);
-    return;
-  }
-
-  // 10. Let storage key be the result of running obtain a storage key given
-  //     client.
-  url::Origin storage_key = client->environment_settings()->ObtainStorageKey();
-
-  // 11. Let job be the result of running Create Job with register, storage key,
-  //     scopeURL, scriptURL, promise, and client.
-  std::unique_ptr<Job> job =
-      CreateJob(kRegister, storage_key, scope_url, script_url,
-                JobPromiseType::Create(std::move(promise_reference)), client);
-  DCHECK(!promise_reference);
-
-  // 12. Set job’s worker type to workerType.
-  // Cobalt only supports 'classic' worker type.
-
-  // 13. Set job’s update via cache mode to updateViaCache.
-  job->update_via_cache = update_via_cache;
-
-  // 14. Set job’s referrer to referrer.
-  // This is the same value as set in CreateJob().
-
-  // 15. Invoke Schedule Job with job.
-  ScheduleJob(std::move(job));
-  DCHECK(!job.get());
-}
+ServiceWorkerJobs::~ServiceWorkerJobs() {}
 
 void ServiceWorkerJobs::PromiseErrorData::Reject(
     std::unique_ptr<JobPromiseType> promise) const {
@@ -366,7 +175,7 @@
     // 5.1. Set job’s containing job queue to jobQueue, and enqueue job to
     // jobQueue.
     job->containing_job_queue = job_queue;
-    if (!IsWebContextRegistered(job->client)) {
+    if (!service_worker_context_->IsWebContextRegistered(job->client)) {
       // Note: The client that requested the job has already exited and isn't
       // able to handle the promise.
       job->containing_job_queue->PrepareJobForClientShutdown(job, job->client);
@@ -396,7 +205,7 @@
     // 6.3. Else, set job’s containing job queue to jobQueue, and enqueue job to
     // jobQueue.
     job->containing_job_queue = job_queue;
-    if (!IsWebContextRegistered(job->client)) {
+    if (!service_worker_context_->IsWebContextRegistered(job->client)) {
       // Note: The client that requested the job has already exited and isn't
       // able to handle the promise.
       job->containing_job_queue->PrepareJobForClientShutdown(job, job->client);
@@ -546,8 +355,8 @@
   // 4. Let registration be the result of running Get Registration given job’s
   // storage key and job’s scope url.
   scoped_refptr<ServiceWorkerRegistrationObject> registration =
-      scope_to_registration_map_->GetRegistration(job->storage_key,
-                                                  job->scope_url);
+      service_worker_context_->registration_map()->GetRegistration(
+          job->storage_key, job->scope_url);
 
   // 5. If registration is not null, then:
   if (registration) {
@@ -573,7 +382,7 @@
 
     // 6.1 Invoke Set Registration algorithm with job’s storage key, job’s scope
     // url, and job’s update via cache mode.
-    registration = scope_to_registration_map_->SetRegistration(
+    registration = service_worker_context_->registration_map()->SetRegistration(
         job->storage_key, job->scope_url, job->update_via_cache);
   }
 
@@ -581,69 +390,6 @@
   Update(job);
 }
 
-void ServiceWorkerJobs::SoftUpdate(
-    ServiceWorkerRegistrationObject* registration, bool force_bypass_cache) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::SoftUpdate()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  DCHECK(registration);
-  // Algorithm for SoftUpdate:
-  //    https://www.w3.org/TR/2022/CRD-service-workers-20220712/#soft-update
-  // 1. Let newestWorker be the result of running Get Newest Worker algorithm
-  // passing registration as its argument.
-  ServiceWorkerObject* newest_worker = registration->GetNewestWorker();
-
-  // 2. If newestWorker is null, abort these steps.
-  if (newest_worker == nullptr) {
-    return;
-  }
-
-  // 3. Let job be the result of running Create Job with update, registration’s
-  // storage key, registration’s scope url, newestWorker’s script url, null, and
-  // null.
-  std::unique_ptr<Job> job = CreateJobWithoutPromise(
-      kUpdate, registration->storage_key(), registration->scope_url(),
-      newest_worker->script_url());
-
-  // 4. Set job’s worker type to newestWorker’s type.
-  // Cobalt only supports 'classic' worker type.
-
-  // 5. Set job’s force bypass cache flag if forceBypassCache is true.
-  job->force_bypass_cache_flag = force_bypass_cache;
-
-  // 6. Invoke Schedule Job with job.
-  message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::BindOnce(&ServiceWorkerJobs::ScheduleJob,
-                                base::Unretained(this), std::move(job)));
-  DCHECK(!job.get());
-}
-
-void ServiceWorkerJobs::EnsureServiceWorkerStarted(
-    const url::Origin& storage_key, const GURL& client_url,
-    base::WaitableEvent* done_event) {
-  if (message_loop() != base::MessageLoop::current()) {
-    message_loop()->task_runner()->PostTask(
-        FROM_HERE,
-        base::BindOnce(&ServiceWorkerJobs::EnsureServiceWorkerStarted,
-                       base::Unretained(this), storage_key, client_url,
-                       done_event));
-    return;
-  }
-  base::ScopedClosureRunner signal_done(base::BindOnce(
-      [](base::WaitableEvent* done_event) { done_event->Signal(); },
-      done_event));
-  base::TimeTicks start = base::TimeTicks::Now();
-  auto registration =
-      scope_to_registration_map_->GetRegistration(storage_key, client_url);
-  if (!registration) {
-    return;
-  }
-  auto service_worker_object = registration->active_worker();
-  if (!service_worker_object || service_worker_object->is_running()) {
-    return;
-  }
-  service_worker_object->ObtainWebAgentAndWaitUntilDone();
-}
-
 void ServiceWorkerJobs::Update(Job* job) {
   TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::Update()");
   DCHECK_EQ(message_loop(), base::MessageLoop::current());
@@ -654,8 +400,8 @@
   // 1. Let registration be the result of running Get Registration given job’s
   //    storage key and job’s scope url.
   scoped_refptr<ServiceWorkerRegistrationObject> registration =
-      scope_to_registration_map_->GetRegistration(job->storage_key,
-                                                  job->scope_url);
+      service_worker_context_->registration_map()->GetRegistration(
+          job->storage_key, job->scope_url);
 
   // 2. If registration is null, then:
   if (!registration) {
@@ -849,12 +595,12 @@
   //   8.19. If response’s cache state is not "local", set registration’s last
   //         update check time to the current time.
   scoped_refptr<ServiceWorkerRegistrationObject> registration =
-      scope_to_registration_map_->GetRegistration(state->job->storage_key,
-                                                  state->job->scope_url);
+      service_worker_context_->registration_map()->GetRegistration(
+          state->job->storage_key, state->job->scope_url);
   if (registration) {
     registration->set_last_update_check_time(base::Time::Now());
-    scope_to_registration_map_->PersistRegistration(registration->storage_key(),
-                                                    registration->scope_url());
+    service_worker_context_->registration_map()->PersistRegistration(
+        registration->storage_key(), registration->scope_url());
   }
   // TODO(b/228904017):
   //   8.20. Set hasUpdatedResources to true if any of the following are true:
@@ -892,8 +638,9 @@
   DCHECK_EQ(message_loop(), base::MessageLoop::current());
   bool check_promise = !state->job->no_promise_okay;
   if (state->job->no_promise_okay && !state->job->client &&
-      web_context_registrations_.size() > 0) {
-    state->job->client = *(web_context_registrations_.begin());
+      service_worker_context_->web_context_registrations().size() > 0) {
+    state->job->client =
+        *(service_worker_context_->web_context_registrations().begin());
   }
   if ((check_promise && !state->job->promise.get()) || !state->job->client) {
     // The job is already rejected, which means there was an error, or the
@@ -908,8 +655,8 @@
         state->job,
         PromiseErrorData(web::DOMException::kSecurityErr, error.value()));
     if (state->newest_worker == nullptr) {
-      scope_to_registration_map_->RemoveRegistration(state->job->storage_key,
-                                                     state->job->scope_url);
+      service_worker_context_->registration_map()->RemoveRegistration(
+          state->job->storage_key, state->job->scope_url);
     }
     FinishJob(state->job);
     return;
@@ -950,8 +697,8 @@
     // 9.2. If newestWorker is null, then remove registration
     //      map[(registration’s storage key, serialized scopeURL)].
     if (state->newest_worker == nullptr) {
-      scope_to_registration_map_->RemoveRegistration(state->job->storage_key,
-                                                     state->job->scope_url);
+      service_worker_context_->registration_map()->RemoveRegistration(
+          state->job->storage_key, state->job->scope_url);
     }
     // 9.3. Invoke Finish Job with job and abort these steps.
     FinishJob(state->job);
@@ -978,8 +725,8 @@
       "ServiceWorker", state->job->client->web_settings(),
       state->job->client->network_module(), state->registration);
   options.web_options.platform_info = state->job->client->platform_info();
-  options.web_options.service_worker_jobs =
-      state->job->client->service_worker_jobs();
+  options.web_options.service_worker_context =
+      state->job->client->service_worker_context();
   scoped_refptr<ServiceWorkerObject> worker(new ServiceWorkerObject(options));
   // 12. Set worker’s script url to job’s script url, worker’s script
   //     resource to script, worker’s type to job’s worker type, and worker’s
@@ -996,7 +743,8 @@
   bool force_bypass_cache = state->job->force_bypass_cache_flag;
   // 16. Let runResult be the result of running the Run Service Worker
   //     algorithm with worker and forceBypassCache.
-  auto* run_result = RunServiceWorker(worker.get(), force_bypass_cache);
+  auto* run_result = service_worker_context_->RunServiceWorker(
+      worker.get(), force_bypass_cache);
   bool run_result_is_success = run_result;
 
   // Post a task for the remaining steps, to let tasks posted by
@@ -1017,8 +765,8 @@
     // 17.2. If newestWorker is null, then remove registration
     //       map[(registration’s storage key, serialized scopeURL)].
     if (state->newest_worker == nullptr) {
-      scope_to_registration_map_->RemoveRegistration(state->job->storage_key,
-                                                     state->job->scope_url);
+      service_worker_context_->registration_map()->RemoveRegistration(
+          state->job->storage_key, state->job->scope_url);
     }
     // 17.3. Invoke Finish Job with job.
     FinishJob(state->job);
@@ -1029,61 +777,6 @@
   }
 }
 
-std::string* ServiceWorkerJobs::RunServiceWorker(ServiceWorkerObject* worker,
-                                                 bool force_bypass_cache) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::RunServiceWorker()");
-
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  DCHECK(worker);
-  // Algorithm for "Run Service Worker"
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#run-service-worker-algorithm
-
-  // 1. Let unsafeCreationTime be the unsafe shared current time.
-  auto unsafe_creation_time = base::TimeTicks::Now();
-  // 2. If serviceWorker is running, then return serviceWorker’s start status.
-  if (worker->is_running()) {
-    return worker->start_status();
-  }
-  // 3. If serviceWorker’s state is "redundant", then return failure.
-  if (worker->state() == kServiceWorkerStateRedundant) {
-    return nullptr;
-  }
-  // 4. Assert: serviceWorker’s start status is null.
-  DCHECK(worker->start_status() == nullptr);
-  // 5. Let script be serviceWorker’s script resource.
-  // 6. Assert: script is not null.
-  DCHECK(worker->HasScriptResource());
-  // 7. Let startFailed be false.
-  worker->store_start_failed(false);
-  // 8. Let agent be the result of obtaining a service worker agent, and run the
-  //    following steps in that context:
-  // 9. Wait for serviceWorker to be running, or for startFailed to be true.
-  worker->ObtainWebAgentAndWaitUntilDone();
-  // 10. If startFailed is true, then return failure.
-  if (worker->load_start_failed()) {
-    return nullptr;
-  }
-  // 11. Return serviceWorker’s start status.
-  return worker->start_status();
-}
-
-bool ServiceWorkerJobs::WaitForAsynchronousExtensions(
-    const scoped_refptr<ServiceWorkerRegistrationObject>& registration) {
-  // TODO(b/240164388): Investigate a better approach for combining waiting
-  // for the ExtendableEvent while also allowing use of algorithms that run
-  // on the same thread from the event handler.
-  base::TimeTicks wait_start_time = base::TimeTicks::Now();
-  do {
-    if (registration->done_event()->TimedWait(
-            base::TimeDelta::FromMilliseconds(100)))
-      break;
-    base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
-    base::RunLoop().RunUntilIdle();
-  } while ((base::TimeTicks::Now() - wait_start_time) <
-           kWaitForAsynchronousExtensionsTimeout);
-  return registration->done_event()->IsSignaled();
-}
-
 void ServiceWorkerJobs::Install(
     Job* job, const scoped_refptr<ServiceWorkerObject>& worker,
     const scoped_refptr<ServiceWorkerRegistrationObject>& registration) {
@@ -1109,12 +802,13 @@
 
   // 4. Run the Update Registration State algorithm passing registration,
   //    "installing" and worker as the arguments.
-  UpdateRegistrationState(registration, kInstalling, worker);
+  service_worker_context_->UpdateRegistrationState(
+      registration, ServiceWorkerContext::kInstalling, worker);
 
   // 5. Run the Update Worker State algorithm passing registration’s installing
   //    worker and "installing" as the arguments.
-  UpdateWorkerState(registration->installing_worker(),
-                    kServiceWorkerStateInstalling);
+  service_worker_context_->UpdateWorkerState(registration->installing_worker(),
+                                             kServiceWorkerStateInstalling);
   // 6. Assert: job’s job promise is not null.
   DCHECK(job->no_promise_okay || job->promise.get() != nullptr);
   // 7. Invoke Resolve Job Promise with job and registration.
@@ -1123,13 +817,13 @@
   //    registration’s scope url's origin.
   auto registration_origin = loader::Origin(registration->scope_url());
   // 9. For each settingsObject of settingsObjects...
-  for (auto& context : web_context_registrations_) {
+  for (auto& context : service_worker_context_->web_context_registrations()) {
     if (context->environment_settings()->GetOrigin() == registration_origin) {
       // 9. ... queue a task on settingsObject’s responsible event loop in the
       //    DOM manipulation task source to run the following steps:
-      context->message_loop()->task_runner()->PostTask(
+      context->message_loop()->task_runner()->PostBlockingTask(
           FROM_HERE,
-          base::BindOnce(
+          base::Bind(
               [](web::Context* context,
                  scoped_refptr<ServiceWorkerRegistrationObject> registration) {
                 // 9.1. Let registrationObjects be every
@@ -1169,7 +863,8 @@
     bool force_bypass_cache = job->force_bypass_cache_flag;
     // 11.2. If the result of running the Run Service Worker algorithm with
     //       installingWorker and forceBypassCache is failure, then:
-    auto* run_result = RunServiceWorker(installing_worker, force_bypass_cache);
+    auto* run_result = service_worker_context_->RunServiceWorker(
+        installing_worker, force_bypass_cache);
     if (!run_result) {
       // 11.2.1. Set installFailed to true.
       install_failed->store(true);
@@ -1233,7 +928,8 @@
       // This waiting is done inside PostBlockingTask above.
       // 11.3.3. Wait for the step labeled WaitForAsynchronousExtensions to
       //         complete.
-      if (!WaitForAsynchronousExtensions(registration)) {
+      if (!service_worker_context_->WaitForAsynchronousExtensions(
+              registration)) {
         // Timeout
         install_failed->store(true);
       }
@@ -1244,17 +940,18 @@
     // 12.1. Run the Update Worker State algorithm passing registration’s
     //       installing worker and "redundant" as the arguments.
     if (registration->installing_worker()) {
-      UpdateWorkerState(registration->installing_worker(),
-                        kServiceWorkerStateRedundant);
+      service_worker_context_->UpdateWorkerState(
+          registration->installing_worker(), kServiceWorkerStateRedundant);
     }
     // 12.2. Run the Update Registration State algorithm passing registration,
     //       "installing" and null as the arguments.
-    UpdateRegistrationState(registration, kInstalling, nullptr);
+    service_worker_context_->UpdateRegistrationState(
+        registration, ServiceWorkerContext::kInstalling, nullptr);
     // 12.3. If newestWorker is null, then remove registration
     //       map[(registration’s storage key, serialized registration’s
     //       scope url)].
     if (newest_worker == nullptr) {
-      scope_to_registration_map_->RemoveRegistration(
+      service_worker_context_->registration_map()->RemoveRegistration(
           registration->storage_key(), registration->scope_url());
     }
     // 12.4. Invoke Finish Job with job and abort these steps.
@@ -1270,643 +967,37 @@
   // 16. If registration’s waiting worker is not null, then:
   if (registration->waiting_worker()) {
     // 16.1. Terminate registration’s waiting worker.
-    TerminateServiceWorker(registration->waiting_worker());
+    service_worker_context_->TerminateServiceWorker(
+        registration->waiting_worker());
     // 16.2. Run the Update Worker State algorithm passing registration’s
     //       waiting worker and "redundant" as the arguments.
-    UpdateWorkerState(registration->waiting_worker(),
-                      kServiceWorkerStateRedundant);
+    service_worker_context_->UpdateWorkerState(registration->waiting_worker(),
+                                               kServiceWorkerStateRedundant);
   }
   // 17. Run the Update Registration State algorithm passing registration,
   //     "waiting" and registration’s installing worker as the arguments.
-  UpdateRegistrationState(registration, kWaiting,
-                          registration->installing_worker());
+  service_worker_context_->UpdateRegistrationState(
+      registration, ServiceWorkerContext::kWaiting,
+      registration->installing_worker());
   // 18. Run the Update Registration State algorithm passing registration,
   //     "installing" and null as the arguments.
-  UpdateRegistrationState(registration, kInstalling, nullptr);
+  service_worker_context_->UpdateRegistrationState(
+      registration, ServiceWorkerContext::kInstalling, nullptr);
   // 19. Run the Update Worker State algorithm passing registration’s waiting
   //     worker and "installed" as the arguments.
-  UpdateWorkerState(registration->waiting_worker(),
-                    kServiceWorkerStateInstalled);
+  service_worker_context_->UpdateWorkerState(registration->waiting_worker(),
+                                             kServiceWorkerStateInstalled);
   // 20. Invoke Finish Job with job.
   FinishJob(job);
   // 21. Wait for all the tasks queued by Update Worker State invoked in this
   //     algorithm to have executed.
   // TODO(b/234788479): Wait for tasks.
   // 22. Invoke Try Activate with registration.
-  TryActivate(registration);
+  service_worker_context_->TryActivate(registration);
 
   // Persist registration since the waiting_worker has been updated.
-  scope_to_registration_map_->PersistRegistration(registration->storage_key(),
-                                                  registration->scope_url());
-}
-
-bool ServiceWorkerJobs::IsAnyClientUsingRegistration(
-    ServiceWorkerRegistrationObject* registration) {
-  bool any_client_is_using = false;
-  for (auto& context : web_context_registrations_) {
-    // When a service worker client is controlled by a service worker, it is
-    // said that the service worker client is using the service worker’s
-    // containing service worker registration.
-    //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-control
-    if (context->is_controlled_by(registration->active_worker())) {
-      any_client_is_using = true;
-      break;
-    }
-  }
-  return any_client_is_using;
-}
-
-void ServiceWorkerJobs::TryActivate(
-    ServiceWorkerRegistrationObject* registration) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::TryActivate()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Algorithm for Try Activate:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-activate-algorithm
-
-  // 1. If registration’s waiting worker is null, return.
-  if (!registration) return;
-  if (!registration->waiting_worker()) return;
-
-  // 2. If registration’s active worker is not null and registration’s active
-  //    worker's state is "activating", return.
-  if (registration->active_worker() &&
-      (registration->active_worker()->state() == kServiceWorkerStateActivating))
-    return;
-
-  // 3. Invoke Activate with registration if either of the following is true:
-
-  //    - registration’s active worker is null.
-  bool invoke_activate = registration->active_worker() == nullptr;
-
-  if (!invoke_activate) {
-    //    - The result of running Service Worker Has No Pending Events with
-    //      registration’s active worker is true...
-    if (ServiceWorkerHasNoPendingEvents(registration->active_worker())) {
-      //      ... and no service worker client is using registration...
-      bool any_client_using = IsAnyClientUsingRegistration(registration);
-      invoke_activate = !any_client_using;
-      //      ... or registration’s waiting worker's skip waiting flag is
-      //      set.
-      if (!invoke_activate && registration->waiting_worker()->skip_waiting())
-        invoke_activate = true;
-    }
-  }
-
-  if (invoke_activate) Activate(registration);
-}
-
-void ServiceWorkerJobs::Activate(
-    ServiceWorkerRegistrationObject* registration) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::Activate()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Algorithm for Activate:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#activation-algorithm
-
-  // 1. If registration’s waiting worker is null, abort these steps.
-  if (registration->waiting_worker() == nullptr) return;
-  // 2. If registration’s active worker is not null, then:
-  if (registration->active_worker()) {
-    // 2.1. Terminate registration’s active worker.
-    TerminateServiceWorker(registration->active_worker());
-    // 2.2. Run the Update Worker State algorithm passing registration’s active
-    //      worker and "redundant" as the arguments.
-    UpdateWorkerState(registration->active_worker(),
-                      kServiceWorkerStateRedundant);
-  }
-  // 3. Run the Update Registration State algorithm passing registration,
-  //    "active" and registration’s waiting worker as the arguments.
-  UpdateRegistrationState(registration, kActive,
-                          registration->waiting_worker());
-  // 4. Run the Update Registration State algorithm passing registration,
-  //    "waiting" and null as the arguments.
-  UpdateRegistrationState(registration, kWaiting, nullptr);
-  // 5. Run the Update Worker State algorithm passing registration’s active
-  //    worker and "activating" as the arguments.
-  UpdateWorkerState(registration->active_worker(),
-                    kServiceWorkerStateActivating);
-  // 6. Let matchedClients be a list of service worker clients whose creation
-  //    URL matches registration’s storage key and registration’s scope url.
-  std::list<web::Context*> matched_clients;
-  for (auto& context : web_context_registrations_) {
-    url::Origin context_storage_key =
-        url::Origin::Create(context->environment_settings()->creation_url());
-    scoped_refptr<ServiceWorkerRegistrationObject> matched_registration =
-        scope_to_registration_map_->MatchServiceWorkerRegistration(
-            context_storage_key, registration->scope_url());
-    if (matched_registration == registration) {
-      matched_clients.push_back(context);
-    }
-  }
-  // 7. For each client of matchedClients, queue a task on client’s  responsible
-  //    event loop, using the DOM manipulation task source, to run the following
-  //    substeps:
-  for (auto& client : matched_clients) {
-    // 7.1. Let readyPromise be client’s global object's
-    //      ServiceWorkerContainer object’s ready
-    //      promise.
-    // 7.2. If readyPromise is null, then continue.
-    // 7.3. If readyPromise is pending, resolve
-    //      readyPromise with the the result of getting
-    //      the service worker registration object that
-    //      represents registration in readyPromise’s
-    //      relevant settings object.
-    client->message_loop()->task_runner()->PostTask(
-        FROM_HERE,
-        base::BindOnce(&ServiceWorkerContainer::MaybeResolveReadyPromise,
-                       base::Unretained(client->GetWindowOrWorkerGlobalScope()
-                                            ->navigator_base()
-                                            ->service_worker()
-                                            .get()),
-                       base::Unretained(registration)));
-  }
-  // 8. For each client of matchedClients:
-  // 8.1. If client is a window client, unassociate client’s responsible
-  //      document from its application cache, if it has one.
-  // 8.2. Else if client is a shared worker client, unassociate client’s
-  //      global object from its application cache, if it has one.
-  // Cobalt doesn't implement 'application cache':
-  //   https://www.w3.org/TR/2011/WD-html5-20110525/offline.html#applicationcache
-  // 9. For each service worker client client who is using registration:
-  // Note: The spec defines "control" and "use" of a service worker from the
-  // value of the active service worker property of the client environment, but
-  // that property is set here, so here we should not use that exact definition
-  // to determine if the client is using this registration. Instead, we use the
-  // Match Service Worker Registration algorithm to find the registration for a
-  // client and compare it with the registration being activated.
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-use
-  for (const auto& client : web_context_registrations_) {
-    scoped_refptr<ServiceWorkerRegistrationObject> client_registration =
-        scope_to_registration_map_->MatchServiceWorkerRegistration(
-            client->environment_settings()->ObtainStorageKey(),
-            client->environment_settings()->creation_url());
-    // When a service worker client is controlled by a service worker, it is
-    // said that the service worker client is using the service worker’s
-    // containing service worker registration.
-    //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-control
-    if (client_registration.get() == registration) {
-      // 9.1. Set client’s active worker to registration’s active worker.
-      client->set_active_service_worker(registration->active_worker());
-      // 9.2. Invoke Notify Controller Change algorithm with client as the
-      //      argument.
-      NotifyControllerChange(client);
-    }
-  }
-  // 10. Let activeWorker be registration’s active worker.
-  ServiceWorkerObject* active_worker = registration->active_worker();
-  bool activated = true;
-  // 11. If the result of running the Should Skip Event algorithm with
-  //     activeWorker and "activate" is false, then:
-  DCHECK(active_worker);
-  if (!active_worker->ShouldSkipEvent(base::Tokens::activate())) {
-    // 11.1. If the result of running the Run Service Worker algorithm with
-    //       activeWorker is not failure, then:
-    auto* run_result = RunServiceWorker(active_worker);
-    if (run_result) {
-      // 11.1.1. Queue a task task on activeWorker’s event loop using the DOM
-      //         manipulation task source to run the following steps:
-      DCHECK_EQ(active_worker->web_agent()->context(),
-                active_worker->worker_global_scope()
-                    ->environment_settings()
-                    ->context());
-      DCHECK(registration->done_event()->IsSignaled());
-      registration->done_event()->Reset();
-      active_worker->web_agent()
-          ->context()
-          ->message_loop()
-          ->task_runner()
-          ->PostBlockingTask(
-              FROM_HERE,
-              base::Bind(
-                  [](ServiceWorkerObject* active_worker,
-                     base::WaitableEvent* done_event) {
-                    auto done_callback =
-                        base::BindOnce([](base::WaitableEvent* done_event,
-                                          bool) { done_event->Signal(); },
-                                       done_event);
-                    auto* settings = active_worker->web_agent()
-                                         ->context()
-                                         ->environment_settings();
-                    scoped_refptr<ExtendableEvent> event(
-                        new ExtendableEvent(settings, base::Tokens::activate(),
-                                            std::move(done_callback)));
-                    // 11.1.1.1. Let e be the result of creating an event with
-                    //           ExtendableEvent.
-                    // 11.1.1.2. Initialize e’s type attribute to activate.
-                    // 11.1.1.3. Dispatch e at activeWorker’s global object.
-                    active_worker->worker_global_scope()->DispatchEvent(event);
-                    // 11.1.1.4. WaitForAsynchronousExtensions: Wait, in
-                    //           parallel, until e is not active.
-                    if (!event->IsActive()) {
-                      // If the event handler doesn't use waitUntil(), it will
-                      // already no longer be active, and there will never be a
-                      // callback to signal the done event.
-                      done_event->Signal();
-                    }
-                  },
-                  base::Unretained(active_worker), registration->done_event()));
-      // 11.1.2. Wait for task to have executed or been discarded.
-      // This waiting is done inside PostBlockingTask above.
-      // 11.1.3. Wait for the step labeled WaitForAsynchronousExtensions to
-      //         complete.
-      // TODO(b/240164388): Investigate a better approach for combining waiting
-      // for the ExtendableEvent while also allowing use of algorithms that run
-      // on the same thread from the event handler.
-      if (!WaitForAsynchronousExtensions(registration)) {
-        // Timeout
-        activated = false;
-      }
-    } else {
-      activated = false;
-    }
-  }
-  // 12. Run the Update Worker State algorithm passing registration’s active
-  //     worker and "activated" as the arguments.
-  if (activated && registration->active_worker()) {
-    UpdateWorkerState(registration->active_worker(),
-                      kServiceWorkerStateActivated);
-
-    // Persist registration since the waiting_worker has been updated to nullptr
-    // and the active_worker has been updated to the previous waiting_worker.
-    scope_to_registration_map_->PersistRegistration(registration->storage_key(),
-                                                    registration->scope_url());
-  }
-}
-
-void ServiceWorkerJobs::NotifyControllerChange(web::Context* client) {
-  // Algorithm for Notify Controller Change:
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#notify-controller-change-algorithm
-  // 1. Assert: client is not null.
-  DCHECK(client);
-
-  // 2. If client is an environment settings object, queue a task to fire an
-  //    event named controllerchange at the ServiceWorkerContainer object that
-  //    client is associated with.
-  client->message_loop()->task_runner()->PostTask(
-      FROM_HERE, base::Bind(
-                     [](web::Context* client) {
-                       client->GetWindowOrWorkerGlobalScope()
-                           ->navigator_base()
-                           ->service_worker()
-                           ->DispatchEvent(new web::Event(
-                               base::Tokens::controllerchange()));
-                     },
-                     client));
-}
-
-bool ServiceWorkerJobs::ServiceWorkerHasNoPendingEvents(
-    ServiceWorkerObject* worker) {
-  // Algorithm for Service Worker Has No Pending Events
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-has-no-pending-events
-  // TODO(b/240174245): Implement this using the 'set of extended events'.
-  NOTIMPLEMENTED();
-
-  // 1. For each event of worker’s set of extended events:
-  // 1.1. If event is active, return false.
-  // 2. Return true.
-  return true;
-}
-
-void ServiceWorkerJobs::ClearRegistration(
-    ServiceWorkerRegistrationObject* registration) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::ClearRegistration()");
-  // Algorithm for Clear Registration:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clear-registration-algorithm
-  // 1. Run the following steps atomically.
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-
-  // 2. If registration’s installing worker is not null, then:
-  ServiceWorkerObject* installing_worker = registration->installing_worker();
-  if (installing_worker) {
-    // 2.1. Terminate registration’s installing worker.
-    TerminateServiceWorker(installing_worker);
-    // 2.2. Run the Update Worker State algorithm passing registration’s
-    //      installing worker and "redundant" as the arguments.
-    UpdateWorkerState(installing_worker, kServiceWorkerStateRedundant);
-    // 2.3. Run the Update Registration State algorithm passing registration,
-    //      "installing" and null as the arguments.
-    UpdateRegistrationState(registration, kInstalling, nullptr);
-  }
-
-  // 3. If registration’s waiting worker is not null, then:
-  ServiceWorkerObject* waiting_worker = registration->waiting_worker();
-  if (waiting_worker) {
-    // 3.1. Terminate registration’s waiting worker.
-    TerminateServiceWorker(waiting_worker);
-    // 3.2. Run the Update Worker State algorithm passing registration’s
-    //      waiting worker and "redundant" as the arguments.
-    UpdateWorkerState(waiting_worker, kServiceWorkerStateRedundant);
-    // 3.3. Run the Update Registration State algorithm passing registration,
-    //      "waiting" and null as the arguments.
-    UpdateRegistrationState(registration, kWaiting, nullptr);
-  }
-
-  // 4. If registration’s active worker is not null, then:
-  ServiceWorkerObject* active_worker = registration->active_worker();
-  if (active_worker) {
-    // 4.1. Terminate registration’s active worker.
-    TerminateServiceWorker(active_worker);
-    // 4.2. Run the Update Worker State algorithm passing registration’s
-    //      active worker and "redundant" as the arguments.
-    UpdateWorkerState(active_worker, kServiceWorkerStateRedundant);
-    // 4.3. Run the Update Registration State algorithm passing registration,
-    //      "active" and null as the arguments.
-    UpdateRegistrationState(registration, kActive, nullptr);
-  }
-
-  // Persist registration since the waiting_worker and active_worker have
-  // been updated to nullptr. This will remove any persisted registration
-  // if one exists.
-  scope_to_registration_map_->PersistRegistration(registration->storage_key(),
-                                                  registration->scope_url());
-}
-
-void ServiceWorkerJobs::TryClearRegistration(
-    ServiceWorkerRegistrationObject* registration) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::TryClearRegistration()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Algorithm for Try Clear Registration:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-clear-registration-algorithm
-
-  // 1. Invoke Clear Registration with registration if no service worker client
-  // is using registration and all of the following conditions are true:
-  if (IsAnyClientUsingRegistration(registration)) return;
-
-  //    . registration’s installing worker is null or the result of running
-  //      Service Worker Has No Pending Events with registration’s installing
-  //      worker is true.
-  if (registration->installing_worker() &&
-      !ServiceWorkerHasNoPendingEvents(registration->installing_worker()))
-    return;
-
-  //    . registration’s waiting worker is null or the result of running
-  //      Service Worker Has No Pending Events with registration’s waiting
-  //      worker is true.
-  if (registration->waiting_worker() &&
-      !ServiceWorkerHasNoPendingEvents(registration->waiting_worker()))
-    return;
-
-  //    . registration’s active worker is null or the result of running
-  //      ServiceWorker Has No Pending Events with registration’s active worker
-  //      is true.
-  if (registration->active_worker() &&
-      !ServiceWorkerHasNoPendingEvents(registration->active_worker()))
-    return;
-
-  ClearRegistration(registration);
-}
-
-void ServiceWorkerJobs::UpdateRegistrationState(
-    ServiceWorkerRegistrationObject* registration, RegistrationState target,
-    const scoped_refptr<ServiceWorkerObject>& source) {
-  TRACE_EVENT2("cobalt::worker", "ServiceWorkerJobs::UpdateRegistrationState()",
-               "target", target, "source", source);
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  DCHECK(registration);
-  // Algorithm for Update Registration State:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-registration-state-algorithm
-
-  // 1. Let registrationObjects be an array containing all the
-  //    ServiceWorkerRegistration objects associated with registration.
-  // This is implemented with a call to LookupServiceWorkerRegistration for each
-  // registered web context.
-
-  switch (target) {
-    // 2. If target is "installing", then:
-    case kInstalling: {
-      // 2.1. Set registration’s installing worker to source.
-      registration->set_installing_worker(source);
-      // 2.2. For each registrationObject in registrationObjects:
-      for (auto& context : web_context_registrations_) {
-        // 2.2.1. Queue a task to...
-        context->message_loop()->task_runner()->PostTask(
-            FROM_HERE,
-            base::BindOnce(
-                [](web::Context* context,
-                   ServiceWorkerRegistrationObject* registration) {
-                  // 2.2.1. ... set the installing attribute of
-                  //        registrationObject to null if registration’s
-                  //        installing worker is null, or the result of getting
-                  //        the service worker object that represents
-                  //        registration’s installing worker in
-                  //        registrationObject’s relevant settings object.
-                  auto registration_object =
-                      context->LookupServiceWorkerRegistration(registration);
-                  if (registration_object) {
-                    registration_object->set_installing(
-                        context->GetServiceWorker(
-                            registration->installing_worker()));
-                  }
-                },
-                context, base::Unretained(registration)));
-      }
-      break;
-    }
-    // 3. Else if target is "waiting", then:
-    case kWaiting: {
-      // 3.1. Set registration’s waiting worker to source.
-      registration->set_waiting_worker(source);
-      // 3.2. For each registrationObject in registrationObjects:
-      for (auto& context : web_context_registrations_) {
-        // 3.2.1. Queue a task to...
-        context->message_loop()->task_runner()->PostTask(
-            FROM_HERE,
-            base::BindOnce(
-                [](web::Context* context,
-                   ServiceWorkerRegistrationObject* registration) {
-                  // 3.2.1. ... set the waiting attribute of registrationObject
-                  //        to null if registration’s waiting worker is null, or
-                  //        the result of getting the service worker object that
-                  //        represents registration’s waiting worker in
-                  //        registrationObject’s relevant settings object.
-                  auto registration_object =
-                      context->LookupServiceWorkerRegistration(registration);
-                  if (registration_object) {
-                    registration_object->set_waiting(context->GetServiceWorker(
-                        registration->waiting_worker()));
-                  }
-                },
-                context, base::Unretained(registration)));
-      }
-      break;
-    }
-    // 4. Else if target is "active", then:
-    case kActive: {
-      // 4.1. Set registration’s active worker to source.
-      registration->set_active_worker(source);
-      // 4.2. For each registrationObject in registrationObjects:
-      for (auto& context : web_context_registrations_) {
-        // 4.2.1. Queue a task to...
-        context->message_loop()->task_runner()->PostTask(
-            FROM_HERE,
-            base::BindOnce(
-                [](web::Context* context,
-                   ServiceWorkerRegistrationObject* registration) {
-                  // 4.2.1. ... set the active attribute of registrationObject
-                  //        to null if registration’s active worker is null, or
-                  //        the result of getting the service worker object that
-                  //        represents registration’s active worker in
-                  //        registrationObject’s relevant settings object.
-                  auto registration_object =
-                      context->LookupServiceWorkerRegistration(registration);
-                  if (registration_object) {
-                    registration_object->set_active(context->GetServiceWorker(
-                        registration->active_worker()));
-                  }
-                },
-                context, base::Unretained(registration)));
-      }
-      break;
-    }
-    default:
-      NOTREACHED();
-  }
-}
-
-void ServiceWorkerJobs::UpdateWorkerState(ServiceWorkerObject* worker,
-                                          ServiceWorkerState state) {
-  TRACE_EVENT1("cobalt::worker", "ServiceWorkerJobs::UpdateWorkerState()",
-               "state", state);
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  DCHECK(worker);
-  if (!worker) {
-    return;
-  }
-  // Algorithm for Update Worker State:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-state-algorithm
-  // 1. Assert: state is not "parsed".
-  DCHECK_NE(kServiceWorkerStateParsed, state);
-  // 2. Set worker's state to state.
-  worker->set_state(state);
-  auto worker_origin = loader::Origin(worker->script_url());
-  // 3. Let settingsObjects be all environment settings objects whose origin is
-  //    worker's script url's origin.
-  // 4. For each settingsObject of settingsObjects...
-  for (auto& context : web_context_registrations_) {
-    if (context->environment_settings()->GetOrigin() == worker_origin) {
-      // 4. ... queue a task on
-      //    settingsObject's responsible event loop in the DOM manipulation task
-      //    source to run the following steps:
-      context->message_loop()->task_runner()->PostTask(
-          FROM_HERE,
-          base::BindOnce(
-              [](web::Context* context, ServiceWorkerObject* worker,
-                 ServiceWorkerState state) {
-                DCHECK_EQ(context->message_loop(),
-                          base::MessageLoop::current());
-                // 4.1. Let objectMap be settingsObject's service worker object
-                //      map.
-                // 4.2. If objectMap[worker] does not exist, then abort these
-                //      steps.
-                // 4.3. Let  workerObj be objectMap[worker].
-                auto worker_obj = context->LookupServiceWorker(worker);
-                if (worker_obj) {
-                  // 4.4. Set workerObj's state to state.
-                  worker_obj->set_state(state);
-                  // 4.5. Fire an event named statechange at workerObj.
-                  context->message_loop()->task_runner()->PostTask(
-                      FROM_HERE,
-                      base::BindOnce(
-                          [](scoped_refptr<ServiceWorker> worker_obj) {
-                            worker_obj->DispatchEvent(
-                                new web::Event(base::Tokens::statechange()));
-                          },
-                          worker_obj));
-                }
-              },
-              context, base::Unretained(worker), state));
-    }
-  }
-}
-
-void ServiceWorkerJobs::HandleServiceWorkerClientUnload(web::Context* client) {
-  TRACE_EVENT0("cobalt::worker",
-               "ServiceWorkerJobs::HandleServiceWorkerClientUnload()");
-  // Algorithm for Handle Servicer Worker Client Unload:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#on-client-unload-algorithm
-  DCHECK(client);
-  // 1. Run the following steps atomically.
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-
-  // 2. Let registration be the service worker registration used by client.
-  // 3. If registration is null, abort these steps.
-  ServiceWorkerObject* active_service_worker = client->active_service_worker();
-  if (!active_service_worker) return;
-  ServiceWorkerRegistrationObject* registration =
-      active_service_worker->containing_service_worker_registration();
-  if (!registration) return;
-
-  // 4. If any other service worker client is using registration, abort these
-  //    steps.
-  // Ensure the client is already removed from the registrations when this runs.
-  DCHECK(web_context_registrations_.end() ==
-         web_context_registrations_.find(client));
-  if (IsAnyClientUsingRegistration(registration)) return;
-
-  // 5. If registration is unregistered, invoke Try Clear Registration with
-  //    registration.
-  if (scope_to_registration_map_ &&
-      scope_to_registration_map_->IsUnregistered(registration)) {
-    TryClearRegistration(registration);
-  }
-
-  // 6. Invoke Try Activate with registration.
-  TryActivate(registration);
-}
-
-void ServiceWorkerJobs::TerminateServiceWorker(ServiceWorkerObject* worker) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::TerminateServiceWorker()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Algorithm for Terminate Service Worker:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#terminate-service-worker
-  // 1. Run the following steps in parallel with serviceWorker’s main loop:
-  // This runs in the ServiceWorkerRegistry thread.
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-
-  // 1.1. Let serviceWorkerGlobalScope be serviceWorker’s global object.
-  WorkerGlobalScope* service_worker_global_scope =
-      worker->worker_global_scope();
-
-  // 1.2. Set serviceWorkerGlobalScope’s closing flag to true.
-  if (service_worker_global_scope != nullptr)
-    service_worker_global_scope->set_closing_flag(true);
-
-  // 1.3. Remove all the items from serviceWorker’s set of extended events.
-  // TODO(b/240174245): Implement 'set of extended events'.
-
-  // 1.4. If there are any tasks, whose task source is either the handle fetch
-  //      task source or the handle functional event task source, queued in
-  //      serviceWorkerGlobalScope’s event loop’s task queues, queue them to
-  //      serviceWorker’s containing service worker registration’s corresponding
-  //      task queues in the same order using their original task sources, and
-  //      discard all the tasks (including tasks whose task source is neither
-  //      the handle fetch task source nor the handle functional event task
-  //      source) from serviceWorkerGlobalScope’s event loop’s task queues
-  //      without processing them.
-  // TODO(b/234787641): Queue tasks to the registration.
-
-  // Note: This step is not in the spec, but without this step the service
-  // worker object map will always keep an entry with a service worker instance
-  // for the terminated service worker, which besides leaking memory can lead to
-  // unexpected behavior when new service worker objects are created with the
-  // same key for the service worker object map (which in Cobalt's case
-  // happens when a new service worker object is constructed at the same
-  // memory address).
-  for (auto& context : web_context_registrations_) {
-    context->message_loop()->task_runner()->PostBlockingTask(
-        FROM_HERE, base::Bind(
-                       [](web::Context* context, ServiceWorkerObject* worker) {
-                         context->RemoveServiceWorker(worker);
-                       },
-                       context, base::Unretained(worker)));
-  }
-
-  // 1.5. Abort the script currently running in serviceWorker.
-  if (worker->is_running()) {
-    worker->Abort();
-  }
-
-  // 1.6. Set serviceWorker’s start status to null.
-  worker->set_start_status(nullptr);
+  service_worker_context_->registration_map()->PersistRegistration(
+      registration->storage_key(), registration->scope_url());
 }
 
 void ServiceWorkerJobs::Unregister(Job* job) {
@@ -1935,8 +1026,8 @@
   // 2. Let registration be the result of running Get Registration given job’s
   //    storage key and job’s scope url.
   scoped_refptr<ServiceWorkerRegistrationObject> registration =
-      scope_to_registration_map_->GetRegistration(job->storage_key,
-                                                  job->scope_url);
+      service_worker_context_->registration_map()->GetRegistration(
+          job->storage_key, job->scope_url);
 
   // 3. If registration is null, then:
   if (!registration) {
@@ -1950,14 +1041,14 @@
 
   // 4. Remove registration map[(registration’s storage key, job’s scope url)].
   // Keep the registration until this algorithm finishes.
-  scope_to_registration_map_->RemoveRegistration(registration->storage_key(),
-                                                 job->scope_url);
+  service_worker_context_->registration_map()->RemoveRegistration(
+      registration->storage_key(), job->scope_url);
 
   // 5. Invoke Resolve Job Promise with job and true.
   ResolveJobPromise(job, true);
 
   // 6. Invoke Try Clear Registration with registration.
-  TryClearRegistration(registration);
+  service_worker_context_->TryClearRegistration(registration);
 
   // 7. Invoke Finish Job with job.
   FinishJob(job);
@@ -1980,7 +1071,7 @@
   //      job promise with a new exception with errorData and a user
   //      agent-defined message, in equivalentJob’s client's Realm.
   if (job->client && job->promise != nullptr) {
-    DCHECK(IsWebContextRegistered(job->client));
+    DCHECK(service_worker_context_->IsWebContextRegistered(job->client));
     job->client->message_loop()->task_runner()->PostTask(
         FROM_HERE, base::BindOnce(
                        [](std::unique_ptr<JobPromiseType> promise,
@@ -2015,7 +1106,7 @@
   // 2.1 If equivalentJob’s client is null, continue to the next iteration of
   // the loop.
   if (job->client && job->promise != nullptr) {
-    DCHECK(IsWebContextRegistered(job->client));
+    DCHECK(service_worker_context_->IsWebContextRegistered(job->client));
     job->client->message_loop()->task_runner()->PostTask(
         FROM_HERE,
         base::BindOnce(
@@ -2079,783 +1170,6 @@
   }
 }
 
-void ServiceWorkerJobs::MaybeResolveReadyPromiseSubSteps(web::Context* client) {
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Algorithm for Sub steps of ServiceWorkerContainer.ready():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#navigator-service-worker-ready
-
-  //    3.1. Let client by this's service worker client.
-  //    3.2. Let storage key be the result of running obtain a storage
-  //         key given client.
-  url::Origin storage_key = client->environment_settings()->ObtainStorageKey();
-  //    3.3. Let registration be the result of running Match Service
-  //         Worker Registration given storage key and client’s
-  //         creation URL.
-  // TODO(b/234659851): Investigate whether this should use the creation URL
-  // directly instead.
-  const GURL& base_url = client->environment_settings()->creation_url();
-  GURL client_url = base_url.Resolve("");
-  scoped_refptr<ServiceWorkerRegistrationObject> registration =
-      scope_to_registration_map_->MatchServiceWorkerRegistration(storage_key,
-                                                                 client_url);
-  //    3.3. If registration is not null, and registration’s active
-  //         worker is not null, queue a task on readyPromise’s
-  //         relevant settings object's responsible event loop, using
-  //         the DOM manipulation task source, to resolve readyPromise
-  //         with the result of getting the service worker
-  //         registration object that represents registration in
-  //         readyPromise’s relevant settings object.
-  if (registration && registration->active_worker()) {
-    client->message_loop()->task_runner()->PostTask(
-        FROM_HERE,
-        base::BindOnce(&ServiceWorkerContainer::MaybeResolveReadyPromise,
-                       base::Unretained(client->GetWindowOrWorkerGlobalScope()
-                                            ->navigator_base()
-                                            ->service_worker()
-                                            .get()),
-                       registration));
-  }
-}
-
-void ServiceWorkerJobs::GetRegistrationSubSteps(
-    const url::Origin& storage_key, const GURL& client_url,
-    web::Context* client,
-    std::unique_ptr<script::ValuePromiseWrappable::Reference>
-        promise_reference) {
-  TRACE_EVENT0("cobalt::worker",
-               "ServiceWorkerJobs::GetRegistrationSubSteps()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Algorithm for Sub steps of ServiceWorkerContainer.getRegistration():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#navigator-service-worker-getRegistration
-
-  // 8.1. Let registration be the result of running Match Service Worker
-  //      Registration algorithm with clientURL as its argument.
-  scoped_refptr<ServiceWorkerRegistrationObject> registration =
-      scope_to_registration_map_->MatchServiceWorkerRegistration(storage_key,
-                                                                 client_url);
-  // 8.2. If registration is null, resolve promise with undefined and abort
-  //      these steps.
-  // 8.3. Resolve promise with the result of getting the service worker
-  //      registration object that represents registration in promise’s
-  //      relevant settings object.
-  client->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](web::Context* client,
-             std::unique_ptr<script::ValuePromiseWrappable::Reference> promise,
-             scoped_refptr<ServiceWorkerRegistrationObject> registration) {
-            TRACE_EVENT0(
-                "cobalt::worker",
-                "ServiceWorkerJobs::GetRegistrationSubSteps() Resolve");
-            promise->value().Resolve(
-                client->GetServiceWorkerRegistration(registration));
-          },
-          client, std::move(promise_reference), registration));
-}
-
-void ServiceWorkerJobs::GetRegistrationsSubSteps(
-    const url::Origin& storage_key, web::Context* client,
-    std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
-        promise_reference) {
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  std::vector<scoped_refptr<ServiceWorkerRegistrationObject>>
-      registration_objects =
-          scope_to_registration_map_->GetRegistrations(storage_key);
-  client->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](web::Context* client,
-             std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
-                 promise,
-             std::vector<scoped_refptr<ServiceWorkerRegistrationObject>>
-                 registration_objects) {
-            TRACE_EVENT0(
-                "cobalt::worker",
-                "ServiceWorkerJobs::GetRegistrationSubSteps() Resolve");
-            script::Sequence<scoped_refptr<script::Wrappable>> registrations;
-            for (auto registration_object : registration_objects) {
-              registrations.push_back(scoped_refptr<script::Wrappable>(
-                  client->GetServiceWorkerRegistration(registration_object)
-                      .get()));
-            }
-            promise->value().Resolve(std::move(registrations));
-          },
-          client, std::move(promise_reference),
-          std::move(registration_objects)));
-}
-
-void ServiceWorkerJobs::SkipWaitingSubSteps(
-    web::Context* worker_context, ServiceWorkerObject* service_worker,
-    std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::SkipWaitingSubSteps()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Check if the client web context is still active. This may trigger if
-  // skipWaiting() was called and service worker installation fails.
-  if (!IsWebContextRegistered(worker_context)) {
-    promise_reference.release();
-    return;
-  }
-
-  // Algorithm for Sub steps of ServiceWorkerGlobalScope.skipWaiting():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-serviceworkerglobalscope-skipwaiting
-
-  // 2.1. Set service worker's skip waiting flag.
-  service_worker->set_skip_waiting();
-
-  // 2.2. Invoke Try Activate with service worker's containing service worker
-  // registration.
-  TryActivate(service_worker->containing_service_worker_registration());
-
-  // 2.3. Resolve promise with undefined.
-  worker_context->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](std::unique_ptr<script::ValuePromiseVoid::Reference> promise) {
-            promise->value().Resolve();
-          },
-          std::move(promise_reference)));
-}
-
-void ServiceWorkerJobs::WaitUntilSubSteps(
-    ServiceWorkerRegistrationObject* registration) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::WaitUntilSubSteps()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Sub steps for WaitUntil.
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-extendableevent-waituntil
-  // 5.2.2. If registration is unregistered, invoke Try Clear Registration
-  //        with registration.
-  if (scope_to_registration_map_->IsUnregistered(registration)) {
-    TryClearRegistration(registration);
-  }
-  // 5.2.3. If registration is not null, invoke Try Activate with
-  //        registration.
-  if (registration) {
-    TryActivate(registration);
-  }
-}
-
-void ServiceWorkerJobs::ClientsGetSubSteps(
-    web::Context* worker_context,
-    ServiceWorkerObject* associated_service_worker,
-    std::unique_ptr<script::ValuePromiseWrappable::Reference> promise_reference,
-    const std::string& id) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::ClientsGetSubSteps()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Check if the client web context is still active. This may trigger if
-  // Clients.get() was called and service worker installation fails.
-  if (!IsWebContextRegistered(worker_context)) {
-    promise_reference.release();
-    return;
-  }
-  // Parallel sub steps (2) for algorithm for Clients.get(id):
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-get
-  // 2.1. For each service worker client client where the result of running
-  //      obtain a storage key given client equals the associated service
-  //      worker's containing service worker registration's storage key:
-  const url::Origin& storage_key =
-      associated_service_worker->containing_service_worker_registration()
-          ->storage_key();
-  for (auto& client : web_context_registrations_) {
-    url::Origin client_storage_key =
-        client->environment_settings()->ObtainStorageKey();
-    if (client_storage_key.IsSameOriginWith(storage_key)) {
-      // 2.1.1. If client’s id is not id, continue.
-      if (client->environment_settings()->id() != id) continue;
-
-      // 2.1.2. Wait for either client’s execution ready flag to be set or for
-      //        client’s discarded flag to be set.
-      // Web Contexts exist only in the web_context_registrations_ set when they
-      // are both execution ready and not discarded.
-
-      // 2.1.3. If client’s execution ready flag is set, then invoke Resolve Get
-      //        Client Promise with client and promise, and abort these steps.
-      ResolveGetClientPromise(client, worker_context,
-                              std::move(promise_reference));
-      return;
-    }
-  }
-  // 2.2. Resolve promise with undefined.
-  worker_context->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](std::unique_ptr<script::ValuePromiseWrappable::Reference>
-                 promise_reference) {
-            TRACE_EVENT0("cobalt::worker",
-                         "ServiceWorkerJobs::ClientsGetSubSteps() Resolve");
-            promise_reference->value().Resolve(scoped_refptr<Client>());
-          },
-          std::move(promise_reference)));
-}
-
-void ServiceWorkerJobs::ResolveGetClientPromise(
-    web::Context* client, web::Context* worker_context,
-    std::unique_ptr<script::ValuePromiseWrappable::Reference>
-        promise_reference) {
-  TRACE_EVENT0("cobalt::worker",
-               "ServiceWorkerJobs::ResolveGetClientPromise()");
-  // Algorithm for Resolve Get Client Promise:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#resolve-get-client-promise
-
-  // 1. If client is an environment settings object, then:
-  // 1.1. If client is not a secure context, queue a task to reject promise with
-  //      a "SecurityError" DOMException, on promise’s relevant settings
-  //      object's responsible event loop using the DOM manipulation task
-  //      source, and abort these steps.
-  // 2. Else:
-  // 2.1. If client’s creation URL is not a potentially trustworthy URL, queue
-  //      a task to reject promise with a "SecurityError" DOMException, on
-  //      promise’s relevant settings object's responsible event loop using the
-  //      DOM manipulation task source, and abort these steps.
-  // In production, Cobalt requires https, therefore all clients are secure
-  // contexts.
-
-  // 3. If client is an environment settings object and is not a window client,
-  //    then:
-  if (!client->GetWindowOrWorkerGlobalScope()->IsWindow()) {
-    // 3.1. Let clientObject be the result of running Create Client algorithm
-    //      with client as the argument.
-    scoped_refptr<Client> client_object =
-        Client::Create(client->environment_settings());
-
-    // 3.2. Queue a task to resolve promise with clientObject, on promise’s
-    //      relevant settings object's responsible event loop using the DOM
-    //      manipulation task source, and abort these steps.
-    worker_context->message_loop()->task_runner()->PostTask(
-        FROM_HERE,
-        base::BindOnce(
-            [](std::unique_ptr<script::ValuePromiseWrappable::Reference>
-                   promise_reference,
-               scoped_refptr<Client> client_object) {
-              TRACE_EVENT0(
-                  "cobalt::worker",
-                  "ServiceWorkerJobs::ResolveGetClientPromise() Resolve");
-              promise_reference->value().Resolve(client_object);
-            },
-            std::move(promise_reference), client_object));
-    return;
-  }
-  // 4. Else:
-  // 4.1. Let browsingContext be null.
-  // 4.2. If client is an environment settings object, set browsingContext to
-  //      client’s global object's browsing context.
-  // 4.3. Else, set browsingContext to client’s target browsing context.
-  // Note: Cobalt does not implement a distinction between environments and
-  // environment settings objects.
-  // 4.4. Queue a task to run the following steps on browsingContext’s event
-  //      loop using the user interaction task source:
-  // Note: The task below does not currently perform any actual
-  // functionality in the client context. It is included however to help future
-  // implementation for fetching values for WindowClient properties, with
-  // similar logic existing in ClientsMatchAllSubSteps.
-  client->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](web::Context* client, web::Context* worker_context,
-             std::unique_ptr<script::ValuePromiseWrappable::Reference>
-                 promise_reference) {
-            // 4.4.1. Let frameType be the result of running Get Frame Type with
-            //        browsingContext.
-            // Cobalt does not support nested or auxiliary browsing contexts.
-            // 4.4.2. Let visibilityState be browsingContext’s active document's
-            //        visibilityState attribute value.
-            // 4.4.3. Let focusState be the result of running the has focus
-            //        steps with browsingContext’s active document as the
-            //        argument.
-            // Handled in the WindowData constructor.
-            std::unique_ptr<WindowData> window_data(
-                new WindowData(client->environment_settings()));
-
-            // 4.4.4. Let ancestorOriginsList be the empty list.
-            // 4.4.5. If client is a window client, set ancestorOriginsList to
-            //        browsingContext’s active document's relevant global
-            //        object's Location object’s ancestor origins list's
-            //        associated list.
-            // Cobalt does not implement Location.ancestorOrigins.
-
-            // 4.4.6. Queue a task to run the following steps on promise’s
-            //        relevant settings object's responsible event loop using
-            //        the DOM manipulation task source:
-            worker_context->message_loop()->task_runner()->PostTask(
-                FROM_HERE,
-                base::BindOnce(
-                    [](std::unique_ptr<script::ValuePromiseWrappable::Reference>
-                           promise_reference,
-                       std::unique_ptr<WindowData> window_data) {
-                      // 4.4.6.1. If client’s discarded flag is set, resolve
-                      //          promise with undefined and abort these
-                      //          steps.
-                      // 4.4.6.2. Let windowClient be the result of running
-                      //          Create Window Client with client,
-                      //          frameType, visibilityState, focusState,
-                      //          and ancestorOriginsList.
-                      scoped_refptr<Client> window_client =
-                          WindowClient::Create(*window_data);
-                      // 4.4.6.3. Resolve promise with windowClient.
-                      promise_reference->value().Resolve(window_client);
-                    },
-                    std::move(promise_reference), std::move(window_data)));
-          },
-          client, worker_context, std::move(promise_reference)));
-  DCHECK_EQ(nullptr, promise_reference.get());
-}
-
-void ServiceWorkerJobs::ClientsMatchAllSubSteps(
-    web::Context* worker_context,
-    ServiceWorkerObject* associated_service_worker,
-    std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
-        promise_reference,
-    bool include_uncontrolled, ClientType type) {
-  TRACE_EVENT0("cobalt::worker",
-               "ServiceWorkerJobs::ClientsMatchAllSubSteps()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  // Check if the worker web context is still active. This may trigger if
-  // Clients.matchAll() was called and service worker installation fails.
-  if (!IsWebContextRegistered(worker_context)) {
-    promise_reference.release();
-    return;
-  }
-
-  // Parallel sub steps (2) for algorithm for Clients.matchAll():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-matchall
-  // 2.1. Let targetClients be a new list.
-  std::list<web::Context*> target_clients;
-
-  // 2.2. For each service worker client client where the result of running
-  //      obtain a storage key given client equals the associated service
-  //      worker's containing service worker registration's storage key:
-  const url::Origin& storage_key =
-      associated_service_worker->containing_service_worker_registration()
-          ->storage_key();
-  for (auto& client : web_context_registrations_) {
-    url::Origin client_storage_key =
-        client->environment_settings()->ObtainStorageKey();
-    if (client_storage_key.IsSameOriginWith(storage_key)) {
-      // 2.2.1. If client’s execution ready flag is unset or client’s discarded
-      //        flag is set, continue.
-      // Web Contexts exist only in the web_context_registrations_ set when they
-      // are both execution ready and not discarded.
-
-      // 2.2.2. If client is not a secure context, continue.
-      // In production, Cobalt requires https, therefore all workers and their
-      // owners are secure contexts.
-
-      // 2.2.3. If options["includeUncontrolled"] is false, and if client’s
-      //        active service worker is not the associated service worker,
-      //        continue.
-      if (!include_uncontrolled &&
-          (client->active_service_worker() != associated_service_worker)) {
-        continue;
-      }
-
-      // 2.2.4. Add client to targetClients.
-      target_clients.push_back(client);
-    }
-  }
-
-  // 2.3. Let matchedWindowData be a new list.
-  std::unique_ptr<std::vector<WindowData>> matched_window_data(
-      new std::vector<WindowData>);
-
-  // 2.4. Let matchedClients be a new list.
-  std::unique_ptr<std::vector<web::Context*>> matched_clients(
-      new std::vector<web::Context*>);
-
-  // 2.5. For each service worker client client in targetClients:
-  for (auto* client : target_clients) {
-    auto* global_scope = client->GetWindowOrWorkerGlobalScope();
-
-    if ((type == kClientTypeWindow || type == kClientTypeAll) &&
-        (global_scope->IsWindow())) {
-      // 2.5.1. If options["type"] is "window" or "all", and client is not an
-      //        environment settings object or is a window client, then:
-
-      // 2.5.1.1. Let windowData be [ "client" -> client, "ancestorOriginsList"
-      //          -> a new list ].
-      WindowData window_data(client->environment_settings());
-
-      // 2.5.1.2. Let browsingContext be null.
-
-      // 2.5.1.3. Let isClientEnumerable be true.
-      // For Cobalt, isClientEnumerable is always true because the clauses that
-      // would set it to false in 2.5.1.6. do not apply to Cobalt.
-
-      // 2.5.1.4. If client is an environment settings object, set
-      //          browsingContext to client’s global object's browsing context.
-      // 2.5.1.5. Else, set browsingContext to client’s target browsing context.
-      web::Context* browsing_context = client;
-
-      // 2.5.1.6. Queue a task task to run the following substeps on
-      //          browsingContext’s event loop using the user interaction task
-      //          source:
-      // Note: The task below does not currently perform any actual
-      // functionality. It is included however to help future implementation for
-      // fetching values for WindowClient properties, with similar logic
-      // existing in ResolveGetClientPromise.
-      browsing_context->message_loop()->task_runner()->PostBlockingTask(
-          FROM_HERE, base::Bind(
-                         [](WindowData* window_data) {
-                           // 2.5.1.6.1. If browsingContext has been discarded,
-                           //            then set isClientEnumerable to false
-                           //            and abort these steps.
-                           // 2.5.1.6.2. If client is a window client and
-                           //            client’s responsible document is not
-                           //            browsingContext’s active document, then
-                           //            set isClientEnumerable to false and
-                           //            abort these steps.
-                           // In Cobalt, the document of a window browsing
-                           // context doesn't change: When a new document is
-                           // created, a new browsing context is created with
-                           // it.
-
-                           // 2.5.1.6.3. Set windowData["frameType"] to the
-                           //            result of running Get Frame Type with
-                           //            browsingContext.
-                           // Cobalt does not support nested or auxiliary
-                           // browsing contexts.
-                           // 2.5.1.6.4. Set windowData["visibilityState"] to
-                           //            browsingContext’s active document's
-                           //            visibilityState attribute value.
-                           // 2.5.1.6.5. Set windowData["focusState"] to the
-                           //            result of running the has focus steps
-                           //            with browsingContext’s active document
-                           //            as the argument.
-
-                           // 2.5.1.6.6. If client is a window client, then set
-                           //            windowData["ancestorOriginsList"] to
-                           //            browsingContext’s active document's
-                           //            relevant global object's Location
-                           //            object’s ancestor origins list's
-                           //            associated list.
-                           // Cobalt does not implement
-                           // Location.ancestorOrigins.
-                         },
-                         &window_data));
-
-      // 2.5.1.7. Wait for task to have executed.
-      // The task above is posted as a blocking task.
-
-      // 2.5.1.8. If isClientEnumerable is true, then:
-
-      // 2.5.1.8.1. Add windowData to matchedWindowData.
-      matched_window_data->emplace_back(window_data);
-
-      // 2.5.2. Else if options["type"] is "worker" or "all" and client is a
-      //        dedicated worker client, or options["type"] is "sharedworker" or
-      //        "all" and client is a shared worker client, then:
-    } else if (((type == kClientTypeWorker || type == kClientTypeAll) &&
-                global_scope->IsDedicatedWorker())) {
-      // Note: Cobalt does not support shared workers.
-      // 2.5.2.1. Add client to matchedClients.
-      matched_clients->emplace_back(client);
-    }
-  }
-
-  // 2.6. Queue a task to run the following steps on promise’s relevant
-  // settings object's responsible event loop using the DOM manipulation
-  // task source:
-  worker_context->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
-                 promise_reference,
-             std::unique_ptr<std::vector<WindowData>> matched_window_data,
-             std::unique_ptr<std::vector<web::Context*>> matched_clients) {
-            TRACE_EVENT0(
-                "cobalt::worker",
-                "ServiceWorkerJobs::ClientsMatchAllSubSteps() Resolve Promise");
-            // 2.6.1. Let clientObjects be a new list.
-            script::Sequence<scoped_refptr<script::Wrappable>> client_objects;
-
-            // 2.6.2. For each windowData in matchedWindowData:
-            for (auto& window_data : *matched_window_data) {
-              // 2.6.2.1. Let WindowClient be the result of running
-              //          Create Window Client algorithm with
-              //          windowData["client"],
-              //          windowData["frameType"],
-              //          windowData["visibilityState"],
-              //          windowData["focusState"], and
-              //          windowData["ancestorOriginsList"] as the
-              //          arguments.
-              // TODO(b/235838698): Implement WindowClient methods.
-              scoped_refptr<Client> window_client =
-                  WindowClient::Create(window_data);
-
-              // 2.6.2.2. Append WindowClient to clientObjects.
-              client_objects.push_back(window_client);
-            }
-
-            // 2.6.3. For each client in matchedClients:
-            for (auto& client : *matched_clients) {
-              // 2.6.3.1. Let clientObject be the result of running
-              //          Create Client algorithm with client as the
-              //          argument.
-              scoped_refptr<Client> client_object =
-                  Client::Create(client->environment_settings());
-
-              // 2.6.3.2. Append clientObject to clientObjects.
-              client_objects.push_back(client_object);
-            }
-            // 2.6.4. Sort clientObjects such that:
-            //        . WindowClient objects whose browsing context has been
-            //          focused are placed first, sorted in the most recently
-            //          focused order.
-            //        . WindowClient objects whose browsing context has never
-            //          been focused are placed next, sorted in their service
-            //          worker client's creation order.
-            //        . Client objects whose associated service worker client is
-            //          a worker client are placed next, sorted in their service
-            //          worker client's creation order.
-            // TODO(b/235876598): Implement sorting of clientObjects.
-
-            // 2.6.5. Resolve promise with a new frozen array of clientObjects
-            //        in promise’s relevant Realm.
-            promise_reference->value().Resolve(client_objects);
-          },
-          std::move(promise_reference), std::move(matched_window_data),
-          std::move(matched_clients)));
-}
-
-void ServiceWorkerJobs::ClaimSubSteps(
-    web::Context* worker_context,
-    ServiceWorkerObject* associated_service_worker,
-    std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference) {
-  TRACE_EVENT0("cobalt::worker", "ServiceWorkerJobs::ClaimSubSteps()");
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-
-  // Check if the client web context is still active. This may trigger if
-  // Clients.claim() was called and service worker installation fails.
-  if (!IsWebContextRegistered(worker_context)) {
-    promise_reference.release();
-    return;
-  }
-
-  // Parallel sub steps (3) for algorithm for Clients.claim():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-clients-claim
-  std::list<web::Context*> target_clients;
-
-  // 3.1. For each service worker client client where the result of running
-  //      obtain a storage key given client equals the service worker's
-  //      containing service worker registration's storage key:
-  const url::Origin& storage_key =
-      associated_service_worker->containing_service_worker_registration()
-          ->storage_key();
-  for (auto& client : web_context_registrations_) {
-    // Don't claim to be our own service worker.
-    if (client == worker_context) continue;
-    url::Origin client_storage_key =
-        client->environment_settings()->ObtainStorageKey();
-    if (client_storage_key.IsSameOriginWith(storage_key)) {
-      // 3.1.1. If client’s execution ready flag is unset or client’s discarded
-      //        flag is set, continue.
-      // Web Contexts exist only in the web_context_registrations_ set when they
-      // are both execution ready and not discarded.
-
-      // 3.1.2. If client is not a secure context, continue.
-      // In production, Cobalt requires https, therefore all clients are secure
-      // contexts.
-
-      // 3.1.3. Let storage key be the result of running obtain a storage key
-      //        given client.
-      // 3.1.4. Let registration be the result of running Match Service Worker
-      //        Registration given storage key and client’s creation URL.
-      // TODO(b/234659851): Investigate whether this should use the creation
-      // URL directly instead.
-      const GURL& base_url = client->environment_settings()->creation_url();
-      GURL client_url = base_url.Resolve("");
-      scoped_refptr<ServiceWorkerRegistrationObject> registration =
-          scope_to_registration_map_->MatchServiceWorkerRegistration(
-              client_storage_key, client_url);
-
-      // 3.1.5. If registration is not the service worker's containing service
-      //        worker registration, continue.
-      if (registration !=
-          associated_service_worker->containing_service_worker_registration()) {
-        continue;
-      }
-
-      // 3.1.6. If client’s active service worker is not the service worker,
-      //        then:
-      if (client->active_service_worker() != associated_service_worker) {
-        // 3.1.6.1. Invoke Handle Service Worker Client Unload with client as
-        //          the argument.
-        HandleServiceWorkerClientUnload(client);
-
-        // 3.1.6.2. Set client’s active service worker to service worker.
-        client->set_active_service_worker(associated_service_worker);
-
-        // 3.1.6.3. Invoke Notify Controller Change algorithm with client as the
-        //          argument.
-        NotifyControllerChange(client);
-      }
-    }
-  }
-  // 3.2. Resolve promise with undefined.
-  worker_context->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](std::unique_ptr<script::ValuePromiseVoid::Reference> promise) {
-            promise->value().Resolve();
-          },
-          std::move(promise_reference)));
-}
-
-void ServiceWorkerJobs::ServiceWorkerPostMessageSubSteps(
-    ServiceWorkerObject* service_worker, web::Context* incumbent_client,
-    std::unique_ptr<script::DataBuffer> serialize_result) {
-  // Parallel sub steps (6) for algorithm for ServiceWorker.postMessage():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-postmessage-options
-  // 3. Let incumbentGlobal be incumbentSettings’s global object.
-  // Note: The 'incumbent' is the sender of the message.
-  // 6.1 If the result of running the Run Service Worker algorithm with
-  //     serviceWorker is failure, then return.
-  auto* run_result = RunServiceWorker(service_worker);
-  if (!run_result) return;
-  if (!serialize_result) return;
-
-  // 6.2 Queue a task on the DOM manipulation task source to run the following
-  //     steps:
-  incumbent_client->message_loop()->task_runner()->PostTask(
-      FROM_HERE,
-      base::BindOnce(
-          [](ServiceWorkerObject* service_worker,
-             web::Context* incumbent_client,
-             std::unique_ptr<script::DataBuffer> serialize_result) {
-            if (!serialize_result) return;
-
-            web::EventTarget* event_target =
-                service_worker->worker_global_scope();
-            if (!event_target) return;
-
-            web::WindowOrWorkerGlobalScope* incumbent_global =
-                incumbent_client->GetWindowOrWorkerGlobalScope();
-            DCHECK_EQ(incumbent_client->environment_settings(),
-                      incumbent_global->environment_settings());
-            base::TypeId incumbent_type = incumbent_global->GetWrappableType();
-            ServiceWorkerObject* incumbent_worker =
-                incumbent_global->IsServiceWorker()
-                    ? incumbent_global->AsServiceWorker()
-                          ->service_worker_object()
-                    : nullptr;
-            base::MessageLoop* message_loop =
-                event_target->environment_settings()->context()->message_loop();
-            if (!message_loop) {
-              return;
-            }
-            message_loop->task_runner()->PostTask(
-                FROM_HERE,
-                base::BindOnce(
-                    [](const base::TypeId& incumbent_type,
-                       ServiceWorkerObject* incumbent_worker,
-                       web::Context* incumbent_client,
-                       web::EventTarget* event_target,
-                       std::unique_ptr<script::DataBuffer> serialize_result) {
-                      ExtendableMessageEventInit init_dict;
-                      if (incumbent_type ==
-                          base::GetTypeId<ServiceWorkerGlobalScope>()) {
-                        // 6.2.1. Let source be determined by switching on the
-                        //        type of incumbentGlobal:
-                        //        . ServiceWorkerGlobalScope
-                        //          The result of getting the service worker
-                        //          object that represents incumbentGlobal’s
-                        //          service worker in the relevant settings
-                        //          object of serviceWorker’s global object.
-                        init_dict.set_source(ExtendableMessageEvent::SourceType(
-                            event_target->environment_settings()
-                                ->context()
-                                ->GetServiceWorker(incumbent_worker)));
-                      } else if (incumbent_type ==
-                                 base::GetTypeId<dom::Window>()) {
-                        //        . Window
-                        //          a new WindowClient object that represents
-                        //          incumbentGlobal’s relevant settings object.
-                        init_dict.set_source(ExtendableMessageEvent::SourceType(
-                            WindowClient::Create(WindowData(
-                                incumbent_client->environment_settings()))));
-                      } else {
-                        //        . Otherwise
-                        //          a new Client object that represents
-                        //          incumbentGlobal’s associated worker
-                        init_dict.set_source(
-                            ExtendableMessageEvent::SourceType(Client::Create(
-                                incumbent_client->environment_settings())));
-                      }
-
-                      event_target->DispatchEvent(
-                          new worker::ExtendableMessageEvent(
-                              event_target->environment_settings(),
-                              base::Tokens::message(), init_dict,
-                              std::move(serialize_result)));
-                    },
-                    incumbent_type, base::Unretained(incumbent_worker),
-                    // Note: These should probably be weak pointers for when
-                    // the message sender disappears before the recipient
-                    // processes the event, but since base::WeakPtr
-                    // dereferencing isn't thread-safe, that can't actually be
-                    // used here.
-                    base::Unretained(incumbent_client),
-                    base::Unretained(event_target),
-                    std::move(serialize_result)));
-          },
-          base::Unretained(service_worker), base::Unretained(incumbent_client),
-          std::move(serialize_result)));
-}
-
-void ServiceWorkerJobs::RegisterWebContext(web::Context* context) {
-  DCHECK_NE(nullptr, context);
-  web_context_registrations_cleared_.Reset();
-  if (base::MessageLoop::current() != message_loop()) {
-    DCHECK(message_loop());
-    message_loop()->task_runner()->PostTask(
-        FROM_HERE, base::BindOnce(&ServiceWorkerJobs::RegisterWebContext,
-                                  base::Unretained(this), context));
-    return;
-  }
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  DCHECK_EQ(0, web_context_registrations_.count(context));
-  web_context_registrations_.insert(context);
-}
-
-void ServiceWorkerJobs::SetActiveWorker(web::EnvironmentSettings* client) {
-  if (!client) return;
-  if (base::MessageLoop::current() != message_loop()) {
-    DCHECK(message_loop());
-    message_loop()->task_runner()->PostTask(
-        FROM_HERE, base::Bind(&ServiceWorkerJobs::SetActiveWorker,
-                              base::Unretained(this), client));
-    return;
-  }
-  DCHECK(scope_to_registration_map_);
-  scoped_refptr<ServiceWorkerRegistrationObject> client_registration =
-      scope_to_registration_map_->MatchServiceWorkerRegistration(
-          client->ObtainStorageKey(), client->creation_url());
-  if (client_registration.get() && client_registration->active_worker()) {
-    client->context()->set_active_service_worker(
-        client_registration->active_worker());
-  } else {
-    client->context()->set_active_service_worker(nullptr);
-  }
-}
-
-void ServiceWorkerJobs::UnregisterWebContext(web::Context* context) {
-  DCHECK_NE(nullptr, context);
-  if (base::MessageLoop::current() != message_loop()) {
-    // Block to ensure that the context is unregistered before it is destroyed.
-    DCHECK(message_loop());
-    message_loop()->task_runner()->PostBlockingTask(
-        FROM_HERE, base::Bind(&ServiceWorkerJobs::UnregisterWebContext,
-                              base::Unretained(this), context));
-    return;
-  }
-  DCHECK_EQ(message_loop(), base::MessageLoop::current());
-  DCHECK_EQ(1, web_context_registrations_.count(context));
-  web_context_registrations_.erase(context);
-  HandleServiceWorkerClientUnload(context);
-  PrepareForClientShutdown(context);
-  if (web_context_registrations_.empty()) {
-    web_context_registrations_cleared_.Signal();
-  }
-}
-
 void ServiceWorkerJobs::PrepareForClientShutdown(web::Context* client) {
   DCHECK(client);
   if (!client) return;
diff --git a/cobalt/worker/service_worker_jobs.h b/cobalt/worker/service_worker_jobs.h
index 50c4cdf..adabe15 100644
--- a/cobalt/worker/service_worker_jobs.h
+++ b/cobalt/worker/service_worker_jobs.h
@@ -18,16 +18,13 @@
 #include <deque>
 #include <map>
 #include <memory>
-#include <set>
 #include <string>
 #include <utility>
 
-#include "base/memory/ref_counted.h"
 #include "base/memory/scoped_refptr.h"
 #include "base/message_loop/message_loop.h"
 #include "base/optional.h"
 #include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
 #include "base/task/sequence_manager/moveable_auto_lock.h"
 #include "cobalt/loader/fetcher_factory.h"
 #include "cobalt/loader/script_loader_factory.h"
@@ -38,17 +35,9 @@
 #include "cobalt/script/script_value_factory.h"
 #include "cobalt/web/context.h"
 #include "cobalt/web/dom_exception.h"
-#include "cobalt/web/web_settings.h"
-#include "cobalt/worker/client_query_options.h"
-#include "cobalt/worker/frame_type.h"
-#include "cobalt/worker/service_worker.h"
-#include "cobalt/worker/service_worker_consts.h"
 #include "cobalt/worker/service_worker_object.h"
-#include "cobalt/worker/service_worker_registration.h"
-#include "cobalt/worker/service_worker_registration_map.h"
 #include "cobalt/worker/service_worker_registration_object.h"
 #include "cobalt/worker/service_worker_update_via_cache.h"
-#include "cobalt/worker/worker_type.h"
 #include "starboard/common/atomic.h"
 #include "url/gurl.h"
 #include "url/origin.h"
@@ -56,6 +45,8 @@
 namespace cobalt {
 namespace worker {
 
+class ServiceWorkerContext;
+
 // Algorithms for Service Worker Jobs.
 //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#algorithms
 class ServiceWorkerJobs {
@@ -189,101 +180,17 @@
     std::deque<std::unique_ptr<Job>> jobs_;
   };
 
-  ServiceWorkerJobs(web::WebSettings* web_settings,
+  ServiceWorkerJobs(ServiceWorkerContext* service_worker_context,
                     network::NetworkModule* network_module,
-                    web::UserAgentPlatformInfo* platform_info,
-                    base::MessageLoop* message_loop, const GURL& url);
+                    base::MessageLoop* message_loop);
   ~ServiceWorkerJobs();
 
   base::MessageLoop* message_loop() { return message_loop_; }
 
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#start-register-algorithm
-  void StartRegister(const base::Optional<GURL>& scope_url,
-                     const GURL& script_url,
-                     std::unique_ptr<script::ValuePromiseWrappable::Reference>
-                         promise_reference,
-                     web::Context* client, const WorkerType& type,
-                     const ServiceWorkerUpdateViaCache& update_via_cache);
-
-  void MaybeResolveReadyPromiseSubSteps(web::Context* client);
-
-  // Sub steps (8) of ServiceWorkerContainer.getRegistration().
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#navigator-service-worker-getRegistration
-  void GetRegistrationSubSteps(
-      const url::Origin& storage_key, const GURL& client_url,
-      web::Context* client,
-      std::unique_ptr<script::ValuePromiseWrappable::Reference>
-          promise_reference);
-
-  void GetRegistrationsSubSteps(
-      const url::Origin& storage_key, web::Context* client,
-      std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
-          promise_reference);
-
-  // Sub steps (2) of ServiceWorkerGlobalScope.skipWaiting().
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-serviceworkerglobalscope-skipwaiting
-  void SkipWaitingSubSteps(
-      web::Context* worker_context, ServiceWorkerObject* service_worker,
-      std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference);
-
-  // Sub steps for ExtendableEvent.WaitUntil().
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-extendableevent-waituntil
-  void WaitUntilSubSteps(ServiceWorkerRegistrationObject* registration);
-
-  // Parallel sub steps (2) for algorithm for Clients.get(id):
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-get
-  void ClientsGetSubSteps(
-      web::Context* worker_context,
-      ServiceWorkerObject* associated_service_worker,
-      std::unique_ptr<script::ValuePromiseWrappable::Reference>
-          promise_reference,
-      const std::string& id);
-
-  // Algorithm for Resolve Get Client Promise:
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#resolve-get-client-promise
-  void ResolveGetClientPromise(
-      web::Context* client, web::Context* worker_context,
-      std::unique_ptr<script::ValuePromiseWrappable::Reference>
-          promise_reference);
-
-  // Parallel sub steps (2) for algorithm for Clients.matchAll():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clients-matchall
-  void ClientsMatchAllSubSteps(
-      web::Context* worker_context,
-      ServiceWorkerObject* associated_service_worker,
-      std::unique_ptr<script::ValuePromiseSequenceWrappable::Reference>
-          promise_reference,
-      bool include_uncontrolled, ClientType type);
-
-  // Parallel sub steps (3) for algorithm for Clients.claim():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dom-clients-claim
-  void ClaimSubSteps(
-      web::Context* worker_context,
-      ServiceWorkerObject* associated_service_worker,
-      std::unique_ptr<script::ValuePromiseVoid::Reference> promise_reference);
-
-  // Parallel sub steps (6) for algorithm for ServiceWorker.postMessage():
-  //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-postmessage-options
-  void ServiceWorkerPostMessageSubSteps(
-      ServiceWorkerObject* service_worker, web::Context* incumbent_client,
-      std::unique_ptr<script::DataBuffer> serialize_result);
-
-  // Registration of web contexts that may have service workers.
-  void RegisterWebContext(web::Context* context);
-  void UnregisterWebContext(web::Context* context);
-  bool IsWebContextRegistered(web::Context* context) {
-    DCHECK(base::MessageLoop::current() == message_loop());
-    return web_context_registrations_.end() !=
-           web_context_registrations_.find(context);
-  }
-
   // Ensure no references are kept to JS objects for a client that is about to
   // be shutdown.
   void PrepareForClientShutdown(web::Context* client);
 
-  // Set the active worker for a client if there is a matching service worker.
-  void SetActiveWorker(web::EnvironmentSettings* client);
-
   // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#create-job
   std::unique_ptr<Job> CreateJob(
       JobType type, const url::Origin& storage_key, const GURL& scope_url,
@@ -318,21 +225,9 @@
   // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#schedule-job
   void ScheduleJob(std::unique_ptr<Job> job);
 
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#activation-algorithm
-  void Activate(ServiceWorkerRegistrationObject* registration);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#clear-registration-algorithm
-  void ClearRegistration(ServiceWorkerRegistrationObject* registration);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#soft-update
-  void SoftUpdate(ServiceWorkerRegistrationObject* registration,
-                  bool force_bypass_cache);
-
-  void EnsureServiceWorkerStarted(const url::Origin& storage_key,
-                                  const GURL& client_url,
-                                  base::WaitableEvent* done_event);
-
  private:
+  friend class ServiceWorkerContext;
+
   // State used for the 'Update' algorithm.
   struct UpdateJobState : public base::RefCounted<UpdateJobState> {
     UpdateJobState(
@@ -380,8 +275,6 @@
     const std::string message_;
   };
 
-  enum RegistrationState { kInstalling, kWaiting, kActive };
-
   // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-job-equivalent
   bool ReturnJobsAreEquivalent(Job* one, Job* two);
 
@@ -428,66 +321,21 @@
   // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#finish-job-algorithm
   void FinishJob(Job* job);
 
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#run-service-worker-algorithm
-  // The return value is a 'Completion or failure'.
-  // A failure is signaled by returning nullptr. Otherwise, the returned string
-  // points to the value of the Completion returned by the script runner
-  // abstraction.
-  std::string* RunServiceWorker(ServiceWorkerObject* worker,
-                                bool force_bypass_cache = false);
-
   // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#installation-algorithm
   void Install(
       Job* job, const scoped_refptr<ServiceWorkerObject>& worker,
       const scoped_refptr<ServiceWorkerRegistrationObject>& registration);
 
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-activate-algorithm
-  void TryActivate(ServiceWorkerRegistrationObject* registration);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#service-worker-has-no-pending-events
-  bool ServiceWorkerHasNoPendingEvents(ServiceWorkerObject* worker);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-registration-state-algorithm
-  void UpdateRegistrationState(
-      ServiceWorkerRegistrationObject* registration, RegistrationState target,
-      const scoped_refptr<ServiceWorkerObject>& source);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#update-state-algorithm
-  void UpdateWorkerState(ServiceWorkerObject* worker, ServiceWorkerState state);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#on-client-unload-algorithm
-  void HandleServiceWorkerClientUnload(web::Context* client);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#terminate-service-worker
-  void TerminateServiceWorker(ServiceWorkerObject* worker);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#notify-controller-change-algorithm
-  void NotifyControllerChange(web::Context* client);
-
-  // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#try-clear-registration-algorithm
-  void TryClearRegistration(ServiceWorkerRegistrationObject* registration);
-
-  bool IsAnyClientUsingRegistration(
-      ServiceWorkerRegistrationObject* registration);
-
-  // Returns false when the timeout is reached.
-  bool WaitForAsynchronousExtensions(
-      const scoped_refptr<ServiceWorkerRegistrationObject>& registration);
+  ServiceWorkerContext* service_worker_context_;
 
   // FetcherFactory that is used to create a fetcher according to URL.
   std::unique_ptr<loader::FetcherFactory> fetcher_factory_;
   // LoaderFactory that is used to acquire references to resources from a URL.
   std::unique_ptr<loader::ScriptLoaderFactory> script_loader_factory_;
+
   base::MessageLoop* message_loop_;
 
   JobQueueMap job_queue_map_;
-  std::unique_ptr<ServiceWorkerRegistrationMap> scope_to_registration_map_;
-
-  std::set<web::Context*> web_context_registrations_;
-
-  base::WaitableEvent web_context_registrations_cleared_ = {
-      base::WaitableEvent::ResetPolicy::MANUAL,
-      base::WaitableEvent::InitialState::NOT_SIGNALED};
 };
 
 }  // namespace worker
diff --git a/cobalt/worker/service_worker_persistent_settings.cc b/cobalt/worker/service_worker_persistent_settings.cc
index 41a689d..f74d63f 100644
--- a/cobalt/worker/service_worker_persistent_settings.cc
+++ b/cobalt/worker/service_worker_persistent_settings.cc
@@ -31,6 +31,7 @@
 #include "cobalt/script/script_value.h"
 #include "cobalt/web/cache_utils.h"
 #include "cobalt/worker/service_worker_consts.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_jobs.h"
 #include "cobalt/worker/service_worker_registration_object.h"
 #include "cobalt/worker/service_worker_update_via_cache.h"
@@ -171,20 +172,20 @@
     registration_map.insert(std::make_pair(key, registration));
     registration->set_is_persisted(true);
 
-    options_.service_worker_jobs->message_loop()->task_runner()->PostTask(
+    options_.service_worker_context->message_loop()->task_runner()->PostTask(
         FROM_HERE,
-        base::BindOnce(&ServiceWorkerJobs::Activate,
-                       base::Unretained(options_.service_worker_jobs),
+        base::BindOnce(&ServiceWorkerContext::Activate,
+                       base::Unretained(options_.service_worker_context),
                        registration));
 
-    auto job = options_.service_worker_jobs->CreateJobWithoutPromise(
+    auto job = options_.service_worker_context->jobs()->CreateJobWithoutPromise(
         ServiceWorkerJobs::JobType::kUpdate, storage_key, scope,
         registration->waiting_worker()->script_url());
-    options_.service_worker_jobs->message_loop()->task_runner()->PostTask(
-        FROM_HERE,
-        base::BindOnce(&ServiceWorkerJobs::ScheduleJob,
-                       base::Unretained(options_.service_worker_jobs),
-                       std::move(job)));
+    options_.service_worker_context->message_loop()->task_runner()->PostTask(
+        FROM_HERE, base::BindOnce(&ServiceWorkerJobs::ScheduleJob,
+                                  base::Unretained(
+                                      options_.service_worker_context->jobs()),
+                                  std::move(job)));
   }
 }
 
@@ -199,7 +200,7 @@
                                        options_.web_settings,
                                        options_.network_module, registration);
   options.web_options.platform_info = options_.platform_info;
-  options.web_options.service_worker_jobs = options_.service_worker_jobs;
+  options.web_options.service_worker_context = options_.service_worker_context;
   scoped_refptr<ServiceWorkerObject> worker(new ServiceWorkerObject(options));
 
   base::Value* script_url_value = value_dict->FindKeyOfType(
diff --git a/cobalt/worker/service_worker_persistent_settings.h b/cobalt/worker/service_worker_persistent_settings.h
index 1d4fd2e..e595acb 100644
--- a/cobalt/worker/service_worker_persistent_settings.h
+++ b/cobalt/worker/service_worker_persistent_settings.h
@@ -48,16 +48,16 @@
     Options(web::WebSettings* web_settings,
             network::NetworkModule* network_module,
             web::UserAgentPlatformInfo* platform_info,
-            ServiceWorkerJobs* service_worker_jobs, const GURL& url)
+            ServiceWorkerContext* service_worker_context, const GURL& url)
         : web_settings(web_settings),
           network_module(network_module),
           platform_info(platform_info),
-          service_worker_jobs(service_worker_jobs),
+          service_worker_context(service_worker_context),
           url(url) {}
     web::WebSettings* web_settings;
     network::NetworkModule* network_module;
     web::UserAgentPlatformInfo* platform_info;
-    ServiceWorkerJobs* service_worker_jobs;
+    ServiceWorkerContext* service_worker_context;
     const GURL& url;
   };
 
diff --git a/cobalt/worker/service_worker_registration.cc b/cobalt/worker/service_worker_registration.cc
index adba128..514463a 100644
--- a/cobalt/worker/service_worker_registration.cc
+++ b/cobalt/worker/service_worker_registration.cc
@@ -27,6 +27,7 @@
 #include "cobalt/web/environment_settings.h"
 #include "cobalt/web/window_or_worker_global_scope.h"
 #include "cobalt/worker/service_worker.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_global_scope.h"
 #include "cobalt/worker/service_worker_jobs.h"
 #include "cobalt/worker/service_worker_registration_object.h"
@@ -110,20 +111,18 @@
   // 6. Let job be the result of running Create Job with update, registration’s
   //    storage key, registration’s scope url, newestWorker’s script url,
   //    promise, and this's relevant settings object.
-  worker::ServiceWorkerJobs* jobs =
-      environment_settings()->context()->service_worker_jobs();
+  ServiceWorkerJobs* jobs =
+      environment_settings()->context()->service_worker_context()->jobs();
   std::unique_ptr<ServiceWorkerJobs::Job> job = jobs->CreateJob(
       ServiceWorkerJobs::JobType::kUpdate, registration_->storage_key(),
       registration_->scope_url(), newest_worker->script_url(),
       std::move(promise_reference), environment_settings()->context());
-  DCHECK(!promise_reference);
 
   // 7. Set job’s worker type to newestWorker’s type.
   // Cobalt only supports 'classic' worker type.
 
   // 8. Invoke Schedule Job with job.
   jobs->ScheduleJob(std::move(job));
-  DCHECK(!job.get());
 }
 
 script::HandlePromiseBool ServiceWorkerRegistration::Unregister() {
@@ -146,7 +145,7 @@
   base::ThreadTaskRunnerHandle::Get()->PostTask(
       FROM_HERE,
       base::BindOnce(
-          [](worker::ServiceWorkerJobs* jobs, const url::Origin& storage_key,
+          [](ServiceWorkerJobs* jobs, const url::Origin& storage_key,
              const GURL& scope_url,
              std::unique_ptr<script::ValuePromiseBool::Reference>
                  promise_reference,
@@ -163,7 +162,7 @@
             jobs->ScheduleJob(std::move(job));
             DCHECK(!job.get());
           },
-          environment_settings()->context()->service_worker_jobs(),
+          environment_settings()->context()->service_worker_context()->jobs(),
           registration_->storage_key(), registration_->scope_url(),
           std::move(promise_reference), environment_settings()->context()));
   // 5. Return promise.
diff --git a/cobalt/worker/service_worker_registration_map.cc b/cobalt/worker/service_worker_registration_map.cc
index 760c457..3532094 100644
--- a/cobalt/worker/service_worker_registration_map.cc
+++ b/cobalt/worker/service_worker_registration_map.cc
@@ -29,7 +29,7 @@
 #include "cobalt/script/exception_message.h"
 #include "cobalt/script/promise.h"
 #include "cobalt/script/script_value.h"
-#include "cobalt/worker/service_worker_jobs.h"
+#include "cobalt/worker/service_worker_context.h"
 #include "cobalt/worker/service_worker_registration_object.h"
 #include "cobalt/worker/service_worker_update_via_cache.h"
 #include "url/gurl.h"
@@ -252,7 +252,7 @@
 }
 
 void ServiceWorkerRegistrationMap::HandleUserAgentShutdown(
-    ServiceWorkerJobs* jobs) {
+    ServiceWorkerContext* context) {
   TRACE_EVENT0("cobalt::worker",
                "ServiceWorkerRegistrationMap::HandleUserAgentShutdown()");
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
@@ -270,7 +270,7 @@
       // active worker is null, invoke Clear Registration with registration and
       // continue to the next iteration of the loop.
       if (!registration->waiting_worker() && !registration->active_worker()) {
-        jobs->ClearRegistration(registration);
+        context->ClearRegistration(registration);
         continue;
       } else {
         // 1.1.2. Else, set installingWorker to null.
@@ -283,7 +283,7 @@
       // substep in parallel:
 
       // 1.2.1. Invoke Activate with registration.
-      jobs->Activate(registration);
+      context->Activate(registration);
     }
   }
 }
diff --git a/cobalt/worker/service_worker_registration_map.h b/cobalt/worker/service_worker_registration_map.h
index f998319..591f58f 100644
--- a/cobalt/worker/service_worker_registration_map.h
+++ b/cobalt/worker/service_worker_registration_map.h
@@ -37,7 +37,8 @@
 
 namespace cobalt {
 namespace worker {
-class ServiceWorkerJobs;
+
+class ServiceWorkerContext;
 
 // Algorithms for the service worker scope to registration map.
 //   https://www.w3.org/TR/2022/CRD-service-workers-20220712/#dfn-scope-to-registration-map
@@ -69,11 +70,11 @@
   bool IsUnregistered(ServiceWorkerRegistrationObject* registration);
 
   // https://www.w3.org/TR/2022/CRD-service-workers-20220712/#on-user-agent-shutdown-algorithm
-  void HandleUserAgentShutdown(ServiceWorkerJobs* jobs);
+  void HandleUserAgentShutdown(ServiceWorkerContext* context);
 
   void AbortAllActive();
 
-  // Called from the end of ServiceWorkerJobs Install, Activate, and Clear
+  // Called from the end of ServiceWorkerContext Install, Activate, and Clear
   // Registration since these are the cases in which a service worker
   // registration's active_worker or waiting_worker are updated.
   void PersistRegistration(const url::Origin& storage_key, const GURL& scope);
diff --git a/cobalt/worker/worker.cc b/cobalt/worker/worker.cc
index 13fa24b..d01d252 100644
--- a/cobalt/worker/worker.cc
+++ b/cobalt/worker/worker.cc
@@ -348,7 +348,7 @@
 
 void Worker::PostMessage(const script::ValueHandleHolder& message) {
   DCHECK(message_loop());
-  auto serialized_message = script::SerializeScriptValue(message);
+  auto structured_clone = std::make_unique<script::StructuredClone>(message);
   if (base::MessageLoop::current() != message_loop()) {
     // Block until the worker thread is ready to execute code to handle the
     // event.
@@ -356,10 +356,10 @@
     message_loop()->task_runner()->PostTask(
         FROM_HERE, base::BindOnce(&web::MessagePort::PostMessageSerialized,
                                   message_port()->AsWeakPtr(),
-                                  std::move(serialized_message)));
+                                  std::move(structured_clone)));
   } else {
     DCHECK(execution_ready_.IsSignaled());
-    message_port()->PostMessageSerialized(std::move(serialized_message));
+    message_port()->PostMessageSerialized(std::move(structured_clone));
   }
 }
 
diff --git a/cobalt/xhr/xml_http_request.cc b/cobalt/xhr/xml_http_request.cc
index 8de549a..12aee93 100644
--- a/cobalt/xhr/xml_http_request.cc
+++ b/cobalt/xhr/xml_http_request.cc
@@ -1424,7 +1424,7 @@
   // Don't retry, let the caller deal with it.
   url_fetcher_->SetAutomaticallyRetryOn5xx(false);
   url_fetcher_->SetExtraRequestHeaders(request_headers_.ToString());
-  network_module->AddClientHintHeaders(*url_fetcher_);
+  network_module->AddClientHintHeaders(*url_fetcher_, network::kCallTypeXHR);
 
   // We want to do cors check and preflight during redirects
   url_fetcher_->SetStopOnRedirect(true);
diff --git a/components/crash/core/common/BUILD.gn b/components/crash/core/common/BUILD.gn
index e5d44d3..5ea6a38 100644
--- a/components/crash/core/common/BUILD.gn
+++ b/components/crash/core/common/BUILD.gn
@@ -15,7 +15,7 @@
     ":crash_key_utils",
   ]
 
-  if (is_mac || is_ios) {
+  if ((is_mac || is_ios) && !use_cobalt_customizations) {
     public_deps += [ ":zombies" ]
   }
 }
@@ -106,7 +106,7 @@
   ]
 }
 
-if (is_mac || is_ios) {
+if ((is_mac || is_ios) && !use_cobalt_customizations) {
   component("zombies") {
     visibility = [ ":common" ]
 
@@ -126,29 +126,31 @@
   }
 }
 
-source_set("unit_tests") {
-  testonly = true
-  sources = [
-    "crash_key_unittest.cc",
-    "crash_keys_unittest.cc",
-  ]
+if (!use_cobalt_customizations) {
+  source_set("unit_tests") {
+    testonly = true
+    sources = [
+      "crash_key_unittest.cc",
+      "crash_keys_unittest.cc",
+    ]
 
-  deps = [
-    ":common",
-    "//base",
-    "//testing/gtest",
-  ]
+    deps = [
+      ":common",
+      "//base",
+      "//testing/gtest",
+    ]
 
-  if (is_mac || is_ios) {
-    sources += [ "objc_zombie_unittest.mm" ]
-  }
+    if (is_mac || is_ios) {
+      sources += [ "objc_zombie_unittest.mm" ]
+    }
 
-  if (!is_mac && !is_win && !is_fuchsia) {
-    include_dirs = [ "//third_party/breakpad/breakpad/src/" ]
-    sources += [ "crash_key_breakpad_unittest.cc" ]
-  }
+    if (!is_mac && !is_win && !is_fuchsia) {
+      include_dirs = [ "//third_party/breakpad/breakpad/src/" ]
+      sources += [ "crash_key_breakpad_unittest.cc" ]
+    }
 
-  if (is_fuchsia) {
-    sources -= [ "crash_key_unittest.cc" ]
+    if (is_fuchsia) {
+      sources -= [ "crash_key_unittest.cc" ]
+    }
   }
 }
diff --git a/components/crash/core/common/crash_key.h b/components/crash/core/common/crash_key.h
index c96108a..8dd89e2 100644
--- a/components/crash/core/common/crash_key.h
+++ b/components/crash/core/common/crash_key.h
@@ -20,7 +20,8 @@
 // Annotation interface. Because not all platforms use Crashpad yet, a
 // source-compatible interface is provided on top of the older Breakpad
 // storage mechanism.
-#if BUILDFLAG(USE_CRASHPAD_ANNOTATION)
+// TODO(b/286881972): Investigate enabling crashpad support in Cobalt/Telemetry.
+#if BUILDFLAG(USE_CRASHPAD_ANNOTATION) && !defined(STARBOARD)
 #include "third_party/crashpad/crashpad/client/annotation.h"  // nogncheck
 #endif
 
@@ -58,7 +59,7 @@
 //      g_operation_id.Clear()
 //    }
 // \endcode
-#if BUILDFLAG(USE_CRASHPAD_ANNOTATION)
+#if BUILDFLAG(USE_CRASHPAD_ANNOTATION) && !defined(STARBOARD)
 
 template <crashpad::Annotation::ValueSizeType MaxLength>
 using CrashKeyString = crashpad::StringAnnotation<MaxLength>;
@@ -172,7 +173,7 @@
 //    }
 class ScopedCrashKeyString {
  public:
-#if BUILDFLAG(USE_CRASHPAD_ANNOTATION)
+#if BUILDFLAG(USE_CRASHPAD_ANNOTATION) && !defined(STARBOARD)
   using CrashKeyType = crashpad::Annotation;
 #else
   using CrashKeyType = internal::CrashKeyStringImpl;
diff --git a/components/crx_file/BUILD.gn b/components/crx_file/BUILD.gn
index 2b103d2..3a05532 100644
--- a/components/crx_file/BUILD.gn
+++ b/components/crx_file/BUILD.gn
@@ -12,6 +12,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+if (is_starboard) {
+  import("//components/crx_file/testdata/sha1_files.gni")
+}
 import("//third_party/protobuf/proto_library.gni")
 
 # The accompanying crx_creator target has been left behind during the migration
@@ -35,3 +38,60 @@
     "//third_party/protobuf:protobuf_lite",
   ]
 }
+
+if (is_starboard) {
+  action("crx_file_download_test_data") {
+    install_content = true
+
+    script = "//tools/download_from_gcs.py"
+
+    sha_sources = []
+    foreach(sha1_file, sha1_files) {
+      sha_sources += [ string_join("/",
+                                   [
+                                     "testdata",
+                                     sha1_file,
+                                   ]) ]
+    }
+
+    sha_outputs = []
+    subdir = "components/crx_file"
+    outdir = "$sb_static_contents_output_data_dir/test/$subdir"
+    foreach(sha_source, sha_sources) {
+      sha_outputs += [ string_join("/",
+                                   [
+                                     outdir,
+                                     string_replace(sha_source, ".sha1", ""),
+                                   ]) ]
+    }
+
+    sources = sha_sources
+    outputs = sha_outputs
+
+    sha1_dir = rebase_path("testdata", root_build_dir)
+
+    args = [
+      "--bucket",
+      "cobalt-static-storage",
+      "--sha1",
+      sha1_dir,
+      "--output",
+      rebase_path("$outdir/testdata", root_build_dir),
+    ]
+  }
+
+  target(gtest_target_type, "crx_file_test") {
+    testonly = true
+
+    sources = [ "crx_verifier_unittest.cc" ]
+
+    deps = [
+      ":crx_file",
+      "//cobalt/test:run_all_unittests",
+      "//starboard:starboard_headers_only",
+      "//testing/gtest",
+    ]
+
+    data_deps = [ ":crx_file_download_test_data" ]
+  }
+}
diff --git a/components/crx_file/crx_verifier_unittest.cc b/components/crx_file/crx_verifier_unittest.cc
index 8028b7c..4c41e4e 100644
--- a/components/crx_file/crx_verifier_unittest.cc
+++ b/components/crx_file/crx_verifier_unittest.cc
@@ -1,4 +1,4 @@
-// Copyright 2017 The Chromium Authors. All rights reserved.
+// Copyright 2017 The Cobalt Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
@@ -7,11 +7,24 @@
 #include "base/files/file_path.h"
 #include "base/path_service.h"
 #include "base/strings/string_number_conversions.h"
+#if defined(STARBOARD)
+#include "starboard/system.h"
+#endif
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace {
 
 base::FilePath TestFile(const std::string& file) {
+#if defined(STARBOARD)
+  std::vector<char> buf(kSbFileMaxPath);
+  SbSystemGetPath(kSbSystemPathContentDirectory, buf.data(), kSbFileMaxPath);
+  return base::FilePath(buf.data())
+      .AppendASCII("test")
+      .AppendASCII("components")
+      .AppendASCII("crx_file")
+      .AppendASCII("testdata")
+      .AppendASCII(file);
+#else
   base::FilePath path;
   base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
   return path.AppendASCII("components")
@@ -19,6 +32,7 @@
       .AppendASCII("data")
       .AppendASCII("crx_file")
       .AppendASCII(file);
+#endif
 }
 
 constexpr char kOjjHash[] = "ojjgnpkioondelmggbekfhllhdaimnho";
diff --git a/cobalt/account/BUILD.gn b/components/crx_file/testdata/sha1_files.gni
similarity index 68%
copy from cobalt/account/BUILD.gn
copy to components/crx_file/testdata/sha1_files.gni
index 02cce3e..f6f5917 100644
--- a/cobalt/account/BUILD.gn
+++ b/components/crx_file/testdata/sha1_files.gni
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,10 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
-
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
-}
+sha1_files = [
+  "unsigned.crx3.sha1",
+  "valid.crx2.sha1",
+  "valid_no_publisher.crx3.sha1",
+  "valid_publisher.crx3.sha1",
+  "valid_test_publisher.crx3.sha1",
+]
diff --git a/components/crx_file/testdata/unsigned.crx3.sha1 b/components/crx_file/testdata/unsigned.crx3.sha1
new file mode 100644
index 0000000..3913e3d
--- /dev/null
+++ b/components/crx_file/testdata/unsigned.crx3.sha1
@@ -0,0 +1 @@
+ad85238e7e3afe325e6be902aeb018e0d14fe3de
diff --git a/components/crx_file/testdata/valid.crx2.sha1 b/components/crx_file/testdata/valid.crx2.sha1
new file mode 100644
index 0000000..3bde513
--- /dev/null
+++ b/components/crx_file/testdata/valid.crx2.sha1
@@ -0,0 +1 @@
+6bd2e7950cdb59ad8d2fc53bdc43be1c207e8173
diff --git a/components/crx_file/testdata/valid_no_publisher.crx3.sha1 b/components/crx_file/testdata/valid_no_publisher.crx3.sha1
new file mode 100644
index 0000000..9735180
--- /dev/null
+++ b/components/crx_file/testdata/valid_no_publisher.crx3.sha1
@@ -0,0 +1 @@
+baf9dd313fa5c4228fe05cce3d292bd6d7006342
diff --git a/components/crx_file/testdata/valid_publisher.crx3.sha1 b/components/crx_file/testdata/valid_publisher.crx3.sha1
new file mode 100644
index 0000000..d4bbfc1
--- /dev/null
+++ b/components/crx_file/testdata/valid_publisher.crx3.sha1
@@ -0,0 +1 @@
+6fbbf33b4ad56ff25608f975fc78840eb41be1ba
diff --git a/components/crx_file/testdata/valid_test_publisher.crx3.sha1 b/components/crx_file/testdata/valid_test_publisher.crx3.sha1
new file mode 100644
index 0000000..419bb87
--- /dev/null
+++ b/components/crx_file/testdata/valid_test_publisher.crx3.sha1
@@ -0,0 +1 @@
+9059d7419401f8764d6788006747f3407fdba6f0
diff --git a/components/metrics/BUILD.gn b/components/metrics/BUILD.gn
index e17fd20..b7c04f3 100644
--- a/components/metrics/BUILD.gn
+++ b/components/metrics/BUILD.gn
@@ -2,10 +2,7 @@
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
-# TODO(b/283275484): Remove this once test.gni is stubbed for Cobalt.
-if (!use_cobalt_customizations) {
-  import("//testing/test.gni")
-}
+import("//testing/test.gni")
 
 static_library("metrics") {
   sources = [
@@ -146,7 +143,7 @@
     deps += [ ":serialization" ]
   }
 
-  if (is_mac) {
+  if (is_mac && !use_cobalt_customizations) {
     libs = [
       # The below are all needed for drive_metrics_provider_mac.mm.
       "CoreFoundation.framework",
@@ -156,7 +153,7 @@
     ]
   }
 
-  if (is_win) {
+  if (is_win && !use_cobalt_customizations) {
     sources -= [ "machine_id_provider_stub.cc" ]
     deps += [ "//components/browser_watcher:stability_client" ]
     libs = [ "wevtapi.lib" ]
@@ -369,7 +366,7 @@
   ]
 }
 
-if (is_linux) {
+if (is_linux && !use_cobalt_customizations) {
   static_library("serialization") {
     sources = [
       "serialization/metric_sample.cc",
@@ -382,6 +379,7 @@
     ]
   }
 }
+
 # TODO(b/283275474): Re-enable as many of these tests as possible.
 if (!use_cobalt_customizations) {
   source_set("unit_tests") {
diff --git a/components/metrics_services_manager/BUILD.gn b/components/metrics_services_manager/BUILD.gn
index 7be3654..c75766c 100644
--- a/components/metrics_services_manager/BUILD.gn
+++ b/components/metrics_services_manager/BUILD.gn
@@ -19,4 +19,16 @@
     "//components/variations/service",
     "//services/network/public/cpp:cpp",
   ]
+
+  # These dependencies are currently disabled or do not exist in Cobalt.
+  # Eliminating these significantly simplifies bringing in the
+  # metrics_services_manager as a dependendency.
+  if (use_cobalt_customizations) {
+    deps -= [
+      "//components/rappor",
+      "//components/ukm",
+      "//components/variations/service",
+      "//services/network/public/cpp:cpp",
+    ]
+  }
 }
diff --git a/components/metrics_services_manager/metrics_services_manager.cc b/components/metrics_services_manager/metrics_services_manager.cc
index 4952631..9406017 100644
--- a/components/metrics_services_manager/metrics_services_manager.cc
+++ b/components/metrics_services_manager/metrics_services_manager.cc
@@ -13,10 +13,13 @@
 #include "components/metrics/metrics_state_manager.h"
 #include "components/metrics/metrics_switches.h"
 #include "components/metrics_services_manager/metrics_services_manager_client.h"
+#if !defined(STARBOARD)
 #include "components/rappor/rappor_service_impl.h"
+// TODOD(b/284467142): Re-enable when UKM is supported.
 #include "components/ukm/ukm_service.h"
 #include "components/variations/service/variations_service.h"
 #include "services/network/public/cpp/shared_url_loader_factory.h"
+#endif
 
 namespace metrics_services_manager {
 
@@ -41,6 +44,7 @@
   return GetMetricsServiceClient()->GetMetricsService();
 }
 
+#if !defined(STARBOARD)
 rappor::RapporServiceImpl* MetricsServicesManager::GetRapporServiceImpl() {
   DCHECK(thread_checker_.CalledOnValidThread());
   if (!rappor_service_) {
@@ -50,6 +54,7 @@
   return rappor_service_.get();
 }
 
+// TODOD(b/284467142): Re-enable when UKM is supported.
 ukm::UkmService* MetricsServicesManager::GetUkmService() {
   DCHECK(thread_checker_.CalledOnValidThread());
   return GetMetricsServiceClient()->GetUkmService();
@@ -61,6 +66,7 @@
     variations_service_ = client_->CreateVariationsService();
   return variations_service_.get();
 }
+#endif
 
 void MetricsServicesManager::OnPluginLoadingError(
     const base::FilePath& plugin_path) {
@@ -88,6 +94,7 @@
                                                bool current_consent_given,
                                                bool current_may_upload) {
   DCHECK(thread_checker_.CalledOnValidThread());
+#if !defined(STARBOARD)
   // If the user has opted out of metrics, delete local UKM state. We Only check
   // consent for UKM.
   if (consent_given_ && !current_consent_given) {
@@ -97,6 +104,7 @@
       ukm->ResetClientId();
     }
   }
+#endif
 
   // Stash the current permissions so that we can update the RapporServiceImpl
   // correctly when the Rappor preference changes.
@@ -113,7 +121,9 @@
   const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
   if (cmdline->HasSwitch(metrics::switches::kMetricsRecordingOnly)) {
     metrics->StartRecordingForTests();
+#if !defined(STARBOARD)
     GetRapporServiceImpl()->Update(true, false);
+#endif
     return;
   }
 
@@ -130,11 +140,16 @@
     metrics->Stop();
   }
 
+#if !defined(STARBOARD)
+  // TODOD(b/284467142): Re-enable when UKM is supported.
   UpdateUkmService();
 
   GetRapporServiceImpl()->Update(may_record_, may_upload_);
+#endif
 }
 
+#if !defined(STARBOARD)
+// TODOD(b/284467142): Re-enable when UKM is supported.
 void MetricsServicesManager::UpdateUkmService() {
   ukm::UkmService* ukm = GetUkmService();
   if (!ukm)
@@ -159,6 +174,7 @@
     ukm->DisableReporting();
   }
 }
+#endif
 
 void MetricsServicesManager::UpdateUploadPermissions(bool may_upload) {
   if (client_->IsMetricsReportingForceEnabled()) {
diff --git a/components/metrics_services_manager/metrics_services_manager.h b/components/metrics_services_manager/metrics_services_manager.h
index 912bf9a..690d39a 100644
--- a/components/metrics_services_manager/metrics_services_manager.h
+++ b/components/metrics_services_manager/metrics_services_manager.h
@@ -19,12 +19,14 @@
 class MetricsService;
 class MetricsServiceClient;
 class MetricsStateManager;
-}
+}  // namespace metrics
 
+#if !defined(STARBOARD)
 namespace rappor {
 class RapporServiceImpl;
 }
 
+// TODOD(b/284467142): Re-enable when UKM is supported.
 namespace ukm {
 class UkmService;
 }
@@ -32,6 +34,7 @@
 namespace variations {
 class VariationsService;
 }
+#endif
 
 namespace metrics_services_manager {
 
@@ -61,14 +64,17 @@
   // additionally creating the MetricsServiceClient in that case).
   metrics::MetricsService* GetMetricsService();
 
+#if !defined(STARBOARD)
   // Returns the RapporServiceImpl, creating it if it hasn't been created yet.
   rappor::RapporServiceImpl* GetRapporServiceImpl();
 
+  // TODOD(b/284467142): Re-enable when UKM is supported.
   // Returns the UkmService, creating it if it hasn't been created yet.
   ukm::UkmService* GetUkmService();
 
   // Returns the VariationsService, creating it if it hasn't been created yet.
   variations::VariationsService* GetVariationsService();
+#endif
 
   // Should be called when a plugin loading error occurs.
   void OnPluginLoadingError(const base::FilePath& plugin_path);
@@ -83,7 +89,21 @@
   // Gets the current state of metric reporting.
   bool IsMetricsReportingEnabled() const;
 
+// In Cobalt, we need public access to the metrics service clients so we can
+// overwrite the upload behavior and enable/disable metrics programmatically.
+#if defined(STARBOARD)
+  // Returns the MetricsServiceClient, creating it if it hasn't been
+  // created yet (and additionally creating the MetricsService in that case).
+  metrics::MetricsServiceClient* GetMetricsServiceClient();
+
+  // Returns the MetricsServicesManagerClient.
+  MetricsServicesManagerClient* GetMetricsServicesManagerClient() {
+    return client_.get();
+  }
+#endif
+
  private:
+#if !defined(STARBOARD)
   // Update the managed services when permissions for recording/uploading
   // metrics change.
   void UpdateRapporServiceImpl();
@@ -91,14 +111,18 @@
   // Returns the MetricsServiceClient, creating it if it hasn't been
   // created yet (and additionally creating the MetricsService in that case).
   metrics::MetricsServiceClient* GetMetricsServiceClient();
+#endif
 
   metrics::MetricsStateManager* GetMetricsStateManager();
 
   // Update which services are running to match current permissions.
   void UpdateRunningServices();
 
+#if !defined(STARBOARD)
+  // TODOD(b/284467142): Re-enable when UKM is supported.
   // Update the state of UkmService to match current permissions.
   void UpdateUkmService();
+#endif
 
   // Update the managed services when permissions for recording/uploading
   // metrics change.
@@ -124,11 +148,13 @@
   // The MetricsServiceClient. Owns the MetricsService.
   std::unique_ptr<metrics::MetricsServiceClient> metrics_service_client_;
 
+#if !defined(STARBOARD)
   // The RapporServiceImpl, for RAPPOR metric uploads.
   std::unique_ptr<rappor::RapporServiceImpl> rappor_service_;
 
   // The VariationsService, for server-side experiments infrastructure.
   std::unique_ptr<variations::VariationsService> variations_service_;
+#endif
 
   DISALLOW_COPY_AND_ASSIGN(MetricsServicesManager);
 };
diff --git a/components/metrics_services_manager/metrics_services_manager_client.h b/components/metrics_services_manager/metrics_services_manager_client.h
index 138f1e0..adb3730 100644
--- a/components/metrics_services_manager/metrics_services_manager_client.h
+++ b/components/metrics_services_manager/metrics_services_manager_client.h
@@ -14,6 +14,7 @@
 class MetricsServiceClient;
 }
 
+#if !defined(STARBOARD)
 namespace network {
 class SharedURLLoaderFactory;
 }
@@ -25,6 +26,7 @@
 namespace variations {
 class VariationsService;
 }
+#endif
 
 namespace metrics_services_manager {
 
@@ -35,18 +37,22 @@
   virtual ~MetricsServicesManagerClient() {}
 
   // Methods that create the various services in the context of the embedder.
+#if !defined(STARBOARD)
   virtual std::unique_ptr<rappor::RapporServiceImpl>
   CreateRapporServiceImpl() = 0;
   virtual std::unique_ptr<variations::VariationsService>
   CreateVariationsService() = 0;
+#endif
   virtual std::unique_ptr<metrics::MetricsServiceClient>
   CreateMetricsServiceClient() = 0;
   virtual std::unique_ptr<const base::FieldTrial::EntropyProvider>
   CreateEntropyProvider() = 0;
 
+#if !defined(STARBOARD)
   // Returns the URL loader factory which the metrics services should use.
   virtual scoped_refptr<network::SharedURLLoaderFactory>
   GetURLLoaderFactory() = 0;
+#endif
 
   // Returns whether metrics reporting is enabled.
   virtual bool IsMetricsReportingEnabled() = 0;
diff --git a/components/ukm/BUILD.gn b/components/ukm/BUILD.gn
index 6bb8424..d101daa 100644
--- a/components/ukm/BUILD.gn
+++ b/components/ukm/BUILD.gn
@@ -38,6 +38,14 @@
     "//components/variations",
     "//url",
   ]
+
+  if (use_cobalt_customizations) {
+    public_deps -= [
+      "//services/metrics/public/cpp:metrics_cpp",
+      "//services/metrics/public/cpp:ukm_builders",
+      "//services/metrics/public/mojom",
+    ]
+  }
 }
 
 # Helper library for observing signals that we need to clear any local data.
@@ -79,40 +87,43 @@
   ]
 }
 
-source_set("unit_tests") {
-  testonly = true
-  sources = [
-    "observers/sync_disable_observer_unittest.cc",
-    "ukm_service_unittest.cc",
-  ]
+# TODO(b/283275474): Re-enable as many tests as possible.
+if (!use_cobalt_customizations) {
+  source_set("unit_tests") {
+    testonly = true
+    sources = [
+      "observers/sync_disable_observer_unittest.cc",
+      "ukm_service_unittest.cc",
+    ]
 
-  deps = [
-    ":observers",
-    ":test_support",
-    ":ukm",
-    "//base",
-    "//base/test:test_support",
-    "//components/metrics",
-    "//components/metrics:test_support",
-    "//components/prefs:test_support",
-    "//components/sync",
-    "//components/sync:test_support_driver",
-    "//components/sync_preferences:test_support",
-    "//components/variations",
-    "//net:test_support",
-    "//services/metrics/public/cpp:ukm_builders",
-    "//testing/gtest",
-    "//third_party/zlib/google:compression_utils",
-    "//url",
-  ]
-}
+    deps = [
+      ":observers",
+      ":test_support",
+      ":ukm",
+      "//base",
+      "//base/test:test_support",
+      "//components/metrics",
+      "//components/metrics:test_support",
+      "//components/prefs:test_support",
+      "//components/sync",
+      "//components/sync:test_support_driver",
+      "//components/sync_preferences:test_support",
+      "//components/variations",
+      "//net:test_support",
+      "//services/metrics/public/cpp:ukm_builders",
+      "//testing/gtest",
+      "//third_party/zlib/google:compression_utils",
+      "//url",
+    ]
+  }
 
-# Convenience testing target
-test("ukm_unittests") {
-  deps = [
-    ":unit_tests",
-    "//base",
-    "//base/test:test_support",
-    "//components/test:run_all_unittests",
-  ]
+  # Convenience testing target
+  test("ukm_unittests") {
+    deps = [
+      ":unit_tests",
+      "//base",
+      "//base/test:test_support",
+      "//components/test:run_all_unittests",
+    ]
+  }
 }
diff --git a/components/update_client/BUILD.gn b/components/update_client/BUILD.gn
index 1a2fd5f..d83b2e6 100644
--- a/components/update_client/BUILD.gn
+++ b/components/update_client/BUILD.gn
@@ -213,6 +213,7 @@
     "//components/crx_file",
     "//components/prefs",
     "//components/prefs:test_support",
+    "//components/version_info",
     "//crypto",
     "//net",
     "//net:test_support",
@@ -240,11 +241,15 @@
     "//components/prefs:test_support",
     "//crypto",
     "//net:test_support",
-    "//starboard/loader_app",
     "//starboard/loader_app:app_key_files",
     "//starboard/loader_app:drain_file",
     "//starboard/loader_app:installation_manager",
     "//testing/gmock",
     "//testing/gtest",
   ]
+  if (build_with_separate_cobalt_toolchain) {
+    data_deps = [ "//starboard/loader_app($starboard_toolchain)" ]
+  } else {
+    deps += [ "//starboard/loader_app" ]
+  }
 }
diff --git a/components/update_client/unzip/unzip_impl.cc b/components/update_client/unzip/unzip_impl.cc
index 1fa9058..3dcfab8 100644
--- a/components/update_client/unzip/unzip_impl.cc
+++ b/components/update_client/unzip/unzip_impl.cc
@@ -20,6 +20,13 @@
              UnzipCompleteCallback callback) override {
     unzip::Unzip(callback_.Run(), zip_file, destination, std::move(callback));
   }
+#if defined(IN_MEMORY_UPDATES)
+  void Unzip(const std::string& zip_str,
+             const base::FilePath& destination,
+             UnzipCompleteCallback callback) override {
+    unzip::Unzip(callback_.Run(), zip_str, destination, std::move(callback));
+  }
+#endif
 
  private:
   const UnzipChromiumFactory::Callback callback_;
diff --git a/components/update_client/unzip/unzip_impl_cobalt.cc b/components/update_client/unzip/unzip_impl_cobalt.cc
index 40882b5..9b7b82b 100644
--- a/components/update_client/unzip/unzip_impl_cobalt.cc
+++ b/components/update_client/unzip/unzip_impl_cobalt.cc
@@ -1,10 +1,12 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
+// Copyright 2019 The Cobalt Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #include "components/update_client/unzip/unzip_impl_cobalt.h"
 
+#include <string>
 #include <utility>
+
 #include "base/callback.h"
 #include "base/files/file_path.h"
 #include "starboard/time.h"
@@ -23,6 +25,13 @@
              UnzipCompleteCallback callback) override {
     std::move(callback).Run(zip::Unzip(zip_path, output_path));
   }
+#if defined(IN_MEMORY_UPDATES)
+  void Unzip(const std::string& zip_str,
+             const base::FilePath& output_path,
+             UnzipCompleteCallback callback) override {
+    std::move(callback).Run(zip::Unzip(zip_str, output_path));
+  }
+#endif
 };
 
 }  // namespace
diff --git a/components/update_client/unzipper.h b/components/update_client/unzipper.h
index 6aed58c..5d1e602 100644
--- a/components/update_client/unzipper.h
+++ b/components/update_client/unzipper.h
@@ -25,6 +25,12 @@
                      const base::FilePath& destination,
                      UnzipCompleteCallback callback) = 0;
 
+#if defined(IN_MEMORY_UPDATES)
+  virtual void Unzip(const std::string& zip_str,
+                     const base::FilePath& destination,
+                     UnzipCompleteCallback callback) = 0;
+#endif
+
  protected:
   Unzipper() = default;
 
diff --git a/components/variations/BUILD.gn b/components/variations/BUILD.gn
index 1a46296..ad64baf 100644
--- a/components/variations/BUILD.gn
+++ b/components/variations/BUILD.gn
@@ -2,9 +2,7 @@
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
-if (!use_cobalt_customizations) {
-  import("//testing/test.gni")
-}
+import("//testing/test.gni")
 
 if (is_android) {
   import("//build/config/android/rules.gni")
@@ -89,7 +87,7 @@
     ]
   }
 
-  if (is_android || is_ios) {
+  if (!use_cobalt_customizations && (is_android || is_ios)) {
     sources += [
       "variations_request_scheduler_mobile.cc",
       "variations_request_scheduler_mobile.h",
@@ -106,12 +104,12 @@
     "//third_party/zlib/google:compression_utils",
   ]
 
-  if (is_android) {
+  if (is_android && !use_cobalt_customizations) {
     deps += [ ":jni" ]
   }
 }
 
-if (is_android) {
+if (is_android && !use_cobalt_customizations) {
   generate_jni("jni") {
     sources = [
       "android/java/src/org/chromium/components/variations/VariationsAssociatedData.java",
@@ -130,25 +128,25 @@
   }
 }
 
-static_library("test_support") {
-  testonly = true
-  sources = [
-    "variations_params_manager.cc",
-    "variations_params_manager.h",
-  ]
-
-  public_deps = [
-    ":variations",
-  ]
-
-  deps = [
-    "field_trial_config:field_trial_config",
-    "//base/test:test_support",
-  ]
-}
-
 # TODO(b/283258321): Re-enable as many tests as posible.
 if (!use_cobalt_customizations) {
+  static_library("test_support") {
+    testonly = true
+    sources = [
+      "variations_params_manager.cc",
+      "variations_params_manager.h",
+    ]
+
+    public_deps = [
+      ":variations",
+    ]
+
+    deps = [
+      "field_trial_config:field_trial_config",
+      "//base/test:test_support",
+    ]
+  }
+
   source_set("unit_tests") {
     testonly = true
     sources = [
diff --git a/crypto/BUILD.gn b/crypto/BUILD.gn
index 1eeebcd..e1292c4 100644
--- a/crypto/BUILD.gn
+++ b/crypto/BUILD.gn
@@ -3,9 +3,7 @@
 # found in the LICENSE file.
 
 import("//build/config/crypto.gni")
-if (!is_starboard) {
-  import("//testing/test.gni")
-}
+import("//testing/test.gni")
 
 component("crypto") {
   output_name = "crcrypto"  # Avoid colliding with OpenSSL's libcrypto.
diff --git a/docker-compose-windows-internal.yml b/docker-compose-windows-internal.yml
index b21f891..5bf059a 100644
--- a/docker-compose-windows-internal.yml
+++ b/docker-compose-windows-internal.yml
@@ -143,7 +143,7 @@
       <<: *shared-build-env
       PLATFORM: ps4
       VISUAL_STUDIO_VERSION: "2022"
-    image: cobalt-build-ps4
+    image: cobalt-build-ps4-vs2022
     depends_on:
       - cobalt-build-vs2022-win-internal
 
@@ -159,7 +159,7 @@
       <<: *shared-build-env
       PLATFORM: ps5
       VISUAL_STUDIO_VERSION: "2022"
-    image: cobalt-build-ps5
+    image: cobalt-build-ps5-vs2022
     depends_on:
       - cobalt-build-vs2022-win-internal
 
@@ -171,12 +171,14 @@
       args:
         - encoded_keyfile=${ENCODED_GS_SERVICE_KEY_FILE}
         - FROM_IMAGE=cobalt-build-vs2022-win-internal
+        - vs_buildtools_version=17
+        - windows_11_sdk_version=22621
     environment:
       <<: *shared-build-env
       PLATFORM: xb1
       COBALT_CONCURRENT_LINKS: ${COBALT_CONCURRENT_LINKS:-1}
       VISUAL_STUDIO_VERSION: "2022"
-    image: cobalt-build-xb1
+    image: cobalt-build-xb1-vs2022
     depends_on:
       - cobalt-build-vs2022-win-internal
 
@@ -192,6 +194,6 @@
       <<: *shared-build-env
       PLATFORM: nxswitch
       VISUAL_STUDIO_VERSION: "2022"
-    image: cobalt-build-nxswitch
+    image: cobalt-build-nxswitch-vs2022
     depends_on:
       - cobalt-build-vs2022-win-internal
diff --git a/docker-compose.yml b/docker-compose.yml
index 245eff7..c519990 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -58,6 +58,8 @@
   build:
     context: ./docker/linux
     dockerfile: unittest/Dockerfile
+    args:
+      - CLANG_VER=${CLANG_VER:-365097-f7e52fbd-8}
   image: cobalt-linux-x64x11-unittest
   environment:
     - PLATFORM=${PLATFORM:-linux-x64x11}
@@ -435,8 +437,13 @@
 
   linux-x64x11-sbversion12-evergreen:
     <<: *build-common-definitions
-    image: cobalt-build-linux-evergreen
-    depends_on: [ build-linux-evergreen ]
+    build:
+      context: ./docker/linux
+      dockerfile: linux-x64x11/Dockerfile
+      args:
+        - FROM_IMAGE=cobalt-build-evergreen
+    image: cobalt-build-linux-x64x11-evergreen
+    depends_on: [ build-evergreen ]
     environment:
       <<: *shared-build-env
       PLATFORM: linux-x64x11-sbversion-12
@@ -445,11 +452,11 @@
 
   # Example usage of unittest:
   # 1. Build the containers for which you want to unittest
-  # docker-compose up --build --no-start linux-x64x11 unittest
+  # docker-compose up --build --no-start linux-x64x11-unittest
   # 2. Build the 'all' target for the platform you want to test
   # PLATFORM=linux-x64x11 CONFIG=devel TARGET=all docker-compose run linux-x64x11
   # 3. Run the unittests for that target.
-  # PLATFORM=linux-x64x11 CONFIG=devel TARGET=all docker-compose run unittest
+  # PLATFORM=linux-x64x11 CONFIG=devel docker-compose run linux-x64x11-unittest
   linux-x64x11-unittest:
     <<: *shared-unittest-definitions
 
diff --git a/docker/docsite/Dockerfile b/docker/docsite/Dockerfile
index 0b2424e..f4e1592 100644
--- a/docker/docsite/Dockerfile
+++ b/docker/docsite/Dockerfile
@@ -33,12 +33,6 @@
     && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* \
     && rm -rf /var/lib/{apt,dpkg,cache,log}
 
-COPY Gemfile /app/Gemfile
-# Note: This file was generated by running a working version of this Docker
-# container. Then it was committed back to the codebase to be copied over as
-# part of the build steps.
-COPY Gemfile.lock /app/Gemfile.lock
-RUN bundle install --gemfile=/app/Gemfile
 
 # We create and use a non-root user explicitly so that the generated and
 # modified files maintain the same permissions as the user that launched the
@@ -53,6 +47,14 @@
 RUN mkdir /project_out_dir \
     && chown ${USER:-defaultuser}:defaultgroup /project_out_dir
 
+
+COPY Gemfile /app/Gemfile
+# Note: This file was generated by running a working version of this Docker
+# container. Then it was committed back to the codebase to be copied over as
+# part of the build steps.
+COPY Gemfile.lock /app/Gemfile.lock
+RUN bundle install --gemfile=/app/Gemfile
+
 USER ${USER:-defaultuser}
 
 CMD /code/third_party/internal/repo-publishing-toolkit-local/preview-site.sh run
diff --git a/docker/docsite/Gemfile.lock b/docker/docsite/Gemfile.lock
index 074ae8c..96ec167 100644
--- a/docker/docsite/Gemfile.lock
+++ b/docker/docsite/Gemfile.lock
@@ -2,13 +2,13 @@
   remote: https://rubygems.org/
   specs:
     RedCloth (4.2.9)
-    activesupport (6.1.7.2)
+    activesupport (6.1.7.3)
       concurrent-ruby (~> 1.0, >= 1.0.2)
       i18n (>= 1.6, < 2)
       minitest (>= 5.1)
       tzinfo (~> 2.0)
       zeitwerk (~> 2.3)
-    addressable (2.8.1)
+    addressable (2.8.4)
       public_suffix (>= 2.0.2, < 6.0)
     blankslate (2.1.2.4)
     bourbon (7.3.0)
@@ -52,7 +52,7 @@
     html-pipeline (1.9.0)
       activesupport (>= 2)
       nokogiri (~> 1.4)
-    i18n (1.12.0)
+    i18n (1.14.1)
       concurrent-ruby (~> 1.0)
     jekyll (2.4.0)
       classifier-reborn (~> 2.0)
@@ -116,7 +116,7 @@
     pygments.rb (0.6.3)
       posix-spawn (~> 0.3.6)
       yajl-ruby (~> 1.2.0)
-    racc (1.6.2)
+    racc (1.7.0)
     rb-fsevent (0.11.2)
     rb-inotify (0.10.1)
       ffi (~> 1.0)
@@ -132,13 +132,13 @@
     sawyer (0.9.2)
       addressable (>= 2.3.5)
       faraday (>= 0.17.3, < 3)
-    thor (1.2.1)
+    thor (1.2.2)
     toml (0.1.2)
       parslet (~> 1.5.0)
     tzinfo (2.0.6)
       concurrent-ruby (~> 1.0)
     yajl-ruby (1.2.3)
-    zeitwerk (2.6.7)
+    zeitwerk (2.6.8)
 
 PLATFORMS
   ruby
diff --git a/docker/linux/android/Dockerfile b/docker/linux/android/Dockerfile
index 5a14a61..0a949a9 100644
--- a/docker/linux/android/Dockerfile
+++ b/docker/linux/android/Dockerfile
@@ -48,11 +48,11 @@
       --sdk_root=${ANDROID_SDK_ROOT} \
     "build-tools;30.0.0" \
     "build-tools;31.0.0" \
-    "cmake;3.10.2.4988404" \
+    "cmake;3.22.1" \
     "cmdline-tools;1.0" \
     "extras;android;m2repository" \
     "extras;google;m2repository" \
-    "ndk;21.1.6352462" \
+    "ndk;25.2.9519653" \
     "patcher;v4" \
     "platforms;android-30" \
     "platforms;android-31" \
diff --git a/docker/linux/base/build/Dockerfile b/docker/linux/base/build/Dockerfile
index 48ed8ee..4d0306d 100644
--- a/docker/linux/base/build/Dockerfile
+++ b/docker/linux/base/build/Dockerfile
@@ -26,7 +26,6 @@
         ninja-build \
         pkgconf \
         unzip \
-        yasm \
     && /opt/clean-after-apt.sh
 
 # === Get Nodejs pinned LTS version via NVM
@@ -111,5 +110,7 @@
     && echo ${CLANG_16_VER} >> ${CLANG_16_TC_HOME}/cr_build_revision \
     && rm clang-llvmorg-${CLANG_16_VER}.tgz
 
+RUN git config --global --add safe.directory /code
+
 WORKDIR /code
 CMD ["/usr/bin/python","--version"]
diff --git a/docker/linux/unittest/Dockerfile b/docker/linux/unittest/Dockerfile
index c9f7915..3b8c901 100644
--- a/docker/linux/unittest/Dockerfile
+++ b/docker/linux/unittest/Dockerfile
@@ -14,6 +14,8 @@
 
 FROM cobalt-base
 
+ARG HOME=/root
+
 RUN apt update -qqy \
     && apt install -qqy --no-install-recommends \
         libasound2 \
@@ -36,6 +38,22 @@
 COPY ./unittest/requirements.txt /opt/requirements.txt
 RUN python3 -m pip install --require-hashes --no-deps -r /opt/requirements.txt
 
+# === Install Clang 16 toolchain coverage tools.
+ARG TC_ROOT=${HOME}/starboard-toolchains/
+ARG CLANG_16_VER=16-init-17653-g39da55e8-2
+ARG CLANG_16_TC_HOME=${TC_ROOT}/x86_64-linux-gnu-clang-chromium-${CLANG_16_VER}
+ARG CLANG_16_BASE_URL=https://commondatastorage.googleapis.com/chromium-browser-clang
+
+RUN echo ${CLANG_16_BASE_URL}/Linux_x64/llvm-code-coverage-llvmorg-${CLANG_VERSION}.tgz
+
+RUN cd /tmp \
+    && mkdir -p ${CLANG_16_TC_HOME} \
+    && curl --silent -O -J \
+        ${CLANG_16_BASE_URL}/Linux_x64/llvm-code-coverage-llvmorg-${CLANG_16_VER}.tgz \
+    && tar xf llvm-code-coverage-llvmorg-${CLANG_16_VER}.tgz -C ${CLANG_16_TC_HOME} \
+    && echo ${CLANG_16_VER} >> ${CLANG_16_TC_HOME}/cr_build_revision \
+    && rm llvm-code-coverage-llvmorg-${CLANG_16_VER}.tgz
+
 WORKDIR /out
 # Sets the locale in the environment. This is needed for NPLB unit tests.
 ENV LANG en_US.UTF-8
diff --git a/docker/windows/base/build/Dockerfile b/docker/windows/base/build/Dockerfile
index d401ba7..1952773 100644
--- a/docker/windows/base/build/Dockerfile
+++ b/docker/windows/base/build/Dockerfile
@@ -29,6 +29,8 @@
 # of the execution, i.e. the full invocation string.
 COPY ./list_python_processes.py /list_python_processes.py
 
+# Pin Choco to 1.4.0 to avoid required reboot in 2.0.0
+ENV chocolateyVersion '1.4.0'
 # Install deps via chocolatey.
 RUN iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'));`
     mkdir C:\choco-cache;`
diff --git a/net/cert/internal/cert_issuer_source_sync_unittest.h b/net/cert/internal/cert_issuer_source_sync_unittest.h
index cf3eb42..a4c4aa7 100644
--- a/net/cert/internal/cert_issuer_source_sync_unittest.h
+++ b/net/cert/internal/cert_issuer_source_sync_unittest.h
@@ -190,6 +190,7 @@
 REGISTER_TYPED_TEST_CASE_P(CertIssuerSourceSyncNormalizationTest,
                            MultipleMatchesAfterNormalization);
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(CertIssuerSourceSyncNotNormalizedTest);
 template <typename TestDelegate>
 class CertIssuerSourceSyncNotNormalizedTest
     : public CertIssuerSourceSyncTest<TestDelegate> {};
diff --git a/net/third_party/nist-pkits/pkits_testcases-inl.h b/net/third_party/nist-pkits/pkits_testcases-inl.h
index 841a93e..c1c7d5e 100644
--- a/net/third_party/nist-pkits/pkits_testcases-inl.h
+++ b/net/third_party/nist-pkits/pkits_testcases-inl.h
@@ -394,6 +394,7 @@
     Section3ValidRolloverfromPrintableStringtoUTF8StringTest10,
     Section3ValidUTF8StringCaseInsensitiveMatchTest11);
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PkitsTest04BasicCertificateRevocationTests);
 template <typename PkitsTestDelegate>
 class PkitsTest04BasicCertificateRevocationTests
     : public PkitsTest<PkitsTestDelegate> {};
@@ -729,6 +730,7 @@
     Section4InvalidSeparateCertificateandCRLKeysTest20,
     Section4InvalidSeparateCertificateandCRLKeysTest21);
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PkitsTest05VerifyingPathswithSelfIssuedCertificates);
 template <typename PkitsTestDelegate>
 class PkitsTest05VerifyingPathswithSelfIssuedCertificates
     : public PkitsTest<PkitsTestDelegate> {};
@@ -3421,6 +3423,8 @@
     Section13InvalidURInameConstraintsTest37,
     Section13InvalidDNSnameConstraintsTest38);
 
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PkitsTest14DistributionPoints);
 template <typename PkitsTestDelegate>
 class PkitsTest14DistributionPoints : public PkitsTest<PkitsTestDelegate> {};
 TYPED_TEST_CASE_P(PkitsTest14DistributionPoints);
@@ -3972,6 +3976,7 @@
     Section14InvalidcRLIssuerTest34,
     Section14InvalidcRLIssuerTest35);
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PkitsTest15DeltaCRLs);
 template <typename PkitsTestDelegate>
 class PkitsTest15DeltaCRLs : public PkitsTest<PkitsTestDelegate> {};
 TYPED_TEST_CASE_P(PkitsTest15DeltaCRLs);
diff --git a/net/third_party/quic/core/crypto/crypto_server_test.cc b/net/third_party/quic/core/crypto/crypto_server_test.cc
index 5ad875d..60cb6d9 100644
--- a/net/third_party/quic/core/crypto/crypto_server_test.cc
+++ b/net/third_party/quic/core/crypto/crypto_server_test.cc
@@ -1101,6 +1101,7 @@
   EXPECT_EQ(0, memcmp(digest, scid_str.c_str(), scid.size()));
 }
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(CryptoServerTestNoConfig);
 class CryptoServerTestNoConfig : public CryptoServerTest {
  public:
   void SetUp() override {
@@ -1120,6 +1121,7 @@
   CheckRejectReasons(kRejectReasons, QUIC_ARRAYSIZE(kRejectReasons));
 }
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(CryptoServerTestOldVersion);
 class CryptoServerTestOldVersion : public CryptoServerTest {
  public:
   void SetUp() override {
diff --git a/net/url_request/url_fetcher_core.cc b/net/url_request/url_fetcher_core.cc
index e9e1891..39512ed 100644
--- a/net/url_request/url_fetcher_core.cc
+++ b/net/url_request/url_fetcher_core.cc
@@ -174,8 +174,9 @@
 }
 
 void URLFetcherCore::Stop() {
-  if (delegate_task_runner_)  // May be NULL in tests.
+  if (delegate_task_runner_) {  // May be NULL in tests.
     DCHECK(delegate_task_runner_->RunsTasksInCurrentSequence());
+  }
 
   delegate_ = NULL;
   fetcher_ = NULL;
@@ -782,8 +783,11 @@
   if (!extra_request_headers_.IsEmpty())
     request_->SetExtraRequestHeaders(extra_request_headers_);
 
+#if defined(STARBOARD)
   request_->SetLoadTimingInfoCallback(base::Bind(&URLFetcherCore::GetLoadTimingInfo,
       base::Unretained(this)));
+#endif
+
   request_->Start();
 }
 
@@ -1132,6 +1136,14 @@
 #if defined(STARBOARD)
 void URLFetcherCore::GetLoadTimingInfo(
     const net::LoadTimingInfo& timing_info) {
+  delegate_task_runner_->PostTask(
+      FROM_HERE,
+      base::Bind(&URLFetcherCore::GetLoadTimingInfoInDelegateThread,
+                 this, timing_info));
+}
+
+void URLFetcherCore::GetLoadTimingInfoInDelegateThread(
+    const net::LoadTimingInfo& timing_info) {
   // Check if the URLFetcherCore has been stopped before.
   if (delegate_) {
     delegate_->ReportLoadTimingInfo(timing_info);
diff --git a/net/url_request/url_fetcher_core.h b/net/url_request/url_fetcher_core.h
index 2df049f..7c1bbcb 100644
--- a/net/url_request/url_fetcher_core.h
+++ b/net/url_request/url_fetcher_core.h
@@ -165,6 +165,7 @@
   static void SetIgnoreCertificateRequests(bool ignored);
 #if defined (STARBOARD)
   void GetLoadTimingInfo(const net::LoadTimingInfo& timing_info);
+  void GetLoadTimingInfoInDelegateThread(const net::LoadTimingInfo& timing_info);
 #endif  // defined(STARBOARD)
  private:
   friend class base::RefCountedThreadSafe<URLFetcherCore>;
diff --git a/net/websockets/websocket_channel_test.cc b/net/websockets/websocket_channel_test.cc
index 020e50b..5e98d4a 100644
--- a/net/websockets/websocket_channel_test.cc
+++ b/net/websockets/websocket_channel_test.cc
@@ -115,6 +115,7 @@
 
 using ::testing::AnyNumber;
 using ::testing::DefaultValue;
+using ::testing::DoAll;
 using ::testing::InSequence;
 using ::testing::MockFunction;
 using ::testing::NotNull;
diff --git a/starboard/BUILD.gn b/starboard/BUILD.gn
index cd9664a..8227a8e 100644
--- a/starboard/BUILD.gn
+++ b/starboard/BUILD.gn
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import("//starboard/build/config/starboard_target_type.gni")
+
 group("gn_all") {
   testonly = true
 
@@ -39,15 +41,15 @@
   }
 
   if (platform_tests_path == "") {
-    deps += [ ":starboard_platform_tests" ]
+    deps += [ ":starboard_platform_tests($starboard_toolchain)" ]
   } else {
     deps += [ platform_tests_path ]
   }
 
   if (sb_filter_based_player) {
     deps += [
-      "//starboard/shared/starboard/player/filter/testing:player_filter_tests",
-      "//starboard/shared/starboard/player/filter/tools:audio_dmp_player",
+      "//starboard/shared/starboard/player/filter/testing:player_filter_tests($starboard_toolchain)",
+      "//starboard/shared/starboard/player/filter/tools:audio_dmp_player($starboard_toolchain)",
     ]
   }
 
@@ -95,19 +97,25 @@
       "//third_party/llvm-project/compiler-rt:compiler_rt",
       "//third_party/llvm-project/libcxx:cxx",
       "//third_party/llvm-project/libcxxabi:cxxabi",
-      "//third_party/llvm-project/libunwind:unwind_evergreen",
       "//third_party/musl:c",
     ]
+    if (build_with_separate_cobalt_toolchain) {
+      data_deps = [ ":starboard_platform_group($starboard_toolchain)" ]
+    } else {
+      public_deps += [ "//third_party/llvm-project/libunwind:unwind_evergreen" ]
+    }
   } else {
     public_deps += [
-      "//$starboard_path:starboard_platform",
+      ":starboard_platform_group($starboard_toolchain)",
       "//starboard/common",
     ]
 
-    if (sb_is_evergreen_compatible) {
-      public_deps += [ "//third_party/crashpad/wrapper" ]
-    } else {
-      public_deps += [ "//third_party/crashpad/wrapper:wrapper_stub" ]
+    if (!build_with_separate_cobalt_toolchain) {
+      if (sb_is_evergreen_compatible) {
+        public_deps += [ "//third_party/crashpad/wrapper" ]
+      } else {
+        public_deps += [ "//third_party/crashpad/wrapper:wrapper_stub" ]
+      }
     }
 
     if (final_executable_type == "shared_library" &&
@@ -168,17 +176,40 @@
   }
 }
 
-if (platform_tests_path == "") {
-  # If 'starboard_platform_tests' is not defined by the platform, then an
-  # empty 'starboard_platform_tests' target is defined.
-  target(gtest_target_type, "starboard_platform_tests") {
-    testonly = true
-
-    sources = [ "//starboard/common/test_main.cc" ]
-
+if (current_toolchain == starboard_toolchain) {
+  target(starboard_target_type, "starboard_platform_group") {
+    if (starboard_target_type == "shared_library") {
+      build_loader = false
+    }
     public_deps = [
-      ":starboard",
-      "//testing/gmock",
+      "//starboard/client_porting/cwrappers",
+      "//starboard/client_porting/eztime",
+      "//starboard/common",
+      "//starboard/egl_and_gles",
     ]
+    if (sb_is_evergreen_compatible) {
+      public_deps += [ "//third_party/crashpad/wrapper" ]
+    } else {
+      public_deps += [ "//third_party/crashpad/wrapper:wrapper_stub" ]
+    }
+    if (!sb_is_evergreen) {
+      public_deps += [ "//$starboard_path:starboard_platform" ]
+    }
+  }
+
+  if (platform_tests_path == "") {
+    # If 'starboard_platform_tests' is not defined by the platform, then an
+    # empty 'starboard_platform_tests' target is defined.
+    target(starboard_level_gtest_target_type, "starboard_platform_tests") {
+      testonly = true
+
+      sources = [ "//starboard/common/test_main.cc" ]
+
+      public_deps = [
+        ":starboard",
+        "//testing/gmock",
+        "//testing/gtest",
+      ]
+    }
   }
 }
diff --git a/starboard/CHANGELOG.md b/starboard/CHANGELOG.md
index 61ec60b..f113a5d 100644
--- a/starboard/CHANGELOG.md
+++ b/starboard/CHANGELOG.md
@@ -100,6 +100,9 @@
 ### Deprecated kSbHasAc3Audio
 This constant is no longer used and has been deprecated.
 
+### Removed BILINEAR_FILTERING_SUPPORT config
+The unused macro for SB_HAS_BILINEAR_FILTERING_SUPPORT feature has been removed.
+
 ## Version 14
 ### Add MP3, FLAC, and PCM values to SbMediaAudioCodec.
 This makes it possible to support these codecs in the future.
diff --git a/starboard/android/apk/app/src/main/java/dev/cobalt/media/MediaCodecBridge.java b/starboard/android/apk/app/src/main/java/dev/cobalt/media/MediaCodecBridge.java
index 1478b37..9fbf090 100644
--- a/starboard/android/apk/app/src/main/java/dev/cobalt/media/MediaCodecBridge.java
+++ b/starboard/android/apk/app/src/main/java/dev/cobalt/media/MediaCodecBridge.java
@@ -591,6 +591,8 @@
       int width,
       int height,
       int fps,
+      int maxWidth,
+      int maxHeight,
       Surface surface,
       MediaCrypto crypto,
       ColorInfo colorInfo,
@@ -671,10 +673,35 @@
       Log.d(TAG, "Enabled tunnel mode playback on audio session " + tunnelModeAudioSessionId);
     }
 
-    int maxWidth = videoCapabilities.getSupportedWidths().getUpper();
-    int maxHeight = videoCapabilities.getSupportedHeights().getUpper();
+    if (maxWidth > 0 && maxHeight > 0) {
+      Log.i(TAG, "Evaluate maxWidth and maxHeight (%d, %d) passed in", maxWidth, maxHeight);
+    } else {
+      maxWidth = videoCapabilities.getSupportedWidths().getUpper();
+      maxHeight = videoCapabilities.getSupportedHeights().getUpper();
+      Log.i(
+          TAG,
+          "maxWidth and maxHeight not passed in, using result of getSupportedWidths()/Heights()"
+              + " (%d, %d)",
+          maxWidth,
+          maxHeight);
+    }
+
     if (fps > 0) {
-      if (!videoCapabilities.areSizeAndRateSupported(maxWidth, maxHeight, fps)) {
+      if (videoCapabilities.areSizeAndRateSupported(maxWidth, maxHeight, fps)) {
+        Log.i(
+            TAG,
+            "Set maxWidth and maxHeight to (%d, %d)@%d per `areSizeAndRateSupported()`",
+            maxWidth,
+            maxHeight,
+            fps);
+      } else {
+        Log.w(
+            TAG,
+            "maxWidth and maxHeight (%d, %d)@%d not supported per `areSizeAndRateSupported()`,"
+                + " continue searching",
+            maxWidth,
+            maxHeight,
+            fps);
         if (maxHeight >= 4320 && videoCapabilities.areSizeAndRateSupported(7680, 4320, fps)) {
           maxWidth = 7680;
           maxHeight = 4320;
@@ -691,18 +718,40 @@
           maxWidth = 1920;
           maxHeight = 1080;
         }
+        Log.i(
+            TAG,
+            "Set maxWidth and maxHeight to (%d, %d)@%d per `areSizeAndRateSupported()`",
+            maxWidth,
+            maxHeight,
+            fps);
       }
     } else {
-      if (maxHeight >= 2160 && videoCapabilities.isSizeSupported(3840, 2160)) {
-        maxWidth = 3840;
-        maxHeight = 2160;
-      } else if (maxHeight >= 1080 && videoCapabilities.isSizeSupported(1920, 1080)) {
-        maxWidth = 1920;
-        maxHeight = 1080;
+      if (maxHeight >= 480 && videoCapabilities.isSizeSupported(maxWidth, maxHeight)) {
+        // Technically we can do this check for all resolutions, but only check for resolution with
+        // height more than 480p to minimize production impact.  To use a lower resolution is more
+        // to reduce memory footprint, and optimize for lower resolution isn't as helpful anyway.
+        Log.i(
+            TAG,
+            "Set maxWidth and maxHeight to (%d, %d) per `isSizeSupported()`",
+            maxWidth,
+            maxHeight);
       } else {
-        Log.e(TAG, "Failed to find a compatible resolution");
-        maxWidth = 1920;
-        maxHeight = 1080;
+        if (maxHeight >= 2160 && videoCapabilities.isSizeSupported(3840, 2160)) {
+          maxWidth = 3840;
+          maxHeight = 2160;
+        } else if (maxHeight >= 1080 && videoCapabilities.isSizeSupported(1920, 1080)) {
+          maxWidth = 1920;
+          maxHeight = 1080;
+        } else {
+          Log.e(TAG, "Failed to find a compatible resolution");
+          maxWidth = 1920;
+          maxHeight = 1080;
+        }
+        Log.i(
+            TAG,
+            "Set maxWidth and maxHeight to (%d, %d) per `isSizeSupported()`",
+            maxWidth,
+            maxHeight);
       }
     }
 
diff --git a/starboard/android/apk/build.gradle b/starboard/android/apk/build.gradle
index 1247002..0860801 100644
--- a/starboard/android/apk/build.gradle
+++ b/starboard/android/apk/build.gradle
@@ -17,7 +17,7 @@
 buildscript {
     repositories {
         google()
-        jcenter()
+        mavenCentral()
     }
     dependencies {
         classpath 'com.android.tools.build:gradle:7.0.2'
@@ -30,7 +30,7 @@
 allprojects {
     repositories {
         google()
-        jcenter()
+        mavenCentral()
     }
     gradle.projectsEvaluated {
         tasks.withType(JavaCompile) {
diff --git a/starboard/android/arm/toolchain/BUILD.gn b/starboard/android/arm/toolchain/BUILD.gn
index 427eb0b..b49df51 100644
--- a/starboard/android/arm/toolchain/BUILD.gn
+++ b/starboard/android/arm/toolchain/BUILD.gn
@@ -22,8 +22,8 @@
   cxx = "$prefix/armv7a-linux-androideabi${android_ndk_api_level}-clang++"
   ld = cxx
   ar = "$prefix/arm-linux-androideabi-readelf"
-  ar = "$prefix/arm-linux-androideabi-ar"
-  nm = "$prefix/arm-linux-androideabi-nm"
+  ar = "ar"
+  nm = "nm"
 
   toolchain_args = {
     is_clang = true
@@ -36,8 +36,8 @@
   cxx = "$prefix/armv7a-linux-androideabi${android_ndk_api_level}-clang++"
   ld = cxx
   ar = "$prefix/arm-linux-androideabi-readelf"
-  ar = "$prefix/arm-linux-androideabi-ar"
-  nm = "$prefix/arm-linux-androideabi-nm"
+  ar = "ar"
+  nm = "nm"
 
   toolchain_args = {
     is_starboard = false
diff --git a/testing/gmock/scripts/generator/cpp/__init__.py b/starboard/android/arm64/cobalt/__init__.py
old mode 100755
new mode 100644
similarity index 100%
rename from testing/gmock/scripts/generator/cpp/__init__.py
rename to starboard/android/arm64/cobalt/__init__.py
diff --git a/starboard/android/arm64/cobalt/configuration.py b/starboard/android/arm64/cobalt/configuration.py
new file mode 100644
index 0000000..e6b0c7d
--- /dev/null
+++ b/starboard/android/arm64/cobalt/configuration.py
@@ -0,0 +1,34 @@
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Starboard Android x86 Cobalt configuration."""
+
+from starboard.android.shared.cobalt import configuration
+from starboard.tools.testing import test_filter
+
+
+class CobaltAndroidArm64Configuration(configuration.CobaltAndroidConfiguration):
+  """Starboard Android Arm64 Cobalt configuration."""
+
+  def GetTestFilters(self):
+    filters = super().GetTestFilters()
+    for target, tests in self.__FILTERED_TESTS.items():
+      filters.extend(test_filter.TestFilter(target, test) for test in tests)
+    return filters
+
+  # A map of failing or crashing tests per target
+  __FILTERED_TESTS = {  # pylint: disable=invalid-name
+      'renderer_test': [
+          'LottieCoveragePixelTest/LottiePixelTest.Run/skottie_luma_matte_json',
+      ]
+  }
diff --git a/starboard/android/arm64/toolchain/BUILD.gn b/starboard/android/arm64/toolchain/BUILD.gn
index 6c98a14..923694b 100644
--- a/starboard/android/arm64/toolchain/BUILD.gn
+++ b/starboard/android/arm64/toolchain/BUILD.gn
@@ -21,9 +21,9 @@
   cc = "$prefix/aarch64-linux-android${android_ndk_api_level}-clang"
   cxx = "$prefix/aarch64-linux-android${android_ndk_api_level}-clang++"
   ld = cxx
-  readelf = "$prefix/aarch64-linux-android-readelf"
-  ar = "$prefix/aarch64-linux-android-ar"
-  nm = "$prefix/aarch64-linux-android-nm"
+  readelf = "readelf"
+  ar = "ar"
+  nm = "nm"
 
   toolchain_args = {
     is_clang = true
diff --git a/starboard/android/arm64/vulkan/toolchain/BUILD.gn b/starboard/android/arm64/vulkan/toolchain/BUILD.gn
index 6c98a14..923694b 100644
--- a/starboard/android/arm64/vulkan/toolchain/BUILD.gn
+++ b/starboard/android/arm64/vulkan/toolchain/BUILD.gn
@@ -21,9 +21,9 @@
   cc = "$prefix/aarch64-linux-android${android_ndk_api_level}-clang"
   cxx = "$prefix/aarch64-linux-android${android_ndk_api_level}-clang++"
   ld = cxx
-  readelf = "$prefix/aarch64-linux-android-readelf"
-  ar = "$prefix/aarch64-linux-android-ar"
-  nm = "$prefix/aarch64-linux-android-nm"
+  readelf = "readelf"
+  ar = "ar"
+  nm = "nm"
 
   toolchain_args = {
     is_clang = true
diff --git a/starboard/android/shared/BUILD.gn b/starboard/android/shared/BUILD.gn
index 23f2537..d8a79e3 100644
--- a/starboard/android/shared/BUILD.gn
+++ b/starboard/android/shared/BUILD.gn
@@ -439,14 +439,6 @@
     "//third_party/opus",
   ]
 
-  if (is_internal_build) {
-    sources += [
-      "//internal/starboard/android/shared/internal/input_events_filter.cc",
-      "//internal/starboard/android/shared/internal/input_events_filter.h",
-    ]
-    defines = [ "STARBOARD_INPUT_EVENTS_FILTER" ]
-  }
-
   if (sb_is_evergreen_compatible) {
     sources -= [
       "crash_handler.cc",
diff --git a/starboard/android/shared/application_android.cc b/starboard/android/shared/application_android.cc
index 0f81e1d..0334d1f 100644
--- a/starboard/android/shared/application_android.cc
+++ b/starboard/android/shared/application_android.cc
@@ -436,12 +436,6 @@
     const GameActivityKeyEvent* event) {
   bool result = false;
 
-#ifdef STARBOARD_INPUT_EVENTS_FILTER
-  if (!input_events_filter_.ShouldProcessKeyEvent(event)) {
-    return result;
-  }
-#endif
-
   ScopedLock lock(input_mutex_);
   if (!input_events_generator_) {
     return false;
diff --git a/starboard/android/shared/application_android.h b/starboard/android/shared/application_android.h
index 336ea9c..d023e74 100644
--- a/starboard/android/shared/application_android.h
+++ b/starboard/android/shared/application_android.h
@@ -22,9 +22,6 @@
 #include <vector>
 
 #include "game-activity/GameActivity.h"
-#ifdef STARBOARD_INPUT_EVENTS_FILTER
-#include "internal/starboard/android/shared/internal/input_events_filter.h"
-#endif
 #include "starboard/android/shared/input_events_generator.h"
 #include "starboard/android/shared/jni_env_ext.h"
 #include "starboard/atomic.h"
@@ -168,10 +165,6 @@
   Mutex input_mutex_;
   scoped_ptr<InputEventsGenerator> input_events_generator_;
 
-#ifdef STARBOARD_INPUT_EVENTS_FILTER
-  internal::InputEventsFilter input_events_filter_;
-#endif
-
   bool last_is_accessibility_high_contrast_text_enabled_;
 
   jobject resource_overlay_;
diff --git a/starboard/android/shared/cobalt/configuration.py b/starboard/android/shared/cobalt/configuration.py
index 7bc2ffb..eb1e814 100644
--- a/starboard/android/shared/cobalt/configuration.py
+++ b/starboard/android/shared/cobalt/configuration.py
@@ -78,6 +78,9 @@
           # test explicitly tries to allocate too much texture memory, we cannot
           # run it on Android platforms.
           'StressTest.TooManyTextures',
+
+          # TODO(b/288107692) Failing with NDK 25.2 upgrade, re-enable
+          'PixelTest.TooManyGlyphs',
       ],
       'zip_unittests': [
           # These tests, and zipping in general, rely on the ability to iterate
diff --git a/starboard/android/shared/configuration_public.h b/starboard/android/shared/configuration_public.h
index 7a11187..3620d7b 100644
--- a/starboard/android/shared/configuration_public.h
+++ b/starboard/android/shared/configuration_public.h
@@ -108,11 +108,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 1
diff --git a/starboard/android/shared/download_sdk.sh b/starboard/android/shared/download_sdk.sh
index e05cef4..d940454 100755
--- a/starboard/android/shared/download_sdk.sh
+++ b/starboard/android/shared/download_sdk.sh
@@ -45,11 +45,11 @@
 # Update the installation
 ${SDK_MANAGER_TOOL} --sdk_root=${ANDROID_SDK_ROOT} \
     "build-tools;31.0.0" \
-    "cmake;3.10.2.4988404" \
+    "cmake;3.22.1" \
     "cmdline-tools;1.0" \
     "extras;android;m2repository" \
     "extras;google;m2repository" \
-    "ndk;21.1.6352462" \
+    "ndk;25.2.9519653" \
     "patcher;v4" \
     "platforms;android-31" \
     "platform-tools"
diff --git a/starboard/android/shared/input_events_generator.cc b/starboard/android/shared/input_events_generator.cc
index a8ef1e5..0b345242 100644
--- a/starboard/android/shared/input_events_generator.cc
+++ b/starboard/android/shared/input_events_generator.cc
@@ -232,6 +232,10 @@
       return kSbKeyMediaRewind;
     case AKEYCODE_MEDIA_FAST_FORWARD:
       return kSbKeyMediaFastForward;
+#if SB_API_VERSION >= 15
+    case AKEYCODE_MEDIA_RECORD:
+      return kSbKeyRecord;
+#endif
 
     // TV Remote specific
     case AKEYCODE_CHANNEL_UP:
diff --git a/starboard/android/shared/media_codec_bridge.cc b/starboard/android/shared/media_codec_bridge.cc
index 6cc41e6..298ea0c 100644
--- a/starboard/android/shared/media_codec_bridge.cc
+++ b/starboard/android/shared/media_codec_bridge.cc
@@ -218,6 +218,8 @@
     int width,
     int height,
     int fps,
+    optional<int> max_width,
+    optional<int> max_height,
     Handler* handler,
     jobject j_surface,
     jobject j_media_crypto,
@@ -229,6 +231,9 @@
     bool force_improved_support_check,
     std::string* error_message) {
   SB_DCHECK(error_message);
+  SB_DCHECK(max_width.has_engaged() == max_height.has_engaged());
+  SB_DCHECK(max_width.value_or(1920) > 0);
+  SB_DCHECK(max_height.value_or(1080) > 0);
 
   const char* mime = SupportedVideoCodecToMimeType(video_codec);
   if (!mime) {
@@ -310,16 +315,16 @@
       new MediaCodecBridge(handler));
   env->CallStaticVoidMethodOrAbort(
       "dev/cobalt/media/MediaCodecBridge", "createVideoMediaCodecBridge",
-      "(JLjava/lang/String;Ljava/lang/String;IIILandroid/view/Surface;"
+      "(JLjava/lang/String;Ljava/lang/String;IIIIILandroid/view/Surface;"
       "Landroid/media/MediaCrypto;"
       "Ldev/cobalt/media/MediaCodecBridge$ColorInfo;"
       "I"
       "Ldev/cobalt/media/MediaCodecBridge$CreateMediaCodecBridgeResult;)"
       "V",
       reinterpret_cast<jlong>(native_media_codec_bridge.get()), j_mime.Get(),
-      j_decoder_name.Get(), width, height, fps, j_surface, j_media_crypto,
-      j_color_info.Get(), tunnel_mode_audio_session_id,
-      j_create_media_codec_bridge_result.Get());
+      j_decoder_name.Get(), width, height, fps, max_width.value_or(-1),
+      max_height.value_or(-1), j_surface, j_media_crypto, j_color_info.Get(),
+      tunnel_mode_audio_session_id, j_create_media_codec_bridge_result.Get());
 
   jobject j_media_codec_bridge = env->CallObjectMethodOrAbort(
       j_create_media_codec_bridge_result.Get(), "mediaCodecBridge",
diff --git a/starboard/android/shared/media_codec_bridge.h b/starboard/android/shared/media_codec_bridge.h
index 743c991..1490b75 100644
--- a/starboard/android/shared/media_codec_bridge.h
+++ b/starboard/android/shared/media_codec_bridge.h
@@ -20,6 +20,7 @@
 #include "starboard/android/shared/jni_env_ext.h"
 #include "starboard/android/shared/jni_utils.h"
 #include "starboard/android/shared/media_common.h"
+#include "starboard/common/optional.h"
 #include "starboard/common/scoped_ptr.h"
 #include "starboard/shared/starboard/media/media_util.h"
 
@@ -104,11 +105,19 @@
       Handler* handler,
       jobject j_media_crypto);
 
+  // `max_width` and `max_height` can be set to positive values to specify the
+  // maximum resolutions the video can be adapted to.
+  // When they are not set, MediaCodecBridge will set them to the maximum
+  // resolutions the platform can decode.
+  // Both of them have to be set at the same time (i.e. we cannot set one of
+  // them without the other), which will be checked in the function.
   static scoped_ptr<MediaCodecBridge> CreateVideoMediaCodecBridge(
       SbMediaVideoCodec video_codec,
       int width,
       int height,
       int fps,
+      optional<int> max_width,
+      optional<int> max_height,
       Handler* handler,
       jobject j_surface,
       jobject j_media_crypto,
diff --git a/starboard/android/shared/media_decoder.cc b/starboard/android/shared/media_decoder.cc
index a09d59e..a44acf8 100644
--- a/starboard/android/shared/media_decoder.cc
+++ b/starboard/android/shared/media_decoder.cc
@@ -105,6 +105,8 @@
                            SbMediaVideoCodec video_codec,
                            int width,
                            int height,
+                           optional<int> max_width,
+                           optional<int> max_height,
                            int fps,
                            jobject j_output_surface,
                            SbDrmSystem drm_system,
@@ -128,10 +130,11 @@
       drm_system_ && drm_system_->require_secured_decoder();
   SB_DCHECK(!drm_system_ || j_media_crypto);
   media_codec_bridge_ = MediaCodecBridge::CreateVideoMediaCodecBridge(
-      video_codec, width, height, fps, this, j_output_surface, j_media_crypto,
-      color_metadata, require_secured_decoder, require_software_codec,
-      tunnel_mode_audio_session_id, force_big_endian_hdr_metadata,
-      force_improved_support_check, error_message);
+      video_codec, width, height, fps, max_width, max_height, this,
+      j_output_surface, j_media_crypto, color_metadata, require_secured_decoder,
+      require_software_codec, tunnel_mode_audio_session_id,
+      force_big_endian_hdr_metadata, force_improved_support_check,
+      error_message);
   if (!media_codec_bridge_) {
     SB_LOG(ERROR) << "Failed to create video media codec bridge with error: "
                   << *error_message;
diff --git a/starboard/android/shared/media_decoder.h b/starboard/android/shared/media_decoder.h
index ed89f0f..350e611 100644
--- a/starboard/android/shared/media_decoder.h
+++ b/starboard/android/shared/media_decoder.h
@@ -84,6 +84,8 @@
                SbMediaVideoCodec video_codec,
                int width,
                int height,
+               optional<int> max_width,
+               optional<int> max_height,
                int fps,
                jobject j_output_surface,
                SbDrmSystem drm_system,
diff --git a/starboard/android/shared/media_is_video_supported.cc b/starboard/android/shared/media_is_video_supported.cc
index 8aa3101..8965d7c 100644
--- a/starboard/android/shared/media_is_video_supported.cc
+++ b/starboard/android/shared/media_is_video_supported.cc
@@ -72,6 +72,13 @@
       return false;
     }
 
+    // Allow the web app to control how software decoders should be used.
+    if (!mime_type->ValidateStringParameter(
+            "softwaredecoder",
+            "allowed|disallowed|preferred|unpreferred|required")) {
+      return false;
+    }
+
     // Forces the use of specific Android APIs (isSizeSupported() and
     // areSizeAndRateSupported()) to determine format support.
     if (!mime_type->ValidateBoolParameter("forceimprovedsupportcheck")) {
diff --git a/starboard/android/shared/platform_configuration/BUILD.gn b/starboard/android/shared/platform_configuration/BUILD.gn
index 5d809f3..5240ff6 100644
--- a/starboard/android/shared/platform_configuration/BUILD.gn
+++ b/starboard/android/shared/platform_configuration/BUILD.gn
@@ -112,6 +112,15 @@
 
     # Don"t warn for implicit sign conversions. (in v8 and protobuf)
     "-Wno-sign-conversion",
+
+    # TODO: b/287129945 - Fix compiler warnings
+    "-Wno-implicit-const-int-float-conversion",
+
+    # TODO: b/287320271 - Fix compiler warnings
+    "-Wno-deprecated-copy",
+
+    # TODO: b/287324882 - Fix compiler warnings
+    "-Wno-unused-but-set-variable",
   ]
   defines += [
     # Enable compile-time decisions based on the ABI
@@ -164,14 +173,14 @@
 }
 
 config("executable_config") {
-  if (current_toolchain == default_toolchain) {
+  if (is_starboardized_toolchain) {
     cflags = [ "-fPIE" ]
     ldflags = [ "-pie" ]
   }
 }
 
 config("library_config") {
-  if (current_toolchain == default_toolchain) {
+  if (is_starboardized_toolchain) {
     cflags = [ "-fPIC" ]
   }
 }
diff --git a/starboard/android/shared/platform_configuration/configuration.gni b/starboard/android/shared/platform_configuration/configuration.gni
index 7c14f16..e788b6c 100644
--- a/starboard/android/shared/platform_configuration/configuration.gni
+++ b/starboard/android/shared/platform_configuration/configuration.gni
@@ -20,6 +20,9 @@
 
 final_executable_type = "shared_library"
 gtest_target_type = "shared_library"
+starboard_level_final_executable_type = "shared_library"
+starboard_level_gtest_target_type = "shared_library"
+
 sb_enable_benchmark = true
 
 size_config_path = "//starboard/android/shared/platform_configuration:size"
diff --git a/starboard/android/shared/player_create.cc b/starboard/android/shared/player_create.cc
index f92b2d0..ebe6faa 100644
--- a/starboard/android/shared/player_create.cc
+++ b/starboard/android/shared/player_create.cc
@@ -184,24 +184,14 @@
     return kSbPlayerInvalid;
   }
 
-  // Android doesn't support multiple concurrent hardware decoders, so we can't
-  // have more than one primary player. And as secondary player is disabled on
-  // android, we simply check the number of active players here.
-  const int kMaxNumberOfPlayers = 1;
-  if (SbPlayerPrivate::number_of_players() >= kMaxNumberOfPlayers) {
-    error_message = starboard::FormatString(
-        "Failed to create a new player. Platform cannot support more than %d "
-        "players.",
-        kMaxNumberOfPlayers);
-    SB_LOG(ERROR) << error_message << ".";
-    player_error_func(kSbPlayerInvalid, context, kSbPlayerErrorDecode,
-                      error_message.c_str());
-    return kSbPlayerInvalid;
-  }
-
   if (creation_param->output_mode != kSbPlayerOutputModeDecodeToTexture &&
       // TODO: This is temporary for supporting background media playback.
       //       Need to be removed with media refactor.
+      //
+      // Now this code is also used to avoid creating multiple punch-out player
+      // as it happens to work as is.  Note that even without the check here,
+      // SbPlayer will properly handle this by reporting error in VideoDecoder,
+      // when it fails to acquire the surface.
       video_codec != kSbMediaVideoCodecNone) {
     // Check the availability of the video window. As we only support one main
     // player, and sub players are in decode to texture mode on Android, a
diff --git a/starboard/android/shared/sdk_utils.py b/starboard/android/shared/sdk_utils.py
index 22d7bbc..8e8fe52 100644
--- a/starboard/android/shared/sdk_utils.py
+++ b/starboard/android/shared/sdk_utils.py
@@ -18,8 +18,8 @@
 
 # Which version of the Android NDK and CMake to install and build with.
 # Note that build.gradle parses these out of this file too.
-_NDK_VERSION = '21.1.6352462'
-_CMAKE_VERSION = '3.10.2.4988404'
+_NDK_VERSION = '25.2.9519653'
+_CMAKE_VERSION = '3.22.1'
 
 _STARBOARD_TOOLCHAINS_DIR = build.GetToolchainsDir()
 
diff --git a/starboard/android/shared/test_filters.py b/starboard/android/shared/test_filters.py
index fca2878..efade80 100644
--- a/starboard/android/shared/test_filters.py
+++ b/starboard/android/shared/test_filters.py
@@ -47,6 +47,10 @@
         'PlayerComponentsTests/PlayerComponentsTest.Pause/*ec3*',
     ],
     'nplb': [
+        # Enable multiplayer tests once it's supported.
+        'MultiplePlayerTests/*',
+        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.SecondaryPlayerTest/*',
+
         # This test is failing because localhost is not defined for IPv6 in
         # /etc/hosts.
         'SbSocketAddressTypes/SbSocketResolveTest.Localhost/filter_ipv6_type_ipv6',
@@ -59,6 +63,7 @@
 
         # These tests are disabled due to not receiving the kEndOfStream
         # player state update within the specified timeout.
+        'SbPlayerGetAudioConfigurationTests/SbPlayerGetAudioConfigurationTest.NoInput/*',
         'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.NoInput/*',
 
         # Android does not use SbDrmSessionClosedFunc, which these tests
@@ -71,6 +76,15 @@
         # when invalid initialization data is passed to
         # SbDrmGenerateSessionUpdateRequest().
         'SbDrmSessionTest.InvalidSessionUpdateRequestParams',
+
+        # TODO: b/288107039 This test crashed after NDK 25 upgrade, re-enable it.
+        'SbUndefinedBehaviorTest.CallThisPointerIsNullRainyDay',
+
+        # TODO: b/288107692 This test crashed on arm64 after NDK 25 upgrade, re-enable it.
+        'PixelTest.TooManyGlyphs',
+
+        # TODO: Filter this test on a per-device basis.
+        'SbMediaCanPlayMimeAndKeySystem.MinimumSupport',
     ],
 }
 # pylint: enable=line-too-long
diff --git a/starboard/android/shared/toolchain/toolchain.gni b/starboard/android/shared/toolchain/toolchain.gni
index 328edd6..9091c94 100644
--- a/starboard/android/shared/toolchain/toolchain.gni
+++ b/starboard/android/shared/toolchain/toolchain.gni
@@ -17,7 +17,7 @@
 declare_args() {
   android_sdk_path = getenv("ANDROID_HOME")
   android_ndk_path = ""
-  sb_android_ndk_version = "21.1.6352462"
+  sb_android_ndk_version = "25.2.9519653"
   android_ndk_api_level = 21
 }
 
diff --git a/starboard/android/shared/video_decoder.cc b/starboard/android/shared/video_decoder.cc
index 1f4688e..807868d 100644
--- a/starboard/android/shared/video_decoder.cc
+++ b/starboard/android/shared/video_decoder.cc
@@ -34,6 +34,7 @@
 #include "starboard/decode_target.h"
 #include "starboard/drm.h"
 #include "starboard/memory.h"
+#include "starboard/shared/starboard/media/mime_type.h"
 #include "starboard/shared/starboard/player/filter/video_frame_internal.h"
 #include "starboard/string.h"
 #include "starboard/thread.h"
@@ -44,12 +45,137 @@
 
 namespace {
 
+using ::starboard::shared::starboard::media::MimeType;
 using ::starboard::shared::starboard::player::filter::VideoFrame;
 using VideoRenderAlgorithmBase =
     ::starboard::shared::starboard::player::filter::VideoRenderAlgorithm;
 using std::placeholders::_1;
 using std::placeholders::_2;
 
+bool IsSoftwareDecodeRequired(const std::string& max_video_capabilities) {
+  if (max_video_capabilities.empty()) {
+    SB_LOG(INFO)
+        << "Use hardware decoder as `max_video_capabilities` is empty.";
+    return false;
+  }
+
+  // `max_video_capabilities` is in the form of mime type attributes, like
+  // "width=1920; height=1080; ...".  Prepend valid mime type/subtype and codecs
+  // so it can be parsed by MimeType.
+  MimeType mime_type("video/mp4; codecs=\"vp9\"; " + max_video_capabilities);
+  if (!mime_type.is_valid()) {
+    SB_LOG(INFO) << "Use hardware decoder as `max_video_capabilities` ("
+                 << max_video_capabilities << ") is invalid.";
+    return false;
+  }
+
+  std::string software_decoder_expectation =
+      mime_type.GetParamStringValue("softwaredecoder", "");
+  if (software_decoder_expectation == "required" ||
+      software_decoder_expectation == "preferred") {
+    SB_LOG(INFO) << "Use software decoder as `softwaredecoder` is set to \""
+                 << software_decoder_expectation << "\".";
+    return true;
+  } else if (software_decoder_expectation == "disallowed" ||
+             software_decoder_expectation == "unpreferred") {
+    SB_LOG(INFO) << "Use hardware decoder as `softwaredecoder` is set to \""
+                 << software_decoder_expectation << "\".";
+    return false;
+  }
+
+  bool is_low_resolution = mime_type.GetParamIntValue("width", 1920) <= 432 &&
+                           mime_type.GetParamIntValue("height", 1080) <= 240;
+  bool is_low_fps = mime_type.GetParamIntValue("fps", 30) <= 15;
+
+  if (is_low_resolution && is_low_fps) {
+    // Workaround to be compatible with existing backend implementation.
+    SB_LOG(INFO) << "Use software decoder as `max_video_capabilities` ("
+                 << max_video_capabilities
+                 << ") indicates a low resolution and low fps playback.";
+    return true;
+  }
+
+  SB_LOG(INFO)
+      << "Use hardware decoder as `max_video_capabilities` is set to \""
+      << max_video_capabilities << "\".";
+  return false;
+}
+
+void ParseMaxResolution(const std::string& max_video_capabilities,
+                        int window_width,
+                        int window_height,
+                        optional<int>* max_width,
+                        optional<int>* max_height) {
+  SB_DCHECK(window_width > 0);
+  SB_DCHECK(window_height > 0);
+  SB_DCHECK(max_width);
+  SB_DCHECK(max_height);
+
+  *max_width = nullopt;
+  *max_height = nullopt;
+
+  if (max_video_capabilities.empty()) {
+    SB_LOG(INFO)
+        << "Didn't parse max resolutions as `max_video_capabilities` is empty.";
+    return;
+  }
+
+  SB_LOG(INFO) << "Try to parse max resolutions from `max_video_capabilities` ("
+               << max_video_capabilities << ").";
+
+  // `max_video_capabilities` is in the form of mime type attributes, like
+  // "width=1920; height=1080; ...".  Prepend valid mime type/subtype and codecs
+  // so it can be parsed by MimeType.
+  MimeType mime_type("video/mp4; codecs=\"vp9\"; " + max_video_capabilities);
+  if (!mime_type.is_valid()) {
+    SB_LOG(WARNING) << "Failed to parse max resolutions as "
+                       "`max_video_capabilities` is invalid.";
+    return;
+  }
+
+  int width = mime_type.GetParamIntValue("width", -1);
+  int height = mime_type.GetParamIntValue("height", -1);
+  if (width <= 0 && height <= 0) {
+    SB_LOG(WARNING) << "Failed to parse max resolutions as either width or "
+                       "height isn't set.";
+    return;
+  }
+  if (width != -1 && height != -1) {
+    *max_width = width;
+    *max_height = height;
+    SB_LOG(INFO) << "Parsed max resolutions @ (" << *max_width << ", "
+                 << *max_height << ").";
+    return;
+  }
+
+  if (window_width <= 0 || window_height <= 0) {
+    // We DCHECK() above, but just be safe.
+    SB_LOG(WARNING)
+        << "Failed to parse max resolutions due to invalid window resolutions ("
+        << window_width << ", " << window_height << ").";
+    return;
+  }
+
+  if (width > 0) {
+    *max_width = width;
+    *max_height = max_width->value() * window_height / window_width;
+    SB_LOG(INFO) << "Inferred max height (" << *max_height
+                 << ") from max_width (" << *max_width
+                 << ") and window resolution @ (" << window_width << ", "
+                 << window_height << ").";
+    return;
+  }
+
+  if (height > 0) {
+    *max_height = height;
+    *max_width = max_height->value() * window_width / window_height;
+    SB_LOG(INFO) << "Inferred max width (" << *max_width
+                 << ") from max_height (" << *max_height
+                 << ") and window resolution @ (" << window_width << ", "
+                 << window_height << ").";
+  }
+}
+
 class VideoFrameImpl : public VideoFrame {
  public:
   typedef std::function<void()> VideoFrameReleaseCallback;
@@ -235,12 +361,13 @@
       output_mode_(output_mode),
       decode_target_graphics_context_provider_(
           decode_target_graphics_context_provider),
+      max_video_capabilities_(max_video_capabilities),
       tunnel_mode_audio_session_id_(tunnel_mode_audio_session_id),
       force_reset_surface_under_tunnel_mode_(
           force_reset_surface_under_tunnel_mode),
       has_new_texture_available_(false),
       surface_condition_variable_(surface_destroy_mutex_),
-      require_software_codec_(!max_video_capabilities.empty()),
+      require_software_codec_(IsSoftwareDecodeRequired(max_video_capabilities)),
       force_big_endian_hdr_metadata_(force_big_endian_hdr_metadata),
       force_improved_support_check_(force_improved_support_check),
       number_of_preroll_frames_(kInitialPrerollFrameCount) {
@@ -555,8 +682,8 @@
     return false;
   }
 
-  int width, height;
-  if (!GetVideoWindowSize(&width, &height)) {
+  int window_width, window_height;
+  if (!GetVideoWindowSize(&window_width, &window_height)) {
     *error_message =
         "Can't initialize the codec since we don't have a video window.";
     SB_LOG(ERROR) << *error_message;
@@ -570,10 +697,17 @@
   } else {
     SB_DCHECK(video_fps_ == 0);
   }
+
+  optional<int> max_width, max_height;
+  // TODO(b/281431214): Evaluate if we should also parse the fps from
+  //                    `max_video_capabilities_` and pass to MediaDecoder ctor.
+  ParseMaxResolution(max_video_capabilities_, window_width, window_height,
+                     &max_width, &max_height);
+
   media_decoder_.reset(new MediaDecoder(
-      this, video_codec_, width, height, video_fps_, j_output_surface,
-      drm_system_, color_metadata_ ? &*color_metadata_ : nullptr,
-      require_software_codec_,
+      this, video_codec_, window_width, window_height, max_width, max_height,
+      video_fps_, j_output_surface, drm_system_,
+      color_metadata_ ? &*color_metadata_ : nullptr, require_software_codec_,
       std::bind(&VideoDecoder::OnTunnelModeFrameRendered, this, _1),
       tunnel_mode_audio_session_id_, force_big_endian_hdr_metadata_,
       force_improved_support_check_, error_message));
diff --git a/starboard/android/shared/video_decoder.h b/starboard/android/shared/video_decoder.h
index 34c7001..d8eafed 100644
--- a/starboard/android/shared/video_decoder.h
+++ b/starboard/android/shared/video_decoder.h
@@ -127,8 +127,10 @@
   ErrorCB error_cb_;
   DrmSystem* drm_system_;
   const SbPlayerOutputMode output_mode_;
-  SbDecodeTargetGraphicsContextProvider*
+  SbDecodeTargetGraphicsContextProvider* const
       decode_target_graphics_context_provider_;
+  const std::string max_video_capabilities_;
+
   // Android doesn't officially support multi concurrent codecs. But the device
   // usually has at least one hardware decoder and Google's software decoders.
   // Google's software decoders can work concurrently. So, we use HW decoder for
diff --git a/starboard/android/shared/video_window.cc b/starboard/android/shared/video_window.cc
index 81d898d..5e401ec 100644
--- a/starboard/android/shared/video_window.cc
+++ b/starboard/android/shared/video_window.cc
@@ -103,7 +103,9 @@
   // Create an OpenGL ES 2.0 context.
   EGLContext context = EGL_NO_CONTEXT;
   EGLint context_attrib_list[] = {
-      EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE,
+      EGL_CONTEXT_CLIENT_VERSION,
+      2,
+      EGL_NONE,
   };
   context =
       eglCreateContext(display, config, EGL_NO_CONTEXT, context_attrib_list);
@@ -171,7 +173,6 @@
 
 jobject VideoSurfaceHolder::AcquireVideoSurface() {
   ScopedLock lock(*GetViewSurfaceMutex());
-  SB_DCHECK(g_video_surface_holder == NULL);
   if (g_video_surface_holder != NULL) {
     return NULL;
   }
diff --git a/starboard/android/x86/test_filters.py b/starboard/android/x86/test_filters.py
index d6ca19a..27e30dc 100644
--- a/starboard/android/x86/test_filters.py
+++ b/starboard/android/x86/test_filters.py
@@ -19,17 +19,20 @@
 # A map of failing or crashing tests per target
 _FILTERED_TESTS = {
     'nplb': [
+        'MultiplePlayerTests/*',
         'SbAccessibilityTest.CallSetCaptionsEnabled',
         'SbAccessibilityTest.GetCaptionSettingsReturnIsValid',
         'SbAudioSinkTest.*',
         'SbMicrophoneCloseTest.*',
         'SbMicrophoneOpenTest.*',
         'SbMicrophoneReadTest.*',
-        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.*',
+        'SbPlayerGetAudioConfigurationTests/*',
+        'SbPlayerWriteSampleTests/*',
         ('SbMediaSetAudioWriteDurationTests/SbMediaSetAudioWriteDurationTest'
          '.WriteContinuedLimitedInput/*'),
         ('SbMediaSetAudioWriteDurationTests/SbMediaSetAudioWriteDurationTest'
          '.WriteLimitedInput/*'),
+        'VerticalVideoTests/VerticalVideoTest.WriteSamples/*',
     ],
     'player_filter_tests': [
         'AudioDecoderTests/*',
diff --git a/starboard/android/x86/toolchain/BUILD.gn b/starboard/android/x86/toolchain/BUILD.gn
index 8bf6d29..3a1cc06 100644
--- a/starboard/android/x86/toolchain/BUILD.gn
+++ b/starboard/android/x86/toolchain/BUILD.gn
@@ -21,9 +21,9 @@
   cc = "$prefix/i686-linux-android${android_ndk_api_level}-clang"
   cxx = "$prefix/i686-linux-android${android_ndk_api_level}-clang++"
   ld = cxx
-  readelf = "$prefix/i686-linux-android-readelf"
-  ar = "$prefix/i686-linux-android-ar"
-  nm = "$prefix/i686-linux-android-nm"
+  readelf = "readelf"
+  ar = "ar"
+  nm = "nm"
 
   toolchain_args = {
     is_clang = true
diff --git a/starboard/build/config/BUILD.gn b/starboard/build/config/BUILD.gn
index acb8597..aaa87f9 100644
--- a/starboard/build/config/BUILD.gn
+++ b/starboard/build/config/BUILD.gn
@@ -92,9 +92,11 @@
 config("target") {
   if (current_toolchain != host_toolchain) {
     if (final_executable_type == "shared_library") {
-      # Rewrite main() functions into StarboardMain. TODO: This is a
-      # hack, it would be better to be more surgical, here.
-      defines = [ "main=StarboardMain" ]
+      if (!build_with_separate_cobalt_toolchain) {
+        # Rewrite main() functions into StarboardMain. TODO: This is a
+        # hack, it would be better to be more surgical, here.
+        defines = [ "main=StarboardMain" ]
+      }
 
       # To link into a shared library on Linux and similar platforms,
       # the compiler must be told to generate Position Independent Code.
@@ -114,7 +116,7 @@
 # TODO(b/212641065): Scope global defines migrated from
 # cobalt_configuration.gypi to only the targets they're necessary in.
 config("starboard") {
-  if (current_toolchain == default_toolchain) {
+  if (is_starboardized_toolchain) {
     defines = [
       "STARBOARD",
       "COBALT",  # TODO: See if this can be replaced by STARBOARD macro.
@@ -180,7 +182,7 @@
 }
 
 config("speed") {
-  if (current_toolchain == default_toolchain) {
+  if (is_starboardized_toolchain) {
     if (defined(speed_config_path)) {
       configs = [ speed_config_path ]
     }
@@ -188,7 +190,7 @@
 }
 
 config("size") {
-  if (current_toolchain == default_toolchain) {
+  if (is_starboardized_toolchain) {
     if (defined(size_config_path)) {
       configs = [ size_config_path ]
     }
@@ -196,7 +198,7 @@
 }
 
 config("pedantic_warnings") {
-  if (current_toolchain == default_toolchain) {
+  if (is_starboardized_toolchain) {
     if (defined(pedantic_warnings_config_path)) {
       configs = [ pedantic_warnings_config_path ]
     }
@@ -204,7 +206,7 @@
 }
 
 config("no_pedantic_warnings") {
-  if (current_toolchain == default_toolchain ||
+  if (is_starboardized_toolchain ||
       current_toolchain == "//$starboard_path/toolchain:native_target") {
     if (defined(no_pedantic_warnings_config_path)) {
       configs = [ no_pedantic_warnings_config_path ]
@@ -223,8 +225,7 @@
 # override flags specified in a platform's "platform_configuration" config,
 # which is where these particular flags would otherwise naturally fit.
 config("default_compiler_flags") {
-  if (current_toolchain == default_toolchain && sb_is_evergreen &&
-      target_cpu == "arm") {
+  if (is_starboardized_toolchain && sb_is_evergreen && target_cpu == "arm") {
     cflags = [ "-mfpu=vfpv3" ]
     asmflags = cflags
   }
diff --git a/starboard/build/config/BUILDCONFIG.gn b/starboard/build/config/BUILDCONFIG.gn
index d1c7eba..5efc2c8 100644
--- a/starboard/build/config/BUILDCONFIG.gn
+++ b/starboard/build/config/BUILDCONFIG.gn
@@ -33,6 +33,8 @@
   is_docker_build = getenv("IS_DOCKER") == "1"
 
   using_old_compiler = false
+
+  build_with_separate_cobalt_toolchain = false
 }
 
 assert(!(is_starboard && is_native_target_build),
@@ -86,9 +88,6 @@
 # configuration.
 import("//starboard/build/platform_path.gni")
 
-import("//$starboard_path/platform_configuration/configuration.gni")
-import("//starboard/build/config/build_assertions.gni")
-
 # TODO(b/272790873): Set host_cpu to x86 for 32 bit builds.
 if (target_cpu == "x86" || target_cpu == "arm") {
   _host_toolchain_cpu = "x86"
@@ -96,12 +95,19 @@
   _host_toolchain_cpu = host_cpu
 }
 host_toolchain = "//starboard/build/toolchain/$host_os:$_host_toolchain_cpu"
-if (sb_is_evergreen) {
-  target_toolchain = "//starboard/build/toolchain/linux:clang_lld"
+
+if (build_with_separate_cobalt_toolchain) {
+  cobalt_toolchain = "//starboard/build/toolchain/linux:clang_lld"
+  starboard_toolchain = "//$starboard_path/toolchain:starboard"
 } else {
-  target_toolchain = "//$starboard_path/toolchain:target"
+  cobalt_toolchain = "//$starboard_path/toolchain:target"
+  starboard_toolchain = cobalt_toolchain
 }
-set_default_toolchain(target_toolchain)
+set_default_toolchain(cobalt_toolchain)
+import("//starboard/build/config/toolchain_variables.gni")
+
+import("//$starboard_path/platform_configuration/configuration.gni")
+import("//starboard/build/config/build_assertions.gni")
 
 declare_args() {
   use_tsan = getenv("USE_TSAN") == 1
@@ -308,12 +314,14 @@
 }
 
 template("executable") {
+  not_needed(invoker, [ "build_loader" ])
+
   target_with_platform_configs(target_name) {
     target_type = "executable"
     forward_variables_from(invoker, "*", [ "install_target" ])
   }
 
-  if (current_toolchain == default_toolchain &&
+  if (is_starboardized_toolchain &&
       (!defined(invoker.install_target) || invoker.install_target)) {
     executable_target_name = target_name
 
@@ -338,13 +346,20 @@
     install_target(target_name + "_install") {
       forward_variables_from(invoker, [ "testonly" ])
       installable_target_name = executable_target_name
+      installable_target_dep = ":$executable_target_name"
+      not_needed([ "installable_target_dep" ])
       type = "executable"
+
       deps = []
       if (defined(invoker.deps)) {
         deps += invoker.deps
       }
       foreach(dep, data_deps) {
-        deps += [ "${dep}_install_content" ]
+        spl = []
+        spl = string_split(dep, "(")
+        if ([ spl[0] ] == spl) {
+          deps += [ "${dep}_install_content" ]
+        }
       }
       if (separate_install_targets_for_bundling) {
         deps += [ ":${executable_target_name}_bundle_content" ]
@@ -354,12 +369,66 @@
 }
 
 template("shared_library") {
-  target_with_platform_configs(target_name) {
+  if (defined(invoker.build_loader) && invoker.build_loader == false) {
+    build_loader = false
+  } else {
+    build_loader = build_with_separate_cobalt_toolchain
+  }
+
+  if (build_loader) {
+    original_target_name = "${target_name}_original_target"
+  } else {
+    original_target_name = target_name
+  }
+  actual_target_name = target_name
+
+  target_with_platform_configs(original_target_name) {
+    output_name = actual_target_name
     target_type = "shared_library"
     forward_variables_from(invoker, "*", [ "install_target" ])
   }
 
-  if (current_toolchain == default_toolchain &&
+  if (build_loader) {
+    group(target_name) {
+      forward_variables_from(invoker, [ "testonly" ])
+      deps = [
+        ":${actual_target_name}_loader($starboard_toolchain)",
+        ":${actual_target_name}_loader_copy($starboard_toolchain)",
+      ]
+    }
+    if (current_toolchain == starboard_toolchain) {
+      executable("${actual_target_name}_loader") {
+        output_name = "${actual_target_name}_loader"
+        forward_variables_from(invoker, [ "testonly" ])
+        sources = [ "//$starboard_path/starboard_loader.cc" ]
+
+        out_dir = rebase_path(root_build_dir)
+        defines = [
+          "SB_LOADER_MODULE=\"$actual_target_name\"",
+          "OUT_DIRECTORY=\"${out_dir}\"",
+        ]
+        configs += [ "//starboard/build/config:starboard_implementation" ]
+
+        ldflags = [
+          "-Wl,-rpath=" + rebase_path("$root_build_dir/starboard"),
+          "-Wl,-rpath=" + rebase_path("$root_build_dir"),
+        ]
+
+        deps = [
+          ":$original_target_name($cobalt_toolchain)",
+          "//starboard:starboard_platform_group($starboard_toolchain)",
+        ]
+      }
+      copy("${actual_target_name}_loader_copy") {
+        forward_variables_from(invoker, [ "testonly" ])
+        sources = [ "$root_out_dir/${actual_target_name}_loader" ]
+        outputs = [ "$root_build_dir/${actual_target_name}_loader" ]
+        deps = [ ":${actual_target_name}_loader" ]
+      }
+    }
+  }
+
+  if (is_starboardized_toolchain &&
       (!defined(invoker.install_target) || invoker.install_target)) {
     shared_library_target_name = target_name
 
@@ -385,13 +454,20 @@
     install_target(target_name + "_install") {
       forward_variables_from(invoker, [ "testonly" ])
       installable_target_name = shared_library_target_name
+      installable_target_dep = ":$original_target_name"
+      not_needed([ "installable_target_dep" ])
       type = "shared_library"
+
       deps = []
       if (defined(invoker.deps)) {
         deps += invoker.deps
       }
       foreach(dep, data_deps) {
-        deps += [ "${dep}_install_content" ]
+        spl = []
+        spl = string_split(dep, "(")
+        if ([ spl[0] ] == spl) {
+          deps += [ "${dep}_install_content" ]
+        }
       }
       if (separate_install_targets_for_bundling) {
         deps += [ ":${shared_library_target_name}_bundle_content" ]
diff --git a/starboard/build/config/base_configuration.gni b/starboard/build/config/base_configuration.gni
index 6960c78..0241180 100644
--- a/starboard/build/config/base_configuration.gni
+++ b/starboard/build/config/base_configuration.gni
@@ -20,6 +20,12 @@
 # All build arguments in this file must have documentation.
 # Please follow the formatting in this file when adding new ones.
 
+if (build_with_separate_cobalt_toolchain) {
+  default_target_type = "shared_library"
+} else {
+  default_target_type = "executable"
+}
+
 declare_args() {
   # Enables the nasm compiler to be used to compile .asm files.
   nasm_exists = false
@@ -55,12 +61,15 @@
   # The target type for test targets. Allows changing the target type
   # on platforms where the native code may require an additional packaging step
   # (ex. Android).
-  gtest_target_type = "executable"
+  gtest_target_type = default_target_type
 
   # The target type for executable targets. Allows changing the target type
   # on platforms where the native code may require an additional packaging step
   # (ex. Android).
-  final_executable_type = "executable"
+  final_executable_type = default_target_type
+
+  starboard_level_gtest_target_type = "executable"
+  starboard_level_final_executable_type = "executable"
 
   # Halt execution on failure to allocate memory.
   abort_on_allocation_failure = true
@@ -101,12 +110,6 @@
   # defines how the build should produce the install/ directory.
   install_target_path = "//starboard/build/install/no_install.gni"
 
-  # Target-specific configurations for executable targets.
-  executable_configs = []
-
-  # Target-specific configurations for shared_library targets.
-  shared_library_configs = []
-
   # Target-specific configurations for static_library targets.
   static_library_configs = []
 
@@ -168,3 +171,24 @@
   # Enable WASM and install WebAssembly global.
   v8_enable_webassembly = false
 }
+
+if (current_toolchain == starboard_toolchain &&
+    build_with_separate_cobalt_toolchain) {
+  declare_args() {
+    # Target-specific configurations for executable targets.
+    executable_configs =
+        [ "//build/config/gcc:rpath_for_built_shared_libraries" ]
+
+    # Target-specific configurations for shared_library targets.
+    shared_library_configs =
+        [ "//build/config/gcc:rpath_for_built_shared_libraries" ]
+  }
+} else {
+  declare_args() {
+    # Target-specific configurations for executable targets.
+    executable_configs = []
+
+    # Target-specific configurations for shared_library targets.
+    shared_library_configs = []
+  }
+}
diff --git a/cobalt/account/BUILD.gn b/starboard/build/config/starboard_target_type.gni
similarity index 65%
copy from cobalt/account/BUILD.gn
copy to starboard/build/config/starboard_target_type.gni
index 02cce3e..0c3983a 100644
--- a/cobalt/account/BUILD.gn
+++ b/starboard/build/config/starboard_target_type.gni
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,14 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
+declare_args() {
+  starboard_target_type = ""
+}
 
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
+if (starboard_target_type == "") {
+  if (build_with_separate_cobalt_toolchain) {
+    starboard_target_type = "shared_library"
+  } else {
+    starboard_target_type = "group"
+  }
 }
diff --git a/starboard/build/config/toolchain_variables.gni b/starboard/build/config/toolchain_variables.gni
new file mode 100644
index 0000000..1ee7982
--- /dev/null
+++ b/starboard/build/config/toolchain_variables.gni
@@ -0,0 +1,21 @@
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+is_default_toolchain = current_toolchain == default_toolchain
+is_starboard_toolchain = current_toolchain == starboard_toolchain
+is_cobalt_toolchain = current_toolchain == cobalt_toolchain
+is_host_toolchain = current_toolchain == host_toolchain
+
+# Toolchains using Starboard tools, not native tools.
+is_starboardized_toolchain = is_starboard_toolchain || is_default_toolchain
diff --git a/starboard/build/config/win/BUILD.gn b/starboard/build/config/win/BUILD.gn
index 6082d82..f2aec79 100644
--- a/starboard/build/config/win/BUILD.gn
+++ b/starboard/build/config/win/BUILD.gn
@@ -20,15 +20,10 @@
 }
 
 config("common") {
-  if (!cobalt_fastbuild) {
-    # Containers cannot use PDBs, so we conditionally disable them.
-    # We want to keep them for non-docker builds as they make compilation
-    # significantly faster.
-    configs = [ ":no_pdbs" ]
-  }
+  configs = []
 
   cflags_cc = [ "/TP" ]
-  cflags = []
+  cflags = [ "/Z7" ]
   ldflags = [
     "/NXCOMPAT",
     "/MANIFEST:NO",
@@ -41,6 +36,9 @@
     "UNICODE",
   ]
 
+  # Allows compilation against VS 2022.
+  configs += [ "//build/config/win:visual_studio_version_compat" ]
+
   # msvs_base
   # OutputDirectory and IntermediateDirectory, maybe CharacterSet
   include_dirs += [
@@ -238,15 +236,3 @@
     "/wd4996",
   ]
 }
-
-config("no_pdbs") {
-  if (is_docker_build) {
-    cflags = [ "/Z7" ]
-  } else {
-    cflags = [
-      "/Zi",
-      "/FS",
-    ]
-  }
-  ldflags = [ "/DEBUG:FULL" ]
-}
diff --git a/starboard/build/install/install_target.gni b/starboard/build/install/install_target.gni
index 765ed41..62f83e0 100644
--- a/starboard/build/install/install_target.gni
+++ b/starboard/build/install/install_target.gni
@@ -16,6 +16,7 @@
 
 template("install_target") {
   installable_target_name = invoker.installable_target_name
+  installable_target_dep = invoker.installable_target_dep
 
   if (invoker.type == "executable") {
     install_subdir = "bin"
@@ -30,7 +31,7 @@
   copy("copy_" + target_name) {
     forward_variables_from(invoker, [ "testonly" ])
     deps = invoker.deps
-    deps += [ ":$installable_target_name" ]
+    deps += [ installable_target_dep ]
     sources = [ "$root_out_dir/$source_name" ]
     outputs = [ "$root_out_dir/install/$install_subdir/{{source_file_part}}" ]
   }
@@ -38,8 +39,8 @@
   group(target_name) {
     forward_variables_from(invoker, [ "testonly" ])
     deps = [
-      ":$installable_target_name",
       ":copy_${target_name}",
+      installable_target_dep,
     ]
   }
 }
diff --git a/starboard/build/toolchain/linux/BUILD.gn b/starboard/build/toolchain/linux/BUILD.gn
index 0d9aa39..97a5b53 100644
--- a/starboard/build/toolchain/linux/BUILD.gn
+++ b/starboard/build/toolchain/linux/BUILD.gn
@@ -14,6 +14,7 @@
 
 import("//build/toolchain/gcc_toolchain.gni")
 import("//starboard/build/platform_path.gni")
+import("//starboard/build/toolchain/linux/clang_lld_toolchain.gni")
 
 clang_toolchain("x64") {
   clang_base_path = clang_base_path
@@ -37,15 +38,5 @@
   }
 }
 
-gcc_toolchain("clang_lld") {
-  prefix = rebase_path("$clang_base_path/bin", root_build_dir)
-  cc = "$prefix/clang"
-  cxx = "$prefix/clang++"
-  ld = "$prefix/ld.lld"
-  ar = "$prefix/llvm-ar"
-  nm = "nm"
-
-  toolchain_args = {
-    is_clang = true
-  }
+clang_lld_toolchain("clang_lld") {
 }
diff --git a/starboard/build/toolchain/linux/clang_lld_toolchain.gni b/starboard/build/toolchain/linux/clang_lld_toolchain.gni
new file mode 100644
index 0000000..f9de0de
--- /dev/null
+++ b/starboard/build/toolchain/linux/clang_lld_toolchain.gni
@@ -0,0 +1,32 @@
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import("//build/toolchain/gcc_toolchain.gni")
+
+template("clang_lld_toolchain") {
+  not_needed(invoker, "*")
+
+  gcc_toolchain(target_name) {
+    prefix = rebase_path("$clang_base_path/bin", root_build_dir)
+    cc = "$prefix/clang"
+    cxx = "$prefix/clang++"
+    ld = "$prefix/ld.lld"
+    ar = "$prefix/llvm-ar"
+    nm = "nm"
+
+    toolchain_args = {
+      is_clang = true
+    }
+  }
+}
diff --git a/starboard/common/BUILD.gn b/starboard/common/BUILD.gn
index d07dfb3..5c1977e 100644
--- a/starboard/common/BUILD.gn
+++ b/starboard/common/BUILD.gn
@@ -61,6 +61,8 @@
     "optional.h",
     "paths.cc",
     "paths.h",
+    "player.cc",
+    "player.h",
     "queue.h",
     "recursive_mutex.cc",
     "recursive_mutex.h",
@@ -94,6 +96,7 @@
   sources = [
     "media_test.cc",
     "memory_test.cc",
+    "player_test.cc",
     "socket_test.cc",
     "test_main.cc",
   ]
diff --git a/starboard/common/player.cc b/starboard/common/player.cc
new file mode 100644
index 0000000..e338cf3
--- /dev/null
+++ b/starboard/common/player.cc
@@ -0,0 +1,35 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "starboard/common/player.h"
+
+#include "starboard/common/log.h"
+
+namespace starboard {
+
+const char* GetPlayerOutputModeName(SbPlayerOutputMode output_mode) {
+  switch (output_mode) {
+    case kSbPlayerOutputModeDecodeToTexture:
+      return "decode-to-texture";
+    case kSbPlayerOutputModePunchOut:
+      return "punch-out";
+    case kSbPlayerOutputModeInvalid:
+      return "invalid";
+  }
+
+  SB_NOTREACHED();
+  return "invalid";
+}
+
+}  // namespace starboard
diff --git a/starboard/common/player.h b/starboard/common/player.h
new file mode 100644
index 0000000..7655109
--- /dev/null
+++ b/starboard/common/player.h
@@ -0,0 +1,26 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef STARBOARD_COMMON_PLAYER_H_
+#define STARBOARD_COMMON_PLAYER_H_
+
+#include "starboard/player.h"
+
+namespace starboard {
+
+const char* GetPlayerOutputModeName(SbPlayerOutputMode output_mode);
+
+}  // namespace starboard
+
+#endif  // STARBOARD_COMMON_PLAYER_H_
diff --git a/starboard/common/player_test.cc b/starboard/common/player_test.cc
new file mode 100644
index 0000000..814eb5d
--- /dev/null
+++ b/starboard/common/player_test.cc
@@ -0,0 +1,31 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "starboard/common/player.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace starboard {
+namespace {
+
+TEST(PlayerTest, GetPlayerOutputModeName) {
+  ASSERT_STREQ(GetPlayerOutputModeName(kSbPlayerOutputModeDecodeToTexture),
+               "decode-to-texture");
+  ASSERT_STREQ(GetPlayerOutputModeName(kSbPlayerOutputModePunchOut),
+               "punch-out");
+  ASSERT_STREQ(GetPlayerOutputModeName(kSbPlayerOutputModeInvalid), "invalid");
+}
+
+}  // namespace
+}  // namespace starboard
diff --git a/starboard/configuration.h b/starboard/configuration.h
index 56b8200..651f131 100644
--- a/starboard/configuration.h
+++ b/starboard/configuration.h
@@ -596,10 +596,6 @@
 #error "New versions of Starboard specify player output mode at runtime."
 #endif
 
-#if !defined(SB_HAS_BILINEAR_FILTERING_SUPPORT)
-#error "Your platform must define SB_HAS_BILINEAR_FILTERING_SUPPORT."
-#endif
-
 #if !defined(SB_HAS_NV12_TEXTURE_SUPPORT)
 #error "Your platform must define SB_HAS_NV12_TEXTURE_SUPPORT."
 #endif
diff --git a/starboard/doc/abstract-toolchain.md b/starboard/doc/abstract-toolchain.md
deleted file mode 100644
index 0a7e5bd..0000000
--- a/starboard/doc/abstract-toolchain.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Abstract Toolchain
-
-## Motivation
-
-The aim of implementing an Abstract Toolchain is to allow porters to add
-new toolchains or customize existing ones without the need of modifying
-common code.
-
-Initially all targets were defined in one common shared file,
-`src/tools/gyp/pylib/gyp/generator/ninja.py`.
-Modifications to this file were required for replacing any of the toolchain
-components, adding platform-specific tooling, adding new toolchains, or
-accommodating platform-specific flavor of reference tool. Doing this in a
-shared file does not scale with the number of ports.
-
-## Overview
-
-The solution implemented to solve toolchain abstraction consists of adding two
-new functions to the platform specific `gyp_configuration.py` file found under:
-
-`starboard/<PLATFORM>/gyp_configuration.py`
-
-The functions to implement are:
-
-`GetHostToolchain` and `GetTargetToolchain`
-
-## Example
-
-The simplest complete GCC based toolchain, where a target and host are the same,
-and all tools are in the PATH:
-
-  class ExamplePlatformConfig(starboard.PlatformConfig)
-    # ...
-
-    def GetTargetToolchain(self):
-      return [
-        starboard.toolchains.gnu.CCompiler(),
-        starboard.toolchains.gnu.CPlusPlusCompiler(),
-        starboard.toolchains.gnu.Assembler(),
-        starboard.toolchains.gnu.StaticLinker(),
-        starboard.toolchains.gnu.DynamicLinker(),
-        starboard.toolchains.gnu.Bison(),
-        starboard.toolchains.gnu.Stamp(),
-        starboard.toolchains.gnu.Copy(),
-      ]
-
-    def GetHostToolchain(self):
-      return self.GetTargetToolchain()
-
-You can find real examples of this in the Open Source repo:
-[Linux x8611](https://cobalt.googlesource.com/cobalt/+/refs/heads/21.lts.1+/src/starboard/linux/x64x11/gyp_configuration.py)
-
-[Raspberry Pi 2](https://cobalt.googlesource.com/cobalt/+/refs/heads/21.lts.1+/src/starboard/raspi/shared/gyp_configuration.py)
diff --git a/starboard/doc/evergreen/cobalt_evergreen_overview.md b/starboard/doc/evergreen/cobalt_evergreen_overview.md
index e614373..8e2591c 100644
--- a/starboard/doc/evergreen/cobalt_evergreen_overview.md
+++ b/starboard/doc/evergreen/cobalt_evergreen_overview.md
@@ -131,7 +131,7 @@
 
 *   `kSbSystemPathStorageDirectory`
     *   Dedicated location for storing Cobalt Evergreen-related binaries
-    *   This path must be writable and have at least 96MB of reserved space for
+    *   This path must be writable and have at least 64MB of reserved space for
         Evergreen updates. Please see the “Platforms Requirements” section below
         for more details.
 *   `kSbMemoryMapProtectExec`
@@ -195,12 +195,12 @@
 
 *   V8
 
-Additional reserved storage (96MB) is required for Evergreen binaries. We expect
+Additional reserved storage (64MB) is required for Evergreen binaries. We expect
 Evergreen implementations to have an initial Cobalt preloaded on the device and
 an additional reserved space for additional Cobalt update storage.
 
 *   Initial Cobalt binary deployment - 64MB
-*   Additional Cobalt update storage - 96MB
+*   Additional Cobalt update storage - 64MB
     *   Required for 2 update slots under `kSbSystemPathStorageDirectory`
 
 As Cobalt Evergreen is intended to be updated from Google Cloud architecture
diff --git a/starboard/egl_and_gles/BUILD.gn b/starboard/egl_and_gles/BUILD.gn
index 3afc18c..cfcf67e 100644
--- a/starboard/egl_and_gles/BUILD.gn
+++ b/starboard/egl_and_gles/BUILD.gn
@@ -23,7 +23,9 @@
 # in the configuration.gni for the current platform.
 
 group("egl_and_gles") {
-  public_deps = [ ":egl_and_gles_$gl_type" ]
+  if (gl_type != "none") {
+    public_deps = [ ":egl_and_gles_$gl_type" ]
+  }
 }
 
 group("egl_and_gles_system_gles2") {
diff --git a/starboard/elf_loader/BUILD.gn b/starboard/elf_loader/BUILD.gn
index e255bc5..bca4126 100644
--- a/starboard/elf_loader/BUILD.gn
+++ b/starboard/elf_loader/BUILD.gn
@@ -88,31 +88,33 @@
   }
 }
 
-target(final_executable_type, "elf_loader_sandbox") {
-  data_deps = [ "//third_party/icu:icudata" ]
-  if (cobalt_font_package == "empty") {
-    data_deps += [ "//cobalt/content/fonts:copy_font_data" ]
-  } else {
-    data_deps += [
-      "//cobalt/content/fonts:copy_fonts",
-      "//cobalt/content/fonts:fonts_xml",
+if (current_toolchain == starboard_toolchain) {
+  target(starboard_level_final_executable_type, "elf_loader_sandbox") {
+    data_deps = [ "//third_party/icu:icudata" ]
+    if (cobalt_font_package == "empty") {
+      data_deps += [ "//cobalt/content/fonts:copy_font_data" ]
+    } else {
+      data_deps += [
+        "//cobalt/content/fonts:copy_fonts",
+        "//cobalt/content/fonts:fonts_xml",
+      ]
+    }
+
+    sources = [ "sandbox.cc" ]
+    configs += [ ":elf_loader_config" ]
+
+    deps = [
+      ":constants",
+      ":elf_loader",
+      ":evergreen_info",
+      ":sabi_string",
+      "//cobalt/content/fonts:copy_font_data",
+      "//starboard",
     ]
-  }
 
-  sources = [ "sandbox.cc" ]
-  configs += [ ":elf_loader_config" ]
-
-  deps = [
-    ":constants",
-    ":elf_loader",
-    ":evergreen_info",
-    ":sabi_string",
-    "//cobalt/content/fonts:copy_font_data",
-    "//starboard",
-  ]
-
-  if (!sb_is_evergreen_compatible) {
-    deps += [ "//third_party/crashpad/wrapper:wrapper_stub" ]
+    if (!sb_is_evergreen_compatible) {
+      deps += [ "//third_party/crashpad/wrapper:wrapper_stub" ]
+    }
   }
 }
 
diff --git a/starboard/evergreen/arm/hardfp/configuration_public.h b/starboard/evergreen/arm/hardfp/configuration_public.h
index d7aa206..1c7f0db 100644
--- a/starboard/evergreen/arm/hardfp/configuration_public.h
+++ b/starboard/evergreen/arm/hardfp/configuration_public.h
@@ -106,11 +106,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 1
diff --git a/cobalt/account/BUILD.gn b/starboard/evergreen/arm/hardfp/toolchain/BUILD.gn
similarity index 69%
rename from cobalt/account/BUILD.gn
rename to starboard/evergreen/arm/hardfp/toolchain/BUILD.gn
index 02cce3e..5bc6339 100644
--- a/cobalt/account/BUILD.gn
+++ b/starboard/evergreen/arm/hardfp/toolchain/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
+import("//starboard/build/toolchain/linux/clang_lld_toolchain.gni")
 
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
+clang_lld_toolchain("target") {
 }
diff --git a/starboard/evergreen/arm/softfp/configuration_public.h b/starboard/evergreen/arm/softfp/configuration_public.h
index dea0581..7b22b1a 100644
--- a/starboard/evergreen/arm/softfp/configuration_public.h
+++ b/starboard/evergreen/arm/softfp/configuration_public.h
@@ -106,11 +106,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 1
diff --git a/cobalt/account/BUILD.gn b/starboard/evergreen/arm/softfp/toolchain/BUILD.gn
similarity index 69%
copy from cobalt/account/BUILD.gn
copy to starboard/evergreen/arm/softfp/toolchain/BUILD.gn
index 02cce3e..5bc6339 100644
--- a/cobalt/account/BUILD.gn
+++ b/starboard/evergreen/arm/softfp/toolchain/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
+import("//starboard/build/toolchain/linux/clang_lld_toolchain.gni")
 
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
+clang_lld_toolchain("target") {
 }
diff --git a/starboard/evergreen/arm64/configuration_public.h b/starboard/evergreen/arm64/configuration_public.h
index 6e570ed..a358708 100644
--- a/starboard/evergreen/arm64/configuration_public.h
+++ b/starboard/evergreen/arm64/configuration_public.h
@@ -106,11 +106,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 1
diff --git a/cobalt/account/BUILD.gn b/starboard/evergreen/arm64/toolchain/BUILD.gn
similarity index 69%
copy from cobalt/account/BUILD.gn
copy to starboard/evergreen/arm64/toolchain/BUILD.gn
index 02cce3e..5bc6339 100644
--- a/cobalt/account/BUILD.gn
+++ b/starboard/evergreen/arm64/toolchain/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
+import("//starboard/build/toolchain/linux/clang_lld_toolchain.gni")
 
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
+clang_lld_toolchain("target") {
 }
diff --git a/starboard/evergreen/shared/gyp_configuration.py b/starboard/evergreen/shared/gyp_configuration.py
index ca85820..c5f355c 100644
--- a/starboard/evergreen/shared/gyp_configuration.py
+++ b/starboard/evergreen/shared/gyp_configuration.py
@@ -27,7 +27,11 @@
 
   def GetTestTargets(self):
     tests = super().GetTestTargets()
-    tests.extend({'cobalt_slot_management_test', 'updater_test'})
+    tests.extend({
+        'cobalt_slot_management_test',
+        'crx_file_test',
+        'updater_test',
+    })
     return [test for test in tests if test not in self.__FORBIDDEN_TESTS]
 
   __FORBIDDEN_TESTS = [  # pylint: disable=invalid-name
diff --git a/starboard/evergreen/shared/launcher.py b/starboard/evergreen/shared/launcher.py
index cad9fbe..41143bd 100644
--- a/starboard/evergreen/shared/launcher.py
+++ b/starboard/evergreen/shared/launcher.py
@@ -119,7 +119,7 @@
         target_params=target_command_line_params,
         output_file=self.output_file,
         out_directory=self.staging_directory,
-        coverage_directory=self.coverage_directory,
+        coverage_file_path=self.coverage_file_path,
         env_variables=self.env_variables,
         log_targets=False)
 
diff --git a/starboard/evergreen/shared/platform_configuration/BUILD.gn b/starboard/evergreen/shared/platform_configuration/BUILD.gn
index ddaf279..6b154a0 100644
--- a/starboard/evergreen/shared/platform_configuration/BUILD.gn
+++ b/starboard/evergreen/shared/platform_configuration/BUILD.gn
@@ -74,6 +74,17 @@
     # By default, <EGL/eglplatform.h> pulls in some X11 headers that have some
     # nasty macros (|Status|, for example) that conflict with Chromium base.
     "MESA_EGL_NO_X11_HEADERS",
+
+    # During Evergreen updates the CRX package is kept in-memory, instead of
+    # on the file system, before getting unpacked.
+    # TODO(b/158043520): we need to make significant customizations to Chromium
+    # code to implement this feature and this macro allows us to switch back
+    # to the legacy behavior during development to verify the customizations
+    # are made cleanly. Once the feature is complete we may want to remove
+    # existing customizations that enable the legacy behavior for Cobalt builds,
+    # change IN_MEMORY_UPDATES references to USE_COBALT_CUSTOMIZATIONS
+    # references, and remove this macro.
+    "IN_MEMORY_UPDATES",
   ]
 
   if (is_debug) {
diff --git a/starboard/evergreen/shared/platform_configuration/configuration.gni b/starboard/evergreen/shared/platform_configuration/configuration.gni
index 5007bb5..f3aab33 100644
--- a/starboard/evergreen/shared/platform_configuration/configuration.gni
+++ b/starboard/evergreen/shared/platform_configuration/configuration.gni
@@ -26,6 +26,8 @@
 
 final_executable_type = "shared_library"
 gtest_target_type = "shared_library"
+starboard_level_final_executable_type = "shared_library"
+starboard_level_gtest_target_type = "shared_library"
 
 speed_config_path = "//starboard/evergreen/shared/platform_configuration:speed"
 size_config_path = "//starboard/evergreen/shared/platform_configuration:size"
diff --git a/starboard/evergreen/shared/strip_install_target.gni b/starboard/evergreen/shared/strip_install_target.gni
index 48b8b1e..7d46688 100644
--- a/starboard/evergreen/shared/strip_install_target.gni
+++ b/starboard/evergreen/shared/strip_install_target.gni
@@ -14,6 +14,7 @@
 
 template("strip_install_target") {
   installable_target_name = invoker.installable_target_name
+  installable_target_dep = invoker.installable_target_dep
 
   assert(defined(invoker.strip_executable) && invoker.strip_executable != "",
          "strip executable required for stripping")
@@ -36,7 +37,7 @@
     inputs = [ "$root_out_dir/$source_name" ]
 
     deps = invoker.deps
-    deps += [ ":$installable_target_name" ]
+    deps += [ installable_target_dep ]
 
     outputs = [ "$sb_install_output_dir/$install_subdir/$source_name" ]
 
diff --git a/starboard/evergreen/testing/run_all_tests.sh b/starboard/evergreen/testing/run_all_tests.sh
index 90a171b..0894d29 100755
--- a/starboard/evergreen/testing/run_all_tests.sh
+++ b/starboard/evergreen/testing/run_all_tests.sh
@@ -24,8 +24,7 @@
 USE_COMPRESSED_SYSTEM_IMAGE="false"
 SYSTEM_IMAGE_EXTENSION=".so"
 
-# TODO: Enable once the Starboard 16 binaries are published for Evergreen.
-DISABLE_TESTS="true"
+DISABLE_TESTS="false"
 
 while getopts "d:a:c" o; do
     case "${o}" in
diff --git a/starboard/evergreen/x64/configuration_public.h b/starboard/evergreen/x64/configuration_public.h
index 3430685..697318b 100644
--- a/starboard/evergreen/x64/configuration_public.h
+++ b/starboard/evergreen/x64/configuration_public.h
@@ -106,11 +106,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 0
diff --git a/starboard/evergreen/x64/test_filters.py b/starboard/evergreen/x64/test_filters.py
index 7d67132..5b1b30d 100644
--- a/starboard/evergreen/x64/test_filters.py
+++ b/starboard/evergreen/x64/test_filters.py
@@ -22,6 +22,10 @@
 # pylint: disable=line-too-long
 _FILTERED_TESTS = {
     'nplb': [
+        'MultiplePlayerTests/*/*sintel_329_ec3_dmp*',
+        'MultiplePlayerTests/*/*sintel_381_ac3_dmp*',
+        'SbPlayerGetAudioConfigurationTests/*audio_sintel_329_ec3_dmp_*',
+        'SbPlayerGetAudioConfigurationTests/*audio_sintel_381_ac3_dmp_*',
         'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteSingleBatch/audio_sintel_329_ec3_dmp_*',
         'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteSingleBatch/audio_sintel_381_ac3_dmp_*',
         'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteMultipleBatches/audio_sintel_329_ec3_dmp_*',
diff --git a/cobalt/account/BUILD.gn b/starboard/evergreen/x64/toolchain/BUILD.gn
similarity index 69%
copy from cobalt/account/BUILD.gn
copy to starboard/evergreen/x64/toolchain/BUILD.gn
index 02cce3e..5bc6339 100644
--- a/cobalt/account/BUILD.gn
+++ b/starboard/evergreen/x64/toolchain/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
+import("//starboard/build/toolchain/linux/clang_lld_toolchain.gni")
 
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
+clang_lld_toolchain("target") {
 }
diff --git a/starboard/evergreen/x86/configuration_public.h b/starboard/evergreen/x86/configuration_public.h
index 5ed04f7..ee3e4c0 100644
--- a/starboard/evergreen/x86/configuration_public.h
+++ b/starboard/evergreen/x86/configuration_public.h
@@ -106,11 +106,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 1
diff --git a/cobalt/account/BUILD.gn b/starboard/evergreen/x86/toolchain/BUILD.gn
similarity index 69%
copy from cobalt/account/BUILD.gn
copy to starboard/evergreen/x86/toolchain/BUILD.gn
index 02cce3e..5bc6339 100644
--- a/cobalt/account/BUILD.gn
+++ b/starboard/evergreen/x86/toolchain/BUILD.gn
@@ -1,4 +1,4 @@
-# Copyright 2021 The Cobalt Authors. All Rights Reserved.
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -12,13 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-static_library("account") {
-  has_pedantic_warnings = true
+import("//starboard/build/toolchain/linux/clang_lld_toolchain.gni")
 
-  sources = [
-    "account_manager.cc",
-    "account_manager.h",
-  ]
-
-  deps = [ "//starboard:starboard_headers_only" ]
+clang_lld_toolchain("target") {
 }
diff --git a/starboard/examples/glclear/BUILD.gn b/starboard/examples/glclear/BUILD.gn
index 3b8cbe1..60c6d62 100644
--- a/starboard/examples/glclear/BUILD.gn
+++ b/starboard/examples/glclear/BUILD.gn
@@ -13,10 +13,6 @@
 # limitations under the License.
 
 target(final_executable_type, "starboard_glclear_example") {
-  deps = [ "//starboard" ]
-  if (!sb_is_evergreen) {
-    deps += [ "//starboard/egl_and_gles" ]
-  }
-
   sources = [ "main.cc" ]
+  deps = [ "//starboard" ]
 }
diff --git a/starboard/extension/platform_info.h b/starboard/extension/platform_info.h
index a9d9b11..e670044 100644
--- a/starboard/extension/platform_info.h
+++ b/starboard/extension/platform_info.h
@@ -35,8 +35,8 @@
 
   // The fields below this point were added in version 1 or later.
 
-  // Returns details about the device firmware version. This can be something
-  // like Android build fingerprint (go/android-build-fingerprint).
+  // Returns details about the device firmware version. On Android, this will
+  // be the Android build fingerprint (go/android-build-fingerprint).
   bool (*GetFirmwareVersionDetails)(char* out_value, int value_length);
 
   // Returns the OS experience. (e.g. Amati or Watson on an Android device).
diff --git a/starboard/linux/shared/BUILD.gn b/starboard/linux/shared/BUILD.gn
index 7069517..01a1bf5 100644
--- a/starboard/linux/shared/BUILD.gn
+++ b/starboard/linux/shared/BUILD.gn
@@ -434,18 +434,21 @@
   }
 }
 
-target(gtest_target_type, "starboard_platform_tests") {
-  testonly = true
+if (current_toolchain == starboard_toolchain) {
+  target(starboard_level_gtest_target_type, "starboard_platform_tests") {
+    build_loader = false
+    testonly = true
 
-  sources = media_tests_sources + player_tests_sources +
-            [ "//starboard/common/test_main.cc" ]
+    sources = media_tests_sources + player_tests_sources +
+              [ "//starboard/common/test_main.cc" ]
 
-  configs += [ "//starboard/build/config:starboard_implementation" ]
+    configs += [ "//starboard/build/config:starboard_implementation" ]
 
-  deps = [
-    "//starboard",
-    "//starboard/shared/starboard/player/filter/testing:test_util",
-    "//testing/gmock",
-    "//testing/gtest",
-  ]
+    deps = [
+      "//starboard",
+      "//starboard/shared/starboard/player/filter/testing:test_util",
+      "//testing/gmock",
+      "//testing/gtest",
+    ]
+  }
 }
diff --git a/starboard/linux/shared/launcher.py b/starboard/linux/shared/launcher.py
index 7145a2c..812b87c 100644
--- a/starboard/linux/shared/launcher.py
+++ b/starboard/linux/shared/launcher.py
@@ -31,6 +31,8 @@
 # This file is still executed with Python2 in CI.
 # pylint:disable=consider-using-f-string,super-with-arguments
 
+IS_MODULAR_BUILD = os.getenv("MODULAR_BUILD", "0") == "1"
+
 
 def GetProcessStatus(pid):
   """Returns process running status given its pid, or empty string if not found.
@@ -61,6 +63,14 @@
       self.device_ip = socket.gethostbyname(socket.gethostname())
 
     self.executable = self.GetTargetPath()
+    if IS_MODULAR_BUILD:
+      self.executable += "_loader"
+      if not os.path.exists(self.executable):
+        self.executable = os.path.abspath(
+            os.path.join(self.out_directory, "starboard", self.target_name))
+
+      # TODO(b/285234546): Resolve ASAN leaks and re-enable it.
+      self.IgnoreAsanLeaks()
 
     env = os.environ.copy()
     env.update(self.env_variables)
@@ -69,14 +79,12 @@
     # Ensure that if the binary has code coverage or profiling instrumentation,
     # the output will be written to a file in the coverage_directory named as
     # the target_name with '.profraw' postfixed.
-    if self.coverage_directory:
-      target_profraw = os.path.join(self.coverage_directory,
-                                    target_name + ".profraw")
-      env.update({"LLVM_PROFILE_FILE": target_profraw})
+    if self.coverage_file_path:
+      env.update({"LLVM_PROFILE_FILE": self.coverage_file_path})
 
       # Remove any stale profraw file that may already exist.
       try:
-        os.remove(target_profraw)
+        os.remove(self.coverage_file_path)
       except OSError as e:
         if e.errno != errno.ENOENT:
           raise
@@ -205,3 +213,12 @@
   def GetDeviceOutputPath(self):
     """Writable path where test targets can output files"""
     return "/tmp/testoutput"
+
+  def IgnoreAsanLeaks(self):
+    asan_options = self.env_variables.get("ASAN_OPTIONS", "")
+    asan_options = [
+        opt for opt in asan_options.split(":") if "detect_leaks" not in opt
+    ]
+    asan_options.append("detect_leaks=0")
+    asan_options.append("detect_odr_violation=0")
+    self.env_variables["ASAN_OPTIONS"] = ":".join(asan_options)
diff --git a/starboard/linux/shared/platform_configuration/BUILD.gn b/starboard/linux/shared/platform_configuration/BUILD.gn
index 681f330..d1cc9e1 100644
--- a/starboard/linux/shared/platform_configuration/BUILD.gn
+++ b/starboard/linux/shared/platform_configuration/BUILD.gn
@@ -33,9 +33,6 @@
       "-Werror",
       "-fcolor-diagnostics",
 
-      # Default visibility to hidden, to enable dead stripping.
-      "-fvisibility=hidden",
-
       # Warn for implicit type conversions that may change a value.
       "-Wconversion",
 
@@ -66,6 +63,13 @@
       # Do not warn about unused function params.
       "-Wno-unused-parameter",
     ]
+    if (build_with_separate_cobalt_toolchain) {
+      # If we're building modularly, we need visibility.
+      cflags += [ "-fvisibility=default" ]
+    } else {
+      # Default visibility to hidden, to enable dead stripping.
+      cflags += [ "-fvisibility=hidden" ]
+    }
 
     if (is_gold) {
       cflags += [
diff --git a/starboard/linux/shared/platform_configuration/configuration.gni b/starboard/linux/shared/platform_configuration/configuration.gni
index 105008d..c2e3f6c 100644
--- a/starboard/linux/shared/platform_configuration/configuration.gni
+++ b/starboard/linux/shared/platform_configuration/configuration.gni
@@ -34,7 +34,8 @@
 
 sb_widevine_platform = "linux"
 
-platform_tests_path = "//starboard/linux/shared:starboard_platform_tests"
+platform_tests_path =
+    "//starboard/linux/shared:starboard_platform_tests($starboard_toolchain)"
 
 enable_in_app_dial = true
 
diff --git a/starboard/linux/shared/test_filters.py b/starboard/linux/shared/test_filters.py
index c2c33f6..43a454d 100644
--- a/starboard/linux/shared/test_filters.py
+++ b/starboard/linux/shared/test_filters.py
@@ -20,9 +20,30 @@
 
 
 # pylint: disable=line-too-long
-_FILTERED_TESTS = {
-    'nplb': [],
+_MODULAR_BUILD_FILTERED_TESTS = {
+    'nplb': [
+        'MultiplePlayerTests/*/*sintel_329_ec3_dmp*',
+        'MultiplePlayerTests/*/*sintel_381_ac3_dmp*',
+        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteSingleBatch/audio_sintel_329_ec3_dmp_*',
+        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteSingleBatch/audio_sintel_381_ac3_dmp_*',
+        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteMultipleBatches/audio_sintel_329_ec3_dmp_*',
+        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteMultipleBatches/audio_sintel_381_ac3_dmp_*',
+        'SbSocketAddressTypes/SbSocketGetInterfaceAddressTest.SunnyDayDestination/type_ipv6',
+        'SbSocketAddressTypes/SbSocketGetInterfaceAddressTest.SunnyDaySourceForDestination/type_ipv6',
+        'SbSocketAddressTypes/SbSocketGetInterfaceAddressTest.SunnyDaySourceNotLoopback/type_ipv6',
+    ],
+    'player_filter_tests': [test_filter.FILTER_ALL],
 }
+
+_FILTERED_TESTS = {
+    'nplb': [
+        # TODO(b/286249595): This test crashes when coverage is enabled.
+        'SbMemoryMapTest.CanChangeMemoryProtection'
+    ],
+}
+if os.getenv('MODULAR_BUILD', '0') == '1':
+  _FILTERED_TESTS = _MODULAR_BUILD_FILTERED_TESTS
+
 # Conditionally disables tests that require ipv6
 if os.getenv('IPV6_AVAILABLE', '1') == '0':
   _FILTERED_TESTS['nplb'].extend([
diff --git a/starboard/linux/x64x11/configuration_public.h b/starboard/linux/x64x11/configuration_public.h
index 6f7b0ab..58fccec 100644
--- a/starboard/linux/x64x11/configuration_public.h
+++ b/starboard/linux/x64x11/configuration_public.h
@@ -29,11 +29,6 @@
 // available on this platform. For a definitive measure, the application should
 // still call SbSystemGetNumberOfProcessors at runtime.
 
-// Whether the current platform's thread scheduler will automatically balance
-// threads between cores, as opposed to systems where threads will only ever run
-// on the specifically pinned core.
-#define SB_HAS_CROSS_CORE_SCHEDULER 1
-
 // --- Graphics Configuration ------------------------------------------------
 
 // Indicates whether or not the given platform supports rendering of NV12
diff --git a/starboard/linux/x64x11/main.cc b/starboard/linux/x64x11/main.cc
index b76fb55..82046a0 100644
--- a/starboard/linux/x64x11/main.cc
+++ b/starboard/linux/x64x11/main.cc
@@ -12,6 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+#include <malloc.h>
 #include <time.h>
 
 #include "starboard/configuration.h"
@@ -31,6 +32,9 @@
 #include "third_party/crashpad/wrapper/wrapper.h"
 
 extern "C" SB_EXPORT_PLATFORM int main(int argc, char** argv) {
+  // Set M_ARENA_MAX to a low value to slow memory growth due to fragmentation.
+  mallopt(M_ARENA_MAX, 2);
+
   tzset();
   starboard::shared::signal::InstallCrashSignalHandlers();
   starboard::shared::signal::InstallDebugSignalHandlers();
diff --git a/starboard/linux/x64x11/shared/platform_configuration/BUILD.gn b/starboard/linux/x64x11/shared/platform_configuration/BUILD.gn
index ae724f7..32c24f6 100644
--- a/starboard/linux/x64x11/shared/platform_configuration/BUILD.gn
+++ b/starboard/linux/x64x11/shared/platform_configuration/BUILD.gn
@@ -13,17 +13,28 @@
 # limitations under the License.
 
 config("platform_configuration") {
-  configs = [
-    ":libraries",
-    "//starboard/linux/shared/platform_configuration",
-    "//starboard/linux/shared/platform_configuration:compiler_flags",
-    ":linker_flags",
-  ]
+  if (current_toolchain == default_toolchain &&
+      build_with_separate_cobalt_toolchain) {
+    configs = [ "//starboard/evergreen/x64/platform_configuration" ]
+  } else {
+    configs = [
+      ":libraries",
+      "//starboard/linux/shared/platform_configuration",
+      "//starboard/linux/shared/platform_configuration:compiler_flags",
+      ":linker_flags",
+    ]
+  }
 }
 
 config("libraries") {
   configs = [ "//starboard/linux/shared/platform_configuration:libraries" ]
-  libs = [ "//third_party/libvpx/platforms/linux-x64/libvpx.a" ]
+  if (build_with_separate_cobalt_toolchain) {
+    libs = [ "//third_party/libvpx/platforms/linux-x64/libvpx.so.6" ]
+    ldflags = [ "-Wl,-rpath=" + rebase_path("//") +
+                "/third_party/libvpx/platforms/linux-x64/" ]
+  } else {
+    libs = [ "//third_party/libvpx/platforms/linux-x64/libvpx.a" ]
+  }
 }
 
 config("linker_flags") {
diff --git a/starboard/linux/x64x11/shared/platform_configuration/configuration.gni b/starboard/linux/x64x11/shared/platform_configuration/configuration.gni
index 457369f..90d2d22 100644
--- a/starboard/linux/x64x11/shared/platform_configuration/configuration.gni
+++ b/starboard/linux/x64x11/shared/platform_configuration/configuration.gni
@@ -12,9 +12,17 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-import("//starboard/linux/shared/platform_configuration/configuration.gni")
+if (current_toolchain == default_toolchain &&
+    build_with_separate_cobalt_toolchain) {
+  import("//starboard/evergreen/x64/platform_configuration/configuration.gni")
+  platform_tests_path =
+      "//starboard/linux/shared:starboard_platform_tests($starboard_toolchain)"
+  cobalt_font_package = "standard"
+} else {
+  import("//starboard/linux/shared/platform_configuration/configuration.gni")
 
-sb_is_evergreen_compatible = true
-sb_evergreen_compatible_use_libunwind = true
+  sb_is_evergreen_compatible = true
+  sb_evergreen_compatible_use_libunwind = true
 
-sabi_path = "//starboard/sabi/x64/sysv/sabi-v$sb_api_version.json"
+  sabi_path = "//starboard/sabi/x64/sysv/sabi-v$sb_api_version.json"
+}
diff --git a/starboard/linux/x64x11/starboard_loader.cc b/starboard/linux/x64x11/starboard_loader.cc
new file mode 100644
index 0000000..065bfaa
--- /dev/null
+++ b/starboard/linux/x64x11/starboard_loader.cc
@@ -0,0 +1,19 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "starboard/event.h"
+
+int main(int argc, char** argv) {
+  return SbRunStarboardMain(argc, argv, SbEventHandle);
+}
diff --git a/starboard/linux/x64x11/toolchain/BUILD.gn b/starboard/linux/x64x11/toolchain/BUILD.gn
index 304fda6..bcee641 100644
--- a/starboard/linux/x64x11/toolchain/BUILD.gn
+++ b/starboard/linux/x64x11/toolchain/BUILD.gn
@@ -15,6 +15,10 @@
 import("//build/config/clang/clang.gni")
 import("//starboard/shared/toolchain/overridable_gcc_toolchain.gni")
 
+overridable_clang_toolchain("starboard") {
+  clang_base_path = clang_base_path
+}
+
 overridable_clang_toolchain("target") {
   clang_base_path = clang_base_path
 }
diff --git a/starboard/loader_app/BUILD.gn b/starboard/loader_app/BUILD.gn
index 18577df..4d38cce 100644
--- a/starboard/loader_app/BUILD.gn
+++ b/starboard/loader_app/BUILD.gn
@@ -88,39 +88,44 @@
   }
 }
 
-target(final_executable_type, "loader_app") {
-  if (target_cpu == "x86" || target_cpu == "x64" || target_cpu == "arm" ||
-      target_cpu == "arm64") {
-    data_deps = [ "//third_party/icu:icudata" ]
-    if (cobalt_font_package == "empty") {
-      data_deps += [ "//cobalt/content/fonts:copy_font_data" ]
-    } else {
-      data_deps += [
-        "//cobalt/content/fonts:copy_fonts",
-        "//cobalt/content/fonts:fonts_xml",
+if (current_toolchain == starboard_toolchain) {
+  target(starboard_level_final_executable_type, "loader_app") {
+    build_loader = false
+    if (target_cpu == "x86" || target_cpu == "x64" || target_cpu == "arm" ||
+        target_cpu == "arm64") {
+      data_deps = [ "//third_party/icu:icudata" ]
+      if (cobalt_font_package == "empty") {
+        data_deps += [ "//cobalt/content/fonts:copy_font_data" ]
+      } else {
+        data_deps += [
+          "//cobalt/content/fonts:copy_fonts",
+          "//cobalt/content/fonts:fonts_xml",
+        ]
+      }
+      sources = _common_loader_app_sources
+      deps = [
+        ":common_loader_app_dependencies",
+        "//cobalt/content/fonts:copy_font_data",
+        "//starboard/elf_loader",
       ]
-    }
-    sources = _common_loader_app_sources
-    deps = [
-      ":common_loader_app_dependencies",
-      "//cobalt/content/fonts:copy_font_data",
-      "//starboard/elf_loader",
-    ]
-    if (sb_is_evergreen_compatible && sb_evergreen_compatible_package) {
-      data_deps += [
-        ":copy_crashpad_handler_named_as_so",
-        ":copy_loader_app_content",
-        ":copy_loader_app_lib",
-        ":copy_loader_app_manifest",
-      ]
-      deps += [
-        ":copy_crashpad_handler_named_as_so",
-        ":copy_loader_app_content",
-        ":copy_loader_app_lib",
-        ":copy_loader_app_manifest",
-      ]
+      if (sb_is_evergreen_compatible && sb_evergreen_compatible_package) {
+        data_deps += [
+          ":copy_crashpad_handler_named_as_so",
+          ":copy_loader_app_content",
+          ":copy_loader_app_lib",
+          ":copy_loader_app_manifest",
+        ]
+        deps += [
+          ":copy_crashpad_handler_named_as_so",
+          ":copy_loader_app_content",
+          ":copy_loader_app_lib",
+          ":copy_loader_app_manifest",
+        ]
+      }
     }
   }
+} else {
+  not_needed([ "_common_loader_app_sources" ])
 }
 
 if (sb_is_evergreen_compatible) {
diff --git a/starboard/nplb/BUILD.gn b/starboard/nplb/BUILD.gn
index ed5dfa9..26baef2 100644
--- a/starboard/nplb/BUILD.gn
+++ b/starboard/nplb/BUILD.gn
@@ -93,9 +93,13 @@
     # TODO: Separate functions tested by media buffer test into multiple
     # files.
     "drm_create_system_test.cc",
+    "maximum_player_configuration_explorer.cc",
+    "maximum_player_configuration_explorer.h",
+    "maximum_player_configuration_explorer_test.cc",
     "media_buffer_test.cc",
     "media_can_play_mime_and_key_system_test.cc",
     "media_configuration_test.cc",
+    "media_set_audio_write_duration_test.cc",
     "memory_allocate_aligned_test.cc",
     "memory_allocate_test.cc",
     "memory_deallocate_aligned_test.cc",
@@ -110,6 +114,7 @@
     "microphone_is_sample_rate_supported_test.cc",
     "microphone_open_test.cc",
     "microphone_read_test.cc",
+    "multiple_player_test.cc",
     "murmurhash2_test.cc",
     "mutex_acquire_test.cc",
     "mutex_acquire_try_test.cc",
@@ -120,6 +125,7 @@
     "player_create_test.cc",
     "player_creation_param_helpers.cc",
     "player_creation_param_helpers.h",
+    "player_get_audio_configuration_test.cc",
     "player_get_preferred_output_mode_test.cc",
     "player_test_fixture.cc",
     "player_test_fixture.h",
@@ -217,6 +223,7 @@
     "user_get_current_test.cc",
     "user_get_property_test.cc",
     "user_get_signed_in_test.cc",
+    "vertical_video_test.cc",
     "window_create_test.cc",
     "window_destroy_test.cc",
     "window_get_diagonal_size_in_inches_test.cc",
@@ -237,6 +244,7 @@
     "//starboard/shared/starboard/media:media_util",
     "//starboard/shared/starboard/player:video_dmp",
     "//testing/gmock",
+    "//testing/gtest",
   ]
 
   deps += cobalt_platform_dependencies
@@ -245,10 +253,6 @@
     deps += [ "//internal/starboard/private/nplb:nplb_private" ]
   }
 
-  if (gl_type != "none") {
-    deps += [ "//starboard/egl_and_gles" ]
-  }
-
   if (sb_enable_cpp17_audit) {
     deps += [ "//starboard/nplb/compiler_compliance:cpp17_supported" ]
   }
diff --git a/starboard/nplb/maximum_player_configuration_explorer.cc b/starboard/nplb/maximum_player_configuration_explorer.cc
new file mode 100644
index 0000000..084e3f4
--- /dev/null
+++ b/starboard/nplb/maximum_player_configuration_explorer.cc
@@ -0,0 +1,288 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "starboard/nplb/maximum_player_configuration_explorer.h"
+
+#include <algorithm>
+#include <numeric>
+#include <stack>
+#include <unordered_map>
+#include <utility>
+
+#include "starboard/common/log.h"
+#include "starboard/nplb/drm_helpers.h"
+#include "starboard/nplb/player_test_util.h"
+#include "starboard/player.h"
+
+namespace starboard {
+namespace nplb {
+
+namespace {
+
+using shared::starboard::player::video_dmp::VideoDmpReader;
+
+class HashFunction {
+ public:
+  size_t operator()(const std::vector<int>& vector) const {
+    size_t hash = 0;
+    for (const auto& v : vector) {
+      hash += v;
+      hash *= 10;  // since we support at most 7 instances, 10 is good enough.
+    }
+    return hash;
+  }
+};
+
+}  // namespace
+
+// The partial order relation here is: Given two vectors, a and b, a >= b if and
+// only if a[i] >= b[i] for all indices i.
+bool PosetGreaterThanOrEqualTo(const std::vector<int>& a,
+                               const std::vector<int>& b) {
+  SB_DCHECK(a.size() == b.size());
+
+  for (int i = 0; i < a.size(); ++i) {
+    if (a[i] < b[i]) {
+      return false;
+    }
+  }
+  return true;
+}
+
+// Given a vector v, test if it is contained within a max elements set s.
+// v is contained in a max elements set s if and only if there is a max element
+// m within s such that m >= v.
+bool PosetContainedByMaxElementsSet(
+    const std::set<std::vector<int>>& max_elements_set,
+    const std::vector<int>& v) {
+  for (const auto& max_element : max_elements_set) {
+    if (PosetGreaterThanOrEqualTo(max_element, v)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+// The function is responsible for arranging the search process to identify the
+// maximum elements within a graded poset, which is based on a set of vectors
+// comprising integers. Specifically, the length of each vector is determined by
+// the number of |resource_types|, while the range of integers in each vector
+// spans from 0 to the maximum number of |max_instances_per_resource|, as [0,
+// max_instances]. The partial order <= between two vectors is defined such that
+// one vector is considered less than or equal to the other vector if all the
+// corresponding integers in the first vector are smaller than or equal to the
+// corresponding integers in the second vector. To identify the maximum
+// elements, a test function, denoted as |test_functor|, must be provided to
+// evaluate whether the current configuration satisfies the criterion for a
+// maximum element. The reason for applying the depth first search scheduler in
+// this context is that it is a faster method.
+std::set<std::vector<int>> SearchPosetMaximalElementsDFS(
+    int resource_types,
+    int max_instances_per_resource,
+    const PosetSearchFunctor& test_functor) {
+  SB_DCHECK(resource_types > 0);
+  SB_DCHECK(max_instances_per_resource > 0);
+  SB_DCHECK(test_functor);
+
+  std::stack<std::pair<std::vector<int>, int>> stack;
+  std::unordered_map<std::vector<int>, bool, HashFunction> valid;
+  std::set<std::vector<int>> max_elements_set;
+
+  stack.push(std::make_pair(std::vector<int>(resource_types, 0), 0));
+  valid[stack.top().first] = false;
+  while (!stack.empty()) {
+    // The current node in the search graph consists of a configuration and the
+    // next index to be advanced.
+    auto& node = stack.top();
+    auto& config = node.first;
+    auto& index = node.second;
+    while (index < resource_types) {
+      if (config[index] != max_instances_per_resource) {
+        ++config[index];
+        break;
+      }
+      ++index;
+    }
+
+    if (index != resource_types) {
+      if ((PosetContainedByMaxElementsSet(max_elements_set, config) ||
+           test_functor(config))) {
+        stack.push(std::make_pair(config, index));
+        valid[config] = true;
+      } else {
+        valid[config] = false;
+      }
+      --config[index];
+      ++index;
+    } else {
+      bool can_advance = false;
+      for (int i = 0; i < config.size(); ++i) {
+        if (config[i] >= max_instances_per_resource) {
+          continue;
+        } else {
+          ++config[i];
+          if (valid[config]) {
+            can_advance = true;
+            break;
+          }
+          --config[i];
+        }
+      }
+      if (!can_advance) {
+        max_elements_set.insert(config);
+      }
+      stack.pop();
+    }
+  }
+  return max_elements_set;
+}
+
+MaximumPlayerConfigurationExplorer::MaximumPlayerConfigurationExplorer(
+    const std::vector<SbPlayerTestConfig>& player_configs,
+    int max_instances_per_config,
+    int max_total_instances,
+    testing::FakeGraphicsContextProvider* fake_graphics_context_provider)
+    : player_configs_(player_configs),
+      max_instances_per_config_(max_instances_per_config),
+      max_total_instances_(max_total_instances),
+      fake_graphics_context_provider_(fake_graphics_context_provider),
+      player_instances_(player_configs.size()) {
+  SB_DCHECK(!player_configs_.empty());
+  SB_DCHECK(max_instances_per_config_ > 0);
+  SB_DCHECK(max_total_instances_ > 0);
+  SB_DCHECK(fake_graphics_context_provider_);
+  SB_DCHECK(player_instances_.size() == player_configs_.size());
+  SB_DCHECK(player_configs_.size() <= 7 && max_instances_per_config_ <= 7)
+      << "Exploring configs with that size may be a time-consuming process.";
+}
+
+MaximumPlayerConfigurationExplorer::~MaximumPlayerConfigurationExplorer() {
+  for (auto& instances : player_instances_) {
+    for (auto& instance : instances) {
+      DestroyPlayerInstance(instance);
+    }
+  }
+}
+
+std::vector<SbPlayerMultiplePlayerTestConfig>
+MaximumPlayerConfigurationExplorer::CalculateMaxTestConfigs() {
+  PosetSearchFunctor test_functor =
+      std::bind(&MaximumPlayerConfigurationExplorer::IsConfigCreatable, this,
+                std::placeholders::_1);
+  std::set<std::vector<int>> result = SearchPosetMaximalElementsDFS(
+      player_configs_.size(), max_instances_per_config_, test_functor);
+  std::vector<SbPlayerMultiplePlayerTestConfig> configs_to_return;
+  for (auto& configs_vector : result) {
+    SB_DCHECK(configs_vector.size() == player_configs_.size());
+
+    SbPlayerMultiplePlayerTestConfig multi_player_test_config;
+    for (int i = 0; i < configs_vector.size(); i++) {
+      multi_player_test_config.insert(multi_player_test_config.end(),
+                                      configs_vector[i], player_configs_[i]);
+    }
+    if (!multi_player_test_config.empty()) {
+      configs_to_return.push_back(multi_player_test_config);
+    }
+  }
+  return configs_to_return;
+}
+
+bool MaximumPlayerConfigurationExplorer::IsConfigCreatable(
+    const std::vector<int>& configs_to_create) {
+  SB_DCHECK(configs_to_create.size() == player_configs_.size());
+
+  if (std::accumulate(configs_to_create.begin(), configs_to_create.end(), 0) >
+      max_total_instances_) {
+    // Total instances should not exceed |max_total_instances_|.
+    return false;
+  }
+
+  for (int i = 0; i < configs_to_create.size(); i++) {
+    SB_DCHECK(configs_to_create[i] >= 0);
+    SB_DCHECK(configs_to_create[i] <= max_instances_per_config_);
+
+    std::vector<PlayerInstance>& instances = player_instances_[i];
+    while (instances.size() > configs_to_create[i]) {
+      DestroyPlayerInstance(instances.back());
+      instances.pop_back();
+    }
+    while (instances.size() < configs_to_create[i]) {
+      PlayerInstance instance = CreatePlayerInstance(player_configs_[i]);
+      if (instance.player == kSbPlayerInvalid) {
+        return false;
+      }
+      instances.push_back(instance);
+    }
+
+    SB_DCHECK(instances.size() == configs_to_create[i]);
+  }
+  return true;
+}
+
+MaximumPlayerConfigurationExplorer::PlayerInstance
+MaximumPlayerConfigurationExplorer::CreatePlayerInstance(
+    const SbPlayerTestConfig& config) {
+  // Currently, audio config is ignored.
+  const char* video_filename = config.video_filename;
+  SbPlayerOutputMode output_mode = config.output_mode;
+  const char* key_system = config.key_system;
+  SB_DCHECK(video_filename && strlen(video_filename) > 0);
+  SB_DCHECK(output_mode == kSbPlayerOutputModeDecodeToTexture ||
+            output_mode == kSbPlayerOutputModePunchOut);
+  SB_DCHECK(key_system);
+
+  SbDrmSystem drm_system = kSbDrmSystemInvalid;
+  if (strlen(key_system) > 0) {
+    drm_system = SbDrmCreateSystem(
+        key_system, NULL /* context */, DummySessionUpdateRequestFunc,
+        DummySessionUpdatedFunc, DummySessionKeyStatusesChangedFunc,
+        DummyServerCertificateUpdatedFunc, DummySessionClosedFunc);
+
+    if (!SbDrmSystemIsValid(drm_system)) {
+      return PlayerInstance();
+    }
+  }
+
+  VideoDmpReader video_dmp_reader(video_filename,
+                                  VideoDmpReader::kEnableReadOnDemand);
+  // TODO: refine CallSbPlayerCreate() to use real video sample info.
+  SbPlayer player = CallSbPlayerCreate(
+      fake_graphics_context_provider_->window(), video_dmp_reader.video_codec(),
+      kSbMediaAudioCodecNone, drm_system, nullptr /* audio_stream_info */,
+      "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
+      DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
+      nullptr /* context */, output_mode,
+      fake_graphics_context_provider_->decoder_target_provider());
+  if (!SbPlayerIsValid(player)) {
+    if (SbDrmSystemIsValid(drm_system)) {
+      SbDrmDestroySystem(drm_system);
+    }
+    return PlayerInstance();
+  }
+
+  return PlayerInstance(player, drm_system, config);
+}
+
+void MaximumPlayerConfigurationExplorer::DestroyPlayerInstance(
+    const MaximumPlayerConfigurationExplorer::PlayerInstance& instance) {
+  SB_DCHECK(SbPlayerIsValid(instance.player));
+  SbPlayerDestroy(instance.player);
+
+  if (SbDrmSystemIsValid(instance.drm_system)) {
+    SbDrmDestroySystem(instance.drm_system);
+  }
+}
+
+}  // namespace nplb
+}  // namespace starboard
diff --git a/starboard/nplb/maximum_player_configuration_explorer.h b/starboard/nplb/maximum_player_configuration_explorer.h
new file mode 100644
index 0000000..bf74aea
--- /dev/null
+++ b/starboard/nplb/maximum_player_configuration_explorer.h
@@ -0,0 +1,93 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef STARBOARD_NPLB_MAXIMUM_PLAYER_CONFIGURATION_EXPLORER_H_
+#define STARBOARD_NPLB_MAXIMUM_PLAYER_CONFIGURATION_EXPLORER_H_
+
+#include <set>
+#include <string>
+#include <vector>
+
+#include "starboard/drm.h"
+#include "starboard/nplb/player_test_util.h"
+#include "starboard/player.h"
+#include "starboard/shared/starboard/media/media_util.h"
+#include "starboard/testing/fake_graphics_context_provider.h"
+
+namespace starboard {
+namespace nplb {
+
+typedef const std::function<bool(const std::vector<int>&)> PosetSearchFunctor;
+typedef std::vector<SbPlayerTestConfig> SbPlayerMultiplePlayerTestConfig;
+
+// Expose the two functions below for testing.
+bool PosetContainedByMaxElementsSet(
+    const std::set<std::vector<int>>& max_elements_set,
+    const std::vector<int>& v);
+std::set<std::vector<int>> SearchPosetMaximalElementsDFS(
+    int resource_types,
+    int max_instances_per_resource,
+    const PosetSearchFunctor& test_functor);
+
+// The MaximumPlayerConfigurationExplorer is to get the maximum feasible
+// configurations for a group of players that the platform can create and run
+// concurrently.
+class MaximumPlayerConfigurationExplorer {
+ public:
+  // Note that with the initial implementation, the audio config is ignored.
+  MaximumPlayerConfigurationExplorer(
+      const std::vector<SbPlayerTestConfig>& player_configs,
+      int max_instances_per_config,
+      int max_total_instances,
+      testing::FakeGraphicsContextProvider* fake_graphics_context_provider);
+  ~MaximumPlayerConfigurationExplorer();
+
+  std::vector<SbPlayerMultiplePlayerTestConfig> CalculateMaxTestConfigs();
+
+ private:
+  struct PlayerInstance {
+    PlayerInstance()
+        : config(nullptr, nullptr, kSbPlayerOutputModeInvalid, "") {}
+    PlayerInstance(SbPlayer player,
+                   SbDrmSystem drm_system,
+                   const SbPlayerTestConfig& config)
+        : player(player), drm_system(drm_system), config(config) {}
+    SbPlayer player = kSbPlayerInvalid;
+    SbDrmSystem drm_system = kSbDrmSystemInvalid;
+    SbPlayerTestConfig config;
+  };
+
+  // Test whether the system can support this particular configuration of
+  // players by creating it.
+  bool IsConfigCreatable(const std::vector<int>& configs_to_create);
+  PlayerInstance CreatePlayerInstance(const SbPlayerTestConfig& config);
+  void DestroyPlayerInstance(const PlayerInstance& instance);
+
+  const std::vector<SbPlayerTestConfig> player_configs_;
+  const int max_instances_per_config_;
+  const int max_total_instances_;
+  testing::FakeGraphicsContextProvider* fake_graphics_context_provider_;
+
+  std::vector<std::vector<PlayerInstance>> player_instances_;
+
+  MaximumPlayerConfigurationExplorer(
+      const MaximumPlayerConfigurationExplorer& other) = delete;
+  MaximumPlayerConfigurationExplorer& operator=(
+      const MaximumPlayerConfigurationExplorer& other) = delete;
+};
+
+}  // namespace nplb
+}  // namespace starboard
+
+#endif  // STARBOARD_NPLB_MAXIMUM_PLAYER_CONFIGURATION_EXPLORER_H_
diff --git a/starboard/nplb/maximum_player_configuration_explorer_test.cc b/starboard/nplb/maximum_player_configuration_explorer_test.cc
new file mode 100644
index 0000000..ed704c3
--- /dev/null
+++ b/starboard/nplb/maximum_player_configuration_explorer_test.cc
@@ -0,0 +1,119 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <set>
+#include <string>
+#include <vector>
+
+#include "starboard/nplb/drm_helpers.h"
+#include "starboard/nplb/maximum_player_configuration_explorer.h"
+#include "starboard/nplb/player_test_util.h"
+#include "starboard/shared/starboard/player/video_dmp_reader.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace starboard {
+namespace nplb {
+namespace {
+
+using shared::starboard::player::video_dmp::VideoDmpReader;
+using ::testing::Combine;
+using ::testing::ValuesIn;
+
+TEST(SearchPosetMaximalElementsTests, SearchPosetMaximalElementsTest) {
+  constexpr int kResource_types = 3;
+  constexpr int kMaxInstances = 5;
+
+  std::set<std::vector<int>> test_pattern_set = {
+      {1, 4, 5}, {2, 5, 3}, {3, 3, 4}, {3, 4, 3}, {4, 0, 3}, {5, 5, 2}};
+
+  auto test_function = std::bind(PosetContainedByMaxElementsSet,
+                                 test_pattern_set, std::placeholders::_1);
+
+  auto max_test_config_set = SearchPosetMaximalElementsDFS(
+      kResource_types, kMaxInstances, test_function);
+
+  EXPECT_EQ(max_test_config_set, test_pattern_set);
+}
+
+class MaximumPlayerConfigurationExplorerTest
+    : public ::testing::TestWithParam<
+          ::testing::tuple<SbPlayerOutputMode, const char*>> {
+ protected:
+  MaximumPlayerConfigurationExplorerTest() {}
+
+  testing::FakeGraphicsContextProvider fake_graphics_context_provider_;
+};
+
+TEST_P(MaximumPlayerConfigurationExplorerTest, SunnyDay) {
+  const int kMaxPlayerInstancesPerConfig = 5;
+  const int kMaxTotalPlayerInstances = 5;
+
+  SbPlayerOutputMode output_mode = std::get<0>(GetParam());
+  const char* key_system = std::get<1>(GetParam());
+
+  const std::vector<const char*>& video_test_files = GetVideoTestFiles();
+  std::vector<SbPlayerTestConfig> supported_player_configs;
+  for (const auto& video_filename : video_test_files) {
+    VideoDmpReader dmp_reader(video_filename,
+                              VideoDmpReader::kEnableReadOnDemand);
+    SB_DCHECK(dmp_reader.number_of_video_buffers() > 0);
+    if (SbMediaCanPlayMimeAndKeySystem(dmp_reader.video_mime_type().c_str(),
+                                       key_system)) {
+      supported_player_configs.emplace_back(nullptr, video_filename,
+                                            output_mode, key_system);
+    }
+  }
+
+  if (supported_player_configs.empty()) {
+    // TODO: Use GTEST_SKIP when we have a newer version of gtest.
+    SB_LOG(INFO) << "No supported video codec. Skip the tests.";
+    return;
+  }
+
+  // The test only ensures the explorer doesn't crash and can get result, but
+  // would not verify the correctness of the result.
+  MaximumPlayerConfigurationExplorer explorer(
+      supported_player_configs, kMaxPlayerInstancesPerConfig,
+      kMaxTotalPlayerInstances, &fake_graphics_context_provider_);
+  explorer.CalculateMaxTestConfigs();
+}
+
+std::string GetTestConfigName(
+    ::testing::TestParamInfo<::testing::tuple<SbPlayerOutputMode, const char*>>
+        info) {
+  const ::testing::tuple<SbPlayerOutputMode, const char*>& config = info.param;
+
+  SbPlayerOutputMode output_mode = std::get<0>(config);
+  const char* key_system = std::get<1>(config);
+
+  std::string name = FormatString(
+      "output_%s_key_system_%s",
+      output_mode == kSbPlayerOutputModeDecodeToTexture ? "decode_to_texture"
+                                                        : "punch_out",
+      strlen(key_system) > 0 ? key_system : "null");
+  std::replace(name.begin(), name.end(), '.', '_');
+  std::replace(name.begin(), name.end(), '(', '_');
+  std::replace(name.begin(), name.end(), ')', '_');
+  return name;
+}
+
+INSTANTIATE_TEST_CASE_P(MaximumPlayerConfigurationExplorerTests,
+                        MaximumPlayerConfigurationExplorerTest,
+                        Combine(ValuesIn(GetPlayerOutputModes()),
+                                ValuesIn(GetKeySystems())),
+                        GetTestConfigName);
+
+}  // namespace
+}  // namespace nplb
+}  // namespace starboard
diff --git a/starboard/nplb/media_buffer_test.cc b/starboard/nplb/media_buffer_test.cc
index ed05240..36a11be 100644
--- a/starboard/nplb/media_buffer_test.cc
+++ b/starboard/nplb/media_buffer_test.cc
@@ -33,10 +33,14 @@
     {1920, 1080},
     {2560, 1440},
     {3840, 2160},
+    {7680, 4320},
 };
 
 constexpr int kBitsPerPixelValues[] = {
-    kSbMediaBitsPerPixelInvalid, 8, 10, 12,
+    kSbMediaBitsPerPixelInvalid,
+    8,
+    10,
+    12,
 };
 
 constexpr SbMediaVideoCodec kVideoCodecs[] = {
@@ -48,13 +52,53 @@
 };
 
 constexpr SbMediaType kMediaTypes[] = {
-    kSbMediaTypeAudio, kSbMediaTypeVideo,
+    kSbMediaTypeAudio,
+    kSbMediaTypeVideo,
 };
 
-// Minimum audio and video budgets required by the 2020 Youtube Software
+// Minimum audio and video budgets required by the 2024 Youtube Hardware
 // Requirements.
 constexpr int kMinAudioBudget = 5 * 1024 * 1024;
-constexpr int kMinVideoBudget = 30 * 1024 * 1024;
+constexpr int kMinVideoBudget1080p = 30 * 1024 * 1024;
+constexpr int kMinVideoBudget4kSdr = 50 * 1024 * 1024;
+constexpr int kMinVideoBudget4kHdr = 80 * 1024 * 1024;
+constexpr int kMinVideoBudget8k = 200 * 1024 * 1024;
+
+int GetVideoBufferBudget(SbMediaVideoCodec codec,
+                         int frame_width,
+                         bool is_hdr) {
+  if (codec != kSbMediaVideoCodecAv1 && codec != kSbMediaVideoCodecH264 &&
+      codec != kSbMediaVideoCodecVp9) {
+    return kMinVideoBudget1080p;
+  }
+
+  static const bool kSupports8k =
+      SbMediaCanPlayMimeAndKeySystem(
+          "video/mp4; codecs=\"av01.0.16M.08\"; width=7680; height=4320", "") ==
+      kSbMediaSupportTypeProbably;
+  static const bool kSupports4kHdr =
+      SbMediaCanPlayMimeAndKeySystem(
+          "video/webm; codecs=\"vp09.02.51.10.01.09.16.09.00\"; width=3840; "
+          "height=2160",
+          "") == kSbMediaSupportTypeProbably;
+  static const bool kSupports4kSdr =
+      SbMediaCanPlayMimeAndKeySystem(
+          "video/webm; codecs=\"vp9\"; width=3840; height=2160", "") ==
+      kSbMediaSupportTypeProbably;
+
+  int video_budget = kMinVideoBudget1080p;
+  if (kSupports8k && frame_width > 3840) {
+    video_budget = kMinVideoBudget8k;
+  } else if (frame_width > 1920 && frame_width <= 3840) {
+    if (kSupports4kHdr && is_hdr) {
+      video_budget = kMinVideoBudget4kHdr;
+    } else if (kSupports4kSdr && !is_hdr) {
+      video_budget = kMinVideoBudget4kSdr;
+    }
+  }
+
+  return video_budget;
+}
 
 std::vector<void*> TryToAllocateMemory(int size,
                                        int allocation_unit,
@@ -121,7 +165,7 @@
     // The test will be run more than once, it's redundant but allows us to keep
     // the test logic in one place.
     int alignment = SbMediaGetBufferAlignment();
-#else  // SB_API_VERSION >= 14
+#else   // SB_API_VERSION >= 14
     int alignment = SbMediaGetBufferAlignment(type);
 #endif  // SB_API_VERSION >= 14
     EXPECT_GE(alignment, 1);
@@ -151,7 +195,7 @@
       // The test will be run more than once, it's redundant but allows us to
       // keep the test logic in one place.
       int alignment = SbMediaGetBufferAlignment();
-#else  // SB_API_VERSION >= 14
+#else   // SB_API_VERSION >= 14
       int alignment = SbMediaGetBufferAlignment(type);
 #endif  // SB_API_VERSION >= 14
       EXPECT_EQ(alignment & (alignment - 1), 0)
@@ -161,7 +205,7 @@
       }
       int media_budget = type == SbMediaType::kSbMediaTypeAudio
                              ? kMinAudioBudget
-                             : kMinVideoBudget;
+                             : kMinVideoBudget1080p;
       std::vector<void*> media_buffer_allocated_memory =
           TryToAllocateMemory(media_budget, allocation_unit, alignment);
       allocated_ptrs.insert(allocated_ptrs.end(),
@@ -266,9 +310,11 @@
   for (auto codec : kVideoCodecs) {
     for (auto resolution : kVideoResolutions) {
       for (auto bits_per_pixel : kBitsPerPixelValues) {
+        int video_budget =
+            GetVideoBufferBudget(codec, resolution[0], bits_per_pixel > 8);
         EXPECT_GE(SbMediaGetVideoBufferBudget(codec, resolution[0],
                                               resolution[1], bits_per_pixel),
-                  kMinVideoBudget);
+                  video_budget);
       }
     }
   }
diff --git a/starboard/nplb/media_can_play_mime_and_key_system_test.cc b/starboard/nplb/media_can_play_mime_and_key_system_test.cc
index 0dc7f4d..2a5594e 100644
--- a/starboard/nplb/media_can_play_mime_and_key_system_test.cc
+++ b/starboard/nplb/media_can_play_mime_and_key_system_test.cc
@@ -53,6 +53,25 @@
   return false;
 }
 
+typedef enum DeviceType {
+  kDeviceTypeFHD,
+  kDeviceType4k,
+  kDeviceType8k,
+} DeviceType;
+
+DeviceType GetDeviceType() {
+  if (SbMediaCanPlayMimeAndKeySystem(
+          "video/mp4; codecs=\"av01.0.16M.08\"; width=7680; height=4320", "") ==
+      kSbMediaSupportTypeProbably) {
+    return kDeviceType8k;
+  } else if (SbMediaCanPlayMimeAndKeySystem(
+                 "video/webm; codecs=\"vp9\"; width=3840; height=2160", "") ==
+             kSbMediaSupportTypeProbably) {
+    return kDeviceType4k;
+  }
+  return kDeviceTypeFHD;
+}
+
 TEST(SbMediaCanPlayMimeAndKeySystem, SunnyDay) {
   // Vp9
   SbMediaCanPlayMimeAndKeySystem(
@@ -220,53 +239,66 @@
 }
 
 TEST(SbMediaCanPlayMimeAndKeySystem, MinimumSupport) {
-  // H.264 High Profile Level 4.2
-  SbMediaSupportType result = SbMediaCanPlayMimeAndKeySystem(
-      "video/mp4; codecs=\"avc1.64002a\"; width=1920; height=1080; "
-      "framerate=30; bitrate=20000000",
-      "");
-  ASSERT_EQ(result, kSbMediaSupportTypeProbably);
-
-  // H.264 Main Profile Level 4.2
-  result = SbMediaCanPlayMimeAndKeySystem(
+  std::vector<const char*> params_fhd{
       "video/mp4; codecs=\"avc1.4d002a\"; width=1920; height=1080; "
-      "framerate=30;",
-      "");
-  ASSERT_EQ(result, kSbMediaSupportTypeProbably);
-
-  result = SbMediaCanPlayMimeAndKeySystem(
-      "video/mp4; codecs=\"avc1.4d002a\"; width=0; height=0; "
-      "framerate=0; bitrate=0",
-      "");
-  ASSERT_EQ(result, kSbMediaSupportTypeProbably);
-
-  result = SbMediaCanPlayMimeAndKeySystem(
-      "video/mp4; codecs=\"avc1.4d002a\"; width=-0; height=-0; "
-      "framerate=-0; bitrate=-0",
-      "");
-  ASSERT_EQ(result, kSbMediaSupportTypeProbably);
-
-  // H.264 Main Profile Level 2.1
-  result = SbMediaCanPlayMimeAndKeySystem(
-      "video/mp4; codecs=\"avc1.4d0015\"; width=432; height=240; "
-      "framerate=15;",
-      "");
-  ASSERT_EQ(result, kSbMediaSupportTypeProbably);
-
-  // AV1 Main Profile 1080p
-  result = SbMediaCanPlayMimeAndKeySystem(
+      "framerate=30",
+      "video/mp4; codecs=\"avc1.64002a\"; width=1920; height=1080; "
+      "framerate=30",
+      "video/webm; codecs=\"vp9\"; width=1920; height=1080; framerate=30",
+      "video/webm; codecs=\"vp09.02.41.10.01.09.16.09.00\"; width=1920; "
+      "height=1080; framerate=30",
       "video/mp4; codecs=\"av01.0.09M.08\"; width=1920; height=1080; "
-      "framerate=30; bitrate=20000000",
-      "");
+      "framerate=30",
+  };
 
-  // VP9 1080p
-  result = SbMediaCanPlayMimeAndKeySystem(
-      "video/webm; codecs=\"vp9\"; width=1920; height=1080; framerate=60; "
-      "bitrate=20000000",
-      "");
+  std::vector<const char*> params_4k{
+      "video/mp4; codecs=\"avc1.4d002a\"; width=1920; height=1080; "
+      "framerate=30",
+      "video/mp4; codecs=\"avc1.64002a\"; width=1920; height=1080; "
+      "framerate=30",
+      "video/webm; codecs=\"vp9\"; width=3840; height=2160; framerate=30",
+      "video/webm; codecs=\"vp09.02.51.10.01.09.16.09.00\"; width=3840; "
+      "height=2160; framerate=30",
+      "video/mp4; codecs=\"av01.0.12M.08\"; width=3840; height=2160; "
+      "framerate=30",
+      "video/mp4; codecs=\"av01.0.13M.10.0.110.09.16.09.0\"; width=3840; "
+      "height=2160; framerate=30",
+  };
+
+  std::vector<const char*> params_8k{
+      "video/mp4; codecs=\"avc1.4d002a\"; width=1920; height=1080; "
+      "framerate=30",
+      "video/mp4; codecs=\"avc1.64002a\"; width=1920; height=1080; "
+      "framerate=30",
+      "video/webm; codecs=\"vp9\"; width=3840; height=2160; framerate=60",
+      "video/webm; codecs=\"vp09.02.51.10.01.09.16.09.00\"; width=3840; "
+      "height=2160; framerate=60",
+      "video/mp4; codecs=\"av01.0.16M.08\"; width=7680; height=4320; "
+      "framerate=30",
+      "video/mp4; codecs=\"av01.0.17M.10.0.110.09.16.09.0\"; width=7680; "
+      "height=4320; framerate=30",
+  };
+
+  DeviceType device_type = GetDeviceType();
+  std::vector<const char*> mime_params;
+  switch (device_type) {
+    case kDeviceType8k:
+      mime_params = params_8k;
+      break;
+    case kDeviceType4k:
+      mime_params = params_4k;
+      break;
+    default:
+      mime_params = params_fhd;
+  }
+
+  for (auto& param : mime_params) {
+    SbMediaSupportType support = SbMediaCanPlayMimeAndKeySystem(param, "");
+    EXPECT_TRUE(support == kSbMediaSupportTypeProbably);
+  }
 
   // AAC-LC
-  result = SbMediaCanPlayMimeAndKeySystem(
+  SbMediaSupportType result = SbMediaCanPlayMimeAndKeySystem(
       "audio/mp4; codecs=\"mp4a.40.2\"; channels=2; bitrate=256000;", "");
   ASSERT_EQ(result, kSbMediaSupportTypeProbably);
 
diff --git a/starboard/nplb/media_set_audio_write_duration_test.cc b/starboard/nplb/media_set_audio_write_duration_test.cc
index af89f56..573dd35 100644
--- a/starboard/nplb/media_set_audio_write_duration_test.cc
+++ b/starboard/nplb/media_set_audio_write_duration_test.cc
@@ -26,13 +26,11 @@
 #include "starboard/testing/fake_graphics_context_provider.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-#if SB_API_VERSION < 15
-
 namespace starboard {
 namespace nplb {
 namespace {
 
-using ::shared::starboard::player::video_dmp::VideoDmpReader;
+using shared::starboard::player::video_dmp::VideoDmpReader;
 using ::starboard::testing::FakeGraphicsContextProvider;
 using ::testing::ValuesIn;
 
@@ -42,8 +40,7 @@
 class SbMediaSetAudioWriteDurationTest
     : public ::testing::TestWithParam<const char*> {
  public:
-  SbMediaSetAudioWriteDurationTest()
-      : dmp_reader_(ResolveTestFileName(GetParam()).c_str()) {}
+  SbMediaSetAudioWriteDurationTest() : dmp_reader_(GetParam()) {}
 
   void TryToWritePendingSample() {
     {
@@ -79,11 +76,11 @@
       pending_decoder_status_ = nullopt;
     }
 
-    CallSbPlayerWriteSamples(player, kSbMediaTypeAudio, dmp_reader_.get(),
-                             index_, 1);
+    CallSbPlayerWriteSamples(player, kSbMediaTypeAudio, &dmp_reader_, index_,
+                             1);
+    last_input_timestamp_ =
+        dmp_reader_.GetPlayerSampleInfo(kSbMediaTypeAudio, index_).timestamp;
     ++index_;
-
-    last_input_timestamp_ = player_sample_info.timestamp;
   }
 
   void PlayerStatus(SbPlayer player, SbPlayerState state, int ticket) {
@@ -103,27 +100,30 @@
   }
 
   SbPlayer CreatePlayer() {
-    SbMediaAudioSampleInfo audio_sample_info = dmp_reader_.audio_sample_info();
-    SbMediaAudioCodec kAudioCodec = dmp_reader_.audio_codec();
-    SbDrmSystem kDrmSystem = kSbDrmSystemInvalid;
+    SbMediaAudioCodec audio_codec = dmp_reader_.audio_codec();
+
+    PlayerCreationParam creation_param = CreatePlayerCreationParam(
+        audio_codec, kSbMediaVideoCodecNone, kSbPlayerOutputModeInvalid);
+
+    SbPlayerCreationParam param = {};
+    creation_param.ConvertTo(&param);
+
+    creation_param.output_mode = SbPlayerGetPreferredOutputMode(&param);
+    EXPECT_NE(creation_param.output_mode, kSbPlayerOutputModeInvalid);
+
+    SbPlayer player = CallSbPlayerCreate(
+        fake_graphics_context_provider_.window(), kSbMediaVideoCodecNone,
+        audio_codec, kSbDrmSystemInvalid, &dmp_reader_.audio_stream_info(), "",
+        DummyDeallocateSampleFunc, DecoderStatusFunc, PlayerStatusFunc,
+        DummyErrorFunc, this /* context */, creation_param.output_mode,
+        fake_graphics_context_provider_.decoder_target_provider());
+
+    EXPECT_TRUE(SbPlayerIsValid(player));
 
     last_input_timestamp_ =
         dmp_reader_.GetPlayerSampleInfo(kSbMediaTypeAudio, 0).timestamp;
     first_input_timestamp_ = last_input_timestamp_;
 
-    SbPlayerCreationParam creation_param = CreatePlayerCreationParam(
-        audio_sample_info.codec, kSbMediaVideoCodecNone,
-        SbPlayerGetPreferredOutputMode(&creation_param));
-    creation_param.audio_sample_info = audio_sample_info;
-    EXPECT_NE(creation_param.output_mode, kSbPlayerOutputModeInvalid);
-
-    SbPlayer player = SbPlayerCreate(
-        fake_graphics_context_provider_.window(), &creation_param,
-        DummyDeallocateSampleFunc, DecoderStatusFunc, PlayerStatusFunc,
-        DummyErrorFunc, this /* context */,
-        fake_graphics_context_provider_.decoder_target_provider());
-
-    EXPECT_TRUE(SbPlayerIsValid(player));
     return player;
   }
 
@@ -183,7 +183,9 @@
   ASSERT_NE(dmp_reader_.audio_codec(), kSbMediaAudioCodecNone);
   ASSERT_GT(dmp_reader_.number_of_audio_buffers(), 0);
 
+#if SB_API_VERSION < 15
   SbMediaSetAudioWriteDuration(kDuration);
+#endif  // SB_API_VERSION < 15
 
   SbPlayer player = CreatePlayer();
   WaitForPlayerState(kSbPlayerStateInitialized);
@@ -224,7 +226,9 @@
   ASSERT_NE(dmp_reader_.audio_codec(), kSbMediaAudioCodecNone);
   ASSERT_GT(dmp_reader_.number_of_audio_buffers(), 0);
 
+#if SB_API_VERSION < 15
   SbMediaSetAudioWriteDuration(kDuration);
+#endif  // SB_API_VERSION < 15
 
   // This directly impacts the runtime of the test.
   total_duration_ = 15 * kSbTimeSecond;
@@ -277,16 +281,14 @@
   }
 
   for (auto filename : kFilenames) {
-    VideoDmpReader dmp_reader(ResolveTestFileName(filename).c_str());
+    VideoDmpReader dmp_reader(filename, VideoDmpReader::kEnableReadOnDemand);
     SB_DCHECK(dmp_reader.number_of_audio_buffers() > 0);
-
-    const SbMediaAudioSampleInfo* audio_sample_info =
-        &dmp_reader.audio_sample_info();
-    if (SbMediaIsAudioSupported(dmp_reader.audio_codec(), nullptr,
-                                dmp_reader.audio_bitrate())) {
+    if (SbMediaCanPlayMimeAndKeySystem(dmp_reader.audio_mime_type().c_str(),
+                                       "")) {
       test_params.push_back(filename);
     }
   }
+
   SB_DCHECK(!test_params.empty());
   return test_params;
 }
@@ -297,5 +299,3 @@
 }  // namespace
 }  // namespace nplb
 }  // namespace starboard
-
-#endif  // SB_API_VERSION < 15
diff --git a/starboard/nplb/multiple_player_test.cc b/starboard/nplb/multiple_player_test.cc
new file mode 100644
index 0000000..b2c8a04
--- /dev/null
+++ b/starboard/nplb/multiple_player_test.cc
@@ -0,0 +1,236 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <list>
+#include <string>
+
+#include "starboard/common/string.h"
+#include "starboard/nplb/maximum_player_configuration_explorer.h"
+#include "starboard/nplb/player_test_fixture.h"
+#include "starboard/nplb/player_test_util.h"
+#include "starboard/nplb/thread_helpers.h"
+#include "starboard/testing/fake_graphics_context_provider.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace starboard {
+namespace nplb {
+namespace {
+
+using shared::starboard::player::video_dmp::VideoDmpReader;
+using ::starboard::testing::FakeGraphicsContextProvider;
+using ::testing::ValuesIn;
+
+typedef SbPlayerTestFixture::GroupedSamples GroupedSamples;
+typedef std::function<void(const SbPlayerTestConfig&,
+                           FakeGraphicsContextProvider*)>
+    MultiplePlayerTestFunctor;
+
+class PlayerThread : public AbstractTestThread {
+ public:
+  explicit PlayerThread(const std::function<void()>& functor)
+      : functor_(functor) {}
+
+  void Run() override { functor_(); }
+
+ private:
+  std::function<void()> functor_;
+};
+
+class MultiplePlayerTest
+    : public ::testing::TestWithParam<SbPlayerMultiplePlayerTestConfig> {
+ protected:
+  void RunTest(const MultiplePlayerTestFunctor& functor);
+  FakeGraphicsContextProvider fake_graphics_context_provider_;
+};
+
+void MultiplePlayerTest::RunTest(const MultiplePlayerTestFunctor& functor) {
+  const SbPlayerMultiplePlayerTestConfig& multiplayer_test_config = GetParam();
+  std::list<PlayerThread> player_threads;
+  for (const SbPlayerTestConfig& player_config : multiplayer_test_config) {
+    player_threads.emplace_back(
+        std::bind(functor, player_config, &fake_graphics_context_provider_));
+  }
+  for (auto& player_thread : player_threads) {
+    player_thread.Start();
+  }
+  for (auto& player_thread : player_threads) {
+    player_thread.Join();
+  }
+}
+
+void NoInput(const SbPlayerTestConfig& player_config,
+             FakeGraphicsContextProvider* fake_graphics_context_provider) {
+  SbPlayerTestFixture player_fixture(player_config,
+                                     fake_graphics_context_provider);
+  if (::testing::Test::HasFatalFailure()) {
+    return;
+  }
+
+  GroupedSamples samples;
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoEOS();
+  }
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+}
+
+TEST_P(MultiplePlayerTest, NoInput) {
+  RunTest(NoInput);
+}
+
+void WriteSamples(const SbPlayerTestConfig& player_config,
+                  FakeGraphicsContextProvider* fake_graphics_context_provider) {
+  SbPlayerTestFixture player_fixture(player_config,
+                                     fake_graphics_context_provider);
+  if (::testing::Test::HasFatalFailure()) {
+    return;
+  }
+
+  const SbTime kDurationToPlay = kSbTimeMillisecond * 200;
+
+  GroupedSamples samples;
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioSamples(
+        0, player_fixture.ConvertDurationToAudioBufferCount(kDurationToPlay));
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(
+        0, player_fixture.ConvertDurationToVideoBufferCount(kDurationToPlay));
+    samples.AddVideoEOS();
+  }
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+}
+
+TEST_P(MultiplePlayerTest, WriteSamples) {
+  RunTest(WriteSamples);
+}
+
+std::string GetMultipleSbPlayerTestConfigName(
+    ::testing::TestParamInfo<SbPlayerMultiplePlayerTestConfig> info) {
+  const SbPlayerMultiplePlayerTestConfig& multiplayer_test_config = info.param;
+
+  SB_DCHECK(multiplayer_test_config.size() > 0);
+  const SbPlayerOutputMode output_mode = multiplayer_test_config[0].output_mode;
+  const char* key_system = multiplayer_test_config[0].key_system;
+
+  std::string name;
+  for (int i = 0; i < multiplayer_test_config.size(); i++) {
+    const SbPlayerTestConfig& config = multiplayer_test_config[i];
+    const char* audio_filename = config.audio_filename;
+    const char* video_filename = config.video_filename;
+
+    if (i > 0) {
+      name += "_";
+    }
+    name += FormatString(
+        "audio%d_%s_video%d_%s", i,
+        audio_filename && strlen(audio_filename) > 0 ? audio_filename : "null",
+        i,
+        video_filename && strlen(video_filename) > 0 ? video_filename : "null");
+  }
+
+  name += FormatString("_output_%s_key_system_%s",
+                       output_mode == kSbPlayerOutputModeDecodeToTexture
+                           ? "decode_to_texture"
+                           : "punch_out",
+                       strlen(key_system) > 0 ? key_system : "null");
+  std::replace(name.begin(), name.end(), '.', '_');
+  std::replace(name.begin(), name.end(), '(', '_');
+  std::replace(name.begin(), name.end(), ')', '_');
+  return name;
+}
+
+std::vector<SbPlayerMultiplePlayerTestConfig> GetMultiplePlayerTestConfigs() {
+  const int kMaxPlayerInstancesPerConfig = 3;
+  const int kMaxTotalPlayerInstances = 5;
+
+  const std::vector<const char*>& audio_test_files = GetAudioTestFiles();
+  const std::vector<const char*>& video_test_files = GetVideoTestFiles();
+  const std::vector<SbPlayerOutputMode>& output_modes = GetPlayerOutputModes();
+  const std::vector<const char*>& key_systems = GetKeySystems();
+
+  FakeGraphicsContextProvider fake_graphics_context_provider;
+  std::vector<SbPlayerMultiplePlayerTestConfig> configs_to_return;
+
+  for (auto key_system : key_systems) {
+    std::vector<SbPlayerTestConfig> supported_configs;
+    for (auto video_filename : video_test_files) {
+      VideoDmpReader dmp_reader(video_filename,
+                                VideoDmpReader::kEnableReadOnDemand);
+      SB_DCHECK(dmp_reader.number_of_video_buffers() > 0);
+      if (SbMediaCanPlayMimeAndKeySystem(dmp_reader.video_mime_type().c_str(),
+                                         key_system)) {
+        supported_configs.push_back(
+            {nullptr, video_filename, kSbPlayerOutputModeInvalid, key_system});
+      }
+    }
+
+    if (supported_configs.empty()) {
+      continue;
+    }
+
+    std::vector<const char*> supported_audio_files;
+    for (auto audio_filename : audio_test_files) {
+      VideoDmpReader dmp_reader(audio_filename,
+                                VideoDmpReader::kEnableReadOnDemand);
+      SB_DCHECK(dmp_reader.number_of_audio_buffers() > 0);
+      if (SbMediaCanPlayMimeAndKeySystem(dmp_reader.audio_mime_type().c_str(),
+                                         key_system)) {
+        supported_audio_files.push_back(audio_filename);
+      }
+    }
+
+    // TODO: use SbPlayerGetPreferredOutputMode() to choose output mode.
+    for (auto output_mode : output_modes) {
+      for (auto& config : supported_configs) {
+        config.output_mode = output_mode;
+      }
+
+      MaximumPlayerConfigurationExplorer explorer(
+          supported_configs, kMaxPlayerInstancesPerConfig,
+          kMaxTotalPlayerInstances, &fake_graphics_context_provider);
+      std::vector<SbPlayerMultiplePlayerTestConfig> explorer_output =
+          explorer.CalculateMaxTestConfigs();
+
+      // Add audio codec to configs using round robin algorithm.
+      for (auto& multi_player_test_config : explorer_output) {
+        int audio_file_index = 0;
+        for (auto& config : multi_player_test_config) {
+          config.audio_filename = supported_audio_files[audio_file_index];
+          audio_file_index =
+              (audio_file_index + 1) % supported_audio_files.size();
+        }
+      }
+
+      configs_to_return.insert(configs_to_return.end(), explorer_output.begin(),
+                               explorer_output.end());
+    }
+  }
+  return configs_to_return;
+}
+
+INSTANTIATE_TEST_CASE_P(MultiplePlayerTests,
+                        MultiplePlayerTest,
+                        ValuesIn(GetMultiplePlayerTestConfigs()),
+                        GetMultipleSbPlayerTestConfigName);
+
+}  // namespace
+}  // namespace nplb
+}  // namespace starboard
diff --git a/starboard/nplb/nplb_evergreen_compat_tests/BUILD.gn b/starboard/nplb/nplb_evergreen_compat_tests/BUILD.gn
index a80482b..6978098 100644
--- a/starboard/nplb/nplb_evergreen_compat_tests/BUILD.gn
+++ b/starboard/nplb/nplb_evergreen_compat_tests/BUILD.gn
@@ -29,6 +29,7 @@
   public_deps = [
     "//starboard",
     "//testing/gmock",
+    "//testing/gtest",
   ]
 
   data_deps = [
diff --git a/starboard/nplb/player_create_test.cc b/starboard/nplb/player_create_test.cc
index c964bdc..9271354 100644
--- a/starboard/nplb/player_create_test.cc
+++ b/starboard/nplb/player_create_test.cc
@@ -12,14 +12,20 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+#include <string>
 #include <vector>
 
+#include "starboard/common/condition_variable.h"
+#include "starboard/common/media.h"
+#include "starboard/common/mutex.h"
+#include "starboard/common/optional.h"
 #include "starboard/configuration_constants.h"
 #include "starboard/decode_target.h"
 #include "starboard/nplb/player_creation_param_helpers.h"
 #include "starboard/nplb/player_test_util.h"
 #include "starboard/player.h"
 #include "starboard/testing/fake_graphics_context_provider.h"
+#include "starboard/time.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace starboard {
@@ -29,12 +35,16 @@
 using ::starboard::testing::FakeGraphicsContextProvider;
 using ::testing::Values;
 
-class SbPlayerTest : public ::testing::TestWithParam<SbPlayerOutputMode> {
- protected:
-  SbPlayerTest() : output_mode_(GetParam()) {}
+constexpr SbPlayerOutputMode kOutputModes[] = {
+    kSbPlayerOutputModeDecodeToTexture, kSbPlayerOutputModePunchOut};
 
-  void GetCurrentFrameIfSupported(SbPlayer player) {
-    if (output_mode_ != kSbPlayerOutputModeDecodeToTexture) {
+class SbPlayerTest : public ::testing::Test {
+ protected:
+  SbPlayerTest() {}
+
+  void GetCurrentFrameIfSupported(SbPlayer player,
+                                  SbPlayerOutputMode output_mode) {
+    if (output_mode != kSbPlayerOutputModeDecodeToTexture) {
       return;
     }
 #if SB_HAS(GLES2)
@@ -48,137 +58,266 @@
 #endif  // SB_HAS(GLES2)
   }
 
+  static void PlayerStatusFunc(SbPlayer player,
+                               void* context,
+                               SbPlayerState state,
+                               int ticket) {
+    ASSERT_NE(context, nullptr);
+    (static_cast<SbPlayerTest*>(context))->OnPlayerStatus(state);
+  }
+
+  static void PlayerErrorFunc(SbPlayer player,
+                              void* context,
+                              SbPlayerError error,
+                              const char* message) {
+    ASSERT_NE(context, nullptr);
+    (static_cast<SbPlayerTest*>(context))->OnPlayerError(error);
+  }
+
+  void OnPlayerStatus(SbPlayerState state) {
+    ScopedLock scoped_lock(mutex_);
+    player_state_ = state;
+    condition_variable_.Signal();
+  }
+
+  void OnPlayerError(SbPlayerError error) {
+    ScopedLock scoped_lock(mutex_);
+    player_error_ = error;
+    condition_variable_.Signal();
+  }
+
+  void ClearPlayerStateAndError() {
+    ScopedLock scoped_lock(mutex_);
+    player_state_ = nullopt;
+    player_error_ = nullopt;
+  }
+
+  void WaitForPlayerInitializedOrError(bool* error_occurred) {
+    const SbTime kWaitTimeout = kSbTimeSecond * 5;
+
+    SB_DCHECK(error_occurred);
+    *error_occurred = false;
+
+    const SbTimeMonotonic wait_end = SbTimeGetMonotonicNow() + kWaitTimeout;
+
+    for (;;) {
+      ScopedLock scoped_lock(mutex_);
+
+      if (player_error_.has_engaged()) {
+        *error_occurred = true;
+        return;
+      }
+
+      if (player_state_.has_engaged()) {
+        *error_occurred = player_state_.value() == kSbPlayerStateInitialized;
+        return;
+      }
+
+      auto now = SbTimeGetMonotonicNow();
+      if (now > wait_end) {
+        break;
+      }
+      condition_variable_.WaitTimed(wait_end - now);
+    }
+
+    SB_LOG(INFO) << "WaitForPlayerInitializedOrError() timed out.";
+    *error_occurred = true;  // Timeout is an error
+  }
+
   FakeGraphicsContextProvider fake_graphics_context_provider_;
 
-  SbPlayerOutputMode output_mode_;
+  Mutex mutex_;
+  ConditionVariable condition_variable_{mutex_};
+  optional<SbPlayerState> player_state_;
+  optional<SbPlayerError> player_error_;
 };
 
-TEST_P(SbPlayerTest, SunnyDay) {
+TEST_F(SbPlayerTest, SunnyDay) {
+  bool at_least_one_created = false;
   auto audio_stream_info = CreateAudioStreamInfo(kSbMediaAudioCodecAac);
 
-  if (!IsOutputModeSupported(output_mode_, kSbMediaAudioCodecAac,
-                             kSbMediaVideoCodecH264)) {
-    return;
+  for (auto output_mode : kOutputModes) {
+    if (!IsOutputModeSupported(output_mode, kSbMediaAudioCodecAac,
+                               kSbMediaVideoCodecH264)) {
+      return;
+    }
+
+    SbPlayer player = CallSbPlayerCreate(
+        fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
+        kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
+        "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
+        DummyDecoderStatusFunc, PlayerStatusFunc, PlayerErrorFunc, this,
+        output_mode, fake_graphics_context_provider_.decoder_target_provider());
+
+    if (SbPlayerIsValid(player)) {
+      bool error_occurred = false;
+      WaitForPlayerInitializedOrError(&error_occurred);
+      GetCurrentFrameIfSupported(player, output_mode);
+      SbPlayerDestroy(player);
+
+      at_least_one_created = error_occurred;
+    }
+
+    ClearPlayerStateAndError();
   }
 
-  SbPlayer player = CallSbPlayerCreate(
-      fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
-      kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
-      "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
-      DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
-      NULL /* context */, output_mode_,
-      fake_graphics_context_provider_.decoder_target_provider());
-  EXPECT_TRUE(SbPlayerIsValid(player));
-
-  GetCurrentFrameIfSupported(player);
-
-  SbPlayerDestroy(player);
+  ASSERT_TRUE(at_least_one_created);
 }
 
-TEST_P(SbPlayerTest, NullCallbacks) {
+TEST_F(SbPlayerTest, MaxVideoCapabilities) {
+  const char* kMaxVideoCapabilities[] = {
+      "width=432; height=240;",
+      "width=432; height=240; framerate=15",
+      "width=432; height=240; framerate=30",
+      "width=640; height=480",
+      "width=640; height=480; framerate=30",
+      "width=640; height=480; framerate=60",
+      "width=1280; height=720",
+  };
+
   auto audio_stream_info = CreateAudioStreamInfo(kSbMediaAudioCodecAac);
 
-  if (!IsOutputModeSupported(output_mode_, kSbMediaAudioCodecAac,
-                             kSbMediaVideoCodecH264)) {
-    return;
-  }
+  for (auto max_video_capabilities : kMaxVideoCapabilities) {
+    bool at_least_one_created = false;
+    for (auto output_mode : kOutputModes) {
+      SbPlayer player = CallSbPlayerCreate(
+          fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
+          kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
+          max_video_capabilities, DummyDeallocateSampleFunc,
+          DummyDecoderStatusFunc, PlayerStatusFunc, PlayerErrorFunc, this,
+          output_mode,
+          fake_graphics_context_provider_.decoder_target_provider());
 
-  {
+      if (SbPlayerIsValid(player)) {
+        bool error_occurred = false;
+        WaitForPlayerInitializedOrError(&error_occurred);
+        GetCurrentFrameIfSupported(player, output_mode);
+        SbPlayerDestroy(player);
+
+        at_least_one_created = error_occurred;
+      }
+
+      ClearPlayerStateAndError();
+    }
+
+    ASSERT_TRUE(at_least_one_created) << max_video_capabilities;
+  }
+}
+
+TEST_F(SbPlayerTest, NullCallbacks) {
+  auto audio_stream_info = CreateAudioStreamInfo(kSbMediaAudioCodecAac);
+
+  for (auto output_mode : kOutputModes) {
+    if (!IsOutputModeSupported(output_mode, kSbMediaAudioCodecAac,
+                               kSbMediaVideoCodecH264)) {
+      return;
+    }
+
+    {
+      SbPlayer player = CallSbPlayerCreate(
+          fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
+          kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
+          "" /* max_video_capabilities */, NULL /* deallocate_sample_func */,
+          DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
+          NULL /* context */, output_mode,
+          fake_graphics_context_provider_.decoder_target_provider());
+      EXPECT_FALSE(SbPlayerIsValid(player));
+
+      SbPlayerDestroy(player);
+    }
+
+    {
+      SbPlayer player = CallSbPlayerCreate(
+          fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
+          kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
+          "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
+          NULL /* decoder_status_func */, DummyPlayerStatusFunc, DummyErrorFunc,
+          NULL /* context */, output_mode,
+          fake_graphics_context_provider_.decoder_target_provider());
+      EXPECT_FALSE(SbPlayerIsValid(player));
+
+      SbPlayerDestroy(player);
+    }
+
+    {
+      SbPlayer player = CallSbPlayerCreate(
+          fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
+          kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
+          "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
+          DummyDecoderStatusFunc, NULL /*status_func */, DummyErrorFunc,
+          NULL /* context */, output_mode,
+          fake_graphics_context_provider_.decoder_target_provider());
+      EXPECT_FALSE(SbPlayerIsValid(player));
+
+      SbPlayerDestroy(player);
+    }
+
+    {
+      SbPlayer player = CallSbPlayerCreate(
+          fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
+          kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info, "",
+          DummyDeallocateSampleFunc, DummyDecoderStatusFunc,
+          DummyPlayerStatusFunc, NULL /* error_func */, NULL /* context */,
+          output_mode,
+          fake_graphics_context_provider_.decoder_target_provider());
+      EXPECT_FALSE(SbPlayerIsValid(player));
+
+      SbPlayerDestroy(player);
+    }
+  }
+}
+
+TEST_F(SbPlayerTest, Audioless) {
+  for (auto output_mode : kOutputModes) {
+    if (!IsOutputModeSupported(output_mode, kSbMediaAudioCodecNone,
+                               kSbMediaVideoCodecH264)) {
+      return;
+    }
+
     SbPlayer player = CallSbPlayerCreate(
         fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
-        kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
-        "" /* max_video_capabilities */, NULL /* deallocate_sample_func */,
-        DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
-        NULL /* context */, output_mode_,
-        fake_graphics_context_provider_.decoder_target_provider());
-    EXPECT_FALSE(SbPlayerIsValid(player));
-
-    SbPlayerDestroy(player);
-  }
-
-  {
-    SbPlayer player = CallSbPlayerCreate(
-        fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
-        kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
-        "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
-        NULL /* decoder_status_func */, DummyPlayerStatusFunc, DummyErrorFunc,
-        NULL /* context */, output_mode_,
-        fake_graphics_context_provider_.decoder_target_provider());
-    EXPECT_FALSE(SbPlayerIsValid(player));
-
-    SbPlayerDestroy(player);
-  }
-
-  {
-    SbPlayer player = CallSbPlayerCreate(
-        fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
-        kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
-        "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
-        DummyDecoderStatusFunc, NULL /*status_func */, DummyErrorFunc,
-        NULL /* context */, output_mode_,
-        fake_graphics_context_provider_.decoder_target_provider());
-    EXPECT_FALSE(SbPlayerIsValid(player));
-
-    SbPlayerDestroy(player);
-  }
-
-  {
-    SbPlayer player = CallSbPlayerCreate(
-        fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
-        kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info, "",
+        kSbMediaAudioCodecNone, kSbDrmSystemInvalid,
+        NULL /* audio_stream_info */, "" /* max_video_capabilities */,
         DummyDeallocateSampleFunc, DummyDecoderStatusFunc,
-        DummyPlayerStatusFunc, NULL /* error_func */, NULL /* context */,
-        output_mode_,
+        DummyPlayerStatusFunc, DummyErrorFunc, NULL /* context */, output_mode,
         fake_graphics_context_provider_.decoder_target_provider());
-    EXPECT_FALSE(SbPlayerIsValid(player));
+    ASSERT_TRUE(SbPlayerIsValid(player));
+
+    // TODO: Validate player state or error.
+
+    GetCurrentFrameIfSupported(player, output_mode);
 
     SbPlayerDestroy(player);
   }
 }
 
-TEST_P(SbPlayerTest, Audioless) {
-  if (!IsOutputModeSupported(output_mode_, kSbMediaAudioCodecNone,
-                             kSbMediaVideoCodecH264)) {
-    return;
-  }
-
-  SbPlayer player = CallSbPlayerCreate(
-      fake_graphics_context_provider_.window(), kSbMediaVideoCodecH264,
-      kSbMediaAudioCodecNone, kSbDrmSystemInvalid, NULL /* audio_stream_info */,
-      "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
-      DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
-      NULL /* context */, output_mode_,
-      fake_graphics_context_provider_.decoder_target_provider());
-  EXPECT_TRUE(SbPlayerIsValid(player));
-
-  GetCurrentFrameIfSupported(player);
-
-  SbPlayerDestroy(player);
-}
-
-TEST_P(SbPlayerTest, AudioOnly) {
+TEST_F(SbPlayerTest, AudioOnly) {
   auto audio_stream_info = CreateAudioStreamInfo(kSbMediaAudioCodecAac);
 
-  if (!IsOutputModeSupported(output_mode_, kSbMediaAudioCodecAac,
-                             kSbMediaVideoCodecH264)) {
-    return;
+  for (auto output_mode : kOutputModes) {
+    if (!IsOutputModeSupported(output_mode, kSbMediaAudioCodecAac,
+                               kSbMediaVideoCodecH264)) {
+      return;
+    }
+
+    SbPlayer player = CallSbPlayerCreate(
+        fake_graphics_context_provider_.window(), kSbMediaVideoCodecNone,
+        kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
+        "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
+        DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
+        NULL /* context */, output_mode,
+        fake_graphics_context_provider_.decoder_target_provider());
+    ASSERT_TRUE(SbPlayerIsValid(player));
+
+    // TODO: Validate player state or error.
+
+    GetCurrentFrameIfSupported(player, output_mode);
+
+    SbPlayerDestroy(player);
   }
-
-  SbPlayer player = CallSbPlayerCreate(
-      fake_graphics_context_provider_.window(), kSbMediaVideoCodecNone,
-      kSbMediaAudioCodecAac, kSbDrmSystemInvalid, &audio_stream_info,
-      "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
-      DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
-      NULL /* context */, output_mode_,
-      fake_graphics_context_provider_.decoder_target_provider());
-  EXPECT_TRUE(SbPlayerIsValid(player));
-
-  GetCurrentFrameIfSupported(player);
-
-  SbPlayerDestroy(player);
 }
 
-TEST_P(SbPlayerTest, MultiPlayer) {
+TEST_F(SbPlayerTest, MultiPlayer) {
   auto audio_stream_info = CreateAudioStreamInfo(kSbMediaAudioCodecAac);
   SbDrmSystem kDrmSystem = kSbDrmSystemInvalid;
 
@@ -252,24 +391,40 @@
       break;
   }
 
-  const int kMaxPlayersPerConfig = 16;
+  const int kMaxPlayersPerConfig = 5;
   std::vector<SbPlayer> created_players;
+  int number_of_create_attempts = 0;
   int number_of_players = 0;
+
   for (int i = 0; i < kMaxPlayersPerConfig; ++i) {
     for (int j = 0; j < SB_ARRAY_SIZE_INT(kOutputModes); ++j) {
       for (int k = 0; k < SB_ARRAY_SIZE_INT(kAudioCodecs); ++k) {
         for (int l = 0; l < SB_ARRAY_SIZE_INT(kVideoCodecs); ++l) {
+          ++number_of_create_attempts;
+          SB_LOG(INFO) << "Attempt to create SbPlayer for "
+                       << number_of_create_attempts << " times, with "
+                       << created_players.size()
+                       << " player created.\n Now creating player for "
+                       << GetMediaAudioCodecName(kAudioCodecs[k]) << " and "
+                       << GetMediaVideoCodecName(kVideoCodecs[l]);
+
           audio_stream_info.codec = kAudioCodecs[k];
           created_players.push_back(CallSbPlayerCreate(
               fake_graphics_context_provider_.window(), kVideoCodecs[l],
               kAudioCodecs[k], kSbDrmSystemInvalid, &audio_stream_info,
               "" /* max_video_capabilities */, DummyDeallocateSampleFunc,
-              DummyDecoderStatusFunc, DummyPlayerStatusFunc, DummyErrorFunc,
-              NULL /* context */, kOutputModes[j],
+              DummyDecoderStatusFunc, PlayerStatusFunc, PlayerErrorFunc, this,
+              kOutputModes[j],
               fake_graphics_context_provider_.decoder_target_provider()));
-          if (!SbPlayerIsValid(created_players.back())) {
+
+          if (SbPlayerIsValid(created_players.back())) {
+            bool error_occurred = false;
+            WaitForPlayerInitializedOrError(&error_occurred);
+          } else {
             created_players.pop_back();
           }
+
+          ClearPlayerStateAndError();
         }
       }
     }
@@ -284,11 +439,6 @@
   }
 }
 
-INSTANTIATE_TEST_CASE_P(SbPlayerTests,
-                        SbPlayerTest,
-                        Values(kSbPlayerOutputModeDecodeToTexture,
-                               kSbPlayerOutputModePunchOut));
-
 }  // namespace
 }  // namespace nplb
 }  // namespace starboard
diff --git a/starboard/nplb/player_creation_param_helpers.cc b/starboard/nplb/player_creation_param_helpers.cc
index 959a071..d20a635 100644
--- a/starboard/nplb/player_creation_param_helpers.cc
+++ b/starboard/nplb/player_creation_param_helpers.cc
@@ -15,6 +15,7 @@
 #include "starboard/nplb/player_creation_param_helpers.h"
 
 #include "starboard/common/log.h"
+#include "starboard/shared/starboard/player/video_dmp_reader.h"
 
 namespace starboard {
 namespace nplb {
@@ -22,6 +23,7 @@
 
 using shared::starboard::media::AudioStreamInfo;
 using shared::starboard::media::VideoStreamInfo;
+using shared::starboard::player::video_dmp::VideoDmpReader;
 
 }  // namespace
 
@@ -134,5 +136,29 @@
   return creation_param;
 }
 
+PlayerCreationParam CreatePlayerCreationParam(
+    const SbPlayerTestConfig& config) {
+  PlayerCreationParam creation_param;
+  if (config.audio_filename) {
+    VideoDmpReader dmp_reader(config.audio_filename);
+    creation_param.audio_stream_info = dmp_reader.audio_stream_info();
+  }
+  if (config.video_filename) {
+    VideoDmpReader dmp_reader(config.video_filename);
+    creation_param.video_stream_info = dmp_reader.video_stream_info();
+    creation_param.video_stream_info.max_video_capabilities =
+        config.max_video_capabilities;
+  }
+  creation_param.output_mode = config.output_mode;
+  return creation_param;
+}
+
+SbPlayerOutputMode GetPreferredOutputMode(
+    const PlayerCreationParam& creation_param) {
+  SbPlayerCreationParam param = {};
+  creation_param.ConvertTo(&param);
+  return SbPlayerGetPreferredOutputMode(&param);
+}
+
 }  // namespace nplb
 }  // namespace starboard
diff --git a/starboard/nplb/player_creation_param_helpers.h b/starboard/nplb/player_creation_param_helpers.h
index 036b404..3c607dc 100644
--- a/starboard/nplb/player_creation_param_helpers.h
+++ b/starboard/nplb/player_creation_param_helpers.h
@@ -20,6 +20,7 @@
 #include "starboard/common/log.h"
 #include "starboard/drm.h"
 #include "starboard/media.h"
+#include "starboard/nplb/player_test_util.h"
 #include "starboard/player.h"
 #include "starboard/shared/starboard/media/media_util.h"
 
@@ -69,6 +70,11 @@
                                               SbMediaVideoCodec video_codec,
                                               SbPlayerOutputMode output_mode);
 
+PlayerCreationParam CreatePlayerCreationParam(const SbPlayerTestConfig& config);
+
+SbPlayerOutputMode GetPreferredOutputMode(
+    const PlayerCreationParam& creation_param);
+
 }  // namespace nplb
 }  // namespace starboard
 
diff --git a/starboard/nplb/player_get_audio_configuration_test.cc b/starboard/nplb/player_get_audio_configuration_test.cc
new file mode 100644
index 0000000..d89fd62
--- /dev/null
+++ b/starboard/nplb/player_get_audio_configuration_test.cc
@@ -0,0 +1,279 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <vector>
+
+#include "starboard/nplb/player_test_fixture.h"
+#include "starboard/string.h"
+#include "starboard/testing/fake_graphics_context_provider.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+#if SB_API_VERSION >= 15
+
+bool operator==(const SbMediaAudioConfiguration& left,
+                const SbMediaAudioConfiguration& right) {
+  return memcmp(&left, &right, sizeof(SbMediaAudioConfiguration)) == 0;
+}
+
+namespace starboard {
+namespace nplb {
+namespace {
+
+using ::starboard::testing::FakeGraphicsContextProvider;
+using ::testing::ValuesIn;
+
+typedef SbPlayerTestFixture::GroupedSamples GroupedSamples;
+
+class SbPlayerGetAudioConfigurationTest
+    : public ::testing::TestWithParam<SbPlayerTestConfig> {
+ public:
+  void ReadAudioConfigurations(
+      const SbPlayerTestFixture& player_fixture,
+      std::vector<SbMediaAudioConfiguration>* configurations) const {
+    SB_CHECK(configurations->empty());
+
+    // We try to read audio configuration with a too large index here, to make
+    // sure SbPlayerGetAudioConfiguration() not always return true and avoid
+    // infinite for loop below.
+    const int kInvalidIndex = 9999;
+    SbMediaAudioConfiguration configuration;
+    ASSERT_FALSE(SbPlayerGetAudioConfiguration(player_fixture.GetPlayer(),
+                                               kInvalidIndex, &configuration));
+
+    for (int index = 0;; index++) {
+      if (SbPlayerGetAudioConfiguration(player_fixture.GetPlayer(), index,
+                                        &configuration)) {
+        ASSERT_NO_FATAL_FAILURE(AssertConfigurationIsValid(configuration));
+        configurations->push_back(configuration);
+      } else {
+        return;
+      }
+    }
+  }
+
+  void AssertConfigurationIsValid(
+      const SbMediaAudioConfiguration& configuration) const {
+    bool connector_is_valid = false;
+    bool coding_type_is_valid = false;
+
+    switch (configuration.connector) {
+      case kSbMediaAudioConnectorUnknown:
+      case kSbMediaAudioConnectorAnalog:
+      case kSbMediaAudioConnectorBluetooth:
+      case kSbMediaAudioConnectorBuiltIn:
+      case kSbMediaAudioConnectorHdmi:
+      case kSbMediaAudioConnectorRemoteWired:
+      case kSbMediaAudioConnectorRemoteWireless:
+      case kSbMediaAudioConnectorRemoteOther:
+      case kSbMediaAudioConnectorSpdif:
+      case kSbMediaAudioConnectorUsb:
+        connector_is_valid = true;
+        break;
+    }
+    switch (configuration.coding_type) {
+      case kSbMediaAudioCodingTypeNone:
+      case kSbMediaAudioCodingTypeAac:
+      case kSbMediaAudioCodingTypeAc3:
+      case kSbMediaAudioCodingTypeAtrac:
+      case kSbMediaAudioCodingTypeBitstream:
+      case kSbMediaAudioCodingTypeDolbyDigitalPlus:
+      case kSbMediaAudioCodingTypeDts:
+      case kSbMediaAudioCodingTypeMpeg1:
+      case kSbMediaAudioCodingTypeMpeg2:
+      case kSbMediaAudioCodingTypeMpeg3:
+      case kSbMediaAudioCodingTypePcm:
+        coding_type_is_valid = true;
+        break;
+    }
+    ASSERT_TRUE(connector_is_valid);
+    ASSERT_TRUE(coding_type_is_valid);
+    ASSERT_GE(configuration.number_of_channels, 0);
+  }
+
+  FakeGraphicsContextProvider fake_graphics_context_provider_;
+};
+
+TEST_P(SbPlayerGetAudioConfigurationTest, SunnyDay) {
+  const int kSamplesToWrite = 8;
+
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+
+  // It's ok to not return any configuration at this point.
+  std::vector<SbMediaAudioConfiguration> initial_configs;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &initial_configs));
+
+  GroupedSamples samples;
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioSamples(0, kSamplesToWrite);
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(0, kSamplesToWrite);
+    samples.AddVideoEOS();
+  }
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting());
+
+  // The audio configurations must be available after `kSbPlayerStatePresenting`
+  // has been received.
+  std::vector<SbMediaAudioConfiguration> configs_after_presenting;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_presenting));
+
+  if (player_fixture.HasAudio()) {
+    ASSERT_FALSE(configs_after_presenting.empty());
+  }
+
+  // Once at least one audio configurations are returned, the return values
+  // shouldn't change during the life time of |player|.
+  if (!initial_configs.empty()) {
+    ASSERT_EQ(initial_configs, configs_after_presenting);
+  }
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+
+  std::vector<SbMediaAudioConfiguration> configs_after_end;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_end));
+  ASSERT_EQ(configs_after_presenting, configs_after_end);
+}
+
+TEST_P(SbPlayerGetAudioConfigurationTest, NoInput) {
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+
+  std::vector<SbMediaAudioConfiguration> initial_configs;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &initial_configs));
+
+  GroupedSamples samples;
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoEOS();
+  }
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting());
+
+  std::vector<SbMediaAudioConfiguration> configs_after_presenting;
+  // Note that as we didn't write any audio input, |configs_after_presenting|
+  // could be empty.
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_presenting));
+
+  if (!initial_configs.empty()) {
+    ASSERT_EQ(initial_configs, configs_after_presenting);
+  }
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+
+  std::vector<SbMediaAudioConfiguration> configs_after_end;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_end));
+  ASSERT_EQ(configs_after_presenting, configs_after_end);
+}
+
+TEST_P(SbPlayerGetAudioConfigurationTest, MultipleSeeks) {
+  const int kSamplesToWrite = 8;
+
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+
+  std::vector<SbMediaAudioConfiguration> initial_configs;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &initial_configs));
+
+  GroupedSamples samples;
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioSamples(0, kSamplesToWrite);
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(0, kSamplesToWrite);
+    samples.AddVideoEOS();
+  }
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting());
+
+  std::vector<SbMediaAudioConfiguration> configs_after_presenting;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_presenting));
+
+  if (player_fixture.HasAudio()) {
+    ASSERT_FALSE(configs_after_presenting.empty());
+  }
+
+  if (!initial_configs.empty()) {
+    ASSERT_EQ(initial_configs, configs_after_presenting);
+  }
+
+  const SbTime seek_to_time = kSbTimeSecond;
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Seek(seek_to_time));
+
+  std::vector<SbMediaAudioConfiguration> configs_after_seek;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_seek));
+  ASSERT_EQ(configs_after_presenting, configs_after_seek);
+
+  samples = GroupedSamples();
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioSamples(
+        0, player_fixture.ConvertDurationToAudioBufferCount(seek_to_time) +
+               kSamplesToWrite);
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(
+        0, player_fixture.ConvertDurationToVideoBufferCount(seek_to_time) +
+               kSamplesToWrite);
+    samples.AddVideoEOS();
+  }
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting());
+
+  configs_after_presenting.clear();
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_presenting));
+  ASSERT_EQ(configs_after_presenting, configs_after_seek);
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+
+  std::vector<SbMediaAudioConfiguration> configs_after_end;
+  ASSERT_NO_FATAL_FAILURE(
+      ReadAudioConfigurations(player_fixture, &configs_after_end));
+  ASSERT_EQ(configs_after_presenting, configs_after_end);
+}
+
+INSTANTIATE_TEST_CASE_P(SbPlayerGetAudioConfigurationTests,
+                        SbPlayerGetAudioConfigurationTest,
+                        ValuesIn(GetSupportedSbPlayerTestConfigs()),
+                        GetSbPlayerTestConfigName);
+
+}  // namespace
+}  // namespace nplb
+}  // namespace starboard
+
+#endif  // SB_API_VERSION >= 15
diff --git a/starboard/nplb/player_get_preferred_output_mode_test.cc b/starboard/nplb/player_get_preferred_output_mode_test.cc
index a3724bc..5b9c745 100644
--- a/starboard/nplb/player_get_preferred_output_mode_test.cc
+++ b/starboard/nplb/player_get_preferred_output_mode_test.cc
@@ -22,13 +22,6 @@
 namespace nplb {
 namespace {
 
-SbPlayerOutputMode GetPreferredOutputMode(
-    const PlayerCreationParam& creation_param) {
-  SbPlayerCreationParam param = {};
-  creation_param.ConvertTo(&param);
-  return SbPlayerGetPreferredOutputMode(&param);
-}
-
 TEST(SbPlayerGetPreferredOutputModeTest, SunnyDay) {
   auto creation_param =
       CreatePlayerCreationParam(kSbMediaAudioCodecAac, kSbMediaVideoCodecH264,
diff --git a/starboard/nplb/player_test_fixture.cc b/starboard/nplb/player_test_fixture.cc
index 9d8273e..7703dcd 100644
--- a/starboard/nplb/player_test_fixture.cc
+++ b/starboard/nplb/player_test_fixture.cc
@@ -15,6 +15,7 @@
 #include "starboard/nplb/player_test_fixture.h"
 
 #include <algorithm>
+#include <vector>
 
 #include "starboard/common/string.h"
 #include "starboard/nplb/drm_helpers.h"
@@ -26,6 +27,162 @@
 using shared::starboard::player::video_dmp::VideoDmpReader;
 using testing::FakeGraphicsContextProvider;
 
+using GroupedSamples = SbPlayerTestFixture::GroupedSamples;
+using AudioSamplesDescriptor = GroupedSamples::AudioSamplesDescriptor;
+using VideoSamplesDescriptor = GroupedSamples::VideoSamplesDescriptor;
+
+// TODO: Refine the implementation.
+class SbPlayerTestFixture::GroupedSamplesIterator {
+ public:
+  explicit GroupedSamplesIterator(const GroupedSamples& grouped_samples)
+      : grouped_samples_(grouped_samples) {}
+
+  bool HasMoreAudio() const {
+    return audio_samples_index_ < grouped_samples_.audio_samples_.size();
+  }
+
+  bool HasMoreVideo() const {
+    return video_samples_index_ < grouped_samples_.video_samples_.size();
+  }
+
+  AudioSamplesDescriptor GetCurrentAudioSamplesToWrite() const {
+    SB_DCHECK(HasMoreAudio());
+    AudioSamplesDescriptor descriptor =
+        grouped_samples_.audio_samples_[audio_samples_index_];
+    descriptor.start_index += current_written_audio_samples_;
+    descriptor.samples_count -= current_written_audio_samples_;
+    return descriptor;
+  }
+
+  VideoSamplesDescriptor GetCurrentVideoSamplesToWrite() const {
+    SB_DCHECK(HasMoreVideo());
+    VideoSamplesDescriptor descriptor =
+        grouped_samples_.video_samples_[video_samples_index_];
+    descriptor.start_index += current_written_video_samples_;
+    descriptor.samples_count -= current_written_video_samples_;
+    return descriptor;
+  }
+
+  void AdvanceAudio(int samples_count) {
+    SB_DCHECK(HasMoreAudio());
+    if (grouped_samples_.audio_samples_[audio_samples_index_]
+            .is_end_of_stream) {
+      // For EOS, |samples_count| must be 1.
+      SB_DCHECK(samples_count == 1);
+      SB_DCHECK(current_written_audio_samples_ == 0);
+      audio_samples_index_++;
+      return;
+    }
+
+    SB_DCHECK(
+        current_written_audio_samples_ + samples_count <=
+        grouped_samples_.audio_samples_[audio_samples_index_].samples_count);
+
+    current_written_audio_samples_ += samples_count;
+    if (current_written_audio_samples_ ==
+        grouped_samples_.audio_samples_[audio_samples_index_].samples_count) {
+      audio_samples_index_++;
+      current_written_audio_samples_ = 0;
+    }
+  }
+
+  void AdvanceVideo(int samples_count) {
+    SB_DCHECK(HasMoreVideo());
+    if (grouped_samples_.video_samples_[video_samples_index_]
+            .is_end_of_stream) {
+      // For EOS, |samples_count| must be 1.
+      SB_DCHECK(samples_count == 1);
+      SB_DCHECK(current_written_video_samples_ == 0);
+      video_samples_index_++;
+      return;
+    }
+
+    SB_DCHECK(
+        current_written_video_samples_ + samples_count <=
+        grouped_samples_.video_samples_[video_samples_index_].samples_count);
+
+    current_written_video_samples_ += samples_count;
+    if (current_written_video_samples_ ==
+        grouped_samples_.video_samples_[video_samples_index_].samples_count) {
+      video_samples_index_++;
+      current_written_video_samples_ = 0;
+    }
+  }
+
+ private:
+  const GroupedSamples& grouped_samples_;
+  int audio_samples_index_ = 0;
+  int current_written_audio_samples_ = 0;
+  int video_samples_index_ = 0;
+  int current_written_video_samples_ = 0;
+};
+
+GroupedSamples& GroupedSamples::AddAudioSamples(int start_index,
+                                                int number_of_samples) {
+  AddAudioSamples(start_index, number_of_samples, 0, 0, 0);
+  return *this;
+}
+
+GroupedSamples& GroupedSamples::AddAudioSamples(
+    int start_index,
+    int number_of_samples,
+    SbTime timestamp_offset,
+    SbTime discarded_duration_from_front,
+    SbTime discarded_duration_from_back) {
+  SB_DCHECK(start_index >= 0);
+  SB_DCHECK(number_of_samples >= 0);
+  SB_DCHECK(audio_samples_.empty() || !audio_samples_.back().is_end_of_stream);
+  // Currently, the implementation only supports writing one sample at a time
+  // if |discarded_duration_from_front| or |discarded_duration_from_back| is not
+  // 0.
+  SB_DCHECK(discarded_duration_from_front == 0 || number_of_samples == 1);
+  SB_DCHECK(discarded_duration_from_back == 0 || number_of_samples == 1);
+
+  AudioSamplesDescriptor descriptor;
+  descriptor.start_index = start_index;
+  descriptor.samples_count = number_of_samples;
+  descriptor.timestamp_offset = timestamp_offset;
+  descriptor.discarded_duration_from_front = discarded_duration_from_front;
+  descriptor.discarded_duration_from_back = discarded_duration_from_back;
+  audio_samples_.push_back(descriptor);
+
+  return *this;
+}
+
+GroupedSamples& GroupedSamples::AddAudioEOS() {
+  SB_DCHECK(audio_samples_.empty() || !audio_samples_.back().is_end_of_stream);
+
+  AudioSamplesDescriptor descriptor;
+  descriptor.is_end_of_stream = true;
+  audio_samples_.push_back(descriptor);
+
+  return *this;
+}
+
+GroupedSamples& GroupedSamples::AddVideoSamples(int start_index,
+                                                int number_of_samples) {
+  SB_DCHECK(start_index >= 0);
+  SB_DCHECK(number_of_samples >= 0);
+  SB_DCHECK(video_samples_.empty() || !video_samples_.back().is_end_of_stream);
+
+  VideoSamplesDescriptor descriptor;
+  descriptor.start_index = start_index;
+  descriptor.samples_count = number_of_samples;
+  video_samples_.push_back(descriptor);
+
+  return *this;
+}
+
+GroupedSamples& GroupedSamples::AddVideoEOS() {
+  SB_DCHECK(video_samples_.empty() || !video_samples_.back().is_end_of_stream);
+
+  VideoSamplesDescriptor descriptor;
+  descriptor.is_end_of_stream = true;
+  video_samples_.push_back(descriptor);
+
+  return *this;
+}
+
 SbPlayerTestFixture::CallbackEvent::CallbackEvent() : event_type(kEmptyEvent) {}
 
 SbPlayerTestFixture::CallbackEvent::CallbackEvent(SbPlayer player,
@@ -46,13 +203,18 @@
       player_state(state),
       ticket(ticket) {}
 
-SbPlayerTestFixture::SbPlayerTestFixture(const SbPlayerTestConfig& config)
-    : output_mode_(std::get<2>(config)), key_system_(std::get<3>(config)) {
+SbPlayerTestFixture::SbPlayerTestFixture(
+    const SbPlayerTestConfig& config,
+    FakeGraphicsContextProvider* fake_graphics_context_provider)
+    : output_mode_(config.output_mode),
+      key_system_(config.key_system),
+      max_video_capabilities_(config.max_video_capabilities),
+      fake_graphics_context_provider_(fake_graphics_context_provider) {
   SB_DCHECK(output_mode_ == kSbPlayerOutputModeDecodeToTexture ||
             output_mode_ == kSbPlayerOutputModePunchOut);
 
-  const char* audio_dmp_filename = std::get<0>(config);
-  const char* video_dmp_filename = std::get<1>(config);
+  const char* audio_dmp_filename = config.audio_filename;
+  const char* video_dmp_filename = config.video_filename;
 
   if (audio_dmp_filename && strlen(audio_dmp_filename) > 0) {
     audio_dmp_reader_.reset(new VideoDmpReader(
@@ -102,75 +264,77 @@
 
   ASSERT_FALSE(error_occurred_);
 
-  int audio_start_index = grouped_samples.audio_start_index();
-  int audio_samples_to_write = grouped_samples.audio_samples_to_write();
-  int video_start_index = grouped_samples.video_start_index();
-  int video_samples_to_write = grouped_samples.video_samples_to_write();
-  bool write_audio_eos = grouped_samples.write_audio_eos();
-  bool write_video_eos = grouped_samples.write_video_eos();
-
-  SB_DCHECK(audio_start_index >= 0);
-  SB_DCHECK(audio_samples_to_write >= 0);
-  SB_DCHECK(video_start_index >= 0);
-  SB_DCHECK(video_samples_to_write >= 0);
-  if (audio_samples_to_write > 0 || write_audio_eos) {
-    SB_DCHECK(audio_dmp_reader_);
-  }
-  if (video_samples_to_write > 0 || write_video_eos) {
-    SB_DCHECK(video_dmp_reader_);
-  }
-
   int max_audio_samples_per_write =
       SbPlayerGetMaximumNumberOfSamplesPerWrite(player_, kSbMediaTypeAudio);
   int max_video_samples_per_write =
       SbPlayerGetMaximumNumberOfSamplesPerWrite(player_, kSbMediaTypeVideo);
 
-  // Cap the samples to write to the end of the dmp files.
-  if (audio_samples_to_write > 0) {
-    audio_samples_to_write = std::min<int>(
-        audio_samples_to_write,
-        audio_dmp_reader_->number_of_audio_buffers() - audio_start_index);
-  }
-  if (video_samples_to_write > 0) {
-    video_samples_to_write = std::min<int>(
-        video_samples_to_write,
-        video_dmp_reader_->number_of_video_buffers() - video_start_index);
-  }
+  GroupedSamplesIterator iterator(grouped_samples);
+  SB_DCHECK(!iterator.HasMoreAudio() || audio_dmp_reader_);
+  SB_DCHECK(!iterator.HasMoreVideo() || video_dmp_reader_);
 
-  bool has_more_audio = audio_samples_to_write > 0 || write_audio_eos;
-  bool has_more_video = video_samples_to_write > 0 || write_video_eos;
-  while (has_more_audio || has_more_video) {
-    ASSERT_NO_FATAL_FAILURE(WaitForDecoderStateNeedsData());
-    if (can_accept_more_audio_data_ && has_more_audio) {
-      if (audio_samples_to_write > 0) {
-        auto samples_to_write =
-            std::min(max_audio_samples_per_write, audio_samples_to_write);
-        ASSERT_NO_FATAL_FAILURE(WriteSamples(
-            kSbMediaTypeAudio, audio_start_index, samples_to_write));
-        audio_start_index += samples_to_write;
-        audio_samples_to_write -= samples_to_write;
-      } else if (!audio_end_of_stream_written_ && write_audio_eos) {
+  const SbTime kDefaultWriteTimeout = kSbTimeSecond * 5;
+
+  SbTimeMonotonic start = SbTimeGetMonotonicNow();
+  while (SbTimeGetMonotonicNow() - start < kDefaultWriteTimeout) {
+    if (CanWriteMoreAudioData() && iterator.HasMoreAudio()) {
+      auto descriptor = iterator.GetCurrentAudioSamplesToWrite();
+      if (descriptor.is_end_of_stream) {
+        SB_DCHECK(!audio_end_of_stream_written_);
         ASSERT_NO_FATAL_FAILURE(WriteEndOfStream(kSbMediaTypeAudio));
+        iterator.AdvanceAudio(1);
+      } else {
+        SB_DCHECK(descriptor.samples_count > 0);
+        SB_DCHECK(descriptor.start_index + descriptor.samples_count <
+                  audio_dmp_reader_->number_of_audio_buffers())
+            << "Audio dmp file is not long enough to finish the test.";
+
+        auto samples_to_write =
+            std::min(max_audio_samples_per_write, descriptor.samples_count);
+        ASSERT_NO_FATAL_FAILURE(
+            WriteAudioSamples(descriptor.start_index, samples_to_write,
+                              descriptor.timestamp_offset,
+                              descriptor.discarded_duration_from_front,
+                              descriptor.discarded_duration_from_back));
+        iterator.AdvanceAudio(samples_to_write);
       }
-      has_more_audio = audio_samples_to_write > 0 ||
-                       (!audio_end_of_stream_written_ && write_audio_eos);
+    }
+    if (CanWriteMoreVideoData() && iterator.HasMoreVideo()) {
+      auto descriptor = iterator.GetCurrentVideoSamplesToWrite();
+      if (descriptor.is_end_of_stream) {
+        SB_DCHECK(!video_end_of_stream_written_);
+        ASSERT_NO_FATAL_FAILURE(WriteEndOfStream(kSbMediaTypeVideo));
+        iterator.AdvanceVideo(1);
+      } else {
+        SB_DCHECK(descriptor.samples_count > 0);
+        SB_DCHECK(descriptor.start_index + descriptor.samples_count <
+                  video_dmp_reader_->number_of_video_buffers())
+            << "Video dmp file is not long enough to finish the test.";
+
+        auto samples_to_write =
+            std::min(max_video_samples_per_write, descriptor.samples_count);
+        ASSERT_NO_FATAL_FAILURE(
+            WriteVideoSamples(descriptor.start_index, samples_to_write));
+        iterator.AdvanceVideo(samples_to_write);
+      }
     }
 
-    if (can_accept_more_video_data_ && has_more_video) {
-      if (video_samples_to_write > 0) {
-        auto samples_to_write =
-            std::min(max_video_samples_per_write, video_samples_to_write);
-        ASSERT_NO_FATAL_FAILURE(WriteSamples(
-            kSbMediaTypeVideo, video_start_index, samples_to_write));
-        video_start_index += samples_to_write;
-        video_samples_to_write -= samples_to_write;
-      } else if (!video_end_of_stream_written_ && write_video_eos) {
-        ASSERT_NO_FATAL_FAILURE(WriteEndOfStream(kSbMediaTypeVideo));
-      }
-      has_more_video = video_samples_to_write > 0 ||
-                       (!video_end_of_stream_written_ && write_video_eos);
+    if (iterator.HasMoreAudio() || iterator.HasMoreVideo()) {
+      ASSERT_NO_FATAL_FAILURE(WaitForDecoderStateNeedsData());
+    } else {
+      return;
     }
   }
+
+  FAIL() << "Failed to write all samples.";
+}
+
+void SbPlayerTestFixture::WaitForPlayerPresenting() {
+  SB_DCHECK(thread_checker_.CalledOnValidThread());
+  SB_DCHECK(SbPlayerIsValid(player_));
+
+  ASSERT_FALSE(error_occurred_);
+  ASSERT_NO_FATAL_FAILURE(WaitForPlayerState(kSbPlayerStatePresenting));
 }
 
 void SbPlayerTestFixture::WaitForPlayerEndOfStream() {
@@ -183,6 +347,46 @@
   ASSERT_NO_FATAL_FAILURE(WaitForPlayerState(kSbPlayerStateEndOfStream));
 }
 
+SbTime SbPlayerTestFixture::GetCurrentMediaTime() const {
+#if SB_API_VERSION >= 15
+  SbPlayerInfo info = {};
+  SbPlayerGetInfo(player_, &info);
+#else   // SB_API_VERSION >= 15
+  SbPlayerInfo2 info = {};
+  SbPlayerGetInfo2(player_, &info);
+#endif  // SB_API_VERSION >= 15
+  return info.current_media_timestamp;
+}
+
+void SbPlayerTestFixture::SetAudioWriteDuration(SbTime duration) {
+  SB_DCHECK(thread_checker_.CalledOnValidThread());
+  SB_DCHECK(duration > 0);
+  audio_write_duration_ = duration;
+}
+
+SbTime SbPlayerTestFixture::GetAudioSampleTimestamp(int index) const {
+  SB_DCHECK(HasAudio());
+  SB_DCHECK(index < audio_dmp_reader_->number_of_audio_buffers());
+  return audio_dmp_reader_->GetPlayerSampleInfo(kSbMediaTypeAudio, index)
+      .timestamp;
+}
+
+int SbPlayerTestFixture::ConvertDurationToAudioBufferCount(
+    SbTime duration) const {
+  SB_DCHECK(HasAudio());
+  SB_DCHECK(audio_dmp_reader_->number_of_audio_buffers());
+  return duration * audio_dmp_reader_->number_of_audio_buffers() /
+         audio_dmp_reader_->audio_duration();
+}
+
+int SbPlayerTestFixture::ConvertDurationToVideoBufferCount(
+    SbTime duration) const {
+  SB_DCHECK(HasVideo());
+  SB_DCHECK(video_dmp_reader_->number_of_video_buffers());
+  return duration * video_dmp_reader_->number_of_video_buffers() /
+         video_dmp_reader_->video_duration();
+}
+
 // static
 void SbPlayerTestFixture::DecoderStatusCallback(SbPlayer player,
                                                 void* context,
@@ -256,11 +460,14 @@
   if (video_dmp_reader_) {
     video_codec = video_dmp_reader_->video_codec();
   }
+
+  // TODO: refine CallSbPlayerCreate() to use real video sample info.
   player_ = CallSbPlayerCreate(
-      fake_graphics_context_provider_.window(), video_codec, audio_codec,
-      drm_system_, audio_stream_info, "", DummyDeallocateSampleFunc,
-      DecoderStatusCallback, PlayerStatusCallback, ErrorCallback, this,
-      output_mode_, fake_graphics_context_provider_.decoder_target_provider());
+      fake_graphics_context_provider_->window(), video_codec, audio_codec,
+      drm_system_, audio_stream_info, max_video_capabilities_.c_str(),
+      DummyDeallocateSampleFunc, DecoderStatusCallback, PlayerStatusCallback,
+      ErrorCallback, this, output_mode_,
+      fake_graphics_context_provider_->decoder_target_provider());
   ASSERT_TRUE(SbPlayerIsValid(player_));
   ASSERT_NO_FATAL_FAILURE(WaitForPlayerState(kSbPlayerStateInitialized));
   ASSERT_NO_FATAL_FAILURE(Seek(0));
@@ -293,34 +500,71 @@
   drm_system_ = kSbDrmSystemInvalid;
 }
 
-void SbPlayerTestFixture::WriteSamples(SbMediaType media_type,
-                                       int start_index,
-                                       int samples_to_write) {
+bool SbPlayerTestFixture::CanWriteMoreAudioData() {
+  if (!can_accept_more_audio_data_) {
+    return false;
+  }
+
+  if (!audio_write_duration_) {
+    return true;
+  }
+
+  return last_written_audio_timestamp_ - GetCurrentMediaTime() <
+         audio_write_duration_;
+}
+
+bool SbPlayerTestFixture::CanWriteMoreVideoData() {
+  return can_accept_more_video_data_;
+}
+
+void SbPlayerTestFixture::WriteAudioSamples(
+    int start_index,
+    int samples_to_write,
+    SbTime timestamp_offset,
+    SbTime discarded_duration_from_front,
+    SbTime discarded_duration_from_back) {
+  SB_DCHECK(thread_checker_.CalledOnValidThread());
+  SB_DCHECK(SbPlayerIsValid(player_));
+  SB_DCHECK(audio_dmp_reader_);
+  SB_DCHECK(start_index >= 0);
+  SB_DCHECK(samples_to_write > 0);
+  SB_DCHECK(samples_to_write <= SbPlayerGetMaximumNumberOfSamplesPerWrite(
+                                    player_, kSbMediaTypeAudio));
+  SB_DCHECK(start_index + samples_to_write + 1 <
+            audio_dmp_reader_->number_of_audio_buffers());
+  SB_DCHECK(discarded_duration_from_front == 0 || samples_to_write == 1);
+  SB_DCHECK(discarded_duration_from_back == 0 || samples_to_write == 1);
+
+  CallSbPlayerWriteSamples(
+      player_, kSbMediaTypeAudio, audio_dmp_reader_.get(), start_index,
+      samples_to_write, timestamp_offset,
+      std::vector<SbTime>(samples_to_write, discarded_duration_from_front),
+      std::vector<SbTime>(samples_to_write, discarded_duration_from_back));
+
+  last_written_audio_timestamp_ =
+      audio_dmp_reader_
+          ->GetPlayerSampleInfo(kSbMediaTypeAudio,
+                                start_index + samples_to_write)
+          .timestamp;
+
+  can_accept_more_audio_data_ = false;
+}
+
+void SbPlayerTestFixture::WriteVideoSamples(int start_index,
+                                            int samples_to_write) {
   SB_DCHECK(thread_checker_.CalledOnValidThread());
   SB_DCHECK(start_index >= 0);
   SB_DCHECK(samples_to_write > 0);
   SB_DCHECK(SbPlayerIsValid(player_));
-  SB_DCHECK(samples_to_write <=
-            SbPlayerGetMaximumNumberOfSamplesPerWrite(player_, media_type));
+  SB_DCHECK(samples_to_write <= SbPlayerGetMaximumNumberOfSamplesPerWrite(
+                                    player_, kSbMediaTypeVideo));
+  SB_DCHECK(video_dmp_reader_);
+  SB_DCHECK(start_index + samples_to_write <
+            video_dmp_reader_->number_of_video_buffers());
 
-  if (media_type == kSbMediaTypeAudio) {
-    SB_DCHECK(audio_dmp_reader_);
-    SB_DCHECK(start_index + samples_to_write <=
-              audio_dmp_reader_->number_of_audio_buffers());
-    CallSbPlayerWriteSamples(player_, kSbMediaTypeAudio,
-                             audio_dmp_reader_.get(), start_index,
-                             samples_to_write);
-    can_accept_more_audio_data_ = false;
-  } else {
-    SB_DCHECK(media_type == kSbMediaTypeVideo);
-    SB_DCHECK(video_dmp_reader_);
-    SB_DCHECK(start_index + samples_to_write <=
-              video_dmp_reader_->number_of_video_buffers());
-    CallSbPlayerWriteSamples(player_, kSbMediaTypeVideo,
-                             video_dmp_reader_.get(), start_index,
-                             samples_to_write);
-    can_accept_more_video_data_ = false;
-  }
+  CallSbPlayerWriteSamples(player_, kSbMediaTypeVideo, video_dmp_reader_.get(),
+                           start_index, samples_to_write);
+  can_accept_more_video_data_ = false;
 }
 
 void SbPlayerTestFixture::WriteEndOfStream(SbMediaType media_type) {
@@ -388,7 +632,6 @@
 
 void SbPlayerTestFixture::WaitForDecoderStateNeedsData(const SbTime timeout) {
   SB_DCHECK(thread_checker_.CalledOnValidThread());
-  SB_DCHECK(!can_accept_more_audio_data_ || !can_accept_more_video_data_);
 
   bool old_can_accept_more_audio_data = can_accept_more_audio_data_;
   bool old_can_accept_more_video_data = can_accept_more_video_data_;
@@ -403,8 +646,6 @@
       return;
     }
   } while (SbTimeGetMonotonicNow() - start < timeout);
-
-  FAIL() << "WaitForDecoderStateNeedsData() did not receive expected state.";
 }
 
 void SbPlayerTestFixture::WaitForPlayerState(const SbPlayerState desired_state,
@@ -432,7 +673,7 @@
     return;
   }
 #if SB_HAS(GLES2)
-  fake_graphics_context_provider_.RunOnGlesContextThread([&]() {
+  fake_graphics_context_provider_->RunOnGlesContextThread([&]() {
     ASSERT_TRUE(SbPlayerIsValid(player_));
     if (output_mode_ != kSbPlayerOutputModeDecodeToTexture) {
       ASSERT_EQ(SbPlayerGetCurrentFrame(player_), kSbDecodeTargetInvalid);
diff --git a/starboard/nplb/player_test_fixture.h b/starboard/nplb/player_test_fixture.h
index 9a66f60..72b069b 100644
--- a/starboard/nplb/player_test_fixture.h
+++ b/starboard/nplb/player_test_fixture.h
@@ -19,6 +19,7 @@
 #include <deque>
 #include <set>
 #include <string>
+#include <vector>
 
 #include "starboard/common/queue.h"
 #include "starboard/common/scoped_ptr.h"
@@ -35,46 +36,44 @@
 class SbPlayerTestFixture {
  public:
   // A simple encapsulation of grouped samples.
+  class GroupedSamplesIterator;
   class GroupedSamples {
    public:
-    int audio_start_index() const { return audio_start_index_; }
-    int audio_samples_to_write() const { return audio_samples_to_write_; }
-    bool write_audio_eos() const { return write_audio_eos_; }
+    struct AudioSamplesDescriptor {
+      int start_index = 0;
+      int samples_count = 0;
+      SbTime timestamp_offset = 0;
+      SbTime discarded_duration_from_front = 0;
+      SbTime discarded_duration_from_back = 0;
+      bool is_end_of_stream = false;
+    };
 
-    int video_start_index() const { return video_start_index_; }
-    int video_samples_to_write() const { return video_samples_to_write_; }
-    bool write_video_eos() const { return write_video_eos_; }
+    struct VideoSamplesDescriptor {
+      int start_index = 0;
+      int samples_count = 0;
+      bool is_end_of_stream = false;
+    };
 
-    void AddAudioSamples(int audio_start_index, int audio_samples_to_write) {
-      audio_start_index_ = audio_start_index;
-      audio_samples_to_write_ = audio_samples_to_write;
-    }
-    void AddAudioSamplesWithEOS(int audio_start_index,
-                                int audio_samples_to_write) {
-      AddAudioSamples(audio_start_index, audio_samples_to_write);
-      write_audio_eos_ = true;
-    }
-    void AddVideoSamples(int video_start_index, int video_samples_to_write) {
-      video_start_index_ = video_start_index;
-      video_samples_to_write_ = video_samples_to_write;
-    }
+    GroupedSamples& AddAudioSamples(int start_index, int number_of_samples);
+    GroupedSamples& AddAudioSamples(int start_index,
+                                    int number_of_samples,
+                                    SbTime timestamp_offset,
+                                    SbTime discarded_duration_from_front,
+                                    SbTime discarded_duration_from_back);
+    GroupedSamples& AddAudioEOS();
+    GroupedSamples& AddVideoSamples(int start_index, int number_of_samples);
+    GroupedSamples& AddVideoEOS();
 
-    void AddVideoSamplesWithEOS(int video_start_index,
-                                int video_samples_to_write) {
-      AddVideoSamples(video_start_index, video_samples_to_write);
-      write_video_eos_ = true;
-    }
+    friend class GroupedSamplesIterator;
 
    private:
-    int audio_start_index_ = 0;
-    int audio_samples_to_write_ = 0;
-    bool write_audio_eos_ = false;
-    int video_start_index_ = 0;
-    int video_samples_to_write_ = 0;
-    bool write_video_eos_ = false;
+    std::vector<AudioSamplesDescriptor> audio_samples_;
+    std::vector<VideoSamplesDescriptor> video_samples_;
   };
 
-  explicit SbPlayerTestFixture(const SbPlayerTestConfig& config);
+  SbPlayerTestFixture(
+      const SbPlayerTestConfig& config,
+      testing::FakeGraphicsContextProvider* fake_graphics_context_provider);
   ~SbPlayerTestFixture();
 
   void Seek(const SbTime time);
@@ -83,16 +82,23 @@
   // requested, the function will write EOS after all samples of the same type
   // are written.
   void Write(const GroupedSamples& grouped_samples);
+  // Wait until kSbPlayerStatePresenting received.
+  void WaitForPlayerPresenting();
   // Wait until kSbPlayerStateEndOfStream received.
   void WaitForPlayerEndOfStream();
+  SbTime GetCurrentMediaTime() const;
 
-  SbPlayer GetPlayer() { return player_; }
+  void SetAudioWriteDuration(SbTime duration);
+
+  SbPlayer GetPlayer() const { return player_; }
   bool HasAudio() const { return audio_dmp_reader_; }
   bool HasVideo() const { return video_dmp_reader_; }
 
+  SbTime GetAudioSampleTimestamp(int index) const;
+  int ConvertDurationToAudioBufferCount(SbTime duration) const;
+  int ConvertDurationToVideoBufferCount(SbTime duration) const;
+
  private:
-  static constexpr SbTime kDefaultWaitForDecoderStateNeedsDataTimeout =
-      5 * kSbTimeSecond;
   static constexpr SbTime kDefaultWaitForPlayerStateTimeout = 5 * kSbTimeSecond;
   static constexpr SbTime kDefaultWaitForCallbackEventTimeout =
       15 * kSbTimeMillisecond;
@@ -149,9 +155,15 @@
   void Initialize();
   void TearDown();
 
-  void WriteSamples(SbMediaType media_type,
-                    int start_index,
-                    int samples_to_write);
+  bool CanWriteMoreAudioData();
+  bool CanWriteMoreVideoData();
+
+  void WriteAudioSamples(int start_index,
+                         int samples_to_write,
+                         SbTime timestamp_offset,
+                         SbTime discarded_duration_from_front,
+                         SbTime discarded_duration_from_back);
+  void WriteVideoSamples(int start_index, int samples_to_write);
   void WriteEndOfStream(SbMediaType media_type);
 
   // Checks if there are pending callback events and, if so, logs the received
@@ -164,7 +176,7 @@
 
   // Waits for |kSbPlayerDecoderStateNeedsData| to be sent.
   void WaitForDecoderStateNeedsData(
-      const SbTime timeout = kDefaultWaitForDecoderStateNeedsDataTimeout);
+      const SbTime timeout = kDefaultWaitForCallbackEventTimeout);
 
   // Waits for desired player state update to be sent.
   void WaitForPlayerState(
@@ -186,9 +198,10 @@
   shared::starboard::ThreadChecker thread_checker_;
   const SbPlayerOutputMode output_mode_;
   std::string key_system_;
+  std::string max_video_capabilities_;
   scoped_ptr<VideoDmpReader> audio_dmp_reader_;
   scoped_ptr<VideoDmpReader> video_dmp_reader_;
-  testing::FakeGraphicsContextProvider fake_graphics_context_provider_;
+  testing::FakeGraphicsContextProvider* fake_graphics_context_provider_;
 
   SbPlayer player_ = kSbPlayerInvalid;
   SbDrmSystem drm_system_ = kSbDrmSystemInvalid;
@@ -200,6 +213,11 @@
   bool can_accept_more_audio_data_ = false;
   bool can_accept_more_video_data_ = false;
 
+  // The duration of how far past the current playback position we will write
+  // audio samples.
+  SbTime audio_write_duration_ = 0;
+  SbTime last_written_audio_timestamp_ = 0;
+
   // Set of received player state updates from the underlying player. This is
   // used to check that the state updates occur in a valid order during normal
   // playback.
diff --git a/starboard/nplb/player_test_util.cc b/starboard/nplb/player_test_util.cc
index 2841800..34639e1 100644
--- a/starboard/nplb/player_test_util.cc
+++ b/starboard/nplb/player_test_util.cc
@@ -21,6 +21,7 @@
 #include "starboard/common/string.h"
 #include "starboard/extension/enhanced_audio.h"
 #include "starboard/nplb/drm_helpers.h"
+#include "starboard/nplb/maximum_player_configuration_explorer.h"
 #include "starboard/nplb/player_creation_param_helpers.h"
 #include "starboard/shared/starboard/player/video_dmp_reader.h"
 #include "starboard/testing/fake_graphics_context_provider.h"
@@ -40,6 +41,24 @@
 using std::placeholders::_4;
 using testing::FakeGraphicsContextProvider;
 
+const char* kAudioTestFiles[] = {"beneath_the_canopy_aac_stereo.dmp",
+                                 "beneath_the_canopy_opus_stereo.dmp",
+                                 "sintel_329_ec3.dmp", "sintel_381_ac3.dmp"};
+
+// For uncommon audio formats, we add audio only tests, without tests combined
+// with a video stream, to shorten the overall test time.
+const char* kAudioOnlyTestFiles[] = {
+    "beneath_the_canopy_aac_5_1.dmp", "beneath_the_canopy_aac_mono.dmp",
+    "beneath_the_canopy_opus_5_1.dmp", "beneath_the_canopy_opus_mono.dmp",
+    "heaac.dmp"};
+
+const char* kVideoTestFiles[] = {"beneath_the_canopy_137_avc.dmp",
+                                 "beneath_the_canopy_248_vp9.dmp",
+                                 "sintel_399_av1.dmp"};
+
+const SbPlayerOutputMode kOutputModes[] = {kSbPlayerOutputModeDecodeToTexture,
+                                           kSbPlayerOutputModePunchOut};
+
 void ErrorFunc(SbPlayer player,
                void* context,
                SbPlayerError error,
@@ -50,30 +69,35 @@
 
 }  // namespace
 
+std::vector<const char*> GetAudioTestFiles() {
+  return std::vector<const char*>(std::begin(kAudioTestFiles),
+                                  std::end(kAudioTestFiles));
+}
+
+std::vector<const char*> GetVideoTestFiles() {
+  return std::vector<const char*>(std::begin(kVideoTestFiles),
+                                  std::end(kVideoTestFiles));
+}
+
+std::vector<SbPlayerOutputMode> GetPlayerOutputModes() {
+  return std::vector<SbPlayerOutputMode>(std::begin(kOutputModes),
+                                         std::end(kOutputModes));
+}
+
+std::vector<const char*> GetKeySystems() {
+  std::vector<const char*> key_systems;
+  key_systems.push_back("");
+  key_systems.insert(key_systems.end(), kKeySystems,
+                     kKeySystems + SB_ARRAY_SIZE_INT(kKeySystems));
+  return key_systems;
+}
+
 std::vector<SbPlayerTestConfig> GetSupportedSbPlayerTestConfigs(
     const char* key_system) {
   SB_DCHECK(key_system);
 
   const char* kEmptyName = NULL;
 
-  const char* kAudioTestFiles[] = {"beneath_the_canopy_aac_stereo.dmp",
-                                   "beneath_the_canopy_opus_stereo.dmp",
-                                   "sintel_329_ec3.dmp", "sintel_381_ac3.dmp"};
-
-  // For uncommon audio formats, we add audio only tests, without tests combined
-  // with a video stream, to shorten the overall test time.
-  const char* kAudioOnlyTestFiles[] = {
-      "beneath_the_canopy_aac_5_1.dmp", "beneath_the_canopy_aac_mono.dmp",
-      "beneath_the_canopy_opus_5_1.dmp", "beneath_the_canopy_opus_mono.dmp",
-      "heaac.dmp"};
-
-  const char* kVideoTestFiles[] = {"beneath_the_canopy_137_avc.dmp",
-                                   "beneath_the_canopy_248_vp9.dmp",
-                                   "sintel_399_av1.dmp"};
-
-  const SbPlayerOutputMode kOutputModes[] = {kSbPlayerOutputModeDecodeToTexture,
-                                             kSbPlayerOutputModePunchOut};
-
   std::vector<const char*> supported_audio_files;
   supported_audio_files.push_back(kEmptyName);
   for (auto audio_filename : kAudioTestFiles) {
@@ -121,8 +145,8 @@
       for (auto output_mode : kOutputModes) {
         if (IsOutputModeSupported(output_mode, audio_codec, video_codec,
                                   key_system)) {
-          test_configs.push_back(std::make_tuple(audio_filename, video_filename,
-                                                 output_mode, key_system));
+          test_configs.emplace_back(audio_filename, video_filename, output_mode,
+                                    key_system);
         }
       }
     }
@@ -137,8 +161,8 @@
       for (auto output_mode : kOutputModes) {
         if (IsOutputModeSupported(output_mode, dmp_reader.audio_codec(),
                                   kSbMediaVideoCodecNone, key_system)) {
-          test_configs.push_back(std::make_tuple(audio_filename, kEmptyName,
-                                                 output_mode, key_system));
+          test_configs.emplace_back(audio_filename, kEmptyName, output_mode,
+                                    key_system);
         }
       }
     }
@@ -147,6 +171,26 @@
   return test_configs;
 }
 
+std::string GetSbPlayerTestConfigName(
+    ::testing::TestParamInfo<SbPlayerTestConfig> info) {
+  const SbPlayerTestConfig& config = info.param;
+  const char* audio_filename = config.audio_filename;
+  const char* video_filename = config.video_filename;
+  const SbPlayerOutputMode output_mode = config.output_mode;
+  const char* key_system = config.key_system;
+  std::string name(FormatString(
+      "audio_%s_video_%s_output_%s_key_system_%s",
+      audio_filename && strlen(audio_filename) > 0 ? audio_filename : "null",
+      video_filename && strlen(video_filename) > 0 ? video_filename : "null",
+      output_mode == kSbPlayerOutputModeDecodeToTexture ? "decode_to_texture"
+                                                        : "punch_out",
+      strlen(key_system) > 0 ? key_system : "null"));
+  std::replace(name.begin(), name.end(), '.', '_');
+  std::replace(name.begin(), name.end(), '(', '_');
+  std::replace(name.begin(), name.end(), ')', '_');
+  return name;
+}
+
 void DummyDeallocateSampleFunc(SbPlayer player,
                                void* context,
                                const void* sample_buffer) {}
@@ -187,6 +231,7 @@
     SB_CHECK(audio_codec == kSbMediaAudioCodecNone);
   }
 
+  // TODO: pass real audio/video info to SbPlayerGetPreferredOutputMode.
   PlayerCreationParam creation_param =
       CreatePlayerCreationParam(audio_codec, video_codec, output_mode);
   if (audio_stream_info) {
@@ -208,10 +253,25 @@
     SbMediaType sample_type,
     shared::starboard::player::video_dmp::VideoDmpReader* dmp_reader,
     int start_index,
-    int number_of_samples_to_write) {
+    int number_of_samples_to_write,
+    SbTime timestamp_offset,
+    const std::vector<SbTime>& discarded_durations_from_front,
+    const std::vector<SbTime>& discarded_durations_from_back) {
   SB_DCHECK(start_index >= 0);
   SB_DCHECK(number_of_samples_to_write > 0);
 
+  if (sample_type == kSbMediaTypeAudio) {
+    SB_DCHECK(discarded_durations_from_front.empty() ||
+              discarded_durations_from_front.size() ==
+                  number_of_samples_to_write);
+    SB_DCHECK(discarded_durations_from_front.size() ==
+              discarded_durations_from_back.size());
+  } else {
+    SB_DCHECK(sample_type == kSbMediaTypeVideo);
+    SB_DCHECK(discarded_durations_from_front.empty());
+    SB_DCHECK(discarded_durations_from_back.empty());
+  }
+
   static auto const* enhanced_audio_extension =
       static_cast<const CobaltExtensionEnhancedAudioApi*>(
           SbSystemGetExtension(kCobaltExtensionEnhancedAudioName));
@@ -238,7 +298,7 @@
       sample_infos.back().type = source.type;
       sample_infos.back().buffer = source.buffer;
       sample_infos.back().buffer_size = source.buffer_size;
-      sample_infos.back().timestamp = source.timestamp;
+      sample_infos.back().timestamp = source.timestamp + timestamp_offset;
       sample_infos.back().side_data = source.side_data;
       sample_infos.back().side_data_count = source.side_data_count;
       sample_infos.back().drm_info = source.drm_info;
@@ -247,8 +307,15 @@
         audio_sample_infos.emplace_back(source.audio_sample_info);
         audio_sample_infos.back().ConvertTo(
             &sample_infos.back().audio_sample_info);
+        if (!discarded_durations_from_front.empty()) {
+          sample_infos.back().audio_sample_info.discarded_duration_from_front =
+              discarded_durations_from_front[i];
+        }
+        if (!discarded_durations_from_back.empty()) {
+          sample_infos.back().audio_sample_info.discarded_duration_from_back =
+              discarded_durations_from_back[i];
+        }
       } else {
-        SB_DCHECK(sample_type == kSbMediaTypeVideo);
         video_sample_infos.emplace_back(source.video_sample_info);
         video_sample_infos.back().ConvertTo(
             &sample_infos.back().video_sample_info);
@@ -265,6 +332,17 @@
   for (int i = 0; i < number_of_samples_to_write; ++i) {
     sample_infos.push_back(
         dmp_reader->GetPlayerSampleInfo(sample_type, start_index++));
+    sample_infos.back().timestamp += timestamp_offset;
+#if SB_API_VERSION >= 15
+    if (!discarded_durations_from_front.empty()) {
+      sample_infos.back().audio_sample_info.discarded_duration_from_front =
+          discarded_durations_from_front[i];
+    }
+    if (!discarded_durations_from_back.empty()) {
+      sample_infos.back().audio_sample_info.discarded_duration_from_back =
+          discarded_durations_from_back[i];
+    }
+#endif  // SB_API_VERSION >= 15
   }
 #if SB_API_VERSION >= 15
   SbPlayerWriteSamples(player, sample_type, sample_infos.data(),
@@ -281,6 +359,7 @@
                            const char* key_system) {
   SB_DCHECK(key_system);
 
+  // TODO: pass real audio/video info to SbPlayerGetPreferredOutputMode.
   PlayerCreationParam creation_param =
       CreatePlayerCreationParam(audio_codec, video_codec, output_mode);
 
@@ -305,5 +384,13 @@
   return supported;
 }
 
+bool IsPartialAudioSupported() {
+#if SB_API_VERSION >= 15
+  return true;
+#else   // SB_API_VERSION >= 15
+  return SbSystemGetExtension(kCobaltExtensionEnhancedAudioName) != nullptr;
+#endif  // SB_API_VERSION >= 15
+}
+
 }  // namespace nplb
 }  // namespace starboard
diff --git a/starboard/nplb/player_test_util.h b/starboard/nplb/player_test_util.h
index a8bf4fc..100bf6c 100644
--- a/starboard/nplb/player_test_util.h
+++ b/starboard/nplb/player_test_util.h
@@ -23,21 +23,49 @@
 #include "starboard/player.h"
 #include "starboard/shared/starboard/media/media_util.h"
 #include "starboard/shared/starboard/player/video_dmp_reader.h"
+#include "testing/gtest/include/gtest/gtest.h"
 
 namespace starboard {
 namespace nplb {
 
-// TODO(b/283002236): create a struct for SbPlayerTestConfig instead of using
-// std::tuple.
-typedef std::tuple<const char* /* audio_filename */,
-                   const char* /* video_filename */,
-                   SbPlayerOutputMode /* output_mode */,
-                   const char* /* key_system */>
-    SbPlayerTestConfig;
+struct SbPlayerTestConfig {
+  SbPlayerTestConfig(const char* audio_filename,
+                     const char* video_filename,
+                     SbPlayerOutputMode output_mode,
+                     const char* key_system)
+      : audio_filename(audio_filename),
+        video_filename(video_filename),
+        output_mode(output_mode),
+        key_system(key_system),
+        max_video_capabilities("") {}
+  SbPlayerTestConfig(const char* audio_filename,
+                     const char* video_filename,
+                     SbPlayerOutputMode output_mode,
+                     const char* key_system,
+                     const char* max_video_capabilities)
+      : audio_filename(audio_filename),
+        video_filename(video_filename),
+        output_mode(output_mode),
+        key_system(key_system),
+        max_video_capabilities(max_video_capabilities) {}
+  const char* audio_filename;
+  const char* video_filename;
+  SbPlayerOutputMode output_mode;
+  const char* key_system;
+  const char* max_video_capabilities;
+};
+
+std::vector<const char*> GetAudioTestFiles();
+std::vector<const char*> GetVideoTestFiles();
+std::vector<SbPlayerOutputMode> GetPlayerOutputModes();
+std::vector<const char*> GetKeySystems();
 
 std::vector<SbPlayerTestConfig> GetSupportedSbPlayerTestConfigs(
     const char* key_system = "");
 
+std::string GetSbPlayerTestConfigName(
+    ::testing::TestParamInfo<SbPlayerTestConfig> info);
+
 void DummyDeallocateSampleFunc(SbPlayer player,
                                void* context,
                                const void* sample_buffer);
@@ -78,13 +106,18 @@
     SbMediaType sample_type,
     shared::starboard::player::video_dmp::VideoDmpReader* dmp_reader,
     int start_index,
-    int number_of_samples_to_write);
+    int number_of_samples_to_write,
+    SbTime timestamp_offset = 0,
+    const std::vector<SbTime>& discarded_durations_from_front = {},
+    const std::vector<SbTime>& discarded_durations_from_back = {});
 
 bool IsOutputModeSupported(SbPlayerOutputMode output_mode,
                            SbMediaAudioCodec audio_codec,
                            SbMediaVideoCodec video_codec,
                            const char* key_system = "");
 
+bool IsPartialAudioSupported();
+
 }  // namespace nplb
 }  // namespace starboard
 
diff --git a/starboard/nplb/player_write_sample_test.cc b/starboard/nplb/player_write_sample_test.cc
index cf33cb4..414a4ea 100644
--- a/starboard/nplb/player_write_sample_test.cc
+++ b/starboard/nplb/player_write_sample_test.cc
@@ -12,11 +12,13 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-#include "starboard/common/string.h"
 #include "starboard/nplb/drm_helpers.h"
+#include "starboard/nplb/player_creation_param_helpers.h"
 #include "starboard/nplb/player_test_fixture.h"
 #include "starboard/nplb/player_test_util.h"
+#include "starboard/nplb/thread_helpers.h"
 #include "starboard/string.h"
+#include "starboard/testing/fake_graphics_context_provider.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace starboard {
@@ -26,12 +28,17 @@
 using ::testing::ValuesIn;
 
 typedef SbPlayerTestFixture::GroupedSamples GroupedSamples;
+typedef testing::FakeGraphicsContextProvider FakeGraphicsContextProvider;
 
 class SbPlayerWriteSampleTest
-    : public ::testing::TestWithParam<SbPlayerTestConfig> {};
+    : public ::testing::TestWithParam<SbPlayerTestConfig> {
+ protected:
+  FakeGraphicsContextProvider fake_graphics_context_provider_;
+};
 
 TEST_P(SbPlayerWriteSampleTest, SeekAndDestroy) {
-  SbPlayerTestFixture player_fixture(GetParam());
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
   if (HasFatalFailure()) {
     return;
   }
@@ -39,24 +46,26 @@
 }
 
 TEST_P(SbPlayerWriteSampleTest, NoInput) {
-  SbPlayerTestFixture player_fixture(GetParam());
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
   if (HasFatalFailure()) {
     return;
   }
 
   GroupedSamples samples;
   if (player_fixture.HasAudio()) {
-    samples.AddAudioSamplesWithEOS(0, 0);
+    samples.AddAudioEOS();
   }
   if (player_fixture.HasVideo()) {
-    samples.AddVideoSamplesWithEOS(0, 0);
+    samples.AddVideoEOS();
   }
   ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
   ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
 }
 
 TEST_P(SbPlayerWriteSampleTest, WriteSingleBatch) {
-  SbPlayerTestFixture player_fixture(GetParam());
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
   if (HasFatalFailure()) {
     return;
   }
@@ -65,12 +74,14 @@
   if (player_fixture.HasAudio()) {
     int samples_to_write = SbPlayerGetMaximumNumberOfSamplesPerWrite(
         player_fixture.GetPlayer(), kSbMediaTypeAudio);
-    samples.AddAudioSamplesWithEOS(0, samples_to_write);
+    samples.AddAudioSamples(0, samples_to_write);
+    samples.AddAudioEOS();
   }
   if (player_fixture.HasVideo()) {
     int samples_to_write = SbPlayerGetMaximumNumberOfSamplesPerWrite(
         player_fixture.GetPlayer(), kSbMediaTypeVideo);
-    samples.AddVideoSamplesWithEOS(0, samples_to_write);
+    samples.AddVideoSamples(0, samples_to_write);
+    samples.AddVideoEOS();
   }
 
   ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
@@ -78,7 +89,8 @@
 }
 
 TEST_P(SbPlayerWriteSampleTest, WriteMultipleBatches) {
-  SbPlayerTestFixture player_fixture(GetParam());
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
   if (HasFatalFailure()) {
     return;
   }
@@ -86,10 +98,9 @@
   int samples_to_write = 0;
   // Try to write multiple batches for both audio and video.
   if (player_fixture.HasAudio()) {
-    samples_to_write = std::max(
-        samples_to_write, SbPlayerGetMaximumNumberOfSamplesPerWrite(
-                              player_fixture.GetPlayer(), kSbMediaTypeAudio) +
-                              1);
+    samples_to_write = SbPlayerGetMaximumNumberOfSamplesPerWrite(
+                           player_fixture.GetPlayer(), kSbMediaTypeAudio) +
+                       1;
   }
   if (player_fixture.HasVideo()) {
     samples_to_write = std::max(
@@ -103,27 +114,279 @@
 
   GroupedSamples samples;
   if (player_fixture.HasAudio()) {
-    samples.AddAudioSamplesWithEOS(0, samples_to_write);
+    samples.AddAudioSamples(0, samples_to_write);
+    samples.AddAudioEOS();
   }
   if (player_fixture.HasVideo()) {
-    samples.AddVideoSamplesWithEOS(0, samples_to_write);
+    samples.AddVideoSamples(0, samples_to_write);
+    samples.AddVideoEOS();
   }
 
   ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
   ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
 }
 
+TEST_P(SbPlayerWriteSampleTest, LimitedAudioInput) {
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+
+  // TODO: we simply set audio write duration to 0.5 second. Ideally, we should
+  // set the audio write duration to 10 seconds if audio connectors are remote.
+  player_fixture.SetAudioWriteDuration(kSbTimeSecond / 2);
+
+  GroupedSamples samples;
+  if (player_fixture.HasAudio()) {
+    samples.AddAudioSamples(
+        0, player_fixture.ConvertDurationToAudioBufferCount(kSbTimeSecond));
+    samples.AddAudioEOS();
+  }
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(
+        0, player_fixture.ConvertDurationToVideoBufferCount(kSbTimeSecond));
+    samples.AddVideoEOS();
+  }
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+}
+
+TEST_P(SbPlayerWriteSampleTest, PartialAudio) {
+  if (!IsPartialAudioSupported()) {
+    // TODO: Use GTEST_SKIP when we have a newer version of gtest.
+    SB_LOG(INFO)
+        << "The platform doesn't support partial audio. Skip the tests.";
+    return;
+  }
+
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+  if (!player_fixture.HasAudio()) {
+    // TODO: Use GTEST_SKIP when we have a newer version of gtest.
+    SB_LOG(INFO) << "Skip PartialAudio test for audioless content.";
+    return;
+  }
+
+  const SbTime kDurationToPlay = kSbTimeSecond;
+  const float kSegmentSize = 0.1f;
+
+  GroupedSamples samples;
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(
+        0, player_fixture.ConvertDurationToVideoBufferCount(kDurationToPlay));
+    samples.AddVideoEOS();
+  }
+
+  int total_buffers_to_write =
+      player_fixture.ConvertDurationToAudioBufferCount(kDurationToPlay);
+  for (int i = 0; i < total_buffers_to_write; i++) {
+    SbTime current_timestamp = player_fixture.GetAudioSampleTimestamp(i);
+    SbTime next_timestamp = player_fixture.GetAudioSampleTimestamp(i + 1);
+    SbTime buffer_duration = next_timestamp - current_timestamp;
+    SbTime segment_duration = buffer_duration * kSegmentSize;
+    SbTime written_duration = 0;
+    while (written_duration < buffer_duration) {
+      samples.AddAudioSamples(
+          i, 1, written_duration, written_duration,
+          std::max<int64_t>(
+              0, buffer_duration - written_duration - segment_duration));
+      written_duration += segment_duration;
+    }
+  }
+  samples.AddAudioEOS();
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting());
+
+  SbTime start_system_time = SbTimeGetMonotonicNow();
+  SbTime start_media_time = player_fixture.GetCurrentMediaTime();
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+
+  SbTime end_system_time = SbTimeGetMonotonicNow();
+  SbTime end_media_time = player_fixture.GetCurrentMediaTime();
+
+  const SbTime kDurationDifferenceAllowance = 500 * kSbTimeMillisecond;
+  EXPECT_NEAR(end_media_time, kDurationToPlay, kDurationDifferenceAllowance);
+  EXPECT_NEAR(end_system_time - start_system_time + start_media_time,
+              kDurationToPlay, kDurationDifferenceAllowance);
+
+  SB_DLOG(INFO) << "The expected media time should be " << kDurationToPlay
+                << ", the actual media time is " << end_media_time
+                << ", with difference "
+                << std::abs(end_media_time - kDurationToPlay) << ".";
+  SB_DLOG(INFO) << "The expected total playing time should be "
+                << kDurationToPlay << ", the actual playing time is "
+                << end_system_time - start_system_time + start_media_time
+                << ", with difference "
+                << std::abs(end_system_time - start_system_time +
+                            start_media_time - kDurationToPlay)
+                << ".";
+}
+
+TEST_P(SbPlayerWriteSampleTest, PartialAudioDiscardAll) {
+  if (!IsPartialAudioSupported()) {
+    // TODO: Use GTEST_SKIP when we have a newer version of gtest.
+    SB_LOG(INFO)
+        << "The platform doesn't support partial audio. Skip the tests.";
+    return;
+  }
+
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+  if (!player_fixture.HasAudio()) {
+    // TODO: Use GTEST_SKIP when we have a newer version of gtest.
+    SB_LOG(INFO) << "Skip PartialAudio test for audioless content.";
+    return;
+  }
+
+  const SbTime kDurationToPlay = kSbTimeSecond;
+  const SbTime kDurationPerWrite = 100 * kSbTimeMillisecond;
+  const SbTime kNumberOfBuffersToDiscard = 20;
+
+  GroupedSamples samples;
+  if (player_fixture.HasVideo()) {
+    samples.AddVideoSamples(
+        0, player_fixture.ConvertDurationToVideoBufferCount(kDurationToPlay));
+    samples.AddVideoEOS();
+  }
+
+  int written_buffer_index = 0;
+  SbTime current_time_offset = 0;
+  int num_of_buffers_per_write =
+      player_fixture.ConvertDurationToAudioBufferCount(kDurationPerWrite);
+  while (current_time_offset < kDurationToPlay) {
+    // Discard from front.
+    for (int i = 0; i < kNumberOfBuffersToDiscard; i++) {
+      samples.AddAudioSamples(written_buffer_index, 1, current_time_offset,
+                              kSbTimeSecond, 0);
+    }
+
+    samples.AddAudioSamples(written_buffer_index, num_of_buffers_per_write);
+    written_buffer_index += num_of_buffers_per_write;
+    current_time_offset += kDurationPerWrite;
+
+    // Discard from back.
+    for (int i = 0; i < kNumberOfBuffersToDiscard; i++) {
+      samples.AddAudioSamples(written_buffer_index, 1, current_time_offset, 0,
+                              kSbTimeSecond);
+    }
+  }
+  samples.AddAudioEOS();
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting());
+
+  SbTime start_system_time = SbTimeGetMonotonicNow();
+  SbTime start_media_time = player_fixture.GetCurrentMediaTime();
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+
+  SbTime end_system_time = SbTimeGetMonotonicNow();
+  SbTime end_media_time = player_fixture.GetCurrentMediaTime();
+
+  const SbTime kDurationDifferenceAllowance = 500 * kSbTimeMillisecond;
+  SbTime total_written_duration =
+      player_fixture.GetAudioSampleTimestamp(written_buffer_index);
+  EXPECT_NEAR(end_media_time, total_written_duration,
+              kDurationDifferenceAllowance);
+  EXPECT_NEAR(end_system_time - start_system_time + start_media_time,
+              total_written_duration, kDurationDifferenceAllowance);
+
+  SB_DLOG(INFO) << "The expected media time should be "
+                << total_written_duration << ", the actual media time is "
+                << end_media_time << ", with difference "
+                << std::abs(end_media_time - total_written_duration) << ".";
+  SB_DLOG(INFO) << "The expected total playing time should be "
+                << total_written_duration << ", the actual playing time is "
+                << end_system_time - start_system_time + start_media_time
+                << ", with difference "
+                << std::abs(end_system_time - start_system_time +
+                            start_media_time - total_written_duration)
+                << ".";
+}
+
+class SecondaryPlayerTestThread : public AbstractTestThread {
+ public:
+  SecondaryPlayerTestThread(
+      const SbPlayerTestConfig& config,
+      FakeGraphicsContextProvider* fake_graphics_context_provider)
+      : config_(config),
+        fake_graphics_context_provider_(fake_graphics_context_provider) {}
+
+  void Run() override {
+    SbPlayerTestFixture player_fixture(config_,
+                                       fake_graphics_context_provider_);
+    if (::testing::Test::HasFatalFailure()) {
+      return;
+    }
+
+    const SbTime kDurationToPlay = kSbTimeMillisecond * 200;
+
+    GroupedSamples samples;
+    if (player_fixture.HasAudio()) {
+      samples.AddAudioSamples(
+          0, player_fixture.ConvertDurationToAudioBufferCount(kDurationToPlay));
+      samples.AddAudioEOS();
+    }
+    if (player_fixture.HasVideo()) {
+      samples.AddVideoSamples(
+          0, player_fixture.ConvertDurationToVideoBufferCount(kDurationToPlay));
+      samples.AddVideoEOS();
+    }
+
+    ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+    ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+  }
+
+ private:
+  const SbPlayerTestConfig config_;
+  FakeGraphicsContextProvider* fake_graphics_context_provider_;
+};
+
+TEST_P(SbPlayerWriteSampleTest, SecondaryPlayerTest) {
+  // The secondary player should at least support h264 at 480p, 30fps and with
+  // a drm system.
+  const char* kMaxVideoCapabilities = "width=640; height=480; framerate=30;";
+  const char* kSecondaryTestFile = "beneath_the_canopy_135_avc.dmp";
+  const char* key_system = GetParam().key_system;
+
+  SbPlayerTestConfig secondary_player_config(nullptr, kSecondaryTestFile,
+                                             kSbPlayerOutputModeInvalid,
+                                             key_system, kMaxVideoCapabilities);
+  PlayerCreationParam creation_param =
+      CreatePlayerCreationParam(secondary_player_config);
+  secondary_player_config.output_mode = GetPreferredOutputMode(creation_param);
+
+  ASSERT_NE(secondary_player_config.output_mode, kSbPlayerOutputModeInvalid);
+
+  SecondaryPlayerTestThread primary_player_thread(
+      GetParam(), &fake_graphics_context_provider_);
+  SecondaryPlayerTestThread secondary_player_thread(
+      secondary_player_config, &fake_graphics_context_provider_);
+
+  primary_player_thread.Start();
+  secondary_player_thread.Start();
+
+  primary_player_thread.Join();
+  secondary_player_thread.Join();
+}
+
 std::vector<SbPlayerTestConfig> GetSupportedTestConfigs() {
   static std::vector<SbPlayerTestConfig> supported_configs;
   if (supported_configs.size() > 0) {
     return supported_configs;
   }
 
-  std::vector<const char*> key_systems;
-  key_systems.push_back("");
-  key_systems.insert(key_systems.end(), kKeySystems,
-                     kKeySystems + SB_ARRAY_SIZE_INT(kKeySystems));
-
+  const std::vector<const char*>& key_systems = GetKeySystems();
   for (auto key_system : key_systems) {
     std::vector<SbPlayerTestConfig> configs =
         GetSupportedSbPlayerTestConfigs(key_system);
@@ -133,30 +396,10 @@
   return supported_configs;
 }
 
-std::string GetTestConfigName(
-    ::testing::TestParamInfo<SbPlayerTestConfig> info) {
-  const SbPlayerTestConfig& config = info.param;
-  const char* audio_filename = std::get<0>(config);
-  const char* video_filename = std::get<1>(config);
-  const SbPlayerOutputMode output_mode = std::get<2>(config);
-  const char* key_system = std::get<3>(config);
-  std::string name(FormatString(
-      "audio_%s_video_%s_output_%s_key_system_%s",
-      audio_filename && strlen(audio_filename) > 0 ? audio_filename : "null",
-      video_filename && strlen(video_filename) > 0 ? video_filename : "null",
-      output_mode == kSbPlayerOutputModeDecodeToTexture ? "decode_to_texture"
-                                                        : "punch_out",
-      strlen(key_system) > 0 ? key_system : "null"));
-  std::replace(name.begin(), name.end(), '.', '_');
-  std::replace(name.begin(), name.end(), '(', '_');
-  std::replace(name.begin(), name.end(), ')', '_');
-  return name;
-}
-
 INSTANTIATE_TEST_CASE_P(SbPlayerWriteSampleTests,
                         SbPlayerWriteSampleTest,
                         ValuesIn(GetSupportedTestConfigs()),
-                        GetTestConfigName);
+                        GetSbPlayerTestConfigName);
 
 }  // namespace
 }  // namespace nplb
diff --git a/starboard/nplb/socket_waiter_wait_test.cc b/starboard/nplb/socket_waiter_wait_test.cc
index 53743e2..5e94c54 100644
--- a/starboard/nplb/socket_waiter_wait_test.cc
+++ b/starboard/nplb/socket_waiter_wait_test.cc
@@ -27,6 +27,7 @@
 namespace nplb {
 namespace {
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SbSocketWaiterWaitTest);
 class SbSocketWaiterWaitTest
     : public ::testing::TestWithParam<SbSocketAddressType> {
  public:
diff --git a/starboard/nplb/socket_waiter_wait_timed_test.cc b/starboard/nplb/socket_waiter_wait_timed_test.cc
index 7541bef..692454d 100644
--- a/starboard/nplb/socket_waiter_wait_timed_test.cc
+++ b/starboard/nplb/socket_waiter_wait_timed_test.cc
@@ -25,6 +25,7 @@
 namespace nplb {
 namespace {
 
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SbSocketWaiterWaitTimedTest);
 class SbSocketWaiterWaitTimedTest
     : public ::testing::TestWithParam<SbSocketAddressType> {
  public:
diff --git a/starboard/nplb/vertical_video_test.cc b/starboard/nplb/vertical_video_test.cc
new file mode 100644
index 0000000..5427aeb
--- /dev/null
+++ b/starboard/nplb/vertical_video_test.cc
@@ -0,0 +1,167 @@
+// Copyright 2023 The Cobalt Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "starboard/common/log.h"
+#include "starboard/media.h"
+#include "starboard/nplb/player_test_fixture.h"
+#include "starboard/nplb/player_test_util.h"
+#include "starboard/player.h"
+#include "starboard/shared/starboard/player/video_dmp_reader.h"
+#include "starboard/testing/fake_graphics_context_provider.h"
+#include "starboard/time.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace starboard {
+namespace nplb {
+namespace {
+
+using shared::starboard::player::video_dmp::VideoDmpReader;
+using ::testing::ValuesIn;
+
+typedef SbPlayerTestFixture::GroupedSamples GroupedSamples;
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(VerticalVideoTest);
+class VerticalVideoTest : public ::testing::TestWithParam<SbPlayerTestConfig> {
+ protected:
+  testing::FakeGraphicsContextProvider fake_graphics_context_provider_;
+};
+
+void CheckVerticalResolutionSupport(const char* mime) {
+  SB_LOG_IF(WARNING, SbMediaCanPlayMimeAndKeySystem(mime, "") !=
+                         kSbMediaSupportTypeProbably)
+      << "Vertical video (" << mime
+      << ") should be supported on this platform.";
+}
+
+std::vector<SbPlayerTestConfig> GetVerticalVideoTestConfigs() {
+  const char* kVideoFilenames[] = {"vertical_1080p_30_fps_137_avc.dmp",
+                                   "vertical_4k_30_fps_313_vp9.dmp",
+                                   "vertical_8k_30_fps_571_av1.dmp"};
+  const char* kAudioFilename = "silence_aac_stereo.dmp";
+
+  const SbPlayerOutputMode kOutputModes[] = {kSbPlayerOutputModeDecodeToTexture,
+                                             kSbPlayerOutputModePunchOut};
+
+  std::vector<const char*> video_files;
+  for (auto video_filename : kVideoFilenames) {
+    VideoDmpReader video_dmp_reader(video_filename,
+                                    VideoDmpReader::kEnableReadOnDemand);
+    SB_DCHECK(video_dmp_reader.number_of_video_buffers() > 0);
+    if (SbMediaCanPlayMimeAndKeySystem(
+            video_dmp_reader.video_mime_type().c_str(), "")) {
+      video_files.push_back(video_filename);
+    }
+  }
+
+  VideoDmpReader audio_dmp_reader(kAudioFilename,
+                                  VideoDmpReader::kEnableReadOnDemand);
+  SbMediaAudioCodec audio_codec = audio_dmp_reader.audio_codec();
+
+  std::vector<SbPlayerTestConfig> test_configs;
+  for (auto video_filename : video_files) {
+    SbMediaVideoCodec video_codec = kSbMediaVideoCodecNone;
+    VideoDmpReader video_dmp_reader(video_filename,
+                                    VideoDmpReader::kEnableReadOnDemand);
+    video_codec = video_dmp_reader.video_codec();
+
+    for (auto output_mode : kOutputModes) {
+      if (IsOutputModeSupported(output_mode, audio_codec, video_codec, "")) {
+        test_configs.emplace_back(kAudioFilename, video_filename, output_mode,
+                                  "");
+      }
+    }
+  }
+
+  return test_configs;
+}
+
+TEST(VerticalVideoTest, CapabilityQuery) {
+  SbMediaSupportType support = SbMediaCanPlayMimeAndKeySystem(
+      "video/mp4; codecs=\"avc1.4d002a\"; width=1920; height=1080", "");
+  if (support == kSbMediaSupportTypeProbably) {
+    CheckVerticalResolutionSupport(
+        "video/mp4; codecs=\"avc1.4d002a\"; width=608; height=1080");
+  }
+
+  support = SbMediaCanPlayMimeAndKeySystem(
+      "video/webm; codecs=\"vp9\"; width=2560; height=1440", "");
+  if (support == kSbMediaSupportTypeProbably) {
+    CheckVerticalResolutionSupport(
+        "video/webm; codecs=\"vp9\"; width=810; height=1440");
+  }
+
+  support = SbMediaCanPlayMimeAndKeySystem(
+      "video/webm; codecs=\"vp9\"; width=3840; height=2160", "");
+  if (support == kSbMediaSupportTypeProbably) {
+    CheckVerticalResolutionSupport(
+        "video/webm; codecs=\"vp9\"; width=1215; height=2160");
+  }
+
+  support = SbMediaCanPlayMimeAndKeySystem(
+      "video/mp4; codecs=\"av01.0.16M.08\"; width=7680; height=4320", "");
+  if (support == kSbMediaSupportTypeProbably) {
+    CheckVerticalResolutionSupport(
+        "video/mp4; codecs=\"av01.0.16M.08\"; width=2430; height=4320");
+  }
+}
+
+TEST_P(VerticalVideoTest, WriteSamples) {
+  SbPlayerTestFixture player_fixture(GetParam(),
+                                     &fake_graphics_context_provider_);
+  if (HasFatalFailure()) {
+    return;
+  }
+
+  SB_DCHECK(player_fixture.HasVideo());
+  SB_DCHECK(player_fixture.HasAudio());
+
+  int audio_samples_to_write = player_fixture.ConvertDurationToAudioBufferCount(
+      200 * kSbTimeMillisecond);
+  int video_samples_to_write = player_fixture.ConvertDurationToVideoBufferCount(
+      200 * kSbTimeMillisecond);
+
+  GroupedSamples samples;
+  samples.AddVideoSamples(0, audio_samples_to_write);
+  samples.AddVideoEOS();
+  samples.AddAudioSamples(0, video_samples_to_write);
+  samples.AddAudioEOS();
+
+  ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples));
+  ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream());
+}
+
+std::vector<SbPlayerTestConfig> GetSupportedTestConfigs() {
+  static std::vector<SbPlayerTestConfig> supported_configs;
+  if (supported_configs.size() > 0) {
+    return supported_configs;
+  }
+
+  std::vector<SbPlayerTestConfig> configs = GetVerticalVideoTestConfigs();
+  supported_configs.insert(supported_configs.end(), configs.begin(),
+                           configs.end());
+  return supported_configs;
+}
+
+INSTANTIATE_TEST_SUITE_P(VerticalVideoTests,
+                         VerticalVideoTest,
+                         ValuesIn(GetSupportedTestConfigs()),
+                         GetSbPlayerTestConfigName);
+
+}  // namespace
+}  // namespace nplb
+}  // namespace starboard
diff --git a/starboard/player.h b/starboard/player.h
index 32b7309..abf17a6 100644
--- a/starboard/player.h
+++ b/starboard/player.h
@@ -668,7 +668,9 @@
 //       issues occur (such as transient or indefinite hanging).
 //
 // The audio configurations should be available as soon as possible, and they
-// have to be available when the |player| is at `kSbPlayerStatePresenting`.
+// have to be available when the |player| is at `kSbPlayerStatePresenting`,
+// unless the audio codec is |kSbMediaAudioCodecNone| or there's no written
+// audio inputs.
 //
 // The app will set |audio_write_duration| to `kSbPlayerWriteDurationLocal`
 // when the audio configuration isn't available (i.e. the function returns false
@@ -676,10 +678,10 @@
 // available immediately after the SbPlayer is created, if it expects the app to
 // treat the platform as using wireless audio outputs.
 //
-// Once at least one audio configurations are returned, the return values
-// shouldn't change during the life time of |player|.  The platform may inform
-// the app of any changes by sending `kSbPlayerErrorCapabilityChanged` to
-// request a playback restart.
+// Once at least one audio configurations are returned, the return values and
+// their orders shouldn't change during the life time of |player|.  The platform
+// may inform the app of any changes by sending
+// `kSbPlayerErrorCapabilityChanged` to request a playback restart.
 //
 // |player|: The player about which information is being retrieved. Must not be
 //   |kSbPlayerInvalid|.
diff --git a/starboard/raspi/2/toolchain/BUILD.gn b/starboard/raspi/2/toolchain/BUILD.gn
index 0993e86..dcce760 100644
--- a/starboard/raspi/2/toolchain/BUILD.gn
+++ b/starboard/raspi/2/toolchain/BUILD.gn
@@ -23,7 +23,7 @@
   # We use whatever 'ar' resolves to.
   ar = gcc_toolchain_ar
 
-  tail_lib_dependencies = "-l:libpthread.so.0"
+  tail_lib_dependencies = "-l:libpthread.so.0 -l:libdl.so.2"
 
   toolchain_args = {
     is_clang = false
@@ -38,7 +38,7 @@
   # We use whatever 'ar' resolves to.
   ar = gcc_toolchain_ar
 
-  tail_lib_dependencies = "-l:libpthread.so.0"
+  tail_lib_dependencies = "-l:libpthread.so.0 -l:libdl.so.2"
 
   toolchain_args = {
     is_starboard = false
diff --git a/starboard/raspi/shared/BUILD.gn b/starboard/raspi/shared/BUILD.gn
index 29c056d..3a4b331 100644
--- a/starboard/raspi/shared/BUILD.gn
+++ b/starboard/raspi/shared/BUILD.gn
@@ -354,7 +354,7 @@
     ":starboard_base_symbolize",
     "//starboard:starboard_headers_only",
     "//starboard/common",
-    "//starboard/shared/ffmpeg:ffmpeg_linked",
+    "//starboard/shared/ffmpeg:ffmpeg_dynamic_load",
     "//starboard/shared/starboard/media:media_util",
     "//starboard/shared/starboard/player/filter:filter_based_player_sources",
   ]
diff --git a/starboard/raspi/shared/configuration_public.h b/starboard/raspi/shared/configuration_public.h
index 3c9ed64..af8fd77 100644
--- a/starboard/raspi/shared/configuration_public.h
+++ b/starboard/raspi/shared/configuration_public.h
@@ -102,11 +102,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 1
diff --git a/starboard/raspi/shared/platform_configuration/BUILD.gn b/starboard/raspi/shared/platform_configuration/BUILD.gn
index fff6fe8..b1c930e 100644
--- a/starboard/raspi/shared/platform_configuration/BUILD.gn
+++ b/starboard/raspi/shared/platform_configuration/BUILD.gn
@@ -123,9 +123,7 @@
 config("platform_configuration") {
   libs = [
     "asound",
-    "avcodec",
-    "avformat",
-    "avutil",
+    "dl",
     "pthread",
     "rt",
     "openmaxil",
diff --git a/starboard/raspi/shared/test_filters.py b/starboard/raspi/shared/test_filters.py
index 9e8e146..d031a5d 100644
--- a/starboard/raspi/shared/test_filters.py
+++ b/starboard/raspi/shared/test_filters.py
@@ -23,14 +23,21 @@
         # Permanently filter out drm system related tests as raspi doesn't
         # support any drm systems and there is no plan to implement such
         # support.
+        'MultiplePlayerTests*',
         'SbDrmTest.AnySupportedKeySystems',
         'SbMediaCanPlayMimeAndKeySystem.AnySupportedKeySystems',
         'SbMediaCanPlayMimeAndKeySystem.KeySystemWithAttributes',
         'SbMediaCanPlayMimeAndKeySystem.MinimumSupport',
         'SbMediaSetAudioWriteDurationTests/*',
+        'SbPlayerGetAudioConfigurationTests/*',
         'SbPlayerWriteSampleTests*',
         'SbUndefinedBehaviorTest.CallThisPointerIsNullRainyDay',
         'SbSystemGetPropertyTest.FLAKY_ReturnsRequired',
+        # Failure tracked by b/287666606.
+        'VerticalVideoTests/VerticalVideoTest.WriteSamples*',
+
+        # Enable once verified on the platform.
+        'SbMediaCanPlayMimeAndKeySystem.MinimumSupport',
     ],
     'player_filter_tests': [
         # The implementations for the raspberry pi (0 and 2) are incomplete
diff --git a/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.cc b/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.cc
index 8a7c898..877869e 100644
--- a/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.cc
+++ b/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.cc
@@ -207,6 +207,7 @@
     InitializeCodec();
   }
 
+  ScopedLock lock(decode_target_and_frames_mutex_);
   decltype(frames_) frames;
   frames_ = std::queue<scoped_refptr<CpuVideoFrame>>();
 }
@@ -310,6 +311,7 @@
 
   bool result = true;
   if (output_mode_ == kSbPlayerOutputModeDecodeToTexture) {
+    ScopedLock lock(decode_target_and_frames_mutex_);
     frames_.push(frame);
   }
 
@@ -396,7 +398,7 @@
   ffmpeg_->FreeFrame(&av_frame_);
 
   if (output_mode_ == kSbPlayerOutputModeDecodeToTexture) {
-    ScopedLock lock(decode_target_mutex_);
+    ScopedLock lock(decode_target_and_frames_mutex_);
     if (SbDecodeTargetIsValid(decode_target_)) {
       DecodeTargetRelease(decode_target_graphics_context_provider_,
                           decode_target_);
@@ -411,7 +413,7 @@
 
   // We must take a lock here since this function can be called from a
   // separate thread.
-  ScopedLock lock(decode_target_mutex_);
+  ScopedLock lock(decode_target_and_frames_mutex_);
   while (frames_.size() > 1 && frames_.front()->HasOneRef()) {
     frames_.pop();
   }
diff --git a/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h b/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h
index aa9faab..5f680e2 100644
--- a/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h
+++ b/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h
@@ -143,9 +143,8 @@
   // GetCurrentDecodeTarget() needs to be called from an arbitrary thread
   // to obtain the current decode target (which ultimately ends up being a
   // copy of |decode_target_|), we need to safe-guard access to |decode_target_|
-  // and we do so through this mutex.
-  Mutex decode_target_mutex_;
-  // Mutex frame_mutex_;
+  // and |frames_|, we do so through this mutex.
+  Mutex decode_target_and_frames_mutex_;
 
   // int frame_last_rendered_pts_;
   // scoped_refptr<VideoFrame> frame_;
diff --git a/starboard/shared/starboard/player/decoded_audio_internal.cc b/starboard/shared/starboard/player/decoded_audio_internal.cc
index 79952d7..2834bc2 100644
--- a/starboard/shared/starboard/player/decoded_audio_internal.cc
+++ b/starboard/shared/starboard/player/decoded_audio_internal.cc
@@ -149,8 +149,6 @@
   discarded_frames_from_front = std::min(discarded_frames_from_front, frames());
   offset_in_bytes_ += bytes_per_frame * discarded_frames_from_front;
   size_in_bytes_ -= bytes_per_frame * discarded_frames_from_front;
-  timestamp_ +=
-      media::AudioFramesToDuration(discarded_frames_from_front, sample_rate);
 
   auto discarded_frames_from_back =
       AudioDurationToFrames(discarded_duration_from_back, sample_rate);
diff --git a/starboard/shared/starboard/player/decoded_audio_test_internal.cc b/starboard/shared/starboard/player/decoded_audio_test_internal.cc
index a4eae16..a1e2cd2 100644
--- a/starboard/shared/starboard/player/decoded_audio_test_internal.cc
+++ b/starboard/shared/starboard/player/decoded_audio_test_internal.cc
@@ -286,19 +286,16 @@
           kSampleRate, quarter_duration, quarter_duration);
       ASSERT_NEAR(adjusted_decoded_audio->frames(),
                   original_decoded_audio->frames() / 2, 2);
-      ASSERT_NEAR(adjusted_decoded_audio->timestamp(),
-                  original_decoded_audio->timestamp() + quarter_duration,
-                  duration_of_one_frame * 2);
+      ASSERT_EQ(adjusted_decoded_audio->timestamp(),
+                original_decoded_audio->timestamp());
 
       adjusted_decoded_audio = original_decoded_audio->Clone();
       // Adjust more frames than it has from front
       adjusted_decoded_audio->AdjustForDiscardedDurations(
           kSampleRate, duration_of_decoded_audio * 2, 0);
       ASSERT_EQ(adjusted_decoded_audio->frames(), 0);
-      ASSERT_NEAR(
-          adjusted_decoded_audio->timestamp(),
-          original_decoded_audio->timestamp() + duration_of_decoded_audio,
-          duration_of_one_frame * 2);
+      ASSERT_EQ(adjusted_decoded_audio->timestamp(),
+                original_decoded_audio->timestamp());
 
       adjusted_decoded_audio = original_decoded_audio->Clone();
       // Adjust more frames than it has from back
diff --git a/starboard/shared/starboard/player/filter/adaptive_audio_decoder_internal.cc b/starboard/shared/starboard/player/filter/adaptive_audio_decoder_internal.cc
index 7f87b5d..7e74803 100644
--- a/starboard/shared/starboard/player/filter/adaptive_audio_decoder_internal.cc
+++ b/starboard/shared/starboard/player/filter/adaptive_audio_decoder_internal.cc
@@ -197,6 +197,12 @@
   int decoded_sample_rate;
   scoped_refptr<DecodedAudio> decoded_audio =
       audio_decoder_->Read(&decoded_sample_rate);
+
+  if (!decoded_audio->is_end_of_stream() && !decoded_audio->frames()) {
+    // Empty output doesn't need further process.
+    return;
+  }
+
   if (!first_output_received_) {
     first_output_received_ = true;
     output_sample_type_ = decoded_audio->sample_type();
diff --git a/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.cc b/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.cc
index 86f21eb..4ad94f1 100644
--- a/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.cc
+++ b/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.cc
@@ -235,6 +235,9 @@
 }
 
 bool InterleavedSincResampler::CanQueueBuffer() const {
+  // TODO(b/289102877): after support partial audio, each input buffer could
+  // have a small amount of frames. We should avoid using count of pending
+  // buffer here.
   if (pending_buffers_.empty()) {
     return true;
   }
diff --git a/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.h b/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.h
index 29974b0..2bf75db 100644
--- a/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.h
+++ b/starboard/shared/starboard/player/filter/interleaved_sinc_resampler.h
@@ -109,7 +109,7 @@
   static const int kBufferSize = kBlockSize + kKernelSize;
 
   // The maximum numbers of buffer can be queued.
-  static const int kMaximumPendingBuffers = 8;
+  static const int kMaximumPendingBuffers = 16;
 
   static const int kMaxChannels = 8;
   static const int kInputBufferSize = kMaxChannels * kBufferSize;
diff --git a/starboard/shared/starboard/player/filter/testing/BUILD.gn b/starboard/shared/starboard/player/filter/testing/BUILD.gn
index 176c1ed..80f2765 100644
--- a/starboard/shared/starboard/player/filter/testing/BUILD.gn
+++ b/starboard/shared/starboard/player/filter/testing/BUILD.gn
@@ -12,41 +12,44 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-target(gtest_target_type, "player_filter_tests") {
-  testonly = true
+if (current_toolchain == starboard_toolchain) {
+  target(starboard_level_gtest_target_type, "player_filter_tests") {
+    build_loader = false
+    testonly = true
 
-  sources = [
-    "//starboard/common/test_main.cc",
-    "//starboard/testing/fake_graphics_context_provider.cc",
-    "//starboard/testing/fake_graphics_context_provider.h",
-    "adaptive_audio_decoder_test.cc",
-    "audio_channel_layout_mixer_test.cc",
-    "audio_decoder_test.cc",
-    "audio_frame_discarder_test.cc",
-    "audio_renderer_internal_test.cc",
-    "file_cache_reader_test.cc",
-    "media_time_provider_impl_test.cc",
-    "player_components_test.cc",
-    "video_decoder_test.cc",
-    "video_decoder_test_fixture.cc",
-    "video_decoder_test_fixture.h",
-    "video_frame_cadence_pattern_generator_test.cc",
-    "video_frame_rate_estimator_test.cc",
-  ]
+    sources = [
+      "//starboard/common/test_main.cc",
+      "//starboard/testing/fake_graphics_context_provider.cc",
+      "//starboard/testing/fake_graphics_context_provider.h",
+      "adaptive_audio_decoder_test.cc",
+      "audio_channel_layout_mixer_test.cc",
+      "audio_decoder_test.cc",
+      "audio_frame_discarder_test.cc",
+      "audio_renderer_internal_test.cc",
+      "file_cache_reader_test.cc",
+      "media_time_provider_impl_test.cc",
+      "player_components_test.cc",
+      "video_decoder_test.cc",
+      "video_decoder_test_fixture.cc",
+      "video_decoder_test_fixture.h",
+      "video_frame_cadence_pattern_generator_test.cc",
+      "video_frame_rate_estimator_test.cc",
+    ]
 
-  public_deps = [
-    ":test_util",
-    "//starboard/shared/starboard/media:media_util",
-    "//testing/gmock",
-  ]
+    public_deps = [
+      ":test_util",
+      "//starboard/shared/starboard/media:media_util",
+      "//testing/gmock",
+    ]
 
-  deps = cobalt_platform_dependencies
+    deps = cobalt_platform_dependencies
 
-  data_deps =
-      [ "//starboard/shared/starboard/player:player_download_test_data" ]
+    data_deps =
+        [ "//starboard/shared/starboard/player:player_download_test_data" ]
+  }
 }
 
-if (host_os != "win") {
+if (host_os != "win" && current_toolchain == starboard_toolchain) {
   target(final_executable_type, "player_filter_benchmarks") {
     testonly = true
 
@@ -81,7 +84,4 @@
     "//starboard/shared/starboard/player:video_dmp",
     "//testing/gtest",
   ]
-  if (gl_type != "none") {
-    public_deps += [ "//starboard/egl_and_gles" ]
-  }
 }
diff --git a/starboard/shared/starboard/player/filter/testing/player_components_test.cc b/starboard/shared/starboard/player/filter/testing/player_components_test.cc
index d57c269..0e3b3ad 100644
--- a/starboard/shared/starboard/player/filter/testing/player_components_test.cc
+++ b/starboard/shared/starboard/player/filter/testing/player_components_test.cc
@@ -382,8 +382,8 @@
   // working.
   void RenderAndProcessPendingJobs() {
     // Call GetCurrentDecodeTarget() periodically for decode to texture mode.
-    if (output_mode_ == kSbPlayerOutputModeDecodeToTexture &&
-        GetVideoRenderer()) {
+    // Or call fake rendering to force renderer go on in punch-out mode.
+    if (GetVideoRenderer()) {
 #if SB_HAS(GLES2)
       fake_graphics_context_provider_.RunOnGlesContextThread(
           std::bind(&PlayerComponentsTest::RenderOnGlesContextThread, this));
@@ -441,7 +441,11 @@
   }
 
   void RenderOnGlesContextThread() {
-    SbDecodeTargetRelease(GetVideoRenderer()->GetCurrentDecodeTarget());
+    if (output_mode_ == kSbPlayerOutputModeDecodeToTexture) {
+      SbDecodeTargetRelease(GetVideoRenderer()->GetCurrentDecodeTarget());
+    } else {
+      fake_graphics_context_provider_.Render();
+    }
   }
 
   bool TryToWriteOneInputBuffer(SbTime max_timestamp) {
diff --git a/starboard/shared/starboard/player/filter/testing/test_util.cc b/starboard/shared/starboard/player/filter/testing/test_util.cc
index 25ad281..39ae17d 100644
--- a/starboard/shared/starboard/player/filter/testing/test_util.cc
+++ b/starboard/shared/starboard/player/filter/testing/test_util.cc
@@ -181,14 +181,32 @@
       const auto& video_stream_info = dmp_reader.video_stream_info();
       const std::string video_mime = dmp_reader.video_mime_type();
       const MimeType video_mime_type(video_mime.c_str());
-      if (SbMediaIsVideoSupported(
-              dmp_reader.video_codec(),
-              video_mime.size() > 0 ? &video_mime_type : nullptr, -1, -1, 8,
-              kSbMediaPrimaryIdUnspecified, kSbMediaTransferIdUnspecified,
-              kSbMediaMatrixIdUnspecified, video_stream_info.frame_width,
-              video_stream_info.frame_height, dmp_reader.video_bitrate(),
-              dmp_reader.video_fps(), false)) {
-        test_params.push_back(std::make_tuple(filename, output_mode));
+      // SbMediaIsVideoSupported may return false for gpu based decoder that in
+      // fact supports av1 or/and vp9 because the system can make async
+      // initialization at startup.
+      // To minimize probability of false negative we check result few times
+      static bool decoder_has_been_checked_once = false;
+      int counter = 5;
+      const SbMediaVideoCodec video_codec = dmp_reader.video_codec();
+      bool need_to_check_with_wait = video_codec == kSbMediaVideoCodecAv1 ||
+                                     video_codec == kSbMediaVideoCodecVp9;
+      do {
+        if (SbMediaIsVideoSupported(
+                video_codec, video_mime.size() > 0 ? &video_mime_type : nullptr,
+                -1, -1, 8, kSbMediaPrimaryIdUnspecified,
+                kSbMediaTransferIdUnspecified, kSbMediaMatrixIdUnspecified,
+                video_stream_info.frame_width, video_stream_info.frame_height,
+                dmp_reader.video_bitrate(), dmp_reader.video_fps(), false)) {
+          test_params.push_back(std::make_tuple(filename, output_mode));
+          break;
+        } else if (need_to_check_with_wait && !decoder_has_been_checked_once) {
+          SbThreadSleep(kSbTimeSecond);
+        } else {
+          break;
+        }
+      } while (--counter);
+      if (need_to_check_with_wait) {
+        decoder_has_been_checked_once = true;
       }
     }
   }
diff --git a/starboard/shared/starboard/player/filter/tools/BUILD.gn b/starboard/shared/starboard/player/filter/tools/BUILD.gn
index 6357dab..b2d0a78 100644
--- a/starboard/shared/starboard/player/filter/tools/BUILD.gn
+++ b/starboard/shared/starboard/player/filter/tools/BUILD.gn
@@ -12,18 +12,21 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-target(final_executable_type, "audio_dmp_player") {
-  sources = [ "audio_dmp_player.cc" ]
-  configs += [ "//starboard/build/config:starboard_implementation" ]
-  public_deps = [
-    "//starboard",
-    "//starboard/shared/starboard/media:media_util",
-    "//starboard/shared/starboard/player:player_download_test_data",
-    "//starboard/shared/starboard/player:video_dmp",
-  ]
-  data_deps = [
-    "//cobalt/network:copy_ssl_certificates",
-    "//starboard/shared/starboard/player:player_download_test_data",
-    "//third_party/icu:icudata",
-  ]
+if (current_toolchain == starboard_toolchain) {
+  target(starboard_level_final_executable_type, "audio_dmp_player") {
+    build_loader = false
+    sources = [ "audio_dmp_player.cc" ]
+    configs += [ "//starboard/build/config:starboard_implementation" ]
+    public_deps = [
+      "//starboard",
+      "//starboard/shared/starboard/media:media_util",
+      "//starboard/shared/starboard/player:player_download_test_data",
+      "//starboard/shared/starboard/player:video_dmp",
+    ]
+    data_deps = [
+      "//cobalt/network:copy_ssl_certificates",
+      "//starboard/shared/starboard/player:player_download_test_data",
+      "//third_party/icu:icudata",
+    ]
+  }
 }
diff --git a/starboard/shared/starboard/player/player_internal.h b/starboard/shared/starboard/player/player_internal.h
index da9cd8c..a43e030 100644
--- a/starboard/shared/starboard/player/player_internal.h
+++ b/starboard/shared/starboard/player/player_internal.h
@@ -47,8 +47,6 @@
       void* context,
       starboard::scoped_ptr<PlayerWorker::Handler> player_worker_handler);
 
-  static int number_of_players() { return number_of_players_; }
-
   void Seek(SbTime seek_to_time, int ticket);
   template <typename PlayerSampleInfo>
   void WriteSamples(const PlayerSampleInfo* sample_infos,
diff --git a/starboard/shared/starboard/player/testdata/sha1_files.gni b/starboard/shared/starboard/player/testdata/sha1_files.gni
index f922d4c..2b3bb46 100644
--- a/starboard/shared/starboard/player/testdata/sha1_files.gni
+++ b/starboard/shared/starboard/player/testdata/sha1_files.gni
@@ -25,7 +25,11 @@
   "beneath_the_canopy_opus_stereo.dmp.sha1",
   "black_test_avc_1080p_30to60_fps.dmp.sha1",
   "heaac.dmp.sha1",
+  "silence_aac_stereo.dmp.sha1",
   "sintel_329_ec3.dmp.sha1",
   "sintel_381_ac3.dmp.sha1",
   "sintel_399_av1.dmp.sha1",
+  "vertical_4k_30_fps_313_vp9.dmp.sha1",
+  "vertical_8k_30_fps_571_av1.dmp.sha1",
+  "vertical_1080p_30_fps_137_avc.dmp.sha1",
 ]
diff --git a/starboard/shared/starboard/player/testdata/silence_aac_stereo.dmp.sha1 b/starboard/shared/starboard/player/testdata/silence_aac_stereo.dmp.sha1
new file mode 100644
index 0000000..9d31274
--- /dev/null
+++ b/starboard/shared/starboard/player/testdata/silence_aac_stereo.dmp.sha1
@@ -0,0 +1 @@
+a4e1cc998dd27018aaa3d247c6316b248be2bbcb
diff --git a/starboard/shared/starboard/player/testdata/vertical_1080p_30_fps_137_avc.dmp.sha1 b/starboard/shared/starboard/player/testdata/vertical_1080p_30_fps_137_avc.dmp.sha1
new file mode 100644
index 0000000..4b0461b
--- /dev/null
+++ b/starboard/shared/starboard/player/testdata/vertical_1080p_30_fps_137_avc.dmp.sha1
@@ -0,0 +1 @@
+9a6a0747a9b9669ccade0ad36c8582f7a74a59f2
diff --git a/starboard/shared/starboard/player/testdata/vertical_4k_30_fps_313_vp9.dmp.sha1 b/starboard/shared/starboard/player/testdata/vertical_4k_30_fps_313_vp9.dmp.sha1
new file mode 100644
index 0000000..4be2726
--- /dev/null
+++ b/starboard/shared/starboard/player/testdata/vertical_4k_30_fps_313_vp9.dmp.sha1
@@ -0,0 +1 @@
+09568d08a3611271c2bde94fef610bfc88862961
diff --git a/starboard/shared/starboard/player/testdata/vertical_8k_30_fps_571_av1.dmp.sha1 b/starboard/shared/starboard/player/testdata/vertical_8k_30_fps_571_av1.dmp.sha1
new file mode 100644
index 0000000..6e2f715
--- /dev/null
+++ b/starboard/shared/starboard/player/testdata/vertical_8k_30_fps_571_av1.dmp.sha1
@@ -0,0 +1 @@
+461c333fdda619c5ac5df1d2ed4fdc5d75e604d4
diff --git a/starboard/shared/starboard/queue_application.cc b/starboard/shared/starboard/queue_application.cc
index 08550a8..b628977 100644
--- a/starboard/shared/starboard/queue_application.cc
+++ b/starboard/shared/starboard/queue_application.cc
@@ -14,7 +14,7 @@
 
 #include "starboard/shared/starboard/queue_application.h"
 
-#include "starboard/atomic.h"
+#include "starboard/common/atomic.h"
 #include "starboard/common/condition_variable.h"
 #include "starboard/common/log.h"
 #include "starboard/event.h"
@@ -24,14 +24,6 @@
 namespace shared {
 namespace starboard {
 
-namespace {
-void SetTrueWhenCalled(void* flag) {
-  volatile bool* bool_flag =
-      const_cast<volatile bool*>(static_cast<bool*>(flag));
-  *bool_flag = true;
-}
-}  // namespace
-
 void QueueApplication::Wake() {
   if (IsCurrentThread()) {
     return;
@@ -100,11 +92,15 @@
 
 void QueueApplication::InjectAndProcess(SbEventType type,
                                         bool checkSystemEvents) {
-  volatile bool event_processed = false;
-  Event* flagged_event =
-      new Event(type, const_cast<bool*>(&event_processed), &SetTrueWhenCalled);
+  atomic_bool event_processed;
+  Event* flagged_event = new Event(
+      type, const_cast<atomic_bool*>(&event_processed), [](void* flag) {
+        auto* bool_flag =
+            const_cast<atomic_bool*>(static_cast<atomic_bool*>(flag));
+        bool_flag->store(true);
+      });
   Inject(flagged_event);
-  while (!event_processed) {
+  while (!event_processed.load()) {
     if (checkSystemEvents) {
       DispatchAndDelete(GetNextEvent());
     } else {
diff --git a/starboard/shared/win32/directory_internal.cc b/starboard/shared/win32/directory_internal.cc
index 7c2190a..0e665db 100644
--- a/starboard/shared/win32/directory_internal.cc
+++ b/starboard/shared/win32/directory_internal.cc
@@ -72,7 +72,9 @@
   WIN32_FILE_ATTRIBUTE_DATA attribute_data = {0};
   if (!GetFileAttributesExW(norm_dir_path.c_str(), GetFileExInfoStandard,
                             &attribute_data)) {
-    return false;
+    // If this is system folder GetFileAttributesExW returns FALSE
+    // but the folder exists
+    return GetLastError() == ERROR_ACCESS_DENIED;
   }
   return (attribute_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
 }
diff --git a/starboard/stub/configuration_public.h b/starboard/stub/configuration_public.h
index b9657c4..bcb6394 100644
--- a/starboard/stub/configuration_public.h
+++ b/starboard/stub/configuration_public.h
@@ -142,11 +142,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 0
diff --git a/starboard/testing/fake_graphics_context_provider.cc b/starboard/testing/fake_graphics_context_provider.cc
index b5716d8..7670f79 100644
--- a/starboard/testing/fake_graphics_context_provider.cc
+++ b/starboard/testing/fake_graphics_context_provider.cc
@@ -65,6 +65,12 @@
 
 #define EGL_CALL_SIMPLE(x) (EGL_CALL_PREFIX x)
 
+#define GL_CALL(x)                                                     \
+  do {                                                                 \
+    SbGetGlesInterface()->x;                                           \
+    SB_DCHECK((SbGetGlesInterface()->glGetError()) == SB_GL_NO_ERROR); \
+  } while (false)
+
 namespace starboard {
 namespace testing {
 
@@ -291,6 +297,11 @@
       eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
 }
 
+void FakeGraphicsContextProvider::Render() {
+  GL_CALL(glClear(SB_GL_COLOR_BUFFER_BIT));
+  EGL_CALL(eglSwapBuffers(display_, surface_));
+}
+
 void FakeGraphicsContextProvider::DestroyContext() {
   MakeNoContextCurrent();
   EGL_CALL_SIMPLE(eglDestroyContext(display_, context_));
diff --git a/starboard/testing/fake_graphics_context_provider.h b/starboard/testing/fake_graphics_context_provider.h
index 8b4c393..4bc9e0d 100644
--- a/starboard/testing/fake_graphics_context_provider.h
+++ b/starboard/testing/fake_graphics_context_provider.h
@@ -51,6 +51,8 @@
   void ReleaseDecodeTarget(SbDecodeTarget decode_target);
 #endif  // SB_HAS(GLES2)
 
+  void Render();
+
  private:
 #if SB_HAS(GLES2)
   static void* ThreadEntryPoint(void* context);
diff --git a/starboard/tools/abstract_launcher.py b/starboard/tools/abstract_launcher.py
index ff0ad61..ff361cf 100644
--- a/starboard/tools/abstract_launcher.py
+++ b/starboard/tools/abstract_launcher.py
@@ -113,7 +113,7 @@
     if not out_directory:
       out_directory = paths.BuildOutputDirectory(platform_name, config)
     self.out_directory = out_directory
-    self.coverage_directory = kwargs.get("coverage_directory", out_directory)
+    self.coverage_file_path = kwargs.get("coverage_file_path", None)
 
     output_file = kwargs.get("output_file", None)
     if not output_file:
diff --git a/starboard/tools/testing/test_coverage.py b/starboard/tools/testing/test_coverage.py
new file mode 100644
index 0000000..fd05bf6
--- /dev/null
+++ b/starboard/tools/testing/test_coverage.py
@@ -0,0 +1,186 @@
+#!/usr/bin/python
+#
+# Copyright 2023 The Cobalt Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Generate coverage reports from llvm coverage data."""
+
+import argparse
+import glob
+import logging
+import os
+import pathlib
+import subprocess
+
+from starboard.build import clang
+from starboard.tools import build
+from starboard.tools.util import SetupDefaultLoggingConfig
+
+SRC_DIR = os.path.join(
+    os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)
+
+
+def _get_raw_reports(test_binaries, coverage_dir):
+  """Get a list of raw coverage reports from the coverage directory."""
+  raw_reports = []
+  missing_reports = []
+  for target in test_binaries:
+    # Find coverage reports from the supplied test binaries.
+    profraw_file = os.path.join(coverage_dir, target + '.profraw')
+    if not os.path.isfile(profraw_file):
+      missing_reports.append(profraw_file)
+    else:
+      raw_reports.append(profraw_file)
+  else:
+    # If no test binaries were supplied we use all coverage data we find.
+    raw_reports = glob.glob(os.path.join(coverage_dir, '*.profraw'))
+
+  if missing_reports:
+    logging.error('Unable to find the following coverage files: %s.',
+                  ', '.join(missing_reports))
+  return raw_reports
+
+
+def _get_test_binary_paths(binaries_dir, test_binaries, coverage_dir):
+  if not test_binaries:
+    # Use the coverage files to deduce the paths if no binaries were specified.
+    raw_reports = _get_raw_reports(test_binaries, coverage_dir)
+    test_binaries = [pathlib.Path(report).stem for report in raw_reports]
+  return [os.path.join(binaries_dir, binary) for binary in test_binaries]
+
+
+def _get_exclude_opts():
+  """Get list of exclude options."""
+  # Get a list of all directories in the src root and exclude all but our code.
+  all_dirs = next(os.walk(SRC_DIR))[1]
+  include_dirs = ['cobalt', 'starboard']
+  exclude_dirs = [d for d in all_dirs if d not in include_dirs]
+  return [
+      r'--ignore-filename-regex=.*_test\.h$',
+      r'--ignore-filename-regex=.*_test\.cc$',
+      r'--ignore-filename-regex=.*_tests\.h$',
+      r'--ignore-filename-regex=.*_tests\.cc$',
+      r'--ignore-filename-regex=.*_test_fixture\.h$',
+      r'--ignore-filename-regex=.*_test_fixture\.cc$',
+      r'--ignore-filename-regex=.*_test_internal\.h$',
+      r'--ignore-filename-regex=.*_test_internal\.cc$',
+      r'--ignore-filename-regex=.*_test_util\.h$',
+      r'--ignore-filename-regex=.*_test_util\.cc$',
+      r'--ignore-filename-regex=.*_unittest\.h$',
+      r'--ignore-filename-regex=.*_unittest\.cc$',
+  ] + [f'--ignore-filename-regex={d}/.*' for d in exclude_dirs]
+
+
+def _generate_reports(target_paths, merged_data_path, report_dir, report_type):
+  """Generate reports based on the combined coverage data."""
+  toolchain_dir = build.GetClangBinPath(clang.GetClangSpecification())
+  llvm_cov = os.path.join(toolchain_dir, 'llvm-cov')
+
+  exclude_opts = _get_exclude_opts()
+  test_binary_opts = [target_paths[0]] + \
+    ['-object=' + target for target in target_paths[1:]]
+
+  if report_type in ['html', 'both']:
+    logging.info('Creating html coverage report')
+    show_cmd_list = [
+        llvm_cov, 'show', *exclude_opts, '-instr-profile=' + merged_data_path,
+        '-format=html', '-output-dir=' + os.path.join(report_dir, 'html'),
+        *test_binary_opts
+    ]
+    subprocess.check_call(show_cmd_list, text=True)
+
+  if report_type in ['gcov', 'both']:
+    logging.info('Creating gcov coverage report')
+    report_cmd_list = [
+        llvm_cov, 'show', *exclude_opts, '-instr-profile=' + merged_data_path,
+        '-format=text', *test_binary_opts
+    ]
+    with open(os.path.join(report_dir, 'report.txt'), 'wb') as out:
+      subprocess.check_call(report_cmd_list, stdout=out, text=True)
+
+
+def _merge_coverage_data(targets, coverage_dir):
+  """Create a combined coverage file from the raw reports."""
+  toolchain_dir = build.GetClangBinPath(clang.GetClangSpecification())
+  llvm_profdata = os.path.join(toolchain_dir, 'llvm-profdata')
+
+  raw_reports = _get_raw_reports(targets, coverage_dir)
+  if not raw_reports:
+    raise RuntimeError('No coverage data found in \'coverage_dir\'')
+
+  logging.info('Merging coverage files')
+  merged_data_path = os.path.join(coverage_dir, 'report.profdata')
+  merge_cmd_list = [
+      llvm_profdata, 'merge', '-sparse=true', '-o', merged_data_path
+  ] + raw_reports
+  subprocess.check_call(merge_cmd_list, text=True)
+
+  return merged_data_path
+
+
+def create_report(binary_dir, test_binaries, coverage_dir, report_type='both'):
+  """Generate source code coverage reports."""
+  merged_data_path = _merge_coverage_data(test_binaries, coverage_dir)
+
+  report_dir = coverage_dir
+  target_paths = _get_test_binary_paths(binary_dir, test_binaries, coverage_dir)
+  _generate_reports(target_paths, merged_data_path, report_dir, report_type)
+
+
+def main():
+  SetupDefaultLoggingConfig()
+
+  arg_parser = argparse.ArgumentParser()
+  arg_parser.add_argument(
+      '--binaries_dir',
+      required=True,
+      help='Directory where the test binaries are located.')
+  arg_parser.add_argument(
+      '--coverage_dir',
+      required=True,
+      help='Directory where coverage files are located and where the reports '
+      'will be generated.')
+  arg_parser.add_argument(
+      '--test_binaries',
+      nargs='+',
+      default=[],
+      help='List of test binaries that should be used for the coverage report. '
+      'If not passed all coverage files in --coverage_dir will be used.')
+
+  report_type_group = arg_parser.add_mutually_exclusive_group()
+  report_type_group.add_argument(
+      '--html_only',
+      action='store_true',
+      help='If passed only the html report will be created. Can not be used '
+      'with --gcov_only.')
+  report_type_group.add_argument(
+      '--gcov_only',
+      action='store_true',
+      help='If passed only the gcov report will be created. Can not be used '
+      'with --html_only.')
+
+  args = arg_parser.parse_args()
+
+  report_type = 'both'
+  if args.html_only:
+    report_type = 'html'
+  elif args.gcov_only:
+    report_type = 'gcov'
+
+  create_report(args.binaries_dir, args.test_binaries, args.coverage_dir,
+                report_type)
+
+
+if __name__ == '__main__':
+  main()
diff --git a/starboard/tools/testing/test_runner.py b/starboard/tools/testing/test_runner.py
index 0abc9f4..97addf1 100755
--- a/starboard/tools/testing/test_runner.py
+++ b/starboard/tools/testing/test_runner.py
@@ -27,7 +27,6 @@
 import traceback
 
 from six.moves import cStringIO as StringIO
-from starboard.build import clang
 from starboard.tools import abstract_launcher
 from starboard.tools import build
 from starboard.tools import command_line
@@ -35,13 +34,14 @@
 from starboard.tools.testing import build_tests
 from starboard.tools.testing import test_filter
 from starboard.tools.testing.test_sharding import ShardingTestConfig
+from starboard.tools.testing.test_coverage import create_report
 from starboard.tools.util import SetupDefaultLoggingConfig
 
 # pylint: disable=consider-using-f-string
 
 _FLAKY_RETRY_LIMIT = 4
 _TOTAL_TESTS_REGEX = re.compile(r"^\[==========\] (.*) tests? from .*"
-                                r"test cases? ran. \(.* ms total\)")
+                                r"test suites? ran. \(.* ms total\)")
 _TESTS_PASSED_REGEX = re.compile(r"^\[  PASSED  \] (.*) tests?")
 _TESTS_FAILED_REGEX = re.compile(r"^\[  FAILED  \] (.*) tests?, listed below:")
 _SINGLE_TEST_FAILED_REGEX = re.compile(r"^\[  FAILED  \] (.*)")
@@ -223,7 +223,8 @@
                xml_output_dir=None,
                log_xml_results=False,
                shard_index=None,
-               launcher_args=None):
+               launcher_args=None,
+               coverage_directory=None):
     self.platform = platform
     self.config = config
     self.loader_platform = loader_platform
@@ -237,7 +238,7 @@
     if not self.out_directory:
       self.out_directory = paths.BuildOutputDirectory(self.platform,
                                                       self.config)
-    self.coverage_directory = os.path.join(self.out_directory, "coverage")
+    self.coverage_directory = coverage_directory
     if (not self.loader_out_directory and self.loader_platform and
         self.loader_config):
       self.loader_out_directory = paths.BuildOutputDirectory(
@@ -439,6 +440,9 @@
     # For on-device testing, this is w.r.t on device storage.
     test_result_xml_path = None
 
+    # Path to coverage file to generate.
+    coverage_file_path = None
+
     def MakeLauncher():
       logging.info("MakeLauncher(): %s", test_result_xml_path)
       return abstract_launcher.LauncherFactory(
@@ -449,7 +453,7 @@
           target_params=test_params,
           output_file=write_pipe,
           out_directory=self.out_directory,
-          coverage_directory=self.coverage_directory,
+          coverage_file_path=coverage_file_path,
           env_variables=env,
           test_result_xml_path=test_result_xml_path,
           loader_platform=self.loader_platform,
@@ -486,6 +490,12 @@
       test_params.append(f"--gtest_output=xml:{test_result_xml_path}")
     logging.info("XML test result path: %s", test_result_xml_path)
 
+    if self.coverage_directory:
+      coverage_file_path = os.path.join(self.coverage_directory,
+                                        target_name + ".profraw")
+      logging.info("Coverage data will be saved to %s",
+                   os.path.relpath(coverage_file_path))
+
     # Turn off color codes from output to make it easy to parse
     test_params.append("--gtest_color=no")
 
@@ -830,51 +840,6 @@
         results.append(self._RunTest(test_target))
     return self._ProcessAllTestResults(results)
 
-  def GenerateCoverageReport(self):
-    """Generate the source code coverage report."""
-    available_profraw_files = []
-    available_targets = []
-    for target in sorted(self.test_targets.keys()):
-      profraw_file = os.path.join(self.coverage_directory, target + ".profraw")
-      if os.path.isfile(profraw_file):
-        available_profraw_files.append(profraw_file)
-        available_targets.append(target)
-
-    # If there are no profraw files, then there is no work to do.
-    if not available_profraw_files:
-      return
-
-    toolchain_dir = build.GetClangBinPath(clang.GetClangSpecification())
-
-    report_name = "report"
-    profdata_name = os.path.join(self.coverage_directory,
-                                 report_name + ".profdata")
-    merge_cmd_list = [
-        os.path.join(toolchain_dir, "llvm-profdata"), "merge", "-sparse=true",
-        "-o", profdata_name
-    ]
-    merge_cmd_list += available_profraw_files
-
-    self._Exec(merge_cmd_list)
-    show_cmd_list = [
-        os.path.join(toolchain_dir, "llvm-cov"), "show",
-        "-instr-profile=" + profdata_name, "-format=html",
-        "-output-dir=" + os.path.join(self.coverage_directory, "html"),
-        available_targets[0]
-    ]
-    show_cmd_list += ["-object=" + target for target in available_targets[1:]]
-    self._Exec(show_cmd_list)
-
-    report_cmd_list = [
-        os.path.join(toolchain_dir, "llvm-cov"), "report",
-        "-instr-profile=" + profdata_name, available_targets[0]
-    ]
-    report_cmd_list += ["-object=" + target for target in available_targets[1:]]
-    self._Exec(
-        report_cmd_list,
-        output_file=os.path.join(self.coverage_directory, report_name + ".txt"))
-    return
-
 
 def main():
   SetupDefaultLoggingConfig()
@@ -941,6 +906,17 @@
       type=int,
       help="The index of the test shard to run. This selects a subset of tests "
       "to run based on the configuration per platform, if it exists.")
+  arg_parser.add_argument(
+      "--coverage_dir",
+      help="If defined, coverage data will be collected in the directory "
+      "specified. This requires the files to have been compiled with clang "
+      "coverage.")
+  arg_parser.add_argument(
+      "--coverage_report",
+      action="store_true",
+      help="If set, a coverage report will be generated if there is available "
+      "coverage information in the directory specified by --coverage_dir."
+      "If --coverage_dir is not passed this parameter is ignored.")
   args = arg_parser.parse_args()
 
   if (args.loader_platform and not args.loader_config or
@@ -961,13 +937,19 @@
   if args.dry_run:
     launcher_args.append(abstract_launcher.ARG_DRYRUN)
 
+  coverage_directory = None
+  if args.coverage_dir:
+    # Clang needs an absolute path to generate coverage reports.
+    coverage_directory = os.path.abspath(args.coverage_dir)
+
   logging.info("Initializing test runner")
   runner = TestRunner(args.platform, args.config, args.loader_platform,
                       args.loader_config, args.device_id, args.target_name,
                       target_params, args.out_directory,
                       args.loader_out_directory, args.platform_tests_only,
                       args.application_name, args.dry_run, args.xml_output_dir,
-                      args.log_xml_results, args.shard_index, launcher_args)
+                      args.log_xml_results, args.shard_index, launcher_args,
+                      coverage_directory)
   logging.info("Test runner initialized")
 
   def Abort(signum, frame):
@@ -998,7 +980,15 @@
   if args.run:
     run_success = runner.RunAllTests()
 
-  runner.GenerateCoverageReport()
+  if args.coverage_report and coverage_directory:
+    if run_success:
+      try:
+        create_report(runner.out_directory, runner.test_targets.keys(),
+                      coverage_directory)
+      except Exception as e:  # pylint: disable=broad-except
+        logging.error("Failed to generate coverage report: %s", e)
+    else:
+      logging.warning("Test run failed, skipping code coverage report.")
 
   # If either step has failed, count the whole test run as failed.
   if not build_success or not run_success:
diff --git a/starboard/win/shared/configuration_public.h b/starboard/win/shared/configuration_public.h
index 1033510..eb3eede 100644
--- a/starboard/win/shared/configuration_public.h
+++ b/starboard/win/shared/configuration_public.h
@@ -112,11 +112,6 @@
 
 // --- Graphics Configuration ------------------------------------------------
 
-// Indicates whether or not the given platform supports bilinear filtering.
-// This can be checked to enable/disable renderer tests that verify that this is
-// working properly.
-#define SB_HAS_BILINEAR_FILTERING_SUPPORT 1
-
 // Indicates whether or not the given platform supports rendering of NV12
 // textures. These textures typically originate from video decoders.
 #define SB_HAS_NV12_TEXTURE_SUPPORT 0
diff --git a/starboard/win/win32/test_filters.py b/starboard/win/win32/test_filters.py
index 2ce06c8..cf8621f 100644
--- a/starboard/win/win32/test_filters.py
+++ b/starboard/win/win32/test_filters.py
@@ -30,12 +30,15 @@
         # attribute.
         'SbSystemGetStackTest.SunnyDayStackDirection',
 
+        # These tests are failing. Enable them once they're supported.
+        'MultiplePlayerTests/*beneath_the_canopy_137_avc_dmp*',
+        'SbMediaSetAudioWriteDurationTests/SbMediaSetAudioWriteDurationTest.WriteContinuedLimitedInput*',
+        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.SecondaryPlayerTest/*',
+
         # Failures tracked by b/256160416.
         'SbSystemGetPathTest.ReturnsRequiredPaths',
-        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.SeekAndDestroy/*_video_beneath_the_canopy_137_avc_dmp_output_decode_to_texture_*',
-        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.NoInput/*_video_beneath_the_canopy_137_avc_dmp_output_decode_to_texture_*',
-        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteSingleBatch/*_video_beneath_the_canopy_137_avc_dmp_output_decode_to_texture_*',
-        'SbPlayerWriteSampleTests/SbPlayerWriteSampleTest.WriteMultipleBatches/*_video_beneath_the_canopy_137_avc_dmp_output_decode_to_texture_*',
+        'SbPlayerGetAudioConfigurationTests/*_video_beneath_the_canopy_137_avc_dmp_output_decode_to_texture_*',
+        'SbPlayerWriteSampleTests/*_video_beneath_the_canopy_137_avc_dmp_output_decode_to_texture_*',
         'SbSocketAddressTypes/SbSocketBindTest.RainyDayBadInterface/type_ipv6_filter_ipv6',
         'SbSocketAddressTypes/SbSocketGetInterfaceAddressTest.SunnyDayDestination/type_ipv6',
         'SbSocketAddressTypes/SbSocketGetInterfaceAddressTest.SunnyDaySourceForDestination/type_ipv6',
@@ -45,6 +48,11 @@
         'SbSocketAddressTypes/SbSocketSetOptionsTest.RainyDayInvalidSocket/type_ipv6',
         # Flakiness is tracked in b/278276779.
         'Semaphore.ThreadTakesWait_TimeExpires',
+        # Failure tracked by b/287666606.
+        'VerticalVideoTests/VerticalVideoTest.WriteSamples*',
+
+        # Enable once verified on the platform.
+        'SbMediaCanPlayMimeAndKeySystem.MinimumSupport',
     ],
     'player_filter_tests': [
         # These tests fail on our VMs for win-win32 builds due to missing
diff --git a/testing/gmock/BUILD.gn b/testing/gmock/BUILD.gn
index 1d27016..b1c28cc 100644
--- a/testing/gmock/BUILD.gn
+++ b/testing/gmock/BUILD.gn
@@ -1,53 +1,25 @@
-# Copyright 2014 The Chromium Authors. All rights reserved.
+# Copyright 2014 The Chromium Authors
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
-# Modifications Copyright 2017 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# The file/directory layout of Google Test is not yet considered stable. Until
+# it stabilizes, Chromium code MUST use this target instead of reaching directly
+# into //third_party/googletest.
 
-config("gmock_direct_config") {
-  include_dirs = [ "include" ]
-}
-
-static_library("gmock") {
+source_set("gmock") {
   testonly = true
   sources = [
     "include/gmock/gmock-actions.h",
-    "include/gmock/gmock-cardinalities.h",
-    "include/gmock/gmock-generated-actions.h",
-    "include/gmock/gmock-generated-function-mockers.h",
-    "include/gmock/gmock-generated-matchers.h",
-    "include/gmock/gmock-generated-nice-strict.h",
     "include/gmock/gmock-matchers.h",
-    "include/gmock/gmock-spec-builders.h",
     "include/gmock/gmock.h",
-    "include/gmock/internal/gmock-generated-internal-utils.h",
-    "include/gmock/internal/gmock-internal-utils.h",
-    "include/gmock/internal/gmock-port.h",
-    "src/gmock-cardinalities.cc",
-    "src/gmock-internal-utils.cc",
-    "src/gmock-matchers.cc",
-    "src/gmock-spec-builders.cc",
-    "src/gmock.cc",
-    "../gmock_mutant.h",
   ]
+  public_deps = [ "//third_party/googletest:gmock" ]
+}
 
-  include_dirs = [ "." ]
-
-  public_configs = [ ":gmock_direct_config" ]
-
-  public_deps = [
-    "//testing/gtest",
-  ]
+# The file/directory layout of Google Test is not yet considered stable. Until
+# it stabilizes, Chromium code MUST use this target instead of reaching directly
+# into //third_party/googletest.
+source_set("gmock_main") {
+  testonly = true
+  deps = [ "//third_party/googletest:gmock_main" ]
 }
diff --git a/testing/gmock/CHANGES b/testing/gmock/CHANGES
deleted file mode 100644
index d6f2f76..0000000
--- a/testing/gmock/CHANGES
+++ /dev/null
@@ -1,126 +0,0 @@
-Changes for 1.7.0:
-
-* All new improvements in Google Test 1.7.0.
-* New feature: matchers DoubleNear(), FloatNear(),
-  NanSensitiveDoubleNear(), NanSensitiveFloatNear(),
-  UnorderedElementsAre(), UnorderedElementsAreArray(), WhenSorted(),
-  WhenSortedBy(), IsEmpty(), and SizeIs().
-* Improvement: Google Mock can now be built as a DLL.
-* Improvement: when compiled by a C++11 compiler, matchers AllOf()
-  and AnyOf() can accept an arbitrary number of matchers.
-* Improvement: when compiled by a C++11 compiler, matchers
-  ElementsAreArray() can accept an initializer list.
-* Improvement: when exceptions are enabled, a mock method with no
-  default action now throws instead crashing the test.
-* Improvement: added class testing::StringMatchResultListener to aid
-  definition of composite matchers.
-* Improvement: function return types used in MOCK_METHOD*() macros can
-  now contain unprotected commas.
-* Improvement (potentially breaking): EXPECT_THAT() and ASSERT_THAT()
-  are now more strict in ensuring that the value type and the matcher
-  type are compatible, catching potential bugs in tests.
-* Improvement: Pointee() now works on an optional<T>.
-* Improvement: the ElementsAreArray() matcher can now take a vector or
-  iterator range as input, and makes a copy of its input elements
-  before the conversion to a Matcher.
-* Improvement: the Google Mock Generator can now generate mocks for
-  some class templates.
-* Bug fix: mock object destruction triggerred by another mock object's
-  destruction no longer hangs.
-* Improvement: Google Mock Doctor works better with newer Clang and
-  GCC now.
-* Compatibility fixes.
-* Bug/warning fixes.
-
-Changes for 1.6.0:
-
-* Compilation is much faster and uses much less memory, especially
-  when the constructor and destructor of a mock class are moved out of
-  the class body.
-* New matchers: Pointwise(), Each().
-* New actions: ReturnPointee() and ReturnRefOfCopy().
-* CMake support.
-* Project files for Visual Studio 2010.
-* AllOf() and AnyOf() can handle up-to 10 arguments now.
-* Google Mock doctor understands Clang error messages now.
-* SetArgPointee<> now accepts string literals.
-* gmock_gen.py handles storage specifier macros and template return
-  types now.
-* Compatibility fixes.
-* Bug fixes and implementation clean-ups.
-* Potentially incompatible changes: disables the harmful 'make install'
-  command in autotools.
-
-Potentially breaking changes:
-
-* The description string for MATCHER*() changes from Python-style
-  interpolation to an ordinary C++ string expression.
-* SetArgumentPointee is deprecated in favor of SetArgPointee.
-* Some non-essential project files for Visual Studio 2005 are removed.
-
-Changes for 1.5.0:
-
- * New feature: Google Mock can be safely used in multi-threaded tests
-   on platforms having pthreads.
- * New feature: function for printing a value of arbitrary type.
- * New feature: function ExplainMatchResult() for easy definition of
-   composite matchers.
- * The new matcher API lets user-defined matchers generate custom
-   explanations more directly and efficiently.
- * Better failure messages all around.
- * NotNull() and IsNull() now work with smart pointers.
- * Field() and Property() now work when the matcher argument is a pointer
-   passed by reference.
- * Regular expression matchers on all platforms.
- * Added GCC 4.0 support for Google Mock Doctor.
- * Added gmock_all_test.cc for compiling most Google Mock tests
-   in a single file.
- * Significantly cleaned up compiler warnings.
- * Bug fixes, better test coverage, and implementation clean-ups.
-
- Potentially breaking changes:
-
- * Custom matchers defined using MatcherInterface or MakePolymorphicMatcher()
-   need to be updated after upgrading to Google Mock 1.5.0; matchers defined
-   using MATCHER or MATCHER_P* aren't affected.
- * Dropped support for 'make install'.
-
-Changes for 1.4.0 (we skipped 1.2.* and 1.3.* to match the version of
-Google Test):
-
- * Works in more environments: Symbian and minGW, Visual C++ 7.1.
- * Lighter weight: comes with our own implementation of TR1 tuple (no
-   more dependency on Boost!).
- * New feature: --gmock_catch_leaked_mocks for detecting leaked mocks.
- * New feature: ACTION_TEMPLATE for defining templatized actions.
- * New feature: the .After() clause for specifying expectation order.
- * New feature: the .With() clause for for specifying inter-argument
-   constraints.
- * New feature: actions ReturnArg<k>(), ReturnNew<T>(...), and
-   DeleteArg<k>().
- * New feature: matchers Key(), Pair(), Args<...>(), AllArgs(), IsNull(),
-   and Contains().
- * New feature: utility class MockFunction<F>, useful for checkpoints, etc.
- * New feature: functions Value(x, m) and SafeMatcherCast<T>(m).
- * New feature: copying a mock object is rejected at compile time.
- * New feature: a script for fusing all Google Mock and Google Test
-   source files for easy deployment.
- * Improved the Google Mock doctor to diagnose more diseases.
- * Improved the Google Mock generator script.
- * Compatibility fixes for Mac OS X and gcc.
- * Bug fixes and implementation clean-ups.
-
-Changes for 1.1.0:
-
- * New feature: ability to use Google Mock with any testing framework.
- * New feature: macros for easily defining new matchers
- * New feature: macros for easily defining new actions.
- * New feature: more container matchers.
- * New feature: actions for accessing function arguments and throwing
-   exceptions.
- * Improved the Google Mock doctor script for diagnosing compiler errors.
- * Bug fixes and implementation clean-ups.
-
-Changes for 1.0.0:
-
- * Initial Open Source release of Google Mock
diff --git a/testing/gmock/CMakeLists.txt b/testing/gmock/CMakeLists.txt
deleted file mode 100644
index 4cc6637..0000000
--- a/testing/gmock/CMakeLists.txt
+++ /dev/null
@@ -1,186 +0,0 @@
-########################################################################
-# CMake build script for Google Mock.
-#
-# To run the tests for Google Mock itself on Linux, use 'make test' or
-# ctest.  You can select which tests to run using 'ctest -R regex'.
-# For more options, run 'ctest --help'.
-
-# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
-# make it prominent in the GUI.
-option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
-
-option(gmock_build_tests "Build all of Google Mock's own tests." OFF)
-
-# A directory to find Google Test sources.
-if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt")
-  set(gtest_dir gtest)
-else()
-  set(gtest_dir ../gtest)
-endif()
-
-# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
-include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL)
-
-if (COMMAND pre_project_set_up_hermetic_build)
-  # Google Test also calls hermetic setup functions from add_subdirectory,
-  # although its changes will not affect things at the current scope.
-  pre_project_set_up_hermetic_build()
-endif()
-
-########################################################################
-#
-# Project-wide settings
-
-# Name of the project.
-#
-# CMake files in this project can refer to the root source directory
-# as ${gmock_SOURCE_DIR} and to the root binary directory as
-# ${gmock_BINARY_DIR}.
-# Language "C" is required for find_package(Threads).
-project(gmock CXX C)
-cmake_minimum_required(VERSION 2.6.2)
-
-if (COMMAND set_up_hermetic_build)
-  set_up_hermetic_build()
-endif()
-
-# Instructs CMake to process Google Test's CMakeLists.txt and add its
-# targets to the current scope.  We are placing Google Test's binary
-# directory in a subdirectory of our own as VC compilation may break
-# if they are the same (the default).
-add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest")
-
-# Although Google Test's CMakeLists.txt calls this function, the
-# changes there don't affect the current scope.  Therefore we have to
-# call it again here.
-config_compiler_and_linker()  # from ${gtest_dir}/cmake/internal_utils.cmake
-
-# Adds Google Mock's and Google Test's header directories to the search path.
-include_directories("${gmock_SOURCE_DIR}/include"
-                    "${gmock_SOURCE_DIR}"
-                    "${gtest_SOURCE_DIR}/include"
-                    # This directory is needed to build directly from Google
-                    # Test sources.
-                    "${gtest_SOURCE_DIR}")
-
-# Summary of tuple support for Microsoft Visual Studio:
-# Compiler    version(MS)  version(cmake)  Support
-# ----------  -----------  --------------  -----------------------------
-# <= VS 2010  <= 10        <= 1600         Use Google Tests's own tuple.
-# VS 2012     11           1700            std::tr1::tuple + _VARIADIC_MAX=10
-# VS 2013     12           1800            std::tr1::tuple
-if (MSVC AND MSVC_VERSION EQUAL 1700)
-  add_definitions(/D _VARIADIC_MAX=10)
-endif()
-
-########################################################################
-#
-# Defines the gmock & gmock_main libraries.  User tests should link
-# with one of them.
-
-# Google Mock libraries.  We build them using more strict warnings than what
-# are used for other targets, to ensure that Google Mock can be compiled by
-# a user aggressive about warnings.
-cxx_library(gmock
-            "${cxx_strict}"
-            "${gtest_dir}/src/gtest-all.cc"
-            src/gmock-all.cc)
-
-cxx_library(gmock_main
-            "${cxx_strict}"
-            "${gtest_dir}/src/gtest-all.cc"
-            src/gmock-all.cc
-            src/gmock_main.cc)
-
-########################################################################
-#
-# Google Mock's own tests.
-#
-# You can skip this section if you aren't interested in testing
-# Google Mock itself.
-#
-# The tests are not built by default.  To build them, set the
-# gmock_build_tests option to ON.  You can do it by running ccmake
-# or specifying the -Dgmock_build_tests=ON flag when running cmake.
-
-if (gmock_build_tests)
-  # This must be set in the root directory for the tests to be run by
-  # 'make test' or ctest.
-  enable_testing()
-
-  ############################################################
-  # C++ tests built with standard compiler flags.
-
-  cxx_test(gmock-actions_test gmock_main)
-  cxx_test(gmock-cardinalities_test gmock_main)
-  cxx_test(gmock_ex_test gmock_main)
-  cxx_test(gmock-generated-actions_test gmock_main)
-  cxx_test(gmock-generated-function-mockers_test gmock_main)
-  cxx_test(gmock-generated-internal-utils_test gmock_main)
-  cxx_test(gmock-generated-matchers_test gmock_main)
-  cxx_test(gmock-internal-utils_test gmock_main)
-  cxx_test(gmock-matchers_test gmock_main)
-  cxx_test(gmock-more-actions_test gmock_main)
-  cxx_test(gmock-nice-strict_test gmock_main)
-  cxx_test(gmock-port_test gmock_main)
-  cxx_test(gmock-spec-builders_test gmock_main)
-  cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc)
-  cxx_test(gmock_test gmock_main)
-
-  if (CMAKE_USE_PTHREADS_INIT)
-    cxx_test(gmock_stress_test gmock)
-  endif()
-
-  # gmock_all_test is commented to save time building and running tests.
-  # Uncomment if necessary.
-  # cxx_test(gmock_all_test gmock_main)
-
-  ############################################################
-  # C++ tests built with non-standard compiler flags.
-
-  cxx_library(gmock_main_no_exception "${cxx_no_exception}"
-    "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
-
-  cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
-    "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
-
-  if (NOT MSVC OR MSVC_VERSION LESS 1600)  # 1600 is Visual Studio 2010.
-    # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that
-    # conflict with our own definitions. Therefore using our own tuple does not
-    # work on those compilers.
-    cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}"
-      "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
-
-    cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}"
-      gmock_main_use_own_tuple test/gmock-spec-builders_test.cc)
-  endif()
-
-  cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
-    gmock_main_no_exception test/gmock-more-actions_test.cc)
-
-  cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}"
-    gmock_main_no_rtti test/gmock-spec-builders_test.cc)
-
-  cxx_shared_library(shared_gmock_main "${cxx_default}"
-    "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
-
-  # Tests that a binary can be built with Google Mock as a shared library.  On
-  # some system configurations, it may not possible to run the binary without
-  # knowing more details about the system configurations. We do not try to run
-  # this binary. To get a more robust shared library coverage, configure with
-  # -DBUILD_SHARED_LIBS=ON.
-  cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}"
-    shared_gmock_main test/gmock-spec-builders_test.cc)
-  set_target_properties(shared_gmock_test_
-    PROPERTIES
-    COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
-
-  ############################################################
-  # Python tests.
-
-  cxx_executable(gmock_leak_test_ test gmock_main)
-  py_test(gmock_leak_test)
-
-  cxx_executable(gmock_output_test_ test gmock)
-  py_test(gmock_output_test)
-endif()
diff --git a/testing/gmock/CONTRIBUTORS b/testing/gmock/CONTRIBUTORS
deleted file mode 100644
index 6e9ae36..0000000
--- a/testing/gmock/CONTRIBUTORS
+++ /dev/null
@@ -1,40 +0,0 @@
-# This file contains a list of people who've made non-trivial
-# contribution to the Google C++ Mocking Framework project.  People
-# who commit code to the project are encouraged to add their names
-# here.  Please keep the list sorted by first names.
-
-Benoit Sigoure <tsuna@google.com>
-Bogdan Piloca <boo@google.com>
-Chandler Carruth <chandlerc@google.com>
-Dave MacLachlan <dmaclach@gmail.com>
-David Anderson <danderson@google.com>
-Dean Sturtevant
-Gene Volovich <gv@cite.com>
-Hal Burch <gmock@hburch.com>
-Jeffrey Yasskin <jyasskin@google.com>
-Jim Keller <jimkeller@google.com>
-Joe Walnes <joe@truemesh.com>
-Jon Wray <jwray@google.com>
-Keir Mierle <mierle@gmail.com>
-Keith Ray <keith.ray@gmail.com>
-Kostya Serebryany <kcc@google.com>
-Lev Makhlis
-Manuel Klimek <klimek@google.com>
-Mario Tanev <radix@google.com>
-Mark Paskin
-Markus Heule <markus.heule@gmail.com>
-Matthew Simmons <simmonmt@acm.org>
-Mike Bland <mbland@google.com>
-Neal Norwitz <nnorwitz@gmail.com>
-Nermin Ozkiranartli <nermin@google.com>
-Owen Carlsen <ocarlsen@google.com>
-Paneendra Ba <paneendra@google.com>
-Paul Menage <menage@google.com>
-Piotr Kaminski <piotrk@google.com>
-Russ Rufer <russ@pentad.com>
-Sverre Sundsdal <sundsdal@gmail.com>
-Takeshi Yoshino <tyoshino@google.com>
-Vadim Berman <vadimb@google.com>
-Vlad Losev <vladl@google.com>
-Wolfgang Klier <wklier@google.com>
-Zhanyong Wan <wan@google.com>
diff --git a/testing/gmock/LICENSE b/testing/gmock/LICENSE
deleted file mode 100644
index 1941a11..0000000
--- a/testing/gmock/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright 2008, Google Inc.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-    * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-    * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/testing/gmock/METADATA b/testing/gmock/METADATA
index 2c70453..90a1d47 100644
--- a/testing/gmock/METADATA
+++ b/testing/gmock/METADATA
@@ -1,16 +1,16 @@
-name: "gmock"
+name: "testing/gmock"
 description:
-  "Subtree at testing/gmock."
+  "Copy of testing/gmock from Chromium branch-heads/5735"
 
 third_party {
   url {
     type: GIT
-    value: "https://chromium.googlesource.com/external/googlemock"
+    value: "https://chromium.googlesource.com/chromium/src"
   }
-  version: "38513a8bb154f0b6d0a4088814fe92552696d465"
+  version: "5cd6a34d059463d2bf7c2090d1904e527c3428b2"
   last_upgrade_date {
-    year: 2012
-    month: 11
-    day: 15
+    year: 2023
+    month: 6
+    day: 16
   }
 }
diff --git a/testing/gmock/Makefile.am b/testing/gmock/Makefile.am
deleted file mode 100644
index 7ad4588..0000000
--- a/testing/gmock/Makefile.am
+++ /dev/null
@@ -1,220 +0,0 @@
-# Automake file
-
-# Nonstandard package files for distribution.
-EXTRA_DIST = LICENSE
-
-# We may need to build our internally packaged gtest. If so, it will be
-# included in the 'subdirs' variable.
-SUBDIRS = $(subdirs)
-
-# This is generated by the configure script, so clean it for distribution.
-DISTCLEANFILES = scripts/gmock-config
-
-# We define the global AM_CPPFLAGS as everything we compile includes from these
-# directories.
-AM_CPPFLAGS = $(GTEST_CPPFLAGS) -I$(srcdir)/include
-
-# Modifies compiler and linker flags for pthreads compatibility.
-if HAVE_PTHREADS
-  AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1
-  AM_LIBS = @PTHREAD_LIBS@
-endif
-
-# Build rules for libraries.
-lib_LTLIBRARIES = lib/libgmock.la lib/libgmock_main.la
-
-lib_libgmock_la_SOURCES = src/gmock-all.cc
-
-pkginclude_HEADERS = \
-  include/gmock/gmock-actions.h \
-  include/gmock/gmock-cardinalities.h \
-  include/gmock/gmock-generated-actions.h \
-  include/gmock/gmock-generated-function-mockers.h \
-  include/gmock/gmock-generated-matchers.h \
-  include/gmock/gmock-generated-nice-strict.h \
-  include/gmock/gmock-matchers.h \
-  include/gmock/gmock-more-actions.h \
-  include/gmock/gmock-more-matchers.h \
-  include/gmock/gmock-spec-builders.h \
-  include/gmock/gmock.h
-
-pkginclude_internaldir = $(pkgincludedir)/internal
-pkginclude_internal_HEADERS = \
-  include/gmock/internal/gmock-generated-internal-utils.h \
-  include/gmock/internal/gmock-internal-utils.h \
-  include/gmock/internal/gmock-port.h
-
-lib_libgmock_main_la_SOURCES = src/gmock_main.cc
-lib_libgmock_main_la_LIBADD = lib/libgmock.la
-
-# Build rules for tests. Automake's naming for some of these variables isn't
-# terribly obvious, so this is a brief reference:
-#
-# TESTS -- Programs run automatically by "make check"
-# check_PROGRAMS -- Programs built by "make check" but not necessarily run
-
-TESTS=
-check_PROGRAMS=
-AM_LDFLAGS = $(GTEST_LDFLAGS)
-
-# This exercises all major components of Google Mock.  It also
-# verifies that libgmock works.
-TESTS += test/gmock-spec-builders_test
-check_PROGRAMS += test/gmock-spec-builders_test
-test_gmock_spec_builders_test_SOURCES = test/gmock-spec-builders_test.cc
-test_gmock_spec_builders_test_LDADD = $(GTEST_LIBS) lib/libgmock.la
-
-# This tests using Google Mock in multiple translation units.  It also
-# verifies that libgmock_main and libgmock work.
-TESTS += test/gmock_link_test
-check_PROGRAMS += test/gmock_link_test
-test_gmock_link_test_SOURCES = \
-  test/gmock_link2_test.cc \
-  test/gmock_link_test.cc \
-  test/gmock_link_test.h
-test_gmock_link_test_LDADD = $(GTEST_LIBS) lib/libgmock_main.la  lib/libgmock.la
-
-if HAVE_PYTHON
-  # Tests that fused gmock files compile and work.
-  TESTS += test/gmock_fused_test
-  check_PROGRAMS += test/gmock_fused_test
-  test_gmock_fused_test_SOURCES = \
-    fused-src/gmock-gtest-all.cc \
-    fused-src/gmock/gmock.h \
-    fused-src/gmock_main.cc \
-    fused-src/gtest/gtest.h \
-    test/gmock_test.cc
-  test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src"
-endif
-
-# Google Mock source files that we don't compile directly.
-GMOCK_SOURCE_INGLUDES = \
-  src/gmock-cardinalities.cc \
-  src/gmock-internal-utils.cc \
-  src/gmock-matchers.cc \
-  src/gmock-spec-builders.cc \
-  src/gmock.cc
-
-EXTRA_DIST += $(GMOCK_SOURCE_INGLUDES)
-
-# C++ tests that we don't compile using autotools.
-EXTRA_DIST += \
-  test/gmock-actions_test.cc \
-  test/gmock_all_test.cc \
-  test/gmock-cardinalities_test.cc \
-  test/gmock_ex_test.cc \
-  test/gmock-generated-actions_test.cc \
-  test/gmock-generated-function-mockers_test.cc \
-  test/gmock-generated-internal-utils_test.cc \
-  test/gmock-generated-matchers_test.cc \
-  test/gmock-internal-utils_test.cc \
-  test/gmock-matchers_test.cc \
-  test/gmock-more-actions_test.cc \
-  test/gmock-nice-strict_test.cc \
-  test/gmock-port_test.cc \
-  test/gmock_stress_test.cc
-
-# Python tests, which we don't run using autotools.
-EXTRA_DIST += \
-  test/gmock_leak_test.py \
-  test/gmock_leak_test_.cc \
-  test/gmock_output_test.py \
-  test/gmock_output_test_.cc \
-  test/gmock_output_test_golden.txt \
-  test/gmock_test_utils.py
-
-# Nonstandard package files for distribution.
-EXTRA_DIST += \
-  CHANGES \
-  CONTRIBUTORS \
-  make/Makefile
-
-# Pump scripts for generating Google Mock headers.
-# TODO(chandlerc@google.com): automate the generation of *.h from *.h.pump.
-EXTRA_DIST += \
-  include/gmock/gmock-generated-actions.h.pump \
-  include/gmock/gmock-generated-function-mockers.h.pump \
-  include/gmock/gmock-generated-matchers.h.pump \
-  include/gmock/gmock-generated-nice-strict.h.pump \
-  include/gmock/internal/gmock-generated-internal-utils.h.pump
-
-# Script for fusing Google Mock and Google Test source files.
-EXTRA_DIST += scripts/fuse_gmock_files.py
-
-# The Google Mock Generator tool from the cppclean project.
-EXTRA_DIST += \
-  scripts/generator/LICENSE \
-  scripts/generator/README \
-  scripts/generator/README.cppclean \
-  scripts/generator/cpp/__init__.py \
-  scripts/generator/cpp/ast.py \
-  scripts/generator/cpp/gmock_class.py \
-  scripts/generator/cpp/keywords.py \
-  scripts/generator/cpp/tokenize.py \
-  scripts/generator/cpp/utils.py \
-  scripts/generator/gmock_gen.py
-
-# Script for diagnosing compiler errors in programs that use Google
-# Mock.
-EXTRA_DIST += scripts/gmock_doctor.py
-
-# CMake scripts.
-EXTRA_DIST += \
-  CMakeLists.txt
-
-# Microsoft Visual Studio 2005 projects.
-EXTRA_DIST += \
-  msvc/2005/gmock.sln \
-  msvc/2005/gmock.vcproj \
-  msvc/2005/gmock_config.vsprops \
-  msvc/2005/gmock_main.vcproj \
-  msvc/2005/gmock_test.vcproj
-
-# Microsoft Visual Studio 2010 projects.
-EXTRA_DIST += \
-  msvc/2010/gmock.sln \
-  msvc/2010/gmock.vcxproj \
-  msvc/2010/gmock_config.props \
-  msvc/2010/gmock_main.vcxproj \
-  msvc/2010/gmock_test.vcxproj
-
-if HAVE_PYTHON
-# gmock_test.cc does not really depend on files generated by the
-# fused-gmock-internal rule.  However, gmock_test.o does, and it is
-# important to include test/gmock_test.cc as part of this rule in order to
-# prevent compiling gmock_test.o until all dependent files have been
-# generated.
-$(test_gmock_fused_test_SOURCES): fused-gmock-internal
-
-# TODO(vladl@google.com): Find a way to add Google Tests's sources here.
-fused-gmock-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \
-                      $(lib_libgmock_la_SOURCES) $(GMOCK_SOURCE_INGLUDES) \
-                      $(lib_libgmock_main_la_SOURCES) \
-                      scripts/fuse_gmock_files.py
-	mkdir -p "$(srcdir)/fused-src"
-	chmod -R u+w "$(srcdir)/fused-src"
-	rm -f "$(srcdir)/fused-src/gtest/gtest.h"
-	rm -f "$(srcdir)/fused-src/gmock/gmock.h"
-	rm -f "$(srcdir)/fused-src/gmock-gtest-all.cc"
-	"$(srcdir)/scripts/fuse_gmock_files.py" "$(srcdir)/fused-src"
-	cp -f "$(srcdir)/src/gmock_main.cc" "$(srcdir)/fused-src"
-
-maintainer-clean-local:
-	rm -rf "$(srcdir)/fused-src"
-endif
-
-# Death tests may produce core dumps in the build directory. In case
-# this happens, clean them to keep distcleancheck happy.
-CLEANFILES = core
-
-# Disables 'make install' as installing a compiled version of Google
-# Mock can lead to undefined behavior due to violation of the
-# One-Definition Rule.
-
-install-exec-local:
-	echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system."
-	false
-
-install-data-local:
-	echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system."
-	false
diff --git a/testing/gmock/OWNERS b/testing/gmock/OWNERS
new file mode 100644
index 0000000..8a7bec9
--- /dev/null
+++ b/testing/gmock/OWNERS
@@ -0,0 +1,3 @@
+thakis@chromium.org
+asully@chromium.org
+ayui@chromium.org
diff --git a/testing/gmock/README b/testing/gmock/README
deleted file mode 100644
index 0cb9123..0000000
--- a/testing/gmock/README
+++ /dev/null
@@ -1,369 +0,0 @@
-Google C++ Mocking Framework
-============================
-
-http://code.google.com/p/googlemock/
-
-Overview
---------
-
-Google's framework for writing and using C++ mock classes on a variety
-of platforms (Linux, Mac OS X, Windows, Windows CE, Symbian, etc).
-Inspired by jMock, EasyMock, and Hamcrest, and designed with C++'s
-specifics in mind, it can help you derive better designs of your
-system and write better tests.
-
-Google Mock:
-
-- provides a declarative syntax for defining mocks,
-- can easily define partial (hybrid) mocks, which are a cross of real
-  and mock objects,
-- handles functions of arbitrary types and overloaded functions,
-- comes with a rich set of matchers for validating function arguments,
-- uses an intuitive syntax for controlling the behavior of a mock,
-- does automatic verification of expectations (no record-and-replay
-  needed),
-- allows arbitrary (partial) ordering constraints on
-  function calls to be expressed,
-- lets a user extend it by defining new matchers and actions.
-- does not use exceptions, and
-- is easy to learn and use.
-
-Please see the project page above for more information as well as the
-mailing list for questions, discussions, and development.  There is
-also an IRC channel on OFTC (irc.oftc.net) #gtest available.  Please
-join us!
-
-Please note that code under scripts/generator/ is from the cppclean
-project (http://code.google.com/p/cppclean/) and under the Apache
-License, which is different from Google Mock's license.
-
-Requirements for End Users
---------------------------
-
-Google Mock is implemented on top of the Google Test C++ testing
-framework (http://code.google.com/p/googletest/), and includes the
-latter as part of the SVN repository and distribution package.  You
-must use the bundled version of Google Test when using Google Mock, or
-you may get compiler/linker errors.
-
-You can also easily configure Google Mock to work with another testing
-framework of your choice; although it will still need Google Test as
-an internal dependency.  Please read
-http://code.google.com/p/googlemock/wiki/ForDummies#Using_Google_Mock_with_Any_Testing_Framework
-for how to do it.
-
-Google Mock depends on advanced C++ features and thus requires a more
-modern compiler.  The following are needed to use Google Mock:
-
-### Linux Requirements ###
-
-These are the base requirements to build and use Google Mock from a source
-package (as described below):
-
-  * GNU-compatible Make or "gmake"
-  * POSIX-standard shell
-  * POSIX(-2) Regular Expressions (regex.h)
-  * C++98-standard-compliant compiler (e.g. GCC 3.4 or newer)
-
-### Windows Requirements ###
-
-  * Microsoft Visual C++ 8.0 SP1 or newer
-
-### Mac OS X Requirements ###
-
-  * Mac OS X 10.4 Tiger or newer
-  * Developer Tools Installed
-
-Requirements for Contributors
------------------------------
-
-We welcome patches.  If you plan to contribute a patch, you need to
-build Google Mock and its own tests from an SVN checkout (described
-below), which has further requirements:
-
-  * Automake version 1.9 or newer
-  * Autoconf version 2.59 or newer
-  * Libtool / Libtoolize
-  * Python version 2.3 or newer (for running some of the tests and
-    re-generating certain source files from templates)
-
-Getting the Source
-------------------
-
-There are two primary ways of getting Google Mock's source code: you
-can download a stable source release in your preferred archive format,
-or directly check out the source from our Subversion (SVN) repository.
-The SVN checkout requires a few extra steps and some extra software
-packages on your system, but lets you track development and make
-patches much more easily, so we highly encourage it.
-
-### Source Package ###
-
-Google Mock is released in versioned source packages which can be
-downloaded from the download page [1].  Several different archive
-formats are provided, but the only difference is the tools needed to
-extract their contents, and the size of the resulting file.  Download
-whichever you are most comfortable with.
-
-  [1] http://code.google.com/p/googlemock/downloads/list
-
-Once downloaded expand the archive using whichever tools you prefer
-for that type.  This will always result in a new directory with the
-name "gmock-X.Y.Z" which contains all of the source code.  Here are
-some examples on Linux:
-
-  tar -xvzf gmock-X.Y.Z.tar.gz
-  tar -xvjf gmock-X.Y.Z.tar.bz2
-  unzip gmock-X.Y.Z.zip
-
-### SVN Checkout ###
-
-To check out the main branch (also known as the "trunk") of Google
-Mock, run the following Subversion command:
-
-  svn checkout http://googlemock.googlecode.com/svn/trunk/ gmock-svn
-
-If you are using a *nix system and plan to use the GNU Autotools build
-system to build Google Mock (described below), you'll need to
-configure it now.  Otherwise you are done with getting the source
-files.
-
-To prepare the Autotools build system, enter the target directory of
-the checkout command you used ('gmock-svn') and proceed with the
-following command:
-
-  autoreconf -fvi
-
-Once you have completed this step, you are ready to build the library.
-Note that you should only need to complete this step once.  The
-subsequent 'make' invocations will automatically re-generate the bits
-of the build system that need to be changed.
-
-If your system uses older versions of the autotools, the above command
-will fail.  You may need to explicitly specify a version to use.  For
-instance, if you have both GNU Automake 1.4 and 1.9 installed and
-'automake' would invoke the 1.4, use instead:
-
-  AUTOMAKE=automake-1.9 ACLOCAL=aclocal-1.9 autoreconf -fvi
-
-Make sure you're using the same version of automake and aclocal.
-
-Setting up the Build
---------------------
-
-To build Google Mock and your tests that use it, you need to tell your
-build system where to find its headers and source files.  The exact
-way to do it depends on which build system you use, and is usually
-straightforward.
-
-### Generic Build Instructions ###
-
-This section shows how you can integrate Google Mock into your
-existing build system.
-
-Suppose you put Google Mock in directory ${GMOCK_DIR} and Google Test
-in ${GTEST_DIR} (the latter is ${GMOCK_DIR}/gtest by default).  To
-build Google Mock, create a library build target (or a project as
-called by Visual Studio and Xcode) to compile
-
-  ${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc
-
-with
-
-  ${GTEST_DIR}/include and ${GMOCK_DIR}/include
-
-in the system header search path, and
-
-  ${GTEST_DIR} and ${GMOCK_DIR}
-
-in the normal header search path.  Assuming a Linux-like system and gcc,
-something like the following will do:
-
-  g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
-      -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
-      -pthread -c ${GTEST_DIR}/src/gtest-all.cc
-  g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
-      -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
-      -pthread -c ${GMOCK_DIR}/src/gmock-all.cc
-  ar -rv libgmock.a gtest-all.o gmock-all.o
-
-(We need -pthread as Google Test and Google Mock use threads.)
-
-Next, you should compile your test source file with
-${GTEST_DIR}/include and ${GMOCK_DIR}/include in the header search
-path, and link it with gmock and any other necessary libraries:
-
-  g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \
-      -pthread path/to/your_test.cc libgmock.a -o your_test
-
-As an example, the make/ directory contains a Makefile that you can
-use to build Google Mock on systems where GNU make is available
-(e.g. Linux, Mac OS X, and Cygwin).  It doesn't try to build Google
-Mock's own tests.  Instead, it just builds the Google Mock library and
-a sample test.  You can use it as a starting point for your own build
-script.
-
-If the default settings are correct for your environment, the
-following commands should succeed:
-
-  cd ${GMOCK_DIR}/make
-  make
-  ./gmock_test
-
-If you see errors, try to tweak the contents of make/Makefile to make
-them go away.  There are instructions in make/Makefile on how to do
-it.
-
-### Windows ###
-
-The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010
-directory contains VC++ 2010 projects for building Google Mock and
-selected tests.
-
-Change to the appropriate directory and run "msbuild gmock.sln" to
-build the library and tests (or open the gmock.sln in the MSVC IDE).
-If you want to create your own project to use with Google Mock, you'll
-have to configure it to use the gmock_config propety sheet.  For that:
-
- * Open the Property Manager window (View | Other Windows | Property Manager)
- * Right-click on your project and select "Add Existing Property Sheet..."
- * Navigate to gmock_config.vsprops or gmock_config.props and select it.
- * In Project Properties | Configuration Properties | General | Additional
-   Include Directories, type <path to Google Mock>/include.
-
-Tweaking Google Mock
---------------------
-
-Google Mock can be used in diverse environments.  The default
-configuration may not work (or may not work well) out of the box in
-some environments.  However, you can easily tweak Google Mock by
-defining control macros on the compiler command line.  Generally,
-these macros are named like GTEST_XYZ and you define them to either 1
-or 0 to enable or disable a certain feature.
-
-We list the most frequently used macros below.  For a complete list,
-see file ${GTEST_DIR}/include/gtest/internal/gtest-port.h.
-
-### Choosing a TR1 Tuple Library ###
-
-Google Mock uses the C++ Technical Report 1 (TR1) tuple library
-heavily.  Unfortunately TR1 tuple is not yet widely available with all
-compilers.  The good news is that Google Test 1.4.0+ implements a
-subset of TR1 tuple that's enough for Google Mock's need.  Google Mock
-will automatically use that implementation when the compiler doesn't
-provide TR1 tuple.
-
-Usually you don't need to care about which tuple library Google Test
-and Google Mock use.  However, if your project already uses TR1 tuple,
-you need to tell Google Test and Google Mock to use the same TR1 tuple
-library the rest of your project uses, or the two tuple
-implementations will clash.  To do that, add
-
-  -DGTEST_USE_OWN_TR1_TUPLE=0
-
-to the compiler flags while compiling Google Test, Google Mock, and
-your tests.  If you want to force Google Test and Google Mock to use
-their own tuple library, just add
-
-  -DGTEST_USE_OWN_TR1_TUPLE=1
-
-to the compiler flags instead.
-
-If you want to use Boost's TR1 tuple library with Google Mock, please
-refer to the Boost website (http://www.boost.org/) for how to obtain
-it and set it up.
-
-### As a Shared Library (DLL) ###
-
-Google Mock is compact, so most users can build and link it as a static
-library for the simplicity.  Google Mock can be used as a DLL, but the
-same DLL must contain Google Test as well.  See Google Test's README
-file for instructions on how to set up necessary compiler settings.
-
-### Tweaking Google Mock ###
-
-Most of Google Test's control macros apply to Google Mock as well.
-Please see file ${GTEST_DIR}/README for how to tweak them.
-
-Upgrading from an Earlier Version
----------------------------------
-
-We strive to keep Google Mock releases backward compatible.
-Sometimes, though, we have to make some breaking changes for the
-users' long-term benefits.  This section describes what you'll need to
-do if you are upgrading from an earlier version of Google Mock.
-
-### Upgrading from 1.1.0 or Earlier ###
-
-You may need to explicitly enable or disable Google Test's own TR1
-tuple library.  See the instructions in section "Choosing a TR1 Tuple
-Library".
-
-### Upgrading from 1.4.0 or Earlier ###
-
-On platforms where the pthread library is available, Google Test and
-Google Mock use it in order to be thread-safe.  For this to work, you
-may need to tweak your compiler and/or linker flags.  Please see the
-"Multi-threaded Tests" section in file ${GTEST_DIR}/README for what
-you may need to do.
-
-If you have custom matchers defined using MatcherInterface or
-MakePolymorphicMatcher(), you'll need to update their definitions to
-use the new matcher API [2].  Matchers defined using MATCHER() or
-MATCHER_P*() aren't affected.
-
-  [2] http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers,
-      http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers
-
-Developing Google Mock
-----------------------
-
-This section discusses how to make your own changes to Google Mock.
-
-### Testing Google Mock Itself ###
-
-To make sure your changes work as intended and don't break existing
-functionality, you'll want to compile and run Google Test's own tests.
-For that you'll need Autotools.  First, make sure you have followed
-the instructions in section "SVN Checkout" to configure Google Mock.
-Then, create a build output directory and enter it.  Next,
-
-  ${GMOCK_DIR}/configure  # Standard GNU configure script, --help for more info
-
-Once you have successfully configured Google Mock, the build steps are
-standard for GNU-style OSS packages.
-
-  make        # Standard makefile following GNU conventions
-  make check  # Builds and runs all tests - all should pass.
-
-Note that when building your project against Google Mock, you are building
-against Google Test as well.  There is no need to configure Google Test
-separately.
-
-### Regenerating Source Files ###
-
-Some of Google Mock's source files are generated from templates (not
-in the C++ sense) using a script.  A template file is named FOO.pump,
-where FOO is the name of the file it will generate.  For example, the
-file include/gmock/gmock-generated-actions.h.pump is used to generate
-gmock-generated-actions.h in the same directory.
-
-Normally you don't need to worry about regenerating the source files,
-unless you need to modify them.  In that case, you should modify the
-corresponding .pump files instead and run the 'pump' script (for Pump
-is Useful for Meta Programming) to regenerate them.  You can find
-pump.py in the ${GTEST_DIR}/scripts/ directory.  Read the Pump manual
-[3] for how to use it.
-
-  [3] http://code.google.com/p/googletest/wiki/PumpManual.
-
-### Contributing a Patch ###
-
-We welcome patches.  Please read the Google Mock developer's guide [4]
-for how you can contribute.  In particular, make sure you have signed
-the Contributor License Agreement, or we won't be able to accept the
-patch.
-
-  [4] http://code.google.com/p/googlemock/wiki/DevGuide
-
-Happy testing!
diff --git a/testing/gmock/build-aux/.keep b/testing/gmock/build-aux/.keep
deleted file mode 100644
index e69de29..0000000
--- a/testing/gmock/build-aux/.keep
+++ /dev/null
diff --git a/testing/gmock/configure.ac b/testing/gmock/configure.ac
deleted file mode 100644
index d268d5d..0000000
--- a/testing/gmock/configure.ac
+++ /dev/null
@@ -1,146 +0,0 @@
-m4_include(gtest/m4/acx_pthread.m4)
-
-AC_INIT([Google C++ Mocking Framework],
-        [1.7.0],
-        [googlemock@googlegroups.com],
-        [gmock])
-
-# Provide various options to initialize the Autoconf and configure processes.
-AC_PREREQ([2.59])
-AC_CONFIG_SRCDIR([./LICENSE])
-AC_CONFIG_AUX_DIR([build-aux])
-AC_CONFIG_HEADERS([build-aux/config.h])
-AC_CONFIG_FILES([Makefile])
-AC_CONFIG_FILES([scripts/gmock-config], [chmod +x scripts/gmock-config])
-
-# Initialize Automake with various options. We require at least v1.9, prevent
-# pedantic complaints about package files, and enable various distribution
-# targets.
-AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects])
-
-# Check for programs used in building Google Test.
-AC_PROG_CC
-AC_PROG_CXX
-AC_LANG([C++])
-AC_PROG_LIBTOOL
-
-# TODO(chandlerc@google.com): Currently we aren't running the Python tests
-# against the interpreter detected by AM_PATH_PYTHON, and so we condition
-# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's
-# version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env"
-# hashbang.
-PYTHON=  # We *do not* allow the user to specify a python interpreter
-AC_PATH_PROG([PYTHON],[python],[:])
-AS_IF([test "$PYTHON" != ":"],
-      [AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])])
-AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"])
-
-# TODO(chandlerc@google.com) Check for the necessary system headers.
-
-# Configure pthreads.
-AC_ARG_WITH([pthreads],
-            [AS_HELP_STRING([--with-pthreads],
-               [use pthreads (default is yes)])],
-            [with_pthreads=$withval],
-            [with_pthreads=check])
-
-have_pthreads=no
-AS_IF([test "x$with_pthreads" != "xno"],
-      [ACX_PTHREAD(
-        [],
-        [AS_IF([test "x$with_pthreads" != "xcheck"],
-               [AC_MSG_FAILURE(
-                 [--with-pthreads was specified, but unable to be used])])])
-       have_pthreads="$acx_pthread_ok"])
-AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" == "xyes"])
-AC_SUBST(PTHREAD_CFLAGS)
-AC_SUBST(PTHREAD_LIBS)
-
-# GoogleMock currently has hard dependencies upon GoogleTest above and beyond
-# running its own test suite, so we both provide our own version in
-# a subdirectory and provide some logic to use a custom version or a system
-# installed version.
-AC_ARG_WITH([gtest],
-            [AS_HELP_STRING([--with-gtest],
-                            [Specifies how to find the gtest package. If no
-                            arguments are given, the default behavior, a
-                            system installed gtest will be used if present,
-                            and an internal version built otherwise. If a
-                            path is provided, the gtest built or installed at
-                            that prefix will be used.])],
-            [],
-            [with_gtest=yes])
-AC_ARG_ENABLE([external-gtest],
-              [AS_HELP_STRING([--disable-external-gtest],
-                              [Disables any detection or use of a system
-                              installed or user provided gtest. Any option to
-                              '--with-gtest' is ignored. (Default is enabled.)])
-              ], [], [enable_external_gtest=yes])
-AS_IF([test "x$with_gtest" == "xno"],
-      [AC_MSG_ERROR([dnl
-Support for GoogleTest was explicitly disabled. Currently GoogleMock has a hard
-dependency upon GoogleTest to build, please provide a version, or allow
-GoogleMock to use any installed version and fall back upon its internal
-version.])])
-
-# Setup various GTEST variables. TODO(chandlerc@google.com): When these are
-# used below, they should be used such that any pre-existing values always
-# trump values we set them to, so that they can be used to selectively override
-# details of the detection process.
-AC_ARG_VAR([GTEST_CONFIG],
-           [The exact path of Google Test's 'gtest-config' script.])
-AC_ARG_VAR([GTEST_CPPFLAGS],
-           [C-like preprocessor flags for Google Test.])
-AC_ARG_VAR([GTEST_CXXFLAGS],
-           [C++ compile flags for Google Test.])
-AC_ARG_VAR([GTEST_LDFLAGS],
-           [Linker path and option flags for Google Test.])
-AC_ARG_VAR([GTEST_LIBS],
-           [Library linking flags for Google Test.])
-AC_ARG_VAR([GTEST_VERSION],
-           [The version of Google Test available.])
-HAVE_BUILT_GTEST="no"
-
-GTEST_MIN_VERSION="1.7.0"
-
-AS_IF([test "x${enable_external_gtest}" = "xyes"],
-      [# Begin filling in variables as we are able.
-      AS_IF([test "x${with_gtest}" != "xyes"],
-            [AS_IF([test -x "${with_gtest}/scripts/gtest-config"],
-                   [GTEST_CONFIG="${with_gtest}/scripts/gtest-config"],
-                   [GTEST_CONFIG="${with_gtest}/bin/gtest-config"])
-            AS_IF([test -x "${GTEST_CONFIG}"], [],
-                  [AC_MSG_ERROR([dnl
-Unable to locate either a built or installed Google Test at '${with_gtest}'.])
-                  ])])
-
-      AS_IF([test -x "${GTEST_CONFIG}"], [],
-            [AC_PATH_PROG([GTEST_CONFIG], [gtest-config])])
-      AS_IF([test -x "${GTEST_CONFIG}"],
-            [AC_MSG_CHECKING([for Google Test version >= ${GTEST_MIN_VERSION}])
-            AS_IF([${GTEST_CONFIG} --min-version=${GTEST_MIN_VERSION}],
-                  [AC_MSG_RESULT([yes])
-                  HAVE_BUILT_GTEST="yes"],
-                  [AC_MSG_RESULT([no])])])])
-
-AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"],
-      [GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags`
-      GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags`
-      GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags`
-      GTEST_LIBS=`${GTEST_CONFIG} --libs`
-      GTEST_VERSION=`${GTEST_CONFIG} --version`],
-      [AC_CONFIG_SUBDIRS([gtest])
-      # GTEST_CONFIG needs to be executable both in a Makefile environmont and
-      # in a shell script environment, so resolve an absolute path for it here.
-      GTEST_CONFIG="`pwd -P`/gtest/scripts/gtest-config"
-      GTEST_CPPFLAGS='-I$(top_srcdir)/gtest/include'
-      GTEST_CXXFLAGS='-g'
-      GTEST_LDFLAGS=''
-      GTEST_LIBS='$(top_builddir)/gtest/lib/libgtest.la'
-      GTEST_VERSION="${GTEST_MIN_VERSION}"])
-
-# TODO(chandlerc@google.com) Check the types, structures, and other compiler
-# and architecture characteristics.
-
-# Output the generated files. No further autoconf macros may be used.
-AC_OUTPUT
diff --git a/testing/gmock/include/gmock/gmock-actions.h b/testing/gmock/include/gmock/gmock-actions.h
index c09c4d6..46d1184 100644
--- a/testing/gmock/include/gmock/gmock-actions.h
+++ b/testing/gmock/include/gmock/gmock-actions.h
@@ -1,1205 +1,15 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
+// Copyright 2017 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
 
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used actions.
+#ifndef TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#define TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
 
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+// The file/directory layout of Google Test is not yet considered stable. Until
+// it stabilizes, Chromium code will use forwarding headers in testing/gtest
+// and testing/gmock, instead of directly including files in
+// third_party/googletest.
 
-#ifndef _WIN32_WCE
-# include <errno.h>
-#endif
+#include "third_party/googletest/src/googlemock/include/gmock/gmock-actions.h"
 
-#include <algorithm>
-#include <string>
-
-#include "gmock/internal/gmock-internal-utils.h"
-#include "gmock/internal/gmock-port.h"
-
-#if GTEST_LANG_CXX11  // Defined by gtest-port.h via gmock-port.h.
-#include <type_traits>
-#endif
-
-namespace testing {
-
-// To implement an action Foo, define:
-//   1. a class FooAction that implements the ActionInterface interface, and
-//   2. a factory function that creates an Action object from a
-//      const FooAction*.
-//
-// The two-level delegation design follows that of Matcher, providing
-// consistency for extension developers.  It also eases ownership
-// management as Action objects can now be copied like plain values.
-
-namespace internal {
-
-template <typename F1, typename F2>
-class ActionAdaptor;
-
-// BuiltInDefaultValueGetter<T, true>::Get() returns a
-// default-constructed T value.  BuiltInDefaultValueGetter<T,
-// false>::Get() crashes with an error.
-//
-// This primary template is used when kDefaultConstructible is true.
-template <typename T, bool kDefaultConstructible>
-struct BuiltInDefaultValueGetter {
-  static T Get() { return T(); }
-};
-template <typename T>
-struct BuiltInDefaultValueGetter<T, false> {
-  static T Get() {
-    Assert(false, __FILE__, __LINE__,
-           "Default action undefined for the function return type.");
-    return internal::Invalid<T>();
-    // The above statement will never be reached, but is required in
-    // order for this function to compile.
-  }
-};
-
-// BuiltInDefaultValue<T>::Get() returns the "built-in" default value
-// for type T, which is NULL when T is a raw pointer type, 0 when T is
-// a numeric type, false when T is bool, or "" when T is string or
-// std::string.  In addition, in C++11 and above, it turns a
-// default-constructed T value if T is default constructible.  For any
-// other type T, the built-in default T value is undefined, and the
-// function will abort the process.
-template <typename T>
-class BuiltInDefaultValue {
- public:
-#if GTEST_LANG_CXX11
-  // This function returns true iff type T has a built-in default value.
-  static bool Exists() {
-    return ::std::is_default_constructible<T>::value;
-  }
-
-  static T Get() {
-    return BuiltInDefaultValueGetter<
-        T, ::std::is_default_constructible<T>::value>::Get();
-  }
-
-#else  // GTEST_LANG_CXX11
-  // This function returns true iff type T has a built-in default value.
-  static bool Exists() {
-    return false;
-  }
-
-  static T Get() {
-    return BuiltInDefaultValueGetter<T, false>::Get();
-  }
-
-#endif  // GTEST_LANG_CXX11
-};
-
-// This partial specialization says that we use the same built-in
-// default value for T and const T.
-template <typename T>
-class BuiltInDefaultValue<const T> {
- public:
-  static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
-  static T Get() { return BuiltInDefaultValue<T>::Get(); }
-};
-
-// This partial specialization defines the default values for pointer
-// types.
-template <typename T>
-class BuiltInDefaultValue<T*> {
- public:
-  static bool Exists() { return true; }
-  static T* Get() { return NULL; }
-};
-
-// The following specializations define the default values for
-// specific types we care about.
-#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
-  template <> \
-  class BuiltInDefaultValue<type> { \
-   public: \
-    static bool Exists() { return true; } \
-    static type Get() { return value; } \
-  }
-
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
-#if GTEST_HAS_GLOBAL_STRING
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
-#endif  // GTEST_HAS_GLOBAL_STRING
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
-
-// There's no need for a default action for signed wchar_t, as that
-// type is the same as wchar_t for gcc, and invalid for MSVC.
-//
-// There's also no need for a default action for unsigned wchar_t, as
-// that type is the same as unsigned int for gcc, and invalid for
-// MSVC.
-#if GMOCK_WCHAR_T_IS_NATIVE_
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT
-#endif
-
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);  // NOLINT
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);     // NOLINT
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
-
-#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
-
-}  // namespace internal
-
-// When an unexpected function call is encountered, Google Mock will
-// let it return a default value if the user has specified one for its
-// return type, or if the return type has a built-in default value;
-// otherwise Google Mock won't know what value to return and will have
-// to abort the process.
-//
-// The DefaultValue<T> class allows a user to specify the
-// default value for a type T that is both copyable and publicly
-// destructible (i.e. anything that can be used as a function return
-// type).  The usage is:
-//
-//   // Sets the default value for type T to be foo.
-//   DefaultValue<T>::Set(foo);
-template <typename T>
-class DefaultValue {
- public:
-  // Sets the default value for type T; requires T to be
-  // copy-constructable and have a public destructor.
-  static void Set(T x) {
-    delete producer_;
-    producer_ = new FixedValueProducer(x);
-  }
-
-  // Provides a factory function to be called to generate the default value.
-  // This method can be used even if T is only move-constructible, but it is not
-  // limited to that case.
-  typedef T (*FactoryFunction)();
-  static void SetFactory(FactoryFunction factory) {
-    delete producer_;
-    producer_ = new FactoryValueProducer(factory);
-  }
-
-  // Unsets the default value for type T.
-  static void Clear() {
-    delete producer_;
-    producer_ = NULL;
-  }
-
-  // Returns true iff the user has set the default value for type T.
-  static bool IsSet() { return producer_ != NULL; }
-
-  // Returns true if T has a default return value set by the user or there
-  // exists a built-in default value.
-  static bool Exists() {
-    return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
-  }
-
-  // Returns the default value for type T if the user has set one;
-  // otherwise returns the built-in default value. Requires that Exists()
-  // is true, which ensures that the return value is well-defined.
-  static T Get() {
-    return producer_ == NULL ?
-        internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
-  }
-
- private:
-  class ValueProducer {
-   public:
-    virtual ~ValueProducer() {}
-    virtual T Produce() = 0;
-  };
-
-  class FixedValueProducer : public ValueProducer {
-   public:
-    explicit FixedValueProducer(T value) : value_(value) {}
-    virtual T Produce() { return value_; }
-
-   private:
-    const T value_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
-  };
-
-  class FactoryValueProducer : public ValueProducer {
-   public:
-    explicit FactoryValueProducer(FactoryFunction factory)
-        : factory_(factory) {}
-    virtual T Produce() { return factory_(); }
-
-   private:
-    const FactoryFunction factory_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
-  };
-
-  static ValueProducer* producer_;
-};
-
-// This partial specialization allows a user to set default values for
-// reference types.
-template <typename T>
-class DefaultValue<T&> {
- public:
-  // Sets the default value for type T&.
-  static void Set(T& x) {  // NOLINT
-    address_ = &x;
-  }
-
-  // Unsets the default value for type T&.
-  static void Clear() {
-    address_ = NULL;
-  }
-
-  // Returns true iff the user has set the default value for type T&.
-  static bool IsSet() { return address_ != NULL; }
-
-  // Returns true if T has a default return value set by the user or there
-  // exists a built-in default value.
-  static bool Exists() {
-    return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
-  }
-
-  // Returns the default value for type T& if the user has set one;
-  // otherwise returns the built-in default value if there is one;
-  // otherwise aborts the process.
-  static T& Get() {
-    return address_ == NULL ?
-        internal::BuiltInDefaultValue<T&>::Get() : *address_;
-  }
-
- private:
-  static T* address_;
-};
-
-// This specialization allows DefaultValue<void>::Get() to
-// compile.
-template <>
-class DefaultValue<void> {
- public:
-  static bool Exists() { return true; }
-  static void Get() {}
-};
-
-// Points to the user-set default value for type T.
-template <typename T>
-typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
-
-// Points to the user-set default value for type T&.
-template <typename T>
-T* DefaultValue<T&>::address_ = NULL;
-
-// Implement this interface to define an action for function type F.
-template <typename F>
-class ActionInterface {
- public:
-  typedef typename internal::Function<F>::Result Result;
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  ActionInterface() {}
-  virtual ~ActionInterface() {}
-
-  // Performs the action.  This method is not const, as in general an
-  // action can have side effects and be stateful.  For example, a
-  // get-the-next-element-from-the-collection action will need to
-  // remember the current element.
-  virtual Result Perform(const ArgumentTuple& args) = 0;
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
-};
-
-// An Action<F> is a copyable and IMMUTABLE (except by assignment)
-// object that represents an action to be taken when a mock function
-// of type F is called.  The implementation of Action<T> is just a
-// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
-// Don't inherit from Action!
-//
-// You can view an object implementing ActionInterface<F> as a
-// concrete action (including its current state), and an Action<F>
-// object as a handle to it.
-template <typename F>
-class Action {
- public:
-  typedef typename internal::Function<F>::Result Result;
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  // Constructs a null Action.  Needed for storing Action objects in
-  // STL containers.
-  Action() : impl_(NULL) {}
-
-  // Constructs an Action from its implementation.  A NULL impl is
-  // used to represent the "do-default" action.
-  explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
-
-  // Copy constructor.
-  Action(const Action& action) : impl_(action.impl_) {}
-
-  // This constructor allows us to turn an Action<Func> object into an
-  // Action<F>, as long as F's arguments can be implicitly converted
-  // to Func's and Func's return type can be implicitly converted to
-  // F's.
-  template <typename Func>
-  explicit Action(const Action<Func>& action);
-
-  // Returns true iff this is the DoDefault() action.
-  bool IsDoDefault() const { return impl_.get() == NULL; }
-
-  // Performs the action.  Note that this method is const even though
-  // the corresponding method in ActionInterface is not.  The reason
-  // is that a const Action<F> means that it cannot be re-bound to
-  // another concrete action, not that the concrete action it binds to
-  // cannot change state.  (Think of the difference between a const
-  // pointer and a pointer to const.)
-  Result Perform(const ArgumentTuple& args) const {
-    internal::Assert(
-        !IsDoDefault(), __FILE__, __LINE__,
-        "You are using DoDefault() inside a composite action like "
-        "DoAll() or WithArgs().  This is not supported for technical "
-        "reasons.  Please instead spell out the default action, or "
-        "assign the default action to an Action variable and use "
-        "the variable in various places.");
-    return impl_->Perform(args);
-  }
-
- private:
-  template <typename F1, typename F2>
-  friend class internal::ActionAdaptor;
-
-  internal::linked_ptr<ActionInterface<F> > impl_;
-};
-
-// The PolymorphicAction class template makes it easy to implement a
-// polymorphic action (i.e. an action that can be used in mock
-// functions of than one type, e.g. Return()).
-//
-// To define a polymorphic action, a user first provides a COPYABLE
-// implementation class that has a Perform() method template:
-//
-//   class FooAction {
-//    public:
-//     template <typename Result, typename ArgumentTuple>
-//     Result Perform(const ArgumentTuple& args) const {
-//       // Processes the arguments and returns a result, using
-//       // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
-//     }
-//     ...
-//   };
-//
-// Then the user creates the polymorphic action using
-// MakePolymorphicAction(object) where object has type FooAction.  See
-// the definition of Return(void) and SetArgumentPointee<N>(value) for
-// complete examples.
-template <typename Impl>
-class PolymorphicAction {
- public:
-  explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
-
-  template <typename F>
-  operator Action<F>() const {
-    return Action<F>(new MonomorphicImpl<F>(impl_));
-  }
-
- private:
-  template <typename F>
-  class MonomorphicImpl : public ActionInterface<F> {
-   public:
-    typedef typename internal::Function<F>::Result Result;
-    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
-
-    virtual Result Perform(const ArgumentTuple& args) {
-      return impl_.template Perform<Result>(args);
-    }
-
-   private:
-    Impl impl_;
-
-    GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
-  };
-
-  Impl impl_;
-
-  GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
-};
-
-// Creates an Action from its implementation and returns it.  The
-// created Action object owns the implementation.
-template <typename F>
-Action<F> MakeAction(ActionInterface<F>* impl) {
-  return Action<F>(impl);
-}
-
-// Creates a polymorphic action from its implementation.  This is
-// easier to use than the PolymorphicAction<Impl> constructor as it
-// doesn't require you to explicitly write the template argument, e.g.
-//
-//   MakePolymorphicAction(foo);
-// vs
-//   PolymorphicAction<TypeOfFoo>(foo);
-template <typename Impl>
-inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
-  return PolymorphicAction<Impl>(impl);
-}
-
-namespace internal {
-
-// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
-// and F1 are compatible.
-template <typename F1, typename F2>
-class ActionAdaptor : public ActionInterface<F1> {
- public:
-  typedef typename internal::Function<F1>::Result Result;
-  typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
-
-  explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
-
-  virtual Result Perform(const ArgumentTuple& args) {
-    return impl_->Perform(args);
-  }
-
- private:
-  const internal::linked_ptr<ActionInterface<F2> > impl_;
-
-  GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
-};
-
-// Helper struct to specialize ReturnAction to execute a move instead of a copy
-// on return. Useful for move-only types, but could be used on any type.
-template <typename T>
-struct ByMoveWrapper {
-  explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
-  T payload;
-};
-
-// Implements the polymorphic Return(x) action, which can be used in
-// any function that returns the type of x, regardless of the argument
-// types.
-//
-// Note: The value passed into Return must be converted into
-// Function<F>::Result when this action is cast to Action<F> rather than
-// when that action is performed. This is important in scenarios like
-//
-// MOCK_METHOD1(Method, T(U));
-// ...
-// {
-//   Foo foo;
-//   X x(&foo);
-//   EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
-// }
-//
-// In the example above the variable x holds reference to foo which leaves
-// scope and gets destroyed.  If copying X just copies a reference to foo,
-// that copy will be left with a hanging reference.  If conversion to T
-// makes a copy of foo, the above code is safe. To support that scenario, we
-// need to make sure that the type conversion happens inside the EXPECT_CALL
-// statement, and conversion of the result of Return to Action<T(U)> is a
-// good place for that.
-//
-template <typename R>
-class ReturnAction {
- public:
-  // Constructs a ReturnAction object from the value to be returned.
-  // 'value' is passed by value instead of by const reference in order
-  // to allow Return("string literal") to compile.
-  explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
-
-  // This template type conversion operator allows Return(x) to be
-  // used in ANY function that returns x's type.
-  template <typename F>
-  operator Action<F>() const {
-    // Assert statement belongs here because this is the best place to verify
-    // conditions on F. It produces the clearest error messages
-    // in most compilers.
-    // Impl really belongs in this scope as a local class but can't
-    // because MSVC produces duplicate symbols in different translation units
-    // in this case. Until MS fixes that bug we put Impl into the class scope
-    // and put the typedef both here (for use in assert statement) and
-    // in the Impl class. But both definitions must be the same.
-    typedef typename Function<F>::Result Result;
-    GTEST_COMPILE_ASSERT_(
-        !is_reference<Result>::value,
-        use_ReturnRef_instead_of_Return_to_return_a_reference);
-    return Action<F>(new Impl<R, F>(value_));
-  }
-
- private:
-  // Implements the Return(x) action for a particular function type F.
-  template <typename R_, typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-
-    // The implicit cast is necessary when Result has more than one
-    // single-argument constructor (e.g. Result is std::vector<int>) and R
-    // has a type conversion operator template.  In that case, value_(value)
-    // won't compile as the compiler doesn't known which constructor of
-    // Result to call.  ImplicitCast_ forces the compiler to convert R to
-    // Result without considering explicit constructors, thus resolving the
-    // ambiguity. value_ is then initialized using its copy constructor.
-    explicit Impl(const linked_ptr<R>& value)
-        : value_before_cast_(*value),
-          value_(ImplicitCast_<Result>(value_before_cast_)) {}
-
-    virtual Result Perform(const ArgumentTuple&) { return value_; }
-
-   private:
-    GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
-                          Result_cannot_be_a_reference_type);
-    // We save the value before casting just in case it is being cast to a
-    // wrapper type.
-    R value_before_cast_;
-    Result value_;
-
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
-  };
-
-  // Partially specialize for ByMoveWrapper. This version of ReturnAction will
-  // move its contents instead.
-  template <typename R_, typename F>
-  class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit Impl(const linked_ptr<R>& wrapper)
-        : performed_(false), wrapper_(wrapper) {}
-
-    virtual Result Perform(const ArgumentTuple&) {
-      GTEST_CHECK_(!performed_)
-          << "A ByMove() action should only be performed once.";
-      performed_ = true;
-      return internal::move(wrapper_->payload);
-    }
-
-   private:
-    bool performed_;
-    const linked_ptr<R> wrapper_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  const linked_ptr<R> value_;
-
-  GTEST_DISALLOW_ASSIGN_(ReturnAction);
-};
-
-// Implements the ReturnNull() action.
-class ReturnNullAction {
- public:
-  // Allows ReturnNull() to be used in any pointer-returning function. In C++11
-  // this is enforced by returning nullptr, and in non-C++11 by asserting a
-  // pointer type on compile time.
-  template <typename Result, typename ArgumentTuple>
-  static Result Perform(const ArgumentTuple&) {
-#if GTEST_LANG_CXX11
-    return nullptr;
-#else
-    GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
-                          ReturnNull_can_be_used_to_return_a_pointer_only);
-    return NULL;
-#endif  // GTEST_LANG_CXX11
-  }
-};
-
-// Implements the Return() action.
-class ReturnVoidAction {
- public:
-  // Allows Return() to be used in any void-returning function.
-  template <typename Result, typename ArgumentTuple>
-  static void Perform(const ArgumentTuple&) {
-    CompileAssertTypesEqual<void, Result>();
-  }
-};
-
-// Implements the polymorphic ReturnRef(x) action, which can be used
-// in any function that returns a reference to the type of x,
-// regardless of the argument types.
-template <typename T>
-class ReturnRefAction {
- public:
-  // Constructs a ReturnRefAction object from the reference to be returned.
-  explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT
-
-  // This template type conversion operator allows ReturnRef(x) to be
-  // used in ANY function that returns a reference to x's type.
-  template <typename F>
-  operator Action<F>() const {
-    typedef typename Function<F>::Result Result;
-    // Asserts that the function return type is a reference.  This
-    // catches the user error of using ReturnRef(x) when Return(x)
-    // should be used, and generates some helpful error message.
-    GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
-                          use_Return_instead_of_ReturnRef_to_return_a_value);
-    return Action<F>(new Impl<F>(ref_));
-  }
-
- private:
-  // Implements the ReturnRef(x) action for a particular function type F.
-  template <typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit Impl(T& ref) : ref_(ref) {}  // NOLINT
-
-    virtual Result Perform(const ArgumentTuple&) {
-      return ref_;
-    }
-
-   private:
-    T& ref_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  T& ref_;
-
-  GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
-};
-
-// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
-// used in any function that returns a reference to the type of x,
-// regardless of the argument types.
-template <typename T>
-class ReturnRefOfCopyAction {
- public:
-  // Constructs a ReturnRefOfCopyAction object from the reference to
-  // be returned.
-  explicit ReturnRefOfCopyAction(const T& value) : value_(value) {}  // NOLINT
-
-  // This template type conversion operator allows ReturnRefOfCopy(x) to be
-  // used in ANY function that returns a reference to x's type.
-  template <typename F>
-  operator Action<F>() const {
-    typedef typename Function<F>::Result Result;
-    // Asserts that the function return type is a reference.  This
-    // catches the user error of using ReturnRefOfCopy(x) when Return(x)
-    // should be used, and generates some helpful error message.
-    GTEST_COMPILE_ASSERT_(
-        internal::is_reference<Result>::value,
-        use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
-    return Action<F>(new Impl<F>(value_));
-  }
-
- private:
-  // Implements the ReturnRefOfCopy(x) action for a particular function type F.
-  template <typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit Impl(const T& value) : value_(value) {}  // NOLINT
-
-    virtual Result Perform(const ArgumentTuple&) {
-      return value_;
-    }
-
-   private:
-    T value_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  const T value_;
-
-  GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
-};
-
-// Implements the polymorphic DoDefault() action.
-class DoDefaultAction {
- public:
-  // This template type conversion operator allows DoDefault() to be
-  // used in any function.
-  template <typename F>
-  operator Action<F>() const { return Action<F>(NULL); }
-};
-
-// Implements the Assign action to set a given pointer referent to a
-// particular value.
-template <typename T1, typename T2>
-class AssignAction {
- public:
-  AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
-
-  template <typename Result, typename ArgumentTuple>
-  void Perform(const ArgumentTuple& /* args */) const {
-    *ptr_ = value_;
-  }
-
- private:
-  T1* const ptr_;
-  const T2 value_;
-
-  GTEST_DISALLOW_ASSIGN_(AssignAction);
-};
-
-#if !GTEST_OS_WINDOWS_MOBILE
-
-// Implements the SetErrnoAndReturn action to simulate return from
-// various system calls and libc functions.
-template <typename T>
-class SetErrnoAndReturnAction {
- public:
-  SetErrnoAndReturnAction(int errno_value, T result)
-      : errno_(errno_value),
-        result_(result) {}
-  template <typename Result, typename ArgumentTuple>
-  Result Perform(const ArgumentTuple& /* args */) const {
-    errno = errno_;
-    return result_;
-  }
-
- private:
-  const int errno_;
-  const T result_;
-
-  GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
-};
-
-#endif  // !GTEST_OS_WINDOWS_MOBILE
-
-// Implements the SetArgumentPointee<N>(x) action for any function
-// whose N-th argument (0-based) is a pointer to x's type.  The
-// template parameter kIsProto is true iff type A is ProtocolMessage,
-// proto2::Message, or a sub-class of those.
-template <size_t N, typename A, bool kIsProto>
-class SetArgumentPointeeAction {
- public:
-  // Constructs an action that sets the variable pointed to by the
-  // N-th function argument to 'value'.
-  explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
-
-  template <typename Result, typename ArgumentTuple>
-  void Perform(const ArgumentTuple& args) const {
-    CompileAssertTypesEqual<void, Result>();
-    *::testing::get<N>(args) = value_;
-  }
-
- private:
-  const A value_;
-
-  GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
-};
-
-template <size_t N, typename Proto>
-class SetArgumentPointeeAction<N, Proto, true> {
- public:
-  // Constructs an action that sets the variable pointed to by the
-  // N-th function argument to 'proto'.  Both ProtocolMessage and
-  // proto2::Message have the CopyFrom() method, so the same
-  // implementation works for both.
-  explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
-    proto_->CopyFrom(proto);
-  }
-
-  template <typename Result, typename ArgumentTuple>
-  void Perform(const ArgumentTuple& args) const {
-    CompileAssertTypesEqual<void, Result>();
-    ::testing::get<N>(args)->CopyFrom(*proto_);
-  }
-
- private:
-  const internal::linked_ptr<Proto> proto_;
-
-  GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
-};
-
-// Implements the InvokeWithoutArgs(f) action.  The template argument
-// FunctionImpl is the implementation type of f, which can be either a
-// function pointer or a functor.  InvokeWithoutArgs(f) can be used as an
-// Action<F> as long as f's type is compatible with F (i.e. f can be
-// assigned to a tr1::function<F>).
-template <typename FunctionImpl>
-class InvokeWithoutArgsAction {
- public:
-  // The c'tor makes a copy of function_impl (either a function
-  // pointer or a functor).
-  explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
-      : function_impl_(function_impl) {}
-
-  // Allows InvokeWithoutArgs(f) to be used as any action whose type is
-  // compatible with f.
-  template <typename Result, typename ArgumentTuple>
-  Result Perform(const ArgumentTuple&) { return function_impl_(); }
-
- private:
-  FunctionImpl function_impl_;
-
-  GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
-};
-
-// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
-template <class Class, typename MethodPtr>
-class InvokeMethodWithoutArgsAction {
- public:
-  InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
-      : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
-
-  template <typename Result, typename ArgumentTuple>
-  Result Perform(const ArgumentTuple&) const {
-    return (obj_ptr_->*method_ptr_)();
-  }
-
- private:
-  Class* const obj_ptr_;
-  const MethodPtr method_ptr_;
-
-  GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
-};
-
-// Implements the IgnoreResult(action) action.
-template <typename A>
-class IgnoreResultAction {
- public:
-  explicit IgnoreResultAction(const A& action) : action_(action) {}
-
-  template <typename F>
-  operator Action<F>() const {
-    // Assert statement belongs here because this is the best place to verify
-    // conditions on F. It produces the clearest error messages
-    // in most compilers.
-    // Impl really belongs in this scope as a local class but can't
-    // because MSVC produces duplicate symbols in different translation units
-    // in this case. Until MS fixes that bug we put Impl into the class scope
-    // and put the typedef both here (for use in assert statement) and
-    // in the Impl class. But both definitions must be the same.
-    typedef typename internal::Function<F>::Result Result;
-
-    // Asserts at compile time that F returns void.
-    CompileAssertTypesEqual<void, Result>();
-
-    return Action<F>(new Impl<F>(action_));
-  }
-
- private:
-  template <typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename internal::Function<F>::Result Result;
-    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit Impl(const A& action) : action_(action) {}
-
-    virtual void Perform(const ArgumentTuple& args) {
-      // Performs the action and ignores its result.
-      action_.Perform(args);
-    }
-
-   private:
-    // Type OriginalFunction is the same as F except that its return
-    // type is IgnoredValue.
-    typedef typename internal::Function<F>::MakeResultIgnoredValue
-        OriginalFunction;
-
-    const Action<OriginalFunction> action_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  const A action_;
-
-  GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
-};
-
-// A ReferenceWrapper<T> object represents a reference to type T,
-// which can be either const or not.  It can be explicitly converted
-// from, and implicitly converted to, a T&.  Unlike a reference,
-// ReferenceWrapper<T> can be copied and can survive template type
-// inference.  This is used to support by-reference arguments in the
-// InvokeArgument<N>(...) action.  The idea was from "reference
-// wrappers" in tr1, which we don't have in our source tree yet.
-template <typename T>
-class ReferenceWrapper {
- public:
-  // Constructs a ReferenceWrapper<T> object from a T&.
-  explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {}  // NOLINT
-
-  // Allows a ReferenceWrapper<T> object to be implicitly converted to
-  // a T&.
-  operator T&() const { return *pointer_; }
- private:
-  T* pointer_;
-};
-
-// Allows the expression ByRef(x) to be printed as a reference to x.
-template <typename T>
-void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
-  T& value = ref;
-  UniversalPrinter<T&>::Print(value, os);
-}
-
-// Does two actions sequentially.  Used for implementing the DoAll(a1,
-// a2, ...) action.
-template <typename Action1, typename Action2>
-class DoBothAction {
- public:
-  DoBothAction(Action1 action1, Action2 action2)
-      : action1_(action1), action2_(action2) {}
-
-  // This template type conversion operator allows DoAll(a1, ..., a_n)
-  // to be used in ANY function of compatible type.
-  template <typename F>
-  operator Action<F>() const {
-    return Action<F>(new Impl<F>(action1_, action2_));
-  }
-
- private:
-  // Implements the DoAll(...) action for a particular function type F.
-  template <typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-    typedef typename Function<F>::MakeResultVoid VoidResult;
-
-    Impl(const Action<VoidResult>& action1, const Action<F>& action2)
-        : action1_(action1), action2_(action2) {}
-
-    virtual Result Perform(const ArgumentTuple& args) {
-      action1_.Perform(args);
-      return action2_.Perform(args);
-    }
-
-   private:
-    const Action<VoidResult> action1_;
-    const Action<F> action2_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  Action1 action1_;
-  Action2 action2_;
-
-  GTEST_DISALLOW_ASSIGN_(DoBothAction);
-};
-
-}  // namespace internal
-
-// An Unused object can be implicitly constructed from ANY value.
-// This is handy when defining actions that ignore some or all of the
-// mock function arguments.  For example, given
-//
-//   MOCK_METHOD3(Foo, double(const string& label, double x, double y));
-//   MOCK_METHOD3(Bar, double(int index, double x, double y));
-//
-// instead of
-//
-//   double DistanceToOriginWithLabel(const string& label, double x, double y) {
-//     return sqrt(x*x + y*y);
-//   }
-//   double DistanceToOriginWithIndex(int index, double x, double y) {
-//     return sqrt(x*x + y*y);
-//   }
-//   ...
-//   EXEPCT_CALL(mock, Foo("abc", _, _))
-//       .WillOnce(Invoke(DistanceToOriginWithLabel));
-//   EXEPCT_CALL(mock, Bar(5, _, _))
-//       .WillOnce(Invoke(DistanceToOriginWithIndex));
-//
-// you could write
-//
-//   // We can declare any uninteresting argument as Unused.
-//   double DistanceToOrigin(Unused, double x, double y) {
-//     return sqrt(x*x + y*y);
-//   }
-//   ...
-//   EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
-//   EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
-typedef internal::IgnoredValue Unused;
-
-// This constructor allows us to turn an Action<From> object into an
-// Action<To>, as long as To's arguments can be implicitly converted
-// to From's and From's return type cann be implicitly converted to
-// To's.
-template <typename To>
-template <typename From>
-Action<To>::Action(const Action<From>& from)
-    : impl_(new internal::ActionAdaptor<To, From>(from)) {}
-
-// Creates an action that returns 'value'.  'value' is passed by value
-// instead of const reference - otherwise Return("string literal")
-// will trigger a compiler error about using array as initializer.
-template <typename R>
-internal::ReturnAction<R> Return(R value) {
-  return internal::ReturnAction<R>(internal::move(value));
-}
-
-// Creates an action that returns NULL.
-inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
-  return MakePolymorphicAction(internal::ReturnNullAction());
-}
-
-// Creates an action that returns from a void function.
-inline PolymorphicAction<internal::ReturnVoidAction> Return() {
-  return MakePolymorphicAction(internal::ReturnVoidAction());
-}
-
-// Creates an action that returns the reference to a variable.
-template <typename R>
-inline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT
-  return internal::ReturnRefAction<R>(x);
-}
-
-// Creates an action that returns the reference to a copy of the
-// argument.  The copy is created when the action is constructed and
-// lives as long as the action.
-template <typename R>
-inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
-  return internal::ReturnRefOfCopyAction<R>(x);
-}
-
-// Modifies the parent action (a Return() action) to perform a move of the
-// argument instead of a copy.
-// Return(ByMove()) actions can only be executed once and will assert this
-// invariant.
-template <typename R>
-internal::ByMoveWrapper<R> ByMove(R x) {
-  return internal::ByMoveWrapper<R>(internal::move(x));
-}
-
-// Creates an action that does the default action for the give mock function.
-inline internal::DoDefaultAction DoDefault() {
-  return internal::DoDefaultAction();
-}
-
-// Creates an action that sets the variable pointed by the N-th
-// (0-based) function argument to 'value'.
-template <size_t N, typename T>
-PolymorphicAction<
-  internal::SetArgumentPointeeAction<
-    N, T, internal::IsAProtocolMessage<T>::value> >
-SetArgPointee(const T& x) {
-  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
-      N, T, internal::IsAProtocolMessage<T>::value>(x));
-}
-
-#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
-// This overload allows SetArgPointee() to accept a string literal.
-// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
-// this overload from the templated version and emit a compile error.
-template <size_t N>
-PolymorphicAction<
-  internal::SetArgumentPointeeAction<N, const char*, false> >
-SetArgPointee(const char* p) {
-  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
-      N, const char*, false>(p));
-}
-
-template <size_t N>
-PolymorphicAction<
-  internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
-SetArgPointee(const wchar_t* p) {
-  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
-      N, const wchar_t*, false>(p));
-}
-#endif
-
-// The following version is DEPRECATED.
-template <size_t N, typename T>
-PolymorphicAction<
-  internal::SetArgumentPointeeAction<
-    N, T, internal::IsAProtocolMessage<T>::value> >
-SetArgumentPointee(const T& x) {
-  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
-      N, T, internal::IsAProtocolMessage<T>::value>(x));
-}
-
-// Creates an action that sets a pointer referent to a given value.
-template <typename T1, typename T2>
-PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
-  return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
-}
-
-#if !GTEST_OS_WINDOWS_MOBILE
-
-// Creates an action that sets errno and returns the appropriate error.
-template <typename T>
-PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
-SetErrnoAndReturn(int errval, T result) {
-  return MakePolymorphicAction(
-      internal::SetErrnoAndReturnAction<T>(errval, result));
-}
-
-#endif  // !GTEST_OS_WINDOWS_MOBILE
-
-// Various overloads for InvokeWithoutArgs().
-
-// Creates an action that invokes 'function_impl' with no argument.
-template <typename FunctionImpl>
-PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
-InvokeWithoutArgs(FunctionImpl function_impl) {
-  return MakePolymorphicAction(
-      internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
-}
-
-// Creates an action that invokes the given method on the given object
-// with no argument.
-template <class Class, typename MethodPtr>
-PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
-InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
-  return MakePolymorphicAction(
-      internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
-          obj_ptr, method_ptr));
-}
-
-// Creates an action that performs an_action and throws away its
-// result.  In other words, it changes the return type of an_action to
-// void.  an_action MUST NOT return void, or the code won't compile.
-template <typename A>
-inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
-  return internal::IgnoreResultAction<A>(an_action);
-}
-
-// Creates a reference wrapper for the given L-value.  If necessary,
-// you can explicitly specify the type of the reference.  For example,
-// suppose 'derived' is an object of type Derived, ByRef(derived)
-// would wrap a Derived&.  If you want to wrap a const Base& instead,
-// where Base is a base class of Derived, just write:
-//
-//   ByRef<const Base>(derived)
-template <typename T>
-inline internal::ReferenceWrapper<T> ByRef(T& l_value) {  // NOLINT
-  return internal::ReferenceWrapper<T>(l_value);
-}
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#endif  // TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
\ No newline at end of file
diff --git a/testing/gmock/include/gmock/gmock-cardinalities.h b/testing/gmock/include/gmock/gmock-cardinalities.h
deleted file mode 100644
index 943ef30..0000000
--- a/testing/gmock/include/gmock/gmock-cardinalities.h
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used cardinalities.  More
-// cardinalities can be defined by the user implementing the
-// CardinalityInterface interface if necessary.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
-
-#if defined(STARBOARD)
-#include "starboard/types.h"
-#else
-#include <limits.h>
-#endif
-
-#include <ostream>  // NOLINT
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-
-// To implement a cardinality Foo, define:
-//   1. a class FooCardinality that implements the
-//      CardinalityInterface interface, and
-//   2. a factory function that creates a Cardinality object from a
-//      const FooCardinality*.
-//
-// The two-level delegation design follows that of Matcher, providing
-// consistency for extension developers.  It also eases ownership
-// management as Cardinality objects can now be copied like plain values.
-
-// The implementation of a cardinality.
-class CardinalityInterface {
- public:
-  virtual ~CardinalityInterface() {}
-
-  // Conservative estimate on the lower/upper bound of the number of
-  // calls allowed.
-  virtual int ConservativeLowerBound() const { return 0; }
-  virtual int ConservativeUpperBound() const { return INT_MAX; }
-
-  // Returns true iff call_count calls will satisfy this cardinality.
-  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
-
-  // Returns true iff call_count calls will saturate this cardinality.
-  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
-
-  // Describes self to an ostream.
-  virtual void DescribeTo(::std::ostream* os) const = 0;
-};
-
-// A Cardinality is a copyable and IMMUTABLE (except by assignment)
-// object that specifies how many times a mock function is expected to
-// be called.  The implementation of Cardinality is just a linked_ptr
-// to const CardinalityInterface, so copying is fairly cheap.
-// Don't inherit from Cardinality!
-class GTEST_API_ Cardinality {
- public:
-  // Constructs a null cardinality.  Needed for storing Cardinality
-  // objects in STL containers.
-  Cardinality() {}
-
-  // Constructs a Cardinality from its implementation.
-  explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
-
-  // Conservative estimate on the lower/upper bound of the number of
-  // calls allowed.
-  int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
-  int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
-
-  // Returns true iff call_count calls will satisfy this cardinality.
-  bool IsSatisfiedByCallCount(int call_count) const {
-    return impl_->IsSatisfiedByCallCount(call_count);
-  }
-
-  // Returns true iff call_count calls will saturate this cardinality.
-  bool IsSaturatedByCallCount(int call_count) const {
-    return impl_->IsSaturatedByCallCount(call_count);
-  }
-
-  // Returns true iff call_count calls will over-saturate this
-  // cardinality, i.e. exceed the maximum number of allowed calls.
-  bool IsOverSaturatedByCallCount(int call_count) const {
-    return impl_->IsSaturatedByCallCount(call_count) &&
-        !impl_->IsSatisfiedByCallCount(call_count);
-  }
-
-  // Describes self to an ostream
-  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
-
-  // Describes the given actual call count to an ostream.
-  static void DescribeActualCallCountTo(int actual_call_count,
-                                        ::std::ostream* os);
-
- private:
-  internal::linked_ptr<const CardinalityInterface> impl_;
-};
-
-// Creates a cardinality that allows at least n calls.
-GTEST_API_ Cardinality AtLeast(int n);
-
-// Creates a cardinality that allows at most n calls.
-GTEST_API_ Cardinality AtMost(int n);
-
-// Creates a cardinality that allows any number of calls.
-GTEST_API_ Cardinality AnyNumber();
-
-// Creates a cardinality that allows between min and max calls.
-GTEST_API_ Cardinality Between(int min, int max);
-
-// Creates a cardinality that allows exactly n calls.
-GTEST_API_ Cardinality Exactly(int n);
-
-// Creates a cardinality from its implementation.
-inline Cardinality MakeCardinality(const CardinalityInterface* c) {
-  return Cardinality(c);
-}
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-actions.h b/testing/gmock/include/gmock/gmock-generated-actions.h
deleted file mode 100644
index b5a889c..0000000
--- a/testing/gmock/include/gmock/gmock-generated-actions.h
+++ /dev/null
@@ -1,2377 +0,0 @@
-// This file was GENERATED by a script.  DO NOT EDIT BY HAND!!!
-
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used variadic actions.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-
-#include "gmock/gmock-actions.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-namespace internal {
-
-// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
-// function or method with the unpacked values, where F is a function
-// type that takes N arguments.
-template <typename Result, typename ArgumentTuple>
-class InvokeHelper;
-
-template <typename R>
-class InvokeHelper<R, ::testing::tuple<> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<>&) {
-           return function();
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<>&) {
-           return (obj_ptr->*method_ptr)();
-  }
-};
-
-template <typename R, typename A1>
-class InvokeHelper<R, ::testing::tuple<A1> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1>& args) {
-           return function(get<0>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2>
-class InvokeHelper<R, ::testing::tuple<A1, A2> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2>& args) {
-           return function(get<0>(args), get<1>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3,
-      A4>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4,
-      A5>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args), get<4>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4, A5>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args), get<4>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
-      A6>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args), get<4>(args), get<5>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4, A5, A6>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args), get<4>(args), get<5>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
-      A6, A7>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args), get<4>(args), get<5>(args), get<6>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4, A5, A6,
-                            A7>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
-               get<6>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
-      A6, A7, A8>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args), get<4>(args), get<5>(args), get<6>(args),
-               get<7>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7,
-                            A8>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
-               get<6>(args), get<7>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8, typename A9>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
-      A6, A7, A8, A9>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args), get<4>(args), get<5>(args), get<6>(args),
-               get<7>(args), get<8>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8,
-                            A9>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
-               get<6>(args), get<7>(args), get<8>(args));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8, typename A9,
-    typename A10>
-class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
-    A10> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5,
-      A6, A7, A8, A9, A10>& args) {
-           return function(get<0>(args), get<1>(args), get<2>(args),
-               get<3>(args), get<4>(args), get<5>(args), get<6>(args),
-               get<7>(args), get<8>(args), get<9>(args));
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8,
-                            A9, A10>& args) {
-           return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args),
-               get<2>(args), get<3>(args), get<4>(args), get<5>(args),
-               get<6>(args), get<7>(args), get<8>(args), get<9>(args));
-  }
-};
-
-// An INTERNAL macro for extracting the type of a tuple field.  It's
-// subject to change without notice - DO NOT USE IN USER CODE!
-#define GMOCK_FIELD_(Tuple, N) \
-    typename ::testing::tuple_element<N, Tuple>::type
-
-// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the
-// type of an n-ary function whose i-th (1-based) argument type is the
-// k{i}-th (0-based) field of ArgumentTuple, which must be a tuple
-// type, and whose return type is Result.  For example,
-//   SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type
-// is int(bool, long).
-//
-// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args)
-// returns the selected fields (k1, k2, ..., k_n) of args as a tuple.
-// For example,
-//   SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select(
-//       ::testing::make_tuple(true, 'a', 2.5))
-// returns tuple (2.5, true).
-//
-// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be
-// in the range [0, 10].  Duplicates are allowed and they don't have
-// to be in an ascending or descending order.
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4, int k5, int k6, int k7, int k8, int k9, int k10>
-class SelectArgs {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
-      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7),
-      GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9),
-      GMOCK_FIELD_(ArgumentTuple, k10));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args),
-        get<k8>(args), get<k9>(args), get<k10>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple>
-class SelectArgs<Result, ArgumentTuple,
-                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef Result type();
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& /* args */) {
-    return SelectedArgs();
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, -1, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, k4, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4, int k5>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, k4, k5, -1, -1, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args), get<k5>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4, int k5, int k6>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, k4, k5, k6, -1, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
-      GMOCK_FIELD_(ArgumentTuple, k6));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args), get<k5>(args), get<k6>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4, int k5, int k6, int k7>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, k4, k5, k6, k7, -1, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
-      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4, int k5, int k6, int k7, int k8>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, k4, k5, k6, k7, k8, -1, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
-      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7),
-      GMOCK_FIELD_(ArgumentTuple, k8));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args),
-        get<k8>(args));
-  }
-};
-
-template <typename Result, typename ArgumentTuple, int k1, int k2, int k3,
-    int k4, int k5, int k6, int k7, int k8, int k9>
-class SelectArgs<Result, ArgumentTuple,
-                 k1, k2, k3, k4, k5, k6, k7, k8, k9, -1> {
- public:
-  typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1),
-      GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3),
-      GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5),
-      GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7),
-      GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9));
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args),
-        get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args),
-        get<k8>(args), get<k9>(args));
-  }
-};
-
-#undef GMOCK_FIELD_
-
-// Implements the WithArgs action.
-template <typename InnerAction, int k1 = -1, int k2 = -1, int k3 = -1,
-    int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1,
-    int k9 = -1, int k10 = -1>
-class WithArgsAction {
- public:
-  explicit WithArgsAction(const InnerAction& action) : action_(action) {}
-
-  template <typename F>
-  operator Action<F>() const { return MakeAction(new Impl<F>(action_)); }
-
- private:
-  template <typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit Impl(const InnerAction& action) : action_(action) {}
-
-    virtual Result Perform(const ArgumentTuple& args) {
-      return action_.Perform(SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4,
-          k5, k6, k7, k8, k9, k10>::Select(args));
-    }
-
-   private:
-    typedef typename SelectArgs<Result, ArgumentTuple,
-        k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>::type InnerFunctionType;
-
-    Action<InnerFunctionType> action_;
-  };
-
-  const InnerAction action_;
-
-  GTEST_DISALLOW_ASSIGN_(WithArgsAction);
-};
-
-// A macro from the ACTION* family (defined later in this file)
-// defines an action that can be used in a mock function.  Typically,
-// these actions only care about a subset of the arguments of the mock
-// function.  For example, if such an action only uses the second
-// argument, it can be used in any mock function that takes >= 2
-// arguments where the type of the second argument is compatible.
-//
-// Therefore, the action implementation must be prepared to take more
-// arguments than it needs.  The ExcessiveArg type is used to
-// represent those excessive arguments.  In order to keep the compiler
-// error messages tractable, we define it in the testing namespace
-// instead of testing::internal.  However, this is an INTERNAL TYPE
-// and subject to change without notice, so a user MUST NOT USE THIS
-// TYPE DIRECTLY.
-struct ExcessiveArg {};
-
-// A helper class needed for implementing the ACTION* macros.
-template <typename Result, class Impl>
-class ActionHelper {
- public:
-  static Result Perform(Impl* impl, const ::testing::tuple<>& args) {
-    return impl->template gmock_PerformImpl<>(args, ExcessiveArg(),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0>& args) {
-    return impl->template gmock_PerformImpl<A0>(args, get<0>(args),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1>& args) {
-    return impl->template gmock_PerformImpl<A0, A1>(args, get<0>(args),
-        get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2>(args, get<0>(args),
-        get<1>(args), get<2>(args), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2,
-      A3>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args, get<0>(args),
-        get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3, typename A4>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3,
-      A4>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4>(args,
-        get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args),
-        ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3, typename A4,
-      typename A5>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
-      A5>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5>(args,
-        get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args),
-        get<5>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3, typename A4,
-      typename A5, typename A6>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
-      A5, A6>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6>(args,
-        get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args),
-        get<5>(args), get<6>(args), ExcessiveArg(), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3, typename A4,
-      typename A5, typename A6, typename A7>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
-      A5, A6, A7>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6,
-        A7>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args),
-        get<4>(args), get<5>(args), get<6>(args), get<7>(args), ExcessiveArg(),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3, typename A4,
-      typename A5, typename A6, typename A7, typename A8>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
-      A5, A6, A7, A8>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7,
-        A8>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args),
-        get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args),
-        ExcessiveArg());
-  }
-
-  template <typename A0, typename A1, typename A2, typename A3, typename A4,
-      typename A5, typename A6, typename A7, typename A8, typename A9>
-  static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4,
-      A5, A6, A7, A8, A9>& args) {
-    return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8,
-        A9>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args),
-        get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args),
-        get<9>(args));
-  }
-};
-
-}  // namespace internal
-
-// Various overloads for Invoke().
-
-// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
-// the selected arguments of the mock function to an_action and
-// performs it.  It serves as an adaptor between actions with
-// different argument lists.  C++ doesn't support default arguments for
-// function templates, so we have to overload it.
-template <int k1, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1>(action);
-}
-
-template <int k1, int k2, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2>(action);
-}
-
-template <int k1, int k2, int k3, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3>(action);
-}
-
-template <int k1, int k2, int k3, int k4, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4>(action);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5>(action);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6>(action);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7,
-    typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6,
-      k7>(action);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
-    typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7,
-      k8>(action);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
-    int k9, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8,
-      k9>(action);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
-    int k9, int k10, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8,
-    k9, k10>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8,
-      k9, k10>(action);
-}
-
-// Creates an action that does actions a1, a2, ..., sequentially in
-// each invocation.
-template <typename Action1, typename Action2>
-inline internal::DoBothAction<Action1, Action2>
-DoAll(Action1 a1, Action2 a2) {
-  return internal::DoBothAction<Action1, Action2>(a1, a2);
-}
-
-template <typename Action1, typename Action2, typename Action3>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    Action3> >
-DoAll(Action1 a1, Action2 a2, Action3 a3) {
-  return DoAll(a1, DoAll(a2, a3));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, Action4> > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4) {
-  return DoAll(a1, DoAll(a2, a3, a4));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4, typename Action5>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
-    Action5> > > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5) {
-  return DoAll(a1, DoAll(a2, a3, a4, a5));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4, typename Action5, typename Action6>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
-    internal::DoBothAction<Action5, Action6> > > > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6) {
-  return DoAll(a1, DoAll(a2, a3, a4, a5, a6));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4, typename Action5, typename Action6, typename Action7>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
-    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
-    Action7> > > > > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
-    Action7 a7) {
-  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4, typename Action5, typename Action6, typename Action7,
-    typename Action8>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
-    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
-    internal::DoBothAction<Action7, Action8> > > > > > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
-    Action7 a7, Action8 a8) {
-  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4, typename Action5, typename Action6, typename Action7,
-    typename Action8, typename Action9>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
-    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
-    internal::DoBothAction<Action7, internal::DoBothAction<Action8,
-    Action9> > > > > > > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
-    Action7 a7, Action8 a8, Action9 a9) {
-  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9));
-}
-
-template <typename Action1, typename Action2, typename Action3,
-    typename Action4, typename Action5, typename Action6, typename Action7,
-    typename Action8, typename Action9, typename Action10>
-inline internal::DoBothAction<Action1, internal::DoBothAction<Action2,
-    internal::DoBothAction<Action3, internal::DoBothAction<Action4,
-    internal::DoBothAction<Action5, internal::DoBothAction<Action6,
-    internal::DoBothAction<Action7, internal::DoBothAction<Action8,
-    internal::DoBothAction<Action9, Action10> > > > > > > > >
-DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6,
-    Action7 a7, Action8 a8, Action9 a9, Action10 a10) {
-  return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9, a10));
-}
-
-}  // namespace testing
-
-// The ACTION* family of macros can be used in a namespace scope to
-// define custom actions easily.  The syntax:
-//
-//   ACTION(name) { statements; }
-//
-// will define an action with the given name that executes the
-// statements.  The value returned by the statements will be used as
-// the return value of the action.  Inside the statements, you can
-// refer to the K-th (0-based) argument of the mock function by
-// 'argK', and refer to its type by 'argK_type'.  For example:
-//
-//   ACTION(IncrementArg1) {
-//     arg1_type temp = arg1;
-//     return ++(*temp);
-//   }
-//
-// allows you to write
-//
-//   ...WillOnce(IncrementArg1());
-//
-// You can also refer to the entire argument tuple and its type by
-// 'args' and 'args_type', and refer to the mock function type and its
-// return type by 'function_type' and 'return_type'.
-//
-// Note that you don't need to specify the types of the mock function
-// arguments.  However rest assured that your code is still type-safe:
-// you'll get a compiler error if *arg1 doesn't support the ++
-// operator, or if the type of ++(*arg1) isn't compatible with the
-// mock function's return type, for example.
-//
-// Sometimes you'll want to parameterize the action.   For that you can use
-// another macro:
-//
-//   ACTION_P(name, param_name) { statements; }
-//
-// For example:
-//
-//   ACTION_P(Add, n) { return arg0 + n; }
-//
-// will allow you to write:
-//
-//   ...WillOnce(Add(5));
-//
-// Note that you don't need to provide the type of the parameter
-// either.  If you need to reference the type of a parameter named
-// 'foo', you can write 'foo_type'.  For example, in the body of
-// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
-// of 'n'.
-//
-// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
-// multi-parameter actions.
-//
-// For the purpose of typing, you can view
-//
-//   ACTION_Pk(Foo, p1, ..., pk) { ... }
-//
-// as shorthand for
-//
-//   template <typename p1_type, ..., typename pk_type>
-//   FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// In particular, you can provide the template type arguments
-// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
-// although usually you can rely on the compiler to infer the types
-// for you automatically.  You can assign the result of expression
-// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
-// pk_type>.  This can be useful when composing actions.
-//
-// You can also overload actions with different numbers of parameters:
-//
-//   ACTION_P(Plus, a) { ... }
-//   ACTION_P2(Plus, a, b) { ... }
-//
-// While it's tempting to always use the ACTION* macros when defining
-// a new action, you should also consider implementing ActionInterface
-// or using MakePolymorphicAction() instead, especially if you need to
-// use the action a lot.  While these approaches require more work,
-// they give you more control on the types of the mock function
-// arguments and the action parameters, which in general leads to
-// better compiler error messages that pay off in the long run.  They
-// also allow overloading actions based on parameter types (as opposed
-// to just based on the number of parameters).
-//
-// CAVEAT:
-//
-// ACTION*() can only be used in a namespace scope.  The reason is
-// that C++ doesn't yet allow function-local types to be used to
-// instantiate templates.  The up-coming C++0x standard will fix this.
-// Once that's done, we'll consider supporting using ACTION*() inside
-// a function.
-//
-// MORE INFORMATION:
-//
-// To learn more about using these macros, please search for 'ACTION'
-// on http://code.google.com/p/googlemock/wiki/CookBook.
-
-// An internal macro needed for implementing ACTION*().
-#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
-    const args_type& args GTEST_ATTRIBUTE_UNUSED_, \
-    arg0_type arg0 GTEST_ATTRIBUTE_UNUSED_, \
-    arg1_type arg1 GTEST_ATTRIBUTE_UNUSED_, \
-    arg2_type arg2 GTEST_ATTRIBUTE_UNUSED_, \
-    arg3_type arg3 GTEST_ATTRIBUTE_UNUSED_, \
-    arg4_type arg4 GTEST_ATTRIBUTE_UNUSED_, \
-    arg5_type arg5 GTEST_ATTRIBUTE_UNUSED_, \
-    arg6_type arg6 GTEST_ATTRIBUTE_UNUSED_, \
-    arg7_type arg7 GTEST_ATTRIBUTE_UNUSED_, \
-    arg8_type arg8 GTEST_ATTRIBUTE_UNUSED_, \
-    arg9_type arg9 GTEST_ATTRIBUTE_UNUSED_
-
-// Sometimes you want to give an action explicit template parameters
-// that cannot be inferred from its value parameters.  ACTION() and
-// ACTION_P*() don't support that.  ACTION_TEMPLATE() remedies that
-// and can be viewed as an extension to ACTION() and ACTION_P*().
-//
-// The syntax:
-//
-//   ACTION_TEMPLATE(ActionName,
-//                   HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
-//                   AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
-//
-// defines an action template that takes m explicit template
-// parameters and n value parameters.  name_i is the name of the i-th
-// template parameter, and kind_i specifies whether it's a typename,
-// an integral constant, or a template.  p_i is the name of the i-th
-// value parameter.
-//
-// Example:
-//
-//   // DuplicateArg<k, T>(output) converts the k-th argument of the mock
-//   // function to type T and copies it to *output.
-//   ACTION_TEMPLATE(DuplicateArg,
-//                   HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
-//                   AND_1_VALUE_PARAMS(output)) {
-//     *output = T(::testing::get<k>(args));
-//   }
-//   ...
-//     int n;
-//     EXPECT_CALL(mock, Foo(_, _))
-//         .WillOnce(DuplicateArg<1, unsigned char>(&n));
-//
-// To create an instance of an action template, write:
-//
-//   ActionName<t1, ..., t_m>(v1, ..., v_n)
-//
-// where the ts are the template arguments and the vs are the value
-// arguments.  The value argument types are inferred by the compiler.
-// If you want to explicitly specify the value argument types, you can
-// provide additional template arguments:
-//
-//   ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
-//
-// where u_i is the desired type of v_i.
-//
-// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
-// number of value parameters, but not on the number of template
-// parameters.  Without the restriction, the meaning of the following
-// is unclear:
-//
-//   OverloadedAction<int, bool>(x);
-//
-// Are we using a single-template-parameter action where 'bool' refers
-// to the type of x, or are we using a two-template-parameter action
-// where the compiler is asked to infer the type of x?
-//
-// Implementation notes:
-//
-// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
-// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
-// implementing ACTION_TEMPLATE.  The main trick we use is to create
-// new macro invocations when expanding a macro.  For example, we have
-//
-//   #define ACTION_TEMPLATE(name, template_params, value_params)
-//       ... GMOCK_INTERNAL_DECL_##template_params ...
-//
-// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
-// to expand to
-//
-//       ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
-//
-// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
-// preprocessor will continue to expand it to
-//
-//       ... typename T ...
-//
-// This technique conforms to the C++ standard and is portable.  It
-// allows us to implement action templates using O(N) code, where N is
-// the maximum number of template/value parameters supported.  Without
-// using it, we'd have to devote O(N^2) amount of code to implement all
-// combinations of m and n.
-
-// Declares the template parameters.
-#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
-#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1) kind0 name0, kind1 name1
-#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2) kind0 name0, kind1 name1, kind2 name2
-#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
-    kind3 name3
-#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
-    kind2 name2, kind3 name3, kind4 name4
-#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
-    kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
-#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
-    kind5 name5, kind6 name6
-#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
-    kind4 name4, kind5 name5, kind6 name6, kind7 name7
-#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
-    kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
-    kind8 name8
-#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
-    kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
-    kind6 name6, kind7 name7, kind8 name8, kind9 name9
-
-// Lists the template parameters.
-#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
-#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1) name0, name1
-#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2) name0, name1, name2
-#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3) name0, name1, name2, name3
-#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
-    name4
-#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
-    name2, name3, name4, name5
-#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6) name0, name1, name2, name3, name4, name5, name6
-#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
-#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
-    name6, name7, name8
-#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
-    name3, name4, name5, name6, name7, name8, name9
-
-// Declares the types of value parameters.
-#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
-    typename p0##_type, typename p1##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
-    typename p0##_type, typename p1##_type, typename p2##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
-    typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
-    typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
-    typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type, \
-    typename p6##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type, \
-    typename p6##_type, typename p7##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type, \
-    typename p6##_type, typename p7##_type, typename p8##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
-    typename p2##_type, typename p3##_type, typename p4##_type, \
-    typename p5##_type, typename p6##_type, typename p7##_type, \
-    typename p8##_type, typename p9##_type
-
-// Initializes the value parameters.
-#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
-    ()
-#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
-    (p0##_type gmock_p0) : p0(gmock_p0)
-#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
-    (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1)
-#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2)
-#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3)
-#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4)
-#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5)
-#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6)
-#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-        p7(gmock_p7)
-#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6, p7##_type gmock_p7, \
-        p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
-        p8(gmock_p8)
-#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
-        p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
-        p8(gmock_p8), p9(gmock_p9)
-
-// Declares the fields for storing the value parameters.
-#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
-#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
-    p1##_type p1;
-#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
-    p1##_type p1; p2##_type p2;
-#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
-    p1##_type p1; p2##_type p2; p3##_type p3;
-#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
-    p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
-#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
-    p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
-    p5##_type p5;
-#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
-    p5##_type p5; p6##_type p6;
-#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
-    p5##_type p5; p6##_type p6; p7##_type p7;
-#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
-    p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
-#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
-    p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
-    p9##_type p9;
-
-// Lists the value parameters.
-#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
-#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
-#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
-#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
-#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
-    p2, p3, p4
-#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
-    p1, p2, p3, p4, p5
-#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) p0, p1, p2, p3, p4, p5, p6
-#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) p0, p1, p2, p3, p4, p5, p6, p7
-#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
-#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
-
-// Lists the value parameter types.
-#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
-    p1##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
-    p1##_type, p2##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
-    p0##_type, p1##_type, p2##_type, p3##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
-    p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
-    p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
-    p6##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-    p5##_type, p6##_type, p7##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-    p5##_type, p6##_type, p7##_type, p8##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-    p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
-
-// Declares the value parameters.
-#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
-#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
-    p1##_type p1
-#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
-    p1##_type p1, p2##_type p2
-#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
-    p1##_type p1, p2##_type p2, p3##_type p3
-#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
-    p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
-#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
-    p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
-    p5##_type p5
-#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
-    p5##_type p5, p6##_type p6
-#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
-    p5##_type p5, p6##_type p6, p7##_type p7
-#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-    p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
-#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-    p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
-    p9##_type p9
-
-// The suffix of the class template implementing the action template.
-#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
-#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
-#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
-#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
-#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
-#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
-#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
-#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) P8
-#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) P9
-#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) P10
-
-// The name of the class template implementing the action template.
-#define GMOCK_ACTION_CLASS_(name, value_params)\
-    GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
-
-#define ACTION_TEMPLATE(name, template_params, value_params)\
-  template <GMOCK_INTERNAL_DECL_##template_params\
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
-  class GMOCK_ACTION_CLASS_(name, value_params) {\
-   public:\
-    explicit GMOCK_ACTION_CLASS_(name, value_params)\
-        GMOCK_INTERNAL_INIT_##value_params {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      GMOCK_INTERNAL_DEFN_##value_params\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(\
-          new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
-    }\
-    GMOCK_INTERNAL_DEFN_##value_params\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
-  };\
-  template <GMOCK_INTERNAL_DECL_##template_params\
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
-  inline GMOCK_ACTION_CLASS_(name, value_params)<\
-      GMOCK_INTERNAL_LIST_##template_params\
-      GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\
-          GMOCK_INTERNAL_DECL_##value_params) {\
-    return GMOCK_ACTION_CLASS_(name, value_params)<\
-        GMOCK_INTERNAL_LIST_##template_params\
-        GMOCK_INTERNAL_LIST_TYPE_##value_params>(\
-            GMOCK_INTERNAL_LIST_##value_params);\
-  }\
-  template <GMOCK_INTERNAL_DECL_##template_params\
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      GMOCK_ACTION_CLASS_(name, value_params)<\
-          GMOCK_INTERNAL_LIST_##template_params\
-          GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
-              gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION(name)\
-  class name##Action {\
-   public:\
-    name##Action() {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl() {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>());\
-    }\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##Action);\
-  };\
-  inline name##Action name() {\
-    return name##Action();\
-  }\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##Action::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P(name, p0)\
-  template <typename p0##_type>\
-  class name##ActionP {\
-   public:\
-    explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0));\
-    }\
-    p0##_type p0;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP);\
-  };\
-  template <typename p0##_type>\
-  inline name##ActionP<p0##_type> name(p0##_type p0) {\
-    return name##ActionP<p0##_type>(p0);\
-  }\
-  template <typename p0##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP<p0##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P2(name, p0, p1)\
-  template <typename p0##_type, typename p1##_type>\
-  class name##ActionP2 {\
-   public:\
-    name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
-        p1(gmock_p1) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
-          p1(gmock_p1) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP2);\
-  };\
-  template <typename p0##_type, typename p1##_type>\
-  inline name##ActionP2<p0##_type, p1##_type> name(p0##_type p0, \
-      p1##_type p1) {\
-    return name##ActionP2<p0##_type, p1##_type>(p0, p1);\
-  }\
-  template <typename p0##_type, typename p1##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP2<p0##_type, p1##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P3(name, p0, p1, p2)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type>\
-  class name##ActionP3 {\
-   public:\
-    name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \
-          p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP3);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type>\
-  inline name##ActionP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
-      p1##_type p1, p2##_type p2) {\
-    return name##ActionP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP3<p0##_type, p1##_type, \
-          p2##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P4(name, p0, p1, p2, p3)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type>\
-  class name##ActionP4 {\
-   public:\
-    name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-          p3(gmock_p3) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP4);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type>\
-  inline name##ActionP4<p0##_type, p1##_type, p2##_type, \
-      p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
-      p3##_type p3) {\
-    return name##ActionP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, p1, \
-        p2, p3);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP4<p0##_type, p1##_type, p2##_type, \
-          p3##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P5(name, p0, p1, p2, p3, p4)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type>\
-  class name##ActionP5 {\
-   public:\
-    name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, \
-        p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \
-          p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP5);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type>\
-  inline name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-      p4##_type p4) {\
-    return name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type>(p0, p1, p2, p3, p4);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
-          p4##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type>\
-  class name##ActionP6 {\
-   public:\
-    name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, \
-          p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP6);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type>\
-  inline name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
-      p3##_type p3, p4##_type p4, p5##_type p5) {\
-    return name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-          p5##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type>\
-  class name##ActionP7 {\
-   public:\
-    name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \
-        p6(gmock_p6) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
-          p6));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP7);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type>\
-  inline name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
-      p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
-      p6##_type p6) {\
-    return name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-          p5##_type, p6##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type>\
-  class name##ActionP8 {\
-   public:\
-    name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6, \
-        p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-        p7(gmock_p7) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \
-          p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \
-          p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-      p7##_type p7;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
-          p6, p7));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-    p7##_type p7;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP8);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type>\
-  inline name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
-      p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
-      p6##_type p6, p7##_type p7) {\
-    return name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
-        p6, p7);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-          p5##_type, p6##_type, \
-          p7##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type>\
-  class name##ActionP9 {\
-   public:\
-    name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
-        p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
-        p8(gmock_p8) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6, p7##_type gmock_p7, \
-          p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-          p7(gmock_p7), p8(gmock_p8) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-      p7##_type p7;\
-      p8##_type p8;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
-          p6, p7, p8));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-    p7##_type p7;\
-    p8##_type p8;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP9);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type>\
-  inline name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type, \
-      p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \
-      p8##_type p8) {\
-    return name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
-        p3, p4, p5, p6, p7, p8);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-          p5##_type, p6##_type, p7##_type, \
-          p8##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type, \
-      typename p9##_type>\
-  class name##ActionP10 {\
-   public:\
-    name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
-        p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-        p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
-          p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-          p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-          p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <typename arg0_type, typename arg1_type, typename arg2_type, \
-          typename arg3_type, typename arg4_type, typename arg5_type, \
-          typename arg6_type, typename arg7_type, typename arg8_type, \
-          typename arg9_type>\
-      return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \
-          arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \
-          arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \
-          arg9_type arg9) const;\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-      p7##_type p7;\
-      p8##_type p8;\
-      p9##_type p9;\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
-          p6, p7, p8, p9));\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-    p7##_type p7;\
-    p8##_type p8;\
-    p9##_type p9;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##ActionP10);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type, \
-      typename p9##_type>\
-  inline name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
-      p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
-      p9##_type p9) {\
-    return name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
-        p1, p2, p3, p4, p5, p6, p7, p8, p9);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type, \
-      typename p9##_type>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-          p5##_type, p6##_type, p7##_type, p8##_type, \
-          p9##_type>::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-namespace testing {
-
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma.  Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Various overloads for InvokeArgument<N>().
-//
-// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
-// (0-based) argument, which must be a k-ary callable, of the mock
-// function, with arguments a1, a2, ..., a_k.
-//
-// Notes:
-//
-//   1. The arguments are passed by value by default.  If you need to
-//   pass an argument by reference, wrap it inside ByRef().  For
-//   example,
-//
-//     InvokeArgument<1>(5, string("Hello"), ByRef(foo))
-//
-//   passes 5 and string("Hello") by value, and passes foo by
-//   reference.
-//
-//   2. If the callable takes an argument by reference but ByRef() is
-//   not used, it will receive the reference to a copy of the value,
-//   instead of the original value.  For example, when the 0-th
-//   argument of the mock function takes a const string&, the action
-//
-//     InvokeArgument<0>(string("Hello"))
-//
-//   makes a copy of the temporary string("Hello") object and passes a
-//   reference of the copy, instead of the original temporary object,
-//   to the callable.  This makes it easy for a user to define an
-//   InvokeArgument action from temporary values and have it performed
-//   later.
-
-namespace internal {
-namespace invoke_argument {
-
-// Appears in InvokeArgumentAdl's argument list to help avoid
-// accidental calls to user functions of the same name.
-struct AdlTag {};
-
-// InvokeArgumentAdl - a helper for InvokeArgument.
-// The basic overloads are provided here for generic functors.
-// Overloads for other custom-callables are provided in the
-// internal/custom/callback-actions.h header.
-
-template <typename R, typename F>
-R InvokeArgumentAdl(AdlTag, F f) {
-  return f();
-}
-template <typename R, typename F, typename A1>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1) {
-  return f(a1);
-}
-template <typename R, typename F, typename A1, typename A2>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) {
-  return f(a1, a2);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) {
-  return f(a1, a2, a3);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) {
-  return f(a1, a2, a3, a4);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4, typename A5>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
-  return f(a1, a2, a3, a4, a5);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) {
-  return f(a1, a2, a3, a4, a5, a6);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
-    A7 a7) {
-  return f(a1, a2, a3, a4, a5, a6, a7);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7, typename A8>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
-    A7 a7, A8 a8) {
-  return f(a1, a2, a3, a4, a5, a6, a7, a8);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7, typename A8,
-    typename A9>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
-    A7 a7, A8 a8, A9 a9) {
-  return f(a1, a2, a3, a4, a5, a6, a7, a8, a9);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7, typename A8,
-    typename A9, typename A10>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
-    A7 a7, A8 a8, A9 a9, A10 a10) {
-  return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
-}
-}  // namespace invoke_argument
-}  // namespace internal
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_0_VALUE_PARAMS()) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args));
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_1_VALUE_PARAMS(p0)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_2_VALUE_PARAMS(p0, p1)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_3_VALUE_PARAMS(p0, p1, p2)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
-// Various overloads for ReturnNew<T>().
-//
-// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
-// instance of type T, constructed on the heap with constructor arguments
-// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_0_VALUE_PARAMS()) {
-  return new T();
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_1_VALUE_PARAMS(p0)) {
-  return new T(p0);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_2_VALUE_PARAMS(p0, p1)) {
-  return new T(p0, p1);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_3_VALUE_PARAMS(p0, p1, p2)) {
-  return new T(p0, p1, p2);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
-  return new T(p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
-  return new T(p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
-  return new T(p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
-  return new T(p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
-  return new T(p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
-  return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
-  return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-}  // namespace testing
-
-// Include any custom actions added by the local installation.
-// We must include this header at the end to make sure it can use the
-// declarations from this file.
-#include "gmock/internal/custom/gmock-generated-actions.h"
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-actions.h.pump b/testing/gmock/include/gmock/gmock-generated-actions.h.pump
deleted file mode 100644
index 66d9f9d..0000000
--- a/testing/gmock/include/gmock/gmock-generated-actions.h.pump
+++ /dev/null
@@ -1,794 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file.  Please use Pump to convert it to
-$$ gmock-generated-actions.h.
-$$
-$var n = 10  $$ The maximum arity we support.
-$$}} This meta comment fixes auto-indentation in editors.
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used variadic actions.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
-
-#include "gmock/gmock-actions.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-namespace internal {
-
-// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
-// function or method with the unpacked values, where F is a function
-// type that takes N arguments.
-template <typename Result, typename ArgumentTuple>
-class InvokeHelper;
-
-
-$range i 0..n
-$for i [[
-$range j 1..i
-$var types = [[$for j [[, typename A$j]]]]
-$var as = [[$for j, [[A$j]]]]
-$var args = [[$if i==0 [[]] $else [[ args]]]]
-$var gets = [[$for j, [[get<$(j - 1)>(args)]]]]
-template <typename R$types>
-class InvokeHelper<R, ::testing::tuple<$as> > {
- public:
-  template <typename Function>
-  static R Invoke(Function function, const ::testing::tuple<$as>&$args) {
-           return function($gets);
-  }
-
-  template <class Class, typename MethodPtr>
-  static R InvokeMethod(Class* obj_ptr,
-                        MethodPtr method_ptr,
-                        const ::testing::tuple<$as>&$args) {
-           return (obj_ptr->*method_ptr)($gets);
-  }
-};
-
-
-]]
-// An INTERNAL macro for extracting the type of a tuple field.  It's
-// subject to change without notice - DO NOT USE IN USER CODE!
-#define GMOCK_FIELD_(Tuple, N) \
-    typename ::testing::tuple_element<N, Tuple>::type
-
-$range i 1..n
-
-// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the
-// type of an n-ary function whose i-th (1-based) argument type is the
-// k{i}-th (0-based) field of ArgumentTuple, which must be a tuple
-// type, and whose return type is Result.  For example,
-//   SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type
-// is int(bool, long).
-//
-// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args)
-// returns the selected fields (k1, k2, ..., k_n) of args as a tuple.
-// For example,
-//   SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select(
-//       ::testing::make_tuple(true, 'a', 2.5))
-// returns tuple (2.5, true).
-//
-// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be
-// in the range [0, $n].  Duplicates are allowed and they don't have
-// to be in an ascending or descending order.
-
-template <typename Result, typename ArgumentTuple, $for i, [[int k$i]]>
-class SelectArgs {
- public:
-  typedef Result type($for i, [[GMOCK_FIELD_(ArgumentTuple, k$i)]]);
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& args) {
-    return SelectedArgs($for i, [[get<k$i>(args)]]);
-  }
-};
-
-
-$for i [[
-$range j 1..n
-$range j1 1..i-1
-template <typename Result, typename ArgumentTuple$for j1[[, int k$j1]]>
-class SelectArgs<Result, ArgumentTuple,
-                 $for j, [[$if j <= i-1 [[k$j]] $else [[-1]]]]> {
- public:
-  typedef Result type($for j1, [[GMOCK_FIELD_(ArgumentTuple, k$j1)]]);
-  typedef typename Function<type>::ArgumentTuple SelectedArgs;
-  static SelectedArgs Select(const ArgumentTuple& [[]]
-$if i == 1 [[/* args */]] $else [[args]]) {
-    return SelectedArgs($for j1, [[get<k$j1>(args)]]);
-  }
-};
-
-
-]]
-#undef GMOCK_FIELD_
-
-$var ks = [[$for i, [[k$i]]]]
-
-// Implements the WithArgs action.
-template <typename InnerAction, $for i, [[int k$i = -1]]>
-class WithArgsAction {
- public:
-  explicit WithArgsAction(const InnerAction& action) : action_(action) {}
-
-  template <typename F>
-  operator Action<F>() const { return MakeAction(new Impl<F>(action_)); }
-
- private:
-  template <typename F>
-  class Impl : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-
-    explicit Impl(const InnerAction& action) : action_(action) {}
-
-    virtual Result Perform(const ArgumentTuple& args) {
-      return action_.Perform(SelectArgs<Result, ArgumentTuple, $ks>::Select(args));
-    }
-
-   private:
-    typedef typename SelectArgs<Result, ArgumentTuple,
-        $ks>::type InnerFunctionType;
-
-    Action<InnerFunctionType> action_;
-  };
-
-  const InnerAction action_;
-
-  GTEST_DISALLOW_ASSIGN_(WithArgsAction);
-};
-
-// A macro from the ACTION* family (defined later in this file)
-// defines an action that can be used in a mock function.  Typically,
-// these actions only care about a subset of the arguments of the mock
-// function.  For example, if such an action only uses the second
-// argument, it can be used in any mock function that takes >= 2
-// arguments where the type of the second argument is compatible.
-//
-// Therefore, the action implementation must be prepared to take more
-// arguments than it needs.  The ExcessiveArg type is used to
-// represent those excessive arguments.  In order to keep the compiler
-// error messages tractable, we define it in the testing namespace
-// instead of testing::internal.  However, this is an INTERNAL TYPE
-// and subject to change without notice, so a user MUST NOT USE THIS
-// TYPE DIRECTLY.
-struct ExcessiveArg {};
-
-// A helper class needed for implementing the ACTION* macros.
-template <typename Result, class Impl>
-class ActionHelper {
- public:
-$range i 0..n
-$for i
-
-[[
-$var template = [[$if i==0 [[]] $else [[
-$range j 0..i-1
-  template <$for j, [[typename A$j]]>
-]]]]
-$range j 0..i-1
-$var As = [[$for j, [[A$j]]]]
-$var as = [[$for j, [[get<$j>(args)]]]]
-$range k 1..n-i
-$var eas = [[$for k, [[ExcessiveArg()]]]]
-$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]]
-$template
-  static Result Perform(Impl* impl, const ::testing::tuple<$As>& args) {
-    return impl->template gmock_PerformImpl<$As>(args, $arg_list);
-  }
-
-]]
-};
-
-}  // namespace internal
-
-// Various overloads for Invoke().
-
-// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
-// the selected arguments of the mock function to an_action and
-// performs it.  It serves as an adaptor between actions with
-// different argument lists.  C++ doesn't support default arguments for
-// function templates, so we have to overload it.
-
-$range i 1..n
-$for i [[
-$range j 1..i
-template <$for j [[int k$j, ]]typename InnerAction>
-inline internal::WithArgsAction<InnerAction$for j [[, k$j]]>
-WithArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction$for j [[, k$j]]>(action);
-}
-
-
-]]
-// Creates an action that does actions a1, a2, ..., sequentially in
-// each invocation.
-$range i 2..n
-$for i [[
-$range j 2..i
-$var types = [[$for j, [[typename Action$j]]]]
-$var Aas = [[$for j [[, Action$j a$j]]]]
-
-template <typename Action1, $types>
-$range k 1..i-1
-
-inline $for k [[internal::DoBothAction<Action$k, ]]Action$i$for k  [[>]]
-
-DoAll(Action1 a1$Aas) {
-$if i==2 [[
-
-  return internal::DoBothAction<Action1, Action2>(a1, a2);
-]] $else [[
-$range j2 2..i
-
-  return DoAll(a1, DoAll($for j2, [[a$j2]]));
-]]
-
-}
-
-]]
-
-}  // namespace testing
-
-// The ACTION* family of macros can be used in a namespace scope to
-// define custom actions easily.  The syntax:
-//
-//   ACTION(name) { statements; }
-//
-// will define an action with the given name that executes the
-// statements.  The value returned by the statements will be used as
-// the return value of the action.  Inside the statements, you can
-// refer to the K-th (0-based) argument of the mock function by
-// 'argK', and refer to its type by 'argK_type'.  For example:
-//
-//   ACTION(IncrementArg1) {
-//     arg1_type temp = arg1;
-//     return ++(*temp);
-//   }
-//
-// allows you to write
-//
-//   ...WillOnce(IncrementArg1());
-//
-// You can also refer to the entire argument tuple and its type by
-// 'args' and 'args_type', and refer to the mock function type and its
-// return type by 'function_type' and 'return_type'.
-//
-// Note that you don't need to specify the types of the mock function
-// arguments.  However rest assured that your code is still type-safe:
-// you'll get a compiler error if *arg1 doesn't support the ++
-// operator, or if the type of ++(*arg1) isn't compatible with the
-// mock function's return type, for example.
-//
-// Sometimes you'll want to parameterize the action.   For that you can use
-// another macro:
-//
-//   ACTION_P(name, param_name) { statements; }
-//
-// For example:
-//
-//   ACTION_P(Add, n) { return arg0 + n; }
-//
-// will allow you to write:
-//
-//   ...WillOnce(Add(5));
-//
-// Note that you don't need to provide the type of the parameter
-// either.  If you need to reference the type of a parameter named
-// 'foo', you can write 'foo_type'.  For example, in the body of
-// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
-// of 'n'.
-//
-// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support
-// multi-parameter actions.
-//
-// For the purpose of typing, you can view
-//
-//   ACTION_Pk(Foo, p1, ..., pk) { ... }
-//
-// as shorthand for
-//
-//   template <typename p1_type, ..., typename pk_type>
-//   FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// In particular, you can provide the template type arguments
-// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
-// although usually you can rely on the compiler to infer the types
-// for you automatically.  You can assign the result of expression
-// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
-// pk_type>.  This can be useful when composing actions.
-//
-// You can also overload actions with different numbers of parameters:
-//
-//   ACTION_P(Plus, a) { ... }
-//   ACTION_P2(Plus, a, b) { ... }
-//
-// While it's tempting to always use the ACTION* macros when defining
-// a new action, you should also consider implementing ActionInterface
-// or using MakePolymorphicAction() instead, especially if you need to
-// use the action a lot.  While these approaches require more work,
-// they give you more control on the types of the mock function
-// arguments and the action parameters, which in general leads to
-// better compiler error messages that pay off in the long run.  They
-// also allow overloading actions based on parameter types (as opposed
-// to just based on the number of parameters).
-//
-// CAVEAT:
-//
-// ACTION*() can only be used in a namespace scope.  The reason is
-// that C++ doesn't yet allow function-local types to be used to
-// instantiate templates.  The up-coming C++0x standard will fix this.
-// Once that's done, we'll consider supporting using ACTION*() inside
-// a function.
-//
-// MORE INFORMATION:
-//
-// To learn more about using these macros, please search for 'ACTION'
-// on http://code.google.com/p/googlemock/wiki/CookBook.
-
-$range i 0..n
-$range k 0..n-1
-
-// An internal macro needed for implementing ACTION*().
-#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
-    const args_type& args GTEST_ATTRIBUTE_UNUSED_
-$for k [[, \
-    arg$k[[]]_type arg$k GTEST_ATTRIBUTE_UNUSED_]]
-
-
-// Sometimes you want to give an action explicit template parameters
-// that cannot be inferred from its value parameters.  ACTION() and
-// ACTION_P*() don't support that.  ACTION_TEMPLATE() remedies that
-// and can be viewed as an extension to ACTION() and ACTION_P*().
-//
-// The syntax:
-//
-//   ACTION_TEMPLATE(ActionName,
-//                   HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
-//                   AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
-//
-// defines an action template that takes m explicit template
-// parameters and n value parameters.  name_i is the name of the i-th
-// template parameter, and kind_i specifies whether it's a typename,
-// an integral constant, or a template.  p_i is the name of the i-th
-// value parameter.
-//
-// Example:
-//
-//   // DuplicateArg<k, T>(output) converts the k-th argument of the mock
-//   // function to type T and copies it to *output.
-//   ACTION_TEMPLATE(DuplicateArg,
-//                   HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
-//                   AND_1_VALUE_PARAMS(output)) {
-//     *output = T(::testing::get<k>(args));
-//   }
-//   ...
-//     int n;
-//     EXPECT_CALL(mock, Foo(_, _))
-//         .WillOnce(DuplicateArg<1, unsigned char>(&n));
-//
-// To create an instance of an action template, write:
-//
-//   ActionName<t1, ..., t_m>(v1, ..., v_n)
-//
-// where the ts are the template arguments and the vs are the value
-// arguments.  The value argument types are inferred by the compiler.
-// If you want to explicitly specify the value argument types, you can
-// provide additional template arguments:
-//
-//   ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
-//
-// where u_i is the desired type of v_i.
-//
-// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
-// number of value parameters, but not on the number of template
-// parameters.  Without the restriction, the meaning of the following
-// is unclear:
-//
-//   OverloadedAction<int, bool>(x);
-//
-// Are we using a single-template-parameter action where 'bool' refers
-// to the type of x, or are we using a two-template-parameter action
-// where the compiler is asked to infer the type of x?
-//
-// Implementation notes:
-//
-// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
-// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
-// implementing ACTION_TEMPLATE.  The main trick we use is to create
-// new macro invocations when expanding a macro.  For example, we have
-//
-//   #define ACTION_TEMPLATE(name, template_params, value_params)
-//       ... GMOCK_INTERNAL_DECL_##template_params ...
-//
-// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
-// to expand to
-//
-//       ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
-//
-// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
-// preprocessor will continue to expand it to
-//
-//       ... typename T ...
-//
-// This technique conforms to the C++ standard and is portable.  It
-// allows us to implement action templates using O(N) code, where N is
-// the maximum number of template/value parameters supported.  Without
-// using it, we'd have to devote O(N^2) amount of code to implement all
-// combinations of m and n.
-
-// Declares the template parameters.
-
-$range j 1..n
-$for j [[
-$range m 0..j-1
-#define GMOCK_INTERNAL_DECL_HAS_$j[[]]
-_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[kind$m name$m]]
-
-
-]]
-
-// Lists the template parameters.
-
-$for j [[
-$range m 0..j-1
-#define GMOCK_INTERNAL_LIST_HAS_$j[[]]
-_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[name$m]]
-
-
-]]
-
-// Declares the types of value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_DECL_TYPE_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]]
-
-
-]]
-
-// Initializes the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\
-    ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(gmock_p$j)]]
-
-
-]]
-
-// Declares the fields for storing the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_DEFN_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j [[p$j##_type p$j; ]]
-
-
-]]
-
-// Lists the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_LIST_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j, [[p$j]]
-
-
-]]
-
-// Lists the value parameter types.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_LIST_TYPE_AND_$i[[]]
-_VALUE_PARAMS($for j, [[p$j]]) $for j [[, p$j##_type]]
-
-
-]]
-
-// Declares the value parameters.
-
-$for i [[
-$range j 0..i-1
-#define GMOCK_INTERNAL_DECL_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
-$for j, [[p$j##_type p$j]]
-
-
-]]
-
-// The suffix of the class template implementing the action template.
-$for i [[
-
-
-$range j 0..i-1
-#define GMOCK_INTERNAL_COUNT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
-$if i==1 [[P]] $elif i>=2 [[P$i]]
-]]
-
-
-// The name of the class template implementing the action template.
-#define GMOCK_ACTION_CLASS_(name, value_params)\
-    GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
-
-$range k 0..n-1
-
-#define ACTION_TEMPLATE(name, template_params, value_params)\
-  template <GMOCK_INTERNAL_DECL_##template_params\
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
-  class GMOCK_ACTION_CLASS_(name, value_params) {\
-   public:\
-    explicit GMOCK_ACTION_CLASS_(name, value_params)\
-        GMOCK_INTERNAL_INIT_##value_params {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <$for k, [[typename arg$k[[]]_type]]>\
-      return_type gmock_PerformImpl(const args_type& args[[]]
-$for k [[, arg$k[[]]_type arg$k]]) const;\
-      GMOCK_INTERNAL_DEFN_##value_params\
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(\
-          new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
-    }\
-    GMOCK_INTERNAL_DEFN_##value_params\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
-  };\
-  template <GMOCK_INTERNAL_DECL_##template_params\
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
-  inline GMOCK_ACTION_CLASS_(name, value_params)<\
-      GMOCK_INTERNAL_LIST_##template_params\
-      GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\
-          GMOCK_INTERNAL_DECL_##value_params) {\
-    return GMOCK_ACTION_CLASS_(name, value_params)<\
-        GMOCK_INTERNAL_LIST_##template_params\
-        GMOCK_INTERNAL_LIST_TYPE_##value_params>(\
-            GMOCK_INTERNAL_LIST_##value_params);\
-  }\
-  template <GMOCK_INTERNAL_DECL_##template_params\
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>\
-  template <typename F>\
-  template <typename arg0_type, typename arg1_type, typename arg2_type, \
-      typename arg3_type, typename arg4_type, typename arg5_type, \
-      typename arg6_type, typename arg7_type, typename arg8_type, \
-      typename arg9_type>\
-  typename ::testing::internal::Function<F>::Result\
-      GMOCK_ACTION_CLASS_(name, value_params)<\
-          GMOCK_INTERNAL_LIST_##template_params\
-          GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
-              gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-$for i
-
-[[
-$var template = [[$if i==0 [[]] $else [[
-$range j 0..i-1
-
-  template <$for j, [[typename p$j##_type]]>\
-]]]]
-$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
-                                                $else [[P$i]]]]]]
-$range j 0..i-1
-$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
-$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
-$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
-$var param_field_decls = [[$for j
-[[
-
-      p$j##_type p$j;\
-]]]]
-$var param_field_decls2 = [[$for j
-[[
-
-    p$j##_type p$j;\
-]]]]
-$var params = [[$for j, [[p$j]]]]
-$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
-$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]]
-$var arg_types_and_names = [[$for k, [[arg$k[[]]_type arg$k]]]]
-$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
-                                        $else [[ACTION_P$i]]]]
-
-#define $macro_name(name$for j [[, p$j]])\$template
-  class $class_name {\
-   public:\
-    [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\
-    template <typename F>\
-    class gmock_Impl : public ::testing::ActionInterface<F> {\
-     public:\
-      typedef F function_type;\
-      typedef typename ::testing::internal::Function<F>::Result return_type;\
-      typedef typename ::testing::internal::Function<F>::ArgumentTuple\
-          args_type;\
-      [[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\
-      virtual return_type Perform(const args_type& args) {\
-        return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
-            Perform(this, args);\
-      }\
-      template <$typename_arg_types>\
-      return_type gmock_PerformImpl(const args_type& args, [[]]
-$arg_types_and_names) const;\$param_field_decls
-     private:\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename F> operator ::testing::Action<F>() const {\
-      return ::testing::Action<F>(new gmock_Impl<F>($params));\
-    }\$param_field_decls2
-   private:\
-    GTEST_DISALLOW_ASSIGN_($class_name);\
-  };\$template
-  inline $class_name$param_types name($param_types_and_names) {\
-    return $class_name$param_types($params);\
-  }\$template
-  template <typename F>\
-  template <$typename_arg_types>\
-  typename ::testing::internal::Function<F>::Result\
-      $class_name$param_types::gmock_Impl<F>::gmock_PerformImpl(\
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-]]
-$$ }  // This meta comment fixes auto-indentation in Emacs.  It won't
-$$    // show up in the generated code.
-
-
-namespace testing {
-
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma.  Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Various overloads for InvokeArgument<N>().
-//
-// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
-// (0-based) argument, which must be a k-ary callable, of the mock
-// function, with arguments a1, a2, ..., a_k.
-//
-// Notes:
-//
-//   1. The arguments are passed by value by default.  If you need to
-//   pass an argument by reference, wrap it inside ByRef().  For
-//   example,
-//
-//     InvokeArgument<1>(5, string("Hello"), ByRef(foo))
-//
-//   passes 5 and string("Hello") by value, and passes foo by
-//   reference.
-//
-//   2. If the callable takes an argument by reference but ByRef() is
-//   not used, it will receive the reference to a copy of the value,
-//   instead of the original value.  For example, when the 0-th
-//   argument of the mock function takes a const string&, the action
-//
-//     InvokeArgument<0>(string("Hello"))
-//
-//   makes a copy of the temporary string("Hello") object and passes a
-//   reference of the copy, instead of the original temporary object,
-//   to the callable.  This makes it easy for a user to define an
-//   InvokeArgument action from temporary values and have it performed
-//   later.
-
-namespace internal {
-namespace invoke_argument {
-
-// Appears in InvokeArgumentAdl's argument list to help avoid
-// accidental calls to user functions of the same name.
-struct AdlTag {};
-
-// InvokeArgumentAdl - a helper for InvokeArgument.
-// The basic overloads are provided here for generic functors.
-// Overloads for other custom-callables are provided in the
-// internal/custom/callback-actions.h header.
-
-$range i 0..n
-$for i
-[[
-$range j 1..i
-
-template <typename R, typename F[[$for j [[, typename A$j]]]]>
-R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) {
-  return f([[$for j, [[a$j]]]]);
-}
-]]
-
-}  // namespace invoke_argument
-}  // namespace internal
-
-$range i 0..n
-$for i [[
-$range j 0..i-1
-
-ACTION_TEMPLATE(InvokeArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) {
-  using internal::invoke_argument::InvokeArgumentAdl;
-  return InvokeArgumentAdl<return_type>(
-      internal::invoke_argument::AdlTag(),
-      ::testing::get<k>(args)$for j [[, p$j]]);
-}
-
-]]
-
-// Various overloads for ReturnNew<T>().
-//
-// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
-// instance of type T, constructed on the heap with constructor arguments
-// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
-$range i 0..n
-$for i [[
-$range j 0..i-1
-$var ps = [[$for j, [[p$j]]]]
-
-ACTION_TEMPLATE(ReturnNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_$i[[]]_VALUE_PARAMS($ps)) {
-  return new T($ps);
-}
-
-]]
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-}  // namespace testing
-
-// Include any custom callback actions added by the local installation.
-// We must include this header at the end to make sure it can use the
-// declarations from this file.
-#include "gmock/internal/custom/gmock-generated-actions.h"
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-function-mockers.h b/testing/gmock/include/gmock/gmock-generated-function-mockers.h
deleted file mode 100644
index 4fa5ca9..0000000
--- a/testing/gmock/include/gmock/gmock-generated-function-mockers.h
+++ /dev/null
@@ -1,1095 +0,0 @@
-// This file was GENERATED by command:
-//     pump.py gmock-generated-function-mockers.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements function mockers of various arities.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-
-#include "gmock/gmock-spec-builders.h"
-#include "gmock/internal/gmock-internal-utils.h"
-
-#if GTEST_HAS_STD_FUNCTION_
-# include <functional>
-#endif
-
-namespace testing {
-namespace internal {
-
-template <typename F>
-class FunctionMockerBase;
-
-// Note: class FunctionMocker really belongs to the ::testing
-// namespace.  However if we define it in ::testing, MSVC will
-// complain when classes in ::testing::internal declare it as a
-// friend class template.  To workaround this compiler bug, we define
-// FunctionMocker in ::testing::internal and import it into ::testing.
-template <typename F>
-class FunctionMocker;
-
-template <typename R>
-class FunctionMocker<R()> : public
-    internal::FunctionMockerBase<R()> {
- public:
-  typedef R F();
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With() {
-    return this->current_spec();
-  }
-
-  R Invoke() {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple());
-  }
-};
-
-template <typename R, typename A1>
-class FunctionMocker<R(A1)> : public
-    internal::FunctionMockerBase<R(A1)> {
- public:
-  typedef R F(A1);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1));
-  }
-};
-
-template <typename R, typename A1, typename A2>
-class FunctionMocker<R(A1, A2)> : public
-    internal::FunctionMockerBase<R(A1, A2)> {
- public:
-  typedef R F(A1, A2);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3>
-class FunctionMocker<R(A1, A2, A3)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3)> {
- public:
-  typedef R F(A1, A2, A3);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4>
-class FunctionMocker<R(A1, A2, A3, A4)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4)> {
- public:
-  typedef R F(A1, A2, A3, A4);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-class FunctionMocker<R(A1, A2, A3, A4, A5)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5)> {
- public:
-  typedef R F(A1, A2, A3, A4, A5);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-class FunctionMocker<R(A1, A2, A3, A4, A5, A6)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6)> {
- public:
-  typedef R F(A1, A2, A3, A4, A5, A6);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
-      const Matcher<A6>& m6) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
-        m6));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7)> {
- public:
-  typedef R F(A1, A2, A3, A4, A5, A6, A7);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
-      const Matcher<A6>& m6, const Matcher<A7>& m7) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
-        m6, m7));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8>
-class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8)> {
- public:
-  typedef R F(A1, A2, A3, A4, A5, A6, A7, A8);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
-      const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
-        m6, m7, m8));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8, typename A9>
-class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
- public:
-  typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
-      const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8,
-      const Matcher<A9>& m9) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
-        m6, m7, m8, m9));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9));
-  }
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8, typename A9,
-    typename A10>
-class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public
-    internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> {
- public:
-  typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2,
-      const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5,
-      const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8,
-      const Matcher<A9>& m9, const Matcher<A10>& m10) {
-    this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5,
-        m6, m7, m8, m9, m10));
-    return this->current_spec();
-  }
-
-  R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9,
-      A10 a10) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9,
-        a10));
-  }
-};
-
-}  // namespace internal
-
-// The style guide prohibits "using" statements in a namespace scope
-// inside a header file.  However, the FunctionMocker class template
-// is meant to be defined in the ::testing namespace.  The following
-// line is just a trick for working around a bug in MSVC 8.0, which
-// cannot handle it if we define FunctionMocker in ::testing.
-using internal::FunctionMocker;
-
-// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
-// We define this as a variadic macro in case F contains unprotected
-// commas (the same reason that we use variadic macros in other places
-// in this file).
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_RESULT_(tn, ...) \
-    tn ::testing::internal::Function<__VA_ARGS__>::Result
-
-// The type of argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_ARG_(tn, N, ...) \
-    tn ::testing::internal::Function<__VA_ARGS__>::Argument##N
-
-// The matcher type for argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MATCHER_(tn, N, ...) \
-    const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
-
-// The variable for mocking the given method.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MOCKER_(arity, constness, Method) \
-    GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      ) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 0), \
-        this_method_does_not_take_0_arguments); \
-    GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(0, constness, Method).Invoke(); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method() constness { \
-    GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(0, constness, Method).With(); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 1), \
-        this_method_does_not_take_1_argument); \
-    GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
-    GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 2), \
-        this_method_does_not_take_2_arguments); \
-    GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
-    GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 3), \
-        this_method_does_not_take_3_arguments); \
-    GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
-    GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 4), \
-        this_method_does_not_take_4_arguments); \
-    GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
-    GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
-      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 5), \
-        this_method_does_not_take_5_arguments); \
-    GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
-                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
-    GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
-      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
-      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 6), \
-        this_method_does_not_take_6_arguments); \
-    GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
-                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
-                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
-    GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
-      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
-      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
-      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 7), \
-        this_method_does_not_take_7_arguments); \
-    GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(7, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
-                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
-                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
-                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
-    GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
-      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
-      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
-      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
-      GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 8), \
-        this_method_does_not_take_8_arguments); \
-    GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(8, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
-                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
-                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
-                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
-                     GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
-    GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
-      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
-      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
-      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
-      GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \
-      GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 9), \
-        this_method_does_not_take_9_arguments); \
-    GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(9, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
-        gmock_a9); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
-                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
-                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
-                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
-                     GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
-                     GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
-    GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
-        gmock_a9); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \
-      Method)
-
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \
-      GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \
-      GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
-      GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \
-      GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \
-      GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
-      GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \
-      GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \
-      GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
-      GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \
-            == 10), \
-        this_method_does_not_take_10_arguments); \
-    GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_(10, constness, Method).Invoke(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
-        gmock_a10); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
-                     GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
-                     GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
-                     GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
-                     GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
-                     GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
-                     GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
-                     GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
-                     GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \
-                     GMOCK_MATCHER_(tn, 10, \
-                         __VA_ARGS__) gmock_a10) constness { \
-    GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \
-        gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
-        gmock_a10); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \
-      Method)
-
-#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__)
-#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__)
-
-#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__)
-#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0_T(m, ...) \
-    GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1_T(m, ...) \
-    GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2_T(m, ...) \
-    GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3_T(m, ...) \
-    GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4_T(m, ...) \
-    GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5_T(m, ...) \
-    GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6_T(m, ...) \
-    GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7_T(m, ...) \
-    GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8_T(m, ...) \
-    GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9_T(m, ...) \
-    GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10_T(m, ...) \
-    GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__)
-
-#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD0_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD1_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD2_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD3_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD4_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD5_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD6_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD7_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD8_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD9_(, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD10_(, , ct, m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__)
-
-#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__)
-#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__)
-
-#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__)
-#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__)
-
-// A MockFunction<F> class has one mock method whose type is F.  It is
-// useful when you just want your test code to emit some messages and
-// have Google Mock verify the right messages are sent (and perhaps at
-// the right times).  For example, if you are exercising code:
-//
-//   Foo(1);
-//   Foo(2);
-//   Foo(3);
-//
-// and want to verify that Foo(1) and Foo(3) both invoke
-// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
-//
-// TEST(FooTest, InvokesBarCorrectly) {
-//   MyMock mock;
-//   MockFunction<void(string check_point_name)> check;
-//   {
-//     InSequence s;
-//
-//     EXPECT_CALL(mock, Bar("a"));
-//     EXPECT_CALL(check, Call("1"));
-//     EXPECT_CALL(check, Call("2"));
-//     EXPECT_CALL(mock, Bar("a"));
-//   }
-//   Foo(1);
-//   check.Call("1");
-//   Foo(2);
-//   check.Call("2");
-//   Foo(3);
-// }
-//
-// The expectation spec says that the first Bar("a") must happen
-// before check point "1", the second Bar("a") must happen after check
-// point "2", and nothing should happen between the two check
-// points. The explicit check points make it easy to tell which
-// Bar("a") is called by which call to Foo().
-//
-// MockFunction<F> can also be used to exercise code that accepts
-// std::function<F> callbacks. To do so, use AsStdFunction() method
-// to create std::function proxy forwarding to original object's Call.
-// Example:
-//
-// TEST(FooTest, RunsCallbackWithBarArgument) {
-//   MockFunction<int(string)> callback;
-//   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
-//   Foo(callback.AsStdFunction());
-// }
-template <typename F>
-class MockFunction;
-
-template <typename R>
-class MockFunction<R()> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD0_T(Call, R());
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R()> AsStdFunction() {
-    return [this]() -> R {
-      return this->Call();
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0>
-class MockFunction<R(A0)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD1_T(Call, R(A0));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0)> AsStdFunction() {
-    return [this](A0 a0) -> R {
-      return this->Call(a0);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1>
-class MockFunction<R(A0, A1)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD2_T(Call, R(A0, A1));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1)> AsStdFunction() {
-    return [this](A0 a0, A1 a1) -> R {
-      return this->Call(a0, a1);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2>
-class MockFunction<R(A0, A1, A2)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD3_T(Call, R(A0, A1, A2));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2) -> R {
-      return this->Call(a0, a1, a2);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3>
-class MockFunction<R(A0, A1, A2, A3)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD4_T(Call, R(A0, A1, A2, A3));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R {
-      return this->Call(a0, a1, a2, a3);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3,
-    typename A4>
-class MockFunction<R(A0, A1, A2, A3, A4)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD5_T(Call, R(A0, A1, A2, A3, A4));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3, A4)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R {
-      return this->Call(a0, a1, a2, a3, a4);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3,
-    typename A4, typename A5>
-class MockFunction<R(A0, A1, A2, A3, A4, A5)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD6_T(Call, R(A0, A1, A2, A3, A4, A5));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3, A4, A5)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R {
-      return this->Call(a0, a1, a2, a3, a4, a5);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6>
-class MockFunction<R(A0, A1, A2, A3, A4, A5, A6)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD7_T(Call, R(A0, A1, A2, A3, A4, A5, A6));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3, A4, A5, A6)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R {
-      return this->Call(a0, a1, a2, a3, a4, a5, a6);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7>
-class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD8_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3, A4, A5, A6, A7)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) -> R {
-      return this->Call(a0, a1, a2, a3, a4, a5, a6, a7);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7, typename A8>
-class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD9_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
-        A8 a8) -> R {
-      return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-template <typename R, typename A0, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7, typename A8,
-    typename A9>
-class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD10_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> AsStdFunction() {
-    return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
-        A8 a8, A9 a9) -> R {
-      return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump b/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump
deleted file mode 100644
index 811502d..0000000
--- a/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump
+++ /dev/null
@@ -1,291 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file.  Please use Pump to convert it to
-$$ gmock-generated-function-mockers.h.
-$$
-$var n = 10  $$ The maximum arity we support.
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements function mockers of various arities.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
-
-#include "gmock/gmock-spec-builders.h"
-#include "gmock/internal/gmock-internal-utils.h"
-
-#if GTEST_HAS_STD_FUNCTION_
-# include <functional>
-#endif
-
-namespace testing {
-namespace internal {
-
-template <typename F>
-class FunctionMockerBase;
-
-// Note: class FunctionMocker really belongs to the ::testing
-// namespace.  However if we define it in ::testing, MSVC will
-// complain when classes in ::testing::internal declare it as a
-// friend class template.  To workaround this compiler bug, we define
-// FunctionMocker in ::testing::internal and import it into ::testing.
-template <typename F>
-class FunctionMocker;
-
-
-$range i 0..n
-$for i [[
-$range j 1..i
-$var typename_As = [[$for j [[, typename A$j]]]]
-$var As = [[$for j, [[A$j]]]]
-$var as = [[$for j, [[a$j]]]]
-$var Aas = [[$for j, [[A$j a$j]]]]
-$var ms = [[$for j, [[m$j]]]]
-$var matchers = [[$for j, [[const Matcher<A$j>& m$j]]]]
-template <typename R$typename_As>
-class FunctionMocker<R($As)> : public
-    internal::FunctionMockerBase<R($As)> {
- public:
-  typedef R F($As);
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-
-  MockSpec<F>& With($matchers) {
-
-$if i >= 1 [[
-    this->current_spec().SetMatchers(::testing::make_tuple($ms));
-
-]]
-    return this->current_spec();
-  }
-
-  R Invoke($Aas) {
-    // Even though gcc and MSVC don't enforce it, 'this->' is required
-    // by the C++ standard [14.6.4] here, as the base class type is
-    // dependent on the template argument (and thus shouldn't be
-    // looked into when resolving InvokeWith).
-    return this->InvokeWith(ArgumentTuple($as));
-  }
-};
-
-
-]]
-}  // namespace internal
-
-// The style guide prohibits "using" statements in a namespace scope
-// inside a header file.  However, the FunctionMocker class template
-// is meant to be defined in the ::testing namespace.  The following
-// line is just a trick for working around a bug in MSVC 8.0, which
-// cannot handle it if we define FunctionMocker in ::testing.
-using internal::FunctionMocker;
-
-// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
-// We define this as a variadic macro in case F contains unprotected
-// commas (the same reason that we use variadic macros in other places
-// in this file).
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_RESULT_(tn, ...) \
-    tn ::testing::internal::Function<__VA_ARGS__>::Result
-
-// The type of argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_ARG_(tn, N, ...) \
-    tn ::testing::internal::Function<__VA_ARGS__>::Argument##N
-
-// The matcher type for argument N of the given function type.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MATCHER_(tn, N, ...) \
-    const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
-
-// The variable for mocking the given method.
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_MOCKER_(arity, constness, Method) \
-    GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
-
-
-$for i [[
-$range j 1..i
-$var arg_as = [[$for j, \
-      [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
-$var as = [[$for j, [[gmock_a$j]]]]
-$var matcher_as = [[$for j, \
-                     [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
-// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
-#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
-  GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
-      $arg_as) constness { \
-    GTEST_COMPILE_ASSERT_((::testing::tuple_size<                          \
-        tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value == $i), \
-        this_method_does_not_take_$i[[]]_argument[[$if i != 1 [[s]]]]); \
-    GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
-    return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
-  } \
-  ::testing::MockSpec<__VA_ARGS__>& \
-      gmock_##Method($matcher_as) constness { \
-    GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
-    return GMOCK_MOCKER_($i, constness, Method).With($as); \
-  } \
-  mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
-
-
-]]
-$for i [[
-#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \
-    GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__)
-
-]]
-
-
-$for i [[
-#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
-    GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__)
-
-]]
-
-// A MockFunction<F> class has one mock method whose type is F.  It is
-// useful when you just want your test code to emit some messages and
-// have Google Mock verify the right messages are sent (and perhaps at
-// the right times).  For example, if you are exercising code:
-//
-//   Foo(1);
-//   Foo(2);
-//   Foo(3);
-//
-// and want to verify that Foo(1) and Foo(3) both invoke
-// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
-//
-// TEST(FooTest, InvokesBarCorrectly) {
-//   MyMock mock;
-//   MockFunction<void(string check_point_name)> check;
-//   {
-//     InSequence s;
-//
-//     EXPECT_CALL(mock, Bar("a"));
-//     EXPECT_CALL(check, Call("1"));
-//     EXPECT_CALL(check, Call("2"));
-//     EXPECT_CALL(mock, Bar("a"));
-//   }
-//   Foo(1);
-//   check.Call("1");
-//   Foo(2);
-//   check.Call("2");
-//   Foo(3);
-// }
-//
-// The expectation spec says that the first Bar("a") must happen
-// before check point "1", the second Bar("a") must happen after check
-// point "2", and nothing should happen between the two check
-// points. The explicit check points make it easy to tell which
-// Bar("a") is called by which call to Foo().
-//
-// MockFunction<F> can also be used to exercise code that accepts
-// std::function<F> callbacks. To do so, use AsStdFunction() method
-// to create std::function proxy forwarding to original object's Call.
-// Example:
-//
-// TEST(FooTest, RunsCallbackWithBarArgument) {
-//   MockFunction<int(string)> callback;
-//   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
-//   Foo(callback.AsStdFunction());
-// }
-template <typename F>
-class MockFunction;
-
-
-$for i [[
-$range j 0..i-1
-$var ArgTypes = [[$for j, [[A$j]]]]
-$var ArgNames = [[$for j, [[a$j]]]]
-$var ArgDecls = [[$for j, [[A$j a$j]]]]
-template <typename R$for j [[, typename A$j]]>
-class MockFunction<R($ArgTypes)> {
- public:
-  MockFunction() {}
-
-  MOCK_METHOD$i[[]]_T(Call, R($ArgTypes));
-
-#if GTEST_HAS_STD_FUNCTION_
-  std::function<R($ArgTypes)> AsStdFunction() {
-    return [this]($ArgDecls) -> R {
-      return this->Call($ArgNames);
-    };
-  }
-#endif  // GTEST_HAS_STD_FUNCTION_
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
-};
-
-
-]]
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-matchers.h b/testing/gmock/include/gmock/gmock-generated-matchers.h
deleted file mode 100644
index 57056fd..0000000
--- a/testing/gmock/include/gmock/gmock-generated-matchers.h
+++ /dev/null
@@ -1,2179 +0,0 @@
-// This file was GENERATED by command:
-//     pump.py gmock-generated-matchers.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used variadic matchers.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-
-#include <iterator>
-#include <sstream>
-#include <string>
-#include <vector>
-#include "gmock/gmock-matchers.h"
-
-namespace testing {
-namespace internal {
-
-// The type of the i-th (0-based) field of Tuple.
-#define GMOCK_FIELD_TYPE_(Tuple, i) \
-    typename ::testing::tuple_element<i, Tuple>::type
-
-// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
-// tuple of type Tuple.  It has two members:
-//
-//   type: a tuple type whose i-th field is the ki-th field of Tuple.
-//   GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple.
-//
-// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have:
-//
-//   type is tuple<int, bool>, and
-//   GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true).
-
-template <class Tuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1,
-    int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1,
-    int k9 = -1>
-class TupleFields;
-
-// This generic version is used when there are 10 selectors.
-template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6,
-    int k7, int k8, int k9>
-class TupleFields {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
-      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6),
-      GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8),
-      GMOCK_FIELD_TYPE_(Tuple, k9)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
-        get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t), get<k9>(t));
-  }
-};
-
-// The following specialization is used for 0 ~ 9 selectors.
-
-template <class Tuple>
-class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<> type;
-  static type GetSelectedFields(const Tuple& /* t */) {
-    return type();
-  }
-};
-
-template <class Tuple, int k0>
-class TupleFields<Tuple, k0, -1, -1, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1>
-class TupleFields<Tuple, k0, k1, -1, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2>
-class TupleFields<Tuple, k0, k1, k2, -1, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2, int k3>
-class TupleFields<Tuple, k0, k1, k2, k3, -1, -1, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2, int k3, int k4>
-class TupleFields<Tuple, k0, k1, k2, k3, k4, -1, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5>
-class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, -1, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
-      GMOCK_FIELD_TYPE_(Tuple, k5)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
-        get<k5>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6>
-class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, -1, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
-      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
-        get<k5>(t), get<k6>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6,
-    int k7>
-class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, -1, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
-      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6),
-      GMOCK_FIELD_TYPE_(Tuple, k7)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
-        get<k5>(t), get<k6>(t), get<k7>(t));
-  }
-};
-
-template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6,
-    int k7, int k8>
-class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, -1> {
- public:
-  typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0),
-      GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2),
-      GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4),
-      GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6),
-      GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8)> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t),
-        get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t));
-  }
-};
-
-#undef GMOCK_FIELD_TYPE_
-
-// Implements the Args() matcher.
-template <class ArgsTuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1,
-    int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1,
-    int k9 = -1>
-class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
- public:
-  // ArgsTuple may have top-level const or reference modifiers.
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple;
-  typedef typename internal::TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5,
-      k6, k7, k8, k9>::type SelectedArgs;
-  typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher;
-
-  template <typename InnerMatcher>
-  explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
-      : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
-
-  virtual bool MatchAndExplain(ArgsTuple args,
-                               MatchResultListener* listener) const {
-    const SelectedArgs& selected_args = GetSelectedArgs(args);
-    if (!listener->IsInterested())
-      return inner_matcher_.Matches(selected_args);
-
-    PrintIndices(listener->stream());
-    *listener << "are " << PrintToString(selected_args);
-
-    StringMatchResultListener inner_listener;
-    const bool match = inner_matcher_.MatchAndExplain(selected_args,
-                                                      &inner_listener);
-    PrintIfNotEmpty(inner_listener.str(), listener->stream());
-    return match;
-  }
-
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "are a tuple ";
-    PrintIndices(os);
-    inner_matcher_.DescribeTo(os);
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "are a tuple ";
-    PrintIndices(os);
-    inner_matcher_.DescribeNegationTo(os);
-  }
-
- private:
-  static SelectedArgs GetSelectedArgs(ArgsTuple args) {
-    return TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8,
-        k9>::GetSelectedFields(args);
-  }
-
-  // Prints the indices of the selected fields.
-  static void PrintIndices(::std::ostream* os) {
-    *os << "whose fields (";
-    const int indices[10] = { k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 };
-    for (int i = 0; i < 10; i++) {
-      if (indices[i] < 0)
-        break;
-
-      if (i >= 1)
-        *os << ", ";
-
-      *os << "#" << indices[i];
-    }
-    *os << ") ";
-  }
-
-  const MonomorphicInnerMatcher inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl);
-};
-
-template <class InnerMatcher, int k0 = -1, int k1 = -1, int k2 = -1,
-    int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1,
-    int k8 = -1, int k9 = -1>
-class ArgsMatcher {
- public:
-  explicit ArgsMatcher(const InnerMatcher& inner_matcher)
-      : inner_matcher_(inner_matcher) {}
-
-  template <typename ArgsTuple>
-  operator Matcher<ArgsTuple>() const {
-    return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k0, k1, k2, k3, k4, k5,
-        k6, k7, k8, k9>(inner_matcher_));
-  }
-
- private:
-  const InnerMatcher inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(ArgsMatcher);
-};
-
-// A set of metafunctions for computing the result type of AllOf.
-// AllOf(m1, ..., mN) returns
-// AllOfResultN<decltype(m1), ..., decltype(mN)>::type.
-
-// Although AllOf isn't defined for one argument, AllOfResult1 is defined
-// to simplify the implementation.
-template <typename M1>
-struct AllOfResult1 {
-  typedef M1 type;
-};
-
-template <typename M1, typename M2>
-struct AllOfResult2 {
-  typedef BothOfMatcher<
-      typename AllOfResult1<M1>::type,
-      typename AllOfResult1<M2>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3>
-struct AllOfResult3 {
-  typedef BothOfMatcher<
-      typename AllOfResult1<M1>::type,
-      typename AllOfResult2<M2, M3>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4>
-struct AllOfResult4 {
-  typedef BothOfMatcher<
-      typename AllOfResult2<M1, M2>::type,
-      typename AllOfResult2<M3, M4>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5>
-struct AllOfResult5 {
-  typedef BothOfMatcher<
-      typename AllOfResult2<M1, M2>::type,
-      typename AllOfResult3<M3, M4, M5>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6>
-struct AllOfResult6 {
-  typedef BothOfMatcher<
-      typename AllOfResult3<M1, M2, M3>::type,
-      typename AllOfResult3<M4, M5, M6>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7>
-struct AllOfResult7 {
-  typedef BothOfMatcher<
-      typename AllOfResult3<M1, M2, M3>::type,
-      typename AllOfResult4<M4, M5, M6, M7>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8>
-struct AllOfResult8 {
-  typedef BothOfMatcher<
-      typename AllOfResult4<M1, M2, M3, M4>::type,
-      typename AllOfResult4<M5, M6, M7, M8>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9>
-struct AllOfResult9 {
-  typedef BothOfMatcher<
-      typename AllOfResult4<M1, M2, M3, M4>::type,
-      typename AllOfResult5<M5, M6, M7, M8, M9>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9, typename M10>
-struct AllOfResult10 {
-  typedef BothOfMatcher<
-      typename AllOfResult5<M1, M2, M3, M4, M5>::type,
-      typename AllOfResult5<M6, M7, M8, M9, M10>::type
-  > type;
-};
-
-// A set of metafunctions for computing the result type of AnyOf.
-// AnyOf(m1, ..., mN) returns
-// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type.
-
-// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined
-// to simplify the implementation.
-template <typename M1>
-struct AnyOfResult1 {
-  typedef M1 type;
-};
-
-template <typename M1, typename M2>
-struct AnyOfResult2 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult1<M1>::type,
-      typename AnyOfResult1<M2>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3>
-struct AnyOfResult3 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult1<M1>::type,
-      typename AnyOfResult2<M2, M3>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4>
-struct AnyOfResult4 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult2<M1, M2>::type,
-      typename AnyOfResult2<M3, M4>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5>
-struct AnyOfResult5 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult2<M1, M2>::type,
-      typename AnyOfResult3<M3, M4, M5>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6>
-struct AnyOfResult6 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult3<M1, M2, M3>::type,
-      typename AnyOfResult3<M4, M5, M6>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7>
-struct AnyOfResult7 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult3<M1, M2, M3>::type,
-      typename AnyOfResult4<M4, M5, M6, M7>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8>
-struct AnyOfResult8 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult4<M1, M2, M3, M4>::type,
-      typename AnyOfResult4<M5, M6, M7, M8>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9>
-struct AnyOfResult9 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult4<M1, M2, M3, M4>::type,
-      typename AnyOfResult5<M5, M6, M7, M8, M9>::type
-  > type;
-};
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9, typename M10>
-struct AnyOfResult10 {
-  typedef EitherOfMatcher<
-      typename AnyOfResult5<M1, M2, M3, M4, M5>::type,
-      typename AnyOfResult5<M6, M7, M8, M9, M10>::type
-  > type;
-};
-
-}  // namespace internal
-
-// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
-// fields of it matches a_matcher.  C++ doesn't support default
-// arguments for function templates, so we have to overload it.
-template <typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher>(matcher);
-}
-
-template <int k1, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1>(matcher);
-}
-
-template <int k1, int k2, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2>(matcher);
-}
-
-template <int k1, int k2, int k3, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7,
-    typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6,
-      k7>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
-    typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7,
-      k8>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
-    int k9, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8,
-      k9>(matcher);
-}
-
-template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8,
-    int k9, int k10, typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9,
-    k10>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8,
-      k9, k10>(matcher);
-}
-
-// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with
-// n elements, where the i-th element in the container must
-// match the i-th argument in the list.  Each argument of
-// ElementsAre() can be either a value or a matcher.  We support up to
-// 10 arguments.
-//
-// The use of DecayArray in the implementation allows ElementsAre()
-// to accept string literals, whose type is const char[N], but we
-// want to treat them as const char*.
-//
-// NOTE: Since ElementsAre() cares about the order of the elements, it
-// must not be used with containers whose elements's order is
-// undefined (e.g. hash_map).
-
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<> >
-ElementsAre() {
-  typedef ::testing::tuple<> Args;
-  return internal::ElementsAreMatcher<Args>(Args());
-}
-
-template <typename T1>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type> >
-ElementsAre(const T1& e1) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1));
-}
-
-template <typename T1, typename T2>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type> >
-ElementsAre(const T1& e1, const T2& e2) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2));
-}
-
-template <typename T1, typename T2, typename T3>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3));
-}
-
-template <typename T1, typename T2, typename T3, typename T4>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7, typename T8>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type,
-        typename internal::DecayArray<T8>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7, const T8& e8) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type,
-      typename internal::DecayArray<T8>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7,
-      e8));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7, typename T8, typename T9>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type,
-        typename internal::DecayArray<T8>::type,
-        typename internal::DecayArray<T9>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type,
-      typename internal::DecayArray<T8>::type,
-      typename internal::DecayArray<T9>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7,
-      e8, e9));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7, typename T8, typename T9, typename T10>
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type,
-        typename internal::DecayArray<T8>::type,
-        typename internal::DecayArray<T9>::type,
-        typename internal::DecayArray<T10>::type> >
-ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9,
-    const T10& e10) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type,
-      typename internal::DecayArray<T8>::type,
-      typename internal::DecayArray<T9>::type,
-      typename internal::DecayArray<T10>::type> Args;
-  return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7,
-      e8, e9, e10));
-}
-
-// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension
-// that matches n elements in any order.  We support up to n=10 arguments.
-
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<> >
-UnorderedElementsAre() {
-  typedef ::testing::tuple<> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args());
-}
-
-template <typename T1>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type> >
-UnorderedElementsAre(const T1& e1) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1));
-}
-
-template <typename T1, typename T2>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2));
-}
-
-template <typename T1, typename T2, typename T3>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3));
-}
-
-template <typename T1, typename T2, typename T3, typename T4>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
-      e6));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
-      e6, e7));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7, typename T8>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type,
-        typename internal::DecayArray<T8>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7, const T8& e8) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type,
-      typename internal::DecayArray<T8>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
-      e6, e7, e8));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7, typename T8, typename T9>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type,
-        typename internal::DecayArray<T8>::type,
-        typename internal::DecayArray<T9>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type,
-      typename internal::DecayArray<T8>::type,
-      typename internal::DecayArray<T9>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
-      e6, e7, e8, e9));
-}
-
-template <typename T1, typename T2, typename T3, typename T4, typename T5,
-    typename T6, typename T7, typename T8, typename T9, typename T10>
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-        typename internal::DecayArray<T1>::type,
-        typename internal::DecayArray<T2>::type,
-        typename internal::DecayArray<T3>::type,
-        typename internal::DecayArray<T4>::type,
-        typename internal::DecayArray<T5>::type,
-        typename internal::DecayArray<T6>::type,
-        typename internal::DecayArray<T7>::type,
-        typename internal::DecayArray<T8>::type,
-        typename internal::DecayArray<T9>::type,
-        typename internal::DecayArray<T10>::type> >
-UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4,
-    const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9,
-    const T10& e10) {
-  typedef ::testing::tuple<
-      typename internal::DecayArray<T1>::type,
-      typename internal::DecayArray<T2>::type,
-      typename internal::DecayArray<T3>::type,
-      typename internal::DecayArray<T4>::type,
-      typename internal::DecayArray<T5>::type,
-      typename internal::DecayArray<T6>::type,
-      typename internal::DecayArray<T7>::type,
-      typename internal::DecayArray<T8>::type,
-      typename internal::DecayArray<T9>::type,
-      typename internal::DecayArray<T10>::type> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5,
-      e6, e7, e8, e9, e10));
-}
-
-// AllOf(m1, m2, ..., mk) matches any value that matches all of the given
-// sub-matchers.  AllOf is called fully qualified to prevent ADL from firing.
-
-template <typename M1, typename M2>
-inline typename internal::AllOfResult2<M1, M2>::type
-AllOf(M1 m1, M2 m2) {
-  return typename internal::AllOfResult2<M1, M2>::type(
-      m1,
-      m2);
-}
-
-template <typename M1, typename M2, typename M3>
-inline typename internal::AllOfResult3<M1, M2, M3>::type
-AllOf(M1 m1, M2 m2, M3 m3) {
-  return typename internal::AllOfResult3<M1, M2, M3>::type(
-      m1,
-      ::testing::AllOf(m2, m3));
-}
-
-template <typename M1, typename M2, typename M3, typename M4>
-inline typename internal::AllOfResult4<M1, M2, M3, M4>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4) {
-  return typename internal::AllOfResult4<M1, M2, M3, M4>::type(
-      ::testing::AllOf(m1, m2),
-      ::testing::AllOf(m3, m4));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5>
-inline typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) {
-  return typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type(
-      ::testing::AllOf(m1, m2),
-      ::testing::AllOf(m3, m4, m5));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6>
-inline typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) {
-  return typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type(
-      ::testing::AllOf(m1, m2, m3),
-      ::testing::AllOf(m4, m5, m6));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7>
-inline typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) {
-  return typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type(
-      ::testing::AllOf(m1, m2, m3),
-      ::testing::AllOf(m4, m5, m6, m7));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8>
-inline typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) {
-  return typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type(
-      ::testing::AllOf(m1, m2, m3, m4),
-      ::testing::AllOf(m5, m6, m7, m8));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9>
-inline typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) {
-  return typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8,
-      M9>::type(
-      ::testing::AllOf(m1, m2, m3, m4),
-      ::testing::AllOf(m5, m6, m7, m8, m9));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9, typename M10>
-inline typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
-    M10>::type
-AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) {
-  return typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
-      M10>::type(
-      ::testing::AllOf(m1, m2, m3, m4, m5),
-      ::testing::AllOf(m6, m7, m8, m9, m10));
-}
-
-// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given
-// sub-matchers.  AnyOf is called fully qualified to prevent ADL from firing.
-
-template <typename M1, typename M2>
-inline typename internal::AnyOfResult2<M1, M2>::type
-AnyOf(M1 m1, M2 m2) {
-  return typename internal::AnyOfResult2<M1, M2>::type(
-      m1,
-      m2);
-}
-
-template <typename M1, typename M2, typename M3>
-inline typename internal::AnyOfResult3<M1, M2, M3>::type
-AnyOf(M1 m1, M2 m2, M3 m3) {
-  return typename internal::AnyOfResult3<M1, M2, M3>::type(
-      m1,
-      ::testing::AnyOf(m2, m3));
-}
-
-template <typename M1, typename M2, typename M3, typename M4>
-inline typename internal::AnyOfResult4<M1, M2, M3, M4>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) {
-  return typename internal::AnyOfResult4<M1, M2, M3, M4>::type(
-      ::testing::AnyOf(m1, m2),
-      ::testing::AnyOf(m3, m4));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5>
-inline typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) {
-  return typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type(
-      ::testing::AnyOf(m1, m2),
-      ::testing::AnyOf(m3, m4, m5));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6>
-inline typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) {
-  return typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type(
-      ::testing::AnyOf(m1, m2, m3),
-      ::testing::AnyOf(m4, m5, m6));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7>
-inline typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) {
-  return typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type(
-      ::testing::AnyOf(m1, m2, m3),
-      ::testing::AnyOf(m4, m5, m6, m7));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8>
-inline typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) {
-  return typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type(
-      ::testing::AnyOf(m1, m2, m3, m4),
-      ::testing::AnyOf(m5, m6, m7, m8));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9>
-inline typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) {
-  return typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8,
-      M9>::type(
-      ::testing::AnyOf(m1, m2, m3, m4),
-      ::testing::AnyOf(m5, m6, m7, m8, m9));
-}
-
-template <typename M1, typename M2, typename M3, typename M4, typename M5,
-    typename M6, typename M7, typename M8, typename M9, typename M10>
-inline typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
-    M10>::type
-AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) {
-  return typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9,
-      M10>::type(
-      ::testing::AnyOf(m1, m2, m3, m4, m5),
-      ::testing::AnyOf(m6, m7, m8, m9, m10));
-}
-
-}  // namespace testing
-
-
-// The MATCHER* family of macros can be used in a namespace scope to
-// define custom matchers easily.
-//
-// Basic Usage
-// ===========
-//
-// The syntax
-//
-//   MATCHER(name, description_string) { statements; }
-//
-// defines a matcher with the given name that executes the statements,
-// which must return a bool to indicate if the match succeeds.  Inside
-// the statements, you can refer to the value being matched by 'arg',
-// and refer to its type by 'arg_type'.
-//
-// The description string documents what the matcher does, and is used
-// to generate the failure message when the match fails.  Since a
-// MATCHER() is usually defined in a header file shared by multiple
-// C++ source files, we require the description to be a C-string
-// literal to avoid possible side effects.  It can be empty, in which
-// case we'll use the sequence of words in the matcher name as the
-// description.
-//
-// For example:
-//
-//   MATCHER(IsEven, "") { return (arg % 2) == 0; }
-//
-// allows you to write
-//
-//   // Expects mock_foo.Bar(n) to be called where n is even.
-//   EXPECT_CALL(mock_foo, Bar(IsEven()));
-//
-// or,
-//
-//   // Verifies that the value of some_expression is even.
-//   EXPECT_THAT(some_expression, IsEven());
-//
-// If the above assertion fails, it will print something like:
-//
-//   Value of: some_expression
-//   Expected: is even
-//     Actual: 7
-//
-// where the description "is even" is automatically calculated from the
-// matcher name IsEven.
-//
-// Argument Type
-// =============
-//
-// Note that the type of the value being matched (arg_type) is
-// determined by the context in which you use the matcher and is
-// supplied to you by the compiler, so you don't need to worry about
-// declaring it (nor can you).  This allows the matcher to be
-// polymorphic.  For example, IsEven() can be used to match any type
-// where the value of "(arg % 2) == 0" can be implicitly converted to
-// a bool.  In the "Bar(IsEven())" example above, if method Bar()
-// takes an int, 'arg_type' will be int; if it takes an unsigned long,
-// 'arg_type' will be unsigned long; and so on.
-//
-// Parameterizing Matchers
-// =======================
-//
-// Sometimes you'll want to parameterize the matcher.  For that you
-// can use another macro:
-//
-//   MATCHER_P(name, param_name, description_string) { statements; }
-//
-// For example:
-//
-//   MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
-//
-// will allow you to write:
-//
-//   EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
-//
-// which may lead to this message (assuming n is 10):
-//
-//   Value of: Blah("a")
-//   Expected: has absolute value 10
-//     Actual: -9
-//
-// Note that both the matcher description and its parameter are
-// printed, making the message human-friendly.
-//
-// In the matcher definition body, you can write 'foo_type' to
-// reference the type of a parameter named 'foo'.  For example, in the
-// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
-// 'value_type' to refer to the type of 'value'.
-//
-// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to
-// support multi-parameter matchers.
-//
-// Describing Parameterized Matchers
-// =================================
-//
-// The last argument to MATCHER*() is a string-typed expression.  The
-// expression can reference all of the matcher's parameters and a
-// special bool-typed variable named 'negation'.  When 'negation' is
-// false, the expression should evaluate to the matcher's description;
-// otherwise it should evaluate to the description of the negation of
-// the matcher.  For example,
-//
-//   using testing::PrintToString;
-//
-//   MATCHER_P2(InClosedRange, low, hi,
-//       string(negation ? "is not" : "is") + " in range [" +
-//       PrintToString(low) + ", " + PrintToString(hi) + "]") {
-//     return low <= arg && arg <= hi;
-//   }
-//   ...
-//   EXPECT_THAT(3, InClosedRange(4, 6));
-//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-//   Expected: is in range [4, 6]
-//   ...
-//   Expected: is not in range [2, 4]
-//
-// If you specify "" as the description, the failure message will
-// contain the sequence of words in the matcher name followed by the
-// parameter values printed as a tuple.  For example,
-//
-//   MATCHER_P2(InClosedRange, low, hi, "") { ... }
-//   ...
-//   EXPECT_THAT(3, InClosedRange(4, 6));
-//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-//   Expected: in closed range (4, 6)
-//   ...
-//   Expected: not (in closed range (2, 4))
-//
-// Types of Matcher Parameters
-// ===========================
-//
-// For the purpose of typing, you can view
-//
-//   MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
-//
-// as shorthand for
-//
-//   template <typename p1_type, ..., typename pk_type>
-//   FooMatcherPk<p1_type, ..., pk_type>
-//   Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// When you write Foo(v1, ..., vk), the compiler infers the types of
-// the parameters v1, ..., and vk for you.  If you are not happy with
-// the result of the type inference, you can specify the types by
-// explicitly instantiating the template, as in Foo<long, bool>(5,
-// false).  As said earlier, you don't get to (or need to) specify
-// 'arg_type' as that's determined by the context in which the matcher
-// is used.  You can assign the result of expression Foo(p1, ..., pk)
-// to a variable of type FooMatcherPk<p1_type, ..., pk_type>.  This
-// can be useful when composing matchers.
-//
-// While you can instantiate a matcher template with reference types,
-// passing the parameters by pointer usually makes your code more
-// readable.  If, however, you still want to pass a parameter by
-// reference, be aware that in the failure message generated by the
-// matcher you will see the value of the referenced object but not its
-// address.
-//
-// Explaining Match Results
-// ========================
-//
-// Sometimes the matcher description alone isn't enough to explain why
-// the match has failed or succeeded.  For example, when expecting a
-// long string, it can be very helpful to also print the diff between
-// the expected string and the actual one.  To achieve that, you can
-// optionally stream additional information to a special variable
-// named result_listener, whose type is a pointer to class
-// MatchResultListener:
-//
-//   MATCHER_P(EqualsLongString, str, "") {
-//     if (arg == str) return true;
-//
-//     *result_listener << "the difference: "
-///                     << DiffStrings(str, arg);
-//     return false;
-//   }
-//
-// Overloading Matchers
-// ====================
-//
-// You can overload matchers with different numbers of parameters:
-//
-//   MATCHER_P(Blah, a, description_string1) { ... }
-//   MATCHER_P2(Blah, a, b, description_string2) { ... }
-//
-// Caveats
-// =======
-//
-// When defining a new matcher, you should also consider implementing
-// MatcherInterface or using MakePolymorphicMatcher().  These
-// approaches require more work than the MATCHER* macros, but also
-// give you more control on the types of the value being matched and
-// the matcher parameters, which may leads to better compiler error
-// messages when the matcher is used wrong.  They also allow
-// overloading matchers based on parameter types (as opposed to just
-// based on the number of parameters).
-//
-// MATCHER*() can only be used in a namespace scope.  The reason is
-// that C++ doesn't yet allow function-local types to be used to
-// instantiate templates.  The up-coming C++0x standard will fix this.
-// Once that's done, we'll consider supporting using MATCHER*() inside
-// a function.
-//
-// More Information
-// ================
-//
-// To learn more about using these macros, please search for 'MATCHER'
-// on http://code.google.com/p/googlemock/wiki/CookBook.
-
-#define MATCHER(name, description)\
-  class name##Matcher {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl()\
-           {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<>()));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>());\
-    }\
-    name##Matcher() {\
-    }\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##Matcher);\
-  };\
-  inline name##Matcher name() {\
-    return name##Matcher();\
-  }\
-  template <typename arg_type>\
-  bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P(name, p0, description)\
-  template <typename p0##_type>\
-  class name##MatcherP {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      explicit gmock_Impl(p0##_type gmock_p0)\
-           : p0(gmock_p0) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type>(p0)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0));\
-    }\
-    explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\
-    }\
-    p0##_type p0;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP);\
-  };\
-  template <typename p0##_type>\
-  inline name##MatcherP<p0##_type> name(p0##_type p0) {\
-    return name##MatcherP<p0##_type>(p0);\
-  }\
-  template <typename p0##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P2(name, p0, p1, description)\
-  template <typename p0##_type, typename p1##_type>\
-  class name##MatcherP2 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\
-           : p0(gmock_p0), p1(gmock_p1) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type>(p0, p1)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1));\
-    }\
-    name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \
-        p1(gmock_p1) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\
-  };\
-  template <typename p0##_type, typename p1##_type>\
-  inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \
-      p1##_type p1) {\
-    return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\
-  }\
-  template <typename p0##_type, typename p1##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP2<p0##_type, \
-      p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P3(name, p0, p1, p2, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type>\
-  class name##MatcherP3 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, \
-                    p2)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2));\
-    }\
-    name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type>\
-  inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
-      p1##_type p1, p2##_type p2) {\
-    return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP3<p0##_type, p1##_type, \
-      p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P4(name, p0, p1, p2, p3, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type>\
-  class name##MatcherP4 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, \
-                    p3##_type>(p0, p1, p2, p3)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3));\
-    }\
-    name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type>\
-  inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \
-      p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
-      p3##_type p3) {\
-    return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \
-        p1, p2, p3);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \
-      p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type>\
-  class name##MatcherP5 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
-               p4(gmock_p4) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
-                    p4##_type>(p0, p1, p2, p3, p4)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\
-    }\
-    name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, \
-        p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type>\
-  inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-      p4##_type p4) {\
-    return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type>(p0, p1, p2, p3, p4);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type>\
-  class name##MatcherP6 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
-               p4(gmock_p4), p5(gmock_p5) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
-                    p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\
-    }\
-    name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type>\
-  inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
-      p3##_type p3, p4##_type p4, p5##_type p5) {\
-    return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-      p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type>\
-  class name##MatcherP7 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
-               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
-                    p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \
-                    p6)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\
-    }\
-    name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \
-        p6(gmock_p6) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type>\
-  inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
-      p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
-      p6##_type p6) {\
-    return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-      p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type>\
-  class name##MatcherP8 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6, p7##_type gmock_p7)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
-               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-      p7##_type p7;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
-                    p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \
-                    p3, p4, p5, p6, p7)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\
-    }\
-    name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6, \
-        p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-        p7(gmock_p7) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-    p7##_type p7;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type>\
-  inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
-      p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
-      p6##_type p6, p7##_type p7) {\
-    return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
-        p6, p7);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-      p5##_type, p6##_type, \
-      p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type>\
-  class name##MatcherP9 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
-               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
-               p8(gmock_p8) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-      p7##_type p7;\
-      p8##_type p8;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
-                    p4##_type, p5##_type, p6##_type, p7##_type, \
-                    p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\
-    }\
-    name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
-        p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \
-        p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
-        p8(gmock_p8) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-    p7##_type p7;\
-    p8##_type p8;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type>\
-  inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type, \
-      p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \
-      p8##_type p8) {\
-    return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
-        p3, p4, p5, p6, p7, p8);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-      p5##_type, p6##_type, p7##_type, \
-      p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type, \
-      typename p9##_type>\
-  class name##MatcherP10 {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-          p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-          p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
-          p9##_type gmock_p9)\
-           : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \
-               p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \
-               p8(gmock_p8), p9(gmock_p9) {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\
-      p0##_type p0;\
-      p1##_type p1;\
-      p2##_type p2;\
-      p3##_type p3;\
-      p4##_type p4;\
-      p5##_type p5;\
-      p6##_type p6;\
-      p7##_type p7;\
-      p8##_type p8;\
-      p9##_type p9;\
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \
-                    p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
-                    p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\
-    }\
-    name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
-        p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \
-        p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \
-        p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\
-    }\
-    p0##_type p0;\
-    p1##_type p1;\
-    p2##_type p2;\
-    p3##_type p3;\
-    p4##_type p4;\
-    p5##_type p5;\
-    p6##_type p6;\
-    p7##_type p7;\
-    p8##_type p8;\
-    p9##_type p9;\
-   private:\
-    GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\
-  };\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type, \
-      typename p9##_type>\
-  inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
-      p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-      p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
-      p9##_type p9) {\
-    return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
-        p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
-        p1, p2, p3, p4, p5, p6, p7, p8, p9);\
-  }\
-  template <typename p0##_type, typename p1##_type, typename p2##_type, \
-      typename p3##_type, typename p4##_type, typename p5##_type, \
-      typename p6##_type, typename p7##_type, typename p8##_type, \
-      typename p9##_type>\
-  template <typename arg_type>\
-  bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
-      p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
-      p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-matchers.h.pump b/testing/gmock/include/gmock/gmock-generated-matchers.h.pump
deleted file mode 100644
index de30c2c..0000000
--- a/testing/gmock/include/gmock/gmock-generated-matchers.h.pump
+++ /dev/null
@@ -1,672 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file.  Please use Pump to convert it to
-$$ gmock-generated-actions.h.
-$$
-$var n = 10  $$ The maximum arity we support.
-$$ }} This line fixes auto-indentation of the following code in Emacs.
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used variadic matchers.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
-
-#include <iterator>
-#include <sstream>
-#include <string>
-#include <vector>
-#include "gmock/gmock-matchers.h"
-
-namespace testing {
-namespace internal {
-
-$range i 0..n-1
-
-// The type of the i-th (0-based) field of Tuple.
-#define GMOCK_FIELD_TYPE_(Tuple, i) \
-    typename ::testing::tuple_element<i, Tuple>::type
-
-// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
-// tuple of type Tuple.  It has two members:
-//
-//   type: a tuple type whose i-th field is the ki-th field of Tuple.
-//   GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple.
-//
-// For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have:
-//
-//   type is tuple<int, bool>, and
-//   GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true).
-
-template <class Tuple$for i [[, int k$i = -1]]>
-class TupleFields;
-
-// This generic version is used when there are $n selectors.
-template <class Tuple$for i [[, int k$i]]>
-class TupleFields {
- public:
-  typedef ::testing::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type;
-  static type GetSelectedFields(const Tuple& t) {
-    return type($for i, [[get<k$i>(t)]]);
-  }
-};
-
-// The following specialization is used for 0 ~ $(n-1) selectors.
-
-$for i [[
-$$ }}}
-$range j 0..i-1
-$range k 0..n-1
-
-template <class Tuple$for j [[, int k$j]]>
-class TupleFields<Tuple, $for k, [[$if k < i [[k$k]] $else [[-1]]]]> {
- public:
-  typedef ::testing::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type;
-  static type GetSelectedFields(const Tuple& $if i==0 [[/* t */]] $else [[t]]) {
-    return type($for j, [[get<k$j>(t)]]);
-  }
-};
-
-]]
-
-#undef GMOCK_FIELD_TYPE_
-
-// Implements the Args() matcher.
-
-$var ks = [[$for i, [[k$i]]]]
-template <class ArgsTuple$for i [[, int k$i = -1]]>
-class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
- public:
-  // ArgsTuple may have top-level const or reference modifiers.
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple;
-  typedef typename internal::TupleFields<RawArgsTuple, $ks>::type SelectedArgs;
-  typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher;
-
-  template <typename InnerMatcher>
-  explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)
-      : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}
-
-  virtual bool MatchAndExplain(ArgsTuple args,
-                               MatchResultListener* listener) const {
-    const SelectedArgs& selected_args = GetSelectedArgs(args);
-    if (!listener->IsInterested())
-      return inner_matcher_.Matches(selected_args);
-
-    PrintIndices(listener->stream());
-    *listener << "are " << PrintToString(selected_args);
-
-    StringMatchResultListener inner_listener;
-    const bool match = inner_matcher_.MatchAndExplain(selected_args,
-                                                      &inner_listener);
-    PrintIfNotEmpty(inner_listener.str(), listener->stream());
-    return match;
-  }
-
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "are a tuple ";
-    PrintIndices(os);
-    inner_matcher_.DescribeTo(os);
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "are a tuple ";
-    PrintIndices(os);
-    inner_matcher_.DescribeNegationTo(os);
-  }
-
- private:
-  static SelectedArgs GetSelectedArgs(ArgsTuple args) {
-    return TupleFields<RawArgsTuple, $ks>::GetSelectedFields(args);
-  }
-
-  // Prints the indices of the selected fields.
-  static void PrintIndices(::std::ostream* os) {
-    *os << "whose fields (";
-    const int indices[$n] = { $ks };
-    for (int i = 0; i < $n; i++) {
-      if (indices[i] < 0)
-        break;
-
-      if (i >= 1)
-        *os << ", ";
-
-      *os << "#" << indices[i];
-    }
-    *os << ") ";
-  }
-
-  const MonomorphicInnerMatcher inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl);
-};
-
-template <class InnerMatcher$for i [[, int k$i = -1]]>
-class ArgsMatcher {
- public:
-  explicit ArgsMatcher(const InnerMatcher& inner_matcher)
-      : inner_matcher_(inner_matcher) {}
-
-  template <typename ArgsTuple>
-  operator Matcher<ArgsTuple>() const {
-    return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, $ks>(inner_matcher_));
-  }
-
- private:
-  const InnerMatcher inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(ArgsMatcher);
-};
-
-// A set of metafunctions for computing the result type of AllOf.
-// AllOf(m1, ..., mN) returns
-// AllOfResultN<decltype(m1), ..., decltype(mN)>::type.
-
-// Although AllOf isn't defined for one argument, AllOfResult1 is defined
-// to simplify the implementation.
-template <typename M1>
-struct AllOfResult1 {
-  typedef M1 type;
-};
-
-$range i 1..n
-
-$range i 2..n
-$for i [[
-$range j 2..i
-$var m = i/2
-$range k 1..m
-$range t m+1..i
-
-template <typename M1$for j [[, typename M$j]]>
-struct AllOfResult$i {
-  typedef BothOfMatcher<
-      typename AllOfResult$m<$for k, [[M$k]]>::type,
-      typename AllOfResult$(i-m)<$for t, [[M$t]]>::type
-  > type;
-};
-
-]]
-
-// A set of metafunctions for computing the result type of AnyOf.
-// AnyOf(m1, ..., mN) returns
-// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type.
-
-// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined
-// to simplify the implementation.
-template <typename M1>
-struct AnyOfResult1 {
-  typedef M1 type;
-};
-
-$range i 1..n
-
-$range i 2..n
-$for i [[
-$range j 2..i
-$var m = i/2
-$range k 1..m
-$range t m+1..i
-
-template <typename M1$for j [[, typename M$j]]>
-struct AnyOfResult$i {
-  typedef EitherOfMatcher<
-      typename AnyOfResult$m<$for k, [[M$k]]>::type,
-      typename AnyOfResult$(i-m)<$for t, [[M$t]]>::type
-  > type;
-};
-
-]]
-
-}  // namespace internal
-
-// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
-// fields of it matches a_matcher.  C++ doesn't support default
-// arguments for function templates, so we have to overload it.
-
-$range i 0..n
-$for i [[
-$range j 1..i
-template <$for j [[int k$j, ]]typename InnerMatcher>
-inline internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>
-Args(const InnerMatcher& matcher) {
-  return internal::ArgsMatcher<InnerMatcher$for j [[, k$j]]>(matcher);
-}
-
-
-]]
-// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with
-// n elements, where the i-th element in the container must
-// match the i-th argument in the list.  Each argument of
-// ElementsAre() can be either a value or a matcher.  We support up to
-// $n arguments.
-//
-// The use of DecayArray in the implementation allows ElementsAre()
-// to accept string literals, whose type is const char[N], but we
-// want to treat them as const char*.
-//
-// NOTE: Since ElementsAre() cares about the order of the elements, it
-// must not be used with containers whose elements's order is
-// undefined (e.g. hash_map).
-
-$range i 0..n
-$for i [[
-
-$range j 1..i
-
-$if i>0 [[
-
-template <$for j, [[typename T$j]]>
-]]
-
-inline internal::ElementsAreMatcher<
-    ::testing::tuple<
-$for j, [[
-
-        typename internal::DecayArray<T$j[[]]>::type]]> >
-ElementsAre($for j, [[const T$j& e$j]]) {
-  typedef ::testing::tuple<
-$for j, [[
-
-      typename internal::DecayArray<T$j[[]]>::type]]> Args;
-  return internal::ElementsAreMatcher<Args>(Args($for j, [[e$j]]));
-}
-
-]]
-
-// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension
-// that matches n elements in any order.  We support up to n=$n arguments.
-
-$range i 0..n
-$for i [[
-
-$range j 1..i
-
-$if i>0 [[
-
-template <$for j, [[typename T$j]]>
-]]
-
-inline internal::UnorderedElementsAreMatcher<
-    ::testing::tuple<
-$for j, [[
-
-        typename internal::DecayArray<T$j[[]]>::type]]> >
-UnorderedElementsAre($for j, [[const T$j& e$j]]) {
-  typedef ::testing::tuple<
-$for j, [[
-
-      typename internal::DecayArray<T$j[[]]>::type]]> Args;
-  return internal::UnorderedElementsAreMatcher<Args>(Args($for j, [[e$j]]));
-}
-
-]]
-
-// AllOf(m1, m2, ..., mk) matches any value that matches all of the given
-// sub-matchers.  AllOf is called fully qualified to prevent ADL from firing.
-
-$range i 2..n
-$for i [[
-$range j 1..i
-$var m = i/2
-$range k 1..m
-$range t m+1..i
-
-template <$for j, [[typename M$j]]>
-inline typename internal::AllOfResult$i<$for j, [[M$j]]>::type
-AllOf($for j, [[M$j m$j]]) {
-  return typename internal::AllOfResult$i<$for j, [[M$j]]>::type(
-      $if m == 1 [[m1]] $else [[::testing::AllOf($for k, [[m$k]])]],
-      $if m+1 == i [[m$i]] $else [[::testing::AllOf($for t, [[m$t]])]]);
-}
-
-]]
-
-// AnyOf(m1, m2, ..., mk) matches any value that matches any of the given
-// sub-matchers.  AnyOf is called fully qualified to prevent ADL from firing.
-
-$range i 2..n
-$for i [[
-$range j 1..i
-$var m = i/2
-$range k 1..m
-$range t m+1..i
-
-template <$for j, [[typename M$j]]>
-inline typename internal::AnyOfResult$i<$for j, [[M$j]]>::type
-AnyOf($for j, [[M$j m$j]]) {
-  return typename internal::AnyOfResult$i<$for j, [[M$j]]>::type(
-      $if m == 1 [[m1]] $else [[::testing::AnyOf($for k, [[m$k]])]],
-      $if m+1 == i [[m$i]] $else [[::testing::AnyOf($for t, [[m$t]])]]);
-}
-
-]]
-
-}  // namespace testing
-$$ } // This Pump meta comment fixes auto-indentation in Emacs. It will not
-$$   // show up in the generated code.
-
-
-// The MATCHER* family of macros can be used in a namespace scope to
-// define custom matchers easily.
-//
-// Basic Usage
-// ===========
-//
-// The syntax
-//
-//   MATCHER(name, description_string) { statements; }
-//
-// defines a matcher with the given name that executes the statements,
-// which must return a bool to indicate if the match succeeds.  Inside
-// the statements, you can refer to the value being matched by 'arg',
-// and refer to its type by 'arg_type'.
-//
-// The description string documents what the matcher does, and is used
-// to generate the failure message when the match fails.  Since a
-// MATCHER() is usually defined in a header file shared by multiple
-// C++ source files, we require the description to be a C-string
-// literal to avoid possible side effects.  It can be empty, in which
-// case we'll use the sequence of words in the matcher name as the
-// description.
-//
-// For example:
-//
-//   MATCHER(IsEven, "") { return (arg % 2) == 0; }
-//
-// allows you to write
-//
-//   // Expects mock_foo.Bar(n) to be called where n is even.
-//   EXPECT_CALL(mock_foo, Bar(IsEven()));
-//
-// or,
-//
-//   // Verifies that the value of some_expression is even.
-//   EXPECT_THAT(some_expression, IsEven());
-//
-// If the above assertion fails, it will print something like:
-//
-//   Value of: some_expression
-//   Expected: is even
-//     Actual: 7
-//
-// where the description "is even" is automatically calculated from the
-// matcher name IsEven.
-//
-// Argument Type
-// =============
-//
-// Note that the type of the value being matched (arg_type) is
-// determined by the context in which you use the matcher and is
-// supplied to you by the compiler, so you don't need to worry about
-// declaring it (nor can you).  This allows the matcher to be
-// polymorphic.  For example, IsEven() can be used to match any type
-// where the value of "(arg % 2) == 0" can be implicitly converted to
-// a bool.  In the "Bar(IsEven())" example above, if method Bar()
-// takes an int, 'arg_type' will be int; if it takes an unsigned long,
-// 'arg_type' will be unsigned long; and so on.
-//
-// Parameterizing Matchers
-// =======================
-//
-// Sometimes you'll want to parameterize the matcher.  For that you
-// can use another macro:
-//
-//   MATCHER_P(name, param_name, description_string) { statements; }
-//
-// For example:
-//
-//   MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
-//
-// will allow you to write:
-//
-//   EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
-//
-// which may lead to this message (assuming n is 10):
-//
-//   Value of: Blah("a")
-//   Expected: has absolute value 10
-//     Actual: -9
-//
-// Note that both the matcher description and its parameter are
-// printed, making the message human-friendly.
-//
-// In the matcher definition body, you can write 'foo_type' to
-// reference the type of a parameter named 'foo'.  For example, in the
-// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
-// 'value_type' to refer to the type of 'value'.
-//
-// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
-// support multi-parameter matchers.
-//
-// Describing Parameterized Matchers
-// =================================
-//
-// The last argument to MATCHER*() is a string-typed expression.  The
-// expression can reference all of the matcher's parameters and a
-// special bool-typed variable named 'negation'.  When 'negation' is
-// false, the expression should evaluate to the matcher's description;
-// otherwise it should evaluate to the description of the negation of
-// the matcher.  For example,
-//
-//   using testing::PrintToString;
-//
-//   MATCHER_P2(InClosedRange, low, hi,
-//       string(negation ? "is not" : "is") + " in range [" +
-//       PrintToString(low) + ", " + PrintToString(hi) + "]") {
-//     return low <= arg && arg <= hi;
-//   }
-//   ...
-//   EXPECT_THAT(3, InClosedRange(4, 6));
-//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-//   Expected: is in range [4, 6]
-//   ...
-//   Expected: is not in range [2, 4]
-//
-// If you specify "" as the description, the failure message will
-// contain the sequence of words in the matcher name followed by the
-// parameter values printed as a tuple.  For example,
-//
-//   MATCHER_P2(InClosedRange, low, hi, "") { ... }
-//   ...
-//   EXPECT_THAT(3, InClosedRange(4, 6));
-//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));
-//
-// would generate two failures that contain the text:
-//
-//   Expected: in closed range (4, 6)
-//   ...
-//   Expected: not (in closed range (2, 4))
-//
-// Types of Matcher Parameters
-// ===========================
-//
-// For the purpose of typing, you can view
-//
-//   MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
-//
-// as shorthand for
-//
-//   template <typename p1_type, ..., typename pk_type>
-//   FooMatcherPk<p1_type, ..., pk_type>
-//   Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// When you write Foo(v1, ..., vk), the compiler infers the types of
-// the parameters v1, ..., and vk for you.  If you are not happy with
-// the result of the type inference, you can specify the types by
-// explicitly instantiating the template, as in Foo<long, bool>(5,
-// false).  As said earlier, you don't get to (or need to) specify
-// 'arg_type' as that's determined by the context in which the matcher
-// is used.  You can assign the result of expression Foo(p1, ..., pk)
-// to a variable of type FooMatcherPk<p1_type, ..., pk_type>.  This
-// can be useful when composing matchers.
-//
-// While you can instantiate a matcher template with reference types,
-// passing the parameters by pointer usually makes your code more
-// readable.  If, however, you still want to pass a parameter by
-// reference, be aware that in the failure message generated by the
-// matcher you will see the value of the referenced object but not its
-// address.
-//
-// Explaining Match Results
-// ========================
-//
-// Sometimes the matcher description alone isn't enough to explain why
-// the match has failed or succeeded.  For example, when expecting a
-// long string, it can be very helpful to also print the diff between
-// the expected string and the actual one.  To achieve that, you can
-// optionally stream additional information to a special variable
-// named result_listener, whose type is a pointer to class
-// MatchResultListener:
-//
-//   MATCHER_P(EqualsLongString, str, "") {
-//     if (arg == str) return true;
-//
-//     *result_listener << "the difference: "
-///                     << DiffStrings(str, arg);
-//     return false;
-//   }
-//
-// Overloading Matchers
-// ====================
-//
-// You can overload matchers with different numbers of parameters:
-//
-//   MATCHER_P(Blah, a, description_string1) { ... }
-//   MATCHER_P2(Blah, a, b, description_string2) { ... }
-//
-// Caveats
-// =======
-//
-// When defining a new matcher, you should also consider implementing
-// MatcherInterface or using MakePolymorphicMatcher().  These
-// approaches require more work than the MATCHER* macros, but also
-// give you more control on the types of the value being matched and
-// the matcher parameters, which may leads to better compiler error
-// messages when the matcher is used wrong.  They also allow
-// overloading matchers based on parameter types (as opposed to just
-// based on the number of parameters).
-//
-// MATCHER*() can only be used in a namespace scope.  The reason is
-// that C++ doesn't yet allow function-local types to be used to
-// instantiate templates.  The up-coming C++0x standard will fix this.
-// Once that's done, we'll consider supporting using MATCHER*() inside
-// a function.
-//
-// More Information
-// ================
-//
-// To learn more about using these macros, please search for 'MATCHER'
-// on http://code.google.com/p/googlemock/wiki/CookBook.
-
-$range i 0..n
-$for i
-
-[[
-$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
-                                         $else [[MATCHER_P$i]]]]
-$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
-                                                 $else [[P$i]]]]]]
-$range j 0..i-1
-$var template = [[$if i==0 [[]] $else [[
-
-  template <$for j, [[typename p$j##_type]]>\
-]]]]
-$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
-$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
-$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
-$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
-$var params = [[$for j, [[p$j]]]]
-$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
-$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
-$var param_field_decls = [[$for j
-[[
-
-      p$j##_type p$j;\
-]]]]
-$var param_field_decls2 = [[$for j
-[[
-
-    p$j##_type p$j;\
-]]]]
-
-#define $macro_name(name$for j [[, p$j]], description)\$template
-  class $class_name {\
-   public:\
-    template <typename arg_type>\
-    class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
-     public:\
-      [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
-          $impl_inits {}\
-      virtual bool MatchAndExplain(\
-          arg_type arg, ::testing::MatchResultListener* result_listener) const;\
-      virtual void DescribeTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(false);\
-      }\
-      virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
-        *gmock_os << FormatDescription(true);\
-      }\$param_field_decls
-     private:\
-      ::testing::internal::string FormatDescription(bool negation) const {\
-        const ::testing::internal::string gmock_description = (description);\
-        if (!gmock_description.empty())\
-          return gmock_description;\
-        return ::testing::internal::FormatMatcherDescription(\
-            negation, #name, \
-            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
-                ::testing::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
-      }\
-      GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
-    };\
-    template <typename arg_type>\
-    operator ::testing::Matcher<arg_type>() const {\
-      return ::testing::Matcher<arg_type>(\
-          new gmock_Impl<arg_type>($params));\
-    }\
-    [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
-    }\$param_field_decls2
-   private:\
-    GTEST_DISALLOW_ASSIGN_($class_name);\
-  };\$template
-  inline $class_name$param_types name($param_types_and_names) {\
-    return $class_name$param_types($params);\
-  }\$template
-  template <typename arg_type>\
-  bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
-      arg_type arg, \
-      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
-          const
-]]
-
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-nice-strict.h b/testing/gmock/include/gmock/gmock-generated-nice-strict.h
deleted file mode 100644
index 4095f4d..0000000
--- a/testing/gmock/include/gmock/gmock-generated-nice-strict.h
+++ /dev/null
@@ -1,397 +0,0 @@
-// This file was GENERATED by command:
-//     pump.py gmock-generated-nice-strict.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Implements class templates NiceMock, NaggyMock, and StrictMock.
-//
-// Given a mock class MockFoo that is created using Google Mock,
-// NiceMock<MockFoo> is a subclass of MockFoo that allows
-// uninteresting calls (i.e. calls to mock methods that have no
-// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
-// that prints a warning when an uninteresting call occurs, and
-// StrictMock<MockFoo> is a subclass of MockFoo that treats all
-// uninteresting calls as errors.
-//
-// Currently a mock is naggy by default, so MockFoo and
-// NaggyMock<MockFoo> behave like the same.  However, we will soon
-// switch the default behavior of mocks to be nice, as that in general
-// leads to more maintainable tests.  When that happens, MockFoo will
-// stop behaving like NaggyMock<MockFoo> and start behaving like
-// NiceMock<MockFoo>.
-//
-// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
-// their respective base class, with up-to 10 arguments.  Therefore
-// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock
-// where MockFoo has a constructor that accepts (int, const char*),
-// for example.
-//
-// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
-// and StrictMock<MockFoo> only works for mock methods defined using
-// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
-// If a mock method is defined in a base class of MockFoo, the "nice"
-// or "strict" modifier may not affect it, depending on the compiler.
-// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
-// supported.
-//
-// Another known limitation is that the constructors of the base mock
-// cannot have arguments passed by non-const reference, which are
-// banned by the Google C++ style guide anyway.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
-
-#include "gmock/gmock-spec-builders.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-
-template <class MockClass>
-class NiceMock : public MockClass {
- public:
-  // We don't factor out the constructor body to a common method, as
-  // we have to avoid a possible clash with members of MockClass.
-  NiceMock() {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  // C++ doesn't (yet) allow inheritance of constructors, so we have
-  // to define it for each arity.
-  template <typename A1>
-  explicit NiceMock(const A1& a1) : MockClass(a1) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-  template <typename A1, typename A2>
-  NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3,
-      const A4& a4) : MockClass(a1, a2, a3, a4) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
-      a6, a7) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
-      a2, a3, a4, a5, a6, a7, a8) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8, typename A9>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8,
-      const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8, typename A9, typename A10>
-  NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
-      const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
-    ::testing::Mock::AllowUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  virtual ~NiceMock() {
-    ::testing::Mock::UnregisterCallReaction(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
-};
-
-template <class MockClass>
-class NaggyMock : public MockClass {
- public:
-  // We don't factor out the constructor body to a common method, as
-  // we have to avoid a possible clash with members of MockClass.
-  NaggyMock() {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  // C++ doesn't (yet) allow inheritance of constructors, so we have
-  // to define it for each arity.
-  template <typename A1>
-  explicit NaggyMock(const A1& a1) : MockClass(a1) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-  template <typename A1, typename A2>
-  NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3,
-      const A4& a4) : MockClass(a1, a2, a3, a4) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
-      a6, a7) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
-      a2, a3, a4, a5, a6, a7, a8) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8, typename A9>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8,
-      const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8, typename A9, typename A10>
-  NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
-      const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
-    ::testing::Mock::WarnUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  virtual ~NaggyMock() {
-    ::testing::Mock::UnregisterCallReaction(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
-};
-
-template <class MockClass>
-class StrictMock : public MockClass {
- public:
-  // We don't factor out the constructor body to a common method, as
-  // we have to avoid a possible clash with members of MockClass.
-  StrictMock() {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  // C++ doesn't (yet) allow inheritance of constructors, so we have
-  // to define it for each arity.
-  template <typename A1>
-  explicit StrictMock(const A1& a1) : MockClass(a1) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-  template <typename A1, typename A2>
-  StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3,
-      const A4& a4) : MockClass(a1, a2, a3, a4) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
-      a6, a7) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
-      a2, a3, a4, a5, a6, a7, a8) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8, typename A9>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8,
-      const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  template <typename A1, typename A2, typename A3, typename A4, typename A5,
-      typename A6, typename A7, typename A8, typename A9, typename A10>
-  StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
-      const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
-      const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
-    ::testing::Mock::FailUninterestingCalls(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  virtual ~StrictMock() {
-    ::testing::Mock::UnregisterCallReaction(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
-};
-
-// The following specializations catch some (relatively more common)
-// user errors of nesting nice and strict mocks.  They do NOT catch
-// all possible errors.
-
-// These specializations are declared but not defined, as NiceMock,
-// NaggyMock, and StrictMock cannot be nested.
-
-template <typename MockClass>
-class NiceMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class NaggyMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class StrictMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<StrictMock<MockClass> >;
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
diff --git a/testing/gmock/include/gmock/gmock-generated-nice-strict.h.pump b/testing/gmock/include/gmock/gmock-generated-nice-strict.h.pump
deleted file mode 100644
index 3ee1ce7..0000000
--- a/testing/gmock/include/gmock/gmock-generated-nice-strict.h.pump
+++ /dev/null
@@ -1,161 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file.  Please use Pump to convert it to
-$$ gmock-generated-nice-strict.h.
-$$
-$var n = 10  $$ The maximum arity we support.
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Implements class templates NiceMock, NaggyMock, and StrictMock.
-//
-// Given a mock class MockFoo that is created using Google Mock,
-// NiceMock<MockFoo> is a subclass of MockFoo that allows
-// uninteresting calls (i.e. calls to mock methods that have no
-// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
-// that prints a warning when an uninteresting call occurs, and
-// StrictMock<MockFoo> is a subclass of MockFoo that treats all
-// uninteresting calls as errors.
-//
-// Currently a mock is naggy by default, so MockFoo and
-// NaggyMock<MockFoo> behave like the same.  However, we will soon
-// switch the default behavior of mocks to be nice, as that in general
-// leads to more maintainable tests.  When that happens, MockFoo will
-// stop behaving like NaggyMock<MockFoo> and start behaving like
-// NiceMock<MockFoo>.
-//
-// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
-// their respective base class, with up-to $n arguments.  Therefore
-// you can write NiceMock<MockFoo>(5, "a") to construct a nice mock
-// where MockFoo has a constructor that accepts (int, const char*),
-// for example.
-//
-// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
-// and StrictMock<MockFoo> only works for mock methods defined using
-// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
-// If a mock method is defined in a base class of MockFoo, the "nice"
-// or "strict" modifier may not affect it, depending on the compiler.
-// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
-// supported.
-//
-// Another known limitation is that the constructors of the base mock
-// cannot have arguments passed by non-const reference, which are
-// banned by the Google C++ style guide anyway.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
-
-#include "gmock/gmock-spec-builders.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-
-$range kind 0..2
-$for kind [[
-
-$var clazz=[[$if kind==0 [[NiceMock]]
-             $elif kind==1 [[NaggyMock]]
-             $else [[StrictMock]]]]
-
-$var method=[[$if kind==0 [[AllowUninterestingCalls]]
-             $elif kind==1 [[WarnUninterestingCalls]]
-             $else [[FailUninterestingCalls]]]]
-
-template <class MockClass>
-class $clazz : public MockClass {
- public:
-  // We don't factor out the constructor body to a common method, as
-  // we have to avoid a possible clash with members of MockClass.
-  $clazz() {
-    ::testing::Mock::$method(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-  // C++ doesn't (yet) allow inheritance of constructors, so we have
-  // to define it for each arity.
-  template <typename A1>
-  explicit $clazz(const A1& a1) : MockClass(a1) {
-    ::testing::Mock::$method(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-$range i 2..n
-$for i [[
-$range j 1..i
-  template <$for j, [[typename A$j]]>
-  $clazz($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) {
-    ::testing::Mock::$method(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
-
-]]
-  virtual ~$clazz() {
-    ::testing::Mock::UnregisterCallReaction(
-        internal::ImplicitCast_<MockClass*>(this));
-  }
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_($clazz);
-};
-
-]]
-
-// The following specializations catch some (relatively more common)
-// user errors of nesting nice and strict mocks.  They do NOT catch
-// all possible errors.
-
-// These specializations are declared but not defined, as NiceMock,
-// NaggyMock, and StrictMock cannot be nested.
-
-template <typename MockClass>
-class NiceMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class NaggyMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class StrictMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<StrictMock<MockClass> >;
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
diff --git a/testing/gmock/include/gmock/gmock-matchers.h b/testing/gmock/include/gmock/gmock-matchers.h
index 33b37a7..6db65f2 100644
--- a/testing/gmock/include/gmock/gmock-matchers.h
+++ b/testing/gmock/include/gmock/gmock-matchers.h
@@ -1,4399 +1,15 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
+// Copyright 2017 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
 
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some commonly used argument matchers.  More
-// matchers can be defined by the user implementing the
-// MatcherInterface<T> interface if necessary.
+#ifndef TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#define TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
 
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+// The file/directory layout of Google Test is not yet considered stable. Until
+// it stabilizes, Chromium code will use forwarding headers in testing/gtest
+// and testing/gmock, instead of directly including files in
+// third_party/googletest.
 
-#include <math.h>
-#include <algorithm>
-#include <iterator>
-#include <limits>
-#include <ostream>  // NOLINT
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
+#include "third_party/googletest/src/googlemock/include/gmock/gmock-matchers.h"
 
-#include "gmock/internal/gmock-internal-utils.h"
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-# include <initializer_list>  // NOLINT -- must be after gtest.h
-#endif
-
-namespace testing {
-
-// To implement a matcher Foo for type T, define:
-//   1. a class FooMatcherImpl that implements the
-//      MatcherInterface<T> interface, and
-//   2. a factory function that creates a Matcher<T> object from a
-//      FooMatcherImpl*.
-//
-// The two-level delegation design makes it possible to allow a user
-// to write "v" instead of "Eq(v)" where a Matcher is expected, which
-// is impossible if we pass matchers by pointers.  It also eases
-// ownership management as Matcher objects can now be copied like
-// plain values.
-
-// MatchResultListener is an abstract class.  Its << operator can be
-// used by a matcher to explain why a value matches or doesn't match.
-//
-// TODO(wan@google.com): add method
-//   bool InterestedInWhy(bool result) const;
-// to indicate whether the listener is interested in why the match
-// result is 'result'.
-class MatchResultListener {
- public:
-  // Creates a listener object with the given underlying ostream.  The
-  // listener does not own the ostream, and does not dereference it
-  // in the constructor or destructor.
-  explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
-  virtual ~MatchResultListener() = 0;  // Makes this class abstract.
-
-  // Streams x to the underlying ostream; does nothing if the ostream
-  // is NULL.
-  template <typename T>
-  MatchResultListener& operator<<(const T& x) {
-    if (stream_ != NULL)
-      *stream_ << x;
-    return *this;
-  }
-
-  // Returns the underlying ostream.
-  ::std::ostream* stream() { return stream_; }
-
-  // Returns true iff the listener is interested in an explanation of
-  // the match result.  A matcher's MatchAndExplain() method can use
-  // this information to avoid generating the explanation when no one
-  // intends to hear it.
-  bool IsInterested() const { return stream_ != NULL; }
-
- private:
-  ::std::ostream* const stream_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
-};
-
-inline MatchResultListener::~MatchResultListener() {
-}
-
-// An instance of a subclass of this knows how to describe itself as a
-// matcher.
-class MatcherDescriberInterface {
- public:
-  virtual ~MatcherDescriberInterface() {}
-
-  // Describes this matcher to an ostream.  The function should print
-  // a verb phrase that describes the property a value matching this
-  // matcher should have.  The subject of the verb phrase is the value
-  // being matched.  For example, the DescribeTo() method of the Gt(7)
-  // matcher prints "is greater than 7".
-  virtual void DescribeTo(::std::ostream* os) const = 0;
-
-  // Describes the negation of this matcher to an ostream.  For
-  // example, if the description of this matcher is "is greater than
-  // 7", the negated description could be "is not greater than 7".
-  // You are not required to override this when implementing
-  // MatcherInterface, but it is highly advised so that your matcher
-  // can produce good error messages.
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "not (";
-    DescribeTo(os);
-    *os << ")";
-  }
-};
-
-// The implementation of a matcher.
-template <typename T>
-class MatcherInterface : public MatcherDescriberInterface {
- public:
-  // Returns true iff the matcher matches x; also explains the match
-  // result to 'listener' if necessary (see the next paragraph), in
-  // the form of a non-restrictive relative clause ("which ...",
-  // "whose ...", etc) that describes x.  For example, the
-  // MatchAndExplain() method of the Pointee(...) matcher should
-  // generate an explanation like "which points to ...".
-  //
-  // Implementations of MatchAndExplain() should add an explanation of
-  // the match result *if and only if* they can provide additional
-  // information that's not already present (or not obvious) in the
-  // print-out of x and the matcher's description.  Whether the match
-  // succeeds is not a factor in deciding whether an explanation is
-  // needed, as sometimes the caller needs to print a failure message
-  // when the match succeeds (e.g. when the matcher is used inside
-  // Not()).
-  //
-  // For example, a "has at least 10 elements" matcher should explain
-  // what the actual element count is, regardless of the match result,
-  // as it is useful information to the reader; on the other hand, an
-  // "is empty" matcher probably only needs to explain what the actual
-  // size is when the match fails, as it's redundant to say that the
-  // size is 0 when the value is already known to be empty.
-  //
-  // You should override this method when defining a new matcher.
-  //
-  // It's the responsibility of the caller (Google Mock) to guarantee
-  // that 'listener' is not NULL.  This helps to simplify a matcher's
-  // implementation when it doesn't care about the performance, as it
-  // can talk to 'listener' without checking its validity first.
-  // However, in order to implement dummy listeners efficiently,
-  // listener->stream() may be NULL.
-  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
-
-  // Inherits these methods from MatcherDescriberInterface:
-  //   virtual void DescribeTo(::std::ostream* os) const = 0;
-  //   virtual void DescribeNegationTo(::std::ostream* os) const;
-};
-
-// A match result listener that stores the explanation in a string.
-class StringMatchResultListener : public MatchResultListener {
- public:
-  StringMatchResultListener() : MatchResultListener(&ss_) {}
-
-  // Returns the explanation accumulated so far.
-  internal::string str() const { return ss_.str(); }
-
-  // Clears the explanation accumulated so far.
-  void Clear() { ss_.str(""); }
-
- private:
-  ::std::stringstream ss_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
-};
-
-namespace internal {
-
-struct AnyEq {
-  template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a == b; }
-};
-struct AnyNe {
-  template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a != b; }
-};
-struct AnyLt {
-  template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a < b; }
-};
-struct AnyGt {
-  template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a > b; }
-};
-struct AnyLe {
-  template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a <= b; }
-};
-struct AnyGe {
-  template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a >= b; }
-};
-
-// A match result listener that ignores the explanation.
-class DummyMatchResultListener : public MatchResultListener {
- public:
-  DummyMatchResultListener() : MatchResultListener(NULL) {}
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
-};
-
-// A match result listener that forwards the explanation to a given
-// ostream.  The difference between this and MatchResultListener is
-// that the former is concrete.
-class StreamMatchResultListener : public MatchResultListener {
- public:
-  explicit StreamMatchResultListener(::std::ostream* os)
-      : MatchResultListener(os) {}
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
-};
-
-// An internal class for implementing Matcher<T>, which will derive
-// from it.  We put functionalities common to all Matcher<T>
-// specializations here to avoid code duplication.
-template <typename T>
-class MatcherBase {
- public:
-  // Returns true iff the matcher matches x; also explains the match
-  // result to 'listener'.
-  bool MatchAndExplain(T x, MatchResultListener* listener) const {
-    return impl_->MatchAndExplain(x, listener);
-  }
-
-  // Returns true iff this matcher matches x.
-  bool Matches(T x) const {
-    DummyMatchResultListener dummy;
-    return MatchAndExplain(x, &dummy);
-  }
-
-  // Describes this matcher to an ostream.
-  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
-
-  // Describes the negation of this matcher to an ostream.
-  void DescribeNegationTo(::std::ostream* os) const {
-    impl_->DescribeNegationTo(os);
-  }
-
-  // Explains why x matches, or doesn't match, the matcher.
-  void ExplainMatchResultTo(T x, ::std::ostream* os) const {
-    StreamMatchResultListener listener(os);
-    MatchAndExplain(x, &listener);
-  }
-
-  // Returns the describer for this matcher object; retains ownership
-  // of the describer, which is only guaranteed to be alive when
-  // this matcher object is alive.
-  const MatcherDescriberInterface* GetDescriber() const {
-    return impl_.get();
-  }
-
- protected:
-  MatcherBase() {}
-
-  // Constructs a matcher from its implementation.
-  explicit MatcherBase(const MatcherInterface<T>* impl)
-      : impl_(impl) {}
-
-  virtual ~MatcherBase() {}
-
- private:
-  // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
-  // interfaces.  The former dynamically allocates a chunk of memory
-  // to hold the reference count, while the latter tracks all
-  // references using a circular linked list without allocating
-  // memory.  It has been observed that linked_ptr performs better in
-  // typical scenarios.  However, shared_ptr can out-perform
-  // linked_ptr when there are many more uses of the copy constructor
-  // than the default constructor.
-  //
-  // If performance becomes a problem, we should see if using
-  // shared_ptr helps.
-  ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
-};
-
-}  // namespace internal
-
-// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
-// object that can check whether a value of type T matches.  The
-// implementation of Matcher<T> is just a linked_ptr to const
-// MatcherInterface<T>, so copying is fairly cheap.  Don't inherit
-// from Matcher!
-template <typename T>
-class Matcher : public internal::MatcherBase<T> {
- public:
-  // Constructs a null matcher.  Needed for storing Matcher objects in STL
-  // containers.  A default-constructed matcher is not yet initialized.  You
-  // cannot use it until a valid value has been assigned to it.
-  explicit Matcher() {}  // NOLINT
-
-  // Constructs a matcher from its implementation.
-  explicit Matcher(const MatcherInterface<T>* impl)
-      : internal::MatcherBase<T>(impl) {}
-
-  // Implicit constructor here allows people to write
-  // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
-  Matcher(T value);  // NOLINT
-};
-
-// The following two specializations allow the user to write str
-// instead of Eq(str) and "foo" instead of Eq("foo") when a string
-// matcher is expected.
-template <>
-class GTEST_API_ Matcher<const internal::string&>
-    : public internal::MatcherBase<const internal::string&> {
- public:
-  Matcher() {}
-
-  explicit Matcher(const MatcherInterface<const internal::string&>* impl)
-      : internal::MatcherBase<const internal::string&>(impl) {}
-
-  // Allows the user to write str instead of Eq(str) sometimes, where
-  // str is a string object.
-  Matcher(const internal::string& s);  // NOLINT
-
-  // Allows the user to write "foo" instead of Eq("foo") sometimes.
-  Matcher(const char* s);  // NOLINT
-};
-
-template <>
-class GTEST_API_ Matcher<internal::string>
-    : public internal::MatcherBase<internal::string> {
- public:
-  Matcher() {}
-
-  explicit Matcher(const MatcherInterface<internal::string>* impl)
-      : internal::MatcherBase<internal::string>(impl) {}
-
-  // Allows the user to write str instead of Eq(str) sometimes, where
-  // str is a string object.
-  Matcher(const internal::string& s);  // NOLINT
-
-  // Allows the user to write "foo" instead of Eq("foo") sometimes.
-  Matcher(const char* s);  // NOLINT
-};
-
-#if GTEST_HAS_STRING_PIECE_
-// The following two specializations allow the user to write str
-// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
-// matcher is expected.
-template <>
-class GTEST_API_ Matcher<const StringPiece&>
-    : public internal::MatcherBase<const StringPiece&> {
- public:
-  Matcher() {}
-
-  explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
-      : internal::MatcherBase<const StringPiece&>(impl) {}
-
-  // Allows the user to write str instead of Eq(str) sometimes, where
-  // str is a string object.
-  Matcher(const internal::string& s);  // NOLINT
-
-  // Allows the user to write "foo" instead of Eq("foo") sometimes.
-  Matcher(const char* s);  // NOLINT
-
-  // Allows the user to pass StringPieces directly.
-  Matcher(StringPiece s);  // NOLINT
-};
-
-template <>
-class GTEST_API_ Matcher<StringPiece>
-    : public internal::MatcherBase<StringPiece> {
- public:
-  Matcher() {}
-
-  explicit Matcher(const MatcherInterface<StringPiece>* impl)
-      : internal::MatcherBase<StringPiece>(impl) {}
-
-  // Allows the user to write str instead of Eq(str) sometimes, where
-  // str is a string object.
-  Matcher(const internal::string& s);  // NOLINT
-
-  // Allows the user to write "foo" instead of Eq("foo") sometimes.
-  Matcher(const char* s);  // NOLINT
-
-  // Allows the user to pass StringPieces directly.
-  Matcher(StringPiece s);  // NOLINT
-};
-#endif  // GTEST_HAS_STRING_PIECE_
-
-// The PolymorphicMatcher class template makes it easy to implement a
-// polymorphic matcher (i.e. a matcher that can match values of more
-// than one type, e.g. Eq(n) and NotNull()).
-//
-// To define a polymorphic matcher, a user should provide an Impl
-// class that has a DescribeTo() method and a DescribeNegationTo()
-// method, and define a member function (or member function template)
-//
-//   bool MatchAndExplain(const Value& value,
-//                        MatchResultListener* listener) const;
-//
-// See the definition of NotNull() for a complete example.
-template <class Impl>
-class PolymorphicMatcher {
- public:
-  explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
-
-  // Returns a mutable reference to the underlying matcher
-  // implementation object.
-  Impl& mutable_impl() { return impl_; }
-
-  // Returns an immutable reference to the underlying matcher
-  // implementation object.
-  const Impl& impl() const { return impl_; }
-
-  template <typename T>
-  operator Matcher<T>() const {
-    return Matcher<T>(new MonomorphicImpl<T>(impl_));
-  }
-
- private:
-  template <typename T>
-  class MonomorphicImpl : public MatcherInterface<T> {
-   public:
-    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      impl_.DescribeTo(os);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      impl_.DescribeNegationTo(os);
-    }
-
-    virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
-      return impl_.MatchAndExplain(x, listener);
-    }
-
-   private:
-    const Impl impl_;
-
-    GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
-  };
-
-  Impl impl_;
-
-  GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
-};
-
-// Creates a matcher from its implementation.  This is easier to use
-// than the Matcher<T> constructor as it doesn't require you to
-// explicitly write the template argument, e.g.
-//
-//   MakeMatcher(foo);
-// vs
-//   Matcher<const string&>(foo);
-template <typename T>
-inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
-  return Matcher<T>(impl);
-}
-
-// Creates a polymorphic matcher from its implementation.  This is
-// easier to use than the PolymorphicMatcher<Impl> constructor as it
-// doesn't require you to explicitly write the template argument, e.g.
-//
-//   MakePolymorphicMatcher(foo);
-// vs
-//   PolymorphicMatcher<TypeOfFoo>(foo);
-template <class Impl>
-inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
-  return PolymorphicMatcher<Impl>(impl);
-}
-
-// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
-// and MUST NOT BE USED IN USER CODE!!!
-namespace internal {
-
-// The MatcherCastImpl class template is a helper for implementing
-// MatcherCast().  We need this helper in order to partially
-// specialize the implementation of MatcherCast() (C++ allows
-// class/struct templates to be partially specialized, but not
-// function templates.).
-
-// This general version is used when MatcherCast()'s argument is a
-// polymorphic matcher (i.e. something that can be converted to a
-// Matcher but is not one yet; for example, Eq(value)) or a value (for
-// example, "hello").
-template <typename T, typename M>
-class MatcherCastImpl {
- public:
-  static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
-    // M can be a polymorhic matcher, in which case we want to use
-    // its conversion operator to create Matcher<T>.  Or it can be a value
-    // that should be passed to the Matcher<T>'s constructor.
-    //
-    // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
-    // polymorphic matcher because it'll be ambiguous if T has an implicit
-    // constructor from M (this usually happens when T has an implicit
-    // constructor from any type).
-    //
-    // It won't work to unconditionally implict_cast
-    // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
-    // a user-defined conversion from M to T if one exists (assuming M is
-    // a value).
-    return CastImpl(
-        polymorphic_matcher_or_value,
-        BooleanConstant<
-            internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
-  }
-
- private:
-  static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
-    // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
-    // matcher.  It must be a value then.  Use direct initialization to create
-    // a matcher.
-    return Matcher<T>(ImplicitCast_<T>(value));
-  }
-
-  static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
-                             BooleanConstant<true>) {
-    // M is implicitly convertible to Matcher<T>, which means that either
-    // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
-    // from M.  In both cases using the implicit conversion will produce a
-    // matcher.
-    //
-    // Even if T has an implicit constructor from M, it won't be called because
-    // creating Matcher<T> would require a chain of two user-defined conversions
-    // (first to create T from M and then to create Matcher<T> from T).
-    return polymorphic_matcher_or_value;
-  }
-};
-
-// This more specialized version is used when MatcherCast()'s argument
-// is already a Matcher.  This only compiles when type T can be
-// statically converted to type U.
-template <typename T, typename U>
-class MatcherCastImpl<T, Matcher<U> > {
- public:
-  static Matcher<T> Cast(const Matcher<U>& source_matcher) {
-    return Matcher<T>(new Impl(source_matcher));
-  }
-
- private:
-  class Impl : public MatcherInterface<T> {
-   public:
-    explicit Impl(const Matcher<U>& source_matcher)
-        : source_matcher_(source_matcher) {}
-
-    // We delegate the matching logic to the source matcher.
-    virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
-      return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
-    }
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      source_matcher_.DescribeTo(os);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      source_matcher_.DescribeNegationTo(os);
-    }
-
-   private:
-    const Matcher<U> source_matcher_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-};
-
-// This even more specialized version is used for efficiently casting
-// a matcher to its own type.
-template <typename T>
-class MatcherCastImpl<T, Matcher<T> > {
- public:
-  static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
-};
-
-}  // namespace internal
-
-// In order to be safe and clear, casting between different matcher
-// types is done explicitly via MatcherCast<T>(m), which takes a
-// matcher m and returns a Matcher<T>.  It compiles only when T can be
-// statically converted to the argument type of m.
-template <typename T, typename M>
-inline Matcher<T> MatcherCast(const M& matcher) {
-  return internal::MatcherCastImpl<T, M>::Cast(matcher);
-}
-
-// Implements SafeMatcherCast().
-//
-// We use an intermediate class to do the actual safe casting as Nokia's
-// Symbian compiler cannot decide between
-// template <T, M> ... (M) and
-// template <T, U> ... (const Matcher<U>&)
-// for function templates but can for member function templates.
-template <typename T>
-class SafeMatcherCastImpl {
- public:
-  // This overload handles polymorphic matchers and values only since
-  // monomorphic matchers are handled by the next one.
-  template <typename M>
-  static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
-    return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
-  }
-
-  // This overload handles monomorphic matchers.
-  //
-  // In general, if type T can be implicitly converted to type U, we can
-  // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
-  // contravariant): just keep a copy of the original Matcher<U>, convert the
-  // argument from type T to U, and then pass it to the underlying Matcher<U>.
-  // The only exception is when U is a reference and T is not, as the
-  // underlying Matcher<U> may be interested in the argument's address, which
-  // is not preserved in the conversion from T to U.
-  template <typename U>
-  static inline Matcher<T> Cast(const Matcher<U>& matcher) {
-    // Enforce that T can be implicitly converted to U.
-    GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
-                          T_must_be_implicitly_convertible_to_U);
-    // Enforce that we are not converting a non-reference type T to a reference
-    // type U.
-    GTEST_COMPILE_ASSERT_(
-        internal::is_reference<T>::value || !internal::is_reference<U>::value,
-        cannot_convert_non_referentce_arg_to_reference);
-    // In case both T and U are arithmetic types, enforce that the
-    // conversion is not lossy.
-    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
-    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
-    const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
-    const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
-    GTEST_COMPILE_ASSERT_(
-        kTIsOther || kUIsOther ||
-        (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
-        conversion_of_arithmetic_types_must_be_lossless);
-    return MatcherCast<T>(matcher);
-  }
-};
-
-template <typename T, typename M>
-inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
-  return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
-}
-
-// A<T>() returns a matcher that matches any value of type T.
-template <typename T>
-Matcher<T> A();
-
-// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
-// and MUST NOT BE USED IN USER CODE!!!
-namespace internal {
-
-// If the explanation is not empty, prints it to the ostream.
-inline void PrintIfNotEmpty(const internal::string& explanation,
-                            ::std::ostream* os) {
-  if (explanation != "" && os != NULL) {
-    *os << ", " << explanation;
-  }
-}
-
-// Returns true if the given type name is easy to read by a human.
-// This is used to decide whether printing the type of a value might
-// be helpful.
-inline bool IsReadableTypeName(const string& type_name) {
-  // We consider a type name readable if it's short or doesn't contain
-  // a template or function type.
-  return (type_name.length() <= 20 ||
-          type_name.find_first_of("<(") == string::npos);
-}
-
-// Matches the value against the given matcher, prints the value and explains
-// the match result to the listener. Returns the match result.
-// 'listener' must not be NULL.
-// Value cannot be passed by const reference, because some matchers take a
-// non-const argument.
-template <typename Value, typename T>
-bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
-                          MatchResultListener* listener) {
-  if (!listener->IsInterested()) {
-    // If the listener is not interested, we do not need to construct the
-    // inner explanation.
-    return matcher.Matches(value);
-  }
-
-  StringMatchResultListener inner_listener;
-  const bool match = matcher.MatchAndExplain(value, &inner_listener);
-
-  UniversalPrint(value, listener->stream());
-#if GTEST_HAS_RTTI
-  const string& type_name = GetTypeName<Value>();
-  if (IsReadableTypeName(type_name))
-    *listener->stream() << " (of type " << type_name << ")";
-#endif
-  PrintIfNotEmpty(inner_listener.str(), listener->stream());
-
-  return match;
-}
-
-// An internal helper class for doing compile-time loop on a tuple's
-// fields.
-template <size_t N>
-class TuplePrefix {
- public:
-  // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
-  // iff the first N fields of matcher_tuple matches the first N
-  // fields of value_tuple, respectively.
-  template <typename MatcherTuple, typename ValueTuple>
-  static bool Matches(const MatcherTuple& matcher_tuple,
-                      const ValueTuple& value_tuple) {
-    return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
-        && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
-  }
-
-  // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
-  // describes failures in matching the first N fields of matchers
-  // against the first N fields of values.  If there is no failure,
-  // nothing will be streamed to os.
-  template <typename MatcherTuple, typename ValueTuple>
-  static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
-                                     const ValueTuple& values,
-                                     ::std::ostream* os) {
-    // First, describes failures in the first N - 1 fields.
-    TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
-
-    // Then describes the failure (if any) in the (N - 1)-th (0-based)
-    // field.
-    typename tuple_element<N - 1, MatcherTuple>::type matcher =
-        get<N - 1>(matchers);
-    typedef typename tuple_element<N - 1, ValueTuple>::type Value;
-    Value value = get<N - 1>(values);
-    StringMatchResultListener listener;
-    if (!matcher.MatchAndExplain(value, &listener)) {
-      // TODO(wan): include in the message the name of the parameter
-      // as used in MOCK_METHOD*() when possible.
-      *os << "  Expected arg #" << N - 1 << ": ";
-      get<N - 1>(matchers).DescribeTo(os);
-      *os << "\n           Actual: ";
-      // We remove the reference in type Value to prevent the
-      // universal printer from printing the address of value, which
-      // isn't interesting to the user most of the time.  The
-      // matcher's MatchAndExplain() method handles the case when
-      // the address is interesting.
-      internal::UniversalPrint(value, os);
-      PrintIfNotEmpty(listener.str(), os);
-      *os << "\n";
-    }
-  }
-};
-
-// The base case.
-template <>
-class TuplePrefix<0> {
- public:
-  template <typename MatcherTuple, typename ValueTuple>
-  static bool Matches(const MatcherTuple& /* matcher_tuple */,
-                      const ValueTuple& /* value_tuple */) {
-    return true;
-  }
-
-  template <typename MatcherTuple, typename ValueTuple>
-  static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
-                                     const ValueTuple& /* values */,
-                                     ::std::ostream* /* os */) {}
-};
-
-// TupleMatches(matcher_tuple, value_tuple) returns true iff all
-// matchers in matcher_tuple match the corresponding fields in
-// value_tuple.  It is a compiler error if matcher_tuple and
-// value_tuple have different number of fields or incompatible field
-// types.
-template <typename MatcherTuple, typename ValueTuple>
-bool TupleMatches(const MatcherTuple& matcher_tuple,
-                  const ValueTuple& value_tuple) {
-  // Makes sure that matcher_tuple and value_tuple have the same
-  // number of fields.
-  GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
-                        tuple_size<ValueTuple>::value,
-                        matcher_and_value_have_different_numbers_of_fields);
-  return TuplePrefix<tuple_size<ValueTuple>::value>::
-      Matches(matcher_tuple, value_tuple);
-}
-
-// Describes failures in matching matchers against values.  If there
-// is no failure, nothing will be streamed to os.
-template <typename MatcherTuple, typename ValueTuple>
-void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
-                                const ValueTuple& values,
-                                ::std::ostream* os) {
-  TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
-      matchers, values, os);
-}
-
-// TransformTupleValues and its helper.
-//
-// TransformTupleValuesHelper hides the internal machinery that
-// TransformTupleValues uses to implement a tuple traversal.
-template <typename Tuple, typename Func, typename OutIter>
-class TransformTupleValuesHelper {
- private:
-  typedef ::testing::tuple_size<Tuple> TupleSize;
-
- public:
-  // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
-  // Returns the final value of 'out' in case the caller needs it.
-  static OutIter Run(Func f, const Tuple& t, OutIter out) {
-    return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
-  }
-
- private:
-  template <typename Tup, size_t kRemainingSize>
-  struct IterateOverTuple {
-    OutIter operator() (Func f, const Tup& t, OutIter out) const {
-      *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
-      return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
-    }
-  };
-  template <typename Tup>
-  struct IterateOverTuple<Tup, 0> {
-    OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
-      return out;
-    }
-  };
-};
-
-// Successively invokes 'f(element)' on each element of the tuple 't',
-// appending each result to the 'out' iterator. Returns the final value
-// of 'out'.
-template <typename Tuple, typename Func, typename OutIter>
-OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
-  return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
-}
-
-// Implements A<T>().
-template <typename T>
-class AnyMatcherImpl : public MatcherInterface<T> {
- public:
-  virtual bool MatchAndExplain(
-      T /* x */, MatchResultListener* /* listener */) const { return true; }
-  virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    // This is mostly for completeness' safe, as it's not very useful
-    // to write Not(A<bool>()).  However we cannot completely rule out
-    // such a possibility, and it doesn't hurt to be prepared.
-    *os << "never matches";
-  }
-};
-
-// Implements _, a matcher that matches any value of any
-// type.  This is a polymorphic matcher, so we need a template type
-// conversion operator to make it appearing as a Matcher<T> for any
-// type T.
-class AnythingMatcher {
- public:
-  template <typename T>
-  operator Matcher<T>() const { return A<T>(); }
-};
-
-// Implements a matcher that compares a given value with a
-// pre-supplied value using one of the ==, <=, <, etc, operators.  The
-// two values being compared don't have to have the same type.
-//
-// The matcher defined here is polymorphic (for example, Eq(5) can be
-// used to match an int, a short, a double, etc).  Therefore we use
-// a template type conversion operator in the implementation.
-//
-// The following template definition assumes that the Rhs parameter is
-// a "bare" type (i.e. neither 'const T' nor 'T&').
-template <typename D, typename Rhs, typename Op>
-class ComparisonBase {
- public:
-  explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
-  template <typename Lhs>
-  operator Matcher<Lhs>() const {
-    return MakeMatcher(new Impl<Lhs>(rhs_));
-  }
-
- private:
-  template <typename Lhs>
-  class Impl : public MatcherInterface<Lhs> {
-   public:
-    explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
-    virtual bool MatchAndExplain(
-        Lhs lhs, MatchResultListener* /* listener */) const {
-      return Op()(lhs, rhs_);
-    }
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << D::Desc() << " ";
-      UniversalPrint(rhs_, os);
-    }
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << D::NegatedDesc() <<  " ";
-      UniversalPrint(rhs_, os);
-    }
-   private:
-    Rhs rhs_;
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-  Rhs rhs_;
-  GTEST_DISALLOW_ASSIGN_(ComparisonBase);
-};
-
-template <typename Rhs>
-class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
- public:
-  explicit EqMatcher(const Rhs& rhs)
-      : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
-  static const char* Desc() { return "is equal to"; }
-  static const char* NegatedDesc() { return "isn't equal to"; }
-};
-template <typename Rhs>
-class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
- public:
-  explicit NeMatcher(const Rhs& rhs)
-      : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
-  static const char* Desc() { return "isn't equal to"; }
-  static const char* NegatedDesc() { return "is equal to"; }
-};
-template <typename Rhs>
-class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
- public:
-  explicit LtMatcher(const Rhs& rhs)
-      : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
-  static const char* Desc() { return "is <"; }
-  static const char* NegatedDesc() { return "isn't <"; }
-};
-template <typename Rhs>
-class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
- public:
-  explicit GtMatcher(const Rhs& rhs)
-      : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
-  static const char* Desc() { return "is >"; }
-  static const char* NegatedDesc() { return "isn't >"; }
-};
-template <typename Rhs>
-class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
- public:
-  explicit LeMatcher(const Rhs& rhs)
-      : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
-  static const char* Desc() { return "is <="; }
-  static const char* NegatedDesc() { return "isn't <="; }
-};
-template <typename Rhs>
-class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
- public:
-  explicit GeMatcher(const Rhs& rhs)
-      : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
-  static const char* Desc() { return "is >="; }
-  static const char* NegatedDesc() { return "isn't >="; }
-};
-
-// Implements the polymorphic IsNull() matcher, which matches any raw or smart
-// pointer that is NULL.
-class IsNullMatcher {
- public:
-  template <typename Pointer>
-  bool MatchAndExplain(const Pointer& p,
-                       MatchResultListener* /* listener */) const {
-#if GTEST_LANG_CXX11
-    return p == nullptr;
-#else  // GTEST_LANG_CXX11
-    return GetRawPointer(p) == NULL;
-#endif  // GTEST_LANG_CXX11
-  }
-
-  void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "isn't NULL";
-  }
-};
-
-// Implements the polymorphic NotNull() matcher, which matches any raw or smart
-// pointer that is not NULL.
-class NotNullMatcher {
- public:
-  template <typename Pointer>
-  bool MatchAndExplain(const Pointer& p,
-                       MatchResultListener* /* listener */) const {
-#if GTEST_LANG_CXX11
-    return p != nullptr;
-#else  // GTEST_LANG_CXX11
-    return GetRawPointer(p) != NULL;
-#endif  // GTEST_LANG_CXX11
-  }
-
-  void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "is NULL";
-  }
-};
-
-// Ref(variable) matches any argument that is a reference to
-// 'variable'.  This matcher is polymorphic as it can match any
-// super type of the type of 'variable'.
-//
-// The RefMatcher template class implements Ref(variable).  It can
-// only be instantiated with a reference type.  This prevents a user
-// from mistakenly using Ref(x) to match a non-reference function
-// argument.  For example, the following will righteously cause a
-// compiler error:
-//
-//   int n;
-//   Matcher<int> m1 = Ref(n);   // This won't compile.
-//   Matcher<int&> m2 = Ref(n);  // This will compile.
-template <typename T>
-class RefMatcher;
-
-template <typename T>
-class RefMatcher<T&> {
-  // Google Mock is a generic framework and thus needs to support
-  // mocking any function types, including those that take non-const
-  // reference arguments.  Therefore the template parameter T (and
-  // Super below) can be instantiated to either a const type or a
-  // non-const type.
- public:
-  // RefMatcher() takes a T& instead of const T&, as we want the
-  // compiler to catch using Ref(const_value) as a matcher for a
-  // non-const reference.
-  explicit RefMatcher(T& x) : object_(x) {}  // NOLINT
-
-  template <typename Super>
-  operator Matcher<Super&>() const {
-    // By passing object_ (type T&) to Impl(), which expects a Super&,
-    // we make sure that Super is a super type of T.  In particular,
-    // this catches using Ref(const_value) as a matcher for a
-    // non-const reference, as you cannot implicitly convert a const
-    // reference to a non-const reference.
-    return MakeMatcher(new Impl<Super>(object_));
-  }
-
- private:
-  template <typename Super>
-  class Impl : public MatcherInterface<Super&> {
-   public:
-    explicit Impl(Super& x) : object_(x) {}  // NOLINT
-
-    // MatchAndExplain() takes a Super& (as opposed to const Super&)
-    // in order to match the interface MatcherInterface<Super&>.
-    virtual bool MatchAndExplain(
-        Super& x, MatchResultListener* listener) const {
-      *listener << "which is located @" << static_cast<const void*>(&x);
-      return &x == &object_;
-    }
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "references the variable ";
-      UniversalPrinter<Super&>::Print(object_, os);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "does not reference the variable ";
-      UniversalPrinter<Super&>::Print(object_, os);
-    }
-
-   private:
-    const Super& object_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  T& object_;
-
-  GTEST_DISALLOW_ASSIGN_(RefMatcher);
-};
-
-// Polymorphic helper functions for narrow and wide string matchers.
-inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
-  return String::CaseInsensitiveCStringEquals(lhs, rhs);
-}
-
-inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
-                                         const wchar_t* rhs) {
-  return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
-}
-
-// String comparison for narrow or wide strings that can have embedded NUL
-// characters.
-template <typename StringType>
-bool CaseInsensitiveStringEquals(const StringType& s1,
-                                 const StringType& s2) {
-  // Are the heads equal?
-  if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
-    return false;
-  }
-
-  // Skip the equal heads.
-  const typename StringType::value_type nul = 0;
-  const size_t i1 = s1.find(nul), i2 = s2.find(nul);
-
-  // Are we at the end of either s1 or s2?
-  if (i1 == StringType::npos || i2 == StringType::npos) {
-    return i1 == i2;
-  }
-
-  // Are the tails equal?
-  return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
-}
-
-// String matchers.
-
-// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
-template <typename StringType>
-class StrEqualityMatcher {
- public:
-  StrEqualityMatcher(const StringType& str, bool expect_eq,
-                     bool case_sensitive)
-      : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
-
-  // Accepts pointer types, particularly:
-  //   const char*
-  //   char*
-  //   const wchar_t*
-  //   wchar_t*
-  template <typename CharType>
-  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
-    if (s == NULL) {
-      return !expect_eq_;
-    }
-    return MatchAndExplain(StringType(s), listener);
-  }
-
-  // Matches anything that can convert to StringType.
-  //
-  // This is a template, not just a plain function with const StringType&,
-  // because StringPiece has some interfering non-explicit constructors.
-  template <typename MatcheeStringType>
-  bool MatchAndExplain(const MatcheeStringType& s,
-                       MatchResultListener* /* listener */) const {
-    const StringType& s2(s);
-    const bool eq = case_sensitive_ ? s2 == string_ :
-        CaseInsensitiveStringEquals(s2, string_);
-    return expect_eq_ == eq;
-  }
-
-  void DescribeTo(::std::ostream* os) const {
-    DescribeToHelper(expect_eq_, os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    DescribeToHelper(!expect_eq_, os);
-  }
-
- private:
-  void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
-    *os << (expect_eq ? "is " : "isn't ");
-    *os << "equal to ";
-    if (!case_sensitive_) {
-      *os << "(ignoring case) ";
-    }
-    UniversalPrint(string_, os);
-  }
-
-  const StringType string_;
-  const bool expect_eq_;
-  const bool case_sensitive_;
-
-  GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
-};
-
-// Implements the polymorphic HasSubstr(substring) matcher, which
-// can be used as a Matcher<T> as long as T can be converted to a
-// string.
-template <typename StringType>
-class HasSubstrMatcher {
- public:
-  explicit HasSubstrMatcher(const StringType& substring)
-      : substring_(substring) {}
-
-  // Accepts pointer types, particularly:
-  //   const char*
-  //   char*
-  //   const wchar_t*
-  //   wchar_t*
-  template <typename CharType>
-  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
-    return s != NULL && MatchAndExplain(StringType(s), listener);
-  }
-
-  // Matches anything that can convert to StringType.
-  //
-  // This is a template, not just a plain function with const StringType&,
-  // because StringPiece has some interfering non-explicit constructors.
-  template <typename MatcheeStringType>
-  bool MatchAndExplain(const MatcheeStringType& s,
-                       MatchResultListener* /* listener */) const {
-    const StringType& s2(s);
-    return s2.find(substring_) != StringType::npos;
-  }
-
-  // Describes what this matcher matches.
-  void DescribeTo(::std::ostream* os) const {
-    *os << "has substring ";
-    UniversalPrint(substring_, os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "has no substring ";
-    UniversalPrint(substring_, os);
-  }
-
- private:
-  const StringType substring_;
-
-  GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
-};
-
-// Implements the polymorphic StartsWith(substring) matcher, which
-// can be used as a Matcher<T> as long as T can be converted to a
-// string.
-template <typename StringType>
-class StartsWithMatcher {
- public:
-  explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
-  }
-
-  // Accepts pointer types, particularly:
-  //   const char*
-  //   char*
-  //   const wchar_t*
-  //   wchar_t*
-  template <typename CharType>
-  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
-    return s != NULL && MatchAndExplain(StringType(s), listener);
-  }
-
-  // Matches anything that can convert to StringType.
-  //
-  // This is a template, not just a plain function with const StringType&,
-  // because StringPiece has some interfering non-explicit constructors.
-  template <typename MatcheeStringType>
-  bool MatchAndExplain(const MatcheeStringType& s,
-                       MatchResultListener* /* listener */) const {
-    const StringType& s2(s);
-    return s2.length() >= prefix_.length() &&
-        s2.substr(0, prefix_.length()) == prefix_;
-  }
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << "starts with ";
-    UniversalPrint(prefix_, os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "doesn't start with ";
-    UniversalPrint(prefix_, os);
-  }
-
- private:
-  const StringType prefix_;
-
-  GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
-};
-
-// Implements the polymorphic EndsWith(substring) matcher, which
-// can be used as a Matcher<T> as long as T can be converted to a
-// string.
-template <typename StringType>
-class EndsWithMatcher {
- public:
-  explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
-
-  // Accepts pointer types, particularly:
-  //   const char*
-  //   char*
-  //   const wchar_t*
-  //   wchar_t*
-  template <typename CharType>
-  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
-    return s != NULL && MatchAndExplain(StringType(s), listener);
-  }
-
-  // Matches anything that can convert to StringType.
-  //
-  // This is a template, not just a plain function with const StringType&,
-  // because StringPiece has some interfering non-explicit constructors.
-  template <typename MatcheeStringType>
-  bool MatchAndExplain(const MatcheeStringType& s,
-                       MatchResultListener* /* listener */) const {
-    const StringType& s2(s);
-    return s2.length() >= suffix_.length() &&
-        s2.substr(s2.length() - suffix_.length()) == suffix_;
-  }
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << "ends with ";
-    UniversalPrint(suffix_, os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "doesn't end with ";
-    UniversalPrint(suffix_, os);
-  }
-
- private:
-  const StringType suffix_;
-
-  GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
-};
-
-// Implements polymorphic matchers MatchesRegex(regex) and
-// ContainsRegex(regex), which can be used as a Matcher<T> as long as
-// T can be converted to a string.
-class MatchesRegexMatcher {
- public:
-  MatchesRegexMatcher(const RE* regex, bool full_match)
-      : regex_(regex), full_match_(full_match) {}
-
-  // Accepts pointer types, particularly:
-  //   const char*
-  //   char*
-  //   const wchar_t*
-  //   wchar_t*
-  template <typename CharType>
-  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
-    return s != NULL && MatchAndExplain(internal::string(s), listener);
-  }
-
-  // Matches anything that can convert to internal::string.
-  //
-  // This is a template, not just a plain function with const internal::string&,
-  // because StringPiece has some interfering non-explicit constructors.
-  template <class MatcheeStringType>
-  bool MatchAndExplain(const MatcheeStringType& s,
-                       MatchResultListener* /* listener */) const {
-    const internal::string& s2(s);
-    return full_match_ ? RE::FullMatch(s2, *regex_) :
-        RE::PartialMatch(s2, *regex_);
-  }
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << (full_match_ ? "matches" : "contains")
-        << " regular expression ";
-    UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "doesn't " << (full_match_ ? "match" : "contain")
-        << " regular expression ";
-    UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
-  }
-
- private:
-  const internal::linked_ptr<const RE> regex_;
-  const bool full_match_;
-
-  GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
-};
-
-// Implements a matcher that compares the two fields of a 2-tuple
-// using one of the ==, <=, <, etc, operators.  The two fields being
-// compared don't have to have the same type.
-//
-// The matcher defined here is polymorphic (for example, Eq() can be
-// used to match a tuple<int, short>, a tuple<const long&, double>,
-// etc).  Therefore we use a template type conversion operator in the
-// implementation.
-template <typename D, typename Op>
-class PairMatchBase {
- public:
-  template <typename T1, typename T2>
-  operator Matcher< ::testing::tuple<T1, T2> >() const {
-    return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
-  }
-  template <typename T1, typename T2>
-  operator Matcher<const ::testing::tuple<T1, T2>&>() const {
-    return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
-  }
-
- private:
-  static ::std::ostream& GetDesc(::std::ostream& os) {  // NOLINT
-    return os << D::Desc();
-  }
-
-  template <typename Tuple>
-  class Impl : public MatcherInterface<Tuple> {
-   public:
-    virtual bool MatchAndExplain(
-        Tuple args,
-        MatchResultListener* /* listener */) const {
-      return Op()(::testing::get<0>(args), ::testing::get<1>(args));
-    }
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "are " << GetDesc;
-    }
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "aren't " << GetDesc;
-    }
-  };
-};
-
-class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
- public:
-  static const char* Desc() { return "an equal pair"; }
-};
-class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
- public:
-  static const char* Desc() { return "an unequal pair"; }
-};
-class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
- public:
-  static const char* Desc() { return "a pair where the first < the second"; }
-};
-class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
- public:
-  static const char* Desc() { return "a pair where the first > the second"; }
-};
-class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
- public:
-  static const char* Desc() { return "a pair where the first <= the second"; }
-};
-class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
- public:
-  static const char* Desc() { return "a pair where the first >= the second"; }
-};
-
-// Implements the Not(...) matcher for a particular argument type T.
-// We do not nest it inside the NotMatcher class template, as that
-// will prevent different instantiations of NotMatcher from sharing
-// the same NotMatcherImpl<T> class.
-template <typename T>
-class NotMatcherImpl : public MatcherInterface<T> {
- public:
-  explicit NotMatcherImpl(const Matcher<T>& matcher)
-      : matcher_(matcher) {}
-
-  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
-    return !matcher_.MatchAndExplain(x, listener);
-  }
-
-  virtual void DescribeTo(::std::ostream* os) const {
-    matcher_.DescribeNegationTo(os);
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    matcher_.DescribeTo(os);
-  }
-
- private:
-  const Matcher<T> matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
-};
-
-// Implements the Not(m) matcher, which matches a value that doesn't
-// match matcher m.
-template <typename InnerMatcher>
-class NotMatcher {
- public:
-  explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
-
-  // This template type conversion operator allows Not(m) to be used
-  // to match any type m can match.
-  template <typename T>
-  operator Matcher<T>() const {
-    return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
-  }
-
- private:
-  InnerMatcher matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(NotMatcher);
-};
-
-// Implements the AllOf(m1, m2) matcher for a particular argument type
-// T. We do not nest it inside the BothOfMatcher class template, as
-// that will prevent different instantiations of BothOfMatcher from
-// sharing the same BothOfMatcherImpl<T> class.
-template <typename T>
-class BothOfMatcherImpl : public MatcherInterface<T> {
- public:
-  BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
-      : matcher1_(matcher1), matcher2_(matcher2) {}
-
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "(";
-    matcher1_.DescribeTo(os);
-    *os << ") and (";
-    matcher2_.DescribeTo(os);
-    *os << ")";
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "(";
-    matcher1_.DescribeNegationTo(os);
-    *os << ") or (";
-    matcher2_.DescribeNegationTo(os);
-    *os << ")";
-  }
-
-  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
-    // If either matcher1_ or matcher2_ doesn't match x, we only need
-    // to explain why one of them fails.
-    StringMatchResultListener listener1;
-    if (!matcher1_.MatchAndExplain(x, &listener1)) {
-      *listener << listener1.str();
-      return false;
-    }
-
-    StringMatchResultListener listener2;
-    if (!matcher2_.MatchAndExplain(x, &listener2)) {
-      *listener << listener2.str();
-      return false;
-    }
-
-    // Otherwise we need to explain why *both* of them match.
-    const internal::string s1 = listener1.str();
-    const internal::string s2 = listener2.str();
-
-    if (s1 == "") {
-      *listener << s2;
-    } else {
-      *listener << s1;
-      if (s2 != "") {
-        *listener << ", and " << s2;
-      }
-    }
-    return true;
-  }
-
- private:
-  const Matcher<T> matcher1_;
-  const Matcher<T> matcher2_;
-
-  GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
-};
-
-#if GTEST_LANG_CXX11
-// MatcherList provides mechanisms for storing a variable number of matchers in
-// a list structure (ListType) and creating a combining matcher from such a
-// list.
-// The template is defined recursively using the following template paramters:
-//   * kSize is the length of the MatcherList.
-//   * Head is the type of the first matcher of the list.
-//   * Tail denotes the types of the remaining matchers of the list.
-template <int kSize, typename Head, typename... Tail>
-struct MatcherList {
-  typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
-  typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
-
-  // BuildList stores variadic type values in a nested pair structure.
-  // Example:
-  // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
-  // the corresponding result of type pair<int, pair<string, float>>.
-  static ListType BuildList(const Head& matcher, const Tail&... tail) {
-    return ListType(matcher, MatcherListTail::BuildList(tail...));
-  }
-
-  // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
-  // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
-  // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
-  // constructor taking two Matcher<T>s as input.
-  template <typename T, template <typename /* T */> class CombiningMatcher>
-  static Matcher<T> CreateMatcher(const ListType& matchers) {
-    return Matcher<T>(new CombiningMatcher<T>(
-        SafeMatcherCast<T>(matchers.first),
-        MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
-            matchers.second)));
-  }
-};
-
-// The following defines the base case for the recursive definition of
-// MatcherList.
-template <typename Matcher1, typename Matcher2>
-struct MatcherList<2, Matcher1, Matcher2> {
-  typedef ::std::pair<Matcher1, Matcher2> ListType;
-
-  static ListType BuildList(const Matcher1& matcher1,
-                            const Matcher2& matcher2) {
-    return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
-  }
-
-  template <typename T, template <typename /* T */> class CombiningMatcher>
-  static Matcher<T> CreateMatcher(const ListType& matchers) {
-    return Matcher<T>(new CombiningMatcher<T>(
-        SafeMatcherCast<T>(matchers.first),
-        SafeMatcherCast<T>(matchers.second)));
-  }
-};
-
-// VariadicMatcher is used for the variadic implementation of
-// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
-// CombiningMatcher<T> is used to recursively combine the provided matchers
-// (of type Args...).
-template <template <typename T> class CombiningMatcher, typename... Args>
-class VariadicMatcher {
- public:
-  VariadicMatcher(const Args&... matchers)  // NOLINT
-      : matchers_(MatcherListType::BuildList(matchers...)) {}
-
-  // This template type conversion operator allows an
-  // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
-  // all of the provided matchers (Matcher1, Matcher2, ...) can match.
-  template <typename T>
-  operator Matcher<T>() const {
-    return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
-        matchers_);
-  }
-
- private:
-  typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
-
-  const typename MatcherListType::ListType matchers_;
-
-  GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
-};
-
-template <typename... Args>
-using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
-
-#endif  // GTEST_LANG_CXX11
-
-// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
-// matches a value that matches all of the matchers m_1, ..., and m_n.
-template <typename Matcher1, typename Matcher2>
-class BothOfMatcher {
- public:
-  BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
-      : matcher1_(matcher1), matcher2_(matcher2) {}
-
-  // This template type conversion operator allows a
-  // BothOfMatcher<Matcher1, Matcher2> object to match any type that
-  // both Matcher1 and Matcher2 can match.
-  template <typename T>
-  operator Matcher<T>() const {
-    return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
-                                               SafeMatcherCast<T>(matcher2_)));
-  }
-
- private:
-  Matcher1 matcher1_;
-  Matcher2 matcher2_;
-
-  GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
-};
-
-// Implements the AnyOf(m1, m2) matcher for a particular argument type
-// T.  We do not nest it inside the AnyOfMatcher class template, as
-// that will prevent different instantiations of AnyOfMatcher from
-// sharing the same EitherOfMatcherImpl<T> class.
-template <typename T>
-class EitherOfMatcherImpl : public MatcherInterface<T> {
- public:
-  EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
-      : matcher1_(matcher1), matcher2_(matcher2) {}
-
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "(";
-    matcher1_.DescribeTo(os);
-    *os << ") or (";
-    matcher2_.DescribeTo(os);
-    *os << ")";
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "(";
-    matcher1_.DescribeNegationTo(os);
-    *os << ") and (";
-    matcher2_.DescribeNegationTo(os);
-    *os << ")";
-  }
-
-  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
-    // If either matcher1_ or matcher2_ matches x, we just need to
-    // explain why *one* of them matches.
-    StringMatchResultListener listener1;
-    if (matcher1_.MatchAndExplain(x, &listener1)) {
-      *listener << listener1.str();
-      return true;
-    }
-
-    StringMatchResultListener listener2;
-    if (matcher2_.MatchAndExplain(x, &listener2)) {
-      *listener << listener2.str();
-      return true;
-    }
-
-    // Otherwise we need to explain why *both* of them fail.
-    const internal::string s1 = listener1.str();
-    const internal::string s2 = listener2.str();
-
-    if (s1 == "") {
-      *listener << s2;
-    } else {
-      *listener << s1;
-      if (s2 != "") {
-        *listener << ", and " << s2;
-      }
-    }
-    return false;
-  }
-
- private:
-  const Matcher<T> matcher1_;
-  const Matcher<T> matcher2_;
-
-  GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
-};
-
-#if GTEST_LANG_CXX11
-// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
-template <typename... Args>
-using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
-
-#endif  // GTEST_LANG_CXX11
-
-// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
-// matches a value that matches at least one of the matchers m_1, ...,
-// and m_n.
-template <typename Matcher1, typename Matcher2>
-class EitherOfMatcher {
- public:
-  EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
-      : matcher1_(matcher1), matcher2_(matcher2) {}
-
-  // This template type conversion operator allows a
-  // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
-  // both Matcher1 and Matcher2 can match.
-  template <typename T>
-  operator Matcher<T>() const {
-    return Matcher<T>(new EitherOfMatcherImpl<T>(
-        SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
-  }
-
- private:
-  Matcher1 matcher1_;
-  Matcher2 matcher2_;
-
-  GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
-};
-
-// Used for implementing Truly(pred), which turns a predicate into a
-// matcher.
-template <typename Predicate>
-class TrulyMatcher {
- public:
-  explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
-
-  // This method template allows Truly(pred) to be used as a matcher
-  // for type T where T is the argument type of predicate 'pred'.  The
-  // argument is passed by reference as the predicate may be
-  // interested in the address of the argument.
-  template <typename T>
-  bool MatchAndExplain(T& x,  // NOLINT
-                       MatchResultListener* /* listener */) const {
-    // Without the if-statement, MSVC sometimes warns about converting
-    // a value to bool (warning 4800).
-    //
-    // We cannot write 'return !!predicate_(x);' as that doesn't work
-    // when predicate_(x) returns a class convertible to bool but
-    // having no operator!().
-    if (predicate_(x))
-      return true;
-    return false;
-  }
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << "satisfies the given predicate";
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "doesn't satisfy the given predicate";
-  }
-
- private:
-  Predicate predicate_;
-
-  GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
-};
-
-// Used for implementing Matches(matcher), which turns a matcher into
-// a predicate.
-template <typename M>
-class MatcherAsPredicate {
- public:
-  explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
-
-  // This template operator() allows Matches(m) to be used as a
-  // predicate on type T where m is a matcher on type T.
-  //
-  // The argument x is passed by reference instead of by value, as
-  // some matcher may be interested in its address (e.g. as in
-  // Matches(Ref(n))(x)).
-  template <typename T>
-  bool operator()(const T& x) const {
-    // We let matcher_ commit to a particular type here instead of
-    // when the MatcherAsPredicate object was constructed.  This
-    // allows us to write Matches(m) where m is a polymorphic matcher
-    // (e.g. Eq(5)).
-    //
-    // If we write Matcher<T>(matcher_).Matches(x) here, it won't
-    // compile when matcher_ has type Matcher<const T&>; if we write
-    // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
-    // when matcher_ has type Matcher<T>; if we just write
-    // matcher_.Matches(x), it won't compile when matcher_ is
-    // polymorphic, e.g. Eq(5).
-    //
-    // MatcherCast<const T&>() is necessary for making the code work
-    // in all of the above situations.
-    return MatcherCast<const T&>(matcher_).Matches(x);
-  }
-
- private:
-  M matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
-};
-
-// For implementing ASSERT_THAT() and EXPECT_THAT().  The template
-// argument M must be a type that can be converted to a matcher.
-template <typename M>
-class PredicateFormatterFromMatcher {
- public:
-  explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
-
-  // This template () operator allows a PredicateFormatterFromMatcher
-  // object to act as a predicate-formatter suitable for using with
-  // Google Test's EXPECT_PRED_FORMAT1() macro.
-  template <typename T>
-  AssertionResult operator()(const char* value_text, const T& x) const {
-    // We convert matcher_ to a Matcher<const T&> *now* instead of
-    // when the PredicateFormatterFromMatcher object was constructed,
-    // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
-    // know which type to instantiate it to until we actually see the
-    // type of x here.
-    //
-    // We write SafeMatcherCast<const T&>(matcher_) instead of
-    // Matcher<const T&>(matcher_), as the latter won't compile when
-    // matcher_ has type Matcher<T> (e.g. An<int>()).
-    // We don't write MatcherCast<const T&> either, as that allows
-    // potentially unsafe downcasting of the matcher argument.
-    const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
-    StringMatchResultListener listener;
-    if (MatchPrintAndExplain(x, matcher, &listener))
-      return AssertionSuccess();
-
-    ::std::stringstream ss;
-    ss << "Value of: " << value_text << "\n"
-       << "Expected: ";
-    matcher.DescribeTo(&ss);
-    ss << "\n  Actual: " << listener.str();
-    return AssertionFailure() << ss.str();
-  }
-
- private:
-  const M matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
-};
-
-// A helper function for converting a matcher to a predicate-formatter
-// without the user needing to explicitly write the type.  This is
-// used for implementing ASSERT_THAT() and EXPECT_THAT().
-// Implementation detail: 'matcher' is received by-value to force decaying.
-template <typename M>
-inline PredicateFormatterFromMatcher<M>
-MakePredicateFormatterFromMatcher(M matcher) {
-  return PredicateFormatterFromMatcher<M>(internal::move(matcher));
-}
-
-// Implements the polymorphic floating point equality matcher, which matches
-// two float values using ULP-based approximation or, optionally, a
-// user-specified epsilon.  The template is meant to be instantiated with
-// FloatType being either float or double.
-template <typename FloatType>
-class FloatingEqMatcher {
- public:
-  // Constructor for FloatingEqMatcher.
-  // The matcher's input will be compared with expected.  The matcher treats two
-  // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,
-  // equality comparisons between NANs will always return false.  We specify a
-  // negative max_abs_error_ term to indicate that ULP-based approximation will
-  // be used for comparison.
-  FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
-    expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
-  }
-
-  // Constructor that supports a user-specified max_abs_error that will be used
-  // for comparison instead of ULP-based approximation.  The max absolute
-  // should be non-negative.
-  FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
-                    FloatType max_abs_error)
-      : expected_(expected),
-        nan_eq_nan_(nan_eq_nan),
-        max_abs_error_(max_abs_error) {
-    GTEST_CHECK_(max_abs_error >= 0)
-        << ", where max_abs_error is" << max_abs_error;
-  }
-
-  // Implements floating point equality matcher as a Matcher<T>.
-  template <typename T>
-  class Impl : public MatcherInterface<T> {
-   public:
-    Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
-        : expected_(expected),
-          nan_eq_nan_(nan_eq_nan),
-          max_abs_error_(max_abs_error) {}
-
-    virtual bool MatchAndExplain(T value,
-                                 MatchResultListener* listener) const {
-      const FloatingPoint<FloatType> actual(value), expected(expected_);
-
-      // Compares NaNs first, if nan_eq_nan_ is true.
-      if (actual.is_nan() || expected.is_nan()) {
-        if (actual.is_nan() && expected.is_nan()) {
-          return nan_eq_nan_;
-        }
-        // One is nan; the other is not nan.
-        return false;
-      }
-      if (HasMaxAbsError()) {
-        // We perform an equality check so that inf will match inf, regardless
-        // of error bounds.  If the result of value - expected_ would result in
-        // overflow or if either value is inf, the default result is infinity,
-        // which should only match if max_abs_error_ is also infinity.
-        if (value == expected_) {
-          return true;
-        }
-
-        const FloatType diff = value - expected_;
-        if (fabs(diff) <= max_abs_error_) {
-          return true;
-        }
-
-        if (listener->IsInterested()) {
-          *listener << "which is " << diff << " from " << expected_;
-        }
-        return false;
-      } else {
-        return actual.AlmostEquals(expected);
-      }
-    }
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      // os->precision() returns the previously set precision, which we
-      // store to restore the ostream to its original configuration
-      // after outputting.
-      const ::std::streamsize old_precision = os->precision(
-          ::std::numeric_limits<FloatType>::digits10 + 2);
-      if (FloatingPoint<FloatType>(expected_).is_nan()) {
-        if (nan_eq_nan_) {
-          *os << "is NaN";
-        } else {
-          *os << "never matches";
-        }
-      } else {
-        *os << "is approximately " << expected_;
-        if (HasMaxAbsError()) {
-          *os << " (absolute error <= " << max_abs_error_ << ")";
-        }
-      }
-      os->precision(old_precision);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      // As before, get original precision.
-      const ::std::streamsize old_precision = os->precision(
-          ::std::numeric_limits<FloatType>::digits10 + 2);
-      if (FloatingPoint<FloatType>(expected_).is_nan()) {
-        if (nan_eq_nan_) {
-          *os << "isn't NaN";
-        } else {
-          *os << "is anything";
-        }
-      } else {
-        *os << "isn't approximately " << expected_;
-        if (HasMaxAbsError()) {
-          *os << " (absolute error > " << max_abs_error_ << ")";
-        }
-      }
-      // Restore original precision.
-      os->precision(old_precision);
-    }
-
-   private:
-    bool HasMaxAbsError() const {
-      return max_abs_error_ >= 0;
-    }
-
-    const FloatType expected_;
-    const bool nan_eq_nan_;
-    // max_abs_error will be used for value comparison when >= 0.
-    const FloatType max_abs_error_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  // The following 3 type conversion operators allow FloatEq(expected) and
-  // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
-  // Matcher<const float&>, or a Matcher<float&>, but nothing else.
-  // (While Google's C++ coding style doesn't allow arguments passed
-  // by non-const reference, we may see them in code not conforming to
-  // the style.  Therefore Google Mock needs to support them.)
-  operator Matcher<FloatType>() const {
-    return MakeMatcher(
-        new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
-  }
-
-  operator Matcher<const FloatType&>() const {
-    return MakeMatcher(
-        new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
-  }
-
-  operator Matcher<FloatType&>() const {
-    return MakeMatcher(
-        new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
-  }
-
- private:
-  const FloatType expected_;
-  const bool nan_eq_nan_;
-  // max_abs_error will be used for value comparison when >= 0.
-  const FloatType max_abs_error_;
-
-  GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
-};
-
-// Implements the Pointee(m) matcher for matching a pointer whose
-// pointee matches matcher m.  The pointer can be either raw or smart.
-template <typename InnerMatcher>
-class PointeeMatcher {
- public:
-  explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
-
-  // This type conversion operator template allows Pointee(m) to be
-  // used as a matcher for any pointer type whose pointee type is
-  // compatible with the inner matcher, where type Pointer can be
-  // either a raw pointer or a smart pointer.
-  //
-  // The reason we do this instead of relying on
-  // MakePolymorphicMatcher() is that the latter is not flexible
-  // enough for implementing the DescribeTo() method of Pointee().
-  template <typename Pointer>
-  operator Matcher<Pointer>() const {
-    return MakeMatcher(new Impl<Pointer>(matcher_));
-  }
-
- private:
-  // The monomorphic implementation that works for a particular pointer type.
-  template <typename Pointer>
-  class Impl : public MatcherInterface<Pointer> {
-   public:
-    typedef typename PointeeOf<GTEST_REMOVE_CONST_(  // NOLINT
-        GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
-
-    explicit Impl(const InnerMatcher& matcher)
-        : matcher_(MatcherCast<const Pointee&>(matcher)) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "points to a value that ";
-      matcher_.DescribeTo(os);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "does not point to a value that ";
-      matcher_.DescribeTo(os);
-    }
-
-    virtual bool MatchAndExplain(Pointer pointer,
-                                 MatchResultListener* listener) const {
-      if (GetRawPointer(pointer) == NULL)
-        return false;
-
-      *listener << "which points to ";
-      return MatchPrintAndExplain(*pointer, matcher_, listener);
-    }
-
-   private:
-    const Matcher<const Pointee&> matcher_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  const InnerMatcher matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
-};
-
-// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
-// reference that matches inner_matcher when dynamic_cast<T> is applied.
-// The result of dynamic_cast<To> is forwarded to the inner matcher.
-// If To is a pointer and the cast fails, the inner matcher will receive NULL.
-// If To is a reference and the cast fails, this matcher returns false
-// immediately.
-template <typename To>
-class WhenDynamicCastToMatcherBase {
- public:
-  explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
-      : matcher_(matcher) {}
-
-  void DescribeTo(::std::ostream* os) const {
-    GetCastTypeDescription(os);
-    matcher_.DescribeTo(os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    GetCastTypeDescription(os);
-    matcher_.DescribeNegationTo(os);
-  }
-
- protected:
-  const Matcher<To> matcher_;
-
-  static string GetToName() {
-#if GTEST_HAS_RTTI
-    return GetTypeName<To>();
-#else  // GTEST_HAS_RTTI
-    return "the target type";
-#endif  // GTEST_HAS_RTTI
-  }
-
- private:
-  static void GetCastTypeDescription(::std::ostream* os) {
-    *os << "when dynamic_cast to " << GetToName() << ", ";
-  }
-
-  GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
-};
-
-// Primary template.
-// To is a pointer. Cast and forward the result.
-template <typename To>
-class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
- public:
-  explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
-      : WhenDynamicCastToMatcherBase<To>(matcher) {}
-
-  template <typename From>
-  bool MatchAndExplain(From from, MatchResultListener* listener) const {
-    // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
-    To to = dynamic_cast<To>(from);
-    return MatchPrintAndExplain(to, this->matcher_, listener);
-  }
-};
-
-// Specialize for references.
-// In this case we return false if the dynamic_cast fails.
-template <typename To>
-class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
- public:
-  explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
-      : WhenDynamicCastToMatcherBase<To&>(matcher) {}
-
-  template <typename From>
-  bool MatchAndExplain(From& from, MatchResultListener* listener) const {
-    // We don't want an std::bad_cast here, so do the cast with pointers.
-    To* to = dynamic_cast<To*>(&from);
-    if (to == NULL) {
-      *listener << "which cannot be dynamic_cast to " << this->GetToName();
-      return false;
-    }
-    return MatchPrintAndExplain(*to, this->matcher_, listener);
-  }
-};
-
-// Implements the Field() matcher for matching a field (i.e. member
-// variable) of an object.
-template <typename Class, typename FieldType>
-class FieldMatcher {
- public:
-  FieldMatcher(FieldType Class::*field,
-               const Matcher<const FieldType&>& matcher)
-      : field_(field), matcher_(matcher) {}
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << "is an object whose given field ";
-    matcher_.DescribeTo(os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "is an object whose given field ";
-    matcher_.DescribeNegationTo(os);
-  }
-
-  template <typename T>
-  bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
-    return MatchAndExplainImpl(
-        typename ::testing::internal::
-            is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
-        value, listener);
-  }
-
- private:
-  // The first argument of MatchAndExplainImpl() is needed to help
-  // Symbian's C++ compiler choose which overload to use.  Its type is
-  // true_type iff the Field() matcher is used to match a pointer.
-  bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
-                           MatchResultListener* listener) const {
-    *listener << "whose given field is ";
-    return MatchPrintAndExplain(obj.*field_, matcher_, listener);
-  }
-
-  bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
-                           MatchResultListener* listener) const {
-    if (p == NULL)
-      return false;
-
-    *listener << "which points to an object ";
-    // Since *p has a field, it must be a class/struct/union type and
-    // thus cannot be a pointer.  Therefore we pass false_type() as
-    // the first argument.
-    return MatchAndExplainImpl(false_type(), *p, listener);
-  }
-
-  const FieldType Class::*field_;
-  const Matcher<const FieldType&> matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(FieldMatcher);
-};
-
-// Implements the Property() matcher for matching a property
-// (i.e. return value of a getter method) of an object.
-template <typename Class, typename PropertyType>
-class PropertyMatcher {
- public:
-  // The property may have a reference type, so 'const PropertyType&'
-  // may cause double references and fail to compile.  That's why we
-  // need GTEST_REFERENCE_TO_CONST, which works regardless of
-  // PropertyType being a reference or not.
-  typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
-
-  PropertyMatcher(PropertyType (Class::*property)() const,
-                  const Matcher<RefToConstProperty>& matcher)
-      : property_(property), matcher_(matcher) {}
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << "is an object whose given property ";
-    matcher_.DescribeTo(os);
-  }
-
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "is an object whose given property ";
-    matcher_.DescribeNegationTo(os);
-  }
-
-  template <typename T>
-  bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
-    return MatchAndExplainImpl(
-        typename ::testing::internal::
-            is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
-        value, listener);
-  }
-
- private:
-  // The first argument of MatchAndExplainImpl() is needed to help
-  // Symbian's C++ compiler choose which overload to use.  Its type is
-  // true_type iff the Property() matcher is used to match a pointer.
-  bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
-                           MatchResultListener* listener) const {
-    *listener << "whose given property is ";
-    // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
-    // which takes a non-const reference as argument.
-#if defined(_PREFAST_ ) && _MSC_VER == 1800
-    // Workaround bug in VC++ 2013's /analyze parser.
-    // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
-    posix::Abort();  // To make sure it is never run.
-    return false;
-#else
-    RefToConstProperty result = (obj.*property_)();
-    return MatchPrintAndExplain(result, matcher_, listener);
-#endif
-  }
-
-  bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
-                           MatchResultListener* listener) const {
-    if (p == NULL)
-      return false;
-
-    *listener << "which points to an object ";
-    // Since *p has a property method, it must be a class/struct/union
-    // type and thus cannot be a pointer.  Therefore we pass
-    // false_type() as the first argument.
-    return MatchAndExplainImpl(false_type(), *p, listener);
-  }
-
-  PropertyType (Class::*property_)() const;
-  const Matcher<RefToConstProperty> matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
-};
-
-// Type traits specifying various features of different functors for ResultOf.
-// The default template specifies features for functor objects.
-// Functor classes have to typedef argument_type and result_type
-// to be compatible with ResultOf.
-template <typename Functor>
-struct CallableTraits {
-  typedef typename Functor::result_type ResultType;
-  typedef Functor StorageType;
-
-  static void CheckIsValid(Functor /* functor */) {}
-  template <typename T>
-  static ResultType Invoke(Functor f, T arg) { return f(arg); }
-};
-
-// Specialization for function pointers.
-template <typename ArgType, typename ResType>
-struct CallableTraits<ResType(*)(ArgType)> {
-  typedef ResType ResultType;
-  typedef ResType(*StorageType)(ArgType);
-
-  static void CheckIsValid(ResType(*f)(ArgType)) {
-    GTEST_CHECK_(f != NULL)
-        << "NULL function pointer is passed into ResultOf().";
-  }
-  template <typename T>
-  static ResType Invoke(ResType(*f)(ArgType), T arg) {
-    return (*f)(arg);
-  }
-};
-
-// Implements the ResultOf() matcher for matching a return value of a
-// unary function of an object.
-template <typename Callable>
-class ResultOfMatcher {
- public:
-  typedef typename CallableTraits<Callable>::ResultType ResultType;
-
-  ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
-      : callable_(callable), matcher_(matcher) {
-    CallableTraits<Callable>::CheckIsValid(callable_);
-  }
-
-  template <typename T>
-  operator Matcher<T>() const {
-    return Matcher<T>(new Impl<T>(callable_, matcher_));
-  }
-
- private:
-  typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
-
-  template <typename T>
-  class Impl : public MatcherInterface<T> {
-   public:
-    Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
-        : callable_(callable), matcher_(matcher) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "is mapped by the given callable to a value that ";
-      matcher_.DescribeTo(os);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "is mapped by the given callable to a value that ";
-      matcher_.DescribeNegationTo(os);
-    }
-
-    virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
-      *listener << "which is mapped by the given callable to ";
-      // Cannot pass the return value (for example, int) to
-      // MatchPrintAndExplain, which takes a non-const reference as argument.
-      ResultType result =
-          CallableTraits<Callable>::template Invoke<T>(callable_, obj);
-      return MatchPrintAndExplain(result, matcher_, listener);
-    }
-
-   private:
-    // Functors often define operator() as non-const method even though
-    // they are actualy stateless. But we need to use them even when
-    // 'this' is a const pointer. It's the user's responsibility not to
-    // use stateful callables with ResultOf(), which does't guarantee
-    // how many times the callable will be invoked.
-    mutable CallableStorageType callable_;
-    const Matcher<ResultType> matcher_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };  // class Impl
-
-  const CallableStorageType callable_;
-  const Matcher<ResultType> matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
-};
-
-// Implements a matcher that checks the size of an STL-style container.
-template <typename SizeMatcher>
-class SizeIsMatcher {
- public:
-  explicit SizeIsMatcher(const SizeMatcher& size_matcher)
-       : size_matcher_(size_matcher) {
-  }
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    return MakeMatcher(new Impl<Container>(size_matcher_));
-  }
-
-  template <typename Container>
-  class Impl : public MatcherInterface<Container> {
-   public:
-    typedef internal::StlContainerView<
-         GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
-    typedef typename ContainerView::type::size_type SizeType;
-    explicit Impl(const SizeMatcher& size_matcher)
-        : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "size ";
-      size_matcher_.DescribeTo(os);
-    }
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "size ";
-      size_matcher_.DescribeNegationTo(os);
-    }
-
-    virtual bool MatchAndExplain(Container container,
-                                 MatchResultListener* listener) const {
-      SizeType size = container.size();
-      StringMatchResultListener size_listener;
-      const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
-      *listener
-          << "whose size " << size << (result ? " matches" : " doesn't match");
-      PrintIfNotEmpty(size_listener.str(), listener->stream());
-      return result;
-    }
-
-   private:
-    const Matcher<SizeType> size_matcher_;
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
- private:
-  const SizeMatcher size_matcher_;
-  GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
-};
-
-// Implements a matcher that checks the begin()..end() distance of an STL-style
-// container.
-template <typename DistanceMatcher>
-class BeginEndDistanceIsMatcher {
- public:
-  explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
-      : distance_matcher_(distance_matcher) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    return MakeMatcher(new Impl<Container>(distance_matcher_));
-  }
-
-  template <typename Container>
-  class Impl : public MatcherInterface<Container> {
-   public:
-    typedef internal::StlContainerView<
-        GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
-    typedef typename std::iterator_traits<
-        typename ContainerView::type::const_iterator>::difference_type
-        DistanceType;
-    explicit Impl(const DistanceMatcher& distance_matcher)
-        : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "distance between begin() and end() ";
-      distance_matcher_.DescribeTo(os);
-    }
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "distance between begin() and end() ";
-      distance_matcher_.DescribeNegationTo(os);
-    }
-
-    virtual bool MatchAndExplain(Container container,
-                                 MatchResultListener* listener) const {
-#if GTEST_HAS_STD_BEGIN_AND_END_
-      using std::begin;
-      using std::end;
-      DistanceType distance = std::distance(begin(container), end(container));
-#else
-      DistanceType distance = std::distance(container.begin(), container.end());
-#endif
-      StringMatchResultListener distance_listener;
-      const bool result =
-          distance_matcher_.MatchAndExplain(distance, &distance_listener);
-      *listener << "whose distance between begin() and end() " << distance
-                << (result ? " matches" : " doesn't match");
-      PrintIfNotEmpty(distance_listener.str(), listener->stream());
-      return result;
-    }
-
-   private:
-    const Matcher<DistanceType> distance_matcher_;
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
- private:
-  const DistanceMatcher distance_matcher_;
-  GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
-};
-
-// Implements an equality matcher for any STL-style container whose elements
-// support ==. This matcher is like Eq(), but its failure explanations provide
-// more detailed information that is useful when the container is used as a set.
-// The failure message reports elements that are in one of the operands but not
-// the other. The failure messages do not report duplicate or out-of-order
-// elements in the containers (which don't properly matter to sets, but can
-// occur if the containers are vectors or lists, for example).
-//
-// Uses the container's const_iterator, value_type, operator ==,
-// begin(), and end().
-template <typename Container>
-class ContainerEqMatcher {
- public:
-  typedef internal::StlContainerView<Container> View;
-  typedef typename View::type StlContainer;
-  typedef typename View::const_reference StlContainerReference;
-
-  // We make a copy of expected in case the elements in it are modified
-  // after this matcher is created.
-  explicit ContainerEqMatcher(const Container& expected)
-      : expected_(View::Copy(expected)) {
-    // Makes sure the user doesn't instantiate this class template
-    // with a const or reference type.
-    (void)testing::StaticAssertTypeEq<Container,
-        GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
-  }
-
-  void DescribeTo(::std::ostream* os) const {
-    *os << "equals ";
-    UniversalPrint(expected_, os);
-  }
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "does not equal ";
-    UniversalPrint(expected_, os);
-  }
-
-  template <typename LhsContainer>
-  bool MatchAndExplain(const LhsContainer& lhs,
-                       MatchResultListener* listener) const {
-    // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
-    // that causes LhsContainer to be a const type sometimes.
-    typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
-        LhsView;
-    typedef typename LhsView::type LhsStlContainer;
-    StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
-    if (lhs_stl_container == expected_)
-      return true;
-
-    ::std::ostream* const os = listener->stream();
-    if (os != NULL) {
-      // Something is different. Check for extra values first.
-      bool printed_header = false;
-      for (typename LhsStlContainer::const_iterator it =
-               lhs_stl_container.begin();
-           it != lhs_stl_container.end(); ++it) {
-        if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
-            expected_.end()) {
-          if (printed_header) {
-            *os << ", ";
-          } else {
-            *os << "which has these unexpected elements: ";
-            printed_header = true;
-          }
-          UniversalPrint(*it, os);
-        }
-      }
-
-      // Now check for missing values.
-      bool printed_header2 = false;
-      for (typename StlContainer::const_iterator it = expected_.begin();
-           it != expected_.end(); ++it) {
-        if (internal::ArrayAwareFind(
-                lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
-            lhs_stl_container.end()) {
-          if (printed_header2) {
-            *os << ", ";
-          } else {
-            *os << (printed_header ? ",\nand" : "which")
-                << " doesn't have these expected elements: ";
-            printed_header2 = true;
-          }
-          UniversalPrint(*it, os);
-        }
-      }
-    }
-
-    return false;
-  }
-
- private:
-  const StlContainer expected_;
-
-  GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
-};
-
-// A comparator functor that uses the < operator to compare two values.
-struct LessComparator {
-  template <typename T, typename U>
-  bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
-};
-
-// Implements WhenSortedBy(comparator, container_matcher).
-template <typename Comparator, typename ContainerMatcher>
-class WhenSortedByMatcher {
- public:
-  WhenSortedByMatcher(const Comparator& comparator,
-                      const ContainerMatcher& matcher)
-      : comparator_(comparator), matcher_(matcher) {}
-
-  template <typename LhsContainer>
-  operator Matcher<LhsContainer>() const {
-    return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
-  }
-
-  template <typename LhsContainer>
-  class Impl : public MatcherInterface<LhsContainer> {
-   public:
-    typedef internal::StlContainerView<
-         GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
-    typedef typename LhsView::type LhsStlContainer;
-    typedef typename LhsView::const_reference LhsStlContainerReference;
-    // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
-    // so that we can match associative containers.
-    typedef typename RemoveConstFromKey<
-        typename LhsStlContainer::value_type>::type LhsValue;
-
-    Impl(const Comparator& comparator, const ContainerMatcher& matcher)
-        : comparator_(comparator), matcher_(matcher) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "(when sorted) ";
-      matcher_.DescribeTo(os);
-    }
-
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "(when sorted) ";
-      matcher_.DescribeNegationTo(os);
-    }
-
-    virtual bool MatchAndExplain(LhsContainer lhs,
-                                 MatchResultListener* listener) const {
-      LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
-      ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
-                                               lhs_stl_container.end());
-      ::std::sort(
-           sorted_container.begin(), sorted_container.end(), comparator_);
-
-      if (!listener->IsInterested()) {
-        // If the listener is not interested, we do not need to
-        // construct the inner explanation.
-        return matcher_.Matches(sorted_container);
-      }
-
-      *listener << "which is ";
-      UniversalPrint(sorted_container, listener->stream());
-      *listener << " when sorted";
-
-      StringMatchResultListener inner_listener;
-      const bool match = matcher_.MatchAndExplain(sorted_container,
-                                                  &inner_listener);
-      PrintIfNotEmpty(inner_listener.str(), listener->stream());
-      return match;
-    }
-
-   private:
-    const Comparator comparator_;
-    const Matcher<const ::std::vector<LhsValue>&> matcher_;
-
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
-  };
-
- private:
-  const Comparator comparator_;
-  const ContainerMatcher matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
-};
-
-// Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher
-// must be able to be safely cast to Matcher<tuple<const T1&, const
-// T2&> >, where T1 and T2 are the types of elements in the LHS
-// container and the RHS container respectively.
-template <typename TupleMatcher, typename RhsContainer>
-class PointwiseMatcher {
- public:
-  typedef internal::StlContainerView<RhsContainer> RhsView;
-  typedef typename RhsView::type RhsStlContainer;
-  typedef typename RhsStlContainer::value_type RhsValue;
-
-  // Like ContainerEq, we make a copy of rhs in case the elements in
-  // it are modified after this matcher is created.
-  PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
-      : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
-    // Makes sure the user doesn't instantiate this class template
-    // with a const or reference type.
-    (void)testing::StaticAssertTypeEq<RhsContainer,
-        GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
-  }
-
-  template <typename LhsContainer>
-  operator Matcher<LhsContainer>() const {
-    return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
-  }
-
-  template <typename LhsContainer>
-  class Impl : public MatcherInterface<LhsContainer> {
-   public:
-    typedef internal::StlContainerView<
-         GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
-    typedef typename LhsView::type LhsStlContainer;
-    typedef typename LhsView::const_reference LhsStlContainerReference;
-    typedef typename LhsStlContainer::value_type LhsValue;
-    // We pass the LHS value and the RHS value to the inner matcher by
-    // reference, as they may be expensive to copy.  We must use tuple
-    // instead of pair here, as a pair cannot hold references (C++ 98,
-    // 20.2.2 [lib.pairs]).
-    typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
-
-    Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
-        // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
-        : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
-          rhs_(rhs) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "contains " << rhs_.size()
-          << " values, where each value and its corresponding value in ";
-      UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
-      *os << " ";
-      mono_tuple_matcher_.DescribeTo(os);
-    }
-    virtual void DescribeNegationTo(::std::ostream* os) const {
-      *os << "doesn't contain exactly " << rhs_.size()
-          << " values, or contains a value x at some index i"
-          << " where x and the i-th value of ";
-      UniversalPrint(rhs_, os);
-      *os << " ";
-      mono_tuple_matcher_.DescribeNegationTo(os);
-    }
-
-    virtual bool MatchAndExplain(LhsContainer lhs,
-                                 MatchResultListener* listener) const {
-      LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
-      const size_t actual_size = lhs_stl_container.size();
-      if (actual_size != rhs_.size()) {
-        *listener << "which contains " << actual_size << " values";
-        return false;
-      }
-
-      typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
-      typename RhsStlContainer::const_iterator right = rhs_.begin();
-      for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
-        const InnerMatcherArg value_pair(*left, *right);
-
-        if (listener->IsInterested()) {
-          StringMatchResultListener inner_listener;
-          if (!mono_tuple_matcher_.MatchAndExplain(
-                  value_pair, &inner_listener)) {
-            *listener << "where the value pair (";
-            UniversalPrint(*left, listener->stream());
-            *listener << ", ";
-            UniversalPrint(*right, listener->stream());
-            *listener << ") at index #" << i << " don't match";
-            PrintIfNotEmpty(inner_listener.str(), listener->stream());
-            return false;
-          }
-        } else {
-          if (!mono_tuple_matcher_.Matches(value_pair))
-            return false;
-        }
-      }
-
-      return true;
-    }
-
-   private:
-    const Matcher<InnerMatcherArg> mono_tuple_matcher_;
-    const RhsStlContainer rhs_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
- private:
-  const TupleMatcher tuple_matcher_;
-  const RhsStlContainer rhs_;
-
-  GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
-};
-
-// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
-template <typename Container>
-class QuantifierMatcherImpl : public MatcherInterface<Container> {
- public:
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
-  typedef StlContainerView<RawContainer> View;
-  typedef typename View::type StlContainer;
-  typedef typename View::const_reference StlContainerReference;
-  typedef typename StlContainer::value_type Element;
-
-  template <typename InnerMatcher>
-  explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
-      : inner_matcher_(
-           testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
-
-  // Checks whether:
-  // * All elements in the container match, if all_elements_should_match.
-  // * Any element in the container matches, if !all_elements_should_match.
-  bool MatchAndExplainImpl(bool all_elements_should_match,
-                           Container container,
-                           MatchResultListener* listener) const {
-    StlContainerReference stl_container = View::ConstReference(container);
-    size_t i = 0;
-    for (typename StlContainer::const_iterator it = stl_container.begin();
-         it != stl_container.end(); ++it, ++i) {
-      StringMatchResultListener inner_listener;
-      const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
-
-      if (matches != all_elements_should_match) {
-        *listener << "whose element #" << i
-                  << (matches ? " matches" : " doesn't match");
-        PrintIfNotEmpty(inner_listener.str(), listener->stream());
-        return !all_elements_should_match;
-      }
-    }
-    return all_elements_should_match;
-  }
-
- protected:
-  const Matcher<const Element&> inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
-};
-
-// Implements Contains(element_matcher) for the given argument type Container.
-// Symmetric to EachMatcherImpl.
-template <typename Container>
-class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
- public:
-  template <typename InnerMatcher>
-  explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
-      : QuantifierMatcherImpl<Container>(inner_matcher) {}
-
-  // Describes what this matcher does.
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "contains at least one element that ";
-    this->inner_matcher_.DescribeTo(os);
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "doesn't contain any element that ";
-    this->inner_matcher_.DescribeTo(os);
-  }
-
-  virtual bool MatchAndExplain(Container container,
-                               MatchResultListener* listener) const {
-    return this->MatchAndExplainImpl(false, container, listener);
-  }
-
- private:
-  GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
-};
-
-// Implements Each(element_matcher) for the given argument type Container.
-// Symmetric to ContainsMatcherImpl.
-template <typename Container>
-class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
- public:
-  template <typename InnerMatcher>
-  explicit EachMatcherImpl(InnerMatcher inner_matcher)
-      : QuantifierMatcherImpl<Container>(inner_matcher) {}
-
-  // Describes what this matcher does.
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "only contains elements that ";
-    this->inner_matcher_.DescribeTo(os);
-  }
-
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "contains some element that ";
-    this->inner_matcher_.DescribeNegationTo(os);
-  }
-
-  virtual bool MatchAndExplain(Container container,
-                               MatchResultListener* listener) const {
-    return this->MatchAndExplainImpl(true, container, listener);
-  }
-
- private:
-  GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
-};
-
-// Implements polymorphic Contains(element_matcher).
-template <typename M>
-class ContainsMatcher {
- public:
-  explicit ContainsMatcher(M m) : inner_matcher_(m) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
-  }
-
- private:
-  const M inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
-};
-
-// Implements polymorphic Each(element_matcher).
-template <typename M>
-class EachMatcher {
- public:
-  explicit EachMatcher(M m) : inner_matcher_(m) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
-  }
-
- private:
-  const M inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(EachMatcher);
-};
-
-// Implements Key(inner_matcher) for the given argument pair type.
-// Key(inner_matcher) matches an std::pair whose 'first' field matches
-// inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
-// std::map that contains at least one element whose key is >= 5.
-template <typename PairType>
-class KeyMatcherImpl : public MatcherInterface<PairType> {
- public:
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
-  typedef typename RawPairType::first_type KeyType;
-
-  template <typename InnerMatcher>
-  explicit KeyMatcherImpl(InnerMatcher inner_matcher)
-      : inner_matcher_(
-          testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
-  }
-
-  // Returns true iff 'key_value.first' (the key) matches the inner matcher.
-  virtual bool MatchAndExplain(PairType key_value,
-                               MatchResultListener* listener) const {
-    StringMatchResultListener inner_listener;
-    const bool match = inner_matcher_.MatchAndExplain(key_value.first,
-                                                      &inner_listener);
-    const internal::string explanation = inner_listener.str();
-    if (explanation != "") {
-      *listener << "whose first field is a value " << explanation;
-    }
-    return match;
-  }
-
-  // Describes what this matcher does.
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "has a key that ";
-    inner_matcher_.DescribeTo(os);
-  }
-
-  // Describes what the negation of this matcher does.
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "doesn't have a key that ";
-    inner_matcher_.DescribeTo(os);
-  }
-
- private:
-  const Matcher<const KeyType&> inner_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
-};
-
-// Implements polymorphic Key(matcher_for_key).
-template <typename M>
-class KeyMatcher {
- public:
-  explicit KeyMatcher(M m) : matcher_for_key_(m) {}
-
-  template <typename PairType>
-  operator Matcher<PairType>() const {
-    return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
-  }
-
- private:
-  const M matcher_for_key_;
-
-  GTEST_DISALLOW_ASSIGN_(KeyMatcher);
-};
-
-// Implements Pair(first_matcher, second_matcher) for the given argument pair
-// type with its two matchers. See Pair() function below.
-template <typename PairType>
-class PairMatcherImpl : public MatcherInterface<PairType> {
- public:
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
-  typedef typename RawPairType::first_type FirstType;
-  typedef typename RawPairType::second_type SecondType;
-
-  template <typename FirstMatcher, typename SecondMatcher>
-  PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
-      : first_matcher_(
-            testing::SafeMatcherCast<const FirstType&>(first_matcher)),
-        second_matcher_(
-            testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
-  }
-
-  // Describes what this matcher does.
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "has a first field that ";
-    first_matcher_.DescribeTo(os);
-    *os << ", and has a second field that ";
-    second_matcher_.DescribeTo(os);
-  }
-
-  // Describes what the negation of this matcher does.
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    *os << "has a first field that ";
-    first_matcher_.DescribeNegationTo(os);
-    *os << ", or has a second field that ";
-    second_matcher_.DescribeNegationTo(os);
-  }
-
-  // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
-  // matches second_matcher.
-  virtual bool MatchAndExplain(PairType a_pair,
-                               MatchResultListener* listener) const {
-    if (!listener->IsInterested()) {
-      // If the listener is not interested, we don't need to construct the
-      // explanation.
-      return first_matcher_.Matches(a_pair.first) &&
-             second_matcher_.Matches(a_pair.second);
-    }
-    StringMatchResultListener first_inner_listener;
-    if (!first_matcher_.MatchAndExplain(a_pair.first,
-                                        &first_inner_listener)) {
-      *listener << "whose first field does not match";
-      PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
-      return false;
-    }
-    StringMatchResultListener second_inner_listener;
-    if (!second_matcher_.MatchAndExplain(a_pair.second,
-                                         &second_inner_listener)) {
-      *listener << "whose second field does not match";
-      PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
-      return false;
-    }
-    ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
-                   listener);
-    return true;
-  }
-
- private:
-  void ExplainSuccess(const internal::string& first_explanation,
-                      const internal::string& second_explanation,
-                      MatchResultListener* listener) const {
-    *listener << "whose both fields match";
-    if (first_explanation != "") {
-      *listener << ", where the first field is a value " << first_explanation;
-    }
-    if (second_explanation != "") {
-      *listener << ", ";
-      if (first_explanation != "") {
-        *listener << "and ";
-      } else {
-        *listener << "where ";
-      }
-      *listener << "the second field is a value " << second_explanation;
-    }
-  }
-
-  const Matcher<const FirstType&> first_matcher_;
-  const Matcher<const SecondType&> second_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
-};
-
-// Implements polymorphic Pair(first_matcher, second_matcher).
-template <typename FirstMatcher, typename SecondMatcher>
-class PairMatcher {
- public:
-  PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
-      : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
-
-  template <typename PairType>
-  operator Matcher<PairType> () const {
-    return MakeMatcher(
-        new PairMatcherImpl<PairType>(
-            first_matcher_, second_matcher_));
-  }
-
- private:
-  const FirstMatcher first_matcher_;
-  const SecondMatcher second_matcher_;
-
-  GTEST_DISALLOW_ASSIGN_(PairMatcher);
-};
-
-// Implements ElementsAre() and ElementsAreArray().
-template <typename Container>
-class ElementsAreMatcherImpl : public MatcherInterface<Container> {
- public:
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
-  typedef internal::StlContainerView<RawContainer> View;
-  typedef typename View::type StlContainer;
-  typedef typename View::const_reference StlContainerReference;
-  typedef typename StlContainer::value_type Element;
-
-  // Constructs the matcher from a sequence of element values or
-  // element matchers.
-  template <typename InputIter>
-  ElementsAreMatcherImpl(InputIter first, InputIter last) {
-    while (first != last) {
-      matchers_.push_back(MatcherCast<const Element&>(*first++));
-    }
-  }
-
-  // Describes what this matcher does.
-  virtual void DescribeTo(::std::ostream* os) const {
-    if (count() == 0) {
-      *os << "is empty";
-    } else if (count() == 1) {
-      *os << "has 1 element that ";
-      matchers_[0].DescribeTo(os);
-    } else {
-      *os << "has " << Elements(count()) << " where\n";
-      for (size_t i = 0; i != count(); ++i) {
-        *os << "element #" << i << " ";
-        matchers_[i].DescribeTo(os);
-        if (i + 1 < count()) {
-          *os << ",\n";
-        }
-      }
-    }
-  }
-
-  // Describes what the negation of this matcher does.
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    if (count() == 0) {
-      *os << "isn't empty";
-      return;
-    }
-
-    *os << "doesn't have " << Elements(count()) << ", or\n";
-    for (size_t i = 0; i != count(); ++i) {
-      *os << "element #" << i << " ";
-      matchers_[i].DescribeNegationTo(os);
-      if (i + 1 < count()) {
-        *os << ", or\n";
-      }
-    }
-  }
-
-  virtual bool MatchAndExplain(Container container,
-                               MatchResultListener* listener) const {
-    // To work with stream-like "containers", we must only walk
-    // through the elements in one pass.
-
-    const bool listener_interested = listener->IsInterested();
-
-    // explanations[i] is the explanation of the element at index i.
-    ::std::vector<internal::string> explanations(count());
-    StlContainerReference stl_container = View::ConstReference(container);
-    typename StlContainer::const_iterator it = stl_container.begin();
-    size_t exam_pos = 0;
-    bool mismatch_found = false;  // Have we found a mismatched element yet?
-
-    // Go through the elements and matchers in pairs, until we reach
-    // the end of either the elements or the matchers, or until we find a
-    // mismatch.
-    for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
-      bool match;  // Does the current element match the current matcher?
-      if (listener_interested) {
-        StringMatchResultListener s;
-        match = matchers_[exam_pos].MatchAndExplain(*it, &s);
-        explanations[exam_pos] = s.str();
-      } else {
-        match = matchers_[exam_pos].Matches(*it);
-      }
-
-      if (!match) {
-        mismatch_found = true;
-        break;
-      }
-    }
-    // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
-
-    // Find how many elements the actual container has.  We avoid
-    // calling size() s.t. this code works for stream-like "containers"
-    // that don't define size().
-    size_t actual_count = exam_pos;
-    for (; it != stl_container.end(); ++it) {
-      ++actual_count;
-    }
-
-    if (actual_count != count()) {
-      // The element count doesn't match.  If the container is empty,
-      // there's no need to explain anything as Google Mock already
-      // prints the empty container.  Otherwise we just need to show
-      // how many elements there actually are.
-      if (listener_interested && (actual_count != 0)) {
-        *listener << "which has " << Elements(actual_count);
-      }
-      return false;
-    }
-
-    if (mismatch_found) {
-      // The element count matches, but the exam_pos-th element doesn't match.
-      if (listener_interested) {
-        *listener << "whose element #" << exam_pos << " doesn't match";
-        PrintIfNotEmpty(explanations[exam_pos], listener->stream());
-      }
-      return false;
-    }
-
-    // Every element matches its expectation.  We need to explain why
-    // (the obvious ones can be skipped).
-    if (listener_interested) {
-      bool reason_printed = false;
-      for (size_t i = 0; i != count(); ++i) {
-        const internal::string& s = explanations[i];
-        if (!s.empty()) {
-          if (reason_printed) {
-            *listener << ",\nand ";
-          }
-          *listener << "whose element #" << i << " matches, " << s;
-          reason_printed = true;
-        }
-      }
-    }
-    return true;
-  }
-
- private:
-  static Message Elements(size_t count) {
-    return Message() << count << (count == 1 ? " element" : " elements");
-  }
-
-  size_t count() const { return matchers_.size(); }
-
-  ::std::vector<Matcher<const Element&> > matchers_;
-
-  GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
-};
-
-// Connectivity matrix of (elements X matchers), in element-major order.
-// Initially, there are no edges.
-// Use NextGraph() to iterate over all possible edge configurations.
-// Use Randomize() to generate a random edge configuration.
-class GTEST_API_ MatchMatrix {
- public:
-  MatchMatrix(size_t num_elements, size_t num_matchers)
-      : num_elements_(num_elements),
-        num_matchers_(num_matchers),
-        matched_(num_elements_* num_matchers_, 0) {
-  }
-
-  size_t LhsSize() const { return num_elements_; }
-  size_t RhsSize() const { return num_matchers_; }
-  bool HasEdge(size_t ilhs, size_t irhs) const {
-    return matched_[SpaceIndex(ilhs, irhs)] == 1;
-  }
-  void SetEdge(size_t ilhs, size_t irhs, bool b) {
-    matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
-  }
-
-  // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
-  // adds 1 to that number; returns false if incrementing the graph left it
-  // empty.
-  bool NextGraph();
-
-  void Randomize();
-
-  string DebugString() const;
-
- private:
-  size_t SpaceIndex(size_t ilhs, size_t irhs) const {
-    return ilhs * num_matchers_ + irhs;
-  }
-
-  size_t num_elements_;
-  size_t num_matchers_;
-
-  // Each element is a char interpreted as bool. They are stored as a
-  // flattened array in lhs-major order, use 'SpaceIndex()' to translate
-  // a (ilhs, irhs) matrix coordinate into an offset.
-  ::std::vector<char> matched_;
-};
-
-typedef ::std::pair<size_t, size_t> ElementMatcherPair;
-typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
-
-// Returns a maximum bipartite matching for the specified graph 'g'.
-// The matching is represented as a vector of {element, matcher} pairs.
-GTEST_API_ ElementMatcherPairs
-FindMaxBipartiteMatching(const MatchMatrix& g);
-
-GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
-                            MatchResultListener* listener);
-
-// Untyped base class for implementing UnorderedElementsAre.  By
-// putting logic that's not specific to the element type here, we
-// reduce binary bloat and increase compilation speed.
-class GTEST_API_ UnorderedElementsAreMatcherImplBase {
- protected:
-  // A vector of matcher describers, one for each element matcher.
-  // Does not own the describers (and thus can be used only when the
-  // element matchers are alive).
-  typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
-
-  // Describes this UnorderedElementsAre matcher.
-  void DescribeToImpl(::std::ostream* os) const;
-
-  // Describes the negation of this UnorderedElementsAre matcher.
-  void DescribeNegationToImpl(::std::ostream* os) const;
-
-  bool VerifyAllElementsAndMatchersAreMatched(
-      const ::std::vector<string>& element_printouts,
-      const MatchMatrix& matrix,
-      MatchResultListener* listener) const;
-
-  MatcherDescriberVec& matcher_describers() {
-    return matcher_describers_;
-  }
-
-  static Message Elements(size_t n) {
-    return Message() << n << " element" << (n == 1 ? "" : "s");
-  }
-
- private:
-  MatcherDescriberVec matcher_describers_;
-
-  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
-};
-
-// Implements unordered ElementsAre and unordered ElementsAreArray.
-template <typename Container>
-class UnorderedElementsAreMatcherImpl
-    : public MatcherInterface<Container>,
-      public UnorderedElementsAreMatcherImplBase {
- public:
-  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
-  typedef internal::StlContainerView<RawContainer> View;
-  typedef typename View::type StlContainer;
-  typedef typename View::const_reference StlContainerReference;
-  typedef typename StlContainer::const_iterator StlContainerConstIterator;
-  typedef typename StlContainer::value_type Element;
-
-  // Constructs the matcher from a sequence of element values or
-  // element matchers.
-  template <typename InputIter>
-  UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
-    for (; first != last; ++first) {
-      matchers_.push_back(MatcherCast<const Element&>(*first));
-      matcher_describers().push_back(matchers_.back().GetDescriber());
-    }
-  }
-
-  // Describes what this matcher does.
-  virtual void DescribeTo(::std::ostream* os) const {
-    return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
-  }
-
-  // Describes what the negation of this matcher does.
-  virtual void DescribeNegationTo(::std::ostream* os) const {
-    return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
-  }
-
-  virtual bool MatchAndExplain(Container container,
-                               MatchResultListener* listener) const {
-    StlContainerReference stl_container = View::ConstReference(container);
-    ::std::vector<string> element_printouts;
-    MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
-                                         stl_container.end(),
-                                         &element_printouts,
-                                         listener);
-
-    const size_t actual_count = matrix.LhsSize();
-    if (actual_count == 0 && matchers_.empty()) {
-      return true;
-    }
-    if (actual_count != matchers_.size()) {
-      // The element count doesn't match.  If the container is empty,
-      // there's no need to explain anything as Google Mock already
-      // prints the empty container. Otherwise we just need to show
-      // how many elements there actually are.
-      if (actual_count != 0 && listener->IsInterested()) {
-        *listener << "which has " << Elements(actual_count);
-      }
-      return false;
-    }
-
-    return VerifyAllElementsAndMatchersAreMatched(element_printouts,
-                                                  matrix, listener) &&
-           FindPairing(matrix, listener);
-  }
-
- private:
-  typedef ::std::vector<Matcher<const Element&> > MatcherVec;
-
-  template <typename ElementIter>
-  MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
-                              ::std::vector<string>* element_printouts,
-                              MatchResultListener* listener) const {
-    element_printouts->clear();
-    ::std::vector<char> did_match;
-    size_t num_elements = 0;
-    for (; elem_first != elem_last; ++num_elements, ++elem_first) {
-      if (listener->IsInterested()) {
-        element_printouts->push_back(PrintToString(*elem_first));
-      }
-      for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
-        did_match.push_back(Matches(matchers_[irhs])(*elem_first));
-      }
-    }
-
-    MatchMatrix matrix(num_elements, matchers_.size());
-    ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
-    for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
-      for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
-        matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
-      }
-    }
-    return matrix;
-  }
-
-  MatcherVec matchers_;
-
-  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
-};
-
-// Functor for use in TransformTuple.
-// Performs MatcherCast<Target> on an input argument of any type.
-template <typename Target>
-struct CastAndAppendTransform {
-  template <typename Arg>
-  Matcher<Target> operator()(const Arg& a) const {
-    return MatcherCast<Target>(a);
-  }
-};
-
-// Implements UnorderedElementsAre.
-template <typename MatcherTuple>
-class UnorderedElementsAreMatcher {
- public:
-  explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
-      : matchers_(args) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
-    typedef typename internal::StlContainerView<RawContainer>::type View;
-    typedef typename View::value_type Element;
-    typedef ::std::vector<Matcher<const Element&> > MatcherVec;
-    MatcherVec matchers;
-    matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
-    TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
-                         ::std::back_inserter(matchers));
-    return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
-                           matchers.begin(), matchers.end()));
-  }
-
- private:
-  const MatcherTuple matchers_;
-  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
-};
-
-// Implements ElementsAre.
-template <typename MatcherTuple>
-class ElementsAreMatcher {
- public:
-  explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
-    typedef typename internal::StlContainerView<RawContainer>::type View;
-    typedef typename View::value_type Element;
-    typedef ::std::vector<Matcher<const Element&> > MatcherVec;
-    MatcherVec matchers;
-    matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
-    TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
-                         ::std::back_inserter(matchers));
-    return MakeMatcher(new ElementsAreMatcherImpl<Container>(
-                           matchers.begin(), matchers.end()));
-  }
-
- private:
-  const MatcherTuple matchers_;
-  GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
-};
-
-// Implements UnorderedElementsAreArray().
-template <typename T>
-class UnorderedElementsAreArrayMatcher {
- public:
-  UnorderedElementsAreArrayMatcher() {}
-
-  template <typename Iter>
-  UnorderedElementsAreArrayMatcher(Iter first, Iter last)
-      : matchers_(first, last) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    return MakeMatcher(
-        new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
-                                                       matchers_.end()));
-  }
-
- private:
-  ::std::vector<T> matchers_;
-
-  GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
-};
-
-// Implements ElementsAreArray().
-template <typename T>
-class ElementsAreArrayMatcher {
- public:
-  template <typename Iter>
-  ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
-
-  template <typename Container>
-  operator Matcher<Container>() const {
-    return MakeMatcher(new ElementsAreMatcherImpl<Container>(
-        matchers_.begin(), matchers_.end()));
-  }
-
- private:
-  const ::std::vector<T> matchers_;
-
-  GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
-};
-
-// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
-// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
-// second) is a polymorphic matcher that matches a value x iff tm
-// matches tuple (x, second).  Useful for implementing
-// UnorderedPointwise() in terms of UnorderedElementsAreArray().
-//
-// BoundSecondMatcher is copyable and assignable, as we need to put
-// instances of this class in a vector when implementing
-// UnorderedPointwise().
-template <typename Tuple2Matcher, typename Second>
-class BoundSecondMatcher {
- public:
-  BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
-      : tuple2_matcher_(tm), second_value_(second) {}
-
-  template <typename T>
-  operator Matcher<T>() const {
-    return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
-  }
-
-  // We have to define this for UnorderedPointwise() to compile in
-  // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
-  // which requires the elements to be assignable in C++98.  The
-  // compiler cannot generate the operator= for us, as Tuple2Matcher
-  // and Second may not be assignable.
-  //
-  // However, this should never be called, so the implementation just
-  // need to assert.
-  void operator=(const BoundSecondMatcher& /*rhs*/) {
-    GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
-  }
-
- private:
-  template <typename T>
-  class Impl : public MatcherInterface<T> {
-   public:
-    typedef ::testing::tuple<T, Second> ArgTuple;
-
-    Impl(const Tuple2Matcher& tm, const Second& second)
-        : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
-          second_value_(second) {}
-
-    virtual void DescribeTo(::std::ostream* os) const {
-      *os << "and ";
-      UniversalPrint(second_value_, os);
-      *os << " ";
-      mono_tuple2_matcher_.DescribeTo(os);
-    }
-
-    virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
-      return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
-                                                  listener);
-    }
-
-   private:
-    const Matcher<const ArgTuple&> mono_tuple2_matcher_;
-    const Second second_value_;
-
-    GTEST_DISALLOW_ASSIGN_(Impl);
-  };
-
-  const Tuple2Matcher tuple2_matcher_;
-  const Second second_value_;
-};
-
-// Given a 2-tuple matcher tm and a value second,
-// MatcherBindSecond(tm, second) returns a matcher that matches a
-// value x iff tm matches tuple (x, second).  Useful for implementing
-// UnorderedPointwise() in terms of UnorderedElementsAreArray().
-template <typename Tuple2Matcher, typename Second>
-BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
-    const Tuple2Matcher& tm, const Second& second) {
-  return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
-}
-
-// Returns the description for a matcher defined using the MATCHER*()
-// macro where the user-supplied description string is "", if
-// 'negation' is false; otherwise returns the description of the
-// negation of the matcher.  'param_values' contains a list of strings
-// that are the print-out of the matcher's parameters.
-GTEST_API_ string FormatMatcherDescription(bool negation,
-                                           const char* matcher_name,
-                                           const Strings& param_values);
-
-}  // namespace internal
-
-// ElementsAreArray(first, last)
-// ElementsAreArray(pointer, count)
-// ElementsAreArray(array)
-// ElementsAreArray(container)
-// ElementsAreArray({ e1, e2, ..., en })
-//
-// The ElementsAreArray() functions are like ElementsAre(...), except
-// that they are given a homogeneous sequence rather than taking each
-// element as a function argument. The sequence can be specified as an
-// array, a pointer and count, a vector, an initializer list, or an
-// STL iterator range. In each of these cases, the underlying sequence
-// can be either a sequence of values or a sequence of matchers.
-//
-// All forms of ElementsAreArray() make a copy of the input matcher sequence.
-
-template <typename Iter>
-inline internal::ElementsAreArrayMatcher<
-    typename ::std::iterator_traits<Iter>::value_type>
-ElementsAreArray(Iter first, Iter last) {
-  typedef typename ::std::iterator_traits<Iter>::value_type T;
-  return internal::ElementsAreArrayMatcher<T>(first, last);
-}
-
-template <typename T>
-inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
-    const T* pointer, size_t count) {
-  return ElementsAreArray(pointer, pointer + count);
-}
-
-template <typename T, size_t N>
-inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
-    const T (&array)[N]) {
-  return ElementsAreArray(array, N);
-}
-
-template <typename Container>
-inline internal::ElementsAreArrayMatcher<typename Container::value_type>
-ElementsAreArray(const Container& container) {
-  return ElementsAreArray(container.begin(), container.end());
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-template <typename T>
-inline internal::ElementsAreArrayMatcher<T>
-ElementsAreArray(::std::initializer_list<T> xs) {
-  return ElementsAreArray(xs.begin(), xs.end());
-}
-#endif
-
-// UnorderedElementsAreArray(first, last)
-// UnorderedElementsAreArray(pointer, count)
-// UnorderedElementsAreArray(array)
-// UnorderedElementsAreArray(container)
-// UnorderedElementsAreArray({ e1, e2, ..., en })
-//
-// The UnorderedElementsAreArray() functions are like
-// ElementsAreArray(...), but allow matching the elements in any order.
-template <typename Iter>
-inline internal::UnorderedElementsAreArrayMatcher<
-    typename ::std::iterator_traits<Iter>::value_type>
-UnorderedElementsAreArray(Iter first, Iter last) {
-  typedef typename ::std::iterator_traits<Iter>::value_type T;
-  return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
-}
-
-template <typename T>
-inline internal::UnorderedElementsAreArrayMatcher<T>
-UnorderedElementsAreArray(const T* pointer, size_t count) {
-  return UnorderedElementsAreArray(pointer, pointer + count);
-}
-
-template <typename T, size_t N>
-inline internal::UnorderedElementsAreArrayMatcher<T>
-UnorderedElementsAreArray(const T (&array)[N]) {
-  return UnorderedElementsAreArray(array, N);
-}
-
-template <typename Container>
-inline internal::UnorderedElementsAreArrayMatcher<
-    typename Container::value_type>
-UnorderedElementsAreArray(const Container& container) {
-  return UnorderedElementsAreArray(container.begin(), container.end());
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-template <typename T>
-inline internal::UnorderedElementsAreArrayMatcher<T>
-UnorderedElementsAreArray(::std::initializer_list<T> xs) {
-  return UnorderedElementsAreArray(xs.begin(), xs.end());
-}
-#endif
-
-// _ is a matcher that matches anything of any type.
-//
-// This definition is fine as:
-//
-//   1. The C++ standard permits using the name _ in a namespace that
-//      is not the global namespace or ::std.
-//   2. The AnythingMatcher class has no data member or constructor,
-//      so it's OK to create global variables of this type.
-//   3. c-style has approved of using _ in this case.
-const internal::AnythingMatcher _ = {};
-// Creates a matcher that matches any value of the given type T.
-template <typename T>
-inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
-
-// Creates a matcher that matches any value of the given type T.
-template <typename T>
-inline Matcher<T> An() { return A<T>(); }
-
-// Creates a polymorphic matcher that matches anything equal to x.
-// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
-// wouldn't compile.
-template <typename T>
-inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
-
-// Constructs a Matcher<T> from a 'value' of type T.  The constructed
-// matcher matches any value that's equal to 'value'.
-template <typename T>
-Matcher<T>::Matcher(T value) { *this = Eq(value); }
-
-// Creates a monomorphic matcher that matches anything with type Lhs
-// and equal to rhs.  A user may need to use this instead of Eq(...)
-// in order to resolve an overloading ambiguity.
-//
-// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
-// or Matcher<T>(x), but more readable than the latter.
-//
-// We could define similar monomorphic matchers for other comparison
-// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
-// it yet as those are used much less than Eq() in practice.  A user
-// can always write Matcher<T>(Lt(5)) to be explicit about the type,
-// for example.
-template <typename Lhs, typename Rhs>
-inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
-
-// Creates a polymorphic matcher that matches anything >= x.
-template <typename Rhs>
-inline internal::GeMatcher<Rhs> Ge(Rhs x) {
-  return internal::GeMatcher<Rhs>(x);
-}
-
-// Creates a polymorphic matcher that matches anything > x.
-template <typename Rhs>
-inline internal::GtMatcher<Rhs> Gt(Rhs x) {
-  return internal::GtMatcher<Rhs>(x);
-}
-
-// Creates a polymorphic matcher that matches anything <= x.
-template <typename Rhs>
-inline internal::LeMatcher<Rhs> Le(Rhs x) {
-  return internal::LeMatcher<Rhs>(x);
-}
-
-// Creates a polymorphic matcher that matches anything < x.
-template <typename Rhs>
-inline internal::LtMatcher<Rhs> Lt(Rhs x) {
-  return internal::LtMatcher<Rhs>(x);
-}
-
-// Creates a polymorphic matcher that matches anything != x.
-template <typename Rhs>
-inline internal::NeMatcher<Rhs> Ne(Rhs x) {
-  return internal::NeMatcher<Rhs>(x);
-}
-
-// Creates a polymorphic matcher that matches any NULL pointer.
-inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
-  return MakePolymorphicMatcher(internal::IsNullMatcher());
-}
-
-// Creates a polymorphic matcher that matches any non-NULL pointer.
-// This is convenient as Not(NULL) doesn't compile (the compiler
-// thinks that that expression is comparing a pointer with an integer).
-inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
-  return MakePolymorphicMatcher(internal::NotNullMatcher());
-}
-
-// Creates a polymorphic matcher that matches any argument that
-// references variable x.
-template <typename T>
-inline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT
-  return internal::RefMatcher<T&>(x);
-}
-
-// Creates a matcher that matches any double argument approximately
-// equal to rhs, where two NANs are considered unequal.
-inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
-  return internal::FloatingEqMatcher<double>(rhs, false);
-}
-
-// Creates a matcher that matches any double argument approximately
-// equal to rhs, including NaN values when rhs is NaN.
-inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
-  return internal::FloatingEqMatcher<double>(rhs, true);
-}
-
-// Creates a matcher that matches any double argument approximately equal to
-// rhs, up to the specified max absolute error bound, where two NANs are
-// considered unequal.  The max absolute error bound must be non-negative.
-inline internal::FloatingEqMatcher<double> DoubleNear(
-    double rhs, double max_abs_error) {
-  return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
-}
-
-// Creates a matcher that matches any double argument approximately equal to
-// rhs, up to the specified max absolute error bound, including NaN values when
-// rhs is NaN.  The max absolute error bound must be non-negative.
-inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
-    double rhs, double max_abs_error) {
-  return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
-}
-
-// Creates a matcher that matches any float argument approximately
-// equal to rhs, where two NANs are considered unequal.
-inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
-  return internal::FloatingEqMatcher<float>(rhs, false);
-}
-
-// Creates a matcher that matches any float argument approximately
-// equal to rhs, including NaN values when rhs is NaN.
-inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
-  return internal::FloatingEqMatcher<float>(rhs, true);
-}
-
-// Creates a matcher that matches any float argument approximately equal to
-// rhs, up to the specified max absolute error bound, where two NANs are
-// considered unequal.  The max absolute error bound must be non-negative.
-inline internal::FloatingEqMatcher<float> FloatNear(
-    float rhs, float max_abs_error) {
-  return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
-}
-
-// Creates a matcher that matches any float argument approximately equal to
-// rhs, up to the specified max absolute error bound, including NaN values when
-// rhs is NaN.  The max absolute error bound must be non-negative.
-inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
-    float rhs, float max_abs_error) {
-  return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
-}
-
-// Creates a matcher that matches a pointer (raw or smart) that points
-// to a value that matches inner_matcher.
-template <typename InnerMatcher>
-inline internal::PointeeMatcher<InnerMatcher> Pointee(
-    const InnerMatcher& inner_matcher) {
-  return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
-}
-
-// Creates a matcher that matches a pointer or reference that matches
-// inner_matcher when dynamic_cast<To> is applied.
-// The result of dynamic_cast<To> is forwarded to the inner matcher.
-// If To is a pointer and the cast fails, the inner matcher will receive NULL.
-// If To is a reference and the cast fails, this matcher returns false
-// immediately.
-template <typename To>
-inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
-WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
-  return MakePolymorphicMatcher(
-      internal::WhenDynamicCastToMatcher<To>(inner_matcher));
-}
-
-// Creates a matcher that matches an object whose given field matches
-// 'matcher'.  For example,
-//   Field(&Foo::number, Ge(5))
-// matches a Foo object x iff x.number >= 5.
-template <typename Class, typename FieldType, typename FieldMatcher>
-inline PolymorphicMatcher<
-  internal::FieldMatcher<Class, FieldType> > Field(
-    FieldType Class::*field, const FieldMatcher& matcher) {
-  return MakePolymorphicMatcher(
-      internal::FieldMatcher<Class, FieldType>(
-          field, MatcherCast<const FieldType&>(matcher)));
-  // The call to MatcherCast() is required for supporting inner
-  // matchers of compatible types.  For example, it allows
-  //   Field(&Foo::bar, m)
-  // to compile where bar is an int32 and m is a matcher for int64.
-}
-
-// Creates a matcher that matches an object whose given property
-// matches 'matcher'.  For example,
-//   Property(&Foo::str, StartsWith("hi"))
-// matches a Foo object x iff x.str() starts with "hi".
-template <typename Class, typename PropertyType, typename PropertyMatcher>
-inline PolymorphicMatcher<
-  internal::PropertyMatcher<Class, PropertyType> > Property(
-    PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
-  return MakePolymorphicMatcher(
-      internal::PropertyMatcher<Class, PropertyType>(
-          property,
-          MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
-  // The call to MatcherCast() is required for supporting inner
-  // matchers of compatible types.  For example, it allows
-  //   Property(&Foo::bar, m)
-  // to compile where bar() returns an int32 and m is a matcher for int64.
-}
-
-// Creates a matcher that matches an object iff the result of applying
-// a callable to x matches 'matcher'.
-// For example,
-//   ResultOf(f, StartsWith("hi"))
-// matches a Foo object x iff f(x) starts with "hi".
-// callable parameter can be a function, function pointer, or a functor.
-// Callable has to satisfy the following conditions:
-//   * It is required to keep no state affecting the results of
-//     the calls on it and make no assumptions about how many calls
-//     will be made. Any state it keeps must be protected from the
-//     concurrent access.
-//   * If it is a function object, it has to define type result_type.
-//     We recommend deriving your functor classes from std::unary_function.
-template <typename Callable, typename ResultOfMatcher>
-internal::ResultOfMatcher<Callable> ResultOf(
-    Callable callable, const ResultOfMatcher& matcher) {
-  return internal::ResultOfMatcher<Callable>(
-          callable,
-          MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
-              matcher));
-  // The call to MatcherCast() is required for supporting inner
-  // matchers of compatible types.  For example, it allows
-  //   ResultOf(Function, m)
-  // to compile where Function() returns an int32 and m is a matcher for int64.
-}
-
-// String matchers.
-
-// Matches a string equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
-    StrEq(const internal::string& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
-      str, true, true));
-}
-
-// Matches a string not equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
-    StrNe(const internal::string& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
-      str, false, true));
-}
-
-// Matches a string equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
-    StrCaseEq(const internal::string& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
-      str, true, false));
-}
-
-// Matches a string not equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
-    StrCaseNe(const internal::string& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
-      str, false, false));
-}
-
-// Creates a matcher that matches any string, std::string, or C string
-// that contains the given substring.
-inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
-    HasSubstr(const internal::string& substring) {
-  return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
-      substring));
-}
-
-// Matches a string that starts with 'prefix' (case-sensitive).
-inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
-    StartsWith(const internal::string& prefix) {
-  return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
-      prefix));
-}
-
-// Matches a string that ends with 'suffix' (case-sensitive).
-inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
-    EndsWith(const internal::string& suffix) {
-  return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
-      suffix));
-}
-
-// Matches a string that fully matches regular expression 'regex'.
-// The matcher takes ownership of 'regex'.
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
-    const internal::RE* regex) {
-  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
-}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
-    const internal::string& regex) {
-  return MatchesRegex(new internal::RE(regex));
-}
-
-// Matches a string that contains regular expression 'regex'.
-// The matcher takes ownership of 'regex'.
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
-    const internal::RE* regex) {
-  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
-}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
-    const internal::string& regex) {
-  return ContainsRegex(new internal::RE(regex));
-}
-
-#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
-// Wide string matchers.
-
-// Matches a string equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
-    StrEq(const internal::wstring& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
-      str, true, true));
-}
-
-// Matches a string not equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
-    StrNe(const internal::wstring& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
-      str, false, true));
-}
-
-// Matches a string equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
-    StrCaseEq(const internal::wstring& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
-      str, true, false));
-}
-
-// Matches a string not equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
-    StrCaseNe(const internal::wstring& str) {
-  return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
-      str, false, false));
-}
-
-// Creates a matcher that matches any wstring, std::wstring, or C wide string
-// that contains the given substring.
-inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
-    HasSubstr(const internal::wstring& substring) {
-  return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
-      substring));
-}
-
-// Matches a string that starts with 'prefix' (case-sensitive).
-inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
-    StartsWith(const internal::wstring& prefix) {
-  return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
-      prefix));
-}
-
-// Matches a string that ends with 'suffix' (case-sensitive).
-inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
-    EndsWith(const internal::wstring& suffix) {
-  return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
-      suffix));
-}
-
-#endif  // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
-
-// Creates a polymorphic matcher that matches a 2-tuple where the
-// first field == the second field.
-inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
-
-// Creates a polymorphic matcher that matches a 2-tuple where the
-// first field >= the second field.
-inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
-
-// Creates a polymorphic matcher that matches a 2-tuple where the
-// first field > the second field.
-inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
-
-// Creates a polymorphic matcher that matches a 2-tuple where the
-// first field <= the second field.
-inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
-
-// Creates a polymorphic matcher that matches a 2-tuple where the
-// first field < the second field.
-inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
-
-// Creates a polymorphic matcher that matches a 2-tuple where the
-// first field != the second field.
-inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
-
-// Creates a matcher that matches any value of type T that m doesn't
-// match.
-template <typename InnerMatcher>
-inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
-  return internal::NotMatcher<InnerMatcher>(m);
-}
-
-// Returns a matcher that matches anything that satisfies the given
-// predicate.  The predicate can be any unary function or functor
-// whose return type can be implicitly converted to bool.
-template <typename Predicate>
-inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
-Truly(Predicate pred) {
-  return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
-}
-
-// Returns a matcher that matches the container size. The container must
-// support both size() and size_type which all STL-like containers provide.
-// Note that the parameter 'size' can be a value of type size_type as well as
-// matcher. For instance:
-//   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
-//   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
-template <typename SizeMatcher>
-inline internal::SizeIsMatcher<SizeMatcher>
-SizeIs(const SizeMatcher& size_matcher) {
-  return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
-}
-
-// Returns a matcher that matches the distance between the container's begin()
-// iterator and its end() iterator, i.e. the size of the container. This matcher
-// can be used instead of SizeIs with containers such as std::forward_list which
-// do not implement size(). The container must provide const_iterator (with
-// valid iterator_traits), begin() and end().
-template <typename DistanceMatcher>
-inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
-BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
-  return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
-}
-
-// Returns a matcher that matches an equal container.
-// This matcher behaves like Eq(), but in the event of mismatch lists the
-// values that are included in one container but not the other. (Duplicate
-// values and order differences are not explained.)
-template <typename Container>
-inline PolymorphicMatcher<internal::ContainerEqMatcher<  // NOLINT
-                            GTEST_REMOVE_CONST_(Container)> >
-    ContainerEq(const Container& rhs) {
-  // This following line is for working around a bug in MSVC 8.0,
-  // which causes Container to be a const type sometimes.
-  typedef GTEST_REMOVE_CONST_(Container) RawContainer;
-  return MakePolymorphicMatcher(
-      internal::ContainerEqMatcher<RawContainer>(rhs));
-}
-
-// Returns a matcher that matches a container that, when sorted using
-// the given comparator, matches container_matcher.
-template <typename Comparator, typename ContainerMatcher>
-inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
-WhenSortedBy(const Comparator& comparator,
-             const ContainerMatcher& container_matcher) {
-  return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
-      comparator, container_matcher);
-}
-
-// Returns a matcher that matches a container that, when sorted using
-// the < operator, matches container_matcher.
-template <typename ContainerMatcher>
-inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
-WhenSorted(const ContainerMatcher& container_matcher) {
-  return
-      internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
-          internal::LessComparator(), container_matcher);
-}
-
-// Matches an STL-style container or a native array that contains the
-// same number of elements as in rhs, where its i-th element and rhs's
-// i-th element (as a pair) satisfy the given pair matcher, for all i.
-// TupleMatcher must be able to be safely cast to Matcher<tuple<const
-// T1&, const T2&> >, where T1 and T2 are the types of elements in the
-// LHS container and the RHS container respectively.
-template <typename TupleMatcher, typename Container>
-inline internal::PointwiseMatcher<TupleMatcher,
-                                  GTEST_REMOVE_CONST_(Container)>
-Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
-  // This following line is for working around a bug in MSVC 8.0,
-  // which causes Container to be a const type sometimes (e.g. when
-  // rhs is a const int[])..
-  typedef GTEST_REMOVE_CONST_(Container) RawContainer;
-  return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
-      tuple_matcher, rhs);
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-
-// Supports the Pointwise(m, {a, b, c}) syntax.
-template <typename TupleMatcher, typename T>
-inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
-    const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
-  return Pointwise(tuple_matcher, std::vector<T>(rhs));
-}
-
-#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
-
-// UnorderedPointwise(pair_matcher, rhs) matches an STL-style
-// container or a native array that contains the same number of
-// elements as in rhs, where in some permutation of the container, its
-// i-th element and rhs's i-th element (as a pair) satisfy the given
-// pair matcher, for all i.  Tuple2Matcher must be able to be safely
-// cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
-// the types of elements in the LHS container and the RHS container
-// respectively.
-//
-// This is like Pointwise(pair_matcher, rhs), except that the element
-// order doesn't matter.
-template <typename Tuple2Matcher, typename RhsContainer>
-inline internal::UnorderedElementsAreArrayMatcher<
-    typename internal::BoundSecondMatcher<
-        Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
-                           RhsContainer)>::type::value_type> >
-UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
-                   const RhsContainer& rhs_container) {
-  // This following line is for working around a bug in MSVC 8.0,
-  // which causes RhsContainer to be a const type sometimes (e.g. when
-  // rhs_container is a const int[]).
-  typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
-
-  // RhsView allows the same code to handle RhsContainer being a
-  // STL-style container and it being a native C-style array.
-  typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
-  typedef typename RhsView::type RhsStlContainer;
-  typedef typename RhsStlContainer::value_type Second;
-  const RhsStlContainer& rhs_stl_container =
-      RhsView::ConstReference(rhs_container);
-
-  // Create a matcher for each element in rhs_container.
-  ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
-  for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
-       it != rhs_stl_container.end(); ++it) {
-    matchers.push_back(
-        internal::MatcherBindSecond(tuple2_matcher, *it));
-  }
-
-  // Delegate the work to UnorderedElementsAreArray().
-  return UnorderedElementsAreArray(matchers);
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-
-// Supports the UnorderedPointwise(m, {a, b, c}) syntax.
-template <typename Tuple2Matcher, typename T>
-inline internal::UnorderedElementsAreArrayMatcher<
-    typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
-UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
-                   std::initializer_list<T> rhs) {
-  return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
-}
-
-#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
-
-// Matches an STL-style container or a native array that contains at
-// least one element matching the given value or matcher.
-//
-// Examples:
-//   ::std::set<int> page_ids;
-//   page_ids.insert(3);
-//   page_ids.insert(1);
-//   EXPECT_THAT(page_ids, Contains(1));
-//   EXPECT_THAT(page_ids, Contains(Gt(2)));
-//   EXPECT_THAT(page_ids, Not(Contains(4)));
-//
-//   ::std::map<int, size_t> page_lengths;
-//   page_lengths[1] = 100;
-//   EXPECT_THAT(page_lengths,
-//               Contains(::std::pair<const int, size_t>(1, 100)));
-//
-//   const char* user_ids[] = { "joe", "mike", "tom" };
-//   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
-template <typename M>
-inline internal::ContainsMatcher<M> Contains(M matcher) {
-  return internal::ContainsMatcher<M>(matcher);
-}
-
-// Matches an STL-style container or a native array that contains only
-// elements matching the given value or matcher.
-//
-// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
-// the messages are different.
-//
-// Examples:
-//   ::std::set<int> page_ids;
-//   // Each(m) matches an empty container, regardless of what m is.
-//   EXPECT_THAT(page_ids, Each(Eq(1)));
-//   EXPECT_THAT(page_ids, Each(Eq(77)));
-//
-//   page_ids.insert(3);
-//   EXPECT_THAT(page_ids, Each(Gt(0)));
-//   EXPECT_THAT(page_ids, Not(Each(Gt(4))));
-//   page_ids.insert(1);
-//   EXPECT_THAT(page_ids, Not(Each(Lt(2))));
-//
-//   ::std::map<int, size_t> page_lengths;
-//   page_lengths[1] = 100;
-//   page_lengths[2] = 200;
-//   page_lengths[3] = 300;
-//   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
-//   EXPECT_THAT(page_lengths, Each(Key(Le(3))));
-//
-//   const char* user_ids[] = { "joe", "mike", "tom" };
-//   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
-template <typename M>
-inline internal::EachMatcher<M> Each(M matcher) {
-  return internal::EachMatcher<M>(matcher);
-}
-
-// Key(inner_matcher) matches an std::pair whose 'first' field matches
-// inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an
-// std::map that contains at least one element whose key is >= 5.
-template <typename M>
-inline internal::KeyMatcher<M> Key(M inner_matcher) {
-  return internal::KeyMatcher<M>(inner_matcher);
-}
-
-// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
-// matches first_matcher and whose 'second' field matches second_matcher.  For
-// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
-// to match a std::map<int, string> that contains exactly one element whose key
-// is >= 5 and whose value equals "foo".
-template <typename FirstMatcher, typename SecondMatcher>
-inline internal::PairMatcher<FirstMatcher, SecondMatcher>
-Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
-  return internal::PairMatcher<FirstMatcher, SecondMatcher>(
-      first_matcher, second_matcher);
-}
-
-// Returns a predicate that is satisfied by anything that matches the
-// given matcher.
-template <typename M>
-inline internal::MatcherAsPredicate<M> Matches(M matcher) {
-  return internal::MatcherAsPredicate<M>(matcher);
-}
-
-// Returns true iff the value matches the matcher.
-template <typename T, typename M>
-inline bool Value(const T& value, M matcher) {
-  return testing::Matches(matcher)(value);
-}
-
-// Matches the value against the given matcher and explains the match
-// result to listener.
-template <typename T, typename M>
-inline bool ExplainMatchResult(
-    M matcher, const T& value, MatchResultListener* listener) {
-  return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
-}
-
-#if GTEST_LANG_CXX11
-// Define variadic matcher versions. They are overloaded in
-// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
-template <typename... Args>
-inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
-  return internal::AllOfMatcher<Args...>(matchers...);
-}
-
-template <typename... Args>
-inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
-  return internal::AnyOfMatcher<Args...>(matchers...);
-}
-
-#endif  // GTEST_LANG_CXX11
-
-// AllArgs(m) is a synonym of m.  This is useful in
-//
-//   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
-//
-// which is easier to read than
-//
-//   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
-template <typename InnerMatcher>
-inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
-
-// These macros allow using matchers to check values in Google Test
-// tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
-// succeed iff the value matches the matcher.  If the assertion fails,
-// the value and the description of the matcher will be printed.
-#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
-    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
-#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
-    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
-
-}  // namespace testing
-
-// Include any custom callback matchers added by the local installation.
-// We must include this header at the end to make sure it can use the
-// declarations from this file.
-#include "gmock/internal/custom/gmock-matchers.h"
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#endif  // TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
\ No newline at end of file
diff --git a/testing/gmock/include/gmock/gmock-more-actions.h b/testing/gmock/include/gmock/gmock-more-actions.h
deleted file mode 100644
index 3d387b6..0000000
--- a/testing/gmock/include/gmock/gmock-more-actions.h
+++ /dev/null
@@ -1,246 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some actions that depend on gmock-generated-actions.h.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
-
-#include <algorithm>
-
-#include "gmock/gmock-generated-actions.h"
-
-namespace testing {
-namespace internal {
-
-// Implements the Invoke(f) action.  The template argument
-// FunctionImpl is the implementation type of f, which can be either a
-// function pointer or a functor.  Invoke(f) can be used as an
-// Action<F> as long as f's type is compatible with F (i.e. f can be
-// assigned to a tr1::function<F>).
-template <typename FunctionImpl>
-class InvokeAction {
- public:
-  // The c'tor makes a copy of function_impl (either a function
-  // pointer or a functor).
-  explicit InvokeAction(FunctionImpl function_impl)
-      : function_impl_(function_impl) {}
-
-  template <typename Result, typename ArgumentTuple>
-  Result Perform(const ArgumentTuple& args) {
-    return InvokeHelper<Result, ArgumentTuple>::Invoke(function_impl_, args);
-  }
-
- private:
-  FunctionImpl function_impl_;
-
-  GTEST_DISALLOW_ASSIGN_(InvokeAction);
-};
-
-// Implements the Invoke(object_ptr, &Class::Method) action.
-template <class Class, typename MethodPtr>
-class InvokeMethodAction {
- public:
-  InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr)
-      : method_ptr_(method_ptr), obj_ptr_(obj_ptr) {}
-
-  template <typename Result, typename ArgumentTuple>
-  Result Perform(const ArgumentTuple& args) const {
-    return InvokeHelper<Result, ArgumentTuple>::InvokeMethod(
-        obj_ptr_, method_ptr_, args);
-  }
-
- private:
-  // The order of these members matters.  Reversing the order can trigger
-  // warning C4121 in MSVC (see
-  // http://computer-programming-forum.com/7-vc.net/6fbc30265f860ad1.htm ).
-  const MethodPtr method_ptr_;
-  Class* const obj_ptr_;
-
-  GTEST_DISALLOW_ASSIGN_(InvokeMethodAction);
-};
-
-// An internal replacement for std::copy which mimics its behavior. This is
-// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996.
-// However Visual Studio 2010 and later do not honor #pragmas which disable that
-// warning.
-template<typename InputIterator, typename OutputIterator>
-inline OutputIterator CopyElements(InputIterator first,
-                                   InputIterator last,
-                                   OutputIterator output) {
-  for (; first != last; ++first, ++output) {
-    *output = *first;
-  }
-  return output;
-}
-
-}  // namespace internal
-
-// Various overloads for Invoke().
-
-// Creates an action that invokes 'function_impl' with the mock
-// function's arguments.
-template <typename FunctionImpl>
-PolymorphicAction<internal::InvokeAction<FunctionImpl> > Invoke(
-    FunctionImpl function_impl) {
-  return MakePolymorphicAction(
-      internal::InvokeAction<FunctionImpl>(function_impl));
-}
-
-// Creates an action that invokes the given method on the given object
-// with the mock function's arguments.
-template <class Class, typename MethodPtr>
-PolymorphicAction<internal::InvokeMethodAction<Class, MethodPtr> > Invoke(
-    Class* obj_ptr, MethodPtr method_ptr) {
-  return MakePolymorphicAction(
-      internal::InvokeMethodAction<Class, MethodPtr>(obj_ptr, method_ptr));
-}
-
-// WithoutArgs(inner_action) can be used in a mock function with a
-// non-empty argument list to perform inner_action, which takes no
-// argument.  In other words, it adapts an action accepting no
-// argument to one that accepts (and ignores) arguments.
-template <typename InnerAction>
-inline internal::WithArgsAction<InnerAction>
-WithoutArgs(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction>(action);
-}
-
-// WithArg<k>(an_action) creates an action that passes the k-th
-// (0-based) argument of the mock function to an_action and performs
-// it.  It adapts an action accepting one argument to one that accepts
-// multiple arguments.  For convenience, we also provide
-// WithArgs<k>(an_action) (defined below) as a synonym.
-template <int k, typename InnerAction>
-inline internal::WithArgsAction<InnerAction, k>
-WithArg(const InnerAction& action) {
-  return internal::WithArgsAction<InnerAction, k>(action);
-}
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma.  Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Action ReturnArg<k>() returns the k-th argument of the mock function.
-ACTION_TEMPLATE(ReturnArg,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_0_VALUE_PARAMS()) {
-  return ::testing::get<k>(args);
-}
-
-// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
-// mock function to *pointer.
-ACTION_TEMPLATE(SaveArg,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_1_VALUE_PARAMS(pointer)) {
-  *pointer = ::testing::get<k>(args);
-}
-
-// Action SaveArgPointee<k>(pointer) saves the value pointed to
-// by the k-th (0-based) argument of the mock function to *pointer.
-ACTION_TEMPLATE(SaveArgPointee,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_1_VALUE_PARAMS(pointer)) {
-  *pointer = *::testing::get<k>(args);
-}
-
-// Action SetArgReferee<k>(value) assigns 'value' to the variable
-// referenced by the k-th (0-based) argument of the mock function.
-ACTION_TEMPLATE(SetArgReferee,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_1_VALUE_PARAMS(value)) {
-  typedef typename ::testing::tuple_element<k, args_type>::type argk_type;
-  // Ensures that argument #k is a reference.  If you get a compiler
-  // error on the next line, you are using SetArgReferee<k>(value) in
-  // a mock function whose k-th (0-based) argument is not a reference.
-  GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value,
-                        SetArgReferee_must_be_used_with_a_reference_argument);
-  ::testing::get<k>(args) = value;
-}
-
-// Action SetArrayArgument<k>(first, last) copies the elements in
-// source range [first, last) to the array pointed to by the k-th
-// (0-based) argument, which can be either a pointer or an
-// iterator. The action does not take ownership of the elements in the
-// source range.
-ACTION_TEMPLATE(SetArrayArgument,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_2_VALUE_PARAMS(first, last)) {
-  // Visual Studio deprecates ::std::copy, so we use our own copy in that case.
-#ifdef _MSC_VER
-  internal::CopyElements(first, last, ::testing::get<k>(args));
-#else
-  ::std::copy(first, last, ::testing::get<k>(args));
-#endif
-}
-
-// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
-// function.
-ACTION_TEMPLATE(DeleteArg,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_0_VALUE_PARAMS()) {
-  delete ::testing::get<k>(args);
-}
-
-// This action returns the value pointed to by 'pointer'.
-ACTION_P(ReturnPointee, pointer) { return *pointer; }
-
-// Action Throw(exception) can be used in a mock function of any type
-// to throw the given exception.  Any copyable value can be thrown.
-#if GTEST_HAS_EXCEPTIONS
-
-// Suppresses the 'unreachable code' warning that VC generates in opt modes.
-# ifdef _MSC_VER
-#  pragma warning(push)          // Saves the current warning state.
-#  pragma warning(disable:4702)  // Temporarily disables warning 4702.
-# endif
-ACTION_P(Throw, exception) { throw exception; }
-# ifdef _MSC_VER
-#  pragma warning(pop)           // Restores the warning state.
-# endif
-
-#endif  // GTEST_HAS_EXCEPTIONS
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
diff --git a/testing/gmock/include/gmock/gmock-more-matchers.h b/testing/gmock/include/gmock/gmock-more-matchers.h
deleted file mode 100644
index 3db899f..0000000
--- a/testing/gmock/include/gmock/gmock-more-matchers.h
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2013, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: marcus.boerger@google.com (Marcus Boerger)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements some matchers that depend on gmock-generated-matchers.h.
-//
-// Note that tests are implemented in gmock-matchers_test.cc rather than
-// gmock-more-matchers-test.cc.
-
-#ifndef GMOCK_GMOCK_MORE_MATCHERS_H_
-#define GMOCK_GMOCK_MORE_MATCHERS_H_
-
-#include "gmock/gmock-generated-matchers.h"
-
-namespace testing {
-
-// Defines a matcher that matches an empty container. The container must
-// support both size() and empty(), which all STL-like containers provide.
-MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
-  if (arg.empty()) {
-    return true;
-  }
-  *result_listener << "whose size is " << arg.size();
-  return false;
-}
-
-}  // namespace testing
-
-#endif  // GMOCK_GMOCK_MORE_MATCHERS_H_
diff --git a/testing/gmock/include/gmock/gmock-spec-builders.h b/testing/gmock/include/gmock/gmock-spec-builders.h
deleted file mode 100644
index fed7de6..0000000
--- a/testing/gmock/include/gmock/gmock-spec-builders.h
+++ /dev/null
@@ -1,1847 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements the ON_CALL() and EXPECT_CALL() macros.
-//
-// A user can use the ON_CALL() macro to specify the default action of
-// a mock method.  The syntax is:
-//
-//   ON_CALL(mock_object, Method(argument-matchers))
-//       .With(multi-argument-matcher)
-//       .WillByDefault(action);
-//
-//  where the .With() clause is optional.
-//
-// A user can use the EXPECT_CALL() macro to specify an expectation on
-// a mock method.  The syntax is:
-//
-//   EXPECT_CALL(mock_object, Method(argument-matchers))
-//       .With(multi-argument-matchers)
-//       .Times(cardinality)
-//       .InSequence(sequences)
-//       .After(expectations)
-//       .WillOnce(action)
-//       .WillRepeatedly(action)
-//       .RetiresOnSaturation();
-//
-// where all clauses are optional, and .InSequence()/.After()/
-// .WillOnce() can appear any number of times.
-
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
-
-#include <map>
-#include <set>
-#include <sstream>
-#include <string>
-#include <vector>
-
-#if GTEST_HAS_EXCEPTIONS
-# include <stdexcept>  // NOLINT
-#endif
-
-#include "gmock/gmock-actions.h"
-#include "gmock/gmock-cardinalities.h"
-#include "gmock/gmock-matchers.h"
-#include "gmock/internal/gmock-internal-utils.h"
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-
-// An abstract handle of an expectation.
-class Expectation;
-
-// A set of expectation handles.
-class ExpectationSet;
-
-// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
-// and MUST NOT BE USED IN USER CODE!!!
-namespace internal {
-
-// Implements a mock function.
-template <typename F> class FunctionMocker;
-
-// Base class for expectations.
-class ExpectationBase;
-
-// Implements an expectation.
-template <typename F> class TypedExpectation;
-
-// Helper class for testing the Expectation class template.
-class ExpectationTester;
-
-// Base class for function mockers.
-template <typename F> class FunctionMockerBase;
-
-// Protects the mock object registry (in class Mock), all function
-// mockers, and all expectations.
-//
-// The reason we don't use more fine-grained protection is: when a
-// mock function Foo() is called, it needs to consult its expectations
-// to see which one should be picked.  If another thread is allowed to
-// call a mock function (either Foo() or a different one) at the same
-// time, it could affect the "retired" attributes of Foo()'s
-// expectations when InSequence() is used, and thus affect which
-// expectation gets picked.  Therefore, we sequence all mock function
-// calls to ensure the integrity of the mock objects' states.
-GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
-
-// Untyped base class for ActionResultHolder<R>.
-class UntypedActionResultHolderBase;
-
-// Abstract base class of FunctionMockerBase.  This is the
-// type-agnostic part of the function mocker interface.  Its pure
-// virtual methods are implemented by FunctionMockerBase.
-class GTEST_API_ UntypedFunctionMockerBase {
- public:
-  UntypedFunctionMockerBase();
-  virtual ~UntypedFunctionMockerBase();
-
-  // Verifies that all expectations on this mock function have been
-  // satisfied.  Reports one or more Google Test non-fatal failures
-  // and returns false if not.
-  bool VerifyAndClearExpectationsLocked()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
-
-  // Clears the ON_CALL()s set on this mock function.
-  virtual void ClearDefaultActionsLocked()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
-
-  // In all of the following Untyped* functions, it's the caller's
-  // responsibility to guarantee the correctness of the arguments'
-  // types.
-
-  // Performs the default action with the given arguments and returns
-  // the action's result.  The call description string will be used in
-  // the error message to describe the call in the case the default
-  // action fails.
-  // L = *
-  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
-      const void* untyped_args,
-      const string& call_description) const = 0;
-
-  // Performs the given action with the given arguments and returns
-  // the action's result.
-  // L = *
-  virtual UntypedActionResultHolderBase* UntypedPerformAction(
-      const void* untyped_action,
-      const void* untyped_args) const = 0;
-
-  // Writes a message that the call is uninteresting (i.e. neither
-  // explicitly expected nor explicitly unexpected) to the given
-  // ostream.
-  virtual void UntypedDescribeUninterestingCall(
-      const void* untyped_args,
-      ::std::ostream* os) const
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
-
-  // Returns the expectation that matches the given function arguments
-  // (or NULL is there's no match); when a match is found,
-  // untyped_action is set to point to the action that should be
-  // performed (or NULL if the action is "do default"), and
-  // is_excessive is modified to indicate whether the call exceeds the
-  // expected number.
-  virtual const ExpectationBase* UntypedFindMatchingExpectation(
-      const void* untyped_args,
-      const void** untyped_action, bool* is_excessive,
-      ::std::ostream* what, ::std::ostream* why)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
-
-  // Prints the given function arguments to the ostream.
-  virtual void UntypedPrintArgs(const void* untyped_args,
-                                ::std::ostream* os) const = 0;
-
-  // Sets the mock object this mock method belongs to, and registers
-  // this information in the global mock registry.  Will be called
-  // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
-  // method.
-  // TODO(wan@google.com): rename to SetAndRegisterOwner().
-  void RegisterOwner(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
-
-  // Sets the mock object this mock method belongs to, and sets the
-  // name of the mock function.  Will be called upon each invocation
-  // of this mock function.
-  void SetOwnerAndName(const void* mock_obj, const char* name)
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
-
-  // Returns the mock object this mock method belongs to.  Must be
-  // called after RegisterOwner() or SetOwnerAndName() has been
-  // called.
-  const void* MockObject() const
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
-
-  // Returns the name of this mock method.  Must be called after
-  // SetOwnerAndName() has been called.
-  const char* Name() const
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
-
-  // Returns the result of invoking this mock function with the given
-  // arguments.  This function can be safely called from multiple
-  // threads concurrently.  The caller is responsible for deleting the
-  // result.
-  UntypedActionResultHolderBase* UntypedInvokeWith(
-      const void* untyped_args)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
-
- protected:
-  typedef std::vector<const void*> UntypedOnCallSpecs;
-
-  typedef std::vector<internal::linked_ptr<ExpectationBase> >
-  UntypedExpectations;
-
-  // Returns an Expectation object that references and co-owns exp,
-  // which must be an expectation on this mock function.
-  Expectation GetHandleOf(ExpectationBase* exp);
-
-  // Address of the mock object this mock method belongs to.  Only
-  // valid after this mock method has been called or
-  // ON_CALL/EXPECT_CALL has been invoked on it.
-  const void* mock_obj_;  // Protected by g_gmock_mutex.
-
-  // Name of the function being mocked.  Only valid after this mock
-  // method has been called.
-  const char* name_;  // Protected by g_gmock_mutex.
-
-  // All default action specs for this function mocker.
-  UntypedOnCallSpecs untyped_on_call_specs_;
-
-  // All expectations for this function mocker.
-  UntypedExpectations untyped_expectations_;
-};  // class UntypedFunctionMockerBase
-
-// Untyped base class for OnCallSpec<F>.
-class UntypedOnCallSpecBase {
- public:
-  // The arguments are the location of the ON_CALL() statement.
-  UntypedOnCallSpecBase(const char* a_file, int a_line)
-      : file_(a_file), line_(a_line), last_clause_(kNone) {}
-
-  // Where in the source file was the default action spec defined?
-  const char* file() const { return file_; }
-  int line() const { return line_; }
-
- protected:
-  // Gives each clause in the ON_CALL() statement a name.
-  enum Clause {
-    // Do not change the order of the enum members!  The run-time
-    // syntax checking relies on it.
-    kNone,
-    kWith,
-    kWillByDefault
-  };
-
-  // Asserts that the ON_CALL() statement has a certain property.
-  void AssertSpecProperty(bool property, const string& failure_message) const {
-    Assert(property, file_, line_, failure_message);
-  }
-
-  // Expects that the ON_CALL() statement has a certain property.
-  void ExpectSpecProperty(bool property, const string& failure_message) const {
-    Expect(property, file_, line_, failure_message);
-  }
-
-  const char* file_;
-  int line_;
-
-  // The last clause in the ON_CALL() statement as seen so far.
-  // Initially kNone and changes as the statement is parsed.
-  Clause last_clause_;
-};  // class UntypedOnCallSpecBase
-
-// This template class implements an ON_CALL spec.
-template <typename F>
-class OnCallSpec : public UntypedOnCallSpecBase {
- public:
-  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
-
-  // Constructs an OnCallSpec object from the information inside
-  // the parenthesis of an ON_CALL() statement.
-  OnCallSpec(const char* a_file, int a_line,
-             const ArgumentMatcherTuple& matchers)
-      : UntypedOnCallSpecBase(a_file, a_line),
-        matchers_(matchers),
-        // By default, extra_matcher_ should match anything.  However,
-        // we cannot initialize it with _ as that triggers a compiler
-        // bug in Symbian's C++ compiler (cannot decide between two
-        // overloaded constructors of Matcher<const ArgumentTuple&>).
-        extra_matcher_(A<const ArgumentTuple&>()) {
-  }
-
-  // Implements the .With() clause.
-  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
-    // Makes sure this is called at most once.
-    ExpectSpecProperty(last_clause_ < kWith,
-                       ".With() cannot appear "
-                       "more than once in an ON_CALL().");
-    last_clause_ = kWith;
-
-    extra_matcher_ = m;
-    return *this;
-  }
-
-  // Implements the .WillByDefault() clause.
-  OnCallSpec& WillByDefault(const Action<F>& action) {
-    ExpectSpecProperty(last_clause_ < kWillByDefault,
-                       ".WillByDefault() must appear "
-                       "exactly once in an ON_CALL().");
-    last_clause_ = kWillByDefault;
-
-    ExpectSpecProperty(!action.IsDoDefault(),
-                       "DoDefault() cannot be used in ON_CALL().");
-    action_ = action;
-    return *this;
-  }
-
-  // Returns true iff the given arguments match the matchers.
-  bool Matches(const ArgumentTuple& args) const {
-    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
-  }
-
-  // Returns the action specified by the user.
-  const Action<F>& GetAction() const {
-    AssertSpecProperty(last_clause_ == kWillByDefault,
-                       ".WillByDefault() must appear exactly "
-                       "once in an ON_CALL().");
-    return action_;
-  }
-
- private:
-  // The information in statement
-  //
-  //   ON_CALL(mock_object, Method(matchers))
-  //       .With(multi-argument-matcher)
-  //       .WillByDefault(action);
-  //
-  // is recorded in the data members like this:
-  //
-  //   source file that contains the statement => file_
-  //   line number of the statement            => line_
-  //   matchers                                => matchers_
-  //   multi-argument-matcher                  => extra_matcher_
-  //   action                                  => action_
-  ArgumentMatcherTuple matchers_;
-  Matcher<const ArgumentTuple&> extra_matcher_;
-  Action<F> action_;
-};  // class OnCallSpec
-
-// Possible reactions on uninteresting calls.
-enum CallReaction {
-  kAllow,
-  kWarn,
-  kFail,
-  kDefault = kWarn  // By default, warn about uninteresting calls.
-};
-
-}  // namespace internal
-
-// Utilities for manipulating mock objects.
-class GTEST_API_ Mock {
- public:
-  // The following public methods can be called concurrently.
-
-  // Tells Google Mock to ignore mock_obj when checking for leaked
-  // mock objects.
-  static void AllowLeak(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Verifies and clears all expectations on the given mock object.
-  // If the expectations aren't satisfied, generates one or more
-  // Google Test non-fatal failures and returns false.
-  static bool VerifyAndClearExpectations(void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Verifies all expectations on the given mock object and clears its
-  // default actions and expectations.  Returns true iff the
-  // verification was successful.
-  static bool VerifyAndClear(void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
- private:
-  friend class internal::UntypedFunctionMockerBase;
-
-  // Needed for a function mocker to register itself (so that we know
-  // how to clear a mock object).
-  template <typename F>
-  friend class internal::FunctionMockerBase;
-
-  template <typename M>
-  friend class NiceMock;
-
-  template <typename M>
-  friend class NaggyMock;
-
-  template <typename M>
-  friend class StrictMock;
-
-  // Tells Google Mock to allow uninteresting calls on the given mock
-  // object.
-  static void AllowUninterestingCalls(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Tells Google Mock to warn the user about uninteresting calls on
-  // the given mock object.
-  static void WarnUninterestingCalls(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Tells Google Mock to fail uninteresting calls on the given mock
-  // object.
-  static void FailUninterestingCalls(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Tells Google Mock the given mock object is being destroyed and
-  // its entry in the call-reaction table should be removed.
-  static void UnregisterCallReaction(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Returns the reaction Google Mock will have on uninteresting calls
-  // made on the given mock object.
-  static internal::CallReaction GetReactionOnUninterestingCalls(
-      const void* mock_obj)
-          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Verifies that all expectations on the given mock object have been
-  // satisfied.  Reports one or more Google Test non-fatal failures
-  // and returns false if not.
-  static bool VerifyAndClearExpectationsLocked(void* mock_obj)
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
-
-  // Clears all ON_CALL()s set on the given mock object.
-  static void ClearDefaultActionsLocked(void* mock_obj)
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
-
-  // Registers a mock object and a mock method it owns.
-  static void Register(
-      const void* mock_obj,
-      internal::UntypedFunctionMockerBase* mocker)
-          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Tells Google Mock where in the source code mock_obj is used in an
-  // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
-  // information helps the user identify which object it is.
-  static void RegisterUseByOnCallOrExpectCall(
-      const void* mock_obj, const char* file, int line)
-          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
-
-  // Unregisters a mock method; removes the owning mock object from
-  // the registry when the last mock method associated with it has
-  // been unregistered.  This is called only in the destructor of
-  // FunctionMockerBase.
-  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
-};  // class Mock
-
-// An abstract handle of an expectation.  Useful in the .After()
-// clause of EXPECT_CALL() for setting the (partial) order of
-// expectations.  The syntax:
-//
-//   Expectation e1 = EXPECT_CALL(...)...;
-//   EXPECT_CALL(...).After(e1)...;
-//
-// sets two expectations where the latter can only be matched after
-// the former has been satisfied.
-//
-// Notes:
-//   - This class is copyable and has value semantics.
-//   - Constness is shallow: a const Expectation object itself cannot
-//     be modified, but the mutable methods of the ExpectationBase
-//     object it references can be called via expectation_base().
-//   - The constructors and destructor are defined out-of-line because
-//     the Symbian WINSCW compiler wants to otherwise instantiate them
-//     when it sees this class definition, at which point it doesn't have
-//     ExpectationBase available yet, leading to incorrect destruction
-//     in the linked_ptr (or compilation errors if using a checking
-//     linked_ptr).
-class GTEST_API_ Expectation {
- public:
-  // Constructs a null object that doesn't reference any expectation.
-  Expectation();
-
-  ~Expectation();
-
-  // This single-argument ctor must not be explicit, in order to support the
-  //   Expectation e = EXPECT_CALL(...);
-  // syntax.
-  //
-  // A TypedExpectation object stores its pre-requisites as
-  // Expectation objects, and needs to call the non-const Retire()
-  // method on the ExpectationBase objects they reference.  Therefore
-  // Expectation must receive a *non-const* reference to the
-  // ExpectationBase object.
-  Expectation(internal::ExpectationBase& exp);  // NOLINT
-
-  // The compiler-generated copy ctor and operator= work exactly as
-  // intended, so we don't need to define our own.
-
-  // Returns true iff rhs references the same expectation as this object does.
-  bool operator==(const Expectation& rhs) const {
-    return expectation_base_ == rhs.expectation_base_;
-  }
-
-  bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
-
- private:
-  friend class ExpectationSet;
-  friend class Sequence;
-  friend class ::testing::internal::ExpectationBase;
-  friend class ::testing::internal::UntypedFunctionMockerBase;
-
-  template <typename F>
-  friend class ::testing::internal::FunctionMockerBase;
-
-  template <typename F>
-  friend class ::testing::internal::TypedExpectation;
-
-  // This comparator is needed for putting Expectation objects into a set.
-  class Less {
-   public:
-    bool operator()(const Expectation& lhs, const Expectation& rhs) const {
-      return lhs.expectation_base_.get() < rhs.expectation_base_.get();
-    }
-  };
-
-  typedef ::std::set<Expectation, Less> Set;
-
-  Expectation(
-      const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
-
-  // Returns the expectation this object references.
-  const internal::linked_ptr<internal::ExpectationBase>&
-  expectation_base() const {
-    return expectation_base_;
-  }
-
-  // A linked_ptr that co-owns the expectation this handle references.
-  internal::linked_ptr<internal::ExpectationBase> expectation_base_;
-};
-
-// A set of expectation handles.  Useful in the .After() clause of
-// EXPECT_CALL() for setting the (partial) order of expectations.  The
-// syntax:
-//
-//   ExpectationSet es;
-//   es += EXPECT_CALL(...)...;
-//   es += EXPECT_CALL(...)...;
-//   EXPECT_CALL(...).After(es)...;
-//
-// sets three expectations where the last one can only be matched
-// after the first two have both been satisfied.
-//
-// This class is copyable and has value semantics.
-class ExpectationSet {
- public:
-  // A bidirectional iterator that can read a const element in the set.
-  typedef Expectation::Set::const_iterator const_iterator;
-
-  // An object stored in the set.  This is an alias of Expectation.
-  typedef Expectation::Set::value_type value_type;
-
-  // Constructs an empty set.
-  ExpectationSet() {}
-
-  // This single-argument ctor must not be explicit, in order to support the
-  //   ExpectationSet es = EXPECT_CALL(...);
-  // syntax.
-  ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
-    *this += Expectation(exp);
-  }
-
-  // This single-argument ctor implements implicit conversion from
-  // Expectation and thus must not be explicit.  This allows either an
-  // Expectation or an ExpectationSet to be used in .After().
-  ExpectationSet(const Expectation& e) {  // NOLINT
-    *this += e;
-  }
-
-  // The compiler-generator ctor and operator= works exactly as
-  // intended, so we don't need to define our own.
-
-  // Returns true iff rhs contains the same set of Expectation objects
-  // as this does.
-  bool operator==(const ExpectationSet& rhs) const {
-    return expectations_ == rhs.expectations_;
-  }
-
-  bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
-
-  // Implements the syntax
-  //   expectation_set += EXPECT_CALL(...);
-  ExpectationSet& operator+=(const Expectation& e) {
-    expectations_.insert(e);
-    return *this;
-  }
-
-  int size() const { return static_cast<int>(expectations_.size()); }
-
-  const_iterator begin() const { return expectations_.begin(); }
-  const_iterator end() const { return expectations_.end(); }
-
- private:
-  Expectation::Set expectations_;
-};
-
-
-// Sequence objects are used by a user to specify the relative order
-// in which the expectations should match.  They are copyable (we rely
-// on the compiler-defined copy constructor and assignment operator).
-class GTEST_API_ Sequence {
- public:
-  // Constructs an empty sequence.
-  Sequence() : last_expectation_(new Expectation) {}
-
-  // Adds an expectation to this sequence.  The caller must ensure
-  // that no other thread is accessing this Sequence object.
-  void AddExpectation(const Expectation& expectation) const;
-
- private:
-  // The last expectation in this sequence.  We use a linked_ptr here
-  // because Sequence objects are copyable and we want the copies to
-  // be aliases.  The linked_ptr allows the copies to co-own and share
-  // the same Expectation object.
-  internal::linked_ptr<Expectation> last_expectation_;
-};  // class Sequence
-
-// An object of this type causes all EXPECT_CALL() statements
-// encountered in its scope to be put in an anonymous sequence.  The
-// work is done in the constructor and destructor.  You should only
-// create an InSequence object on the stack.
-//
-// The sole purpose for this class is to support easy definition of
-// sequential expectations, e.g.
-//
-//   {
-//     InSequence dummy;  // The name of the object doesn't matter.
-//
-//     // The following expectations must match in the order they appear.
-//     EXPECT_CALL(a, Bar())...;
-//     EXPECT_CALL(a, Baz())...;
-//     ...
-//     EXPECT_CALL(b, Xyz())...;
-//   }
-//
-// You can create InSequence objects in multiple threads, as long as
-// they are used to affect different mock objects.  The idea is that
-// each thread can create and set up its own mocks as if it's the only
-// thread.  However, for clarity of your tests we recommend you to set
-// up mocks in the main thread unless you have a good reason not to do
-// so.
-class GTEST_API_ InSequence {
- public:
-  InSequence();
-  ~InSequence();
- private:
-  bool sequence_created_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
-} GTEST_ATTRIBUTE_UNUSED_;
-
-namespace internal {
-
-// Points to the implicit sequence introduced by a living InSequence
-// object (if any) in the current thread or NULL.
-GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
-
-// Base class for implementing expectations.
-//
-// There are two reasons for having a type-agnostic base class for
-// Expectation:
-//
-//   1. We need to store collections of expectations of different
-//   types (e.g. all pre-requisites of a particular expectation, all
-//   expectations in a sequence).  Therefore these expectation objects
-//   must share a common base class.
-//
-//   2. We can avoid binary code bloat by moving methods not depending
-//   on the template argument of Expectation to the base class.
-//
-// This class is internal and mustn't be used by user code directly.
-class GTEST_API_ ExpectationBase {
- public:
-  // source_text is the EXPECT_CALL(...) source that created this Expectation.
-  ExpectationBase(const char* file, int line, const string& source_text);
-
-  virtual ~ExpectationBase();
-
-  // Where in the source file was the expectation spec defined?
-  const char* file() const { return file_; }
-  int line() const { return line_; }
-  const char* source_text() const { return source_text_.c_str(); }
-  // Returns the cardinality specified in the expectation spec.
-  const Cardinality& cardinality() const { return cardinality_; }
-
-  // Describes the source file location of this expectation.
-  void DescribeLocationTo(::std::ostream* os) const {
-    *os << FormatFileLocation(file(), line()) << " ";
-  }
-
-  // Describes how many times a function call matching this
-  // expectation has occurred.
-  void DescribeCallCountTo(::std::ostream* os) const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
-
-  // If this mock method has an extra matcher (i.e. .With(matcher)),
-  // describes it to the ostream.
-  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
-
- protected:
-  friend class ::testing::Expectation;
-  friend class UntypedFunctionMockerBase;
-
-  enum Clause {
-    // Don't change the order of the enum members!
-    kNone,
-    kWith,
-    kTimes,
-    kInSequence,
-    kAfter,
-    kWillOnce,
-    kWillRepeatedly,
-    kRetiresOnSaturation
-  };
-
-  typedef std::vector<const void*> UntypedActions;
-
-  // Returns an Expectation object that references and co-owns this
-  // expectation.
-  virtual Expectation GetHandle() = 0;
-
-  // Asserts that the EXPECT_CALL() statement has the given property.
-  void AssertSpecProperty(bool property, const string& failure_message) const {
-    Assert(property, file_, line_, failure_message);
-  }
-
-  // Expects that the EXPECT_CALL() statement has the given property.
-  void ExpectSpecProperty(bool property, const string& failure_message) const {
-    Expect(property, file_, line_, failure_message);
-  }
-
-  // Explicitly specifies the cardinality of this expectation.  Used
-  // by the subclasses to implement the .Times() clause.
-  void SpecifyCardinality(const Cardinality& cardinality);
-
-  // Returns true iff the user specified the cardinality explicitly
-  // using a .Times().
-  bool cardinality_specified() const { return cardinality_specified_; }
-
-  // Sets the cardinality of this expectation spec.
-  void set_cardinality(const Cardinality& a_cardinality) {
-    cardinality_ = a_cardinality;
-  }
-
-  // The following group of methods should only be called after the
-  // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
-  // the current thread.
-
-  // Retires all pre-requisites of this expectation.
-  void RetireAllPreRequisites()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
-
-  // Returns true iff this expectation is retired.
-  bool is_retired() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    return retired_;
-  }
-
-  // Retires this expectation.
-  void Retire()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    retired_ = true;
-  }
-
-  // Returns true iff this expectation is satisfied.
-  bool IsSatisfied() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    return cardinality().IsSatisfiedByCallCount(call_count_);
-  }
-
-  // Returns true iff this expectation is saturated.
-  bool IsSaturated() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    return cardinality().IsSaturatedByCallCount(call_count_);
-  }
-
-  // Returns true iff this expectation is over-saturated.
-  bool IsOverSaturated() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    return cardinality().IsOverSaturatedByCallCount(call_count_);
-  }
-
-  // Returns true iff all pre-requisites of this expectation are satisfied.
-  bool AllPrerequisitesAreSatisfied() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
-
-  // Adds unsatisfied pre-requisites of this expectation to 'result'.
-  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
-
-  // Returns the number this expectation has been invoked.
-  int call_count() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    return call_count_;
-  }
-
-  // Increments the number this expectation has been invoked.
-  void IncrementCallCount()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    call_count_++;
-  }
-
-  // Checks the action count (i.e. the number of WillOnce() and
-  // WillRepeatedly() clauses) against the cardinality if this hasn't
-  // been done before.  Prints a warning if there are too many or too
-  // few actions.
-  void CheckActionCountIfNotDone() const
-      GTEST_LOCK_EXCLUDED_(mutex_);
-
-  friend class ::testing::Sequence;
-  friend class ::testing::internal::ExpectationTester;
-
-  template <typename Function>
-  friend class TypedExpectation;
-
-  // Implements the .Times() clause.
-  void UntypedTimes(const Cardinality& a_cardinality);
-
-  // This group of fields are part of the spec and won't change after
-  // an EXPECT_CALL() statement finishes.
-  const char* file_;          // The file that contains the expectation.
-  int line_;                  // The line number of the expectation.
-  const string source_text_;  // The EXPECT_CALL(...) source text.
-  // True iff the cardinality is specified explicitly.
-  bool cardinality_specified_;
-  Cardinality cardinality_;            // The cardinality of the expectation.
-  // The immediate pre-requisites (i.e. expectations that must be
-  // satisfied before this expectation can be matched) of this
-  // expectation.  We use linked_ptr in the set because we want an
-  // Expectation object to be co-owned by its FunctionMocker and its
-  // successors.  This allows multiple mock objects to be deleted at
-  // different times.
-  ExpectationSet immediate_prerequisites_;
-
-  // This group of fields are the current state of the expectation,
-  // and can change as the mock function is called.
-  int call_count_;  // How many times this expectation has been invoked.
-  bool retired_;    // True iff this expectation has retired.
-  UntypedActions untyped_actions_;
-  bool extra_matcher_specified_;
-  bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
-  bool retires_on_saturation_;
-  Clause last_clause_;
-  mutable bool action_count_checked_;  // Under mutex_.
-  mutable Mutex mutex_;  // Protects action_count_checked_.
-
-  GTEST_DISALLOW_ASSIGN_(ExpectationBase);
-};  // class ExpectationBase
-
-// Impements an expectation for the given function type.
-template <typename F>
-class TypedExpectation : public ExpectationBase {
- public:
-  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
-  typedef typename Function<F>::Result Result;
-
-  TypedExpectation(FunctionMockerBase<F>* owner,
-                   const char* a_file, int a_line, const string& a_source_text,
-                   const ArgumentMatcherTuple& m)
-      : ExpectationBase(a_file, a_line, a_source_text),
-        owner_(owner),
-        matchers_(m),
-        // By default, extra_matcher_ should match anything.  However,
-        // we cannot initialize it with _ as that triggers a compiler
-        // bug in Symbian's C++ compiler (cannot decide between two
-        // overloaded constructors of Matcher<const ArgumentTuple&>).
-        extra_matcher_(A<const ArgumentTuple&>()),
-        repeated_action_(DoDefault()) {}
-
-  virtual ~TypedExpectation() {
-    // Check the validity of the action count if it hasn't been done
-    // yet (for example, if the expectation was never used).
-    CheckActionCountIfNotDone();
-    for (UntypedActions::const_iterator it = untyped_actions_.begin();
-         it != untyped_actions_.end(); ++it) {
-      delete static_cast<const Action<F>*>(*it);
-    }
-  }
-
-  // Implements the .With() clause.
-  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
-    if (last_clause_ == kWith) {
-      ExpectSpecProperty(false,
-                         ".With() cannot appear "
-                         "more than once in an EXPECT_CALL().");
-    } else {
-      ExpectSpecProperty(last_clause_ < kWith,
-                         ".With() must be the first "
-                         "clause in an EXPECT_CALL().");
-    }
-    last_clause_ = kWith;
-
-    extra_matcher_ = m;
-    extra_matcher_specified_ = true;
-    return *this;
-  }
-
-  // Implements the .Times() clause.
-  TypedExpectation& Times(const Cardinality& a_cardinality) {
-    ExpectationBase::UntypedTimes(a_cardinality);
-    return *this;
-  }
-
-  // Implements the .Times() clause.
-  TypedExpectation& Times(int n) {
-    return Times(Exactly(n));
-  }
-
-  // Implements the .InSequence() clause.
-  TypedExpectation& InSequence(const Sequence& s) {
-    ExpectSpecProperty(last_clause_ <= kInSequence,
-                       ".InSequence() cannot appear after .After(),"
-                       " .WillOnce(), .WillRepeatedly(), or "
-                       ".RetiresOnSaturation().");
-    last_clause_ = kInSequence;
-
-    s.AddExpectation(GetHandle());
-    return *this;
-  }
-  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
-    return InSequence(s1).InSequence(s2);
-  }
-  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
-                               const Sequence& s3) {
-    return InSequence(s1, s2).InSequence(s3);
-  }
-  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
-                               const Sequence& s3, const Sequence& s4) {
-    return InSequence(s1, s2, s3).InSequence(s4);
-  }
-  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
-                               const Sequence& s3, const Sequence& s4,
-                               const Sequence& s5) {
-    return InSequence(s1, s2, s3, s4).InSequence(s5);
-  }
-
-  // Implements that .After() clause.
-  TypedExpectation& After(const ExpectationSet& s) {
-    ExpectSpecProperty(last_clause_ <= kAfter,
-                       ".After() cannot appear after .WillOnce(),"
-                       " .WillRepeatedly(), or "
-                       ".RetiresOnSaturation().");
-    last_clause_ = kAfter;
-
-    for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
-      immediate_prerequisites_ += *it;
-    }
-    return *this;
-  }
-  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
-    return After(s1).After(s2);
-  }
-  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
-                          const ExpectationSet& s3) {
-    return After(s1, s2).After(s3);
-  }
-  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
-                          const ExpectationSet& s3, const ExpectationSet& s4) {
-    return After(s1, s2, s3).After(s4);
-  }
-  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
-                          const ExpectationSet& s3, const ExpectationSet& s4,
-                          const ExpectationSet& s5) {
-    return After(s1, s2, s3, s4).After(s5);
-  }
-
-  // Implements the .WillOnce() clause.
-  TypedExpectation& WillOnce(const Action<F>& action) {
-    ExpectSpecProperty(last_clause_ <= kWillOnce,
-                       ".WillOnce() cannot appear after "
-                       ".WillRepeatedly() or .RetiresOnSaturation().");
-    last_clause_ = kWillOnce;
-
-    untyped_actions_.push_back(new Action<F>(action));
-    if (!cardinality_specified()) {
-      set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
-    }
-    return *this;
-  }
-
-  // Implements the .WillRepeatedly() clause.
-  TypedExpectation& WillRepeatedly(const Action<F>& action) {
-    if (last_clause_ == kWillRepeatedly) {
-      ExpectSpecProperty(false,
-                         ".WillRepeatedly() cannot appear "
-                         "more than once in an EXPECT_CALL().");
-    } else {
-      ExpectSpecProperty(last_clause_ < kWillRepeatedly,
-                         ".WillRepeatedly() cannot appear "
-                         "after .RetiresOnSaturation().");
-    }
-    last_clause_ = kWillRepeatedly;
-    repeated_action_specified_ = true;
-
-    repeated_action_ = action;
-    if (!cardinality_specified()) {
-      set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
-    }
-
-    // Now that no more action clauses can be specified, we check
-    // whether their count makes sense.
-    CheckActionCountIfNotDone();
-    return *this;
-  }
-
-  // Implements the .RetiresOnSaturation() clause.
-  TypedExpectation& RetiresOnSaturation() {
-    ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
-                       ".RetiresOnSaturation() cannot appear "
-                       "more than once.");
-    last_clause_ = kRetiresOnSaturation;
-    retires_on_saturation_ = true;
-
-    // Now that no more action clauses can be specified, we check
-    // whether their count makes sense.
-    CheckActionCountIfNotDone();
-    return *this;
-  }
-
-  // Returns the matchers for the arguments as specified inside the
-  // EXPECT_CALL() macro.
-  const ArgumentMatcherTuple& matchers() const {
-    return matchers_;
-  }
-
-  // Returns the matcher specified by the .With() clause.
-  const Matcher<const ArgumentTuple&>& extra_matcher() const {
-    return extra_matcher_;
-  }
-
-  // Returns the action specified by the .WillRepeatedly() clause.
-  const Action<F>& repeated_action() const { return repeated_action_; }
-
-  // If this mock method has an extra matcher (i.e. .With(matcher)),
-  // describes it to the ostream.
-  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
-    if (extra_matcher_specified_) {
-      *os << "    Expected args: ";
-      extra_matcher_.DescribeTo(os);
-      *os << "\n";
-    }
-  }
-
- private:
-  template <typename Function>
-  friend class FunctionMockerBase;
-
-  // Returns an Expectation object that references and co-owns this
-  // expectation.
-  virtual Expectation GetHandle() {
-    return owner_->GetHandleOf(this);
-  }
-
-  // The following methods will be called only after the EXPECT_CALL()
-  // statement finishes and when the current thread holds
-  // g_gmock_mutex.
-
-  // Returns true iff this expectation matches the given arguments.
-  bool Matches(const ArgumentTuple& args) const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
-  }
-
-  // Returns true iff this expectation should handle the given arguments.
-  bool ShouldHandleArguments(const ArgumentTuple& args) const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-
-    // In case the action count wasn't checked when the expectation
-    // was defined (e.g. if this expectation has no WillRepeatedly()
-    // or RetiresOnSaturation() clause), we check it when the
-    // expectation is used for the first time.
-    CheckActionCountIfNotDone();
-    return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
-  }
-
-  // Describes the result of matching the arguments against this
-  // expectation to the given ostream.
-  void ExplainMatchResultTo(
-      const ArgumentTuple& args,
-      ::std::ostream* os) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-
-    if (is_retired()) {
-      *os << "         Expected: the expectation is active\n"
-          << "           Actual: it is retired\n";
-    } else if (!Matches(args)) {
-      if (!TupleMatches(matchers_, args)) {
-        ExplainMatchFailureTupleTo(matchers_, args, os);
-      }
-      StringMatchResultListener listener;
-      if (!extra_matcher_.MatchAndExplain(args, &listener)) {
-        *os << "    Expected args: ";
-        extra_matcher_.DescribeTo(os);
-        *os << "\n           Actual: don't match";
-
-        internal::PrintIfNotEmpty(listener.str(), os);
-        *os << "\n";
-      }
-    } else if (!AllPrerequisitesAreSatisfied()) {
-      *os << "         Expected: all pre-requisites are satisfied\n"
-          << "           Actual: the following immediate pre-requisites "
-          << "are not satisfied:\n";
-      ExpectationSet unsatisfied_prereqs;
-      FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
-      int i = 0;
-      for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
-           it != unsatisfied_prereqs.end(); ++it) {
-        it->expectation_base()->DescribeLocationTo(os);
-        *os << "pre-requisite #" << i++ << "\n";
-      }
-      *os << "                   (end of pre-requisites)\n";
-    } else {
-      // This line is here just for completeness' sake.  It will never
-      // be executed as currently the ExplainMatchResultTo() function
-      // is called only when the mock function call does NOT match the
-      // expectation.
-      *os << "The call matches the expectation.\n";
-    }
-  }
-
-  // Returns the action that should be taken for the current invocation.
-  const Action<F>& GetCurrentAction(
-      const FunctionMockerBase<F>* mocker,
-      const ArgumentTuple& args) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    const int count = call_count();
-    Assert(count >= 1, __FILE__, __LINE__,
-           "call_count() is <= 0 when GetCurrentAction() is "
-           "called - this should never happen.");
-
-    const int action_count = static_cast<int>(untyped_actions_.size());
-    if (action_count > 0 && !repeated_action_specified_ &&
-        count > action_count) {
-      // If there is at least one WillOnce() and no WillRepeatedly(),
-      // we warn the user when the WillOnce() clauses ran out.
-      ::std::stringstream ss;
-      DescribeLocationTo(&ss);
-      ss << "Actions ran out in " << source_text() << "...\n"
-         << "Called " << count << " times, but only "
-         << action_count << " WillOnce()"
-         << (action_count == 1 ? " is" : "s are") << " specified - ";
-      mocker->DescribeDefaultActionTo(args, &ss);
-      Log(kWarning, ss.str(), 1);
-    }
-
-    return count <= action_count ?
-        *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
-        repeated_action();
-  }
-
-  // Given the arguments of a mock function call, if the call will
-  // over-saturate this expectation, returns the default action;
-  // otherwise, returns the next action in this expectation.  Also
-  // describes *what* happened to 'what', and explains *why* Google
-  // Mock does it to 'why'.  This method is not const as it calls
-  // IncrementCallCount().  A return value of NULL means the default
-  // action.
-  const Action<F>* GetActionForArguments(
-      const FunctionMockerBase<F>* mocker,
-      const ArgumentTuple& args,
-      ::std::ostream* what,
-      ::std::ostream* why)
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    if (IsSaturated()) {
-      // We have an excessive call.
-      IncrementCallCount();
-      *what << "Mock function called more times than expected - ";
-      mocker->DescribeDefaultActionTo(args, what);
-      DescribeCallCountTo(why);
-
-      // TODO(wan@google.com): allow the user to control whether
-      // unexpected calls should fail immediately or continue using a
-      // flag --gmock_unexpected_calls_are_fatal.
-      return NULL;
-    }
-
-    IncrementCallCount();
-    RetireAllPreRequisites();
-
-    if (retires_on_saturation_ && IsSaturated()) {
-      Retire();
-    }
-
-    // Must be done after IncrementCount()!
-    *what << "Mock function call matches " << source_text() <<"...\n";
-    return &(GetCurrentAction(mocker, args));
-  }
-
-  // All the fields below won't change once the EXPECT_CALL()
-  // statement finishes.
-  FunctionMockerBase<F>* const owner_;
-  ArgumentMatcherTuple matchers_;
-  Matcher<const ArgumentTuple&> extra_matcher_;
-  Action<F> repeated_action_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
-};  // class TypedExpectation
-
-// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
-// specifying the default behavior of, or expectation on, a mock
-// function.
-
-// Note: class MockSpec really belongs to the ::testing namespace.
-// However if we define it in ::testing, MSVC will complain when
-// classes in ::testing::internal declare it as a friend class
-// template.  To workaround this compiler bug, we define MockSpec in
-// ::testing::internal and import it into ::testing.
-
-// Logs a message including file and line number information.
-GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
-                                const char* file, int line,
-                                const string& message);
-
-template <typename F>
-class MockSpec {
- public:
-  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-  typedef typename internal::Function<F>::ArgumentMatcherTuple
-      ArgumentMatcherTuple;
-
-  // Constructs a MockSpec object, given the function mocker object
-  // that the spec is associated with.
-  explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
-      : function_mocker_(function_mocker) {}
-
-  // Adds a new default action spec to the function mocker and returns
-  // the newly created spec.
-  internal::OnCallSpec<F>& InternalDefaultActionSetAt(
-      const char* file, int line, const char* obj, const char* call) {
-    LogWithLocation(internal::kInfo, file, line,
-        string("ON_CALL(") + obj + ", " + call + ") invoked");
-    return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
-  }
-
-  // Adds a new expectation spec to the function mocker and returns
-  // the newly created spec.
-  internal::TypedExpectation<F>& InternalExpectedAt(
-      const char* file, int line, const char* obj, const char* call) {
-    const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
-    LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
-    return function_mocker_->AddNewExpectation(
-        file, line, source_text, matchers_);
-  }
-
- private:
-  template <typename Function>
-  friend class internal::FunctionMocker;
-
-  void SetMatchers(const ArgumentMatcherTuple& matchers) {
-    matchers_ = matchers;
-  }
-
-  // The function mocker that owns this spec.
-  internal::FunctionMockerBase<F>* const function_mocker_;
-  // The argument matchers specified in the spec.
-  ArgumentMatcherTuple matchers_;
-
-  GTEST_DISALLOW_ASSIGN_(MockSpec);
-};  // class MockSpec
-
-// Wrapper type for generically holding an ordinary value or lvalue reference.
-// If T is not a reference type, it must be copyable or movable.
-// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
-// T is a move-only value type (which means that it will always be copyable
-// if the current platform does not support move semantics).
-//
-// The primary template defines handling for values, but function header
-// comments describe the contract for the whole template (including
-// specializations).
-template <typename T>
-class ReferenceOrValueWrapper {
- public:
-  // Constructs a wrapper from the given value/reference.
-  explicit ReferenceOrValueWrapper(T value)
-      : value_(::testing::internal::move(value)) {
-  }
-
-  // Unwraps and returns the underlying value/reference, exactly as
-  // originally passed. The behavior of calling this more than once on
-  // the same object is unspecified.
-  T Unwrap() { return ::testing::internal::move(value_); }
-
-  // Provides nondestructive access to the underlying value/reference.
-  // Always returns a const reference (more precisely,
-  // const RemoveReference<T>&). The behavior of calling this after
-  // calling Unwrap on the same object is unspecified.
-  const T& Peek() const {
-    return value_;
-  }
-
- private:
-  T value_;
-};
-
-// Specialization for lvalue reference types. See primary template
-// for documentation.
-template <typename T>
-class ReferenceOrValueWrapper<T&> {
- public:
-  // Workaround for debatable pass-by-reference lint warning (c-library-team
-  // policy precludes NOLINT in this context)
-  typedef T& reference;
-  explicit ReferenceOrValueWrapper(reference ref)
-      : value_ptr_(&ref) {}
-  T& Unwrap() { return *value_ptr_; }
-  const T& Peek() const { return *value_ptr_; }
-
- private:
-  T* value_ptr_;
-};
-
-// MSVC warns about using 'this' in base member initializer list, so
-// we need to temporarily disable the warning.  We have to do it for
-// the entire class to suppress the warning, even though it's about
-// the constructor only.
-
-#ifdef _MSC_VER
-# pragma warning(push)          // Saves the current warning state.
-# pragma warning(disable:4355)  // Temporarily disables warning 4355.
-#endif  // _MSV_VER
-
-// C++ treats the void type specially.  For example, you cannot define
-// a void-typed variable or pass a void value to a function.
-// ActionResultHolder<T> holds a value of type T, where T must be a
-// copyable type or void (T doesn't need to be default-constructable).
-// It hides the syntactic difference between void and other types, and
-// is used to unify the code for invoking both void-returning and
-// non-void-returning mock functions.
-
-// Untyped base class for ActionResultHolder<T>.
-class UntypedActionResultHolderBase {
- public:
-  virtual ~UntypedActionResultHolderBase() {}
-
-  // Prints the held value as an action's result to os.
-  virtual void PrintAsActionResult(::std::ostream* os) const = 0;
-};
-
-// This generic definition is used when T is not void.
-template <typename T>
-class ActionResultHolder : public UntypedActionResultHolderBase {
- public:
-  // Returns the held value. Must not be called more than once.
-  T Unwrap() {
-    return result_.Unwrap();
-  }
-
-  // Prints the held value as an action's result to os.
-  virtual void PrintAsActionResult(::std::ostream* os) const {
-    *os << "\n          Returns: ";
-    // T may be a reference type, so we don't use UniversalPrint().
-    UniversalPrinter<T>::Print(result_.Peek(), os);
-  }
-
-  // Performs the given mock function's default action and returns the
-  // result in a new-ed ActionResultHolder.
-  template <typename F>
-  static ActionResultHolder* PerformDefaultAction(
-      const FunctionMockerBase<F>* func_mocker,
-      const typename Function<F>::ArgumentTuple& args,
-      const string& call_description) {
-    return new ActionResultHolder(Wrapper(
-        func_mocker->PerformDefaultAction(args, call_description)));
-  }
-
-  // Performs the given action and returns the result in a new-ed
-  // ActionResultHolder.
-  template <typename F>
-  static ActionResultHolder*
-  PerformAction(const Action<F>& action,
-                const typename Function<F>::ArgumentTuple& args) {
-    return new ActionResultHolder(Wrapper(action.Perform(args)));
-  }
-
- private:
-  typedef ReferenceOrValueWrapper<T> Wrapper;
-
-  explicit ActionResultHolder(Wrapper result)
-      : result_(::testing::internal::move(result)) {
-  }
-
-  Wrapper result_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
-};
-
-// Specialization for T = void.
-template <>
-class ActionResultHolder<void> : public UntypedActionResultHolderBase {
- public:
-  void Unwrap() { }
-
-  virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
-
-  // Performs the given mock function's default action and returns ownership
-  // of an empty ActionResultHolder*.
-  template <typename F>
-  static ActionResultHolder* PerformDefaultAction(
-      const FunctionMockerBase<F>* func_mocker,
-      const typename Function<F>::ArgumentTuple& args,
-      const string& call_description) {
-    func_mocker->PerformDefaultAction(args, call_description);
-    return new ActionResultHolder;
-  }
-
-  // Performs the given action and returns ownership of an empty
-  // ActionResultHolder*.
-  template <typename F>
-  static ActionResultHolder* PerformAction(
-      const Action<F>& action,
-      const typename Function<F>::ArgumentTuple& args) {
-    action.Perform(args);
-    return new ActionResultHolder;
-  }
-
- private:
-  ActionResultHolder() {}
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
-};
-
-// The base of the function mocker class for the given function type.
-// We put the methods in this class instead of its child to avoid code
-// bloat.
-template <typename F>
-class FunctionMockerBase : public UntypedFunctionMockerBase {
- public:
-  typedef typename Function<F>::Result Result;
-  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
-  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
-
-  FunctionMockerBase() : current_spec_(this) {}
-
-  // The destructor verifies that all expectations on this mock
-  // function have been satisfied.  If not, it will report Google Test
-  // non-fatal failures for the violations.
-  virtual ~FunctionMockerBase()
-        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    MutexLock l(&g_gmock_mutex);
-    VerifyAndClearExpectationsLocked();
-    Mock::UnregisterLocked(this);
-    ClearDefaultActionsLocked();
-  }
-
-  // Returns the ON_CALL spec that matches this mock function with the
-  // given arguments; returns NULL if no matching ON_CALL is found.
-  // L = *
-  const OnCallSpec<F>* FindOnCallSpec(
-      const ArgumentTuple& args) const {
-    for (UntypedOnCallSpecs::const_reverse_iterator it
-             = untyped_on_call_specs_.rbegin();
-         it != untyped_on_call_specs_.rend(); ++it) {
-      const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
-      if (spec->Matches(args))
-        return spec;
-    }
-
-    return NULL;
-  }
-
-  // Performs the default action of this mock function on the given
-  // arguments and returns the result. Asserts (or throws if
-  // exceptions are enabled) with a helpful call descrption if there
-  // is no valid return value. This method doesn't depend on the
-  // mutable state of this object, and thus can be called concurrently
-  // without locking.
-  // L = *
-  Result PerformDefaultAction(const ArgumentTuple& args,
-                              const string& call_description) const {
-    const OnCallSpec<F>* const spec =
-        this->FindOnCallSpec(args);
-    if (spec != NULL) {
-      return spec->GetAction().Perform(args);
-    }
-    const string message = call_description +
-        "\n    The mock function has no default action "
-        "set, and its return type has no default value set.";
-#if GTEST_HAS_EXCEPTIONS
-    if (!DefaultValue<Result>::Exists()) {
-      throw std::runtime_error(message);
-    }
-#else
-    Assert(DefaultValue<Result>::Exists(), "", -1, message);
-#endif
-    return DefaultValue<Result>::Get();
-  }
-
-  // Performs the default action with the given arguments and returns
-  // the action's result.  The call description string will be used in
-  // the error message to describe the call in the case the default
-  // action fails.  The caller is responsible for deleting the result.
-  // L = *
-  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
-      const void* untyped_args,  // must point to an ArgumentTuple
-      const string& call_description) const {
-    const ArgumentTuple& args =
-        *static_cast<const ArgumentTuple*>(untyped_args);
-    return ResultHolder::PerformDefaultAction(this, args, call_description);
-  }
-
-  // Performs the given action with the given arguments and returns
-  // the action's result.  The caller is responsible for deleting the
-  // result.
-  // L = *
-  virtual UntypedActionResultHolderBase* UntypedPerformAction(
-      const void* untyped_action, const void* untyped_args) const {
-    // Make a copy of the action before performing it, in case the
-    // action deletes the mock object (and thus deletes itself).
-    const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
-    const ArgumentTuple& args =
-        *static_cast<const ArgumentTuple*>(untyped_args);
-    return ResultHolder::PerformAction(action, args);
-  }
-
-  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
-  // clears the ON_CALL()s set on this mock function.
-  virtual void ClearDefaultActionsLocked()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-
-    // Deleting our default actions may trigger other mock objects to be
-    // deleted, for example if an action contains a reference counted smart
-    // pointer to that mock object, and that is the last reference. So if we
-    // delete our actions within the context of the global mutex we may deadlock
-    // when this method is called again. Instead, make a copy of the set of
-    // actions to delete, clear our set within the mutex, and then delete the
-    // actions outside of the mutex.
-    UntypedOnCallSpecs specs_to_delete;
-    untyped_on_call_specs_.swap(specs_to_delete);
-
-    g_gmock_mutex.Unlock();
-    for (UntypedOnCallSpecs::const_iterator it =
-             specs_to_delete.begin();
-         it != specs_to_delete.end(); ++it) {
-      delete static_cast<const OnCallSpec<F>*>(*it);
-    }
-
-    // Lock the mutex again, since the caller expects it to be locked when we
-    // return.
-    g_gmock_mutex.Lock();
-  }
-
- protected:
-  template <typename Function>
-  friend class MockSpec;
-
-  typedef ActionResultHolder<Result> ResultHolder;
-
-  // Returns the result of invoking this mock function with the given
-  // arguments.  This function can be safely called from multiple
-  // threads concurrently.
-  Result InvokeWith(const ArgumentTuple& args)
-        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    scoped_ptr<ResultHolder> holder(
-        DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
-    return holder->Unwrap();
-  }
-
-  // Adds and returns a default action spec for this mock function.
-  OnCallSpec<F>& AddNewOnCallSpec(
-      const char* file, int line,
-      const ArgumentMatcherTuple& m)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
-    OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
-    untyped_on_call_specs_.push_back(on_call_spec);
-    return *on_call_spec;
-  }
-
-  // Adds and returns an expectation spec for this mock function.
-  TypedExpectation<F>& AddNewExpectation(
-      const char* file,
-      int line,
-      const string& source_text,
-      const ArgumentMatcherTuple& m)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
-    TypedExpectation<F>* const expectation =
-        new TypedExpectation<F>(this, file, line, source_text, m);
-    const linked_ptr<ExpectationBase> untyped_expectation(expectation);
-    untyped_expectations_.push_back(untyped_expectation);
-
-    // Adds this expectation into the implicit sequence if there is one.
-    Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
-    if (implicit_sequence != NULL) {
-      implicit_sequence->AddExpectation(Expectation(untyped_expectation));
-    }
-
-    return *expectation;
-  }
-
-  // The current spec (either default action spec or expectation spec)
-  // being described on this function mocker.
-  MockSpec<F>& current_spec() { return current_spec_; }
-
- private:
-  template <typename Func> friend class TypedExpectation;
-
-  // Some utilities needed for implementing UntypedInvokeWith().
-
-  // Describes what default action will be performed for the given
-  // arguments.
-  // L = *
-  void DescribeDefaultActionTo(const ArgumentTuple& args,
-                               ::std::ostream* os) const {
-    const OnCallSpec<F>* const spec = FindOnCallSpec(args);
-
-    if (spec == NULL) {
-      *os << (internal::type_equals<Result, void>::value ?
-              "returning directly.\n" :
-              "returning default value.\n");
-    } else {
-      *os << "taking default action specified at:\n"
-          << FormatFileLocation(spec->file(), spec->line()) << "\n";
-    }
-  }
-
-  // Writes a message that the call is uninteresting (i.e. neither
-  // explicitly expected nor explicitly unexpected) to the given
-  // ostream.
-  virtual void UntypedDescribeUninterestingCall(
-      const void* untyped_args,
-      ::std::ostream* os) const
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    const ArgumentTuple& args =
-        *static_cast<const ArgumentTuple*>(untyped_args);
-    *os << "Uninteresting mock function call - ";
-    DescribeDefaultActionTo(args, os);
-    *os << "    Function call: " << Name();
-    UniversalPrint(args, os);
-  }
-
-  // Returns the expectation that matches the given function arguments
-  // (or NULL is there's no match); when a match is found,
-  // untyped_action is set to point to the action that should be
-  // performed (or NULL if the action is "do default"), and
-  // is_excessive is modified to indicate whether the call exceeds the
-  // expected number.
-  //
-  // Critical section: We must find the matching expectation and the
-  // corresponding action that needs to be taken in an ATOMIC
-  // transaction.  Otherwise another thread may call this mock
-  // method in the middle and mess up the state.
-  //
-  // However, performing the action has to be left out of the critical
-  // section.  The reason is that we have no control on what the
-  // action does (it can invoke an arbitrary user function or even a
-  // mock function) and excessive locking could cause a dead lock.
-  virtual const ExpectationBase* UntypedFindMatchingExpectation(
-      const void* untyped_args,
-      const void** untyped_action, bool* is_excessive,
-      ::std::ostream* what, ::std::ostream* why)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    const ArgumentTuple& args =
-        *static_cast<const ArgumentTuple*>(untyped_args);
-    MutexLock l(&g_gmock_mutex);
-    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
-    if (exp == NULL) {  // A match wasn't found.
-      this->FormatUnexpectedCallMessageLocked(args, what, why);
-      return NULL;
-    }
-
-    // This line must be done before calling GetActionForArguments(),
-    // which will increment the call count for *exp and thus affect
-    // its saturation status.
-    *is_excessive = exp->IsSaturated();
-    const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
-    if (action != NULL && action->IsDoDefault())
-      action = NULL;  // Normalize "do default" to NULL.
-    *untyped_action = action;
-    return exp;
-  }
-
-  // Prints the given function arguments to the ostream.
-  virtual void UntypedPrintArgs(const void* untyped_args,
-                                ::std::ostream* os) const {
-    const ArgumentTuple& args =
-        *static_cast<const ArgumentTuple*>(untyped_args);
-    UniversalPrint(args, os);
-  }
-
-  // Returns the expectation that matches the arguments, or NULL if no
-  // expectation matches them.
-  TypedExpectation<F>* FindMatchingExpectationLocked(
-      const ArgumentTuple& args) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    for (typename UntypedExpectations::const_reverse_iterator it =
-             untyped_expectations_.rbegin();
-         it != untyped_expectations_.rend(); ++it) {
-      TypedExpectation<F>* const exp =
-          static_cast<TypedExpectation<F>*>(it->get());
-      if (exp->ShouldHandleArguments(args)) {
-        return exp;
-      }
-    }
-    return NULL;
-  }
-
-  // Returns a message that the arguments don't match any expectation.
-  void FormatUnexpectedCallMessageLocked(
-      const ArgumentTuple& args,
-      ::std::ostream* os,
-      ::std::ostream* why) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    *os << "\nUnexpected mock function call - ";
-    DescribeDefaultActionTo(args, os);
-    PrintTriedExpectationsLocked(args, why);
-  }
-
-  // Prints a list of expectations that have been tried against the
-  // current mock function call.
-  void PrintTriedExpectationsLocked(
-      const ArgumentTuple& args,
-      ::std::ostream* why) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-    g_gmock_mutex.AssertHeld();
-    const int count = static_cast<int>(untyped_expectations_.size());
-    *why << "Google Mock tried the following " << count << " "
-         << (count == 1 ? "expectation, but it didn't match" :
-             "expectations, but none matched")
-         << ":\n";
-    for (int i = 0; i < count; i++) {
-      TypedExpectation<F>* const expectation =
-          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
-      *why << "\n";
-      expectation->DescribeLocationTo(why);
-      if (count > 1) {
-        *why << "tried expectation #" << i << ": ";
-      }
-      *why << expectation->source_text() << "...\n";
-      expectation->ExplainMatchResultTo(args, why);
-      expectation->DescribeCallCountTo(why);
-    }
-  }
-
-  // The current spec (either default action spec or expectation spec)
-  // being described on this function mocker.
-  MockSpec<F> current_spec_;
-
-  // There is no generally useful and implementable semantics of
-  // copying a mock object, so copying a mock is usually a user error.
-  // Thus we disallow copying function mockers.  If the user really
-  // wants to copy a mock object, he should implement his own copy
-  // operation, for example:
-  //
-  //   class MockFoo : public Foo {
-  //    public:
-  //     // Defines a copy constructor explicitly.
-  //     MockFoo(const MockFoo& src) {}
-  //     ...
-  //   };
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
-};  // class FunctionMockerBase
-
-#ifdef _MSC_VER
-# pragma warning(pop)  // Restores the warning state.
-#endif  // _MSV_VER
-
-// Implements methods of FunctionMockerBase.
-
-// Verifies that all expectations on this mock function have been
-// satisfied.  Reports one or more Google Test non-fatal failures and
-// returns false if not.
-
-// Reports an uninteresting call (whose description is in msg) in the
-// manner specified by 'reaction'.
-void ReportUninterestingCall(CallReaction reaction, const string& msg);
-
-}  // namespace internal
-
-// The style guide prohibits "using" statements in a namespace scope
-// inside a header file.  However, the MockSpec class template is
-// meant to be defined in the ::testing namespace.  The following line
-// is just a trick for working around a bug in MSVC 8.0, which cannot
-// handle it if we define MockSpec in ::testing.
-using internal::MockSpec;
-
-// Const(x) is a convenient function for obtaining a const reference
-// to x.  This is useful for setting expectations on an overloaded
-// const mock method, e.g.
-//
-//   class MockFoo : public FooInterface {
-//    public:
-//     MOCK_METHOD0(Bar, int());
-//     MOCK_CONST_METHOD0(Bar, int&());
-//   };
-//
-//   MockFoo foo;
-//   // Expects a call to non-const MockFoo::Bar().
-//   EXPECT_CALL(foo, Bar());
-//   // Expects a call to const MockFoo::Bar().
-//   EXPECT_CALL(Const(foo), Bar());
-template <typename T>
-inline const T& Const(const T& x) { return x; }
-
-// Constructs an Expectation object that references and co-owns exp.
-inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
-    : expectation_base_(exp.GetHandle().expectation_base()) {}
-
-}  // namespace testing
-
-// A separate macro is required to avoid compile errors when the name
-// of the method used in call is a result of macro expansion.
-// See CompilesWithMethodNameExpandedFromMacro tests in
-// internal/gmock-spec-builders_test.cc for more details.
-#define GMOCK_ON_CALL_IMPL_(obj, call) \
-    ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
-                                                    #obj, #call)
-#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
-
-#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
-    ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
-#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
diff --git a/testing/gmock/include/gmock/gmock.h b/testing/gmock/include/gmock/gmock.h
index 6735c71..e8d1b3b 100644
--- a/testing/gmock/include/gmock/gmock.h
+++ b/testing/gmock/include/gmock/gmock.h
@@ -1,94 +1,15 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
+// Copyright 2017 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
 
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This is the main header file a user should include.
+#ifndef TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#define TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_H_
 
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_H_
+// The file/directory layout of Google Test is not yet considered stable. Until
+// it stabilizes, Chromium code will use forwarding headers in testing/gtest
+// and testing/gmock, instead of directly including files in
+// third_party/googletest.
 
-// This file implements the following syntax:
-//
-//   ON_CALL(mock_object.Method(...))
-//     .With(...) ?
-//     .WillByDefault(...);
-//
-// where With() is optional and WillByDefault() must appear exactly
-// once.
-//
-//   EXPECT_CALL(mock_object.Method(...))
-//     .With(...) ?
-//     .Times(...) ?
-//     .InSequence(...) *
-//     .WillOnce(...) *
-//     .WillRepeatedly(...) ?
-//     .RetiresOnSaturation() ? ;
-//
-// where all clauses are optional and WillOnce() can be repeated.
+#include "third_party/googletest/src/googlemock/include/gmock/gmock.h"  // IWYU pragma: export
 
-#include "gmock/gmock-actions.h"
-#include "gmock/gmock-cardinalities.h"
-#include "gmock/gmock-generated-actions.h"
-#include "gmock/gmock-generated-function-mockers.h"
-#include "gmock/gmock-generated-nice-strict.h"
-#include "gmock/gmock-generated-matchers.h"
-#include "gmock/gmock-matchers.h"
-#include "gmock/gmock-more-actions.h"
-#include "gmock/gmock-more-matchers.h"
-#include "gmock/internal/gmock-internal-utils.h"
-
-namespace testing {
-
-// Declares Google Mock flags that we want a user to use programmatically.
-GMOCK_DECLARE_bool_(catch_leaked_mocks);
-GMOCK_DECLARE_string_(verbose);
-
-// Initializes Google Mock.  This must be called before running the
-// tests.  In particular, it parses the command line for the flags
-// that Google Mock recognizes.  Whenever a Google Mock flag is seen,
-// it is removed from argv, and *argc is decremented.
-//
-// No value is returned.  Instead, the Google Mock flag variables are
-// updated.
-//
-// Since Google Test is needed for Google Mock to work, this function
-// also initializes Google Test and parses its flags, if that hasn't
-// been done.
-GTEST_API_ void InitGoogleMock(int* argc, char** argv);
-
-// This overloaded version can be used in Windows programs compiled in
-// UNICODE mode.
-GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#endif  // TESTING_GMOCK_INCLUDE_GMOCK_GMOCK_H_
diff --git a/testing/gmock/include/gmock/internal/custom/gmock-generated-actions.h b/testing/gmock/include/gmock/internal/custom/gmock-generated-actions.h
deleted file mode 100644
index 7dc3b1a..0000000
--- a/testing/gmock/include/gmock/internal/custom/gmock-generated-actions.h
+++ /dev/null
@@ -1,8 +0,0 @@
-// This file was GENERATED by command:
-//     pump.py gmock-generated-actions.h.pump
-// DO NOT EDIT BY HAND!!!
-
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
diff --git a/testing/gmock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/testing/gmock/include/gmock/internal/custom/gmock-generated-actions.h.pump
deleted file mode 100644
index d26c8a0..0000000
--- a/testing/gmock/include/gmock/internal/custom/gmock-generated-actions.h.pump
+++ /dev/null
@@ -1,10 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file (http://go/pump).  Please use Pump to convert
-$$ it to callback-actions.h.
-$$
-$var max_callback_arity = 5
-$$}} This meta comment fixes auto-indentation in editors.
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
diff --git a/testing/gmock/include/gmock/internal/custom/gmock-matchers.h b/testing/gmock/include/gmock/internal/custom/gmock-matchers.h
deleted file mode 100644
index f2efef9..0000000
--- a/testing/gmock/include/gmock/internal/custom/gmock-matchers.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2015, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// ============================================================
-// An installation-specific extension point for gmock-matchers.h.
-// ============================================================
-//
-// Adds google3 callback support to CallableTraits.
-//
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
-
-#endif  //  GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
diff --git a/testing/gmock/include/gmock/internal/custom/gmock-port.h b/testing/gmock/include/gmock/internal/custom/gmock-port.h
deleted file mode 100644
index 9ce8bfe..0000000
--- a/testing/gmock/include/gmock/internal/custom/gmock-port.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2015, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Injection point for custom user configurations.
-// The following macros can be defined:
-//
-//   Flag related macros:
-//     GMOCK_DECLARE_bool_(name)
-//     GMOCK_DECLARE_int32_(name)
-//     GMOCK_DECLARE_string_(name)
-//     GMOCK_DEFINE_bool_(name, default_val, doc)
-//     GMOCK_DEFINE_int32_(name, default_val, doc)
-//     GMOCK_DEFINE_string_(name, default_val, doc)
-//
-// ** Custom implementation starts here **
-
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
diff --git a/testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h b/testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h
deleted file mode 100644
index 7811e43..0000000
--- a/testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h
+++ /dev/null
@@ -1,279 +0,0 @@
-// This file was GENERATED by command:
-//     pump.py gmock-generated-internal-utils.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file contains template meta-programming utility classes needed
-// for implementing Google Mock.
-
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
-
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-
-template <typename T>
-class Matcher;
-
-namespace internal {
-
-// An IgnoredValue object can be implicitly constructed from ANY value.
-// This is used in implementing the IgnoreResult(a) action.
-class IgnoredValue {
- public:
-  // This constructor template allows any value to be implicitly
-  // converted to IgnoredValue.  The object has no data member and
-  // doesn't try to remember anything about the argument.  We
-  // deliberately omit the 'explicit' keyword in order to allow the
-  // conversion to be implicit.
-  template <typename T>
-  IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
-};
-
-// MatcherTuple<T>::type is a tuple type where each field is a Matcher
-// for the corresponding field in tuple type T.
-template <typename Tuple>
-struct MatcherTuple;
-
-template <>
-struct MatcherTuple< ::testing::tuple<> > {
-  typedef ::testing::tuple< > type;
-};
-
-template <typename A1>
-struct MatcherTuple< ::testing::tuple<A1> > {
-  typedef ::testing::tuple<Matcher<A1> > type;
-};
-
-template <typename A1, typename A2>
-struct MatcherTuple< ::testing::tuple<A1, A2> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type;
-};
-
-template <typename A1, typename A2, typename A3>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>,
-      Matcher<A4> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4, typename A5>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
-      Matcher<A5> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4, typename A5,
-    typename A6>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
-      Matcher<A5>, Matcher<A6> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4, typename A5,
-    typename A6, typename A7>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
-      Matcher<A5>, Matcher<A6>, Matcher<A7> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4, typename A5,
-    typename A6, typename A7, typename A8>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
-      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4, typename A5,
-    typename A6, typename A7, typename A8, typename A9>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
-      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type;
-};
-
-template <typename A1, typename A2, typename A3, typename A4, typename A5,
-    typename A6, typename A7, typename A8, typename A9, typename A10>
-struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
-    A10> > {
-  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
-      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>,
-      Matcher<A10> > type;
-};
-
-// Template struct Function<F>, where F must be a function type, contains
-// the following typedefs:
-//
-//   Result:               the function's return type.
-//   ArgumentN:            the type of the N-th argument, where N starts with 1.
-//   ArgumentTuple:        the tuple type consisting of all parameters of F.
-//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
-//                         parameters of F.
-//   MakeResultVoid:       the function type obtained by substituting void
-//                         for the return type of F.
-//   MakeResultIgnoredValue:
-//                         the function type obtained by substituting Something
-//                         for the return type of F.
-template <typename F>
-struct Function;
-
-template <typename R>
-struct Function<R()> {
-  typedef R Result;
-  typedef ::testing::tuple<> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid();
-  typedef IgnoredValue MakeResultIgnoredValue();
-};
-
-template <typename R, typename A1>
-struct Function<R(A1)>
-    : Function<R()> {
-  typedef A1 Argument1;
-  typedef ::testing::tuple<A1> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1);
-  typedef IgnoredValue MakeResultIgnoredValue(A1);
-};
-
-template <typename R, typename A1, typename A2>
-struct Function<R(A1, A2)>
-    : Function<R(A1)> {
-  typedef A2 Argument2;
-  typedef ::testing::tuple<A1, A2> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2);
-};
-
-template <typename R, typename A1, typename A2, typename A3>
-struct Function<R(A1, A2, A3)>
-    : Function<R(A1, A2)> {
-  typedef A3 Argument3;
-  typedef ::testing::tuple<A1, A2, A3> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4>
-struct Function<R(A1, A2, A3, A4)>
-    : Function<R(A1, A2, A3)> {
-  typedef A4 Argument4;
-  typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-struct Function<R(A1, A2, A3, A4, A5)>
-    : Function<R(A1, A2, A3, A4)> {
-  typedef A5 Argument5;
-  typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4, A5);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-struct Function<R(A1, A2, A3, A4, A5, A6)>
-    : Function<R(A1, A2, A3, A4, A5)> {
-  typedef A6 Argument6;
-  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-struct Function<R(A1, A2, A3, A4, A5, A6, A7)>
-    : Function<R(A1, A2, A3, A4, A5, A6)> {
-  typedef A7 Argument7;
-  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8>
-struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)>
-    : Function<R(A1, A2, A3, A4, A5, A6, A7)> {
-  typedef A8 Argument8;
-  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8, typename A9>
-struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)>
-    : Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> {
-  typedef A9 Argument9;
-  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
-      A9);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7, typename A8, typename A9,
-    typename A10>
-struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>
-    : Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
-  typedef A10 Argument10;
-  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
-      A10> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
-  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
-      A9, A10);
-};
-
-}  // namespace internal
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
diff --git a/testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h.pump b/testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h.pump
deleted file mode 100644
index 800af17..0000000
--- a/testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h.pump
+++ /dev/null
@@ -1,136 +0,0 @@
-$$ -*- mode: c++; -*-
-$$ This is a Pump source file.  Please use Pump to convert it to
-$$ gmock-generated-function-mockers.h.
-$$
-$var n = 10  $$ The maximum arity we support.
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file contains template meta-programming utility classes needed
-// for implementing Google Mock.
-
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
-
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-
-template <typename T>
-class Matcher;
-
-namespace internal {
-
-// An IgnoredValue object can be implicitly constructed from ANY value.
-// This is used in implementing the IgnoreResult(a) action.
-class IgnoredValue {
- public:
-  // This constructor template allows any value to be implicitly
-  // converted to IgnoredValue.  The object has no data member and
-  // doesn't try to remember anything about the argument.  We
-  // deliberately omit the 'explicit' keyword in order to allow the
-  // conversion to be implicit.
-  template <typename T>
-  IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
-};
-
-// MatcherTuple<T>::type is a tuple type where each field is a Matcher
-// for the corresponding field in tuple type T.
-template <typename Tuple>
-struct MatcherTuple;
-
-
-$range i 0..n
-$for i [[
-$range j 1..i
-$var typename_As = [[$for j, [[typename A$j]]]]
-$var As = [[$for j, [[A$j]]]]
-$var matcher_As = [[$for j, [[Matcher<A$j>]]]]
-template <$typename_As>
-struct MatcherTuple< ::testing::tuple<$As> > {
-  typedef ::testing::tuple<$matcher_As > type;
-};
-
-
-]]
-// Template struct Function<F>, where F must be a function type, contains
-// the following typedefs:
-//
-//   Result:               the function's return type.
-//   ArgumentN:            the type of the N-th argument, where N starts with 1.
-//   ArgumentTuple:        the tuple type consisting of all parameters of F.
-//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
-//                         parameters of F.
-//   MakeResultVoid:       the function type obtained by substituting void
-//                         for the return type of F.
-//   MakeResultIgnoredValue:
-//                         the function type obtained by substituting Something
-//                         for the return type of F.
-template <typename F>
-struct Function;
-
-template <typename R>
-struct Function<R()> {
-  typedef R Result;
-  typedef ::testing::tuple<> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid();
-  typedef IgnoredValue MakeResultIgnoredValue();
-};
-
-
-$range i 1..n
-$for i [[
-$range j 1..i
-$var typename_As = [[$for j [[, typename A$j]]]]
-$var As = [[$for j, [[A$j]]]]
-$var matcher_As = [[$for j, [[Matcher<A$j>]]]]
-$range k 1..i-1
-$var prev_As = [[$for k, [[A$k]]]]
-template <typename R$typename_As>
-struct Function<R($As)>
-    : Function<R($prev_As)> {
-  typedef A$i Argument$i;
-  typedef ::testing::tuple<$As> ArgumentTuple;
-  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
-  typedef void MakeResultVoid($As);
-  typedef IgnoredValue MakeResultIgnoredValue($As);
-};
-
-
-]]
-}  // namespace internal
-
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
diff --git a/testing/gmock/include/gmock/internal/gmock-internal-utils.h b/testing/gmock/include/gmock/internal/gmock-internal-utils.h
deleted file mode 100644
index d734eee..0000000
--- a/testing/gmock/include/gmock/internal/gmock-internal-utils.h
+++ /dev/null
@@ -1,514 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file defines some utilities useful for implementing Google
-// Mock.  They are subject to change without notice, so please DO NOT
-// USE THEM IN USER CODE.
-
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
-
-#if !defined(STARBOARD)
-#include <stdio.h>
-#endif
-
-#include <ostream>  // NOLINT
-#include <string>
-
-#include "gmock/internal/gmock-generated-internal-utils.h"
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace internal {
-
-// Converts an identifier name to a space-separated list of lower-case
-// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
-// treated as one word.  For example, both "FooBar123" and
-// "foo_bar_123" are converted to "foo bar 123".
-GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name);
-
-// PointeeOf<Pointer>::type is the type of a value pointed to by a
-// Pointer, which can be either a smart pointer or a raw pointer.  The
-// following default implementation is for the case where Pointer is a
-// smart pointer.
-template <typename Pointer>
-struct PointeeOf {
-  // Smart pointer classes define type element_type as the type of
-  // their pointees.
-  typedef typename Pointer::element_type type;
-};
-// This specialization is for the raw pointer case.
-template <typename T>
-struct PointeeOf<T*> { typedef T type; };  // NOLINT
-
-// GetRawPointer(p) returns the raw pointer underlying p when p is a
-// smart pointer, or returns p itself when p is already a raw pointer.
-// The following default implementation is for the smart pointer case.
-template <typename Pointer>
-inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
-  return p.get();
-}
-// This overloaded version is for the raw pointer case.
-template <typename Element>
-inline Element* GetRawPointer(Element* p) { return p; }
-
-// This comparator allows linked_ptr to be stored in sets.
-template <typename T>
-struct LinkedPtrLessThan {
-  bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
-                  const ::testing::internal::linked_ptr<T>& rhs) const {
-    return lhs.get() < rhs.get();
-  }
-};
-
-// Symbian compilation can be done with wchar_t being either a native
-// type or a typedef.  Using Google Mock with OpenC without wchar_t
-// should require the definition of _STLP_NO_WCHAR_T.
-//
-// MSVC treats wchar_t as a native type usually, but treats it as the
-// same as unsigned short when the compiler option /Zc:wchar_t- is
-// specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
-// is a native type.
-#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
-    (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
-// wchar_t is a typedef.
-#else
-# define GMOCK_WCHAR_T_IS_NATIVE_ 1
-#endif
-
-// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
-// Using them is a bad practice and not portable.  So DON'T use them.
-//
-// Still, Google Mock is designed to work even if the user uses signed
-// wchar_t or unsigned wchar_t (obviously, assuming the compiler
-// supports them).
-//
-// To gcc,
-//   wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
-#ifdef __GNUC__
-// signed/unsigned wchar_t are valid types.
-# define GMOCK_HAS_SIGNED_WCHAR_T_ 1
-#endif
-
-// In what follows, we use the term "kind" to indicate whether a type
-// is bool, an integer type (excluding bool), a floating-point type,
-// or none of them.  This categorization is useful for determining
-// when a matcher argument type can be safely converted to another
-// type in the implementation of SafeMatcherCast.
-enum TypeKind {
-  kBool, kInteger, kFloatingPoint, kOther
-};
-
-// KindOf<T>::value is the kind of type T.
-template <typename T> struct KindOf {
-  enum { value = kOther };  // The default kind.
-};
-
-// This macro declares that the kind of 'type' is 'kind'.
-#define GMOCK_DECLARE_KIND_(type, kind) \
-  template <> struct KindOf<type> { enum { value = kind }; }
-
-GMOCK_DECLARE_KIND_(bool, kBool);
-
-// All standard integer types.
-GMOCK_DECLARE_KIND_(char, kInteger);
-GMOCK_DECLARE_KIND_(signed char, kInteger);
-GMOCK_DECLARE_KIND_(unsigned char, kInteger);
-GMOCK_DECLARE_KIND_(short, kInteger);  // NOLINT
-GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
-GMOCK_DECLARE_KIND_(int, kInteger);
-GMOCK_DECLARE_KIND_(unsigned int, kInteger);
-GMOCK_DECLARE_KIND_(long, kInteger);  // NOLINT
-GMOCK_DECLARE_KIND_(unsigned long, kInteger);  // NOLINT
-
-#if GMOCK_WCHAR_T_IS_NATIVE_
-GMOCK_DECLARE_KIND_(wchar_t, kInteger);
-#endif
-
-// Non-standard integer types.
-GMOCK_DECLARE_KIND_(Int64, kInteger);
-GMOCK_DECLARE_KIND_(UInt64, kInteger);
-
-// All standard floating-point types.
-GMOCK_DECLARE_KIND_(float, kFloatingPoint);
-GMOCK_DECLARE_KIND_(double, kFloatingPoint);
-GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
-
-#undef GMOCK_DECLARE_KIND_
-
-// Evaluates to the kind of 'type'.
-#define GMOCK_KIND_OF_(type) \
-  static_cast< ::testing::internal::TypeKind>( \
-      ::testing::internal::KindOf<type>::value)
-
-// Evaluates to true iff integer type T is signed.
-#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
-
-// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
-// is true iff arithmetic type From can be losslessly converted to
-// arithmetic type To.
-//
-// It's the user's responsibility to ensure that both From and To are
-// raw (i.e. has no CV modifier, is not a pointer, and is not a
-// reference) built-in arithmetic types, kFromKind is the kind of
-// From, and kToKind is the kind of To; the value is
-// implementation-defined when the above pre-condition is violated.
-template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
-struct LosslessArithmeticConvertibleImpl : public false_type {};
-
-// Converting bool to bool is lossless.
-template <>
-struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
-    : public true_type {};  // NOLINT
-
-// Converting bool to any integer type is lossless.
-template <typename To>
-struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
-    : public true_type {};  // NOLINT
-
-// Converting bool to any floating-point type is lossless.
-template <typename To>
-struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
-    : public true_type {};  // NOLINT
-
-// Converting an integer to bool is lossy.
-template <typename From>
-struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
-    : public false_type {};  // NOLINT
-
-// Converting an integer to another non-bool integer is lossless iff
-// the target type's range encloses the source type's range.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
-    : public bool_constant<
-      // When converting from a smaller size to a larger size, we are
-      // fine as long as we are not converting from signed to unsigned.
-      ((sizeof(From) < sizeof(To)) &&
-       (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
-      // When converting between the same size, the signedness must match.
-      ((sizeof(From) == sizeof(To)) &&
-       (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {};  // NOLINT
-
-#undef GMOCK_IS_SIGNED_
-
-// Converting an integer to a floating-point type may be lossy, since
-// the format of a floating-point number is implementation-defined.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
-    : public false_type {};  // NOLINT
-
-// Converting a floating-point to bool is lossy.
-template <typename From>
-struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
-    : public false_type {};  // NOLINT
-
-// Converting a floating-point to an integer is lossy.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
-    : public false_type {};  // NOLINT
-
-// Converting a floating-point to another floating-point is lossless
-// iff the target type is at least as big as the source type.
-template <typename From, typename To>
-struct LosslessArithmeticConvertibleImpl<
-  kFloatingPoint, From, kFloatingPoint, To>
-    : public bool_constant<sizeof(From) <= sizeof(To)> {};  // NOLINT
-
-// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
-// type From can be losslessly converted to arithmetic type To.
-//
-// It's the user's responsibility to ensure that both From and To are
-// raw (i.e. has no CV modifier, is not a pointer, and is not a
-// reference) built-in arithmetic types; the value is
-// implementation-defined when the above pre-condition is violated.
-template <typename From, typename To>
-struct LosslessArithmeticConvertible
-    : public LosslessArithmeticConvertibleImpl<
-  GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {};  // NOLINT
-
-// This interface knows how to report a Google Mock failure (either
-// non-fatal or fatal).
-class FailureReporterInterface {
- public:
-  // The type of a failure (either non-fatal or fatal).
-  enum FailureType {
-    kNonfatal, kFatal
-  };
-
-  virtual ~FailureReporterInterface() {}
-
-  // Reports a failure that occurred at the given source file location.
-  virtual void ReportFailure(FailureType type, const char* file, int line,
-                             const string& message) = 0;
-};
-
-// Returns the failure reporter used by Google Mock.
-GTEST_API_ FailureReporterInterface* GetFailureReporter();
-
-// Asserts that condition is true; aborts the process with the given
-// message if condition is false.  We cannot use LOG(FATAL) or CHECK()
-// as Google Mock might be used to mock the log sink itself.  We
-// inline this function to prevent it from showing up in the stack
-// trace.
-inline void Assert(bool condition, const char* file, int line,
-                   const string& msg) {
-  if (!condition) {
-    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
-                                        file, line, msg);
-  }
-}
-inline void Assert(bool condition, const char* file, int line) {
-  Assert(condition, file, line, "Assertion failed.");
-}
-
-// Verifies that condition is true; generates a non-fatal failure if
-// condition is false.
-inline void Expect(bool condition, const char* file, int line,
-                   const string& msg) {
-  if (!condition) {
-    GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
-                                        file, line, msg);
-  }
-}
-inline void Expect(bool condition, const char* file, int line) {
-  Expect(condition, file, line, "Expectation failed.");
-}
-
-// Severity level of a log.
-enum LogSeverity {
-  kInfo = 0,
-  kWarning = 1
-};
-
-// Valid values for the --gmock_verbose flag.
-
-// All logs (informational and warnings) are printed.
-const char kInfoVerbosity[] = "info";
-// Only warnings are printed.
-const char kWarningVerbosity[] = "warning";
-// No logs are printed.
-const char kErrorVerbosity[] = "error";
-
-// Returns true iff a log with the given severity is visible according
-// to the --gmock_verbose flag.
-GTEST_API_ bool LogIsVisible(LogSeverity severity);
-
-// Prints the given message to stdout iff 'severity' >= the level
-// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
-// 0, also prints the stack trace excluding the top
-// stack_frames_to_skip frames.  In opt mode, any positive
-// stack_frames_to_skip is treated as 0, since we don't know which
-// function calls will be inlined by the compiler and need to be
-// conservative.
-GTEST_API_ void Log(LogSeverity severity,
-                    const string& message,
-                    int stack_frames_to_skip);
-
-// TODO(wan@google.com): group all type utilities together.
-
-// Type traits.
-
-// is_reference<T>::value is non-zero iff T is a reference type.
-template <typename T> struct is_reference : public false_type {};
-template <typename T> struct is_reference<T&> : public true_type {};
-
-// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
-template <typename T1, typename T2> struct type_equals : public false_type {};
-template <typename T> struct type_equals<T, T> : public true_type {};
-
-// remove_reference<T>::type removes the reference from type T, if any.
-template <typename T> struct remove_reference { typedef T type; };  // NOLINT
-template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
-
-// DecayArray<T>::type turns an array type U[N] to const U* and preserves
-// other types.  Useful for saving a copy of a function argument.
-template <typename T> struct DecayArray { typedef T type; };  // NOLINT
-template <typename T, size_t N> struct DecayArray<T[N]> {
-  typedef const T* type;
-};
-// Sometimes people use arrays whose size is not available at the use site
-// (e.g. extern const char kNamePrefix[]).  This specialization covers that
-// case.
-template <typename T> struct DecayArray<T[]> {
-  typedef const T* type;
-};
-
-// Disable MSVC warnings for infinite recursion, since in this case the
-// the recursion is unreachable.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4717)
-#endif
-
-// Invalid<T>() is usable as an expression of type T, but will terminate
-// the program with an assertion failure if actually run.  This is useful
-// when a value of type T is needed for compilation, but the statement
-// will not really be executed (or we don't care if the statement
-// crashes).
-template <typename T>
-inline T Invalid() {
-  Assert(false, "", -1, "Internal error: attempt to return invalid value");
-  // This statement is unreachable, and would never terminate even if it
-  // could be reached. It is provided only to placate compiler warnings
-  // about missing return statements.
-  return Invalid<T>();
-}
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-// Given a raw type (i.e. having no top-level reference or const
-// modifier) RawContainer that's either an STL-style container or a
-// native array, class StlContainerView<RawContainer> has the
-// following members:
-//
-//   - type is a type that provides an STL-style container view to
-//     (i.e. implements the STL container concept for) RawContainer;
-//   - const_reference is a type that provides a reference to a const
-//     RawContainer;
-//   - ConstReference(raw_container) returns a const reference to an STL-style
-//     container view to raw_container, which is a RawContainer.
-//   - Copy(raw_container) returns an STL-style container view of a
-//     copy of raw_container, which is a RawContainer.
-//
-// This generic version is used when RawContainer itself is already an
-// STL-style container.
-template <class RawContainer>
-class StlContainerView {
- public:
-  typedef RawContainer type;
-  typedef const type& const_reference;
-
-  static const_reference ConstReference(const RawContainer& container) {
-    // Ensures that RawContainer is not a const type.
-    testing::StaticAssertTypeEq<RawContainer,
-        GTEST_REMOVE_CONST_(RawContainer)>();
-    return container;
-  }
-  static type Copy(const RawContainer& container) { return container; }
-};
-
-// This specialization is used when RawContainer is a native array type.
-template <typename Element, size_t N>
-class StlContainerView<Element[N]> {
- public:
-  typedef GTEST_REMOVE_CONST_(Element) RawElement;
-  typedef internal::NativeArray<RawElement> type;
-  // NativeArray<T> can represent a native array either by value or by
-  // reference (selected by a constructor argument), so 'const type'
-  // can be used to reference a const native array.  We cannot
-  // 'typedef const type& const_reference' here, as that would mean
-  // ConstReference() has to return a reference to a local variable.
-  typedef const type const_reference;
-
-  static const_reference ConstReference(const Element (&array)[N]) {
-    // Ensures that Element is not a const type.
-    testing::StaticAssertTypeEq<Element, RawElement>();
-#if GTEST_OS_SYMBIAN
-    // The Nokia Symbian compiler confuses itself in template instantiation
-    // for this call without the cast to Element*:
-    // function call '[testing::internal::NativeArray<char *>].NativeArray(
-    //     {lval} const char *[4], long, testing::internal::RelationToSource)'
-    //     does not match
-    // 'testing::internal::NativeArray<char *>::NativeArray(
-    //     char *const *, unsigned int, testing::internal::RelationToSource)'
-    // (instantiating: 'testing::internal::ContainsMatcherImpl
-    //     <const char * (&)[4]>::Matches(const char * (&)[4]) const')
-    // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
-    //     ConstReference(const char * (&)[4])')
-    // (and though the N parameter type is mismatched in the above explicit
-    // conversion of it doesn't help - only the conversion of the array).
-    return type(const_cast<Element*>(&array[0]), N,
-                RelationToSourceReference());
-#else
-    return type(array, N, RelationToSourceReference());
-#endif  // GTEST_OS_SYMBIAN
-  }
-  static type Copy(const Element (&array)[N]) {
-#if GTEST_OS_SYMBIAN
-    return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
-#else
-    return type(array, N, RelationToSourceCopy());
-#endif  // GTEST_OS_SYMBIAN
-  }
-};
-
-// This specialization is used when RawContainer is a native array
-// represented as a (pointer, size) tuple.
-template <typename ElementPointer, typename Size>
-class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
- public:
-  typedef GTEST_REMOVE_CONST_(
-      typename internal::PointeeOf<ElementPointer>::type) RawElement;
-  typedef internal::NativeArray<RawElement> type;
-  typedef const type const_reference;
-
-  static const_reference ConstReference(
-      const ::testing::tuple<ElementPointer, Size>& array) {
-    return type(get<0>(array), get<1>(array), RelationToSourceReference());
-  }
-  static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
-    return type(get<0>(array), get<1>(array), RelationToSourceCopy());
-  }
-};
-
-// The following specialization prevents the user from instantiating
-// StlContainer with a reference type.
-template <typename T> class StlContainerView<T&>;
-
-// A type transform to remove constness from the first part of a pair.
-// Pairs like that are used as the value_type of associative containers,
-// and this transform produces a similar but assignable pair.
-template <typename T>
-struct RemoveConstFromKey {
-  typedef T type;
-};
-
-// Partially specialized to remove constness from std::pair<const K, V>.
-template <typename K, typename V>
-struct RemoveConstFromKey<std::pair<const K, V> > {
-  typedef std::pair<K, V> type;
-};
-
-// Mapping from booleans to types. Similar to boost::bool_<kValue> and
-// std::integral_constant<bool, kValue>.
-template <bool kValue>
-struct BooleanConstant {};
-
-}  // namespace internal
-}  // namespace testing
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
-
diff --git a/testing/gmock/include/gmock/internal/gmock-port.h b/testing/gmock/include/gmock/internal/gmock-port.h
deleted file mode 100644
index 4b0fe16..0000000
--- a/testing/gmock/include/gmock/internal/gmock-port.h
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: vadimb@google.com (Vadim Berman)
-//
-// Low-level types and utilities for porting Google Mock to various
-// platforms.  All macros ending with _ and symbols defined in an
-// internal namespace are subject to change without notice.  Code
-// outside Google Mock MUST NOT USE THEM DIRECTLY.  Macros that don't
-// end with _ are part of Google Mock's public API and can be used by
-// code outside Google Mock.
-
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
-
-#if !defined(STARBOARD)
-#include <assert.h>
-#include <stdlib.h>
-#endif
-
-#include <iostream>
-
-// Most of the utilities needed for porting Google Mock are also
-// required for Google Test and are defined in gtest-port.h.
-//
-// Note to maintainers: to reduce code duplication, prefer adding
-// portability utilities to Google Test's gtest-port.h instead of
-// here, as Google Mock depends on Google Test.  Only add a utility
-// here if it's truly specific to Google Mock.
-#include "gtest/internal/gtest-linked_ptr.h"
-#include "gtest/internal/gtest-port.h"
-#include "gmock/internal/custom/gmock-port.h"
-
-// To avoid conditional compilation everywhere, we make it
-// gmock-port.h's responsibility to #include the header implementing
-// tr1/tuple.  gmock-port.h does this via gtest-port.h, which is
-// guaranteed to pull in the tuple header.
-
-// For MS Visual C++, check the compiler version. At least VS 2003 is
-// required to compile Google Mock.
-#if defined(_MSC_VER) && _MSC_VER < 1310
-# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock."
-#endif
-
-// Macro for referencing flags.  This is public as we want the user to
-// use this syntax to reference Google Mock flags.
-#define GMOCK_FLAG(name) FLAGS_gmock_##name
-
-#if !defined(GMOCK_DECLARE_bool_)
-
-// Macros for declaring flags.
-#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
-#define GMOCK_DECLARE_int32_(name) \
-    extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name)
-#define GMOCK_DECLARE_string_(name) \
-    extern GTEST_API_ ::std::string GMOCK_FLAG(name)
-
-// Macros for defining flags.
-#define GMOCK_DEFINE_bool_(name, default_val, doc) \
-    GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
-#define GMOCK_DEFINE_int32_(name, default_val, doc) \
-    GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
-#define GMOCK_DEFINE_string_(name, default_val, doc) \
-    GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
-
-#endif  // !defined(GMOCK_DECLARE_bool_)
-
-#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
diff --git a/testing/gmock/make/Makefile b/testing/gmock/make/Makefile
deleted file mode 100644
index c1cc0e9..0000000
--- a/testing/gmock/make/Makefile
+++ /dev/null
@@ -1,101 +0,0 @@
-# A sample Makefile for building both Google Mock and Google Test and
-# using them in user tests.  This file is self-contained, so you don't
-# need to use the Makefile in Google Test's source tree.  Please tweak
-# it to suit your environment and project.  You may want to move it to
-# your project's root directory.
-#
-# SYNOPSIS:
-#
-#   make [all]  - makes everything.
-#   make TARGET - makes the given target.
-#   make clean  - removes all files generated by make.
-
-# Please tweak the following variable definitions as needed by your
-# project, except GMOCK_HEADERS and GTEST_HEADERS, which you can use
-# in your own targets but shouldn't modify.
-
-# Points to the root of Google Test, relative to where this file is.
-# Remember to tweak this if you move this file, or if you want to use
-# a copy of Google Test at a different location.
-GTEST_DIR = ../gtest
-
-# Points to the root of Google Mock, relative to where this file is.
-# Remember to tweak this if you move this file.
-GMOCK_DIR = ..
-
-# Where to find user code.
-USER_DIR = ../test
-
-# Flags passed to the preprocessor.
-# Set Google Test and Google Mock's header directories as system
-# directories, such that the compiler doesn't generate warnings in
-# these headers.
-CPPFLAGS += -isystem $(GTEST_DIR)/include -isystem $(GMOCK_DIR)/include
-
-# Flags passed to the C++ compiler.
-CXXFLAGS += -g -Wall -Wextra -pthread
-
-# All tests produced by this Makefile.  Remember to add new tests you
-# created to the list.
-TESTS = gmock_test
-
-# All Google Test headers.  Usually you shouldn't change this
-# definition.
-GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \
-                $(GTEST_DIR)/include/gtest/internal/*.h
-
-# All Google Mock headers. Note that all Google Test headers are
-# included here too, as they are #included by Google Mock headers.
-# Usually you shouldn't change this definition.	
-GMOCK_HEADERS = $(GMOCK_DIR)/include/gmock/*.h \
-                $(GMOCK_DIR)/include/gmock/internal/*.h \
-                $(GTEST_HEADERS)
-
-# House-keeping build targets.
-
-all : $(TESTS)
-
-clean :
-	rm -f $(TESTS) gmock.a gmock_main.a *.o
-
-# Builds gmock.a and gmock_main.a.  These libraries contain both
-# Google Mock and Google Test.  A test should link with either gmock.a
-# or gmock_main.a, depending on whether it defines its own main()
-# function.  It's fine if your test only uses features from Google
-# Test (and not Google Mock).
-
-# Usually you shouldn't tweak such internal variables, indicated by a
-# trailing _.
-GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)
-GMOCK_SRCS_ = $(GMOCK_DIR)/src/*.cc $(GMOCK_HEADERS)
-
-# For simplicity and to avoid depending on implementation details of
-# Google Mock and Google Test, the dependencies specified below are
-# conservative and not optimized.  This is fine as Google Mock and
-# Google Test compile fast and for ordinary users their source rarely
-# changes.
-gtest-all.o : $(GTEST_SRCS_)
-	$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
-            -c $(GTEST_DIR)/src/gtest-all.cc
-
-gmock-all.o : $(GMOCK_SRCS_)
-	$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
-            -c $(GMOCK_DIR)/src/gmock-all.cc
-
-gmock_main.o : $(GMOCK_SRCS_)
-	$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \
-            -c $(GMOCK_DIR)/src/gmock_main.cc
-
-gmock.a : gmock-all.o gtest-all.o
-	$(AR) $(ARFLAGS) $@ $^
-
-gmock_main.a : gmock-all.o gtest-all.o gmock_main.o
-	$(AR) $(ARFLAGS) $@ $^
-
-# Builds a sample test.
-
-gmock_test.o : $(USER_DIR)/gmock_test.cc $(GMOCK_HEADERS)
-	$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_test.cc
-
-gmock_test : gmock_test.o gmock_main.a
-	$(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@
diff --git a/testing/gmock/msvc/2005/gmock.sln b/testing/gmock/msvc/2005/gmock.sln
deleted file mode 100644
index b752f87..0000000
--- a/testing/gmock/msvc/2005/gmock.sln
+++ /dev/null
@@ -1,32 +0,0 @@
-

-Microsoft Visual Studio Solution File, Format Version 9.00

-# Visual Studio 2005

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"

-EndProject

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"

-EndProject

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"

-EndProject

-Global

-	GlobalSection(SolutionConfigurationPlatforms) = preSolution

-		Debug|Win32 = Debug|Win32

-		Release|Win32 = Release|Win32

-	EndGlobalSection

-	GlobalSection(ProjectConfigurationPlatforms) = postSolution

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32

-	EndGlobalSection

-	GlobalSection(SolutionProperties) = preSolution

-		HideSolutionNode = FALSE

-	EndGlobalSection

-EndGlobal

diff --git a/testing/gmock/msvc/2005/gmock.vcproj b/testing/gmock/msvc/2005/gmock.vcproj
deleted file mode 100644
index 4bbfe98..0000000
--- a/testing/gmock/msvc/2005/gmock.vcproj
+++ /dev/null
@@ -1,191 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>

-<VisualStudioProject

-	ProjectType="Visual C++"

-	Version="8.00"

-	Name="gmock"

-	ProjectGUID="{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"

-	RootNamespace="gmock"

-	Keyword="Win32Proj"

-	>

-	<Platforms>

-		<Platform

-			Name="Win32"

-		/>

-	</Platforms>

-	<ToolFiles>

-	</ToolFiles>

-	<Configurations>

-		<Configuration

-			Name="Debug|Win32"

-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"

-			IntermediateDirectory="$(OutDir)\$(ProjectName)"

-			ConfigurationType="4"

-			InheritedPropertySheets=".\gmock_config.vsprops"

-			CharacterSet="1"

-			>

-			<Tool

-				Name="VCPreBuildEventTool"

-			/>

-			<Tool

-				Name="VCCustomBuildTool"

-			/>

-			<Tool

-				Name="VCXMLDataGeneratorTool"

-			/>

-			<Tool

-				Name="VCWebServiceProxyGeneratorTool"

-			/>

-			<Tool

-				Name="VCMIDLTool"

-			/>

-			<Tool

-				Name="VCCLCompilerTool"

-				Optimization="0"

-				AdditionalIncludeDirectories="..\..\include;..\.."

-				PreprocessorDefinitions="WIN32;_DEBUG;_LIB"

-				MinimalRebuild="true"

-				BasicRuntimeChecks="3"

-				RuntimeLibrary="1"

-				UsePrecompiledHeader="0"

-				WarningLevel="3"

-				Detect64BitPortabilityProblems="true"

-				DebugInformationFormat="3"

-			/>

-			<Tool

-				Name="VCManagedResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCPreLinkEventTool"

-			/>

-			<Tool

-				Name="VCLibrarianTool"

-			/>

-			<Tool

-				Name="VCALinkTool"

-			/>

-			<Tool

-				Name="VCXDCMakeTool"

-			/>

-			<Tool

-				Name="VCBscMakeTool"

-			/>

-			<Tool

-				Name="VCFxCopTool"

-			/>

-			<Tool

-				Name="VCPostBuildEventTool"

-			/>

-		</Configuration>

-		<Configuration

-			Name="Release|Win32"

-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"

-			IntermediateDirectory="$(OutDir)\$(ProjectName)"

-			ConfigurationType="4"

-			InheritedPropertySheets=".\gmock_config.vsprops"

-			CharacterSet="1"

-			WholeProgramOptimization="1"

-			>

-			<Tool

-				Name="VCPreBuildEventTool"

-			/>

-			<Tool

-				Name="VCCustomBuildTool"

-			/>

-			<Tool

-				Name="VCXMLDataGeneratorTool"

-			/>

-			<Tool

-				Name="VCWebServiceProxyGeneratorTool"

-			/>

-			<Tool

-				Name="VCMIDLTool"

-			/>

-			<Tool

-				Name="VCCLCompilerTool"

-				AdditionalIncludeDirectories="..\..\include;..\.."

-				PreprocessorDefinitions="WIN32;NDEBUG;_LIB"

-				RuntimeLibrary="0"

-				UsePrecompiledHeader="0"

-				WarningLevel="3"

-				Detect64BitPortabilityProblems="true"

-				DebugInformationFormat="3"

-			/>

-			<Tool

-				Name="VCManagedResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCPreLinkEventTool"

-			/>

-			<Tool

-				Name="VCLibrarianTool"

-			/>

-			<Tool

-				Name="VCALinkTool"

-			/>

-			<Tool

-				Name="VCXDCMakeTool"

-			/>

-			<Tool

-				Name="VCBscMakeTool"

-			/>

-			<Tool

-				Name="VCFxCopTool"

-			/>

-			<Tool

-				Name="VCPostBuildEventTool"

-			/>

-		</Configuration>

-	</Configurations>

-	<References>

-	</References>

-	<Files>

-		<Filter

-			Name="Source Files"

-			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"

-			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"

-			>

-			<File

-				RelativePath="..\..\src\gmock-all.cc"

-				>

-			</File>

-			<File

-				RelativePath="$(GTestDir)\src\gtest-all.cc"

-				>

-				<FileConfiguration

-					Name="Debug|Win32"

-					>

-					<Tool

-						Name="VCCLCompilerTool"

-						AdditionalIncludeDirectories="$(GTestDir)"

-					/>

-				</FileConfiguration>

-				<FileConfiguration

-					Name="Release|Win32"

-					>

-					<Tool

-						Name="VCCLCompilerTool"

-						AdditionalIncludeDirectories="$(GTestDir)"

-					/>

-				</FileConfiguration>

-			</File>

-		</Filter>

-		<Filter

-			Name="Public Header Files"

-			Filter="h;hpp;hxx;hm;inl;inc;xsd"

-			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"

-			>

-		</Filter>

-		<Filter

-			Name="Private Header Files"

-			>

-		</Filter>

-	</Files>

-	<Globals>

-	</Globals>

-</VisualStudioProject>

diff --git a/testing/gmock/msvc/2005/gmock_config.vsprops b/testing/gmock/msvc/2005/gmock_config.vsprops
deleted file mode 100644
index 8b65cfb..0000000
--- a/testing/gmock/msvc/2005/gmock_config.vsprops
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>

-<VisualStudioPropertySheet

-	ProjectType="Visual C++"

-	Version="8.00"

-	Name="gmock_config"

-	>

-	<Tool

-		Name="VCCLCompilerTool"

-		AdditionalIncludeDirectories="&quot;$(GTestDir)/include&quot;"

-	/>

-	<UserMacro

-		Name="GTestDir"

-		Value="../../gtest"

-	/>

-</VisualStudioPropertySheet>

diff --git a/testing/gmock/msvc/2005/gmock_main.vcproj b/testing/gmock/msvc/2005/gmock_main.vcproj
deleted file mode 100644
index 01505a9..0000000
--- a/testing/gmock/msvc/2005/gmock_main.vcproj
+++ /dev/null
@@ -1,187 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>

-<VisualStudioProject

-	ProjectType="Visual C++"

-	Version="8.00"

-	Name="gmock_main"

-	ProjectGUID="{E4EF614B-30DF-4954-8C53-580A0BF6B589}"

-	RootNamespace="gmock_main"

-	Keyword="Win32Proj"

-	>

-	<Platforms>

-		<Platform

-			Name="Win32"

-		/>

-	</Platforms>

-	<ToolFiles>

-	</ToolFiles>

-	<Configurations>

-		<Configuration

-			Name="Debug|Win32"

-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"

-			IntermediateDirectory="$(OutDir)\$(ProjectName)"

-			ConfigurationType="4"

-			InheritedPropertySheets=".\gmock_config.vsprops"

-			CharacterSet="1"

-			>

-			<Tool

-				Name="VCPreBuildEventTool"

-			/>

-			<Tool

-				Name="VCCustomBuildTool"

-			/>

-			<Tool

-				Name="VCXMLDataGeneratorTool"

-			/>

-			<Tool

-				Name="VCWebServiceProxyGeneratorTool"

-			/>

-			<Tool

-				Name="VCMIDLTool"

-			/>

-			<Tool

-				Name="VCCLCompilerTool"

-				Optimization="0"

-				AdditionalIncludeDirectories="../../include"

-				PreprocessorDefinitions="WIN32;_DEBUG;_LIB"

-				MinimalRebuild="true"

-				BasicRuntimeChecks="3"

-				RuntimeLibrary="1"

-				UsePrecompiledHeader="0"

-				WarningLevel="3"

-				Detect64BitPortabilityProblems="true"

-				DebugInformationFormat="3"

-			/>

-			<Tool

-				Name="VCManagedResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCPreLinkEventTool"

-			/>

-			<Tool

-				Name="VCLibrarianTool"

-			/>

-			<Tool

-				Name="VCALinkTool"

-			/>

-			<Tool

-				Name="VCXDCMakeTool"

-			/>

-			<Tool

-				Name="VCBscMakeTool"

-			/>

-			<Tool

-				Name="VCFxCopTool"

-			/>

-			<Tool

-				Name="VCPostBuildEventTool"

-			/>

-		</Configuration>

-		<Configuration

-			Name="Release|Win32"

-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"

-			IntermediateDirectory="$(OutDir)\$(ProjectName)"

-			ConfigurationType="4"

-			InheritedPropertySheets=".\gmock_config.vsprops"

-			CharacterSet="1"

-			WholeProgramOptimization="1"

-			>

-			<Tool

-				Name="VCPreBuildEventTool"

-			/>

-			<Tool

-				Name="VCCustomBuildTool"

-			/>

-			<Tool

-				Name="VCXMLDataGeneratorTool"

-			/>

-			<Tool

-				Name="VCWebServiceProxyGeneratorTool"

-			/>

-			<Tool

-				Name="VCMIDLTool"

-			/>

-			<Tool

-				Name="VCCLCompilerTool"

-				AdditionalIncludeDirectories="../../include"

-				PreprocessorDefinitions="WIN32;NDEBUG;_LIB"

-				RuntimeLibrary="0"

-				UsePrecompiledHeader="0"

-				WarningLevel="3"

-				Detect64BitPortabilityProblems="true"

-				DebugInformationFormat="3"

-			/>

-			<Tool

-				Name="VCManagedResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCPreLinkEventTool"

-			/>

-			<Tool

-				Name="VCLibrarianTool"

-			/>

-			<Tool

-				Name="VCALinkTool"

-			/>

-			<Tool

-				Name="VCXDCMakeTool"

-			/>

-			<Tool

-				Name="VCBscMakeTool"

-			/>

-			<Tool

-				Name="VCFxCopTool"

-			/>

-			<Tool

-				Name="VCPostBuildEventTool"

-			/>

-		</Configuration>

-	</Configurations>

-	<References>

-		<ProjectReference

-			ReferencedProjectIdentifier="{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"

-			RelativePathToProject=".\gmock.vcproj"

-		/>

-	</References>

-	<Files>

-		<Filter

-			Name="Source Files"

-			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"

-			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"

-			>

-			<File

-				RelativePath="..\..\src\gmock_main.cc"

-				>

-				<FileConfiguration

-					Name="Debug|Win32"

-					>

-					<Tool

-						Name="VCCLCompilerTool"

-						AdditionalIncludeDirectories="../../include"

-					/>

-				</FileConfiguration>

-				<FileConfiguration

-					Name="Release|Win32"

-					>

-					<Tool

-						Name="VCCLCompilerTool"

-						AdditionalIncludeDirectories="../../include"

-					/>

-				</FileConfiguration>

-			</File>

-		</Filter>

-		<Filter

-			Name="Header Files"

-			Filter="h;hpp;hxx;hm;inl;inc;xsd"

-			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"

-			>

-		</Filter>

-	</Files>

-	<Globals>

-	</Globals>

-</VisualStudioProject>

diff --git a/testing/gmock/msvc/2005/gmock_test.vcproj b/testing/gmock/msvc/2005/gmock_test.vcproj
deleted file mode 100644
index d1e01e7..0000000
--- a/testing/gmock/msvc/2005/gmock_test.vcproj
+++ /dev/null
@@ -1,201 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>

-<VisualStudioProject

-	ProjectType="Visual C++"

-	Version="8.00"

-	Name="gmock_test"

-	ProjectGUID="{F10D22F8-AC7B-4213-8720-608E7D878CD2}"

-	RootNamespace="gmock_test"

-	Keyword="Win32Proj"

-	>

-	<Platforms>

-		<Platform

-			Name="Win32"

-		/>

-	</Platforms>

-	<ToolFiles>

-	</ToolFiles>

-	<Configurations>

-		<Configuration

-			Name="Debug|Win32"

-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"

-			IntermediateDirectory="$(OutDir)\$(ProjectName)"

-			ConfigurationType="1"

-			InheritedPropertySheets=".\gmock_config.vsprops"

-			CharacterSet="1"

-			>

-			<Tool

-				Name="VCPreBuildEventTool"

-			/>

-			<Tool

-				Name="VCCustomBuildTool"

-			/>

-			<Tool

-				Name="VCXMLDataGeneratorTool"

-			/>

-			<Tool

-				Name="VCWebServiceProxyGeneratorTool"

-			/>

-			<Tool

-				Name="VCMIDLTool"

-			/>

-			<Tool

-				Name="VCCLCompilerTool"

-				AdditionalOptions="/bigobj"

-				Optimization="0"

-				AdditionalIncludeDirectories="..\..\include;..\.."

-				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"

-				MinimalRebuild="true"

-				BasicRuntimeChecks="3"

-				RuntimeLibrary="1"

-				UsePrecompiledHeader="0"

-				WarningLevel="3"

-				Detect64BitPortabilityProblems="true"

-				DebugInformationFormat="3"

-			/>

-			<Tool

-				Name="VCManagedResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCPreLinkEventTool"

-			/>

-			<Tool

-				Name="VCLinkerTool"

-				LinkIncremental="2"

-				GenerateDebugInformation="true"

-				SubSystem="1"

-				TargetMachine="1"

-			/>

-			<Tool

-				Name="VCALinkTool"

-			/>

-			<Tool

-				Name="VCManifestTool"

-			/>

-			<Tool

-				Name="VCXDCMakeTool"

-			/>

-			<Tool

-				Name="VCBscMakeTool"

-			/>

-			<Tool

-				Name="VCFxCopTool"

-			/>

-			<Tool

-				Name="VCAppVerifierTool"

-			/>

-			<Tool

-				Name="VCWebDeploymentTool"

-			/>

-			<Tool

-				Name="VCPostBuildEventTool"

-			/>

-		</Configuration>

-		<Configuration

-			Name="Release|Win32"

-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"

-			IntermediateDirectory="$(OutDir)\$(ProjectName)"

-			ConfigurationType="1"

-			InheritedPropertySheets=".\gmock_config.vsprops"

-			CharacterSet="1"

-			WholeProgramOptimization="1"

-			>

-			<Tool

-				Name="VCPreBuildEventTool"

-			/>

-			<Tool

-				Name="VCCustomBuildTool"

-			/>

-			<Tool

-				Name="VCXMLDataGeneratorTool"

-			/>

-			<Tool

-				Name="VCWebServiceProxyGeneratorTool"

-			/>

-			<Tool

-				Name="VCMIDLTool"

-			/>

-			<Tool

-				Name="VCCLCompilerTool"

-				AdditionalOptions="/bigobj"

-				AdditionalIncludeDirectories="..\..\include;..\.."

-				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"

-				RuntimeLibrary="0"

-				UsePrecompiledHeader="0"

-				WarningLevel="3"

-				Detect64BitPortabilityProblems="true"

-				DebugInformationFormat="3"

-			/>

-			<Tool

-				Name="VCManagedResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCResourceCompilerTool"

-			/>

-			<Tool

-				Name="VCPreLinkEventTool"

-			/>

-			<Tool

-				Name="VCLinkerTool"

-				LinkIncremental="1"

-				GenerateDebugInformation="true"

-				SubSystem="1"

-				OptimizeReferences="2"

-				EnableCOMDATFolding="2"

-				TargetMachine="1"

-			/>

-			<Tool

-				Name="VCALinkTool"

-			/>

-			<Tool

-				Name="VCManifestTool"

-			/>

-			<Tool

-				Name="VCXDCMakeTool"

-			/>

-			<Tool

-				Name="VCBscMakeTool"

-			/>

-			<Tool

-				Name="VCFxCopTool"

-			/>

-			<Tool

-				Name="VCAppVerifierTool"

-			/>

-			<Tool

-				Name="VCWebDeploymentTool"

-			/>

-			<Tool

-				Name="VCPostBuildEventTool"

-			/>

-		</Configuration>

-	</Configurations>

-	<References>

-		<ProjectReference

-			ReferencedProjectIdentifier="{E4EF614B-30DF-4954-8C53-580A0BF6B589}"

-			RelativePathToProject=".\gmock_main.vcproj"

-		/>

-	</References>

-	<Files>

-		<Filter

-			Name="Source Files"

-			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"

-			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"

-			>

-			<File

-				RelativePath="..\..\test\gmock_all_test.cc"

-				>

-			</File>

-		</Filter>

-		<Filter

-			Name="Header Files"

-			Filter="h;hpp;hxx;hm;inl;inc;xsd"

-			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"

-			>

-		</Filter>

-	</Files>

-	<Globals>

-	</Globals>

-</VisualStudioProject>

diff --git a/testing/gmock/msvc/2010/gmock.sln b/testing/gmock/msvc/2010/gmock.sln
deleted file mode 100644
index d949656..0000000
--- a/testing/gmock/msvc/2010/gmock.sln
+++ /dev/null
@@ -1,32 +0,0 @@
-

-Microsoft Visual Studio Solution File, Format Version 11.00

-# Visual C++ Express 2010

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcxproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"

-EndProject

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcxproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"

-EndProject

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcxproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"

-EndProject

-Global

-	GlobalSection(SolutionConfigurationPlatforms) = preSolution

-		Debug|Win32 = Debug|Win32

-		Release|Win32 = Release|Win32

-	EndGlobalSection

-	GlobalSection(ProjectConfigurationPlatforms) = postSolution

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32

-		{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32

-		{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32

-		{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32

-	EndGlobalSection

-	GlobalSection(SolutionProperties) = preSolution

-		HideSolutionNode = FALSE

-	EndGlobalSection

-EndGlobal

diff --git a/testing/gmock/msvc/2010/gmock.vcxproj b/testing/gmock/msvc/2010/gmock.vcxproj
deleted file mode 100644
index 21a85ef..0000000
--- a/testing/gmock/msvc/2010/gmock.vcxproj
+++ /dev/null
@@ -1,82 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>

-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

-  <ItemGroup Label="ProjectConfigurations">

-    <ProjectConfiguration Include="Debug|Win32">

-      <Configuration>Debug</Configuration>

-      <Platform>Win32</Platform>

-    </ProjectConfiguration>

-    <ProjectConfiguration Include="Release|Win32">

-      <Configuration>Release</Configuration>

-      <Platform>Win32</Platform>

-    </ProjectConfiguration>

-  </ItemGroup>

-  <PropertyGroup Label="Globals">

-    <ProjectGuid>{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}</ProjectGuid>

-    <RootNamespace>gmock</RootNamespace>

-    <Keyword>Win32Proj</Keyword>

-  </PropertyGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />

-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">

-    <ConfigurationType>StaticLibrary</ConfigurationType>

-    <CharacterSet>Unicode</CharacterSet>

-    <WholeProgramOptimization>true</WholeProgramOptimization>

-  </PropertyGroup>

-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">

-    <ConfigurationType>StaticLibrary</ConfigurationType>

-    <CharacterSet>Unicode</CharacterSet>

-  </PropertyGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />

-  <ImportGroup Label="ExtensionSettings">

-  </ImportGroup>

-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">

-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />

-    <Import Project="gmock_config.props" />

-  </ImportGroup>

-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">

-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />

-    <Import Project="gmock_config.props" />

-  </ImportGroup>

-  <PropertyGroup Label="UserMacros" />

-  <PropertyGroup>

-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>

-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>

-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>

-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>

-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>

-  </PropertyGroup>

-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

-    <ClCompile>

-      <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>

-      <MinimalRebuild>true</MinimalRebuild>

-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

-      <PrecompiledHeader>

-      </PrecompiledHeader>

-      <WarningLevel>Level3</WarningLevel>

-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>

-    </ClCompile>

-  </ItemDefinitionGroup>

-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">

-    <ClCompile>

-      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>

-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

-      <PrecompiledHeader>

-      </PrecompiledHeader>

-      <WarningLevel>Level3</WarningLevel>

-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>

-    </ClCompile>

-  </ItemDefinitionGroup>

-  <ItemGroup>

-    <ClCompile Include="..\..\src\gmock-all.cc" />

-    <ClCompile Include="$(GTestDir)\src\gtest-all.cc">

-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-    </ClCompile>

-  </ItemGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

-  <ImportGroup Label="ExtensionTargets">

-  </ImportGroup>

-</Project>

diff --git a/testing/gmock/msvc/2010/gmock_config.props b/testing/gmock/msvc/2010/gmock_config.props
deleted file mode 100644
index bd497f1..0000000
--- a/testing/gmock/msvc/2010/gmock_config.props
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>

-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

-  <PropertyGroup Label="UserMacros">

-    <GTestDir>../../gtest</GTestDir>

-  </PropertyGroup>

-  <PropertyGroup>

-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>

-  </PropertyGroup>

-  <ItemDefinitionGroup>

-    <ClCompile>

-      <AdditionalIncludeDirectories>$(GTestDir)/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-    </ClCompile>

-  </ItemDefinitionGroup>

-  <ItemGroup>

-    <BuildMacro Include="GTestDir">

-      <Value>$(GTestDir)</Value>

-    </BuildMacro>

-  </ItemGroup>

-</Project>

diff --git a/testing/gmock/msvc/2010/gmock_main.vcxproj b/testing/gmock/msvc/2010/gmock_main.vcxproj
deleted file mode 100644
index 27fecd5..0000000
--- a/testing/gmock/msvc/2010/gmock_main.vcxproj
+++ /dev/null
@@ -1,88 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>

-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

-  <ItemGroup Label="ProjectConfigurations">

-    <ProjectConfiguration Include="Debug|Win32">

-      <Configuration>Debug</Configuration>

-      <Platform>Win32</Platform>

-    </ProjectConfiguration>

-    <ProjectConfiguration Include="Release|Win32">

-      <Configuration>Release</Configuration>

-      <Platform>Win32</Platform>

-    </ProjectConfiguration>

-  </ItemGroup>

-  <PropertyGroup Label="Globals">

-    <ProjectGuid>{E4EF614B-30DF-4954-8C53-580A0BF6B589}</ProjectGuid>

-    <RootNamespace>gmock_main</RootNamespace>

-    <Keyword>Win32Proj</Keyword>

-  </PropertyGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />

-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">

-    <ConfigurationType>StaticLibrary</ConfigurationType>

-    <CharacterSet>Unicode</CharacterSet>

-    <WholeProgramOptimization>true</WholeProgramOptimization>

-  </PropertyGroup>

-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">

-    <ConfigurationType>StaticLibrary</ConfigurationType>

-    <CharacterSet>Unicode</CharacterSet>

-  </PropertyGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />

-  <ImportGroup Label="ExtensionSettings">

-  </ImportGroup>

-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">

-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />

-    <Import Project="gmock_config.props" />

-  </ImportGroup>

-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">

-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />

-    <Import Project="gmock_config.props" />

-  </ImportGroup>

-  <PropertyGroup Label="UserMacros" />

-  <PropertyGroup>

-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>

-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>

-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>

-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>

-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>

-  </PropertyGroup>

-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

-    <ClCompile>

-      <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>

-      <MinimalRebuild>true</MinimalRebuild>

-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

-      <PrecompiledHeader>

-      </PrecompiledHeader>

-      <WarningLevel>Level3</WarningLevel>

-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>

-    </ClCompile>

-  </ItemDefinitionGroup>

-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">

-    <ClCompile>

-      <AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>

-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

-      <PrecompiledHeader>

-      </PrecompiledHeader>

-      <WarningLevel>Level3</WarningLevel>

-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>

-    </ClCompile>

-  </ItemDefinitionGroup>

-  <ItemGroup>

-    <ProjectReference Include="gmock.vcxproj">

-      <Project>{34681f0d-ce45-415d-b5f2-5c662dfe3bd5}</Project>

-      <CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>

-      <ReferenceOutputAssembly>true</ReferenceOutputAssembly>

-    </ProjectReference>

-  </ItemGroup>

-  <ItemGroup>

-    <ClCompile Include="..\..\src\gmock_main.cc">

-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-    </ClCompile>

-  </ItemGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

-  <ImportGroup Label="ExtensionTargets">

-  </ImportGroup>

-</Project>

diff --git a/testing/gmock/msvc/2010/gmock_test.vcxproj b/testing/gmock/msvc/2010/gmock_test.vcxproj
deleted file mode 100644
index 265439e..0000000
--- a/testing/gmock/msvc/2010/gmock_test.vcxproj
+++ /dev/null
@@ -1,101 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>

-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

-  <ItemGroup Label="ProjectConfigurations">

-    <ProjectConfiguration Include="Debug|Win32">

-      <Configuration>Debug</Configuration>

-      <Platform>Win32</Platform>

-    </ProjectConfiguration>

-    <ProjectConfiguration Include="Release|Win32">

-      <Configuration>Release</Configuration>

-      <Platform>Win32</Platform>

-    </ProjectConfiguration>

-  </ItemGroup>

-  <PropertyGroup Label="Globals">

-    <ProjectGuid>{F10D22F8-AC7B-4213-8720-608E7D878CD2}</ProjectGuid>

-    <RootNamespace>gmock_test</RootNamespace>

-    <Keyword>Win32Proj</Keyword>

-  </PropertyGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />

-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">

-    <ConfigurationType>Application</ConfigurationType>

-    <CharacterSet>Unicode</CharacterSet>

-    <WholeProgramOptimization>true</WholeProgramOptimization>

-  </PropertyGroup>

-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">

-    <ConfigurationType>Application</ConfigurationType>

-    <CharacterSet>Unicode</CharacterSet>

-  </PropertyGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />

-  <ImportGroup Label="ExtensionSettings">

-  </ImportGroup>

-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">

-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />

-    <Import Project="gmock_config.props" />

-  </ImportGroup>

-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">

-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />

-    <Import Project="gmock_config.props" />

-  </ImportGroup>

-  <PropertyGroup Label="UserMacros" />

-  <PropertyGroup>

-    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>

-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>

-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>

-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>

-    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>

-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>

-    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>

-  </PropertyGroup>

-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

-    <ClCompile>

-      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>

-      <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

-      <MinimalRebuild>true</MinimalRebuild>

-      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

-      <PrecompiledHeader>

-      </PrecompiledHeader>

-      <WarningLevel>Level3</WarningLevel>

-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>

-    </ClCompile>

-    <Link>

-      <GenerateDebugInformation>true</GenerateDebugInformation>

-      <SubSystem>Console</SubSystem>

-      <TargetMachine>MachineX86</TargetMachine>

-    </Link>

-  </ItemDefinitionGroup>

-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">

-    <ClCompile>

-      <AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>

-      <AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

-      <PrecompiledHeader>

-      </PrecompiledHeader>

-      <WarningLevel>Level3</WarningLevel>

-      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>

-    </ClCompile>

-    <Link>

-      <GenerateDebugInformation>true</GenerateDebugInformation>

-      <SubSystem>Console</SubSystem>

-      <OptimizeReferences>true</OptimizeReferences>

-      <EnableCOMDATFolding>true</EnableCOMDATFolding>

-      <TargetMachine>MachineX86</TargetMachine>

-    </Link>

-  </ItemDefinitionGroup>

-  <ItemGroup>

-    <ProjectReference Include="gmock_main.vcxproj">

-      <Project>{e4ef614b-30df-4954-8c53-580a0bf6b589}</Project>

-      <CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>

-      <ReferenceOutputAssembly>true</ReferenceOutputAssembly>

-    </ProjectReference>

-  </ItemGroup>

-  <ItemGroup>

-    <ClCompile Include="..\..\test\gmock_all_test.cc" />

-  </ItemGroup>

-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

-  <ImportGroup Label="ExtensionTargets">

-  </ImportGroup>

-</Project>

diff --git a/testing/gmock/scripts/fuse_gmock_files.py b/testing/gmock/scripts/fuse_gmock_files.py
deleted file mode 100755
index fc0baf7..0000000
--- a/testing/gmock/scripts/fuse_gmock_files.py
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2009, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-#     * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#     * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-#     * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""fuse_gmock_files.py v0.1.0
-Fuses Google Mock and Google Test source code into two .h files and a .cc file.
-
-SYNOPSIS
-       fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR
-
-       Scans GMOCK_ROOT_DIR for Google Mock and Google Test source
-       code, assuming Google Test is in the GMOCK_ROOT_DIR/gtest
-       sub-directory, and generates three files:
-       OUTPUT_DIR/gtest/gtest.h, OUTPUT_DIR/gmock/gmock.h, and
-       OUTPUT_DIR/gmock-gtest-all.cc.  Then you can build your tests
-       by adding OUTPUT_DIR to the include search path and linking
-       with OUTPUT_DIR/gmock-gtest-all.cc.  These three files contain
-       everything you need to use Google Mock.  Hence you can
-       "install" Google Mock by copying them to wherever you want.
-
-       GMOCK_ROOT_DIR can be omitted and defaults to the parent
-       directory of the directory holding this script.
-
-EXAMPLES
-       ./fuse_gmock_files.py fused_gmock
-       ./fuse_gmock_files.py path/to/unpacked/gmock fused_gmock
-
-This tool is experimental.  In particular, it assumes that there is no
-conditional inclusion of Google Mock or Google Test headers.  Please
-report any problems to googlemock@googlegroups.com.  You can read
-http://code.google.com/p/googlemock/wiki/CookBook for more
-information.
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import re
-import sets
-import sys
-
-# We assume that this file is in the scripts/ directory in the Google
-# Mock root directory.
-DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
-
-# We need to call into gtest/scripts/fuse_gtest_files.py.
-sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, 'gtest/scripts'))
-import fuse_gtest_files
-gtest = fuse_gtest_files
-
-# Regex for matching '#include "gmock/..."'.
-INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
-
-# Where to find the source seed files.
-GMOCK_H_SEED = 'include/gmock/gmock.h'
-GMOCK_ALL_CC_SEED = 'src/gmock-all.cc'
-
-# Where to put the generated files.
-GTEST_H_OUTPUT = 'gtest/gtest.h'
-GMOCK_H_OUTPUT = 'gmock/gmock.h'
-GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
-
-
-def GetGTestRootDir(gmock_root):
-  """Returns the root directory of Google Test."""
-
-  return os.path.join(gmock_root, 'gtest')
-
-
-def ValidateGMockRootDir(gmock_root):
-  """Makes sure gmock_root points to a valid gmock root directory.
-
-  The function aborts the program on failure.
-  """
-
-  gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
-  gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED)
-  gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
-
-
-def ValidateOutputDir(output_dir):
-  """Makes sure output_dir points to a valid output directory.
-
-  The function aborts the program on failure.
-  """
-
-  gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
-  gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT)
-  gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
-
-
-def FuseGMockH(gmock_root, output_dir):
-  """Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
-
-  output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
-  processed_files = sets.Set()  # Holds all gmock headers we've processed.
-
-  def ProcessFile(gmock_header_path):
-    """Processes the given gmock header file."""
-
-    # We don't process the same header twice.
-    if gmock_header_path in processed_files:
-      return
-
-    processed_files.add(gmock_header_path)
-
-    # Reads each line in the given gmock header.
-    for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
-      m = INCLUDE_GMOCK_FILE_REGEX.match(line)
-      if m:
-        # It's '#include "gmock/..."' - let's process it recursively.
-        ProcessFile('include/' + m.group(1))
-      else:
-        m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
-        if m:
-          # It's '#include "gtest/foo.h"'.  We translate it to
-          # "gtest/gtest.h", regardless of what foo is, since all
-          # gtest headers are fused into gtest/gtest.h.
-
-          # There is no need to #include gtest.h twice.
-          if not gtest.GTEST_H_SEED in processed_files:
-            processed_files.add(gtest.GTEST_H_SEED)
-            output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
-        else:
-          # Otherwise we copy the line unchanged to the output file.
-          output_file.write(line)
-
-  ProcessFile(GMOCK_H_SEED)
-  output_file.close()
-
-
-def FuseGMockAllCcToFile(gmock_root, output_file):
-  """Scans folder gmock_root to fuse gmock-all.cc into output_file."""
-
-  processed_files = sets.Set()
-
-  def ProcessFile(gmock_source_file):
-    """Processes the given gmock source file."""
-
-    # We don't process the same #included file twice.
-    if gmock_source_file in processed_files:
-      return
-
-    processed_files.add(gmock_source_file)
-
-    # Reads each line in the given gmock source file.
-    for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
-      m = INCLUDE_GMOCK_FILE_REGEX.match(line)
-      if m:
-        # It's '#include "gmock/foo.h"'.  We treat it as '#include
-        # "gmock/gmock.h"', as all other gmock headers are being fused
-        # into gmock.h and cannot be #included directly.
-
-        # There is no need to #include "gmock/gmock.h" more than once.
-        if not GMOCK_H_SEED in processed_files:
-          processed_files.add(GMOCK_H_SEED)
-          output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
-      else:
-        m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
-        if m:
-          # It's '#include "gtest/..."'.
-          # There is no need to #include gtest.h as it has been
-          # #included by gtest-all.cc.
-          pass
-        else:
-          m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
-          if m:
-            # It's '#include "src/foo"' - let's process it recursively.
-            ProcessFile(m.group(1))
-          else:
-            # Otherwise we copy the line unchanged to the output file.
-            output_file.write(line)
-
-  ProcessFile(GMOCK_ALL_CC_SEED)
-
-
-def FuseGMockGTestAllCc(gmock_root, output_dir):
-  """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
-
-  output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
-  # First, fuse gtest-all.cc into gmock-gtest-all.cc.
-  gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
-  # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
-  FuseGMockAllCcToFile(gmock_root, output_file)
-  output_file.close()
-
-
-def FuseGMock(gmock_root, output_dir):
-  """Fuses gtest.h, gmock.h, and gmock-gtest-all.h."""
-
-  ValidateGMockRootDir(gmock_root)
-  ValidateOutputDir(output_dir)
-
-  gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir)
-  FuseGMockH(gmock_root, output_dir)
-  FuseGMockGTestAllCc(gmock_root, output_dir)
-
-
-def main():
-  argc = len(sys.argv)
-  if argc == 2:
-    # fuse_gmock_files.py OUTPUT_DIR
-    FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1])
-  elif argc == 3:
-    # fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
-    FuseGMock(sys.argv[1], sys.argv[2])
-  else:
-    print __doc__
-    sys.exit(1)
-
-
-if __name__ == '__main__':
-  main()
diff --git a/testing/gmock/scripts/generator/LICENSE b/testing/gmock/scripts/generator/LICENSE
deleted file mode 100644
index 87ea063..0000000
--- a/testing/gmock/scripts/generator/LICENSE
+++ /dev/null
@@ -1,203 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "[]"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright [2007] Neal Norwitz
-   Portions Copyright [2007] Google Inc.
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
diff --git a/testing/gmock/scripts/generator/README b/testing/gmock/scripts/generator/README
deleted file mode 100644
index d6f9597..0000000
--- a/testing/gmock/scripts/generator/README
+++ /dev/null
@@ -1,35 +0,0 @@
-
-The Google Mock class generator is an application that is part of cppclean.
-For more information about cppclean, see the README.cppclean file or
-visit http://code.google.com/p/cppclean/
-
-cppclean requires Python 2.3.5 or later.  If you don't have Python installed
-on your system, you will also need to install it.  You can download Python
-from:  http://www.python.org/download/releases/
-
-To use the Google Mock class generator, you need to call it
-on the command line passing the header file and class for which you want
-to generate a Google Mock class.
-
-Make sure to install the scripts somewhere in your path.  Then you can
-run the program.
-
-  gmock_gen.py header-file.h [ClassName]...
-
-If no ClassNames are specified, all classes in the file are emitted.
-
-To change the indentation from the default of 2, set INDENT in
-the environment.  For example to use an indent of 4 spaces:
-
-INDENT=4 gmock_gen.py header-file.h ClassName
-
-This version was made from SVN revision 281 in the cppclean repository.
-
-Known Limitations
------------------
-Not all code will be generated properly.  For example, when mocking templated
-classes, the template information is lost.  You will need to add the template
-information manually.
-
-Not all permutations of using multiple pointers/references will be rendered
-properly.  These will also have to be fixed manually.
diff --git a/testing/gmock/scripts/generator/README.cppclean b/testing/gmock/scripts/generator/README.cppclean
deleted file mode 100644
index 65431b6..0000000
--- a/testing/gmock/scripts/generator/README.cppclean
+++ /dev/null
@@ -1,115 +0,0 @@
-Goal:
------
-  CppClean attempts to find problems in C++ source that slow development
-  in large code bases, for example various forms of unused code.
-  Unused code can be unused functions, methods, data members, types, etc
-  to unnecessary #include directives.  Unnecessary #includes can cause
-  considerable extra compiles increasing the edit-compile-run cycle.
-
-  The project home page is:   http://code.google.com/p/cppclean/
-
-
-Features:
----------
- * Find and print C++ language constructs: classes, methods, functions, etc.
- * Find classes with virtual methods, no virtual destructor, and no bases
- * Find global/static data that are potential problems when using threads
- * Unnecessary forward class declarations
- * Unnecessary function declarations
- * Undeclared function definitions
- * (planned) Find unnecessary header files #included
-   - No direct reference to anything in the header
-   - Header is unnecessary if classes were forward declared instead
- * (planned) Source files that reference headers not directly #included,
-   ie, files that rely on a transitive #include from another header
- * (planned) Unused members (private, protected, & public) methods and data
- * (planned) Store AST in a SQL database so relationships can be queried
-
-AST is Abstract Syntax Tree, a representation of parsed source code.
-http://en.wikipedia.org/wiki/Abstract_syntax_tree
-
-
-System Requirements:
---------------------
- * Python 2.4 or later (2.3 probably works too)
- * Works on Windows (untested), Mac OS X, and Unix
-
-
-How to Run:
------------
-  For all examples, it is assumed that cppclean resides in a directory called
-  /cppclean.
-
-  To print warnings for classes with virtual methods, no virtual destructor and
-  no base classes:
-
-      /cppclean/run.sh nonvirtual_dtors.py file1.h file2.h file3.cc ...
-
-  To print all the functions defined in header file(s):
-
-      /cppclean/run.sh functions.py file1.h file2.h ...
-
-  All the commands take multiple files on the command line.  Other programs
-  include: find_warnings, headers, methods, and types.  Some other programs
-  are available, but used primarily for debugging.
-
-  run.sh is a simple wrapper that sets PYTHONPATH to /cppclean and then
-  runs the program in /cppclean/cpp/PROGRAM.py.  There is currently
-  no equivalent for Windows.  Contributions for a run.bat file
-  would be greatly appreciated.
-
-
-How to Configure:
------------------
-  You can add a siteheaders.py file in /cppclean/cpp to configure where
-  to look for other headers (typically -I options passed to a compiler).
-  Currently two values are supported:  _TRANSITIVE and GetIncludeDirs.
-  _TRANSITIVE should be set to a boolean value (True or False) indicating
-  whether to transitively process all header files.  The default is False.
-
-  GetIncludeDirs is a function that takes a single argument and returns
-  a sequence of directories to include.  This can be a generator or
-  return a static list.
-
-      def GetIncludeDirs(filename):
-          return ['/some/path/with/other/headers']
-
-      # Here is a more complicated example.
-      def GetIncludeDirs(filename):
-          yield '/path1'
-          yield os.path.join('/path2', os.path.dirname(filename))
-          yield '/path3'
-
-
-How to Test:
-------------
-  For all examples, it is assumed that cppclean resides in a directory called
-  /cppclean.  The tests require
-
-  cd /cppclean
-  make test
-  # To generate expected results after a change:
-  make expected
-
-
-Current Status:
----------------
-  The parser works pretty well for header files, parsing about 99% of Google's
-  header files.  Anything which inspects structure of C++ source files should
-  work reasonably well.  Function bodies are not transformed to an AST,
-  but left as tokens.  Much work is still needed on finding unused header files
-  and storing an AST in a database.
-
-
-Non-goals:
-----------
- * Parsing all valid C++ source
- * Handling invalid C++ source gracefully
- * Compiling to machine code (or anything beyond an AST)
-
-
-Contact:
---------
-  If you used cppclean, I would love to hear about your experiences
-  cppclean@googlegroups.com.  Even if you don't use cppclean, I'd like to
-  hear from you.  :-)  (You can contact me directly at:  nnorwitz@gmail.com)
diff --git a/testing/gmock/scripts/generator/cpp/ast.py b/testing/gmock/scripts/generator/cpp/ast.py
deleted file mode 100755
index 11cbe91..0000000
--- a/testing/gmock/scripts/generator/cpp/ast.py
+++ /dev/null
@@ -1,1733 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generate an Abstract Syntax Tree (AST) for C++."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-# TODO:
-#  * Tokens should never be exported, need to convert to Nodes
-#    (return types, parameters, etc.)
-#  * Handle static class data for templatized classes
-#  * Handle casts (both C++ and C-style)
-#  * Handle conditions and loops (if/else, switch, for, while/do)
-#
-# TODO much, much later:
-#  * Handle #define
-#  * exceptions
-
-
-try:
-    # Python 3.x
-    import builtins
-except ImportError:
-    # Python 2.x
-    import __builtin__ as builtins
-
-import sys
-import traceback
-
-from cpp import keywords
-from cpp import tokenize
-from cpp import utils
-
-
-if not hasattr(builtins, 'reversed'):
-    # Support Python 2.3 and earlier.
-    def reversed(seq):
-        for i in range(len(seq)-1, -1, -1):
-            yield seq[i]
-
-if not hasattr(builtins, 'next'):
-    # Support Python 2.5 and earlier.
-    def next(obj):
-        return obj.next()
-
-
-VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3)
-
-FUNCTION_NONE = 0x00
-FUNCTION_CONST = 0x01
-FUNCTION_VIRTUAL = 0x02
-FUNCTION_PURE_VIRTUAL = 0x04
-FUNCTION_CTOR = 0x08
-FUNCTION_DTOR = 0x10
-FUNCTION_ATTRIBUTE = 0x20
-FUNCTION_UNKNOWN_ANNOTATION = 0x40
-FUNCTION_THROW = 0x80
-FUNCTION_OVERRIDE = 0x100
-
-"""
-These are currently unused.  Should really handle these properly at some point.
-
-TYPE_MODIFIER_INLINE   = 0x010000
-TYPE_MODIFIER_EXTERN   = 0x020000
-TYPE_MODIFIER_STATIC   = 0x040000
-TYPE_MODIFIER_CONST    = 0x080000
-TYPE_MODIFIER_REGISTER = 0x100000
-TYPE_MODIFIER_VOLATILE = 0x200000
-TYPE_MODIFIER_MUTABLE  = 0x400000
-
-TYPE_MODIFIER_MAP = {
-    'inline': TYPE_MODIFIER_INLINE,
-    'extern': TYPE_MODIFIER_EXTERN,
-    'static': TYPE_MODIFIER_STATIC,
-    'const': TYPE_MODIFIER_CONST,
-    'register': TYPE_MODIFIER_REGISTER,
-    'volatile': TYPE_MODIFIER_VOLATILE,
-    'mutable': TYPE_MODIFIER_MUTABLE,
-    }
-"""
-
-_INTERNAL_TOKEN = 'internal'
-_NAMESPACE_POP = 'ns-pop'
-
-
-# TODO(nnorwitz): use this as a singleton for templated_types, etc
-# where we don't want to create a new empty dict each time.  It is also const.
-class _NullDict(object):
-    __contains__ = lambda self: False
-    keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
-
-
-# TODO(nnorwitz): move AST nodes into a separate module.
-class Node(object):
-    """Base AST node."""
-
-    def __init__(self, start, end):
-        self.start = start
-        self.end = end
-
-    def IsDeclaration(self):
-        """Returns bool if this node is a declaration."""
-        return False
-
-    def IsDefinition(self):
-        """Returns bool if this node is a definition."""
-        return False
-
-    def IsExportable(self):
-        """Returns bool if this node exportable from a header file."""
-        return False
-
-    def Requires(self, node):
-        """Does this AST node require the definition of the node passed in?"""
-        return False
-
-    def XXX__str__(self):
-        return self._StringHelper(self.__class__.__name__, '')
-
-    def _StringHelper(self, name, suffix):
-        if not utils.DEBUG:
-            return '%s(%s)' % (name, suffix)
-        return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
-
-    def __repr__(self):
-        return str(self)
-
-
-class Define(Node):
-    def __init__(self, start, end, name, definition):
-        Node.__init__(self, start, end)
-        self.name = name
-        self.definition = definition
-
-    def __str__(self):
-        value = '%s %s' % (self.name, self.definition)
-        return self._StringHelper(self.__class__.__name__, value)
-
-
-class Include(Node):
-    def __init__(self, start, end, filename, system):
-        Node.__init__(self, start, end)
-        self.filename = filename
-        self.system = system
-
-    def __str__(self):
-        fmt = '"%s"'
-        if self.system:
-            fmt = '<%s>'
-        return self._StringHelper(self.__class__.__name__, fmt % self.filename)
-
-
-class Goto(Node):
-    def __init__(self, start, end, label):
-        Node.__init__(self, start, end)
-        self.label = label
-
-    def __str__(self):
-        return self._StringHelper(self.__class__.__name__, str(self.label))
-
-
-class Expr(Node):
-    def __init__(self, start, end, expr):
-        Node.__init__(self, start, end)
-        self.expr = expr
-
-    def Requires(self, node):
-        # TODO(nnorwitz): impl.
-        return False
-
-    def __str__(self):
-        return self._StringHelper(self.__class__.__name__, str(self.expr))
-
-
-class Return(Expr):
-    pass
-
-
-class Delete(Expr):
-    pass
-
-
-class Friend(Expr):
-    def __init__(self, start, end, expr, namespace):
-        Expr.__init__(self, start, end, expr)
-        self.namespace = namespace[:]
-
-
-class Using(Node):
-    def __init__(self, start, end, names):
-        Node.__init__(self, start, end)
-        self.names = names
-
-    def __str__(self):
-        return self._StringHelper(self.__class__.__name__, str(self.names))
-
-
-class Parameter(Node):
-    def __init__(self, start, end, name, parameter_type, default):
-        Node.__init__(self, start, end)
-        self.name = name
-        self.type = parameter_type
-        self.default = default
-
-    def Requires(self, node):
-        # TODO(nnorwitz): handle namespaces, etc.
-        return self.type.name == node.name
-
-    def __str__(self):
-        name = str(self.type)
-        suffix = '%s %s' % (name, self.name)
-        if self.default:
-            suffix += ' = ' + ''.join([d.name for d in self.default])
-        return self._StringHelper(self.__class__.__name__, suffix)
-
-
-class _GenericDeclaration(Node):
-    def __init__(self, start, end, name, namespace):
-        Node.__init__(self, start, end)
-        self.name = name
-        self.namespace = namespace[:]
-
-    def FullName(self):
-        prefix = ''
-        if self.namespace and self.namespace[-1]:
-            prefix = '::'.join(self.namespace) + '::'
-        return prefix + self.name
-
-    def _TypeStringHelper(self, suffix):
-        if self.namespace:
-            names = [n or '<anonymous>' for n in self.namespace]
-            suffix += ' in ' + '::'.join(names)
-        return self._StringHelper(self.__class__.__name__, suffix)
-
-
-# TODO(nnorwitz): merge with Parameter in some way?
-class VariableDeclaration(_GenericDeclaration):
-    def __init__(self, start, end, name, var_type, initial_value, namespace):
-        _GenericDeclaration.__init__(self, start, end, name, namespace)
-        self.type = var_type
-        self.initial_value = initial_value
-
-    def Requires(self, node):
-        # TODO(nnorwitz): handle namespaces, etc.
-        return self.type.name == node.name
-
-    def ToString(self):
-        """Return a string that tries to reconstitute the variable decl."""
-        suffix = '%s %s' % (self.type, self.name)
-        if self.initial_value:
-            suffix += ' = ' + self.initial_value
-        return suffix
-
-    def __str__(self):
-        return self._StringHelper(self.__class__.__name__, self.ToString())
-
-
-class Typedef(_GenericDeclaration):
-    def __init__(self, start, end, name, alias, namespace):
-        _GenericDeclaration.__init__(self, start, end, name, namespace)
-        self.alias = alias
-
-    def IsDefinition(self):
-        return True
-
-    def IsExportable(self):
-        return True
-
-    def Requires(self, node):
-        # TODO(nnorwitz): handle namespaces, etc.
-        name = node.name
-        for token in self.alias:
-            if token is not None and name == token.name:
-                return True
-        return False
-
-    def __str__(self):
-        suffix = '%s, %s' % (self.name, self.alias)
-        return self._TypeStringHelper(suffix)
-
-
-class _NestedType(_GenericDeclaration):
-    def __init__(self, start, end, name, fields, namespace):
-        _GenericDeclaration.__init__(self, start, end, name, namespace)
-        self.fields = fields
-
-    def IsDefinition(self):
-        return True
-
-    def IsExportable(self):
-        return True
-
-    def __str__(self):
-        suffix = '%s, {%s}' % (self.name, self.fields)
-        return self._TypeStringHelper(suffix)
-
-
-class Union(_NestedType):
-    pass
-
-
-class Enum(_NestedType):
-    pass
-
-
-class Class(_GenericDeclaration):
-    def __init__(self, start, end, name, bases, templated_types, body, namespace):
-        _GenericDeclaration.__init__(self, start, end, name, namespace)
-        self.bases = bases
-        self.body = body
-        self.templated_types = templated_types
-
-    def IsDeclaration(self):
-        return self.bases is None and self.body is None
-
-    def IsDefinition(self):
-        return not self.IsDeclaration()
-
-    def IsExportable(self):
-        return not self.IsDeclaration()
-
-    def Requires(self, node):
-        # TODO(nnorwitz): handle namespaces, etc.
-        if self.bases:
-            for token_list in self.bases:
-                # TODO(nnorwitz): bases are tokens, do name comparision.
-                for token in token_list:
-                    if token.name == node.name:
-                        return True
-        # TODO(nnorwitz): search in body too.
-        return False
-
-    def __str__(self):
-        name = self.name
-        if self.templated_types:
-            name += '<%s>' % self.templated_types
-        suffix = '%s, %s, %s' % (name, self.bases, self.body)
-        return self._TypeStringHelper(suffix)
-
-
-class Struct(Class):
-    pass
-
-
-class Function(_GenericDeclaration):
-    def __init__(self, start, end, name, return_type, parameters,
-                 modifiers, templated_types, body, namespace):
-        _GenericDeclaration.__init__(self, start, end, name, namespace)
-        converter = TypeConverter(namespace)
-        self.return_type = converter.CreateReturnType(return_type)
-        self.parameters = converter.ToParameters(parameters)
-        self.modifiers = modifiers
-        self.body = body
-        self.templated_types = templated_types
-
-    def IsDeclaration(self):
-        return self.body is None
-
-    def IsDefinition(self):
-        return self.body is not None
-
-    def IsExportable(self):
-        if self.return_type and 'static' in self.return_type.modifiers:
-            return False
-        return None not in self.namespace
-
-    def Requires(self, node):
-        if self.parameters:
-            # TODO(nnorwitz): parameters are tokens, do name comparision.
-            for p in self.parameters:
-                if p.name == node.name:
-                    return True
-        # TODO(nnorwitz): search in body too.
-        return False
-
-    def __str__(self):
-        # TODO(nnorwitz): add templated_types.
-        suffix = ('%s %s(%s), 0x%02x, %s' %
-                  (self.return_type, self.name, self.parameters,
-                   self.modifiers, self.body))
-        return self._TypeStringHelper(suffix)
-
-
-class Method(Function):
-    def __init__(self, start, end, name, in_class, return_type, parameters,
-                 modifiers, templated_types, body, namespace):
-        Function.__init__(self, start, end, name, return_type, parameters,
-                          modifiers, templated_types, body, namespace)
-        # TODO(nnorwitz): in_class could also be a namespace which can
-        # mess up finding functions properly.
-        self.in_class = in_class
-
-
-class Type(_GenericDeclaration):
-    """Type used for any variable (eg class, primitive, struct, etc)."""
-
-    def __init__(self, start, end, name, templated_types, modifiers,
-                 reference, pointer, array):
-        """
-        Args:
-          name: str name of main type
-          templated_types: [Class (Type?)] template type info between <>
-          modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
-          reference, pointer, array: bools
-        """
-        _GenericDeclaration.__init__(self, start, end, name, [])
-        self.templated_types = templated_types
-        if not name and modifiers:
-            self.name = modifiers.pop()
-        self.modifiers = modifiers
-        self.reference = reference
-        self.pointer = pointer
-        self.array = array
-
-    def __str__(self):
-        prefix = ''
-        if self.modifiers:
-            prefix = ' '.join(self.modifiers) + ' '
-        name = str(self.name)
-        if self.templated_types:
-            name += '<%s>' % self.templated_types
-        suffix = prefix + name
-        if self.reference:
-            suffix += '&'
-        if self.pointer:
-            suffix += '*'
-        if self.array:
-            suffix += '[]'
-        return self._TypeStringHelper(suffix)
-
-    # By definition, Is* are always False.  A Type can only exist in
-    # some sort of variable declaration, parameter, or return value.
-    def IsDeclaration(self):
-        return False
-
-    def IsDefinition(self):
-        return False
-
-    def IsExportable(self):
-        return False
-
-
-class TypeConverter(object):
-
-    def __init__(self, namespace_stack):
-        self.namespace_stack = namespace_stack
-
-    def _GetTemplateEnd(self, tokens, start):
-        count = 1
-        end = start
-        while 1:
-            token = tokens[end]
-            end += 1
-            if token.name == '<':
-                count += 1
-            elif token.name == '>':
-                count -= 1
-                if count == 0:
-                    break
-        return tokens[start:end-1], end
-
-    def ToType(self, tokens):
-        """Convert [Token,...] to [Class(...), ] useful for base classes.
-        For example, code like class Foo : public Bar<x, y> { ... };
-        the "Bar<x, y>" portion gets converted to an AST.
-
-        Returns:
-          [Class(...), ...]
-        """
-        result = []
-        name_tokens = []
-        reference = pointer = array = False
-
-        def AddType(templated_types):
-            # Partition tokens into name and modifier tokens.
-            names = []
-            modifiers = []
-            for t in name_tokens:
-                if keywords.IsKeyword(t.name):
-                    modifiers.append(t.name)
-                else:
-                    names.append(t.name)
-            name = ''.join(names)
-            if name_tokens:
-                result.append(Type(name_tokens[0].start, name_tokens[-1].end,
-                                   name, templated_types, modifiers,
-                                   reference, pointer, array))
-            del name_tokens[:]
-
-        i = 0
-        end = len(tokens)
-        while i < end:
-            token = tokens[i]
-            if token.name == '<':
-                new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
-                AddType(self.ToType(new_tokens))
-                # If there is a comma after the template, we need to consume
-                # that here otherwise it becomes part of the name.
-                i = new_end
-                reference = pointer = array = False
-            elif token.name == ',':
-                AddType([])
-                reference = pointer = array = False
-            elif token.name == '*':
-                pointer = True
-            elif token.name == '&':
-                reference = True
-            elif token.name == '[':
-               pointer = True
-            elif token.name == ']':
-                pass
-            else:
-                name_tokens.append(token)
-            i += 1
-
-        if name_tokens:
-            # No '<' in the tokens, just a simple name and no template.
-            AddType([])
-        return result
-
-    def DeclarationToParts(self, parts, needs_name_removed):
-        name = None
-        default = []
-        if needs_name_removed:
-            # Handle default (initial) values properly.
-            for i, t in enumerate(parts):
-                if t.name == '=':
-                    default = parts[i+1:]
-                    name = parts[i-1].name
-                    if name == ']' and parts[i-2].name == '[':
-                        name = parts[i-3].name
-                        i -= 1
-                    parts = parts[:i-1]
-                    break
-            else:
-                if parts[-1].token_type == tokenize.NAME:
-                    name = parts.pop().name
-                else:
-                    # TODO(nnorwitz): this is a hack that happens for code like
-                    # Register(Foo<T>); where it thinks this is a function call
-                    # but it's actually a declaration.
-                    name = '???'
-        modifiers = []
-        type_name = []
-        other_tokens = []
-        templated_types = []
-        i = 0
-        end = len(parts)
-        while i < end:
-            p = parts[i]
-            if keywords.IsKeyword(p.name):
-                modifiers.append(p.name)
-            elif p.name == '<':
-                templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
-                templated_types = self.ToType(templated_tokens)
-                i = new_end - 1
-                # Don't add a spurious :: to data members being initialized.
-                next_index = i + 1
-                if next_index < end and parts[next_index].name == '::':
-                    i += 1
-            elif p.name in ('[', ']', '='):
-                # These are handled elsewhere.
-                other_tokens.append(p)
-            elif p.name not in ('*', '&', '>'):
-                # Ensure that names have a space between them.
-                if (type_name and type_name[-1].token_type == tokenize.NAME and
-                    p.token_type == tokenize.NAME):
-                    type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
-                type_name.append(p)
-            else:
-                other_tokens.append(p)
-            i += 1
-        type_name = ''.join([t.name for t in type_name])
-        return name, type_name, templated_types, modifiers, default, other_tokens
-
-    def ToParameters(self, tokens):
-        if not tokens:
-            return []
-
-        result = []
-        name = type_name = ''
-        type_modifiers = []
-        pointer = reference = array = False
-        first_token = None
-        default = []
-
-        def AddParameter(end):
-            if default:
-                del default[0]  # Remove flag.
-            parts = self.DeclarationToParts(type_modifiers, True)
-            (name, type_name, templated_types, modifiers,
-             unused_default, unused_other_tokens) = parts
-            parameter_type = Type(first_token.start, first_token.end,
-                                  type_name, templated_types, modifiers,
-                                  reference, pointer, array)
-            p = Parameter(first_token.start, end, name,
-                          parameter_type, default)
-            result.append(p)
-
-        template_count = 0
-        for s in tokens:
-            if not first_token:
-                first_token = s
-            if s.name == '<':
-                template_count += 1
-            elif s.name == '>':
-                template_count -= 1
-            if template_count > 0:
-                type_modifiers.append(s)
-                continue
-
-            if s.name == ',':
-                AddParameter(s.start)
-                name = type_name = ''
-                type_modifiers = []
-                pointer = reference = array = False
-                first_token = None
-                default = []
-            elif s.name == '*':
-                pointer = True
-            elif s.name == '&':
-                reference = True
-            elif s.name == '[':
-                array = True
-            elif s.name == ']':
-                pass  # Just don't add to type_modifiers.
-            elif s.name == '=':
-                # Got a default value.  Add any value (None) as a flag.
-                default.append(None)
-            elif default:
-                default.append(s)
-            else:
-                type_modifiers.append(s)
-        AddParameter(tokens[-1].end)
-        return result
-
-    def CreateReturnType(self, return_type_seq):
-        if not return_type_seq:
-            return None
-        start = return_type_seq[0].start
-        end = return_type_seq[-1].end
-        _, name, templated_types, modifiers, default, other_tokens = \
-           self.DeclarationToParts(return_type_seq, False)
-        names = [n.name for n in other_tokens]
-        reference = '&' in names
-        pointer = '*' in names
-        array = '[' in names
-        return Type(start, end, name, templated_types, modifiers,
-                    reference, pointer, array)
-
-    def GetTemplateIndices(self, names):
-        # names is a list of strings.
-        start = names.index('<')
-        end = len(names) - 1
-        while end > 0:
-            if names[end] == '>':
-                break
-            end -= 1
-        return start, end+1
-
-class AstBuilder(object):
-    def __init__(self, token_stream, filename, in_class='', visibility=None,
-                 namespace_stack=[]):
-        self.tokens = token_stream
-        self.filename = filename
-        # TODO(nnorwitz): use a better data structure (deque) for the queue.
-        # Switching directions of the "queue" improved perf by about 25%.
-        # Using a deque should be even better since we access from both sides.
-        self.token_queue = []
-        self.namespace_stack = namespace_stack[:]
-        self.in_class = in_class
-        if in_class is None:
-            self.in_class_name_only = None
-        else:
-            self.in_class_name_only = in_class.split('::')[-1]
-        self.visibility = visibility
-        self.in_function = False
-        self.current_token = None
-        # Keep the state whether we are currently handling a typedef or not.
-        self._handling_typedef = False
-
-        self.converter = TypeConverter(self.namespace_stack)
-
-    def HandleError(self, msg, token):
-        printable_queue = list(reversed(self.token_queue[-20:]))
-        sys.stderr.write('Got %s in %s @ %s %s\n' %
-                         (msg, self.filename, token, printable_queue))
-
-    def Generate(self):
-        while 1:
-            token = self._GetNextToken()
-            if not token:
-                break
-
-            # Get the next token.
-            self.current_token = token
-
-            # Dispatch on the next token type.
-            if token.token_type == _INTERNAL_TOKEN:
-                if token.name == _NAMESPACE_POP:
-                    self.namespace_stack.pop()
-                continue
-
-            try:
-                result = self._GenerateOne(token)
-                if result is not None:
-                    yield result
-            except:
-                self.HandleError('exception', token)
-                raise
-
-    def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
-                        ref_pointer_name_seq, templated_types, value=None):
-        reference = '&' in ref_pointer_name_seq
-        pointer = '*' in ref_pointer_name_seq
-        array = '[' in ref_pointer_name_seq
-        var_type = Type(pos_token.start, pos_token.end, type_name,
-                        templated_types, type_modifiers,
-                        reference, pointer, array)
-        return VariableDeclaration(pos_token.start, pos_token.end,
-                                   name, var_type, value, self.namespace_stack)
-
-    def _GenerateOne(self, token):
-        if token.token_type == tokenize.NAME:
-            if (keywords.IsKeyword(token.name) and
-                not keywords.IsBuiltinType(token.name)):
-                method = getattr(self, 'handle_' + token.name)
-                return method()
-            elif token.name == self.in_class_name_only:
-                # The token name is the same as the class, must be a ctor if
-                # there is a paren.  Otherwise, it's the return type.
-                # Peek ahead to get the next token to figure out which.
-                next = self._GetNextToken()
-                self._AddBackToken(next)
-                if next.token_type == tokenize.SYNTAX and next.name == '(':
-                    return self._GetMethod([token], FUNCTION_CTOR, None, True)
-                # Fall through--handle like any other method.
-
-            # Handle data or function declaration/definition.
-            syntax = tokenize.SYNTAX
-            temp_tokens, last_token = \
-                self._GetVarTokensUpTo(syntax, '(', ';', '{', '[')
-            temp_tokens.insert(0, token)
-            if last_token.name == '(':
-                # If there is an assignment before the paren,
-                # this is an expression, not a method.
-                expr = bool([e for e in temp_tokens if e.name == '='])
-                if expr:
-                    new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-                    temp_tokens.append(last_token)
-                    temp_tokens.extend(new_temp)
-                    last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
-
-            if last_token.name == '[':
-                # Handle array, this isn't a method, unless it's an operator.
-                # TODO(nnorwitz): keep the size somewhere.
-                # unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
-                temp_tokens.append(last_token)
-                if temp_tokens[-2].name == 'operator':
-                    temp_tokens.append(self._GetNextToken())
-                else:
-                    temp_tokens2, last_token = \
-                        self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
-                    temp_tokens.extend(temp_tokens2)
-
-            if last_token.name == ';':
-                # Handle data, this isn't a method.
-                parts = self.converter.DeclarationToParts(temp_tokens, True)
-                (name, type_name, templated_types, modifiers, default,
-                 unused_other_tokens) = parts
-
-                t0 = temp_tokens[0]
-                names = [t.name for t in temp_tokens]
-                if templated_types:
-                    start, end = self.converter.GetTemplateIndices(names)
-                    names = names[:start] + names[end:]
-                default = ''.join([t.name for t in default])
-                return self._CreateVariable(t0, name, type_name, modifiers,
-                                            names, templated_types, default)
-            if last_token.name == '{':
-                self._AddBackTokens(temp_tokens[1:])
-                self._AddBackToken(last_token)
-                method_name = temp_tokens[0].name
-                method = getattr(self, 'handle_' + method_name, None)
-                if not method:
-                    # Must be declaring a variable.
-                    # TODO(nnorwitz): handle the declaration.
-                    return None
-                return method()
-            return self._GetMethod(temp_tokens, 0, None, False)
-        elif token.token_type == tokenize.SYNTAX:
-            if token.name == '~' and self.in_class:
-                # Must be a dtor (probably not in method body).
-                token = self._GetNextToken()
-                # self.in_class can contain A::Name, but the dtor will only
-                # be Name.  Make sure to compare against the right value.
-                if (token.token_type == tokenize.NAME and
-                    token.name == self.in_class_name_only):
-                    return self._GetMethod([token], FUNCTION_DTOR, None, True)
-            # TODO(nnorwitz): handle a lot more syntax.
-        elif token.token_type == tokenize.PREPROCESSOR:
-            # TODO(nnorwitz): handle more preprocessor directives.
-            # token starts with a #, so remove it and strip whitespace.
-            name = token.name[1:].lstrip()
-            if name.startswith('include'):
-                # Remove "include".
-                name = name[7:].strip()
-                assert name
-                # Handle #include \<newline> "header-on-second-line.h".
-                if name.startswith('\\'):
-                    name = name[1:].strip()
-                assert name[0] in '<"', token
-                assert name[-1] in '>"', token
-                system = name[0] == '<'
-                filename = name[1:-1]
-                return Include(token.start, token.end, filename, system)
-            if name.startswith('define'):
-                # Remove "define".
-                name = name[6:].strip()
-                assert name
-                value = ''
-                for i, c in enumerate(name):
-                    if c.isspace():
-                        value = name[i:].lstrip()
-                        name = name[:i]
-                        break
-                return Define(token.start, token.end, name, value)
-            if name.startswith('if') and name[2:3].isspace():
-                condition = name[3:].strip()
-                if condition.startswith('0') or condition.startswith('(0)'):
-                    self._SkipIf0Blocks()
-        return None
-
-    def _GetTokensUpTo(self, expected_token_type, expected_token):
-        return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
-
-    def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
-        last_token = self._GetNextToken()
-        tokens = []
-        while (last_token.token_type != expected_token_type or
-               last_token.name not in expected_tokens):
-            tokens.append(last_token)
-            last_token = self._GetNextToken()
-        return tokens, last_token
-
-    # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
-    def _IgnoreUpTo(self, token_type, token):
-        unused_tokens = self._GetTokensUpTo(token_type, token)
-
-    def _SkipIf0Blocks(self):
-        count = 1
-        while 1:
-            token = self._GetNextToken()
-            if token.token_type != tokenize.PREPROCESSOR:
-                continue
-
-            name = token.name[1:].lstrip()
-            if name.startswith('endif'):
-                count -= 1
-                if count == 0:
-                    break
-            elif name.startswith('if'):
-                count += 1
-
-    def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
-        if GetNextToken is None:
-            GetNextToken = self._GetNextToken
-        # Assumes the current token is open_paren and we will consume
-        # and return up to the close_paren.
-        count = 1
-        token = GetNextToken()
-        while 1:
-            if token.token_type == tokenize.SYNTAX:
-                if token.name == open_paren:
-                    count += 1
-                elif token.name == close_paren:
-                    count -= 1
-                    if count == 0:
-                        break
-            yield token
-            token = GetNextToken()
-        yield token
-
-    def _GetParameters(self):
-        return self._GetMatchingChar('(', ')')
-
-    def GetScope(self):
-        return self._GetMatchingChar('{', '}')
-
-    def _GetNextToken(self):
-        if self.token_queue:
-            return self.token_queue.pop()
-        return next(self.tokens)
-
-    def _AddBackToken(self, token):
-        if token.whence == tokenize.WHENCE_STREAM:
-            token.whence = tokenize.WHENCE_QUEUE
-            self.token_queue.insert(0, token)
-        else:
-            assert token.whence == tokenize.WHENCE_QUEUE, token
-            self.token_queue.append(token)
-
-    def _AddBackTokens(self, tokens):
-        if tokens:
-            if tokens[-1].whence == tokenize.WHENCE_STREAM:
-                for token in tokens:
-                    token.whence = tokenize.WHENCE_QUEUE
-                self.token_queue[:0] = reversed(tokens)
-            else:
-                assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
-                self.token_queue.extend(reversed(tokens))
-
-    def GetName(self, seq=None):
-        """Returns ([tokens], next_token_info)."""
-        GetNextToken = self._GetNextToken
-        if seq is not None:
-            it = iter(seq)
-            GetNextToken = lambda: next(it)
-        next_token = GetNextToken()
-        tokens = []
-        last_token_was_name = False
-        while (next_token.token_type == tokenize.NAME or
-               (next_token.token_type == tokenize.SYNTAX and
-                next_token.name in ('::', '<'))):
-            # Two NAMEs in a row means the identifier should terminate.
-            # It's probably some sort of variable declaration.
-            if last_token_was_name and next_token.token_type == tokenize.NAME:
-                break
-            last_token_was_name = next_token.token_type == tokenize.NAME
-            tokens.append(next_token)
-            # Handle templated names.
-            if next_token.name == '<':
-                tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
-                last_token_was_name = True
-            next_token = GetNextToken()
-        return tokens, next_token
-
-    def GetMethod(self, modifiers, templated_types):
-        return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
-        assert len(return_type_and_name) >= 1
-        return self._GetMethod(return_type_and_name, modifiers, templated_types,
-                               False)
-
-    def _GetMethod(self, return_type_and_name, modifiers, templated_types,
-                   get_paren):
-        template_portion = None
-        if get_paren:
-            token = self._GetNextToken()
-            assert token.token_type == tokenize.SYNTAX, token
-            if token.name == '<':
-                # Handle templatized dtors.
-                template_portion = [token]
-                template_portion.extend(self._GetMatchingChar('<', '>'))
-                token = self._GetNextToken()
-            assert token.token_type == tokenize.SYNTAX, token
-            assert token.name == '(', token
-
-        name = return_type_and_name.pop()
-        # Handle templatized ctors.
-        if name.name == '>':
-            index = 1
-            while return_type_and_name[index].name != '<':
-                index += 1
-            template_portion = return_type_and_name[index:] + [name]
-            del return_type_and_name[index:]
-            name = return_type_and_name.pop()
-        elif name.name == ']':
-            rt = return_type_and_name
-            assert rt[-1].name == '[', return_type_and_name
-            assert rt[-2].name == 'operator', return_type_and_name
-            name_seq = return_type_and_name[-2:]
-            del return_type_and_name[-2:]
-            name = tokenize.Token(tokenize.NAME, 'operator[]',
-                                  name_seq[0].start, name.end)
-            # Get the open paren so _GetParameters() below works.
-            unused_open_paren = self._GetNextToken()
-
-        # TODO(nnorwitz): store template_portion.
-        return_type = return_type_and_name
-        indices = name
-        if return_type:
-            indices = return_type[0]
-
-        # Force ctor for templatized ctors.
-        if name.name == self.in_class and not modifiers:
-            modifiers |= FUNCTION_CTOR
-        parameters = list(self._GetParameters())
-        del parameters[-1]              # Remove trailing ')'.
-
-        # Handling operator() is especially weird.
-        if name.name == 'operator' and not parameters:
-            token = self._GetNextToken()
-            assert token.name == '(', token
-            parameters = list(self._GetParameters())
-            del parameters[-1]          # Remove trailing ')'.
-
-        token = self._GetNextToken()
-        while token.token_type == tokenize.NAME:
-            modifier_token = token
-            token = self._GetNextToken()
-            if modifier_token.name == 'const':
-                modifiers |= FUNCTION_CONST
-            elif modifier_token.name == '__attribute__':
-                # TODO(nnorwitz): handle more __attribute__ details.
-                modifiers |= FUNCTION_ATTRIBUTE
-                assert token.name == '(', token
-                # Consume everything between the (parens).
-                unused_tokens = list(self._GetMatchingChar('(', ')'))
-                token = self._GetNextToken()
-            elif modifier_token.name == 'throw':
-                modifiers |= FUNCTION_THROW
-                assert token.name == '(', token
-                # Consume everything between the (parens).
-                unused_tokens = list(self._GetMatchingChar('(', ')'))
-                token = self._GetNextToken()
-            elif modifier_token.name == 'override':
-                modifiers |= FUNCTION_OVERRIDE
-            elif modifier_token.name == modifier_token.name.upper():
-                # HACK(nnorwitz):  assume that all upper-case names
-                # are some macro we aren't expanding.
-                modifiers |= FUNCTION_UNKNOWN_ANNOTATION
-            else:
-                self.HandleError('unexpected token', modifier_token)
-
-        assert token.token_type == tokenize.SYNTAX, token
-        # Handle ctor initializers.
-        if token.name == ':':
-            # TODO(nnorwitz): anything else to handle for initializer list?
-            while token.name != ';' and token.name != '{':
-                token = self._GetNextToken()
-
-        # Handle pointer to functions that are really data but look
-        # like method declarations.
-        if token.name == '(':
-            if parameters[0].name == '*':
-                # name contains the return type.
-                name = parameters.pop()
-                # parameters contains the name of the data.
-                modifiers = [p.name for p in parameters]
-                # Already at the ( to open the parameter list.
-                function_parameters = list(self._GetMatchingChar('(', ')'))
-                del function_parameters[-1]  # Remove trailing ')'.
-                # TODO(nnorwitz): store the function_parameters.
-                token = self._GetNextToken()
-                assert token.token_type == tokenize.SYNTAX, token
-                assert token.name == ';', token
-                return self._CreateVariable(indices, name.name, indices.name,
-                                            modifiers, '', None)
-            # At this point, we got something like:
-            #  return_type (type::*name_)(params);
-            # This is a data member called name_ that is a function pointer.
-            # With this code: void (sq_type::*field_)(string&);
-            # We get: name=void return_type=[] parameters=sq_type ... field_
-            # TODO(nnorwitz): is return_type always empty?
-            # TODO(nnorwitz): this isn't even close to being correct.
-            # Just put in something so we don't crash and can move on.
-            real_name = parameters[-1]
-            modifiers = [p.name for p in self._GetParameters()]
-            del modifiers[-1]           # Remove trailing ')'.
-            return self._CreateVariable(indices, real_name.name, indices.name,
-                                        modifiers, '', None)
-
-        if token.name == '{':
-            body = list(self.GetScope())
-            del body[-1]                # Remove trailing '}'.
-        else:
-            body = None
-            if token.name == '=':
-                token = self._GetNextToken()
-
-                if token.name == 'default' or token.name == 'delete':
-                    # Ignore explicitly defaulted and deleted special members
-                    # in C++11.
-                    token = self._GetNextToken()
-                else:
-                    # Handle pure-virtual declarations.
-                    assert token.token_type == tokenize.CONSTANT, token
-                    assert token.name == '0', token
-                    modifiers |= FUNCTION_PURE_VIRTUAL
-                    token = self._GetNextToken()
-
-            if token.name == '[':
-                # TODO(nnorwitz): store tokens and improve parsing.
-                # template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
-                tokens = list(self._GetMatchingChar('[', ']'))
-                token = self._GetNextToken()
-
-            assert token.name == ';', (token, return_type_and_name, parameters)
-
-        # Looks like we got a method, not a function.
-        if len(return_type) > 2 and return_type[-1].name == '::':
-            return_type, in_class = \
-                         self._GetReturnTypeAndClassName(return_type)
-            return Method(indices.start, indices.end, name.name, in_class,
-                          return_type, parameters, modifiers, templated_types,
-                          body, self.namespace_stack)
-        return Function(indices.start, indices.end, name.name, return_type,
-                        parameters, modifiers, templated_types, body,
-                        self.namespace_stack)
-
-    def _GetReturnTypeAndClassName(self, token_seq):
-        # Splitting the return type from the class name in a method
-        # can be tricky.  For example, Return::Type::Is::Hard::To::Find().
-        # Where is the return type and where is the class name?
-        # The heuristic used is to pull the last name as the class name.
-        # This includes all the templated type info.
-        # TODO(nnorwitz): if there is only One name like in the
-        # example above, punt and assume the last bit is the class name.
-
-        # Ignore a :: prefix, if exists so we can find the first real name.
-        i = 0
-        if token_seq[0].name == '::':
-            i = 1
-        # Ignore a :: suffix, if exists.
-        end = len(token_seq) - 1
-        if token_seq[end-1].name == '::':
-            end -= 1
-
-        # Make a copy of the sequence so we can append a sentinel
-        # value. This is required for GetName will has to have some
-        # terminating condition beyond the last name.
-        seq_copy = token_seq[i:end]
-        seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
-        names = []
-        while i < end:
-            # Iterate through the sequence parsing out each name.
-            new_name, next = self.GetName(seq_copy[i:])
-            assert new_name, 'Got empty new_name, next=%s' % next
-            # We got a pointer or ref.  Add it to the name.
-            if next and next.token_type == tokenize.SYNTAX:
-                new_name.append(next)
-            names.append(new_name)
-            i += len(new_name)
-
-        # Now that we have the names, it's time to undo what we did.
-
-        # Remove the sentinel value.
-        names[-1].pop()
-        # Flatten the token sequence for the return type.
-        return_type = [e for seq in names[:-1] for e in seq]
-        # The class name is the last name.
-        class_name = names[-1]
-        return return_type, class_name
-
-    def handle_bool(self):
-        pass
-
-    def handle_char(self):
-        pass
-
-    def handle_int(self):
-        pass
-
-    def handle_long(self):
-        pass
-
-    def handle_short(self):
-        pass
-
-    def handle_double(self):
-        pass
-
-    def handle_float(self):
-        pass
-
-    def handle_void(self):
-        pass
-
-    def handle_wchar_t(self):
-        pass
-
-    def handle_unsigned(self):
-        pass
-
-    def handle_signed(self):
-        pass
-
-    def _GetNestedType(self, ctor):
-        name = None
-        name_tokens, token = self.GetName()
-        if name_tokens:
-            name = ''.join([t.name for t in name_tokens])
-
-        # Handle forward declarations.
-        if token.token_type == tokenize.SYNTAX and token.name == ';':
-            return ctor(token.start, token.end, name, None,
-                        self.namespace_stack)
-
-        if token.token_type == tokenize.NAME and self._handling_typedef:
-            self._AddBackToken(token)
-            return ctor(token.start, token.end, name, None,
-                        self.namespace_stack)
-
-        # Must be the type declaration.
-        fields = list(self._GetMatchingChar('{', '}'))
-        del fields[-1]                  # Remove trailing '}'.
-        if token.token_type == tokenize.SYNTAX and token.name == '{':
-            next = self._GetNextToken()
-            new_type = ctor(token.start, token.end, name, fields,
-                            self.namespace_stack)
-            # A name means this is an anonymous type and the name
-            # is the variable declaration.
-            if next.token_type != tokenize.NAME:
-                return new_type
-            name = new_type
-            token = next
-
-        # Must be variable declaration using the type prefixed with keyword.
-        assert token.token_type == tokenize.NAME, token
-        return self._CreateVariable(token, token.name, name, [], '', None)
-
-    def handle_struct(self):
-        # Special case the handling typedef/aliasing of structs here.
-        # It would be a pain to handle in the class code.
-        name_tokens, var_token = self.GetName()
-        if name_tokens:
-            next_token = self._GetNextToken()
-            is_syntax = (var_token.token_type == tokenize.SYNTAX and
-                         var_token.name[0] in '*&')
-            is_variable = (var_token.token_type == tokenize.NAME and
-                           next_token.name == ';')
-            variable = var_token
-            if is_syntax and not is_variable:
-                variable = next_token
-                temp = self._GetNextToken()
-                if temp.token_type == tokenize.SYNTAX and temp.name == '(':
-                    # Handle methods declared to return a struct.
-                    t0 = name_tokens[0]
-                    struct = tokenize.Token(tokenize.NAME, 'struct',
-                                            t0.start-7, t0.start-2)
-                    type_and_name = [struct]
-                    type_and_name.extend(name_tokens)
-                    type_and_name.extend((var_token, next_token))
-                    return self._GetMethod(type_and_name, 0, None, False)
-                assert temp.name == ';', (temp, name_tokens, var_token)
-            if is_syntax or (is_variable and not self._handling_typedef):
-                modifiers = ['struct']
-                type_name = ''.join([t.name for t in name_tokens])
-                position = name_tokens[0]
-                return self._CreateVariable(position, variable.name, type_name,
-                                            modifiers, var_token.name, None)
-            name_tokens.extend((var_token, next_token))
-            self._AddBackTokens(name_tokens)
-        else:
-            self._AddBackToken(var_token)
-        return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
-
-    def handle_union(self):
-        return self._GetNestedType(Union)
-
-    def handle_enum(self):
-        return self._GetNestedType(Enum)
-
-    def handle_auto(self):
-        # TODO(nnorwitz): warn about using auto?  Probably not since it
-        # will be reclaimed and useful for C++0x.
-        pass
-
-    def handle_register(self):
-        pass
-
-    def handle_const(self):
-        pass
-
-    def handle_inline(self):
-        pass
-
-    def handle_extern(self):
-        pass
-
-    def handle_static(self):
-        pass
-
-    def handle_virtual(self):
-        # What follows must be a method.
-        token = token2 = self._GetNextToken()
-        if token.name == 'inline':
-            # HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
-            token2 = self._GetNextToken()
-        if token2.token_type == tokenize.SYNTAX and token2.name == '~':
-            return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
-        assert token.token_type == tokenize.NAME or token.name == '::', token
-        return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')  # )
-        return_type_and_name.insert(0, token)
-        if token2 is not token:
-            return_type_and_name.insert(1, token2)
-        return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
-                               None, False)
-
-    def handle_volatile(self):
-        pass
-
-    def handle_mutable(self):
-        pass
-
-    def handle_public(self):
-        assert self.in_class
-        self.visibility = VISIBILITY_PUBLIC
-
-    def handle_protected(self):
-        assert self.in_class
-        self.visibility = VISIBILITY_PROTECTED
-
-    def handle_private(self):
-        assert self.in_class
-        self.visibility = VISIBILITY_PRIVATE
-
-    def handle_friend(self):
-        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-        assert tokens
-        t0 = tokens[0]
-        return Friend(t0.start, t0.end, tokens, self.namespace_stack)
-
-    def handle_static_cast(self):
-        pass
-
-    def handle_const_cast(self):
-        pass
-
-    def handle_dynamic_cast(self):
-        pass
-
-    def handle_reinterpret_cast(self):
-        pass
-
-    def handle_new(self):
-        pass
-
-    def handle_delete(self):
-        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-        assert tokens
-        return Delete(tokens[0].start, tokens[0].end, tokens)
-
-    def handle_typedef(self):
-        token = self._GetNextToken()
-        if (token.token_type == tokenize.NAME and
-            keywords.IsKeyword(token.name)):
-            # Token must be struct/enum/union/class.
-            method = getattr(self, 'handle_' + token.name)
-            self._handling_typedef = True
-            tokens = [method()]
-            self._handling_typedef = False
-        else:
-            tokens = [token]
-
-        # Get the remainder of the typedef up to the semi-colon.
-        tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
-
-        # TODO(nnorwitz): clean all this up.
-        assert tokens
-        name = tokens.pop()
-        indices = name
-        if tokens:
-            indices = tokens[0]
-        if not indices:
-            indices = token
-        if name.name == ')':
-            # HACK(nnorwitz): Handle pointers to functions "properly".
-            if (len(tokens) >= 4 and
-                tokens[1].name == '(' and tokens[2].name == '*'):
-                tokens.append(name)
-                name = tokens[3]
-        elif name.name == ']':
-            # HACK(nnorwitz): Handle arrays properly.
-            if len(tokens) >= 2:
-                tokens.append(name)
-                name = tokens[1]
-        new_type = tokens
-        if tokens and isinstance(tokens[0], tokenize.Token):
-            new_type = self.converter.ToType(tokens)[0]
-        return Typedef(indices.start, indices.end, name.name,
-                       new_type, self.namespace_stack)
-
-    def handle_typeid(self):
-        pass  # Not needed yet.
-
-    def handle_typename(self):
-        pass  # Not needed yet.
-
-    def _GetTemplatedTypes(self):
-        result = {}
-        tokens = list(self._GetMatchingChar('<', '>'))
-        len_tokens = len(tokens) - 1    # Ignore trailing '>'.
-        i = 0
-        while i < len_tokens:
-            key = tokens[i].name
-            i += 1
-            if keywords.IsKeyword(key) or key == ',':
-                continue
-            type_name = default = None
-            if i < len_tokens:
-                i += 1
-                if tokens[i-1].name == '=':
-                    assert i < len_tokens, '%s %s' % (i, tokens)
-                    default, unused_next_token = self.GetName(tokens[i:])
-                    i += len(default)
-                else:
-                    if tokens[i-1].name != ',':
-                        # We got something like: Type variable.
-                        # Re-adjust the key (variable) and type_name (Type).
-                        key = tokens[i-1].name
-                        type_name = tokens[i-2]
-
-            result[key] = (type_name, default)
-        return result
-
-    def handle_template(self):
-        token = self._GetNextToken()
-        assert token.token_type == tokenize.SYNTAX, token
-        assert token.name == '<', token
-        templated_types = self._GetTemplatedTypes()
-        # TODO(nnorwitz): for now, just ignore the template params.
-        token = self._GetNextToken()
-        if token.token_type == tokenize.NAME:
-            if token.name == 'class':
-                return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
-            elif token.name == 'struct':
-                return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
-            elif token.name == 'friend':
-                return self.handle_friend()
-        self._AddBackToken(token)
-        tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
-        tokens.append(last)
-        self._AddBackTokens(tokens)
-        if last.name == '(':
-            return self.GetMethod(FUNCTION_NONE, templated_types)
-        # Must be a variable definition.
-        return None
-
-    def handle_true(self):
-        pass  # Nothing to do.
-
-    def handle_false(self):
-        pass  # Nothing to do.
-
-    def handle_asm(self):
-        pass  # Not needed yet.
-
-    def handle_class(self):
-        return self._GetClass(Class, VISIBILITY_PRIVATE, None)
-
-    def _GetBases(self):
-        # Get base classes.
-        bases = []
-        while 1:
-            token = self._GetNextToken()
-            assert token.token_type == tokenize.NAME, token
-            # TODO(nnorwitz): store kind of inheritance...maybe.
-            if token.name not in ('public', 'protected', 'private'):
-                # If inheritance type is not specified, it is private.
-                # Just put the token back so we can form a name.
-                # TODO(nnorwitz): it would be good to warn about this.
-                self._AddBackToken(token)
-            else:
-                # Check for virtual inheritance.
-                token = self._GetNextToken()
-                if token.name != 'virtual':
-                    self._AddBackToken(token)
-                else:
-                    # TODO(nnorwitz): store that we got virtual for this base.
-                    pass
-            base, next_token = self.GetName()
-            bases_ast = self.converter.ToType(base)
-            assert len(bases_ast) == 1, bases_ast
-            bases.append(bases_ast[0])
-            assert next_token.token_type == tokenize.SYNTAX, next_token
-            if next_token.name == '{':
-                token = next_token
-                break
-            # Support multiple inheritance.
-            assert next_token.name == ',', next_token
-        return bases, token
-
-    def _GetClass(self, class_type, visibility, templated_types):
-        class_name = None
-        class_token = self._GetNextToken()
-        if class_token.token_type != tokenize.NAME:
-            assert class_token.token_type == tokenize.SYNTAX, class_token
-            token = class_token
-        else:
-            # Skip any macro (e.g. storage class specifiers) after the
-            # 'class' keyword.
-            next_token = self._GetNextToken()
-            if next_token.token_type == tokenize.NAME:
-                self._AddBackToken(next_token)
-            else:
-                self._AddBackTokens([class_token, next_token])
-            name_tokens, token = self.GetName()
-            class_name = ''.join([t.name for t in name_tokens])
-        bases = None
-        if token.token_type == tokenize.SYNTAX:
-            if token.name == ';':
-                # Forward declaration.
-                return class_type(class_token.start, class_token.end,
-                                  class_name, None, templated_types, None,
-                                  self.namespace_stack)
-            if token.name in '*&':
-                # Inline forward declaration.  Could be method or data.
-                name_token = self._GetNextToken()
-                next_token = self._GetNextToken()
-                if next_token.name == ';':
-                    # Handle data
-                    modifiers = ['class']
-                    return self._CreateVariable(class_token, name_token.name,
-                                                class_name,
-                                                modifiers, token.name, None)
-                else:
-                    # Assume this is a method.
-                    tokens = (class_token, token, name_token, next_token)
-                    self._AddBackTokens(tokens)
-                    return self.GetMethod(FUNCTION_NONE, None)
-            if token.name == ':':
-                bases, token = self._GetBases()
-
-        body = None
-        if token.token_type == tokenize.SYNTAX and token.name == '{':
-            assert token.token_type == tokenize.SYNTAX, token
-            assert token.name == '{', token
-
-            ast = AstBuilder(self.GetScope(), self.filename, class_name,
-                             visibility, self.namespace_stack)
-            body = list(ast.Generate())
-
-            if not self._handling_typedef:
-                token = self._GetNextToken()
-                if token.token_type != tokenize.NAME:
-                    assert token.token_type == tokenize.SYNTAX, token
-                    assert token.name == ';', token
-                else:
-                    new_class = class_type(class_token.start, class_token.end,
-                                           class_name, bases, None,
-                                           body, self.namespace_stack)
-
-                    modifiers = []
-                    return self._CreateVariable(class_token,
-                                                token.name, new_class,
-                                                modifiers, token.name, None)
-        else:
-            if not self._handling_typedef:
-                self.HandleError('non-typedef token', token)
-            self._AddBackToken(token)
-
-        return class_type(class_token.start, class_token.end, class_name,
-                          bases, templated_types, body, self.namespace_stack)
-
-    def handle_namespace(self):
-        token = self._GetNextToken()
-        # Support anonymous namespaces.
-        name = None
-        if token.token_type == tokenize.NAME:
-            name = token.name
-            token = self._GetNextToken()
-        self.namespace_stack.append(name)
-        assert token.token_type == tokenize.SYNTAX, token
-        # Create an internal token that denotes when the namespace is complete.
-        internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
-                                        None, None)
-        internal_token.whence = token.whence
-        if token.name == '=':
-            # TODO(nnorwitz): handle aliasing namespaces.
-            name, next_token = self.GetName()
-            assert next_token.name == ';', next_token
-            self._AddBackToken(internal_token)
-        else:
-            assert token.name == '{', token
-            tokens = list(self.GetScope())
-            # Replace the trailing } with the internal namespace pop token.
-            tokens[-1] = internal_token
-            # Handle namespace with nothing in it.
-            self._AddBackTokens(tokens)
-        return None
-
-    def handle_using(self):
-        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-        assert tokens
-        return Using(tokens[0].start, tokens[0].end, tokens)
-
-    def handle_explicit(self):
-        assert self.in_class
-        # Nothing much to do.
-        # TODO(nnorwitz): maybe verify the method name == class name.
-        # This must be a ctor.
-        return self.GetMethod(FUNCTION_CTOR, None)
-
-    def handle_this(self):
-        pass  # Nothing to do.
-
-    def handle_operator(self):
-        # Pull off the next token(s?) and make that part of the method name.
-        pass
-
-    def handle_sizeof(self):
-        pass
-
-    def handle_case(self):
-        pass
-
-    def handle_switch(self):
-        pass
-
-    def handle_default(self):
-        token = self._GetNextToken()
-        assert token.token_type == tokenize.SYNTAX
-        assert token.name == ':'
-
-    def handle_if(self):
-        pass
-
-    def handle_else(self):
-        pass
-
-    def handle_return(self):
-        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-        if not tokens:
-            return Return(self.current_token.start, self.current_token.end, None)
-        return Return(tokens[0].start, tokens[0].end, tokens)
-
-    def handle_goto(self):
-        tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-        assert len(tokens) == 1, str(tokens)
-        return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
-
-    def handle_try(self):
-        pass  # Not needed yet.
-
-    def handle_catch(self):
-        pass  # Not needed yet.
-
-    def handle_throw(self):
-        pass  # Not needed yet.
-
-    def handle_while(self):
-        pass
-
-    def handle_do(self):
-        pass
-
-    def handle_for(self):
-        pass
-
-    def handle_break(self):
-        self._IgnoreUpTo(tokenize.SYNTAX, ';')
-
-    def handle_continue(self):
-        self._IgnoreUpTo(tokenize.SYNTAX, ';')
-
-
-def BuilderFromSource(source, filename):
-    """Utility method that returns an AstBuilder from source code.
-
-    Args:
-      source: 'C++ source code'
-      filename: 'file1'
-
-    Returns:
-      AstBuilder
-    """
-    return AstBuilder(tokenize.GetTokens(source), filename)
-
-
-def PrintIndentifiers(filename, should_print):
-    """Prints all identifiers for a C++ source file.
-
-    Args:
-      filename: 'file1'
-      should_print: predicate with signature: bool Function(token)
-    """
-    source = utils.ReadFile(filename, False)
-    if source is None:
-        sys.stderr.write('Unable to find: %s\n' % filename)
-        return
-
-    #print('Processing %s' % actual_filename)
-    builder = BuilderFromSource(source, filename)
-    try:
-        for node in builder.Generate():
-            if should_print(node):
-                print(node.name)
-    except KeyboardInterrupt:
-        return
-    except:
-        pass
-
-
-def PrintAllIndentifiers(filenames, should_print):
-    """Prints all identifiers for each C++ source file in filenames.
-
-    Args:
-      filenames: ['file1', 'file2', ...]
-      should_print: predicate with signature: bool Function(token)
-    """
-    for path in filenames:
-        PrintIndentifiers(path, should_print)
-
-
-def main(argv):
-    for filename in argv[1:]:
-        source = utils.ReadFile(filename)
-        if source is None:
-            continue
-
-        print('Processing %s' % filename)
-        builder = BuilderFromSource(source, filename)
-        try:
-            entire_ast = filter(None, builder.Generate())
-        except KeyboardInterrupt:
-            return
-        except:
-            # Already printed a warning, print the traceback and continue.
-            traceback.print_exc()
-        else:
-            if utils.DEBUG:
-                for ast in entire_ast:
-                    print(ast)
-
-
-if __name__ == '__main__':
-    main(sys.argv)
diff --git a/testing/gmock/scripts/generator/cpp/gmock_class.py b/testing/gmock/scripts/generator/cpp/gmock_class.py
deleted file mode 100755
index f9966cb..0000000
--- a/testing/gmock/scripts/generator/cpp/gmock_class.py
+++ /dev/null
@@ -1,227 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008 Google Inc.  All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generate Google Mock classes from base classes.
-
-This program will read in a C++ source file and output the Google Mock
-classes for the specified classes.  If no class is specified, all
-classes in the source file are emitted.
-
-Usage:
-  gmock_class.py header-file.h [ClassName]...
-
-Output is sent to stdout.
-"""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-import os
-import re
-import sys
-
-from cpp import ast
-from cpp import utils
-
-# Preserve compatibility with Python 2.3.
-try:
-  _dummy = set
-except NameError:
-  import sets
-  set = sets.Set
-
-_VERSION = (1, 0, 1)  # The version of this script.
-# How many spaces to indent.  Can set me with the INDENT environment variable.
-_INDENT = 2
-
-
-def _GenerateMethods(output_lines, source, class_node):
-  function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL |
-                   ast.FUNCTION_OVERRIDE)
-  ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
-  indent = ' ' * _INDENT
-
-  for node in class_node.body:
-    # We only care about virtual functions.
-    if (isinstance(node, ast.Function) and
-        node.modifiers & function_type and
-        not node.modifiers & ctor_or_dtor):
-      # Pick out all the elements we need from the original function.
-      const = ''
-      if node.modifiers & ast.FUNCTION_CONST:
-        const = 'CONST_'
-      return_type = 'void'
-      if node.return_type:
-        # Add modifiers like 'const'.
-        modifiers = ''
-        if node.return_type.modifiers:
-          modifiers = ' '.join(node.return_type.modifiers) + ' '
-        return_type = modifiers + node.return_type.name
-        template_args = [arg.name for arg in node.return_type.templated_types]
-        if template_args:
-          return_type += '<' + ', '.join(template_args) + '>'
-          if len(template_args) > 1:
-            for line in [
-                '// The following line won\'t really compile, as the return',
-                '// type has multiple template arguments.  To fix it, use a',
-                '// typedef for the return type.']:
-              output_lines.append(indent + line)
-        if node.return_type.pointer:
-          return_type += '*'
-        if node.return_type.reference:
-          return_type += '&'
-        num_parameters = len(node.parameters)
-        if len(node.parameters) == 1:
-          first_param = node.parameters[0]
-          if source[first_param.start:first_param.end].strip() == 'void':
-            # We must treat T(void) as a function with no parameters.
-            num_parameters = 0
-      tmpl = ''
-      if class_node.templated_types:
-        tmpl = '_T'
-      mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
-
-      args = ''
-      if node.parameters:
-        # Due to the parser limitations, it is impossible to keep comments
-        # while stripping the default parameters.  When defaults are
-        # present, we choose to strip them and comments (and produce
-        # compilable code).
-        # TODO(nnorwitz@google.com): Investigate whether it is possible to
-        # preserve parameter name when reconstructing parameter text from
-        # the AST.
-        if len([param for param in node.parameters if param.default]) > 0:
-          args = ', '.join(param.type.name for param in node.parameters)
-        else:
-          # Get the full text of the parameters from the start
-          # of the first parameter to the end of the last parameter.
-          start = node.parameters[0].start
-          end = node.parameters[-1].end
-          # Remove // comments.
-          args_strings = re.sub(r'//.*', '', source[start:end])
-          # Condense multiple spaces and eliminate newlines putting the
-          # parameters together on a single line.  Ensure there is a
-          # space in an argument which is split by a newline without
-          # intervening whitespace, e.g.: int\nBar
-          args = re.sub('  +', ' ', args_strings.replace('\n', ' '))
-
-      # Create the mock method definition.
-      output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
-                           '%s%s(%s));' % (indent*3, return_type, args)])
-
-
-def _GenerateMocks(filename, source, ast_list, desired_class_names):
-  processed_class_names = set()
-  lines = []
-  for node in ast_list:
-    if (isinstance(node, ast.Class) and node.body and
-        # desired_class_names being None means that all classes are selected.
-        (not desired_class_names or node.name in desired_class_names)):
-      class_name = node.name
-      parent_name = class_name
-      processed_class_names.add(class_name)
-      class_node = node
-      # Add namespace before the class.
-      if class_node.namespace:
-        lines.extend(['namespace %s {' % n for n in class_node.namespace])  # }
-        lines.append('')
-
-      # Add template args for templated classes.
-      if class_node.templated_types:
-        # TODO(paulchang): The AST doesn't preserve template argument order,
-        # so we have to make up names here.
-        # TODO(paulchang): Handle non-type template arguments (e.g.
-        # template<typename T, int N>).
-        template_arg_count = len(class_node.templated_types.keys())
-        template_args = ['T%d' % n for n in range(template_arg_count)]
-        template_decls = ['typename ' + arg for arg in template_args]
-        lines.append('template <' + ', '.join(template_decls) + '>')
-        parent_name += '<' + ', '.join(template_args) + '>'
-
-      # Add the class prolog.
-      lines.append('class Mock%s : public %s {'  # }
-                   % (class_name, parent_name))
-      lines.append('%spublic:' % (' ' * (_INDENT // 2)))
-
-      # Add all the methods.
-      _GenerateMethods(lines, source, class_node)
-
-      # Close the class.
-      if lines:
-        # If there are no virtual methods, no need for a public label.
-        if len(lines) == 2:
-          del lines[-1]
-
-        # Only close the class if there really is a class.
-        lines.append('};')
-        lines.append('')  # Add an extra newline.
-
-      # Close the namespace.
-      if class_node.namespace:
-        for i in range(len(class_node.namespace)-1, -1, -1):
-          lines.append('}  // namespace %s' % class_node.namespace[i])
-        lines.append('')  # Add an extra newline.
-
-  if desired_class_names:
-    missing_class_name_list = list(desired_class_names - processed_class_names)
-    if missing_class_name_list:
-      missing_class_name_list.sort()
-      sys.stderr.write('Class(es) not found in %s: %s\n' %
-                       (filename, ', '.join(missing_class_name_list)))
-  elif not processed_class_names:
-    sys.stderr.write('No class found in %s\n' % filename)
-
-  return lines
-
-
-def main(argv=sys.argv):
-  if len(argv) < 2:
-    sys.stderr.write('Google Mock Class Generator v%s\n\n' %
-                     '.'.join(map(str, _VERSION)))
-    sys.stderr.write(__doc__)
-    return 1
-
-  global _INDENT
-  try:
-    _INDENT = int(os.environ['INDENT'])
-  except KeyError:
-    pass
-  except:
-    sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
-
-  filename = argv[1]
-  desired_class_names = None  # None means all classes in the source file.
-  if len(argv) >= 3:
-    desired_class_names = set(argv[2:])
-  source = utils.ReadFile(filename)
-  if source is None:
-    return 1
-
-  builder = ast.BuilderFromSource(source, filename)
-  try:
-    entire_ast = filter(None, builder.Generate())
-  except KeyboardInterrupt:
-    return
-  except:
-    # An error message was already printed since we couldn't parse.
-    sys.exit(1)
-  else:
-    lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
-    sys.stdout.write('\n'.join(lines))
-
-
-if __name__ == '__main__':
-  main(sys.argv)
diff --git a/testing/gmock/scripts/generator/cpp/gmock_class_test.py b/testing/gmock/scripts/generator/cpp/gmock_class_test.py
deleted file mode 100755
index 018f90a..0000000
--- a/testing/gmock/scripts/generator/cpp/gmock_class_test.py
+++ /dev/null
@@ -1,448 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2009 Neal Norwitz All Rights Reserved.
-# Portions Copyright 2009 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Tests for gmock.scripts.generator.cpp.gmock_class."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-import os
-import sys
-import unittest
-
-# Allow the cpp imports below to work when run as a standalone script.
-sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
-
-from cpp import ast
-from cpp import gmock_class
-
-
-class TestCase(unittest.TestCase):
-  """Helper class that adds assert methods."""
-
-  def StripLeadingWhitespace(self, lines):
-    """Strip leading whitespace in each line in 'lines'."""
-    return '\n'.join([s.lstrip() for s in lines.split('\n')])
-
-  def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
-    """Specialized assert that ignores the indent level."""
-    self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
-
-
-class GenerateMethodsTest(TestCase):
-
-  def GenerateMethodSource(self, cpp_source):
-    """Convert C++ source to Google Mock output source lines."""
-    method_source_lines = []
-    # <test> is a pseudo-filename, it is not read or written.
-    builder = ast.BuilderFromSource(cpp_source, '<test>')
-    ast_list = list(builder.Generate())
-    gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
-    return '\n'.join(method_source_lines)
-
-  def testSimpleMethod(self):
-    source = """
-class Foo {
- public:
-  virtual int Bar();
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testSimpleConstructorsAndDestructor(self):
-    source = """
-class Foo {
- public:
-  Foo();
-  Foo(int x);
-  Foo(const Foo& f);
-  Foo(Foo&& f);
-  ~Foo();
-  virtual int Bar() = 0;
-};
-"""
-    # The constructors and destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testVirtualDestructor(self):
-    source = """
-class Foo {
- public:
-  virtual ~Foo();
-  virtual int Bar() = 0;
-};
-"""
-    # The destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testExplicitlyDefaultedConstructorsAndDestructor(self):
-    source = """
-class Foo {
- public:
-  Foo() = default;
-  Foo(const Foo& f) = default;
-  Foo(Foo&& f) = default;
-  ~Foo() = default;
-  virtual int Bar() = 0;
-};
-"""
-    # The constructors and destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testExplicitlyDeletedConstructorsAndDestructor(self):
-    source = """
-class Foo {
- public:
-  Foo() = delete;
-  Foo(const Foo& f) = delete;
-  Foo(Foo&& f) = delete;
-  ~Foo() = delete;
-  virtual int Bar() = 0;
-};
-"""
-    # The constructors and destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testSimpleOverrideMethod(self):
-    source = """
-class Foo {
- public:
-  int Bar() override;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testSimpleConstMethod(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(bool flag) const;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));',
-        self.GenerateMethodSource(source))
-
-  def testExplicitVoid(self):
-    source = """
-class Foo {
- public:
-  virtual int Bar(void);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0(Bar,\nint(void));',
-        self.GenerateMethodSource(source))
-
-  def testStrangeNewlineInParameter(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int
-a) = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD1(Bar,\nvoid(int a));',
-        self.GenerateMethodSource(source))
-
-  def testDefaultParameters(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a, char c = 'x') = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD2(Bar,\nvoid(int, char));',
-        self.GenerateMethodSource(source))
-
-  def testMultipleDefaultParameters(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a = 42, char c = 'x') = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD2(Bar,\nvoid(int, char));',
-        self.GenerateMethodSource(source))
-
-  def testRemovesCommentsWhenDefaultsArePresent(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a = 42 /* a comment */,
-                   char /* other comment */ c= 'x') = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD2(Bar,\nvoid(int, char));',
-        self.GenerateMethodSource(source))
-
-  def testDoubleSlashCommentsInParameterListAreRemoved(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a,  // inline comments should be elided.
-                   int b   // inline comments should be elided.
-                   ) const = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));',
-        self.GenerateMethodSource(source))
-
-  def testCStyleCommentsInParameterListAreNotRemoved(self):
-    # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
-    # comments.  Also note that C style comments after the last parameter
-    # are still elided.
-    source = """
-class Foo {
- public:
-  virtual const string& Bar(int /* keeper */, int b);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));',
-        self.GenerateMethodSource(source))
-
-  def testArgsOfTemplateTypes(self):
-    source = """
-class Foo {
- public:
-  virtual int Bar(const vector<int>& v, map<int, string>* output);
-};"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD2(Bar,\n'
-        'int(const vector<int>& v, map<int, string>* output));',
-        self.GenerateMethodSource(source))
-
-  def testReturnTypeWithOneTemplateArg(self):
-    source = """
-class Foo {
- public:
-  virtual vector<int>* Bar(int n);
-};"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD1(Bar,\nvector<int>*(int n));',
-        self.GenerateMethodSource(source))
-
-  def testReturnTypeWithManyTemplateArgs(self):
-    source = """
-class Foo {
- public:
-  virtual map<int, string> Bar();
-};"""
-    # Comparing the comment text is brittle - we'll think of something
-    # better in case this gets annoying, but for now let's keep it simple.
-    self.assertEqualIgnoreLeadingWhitespace(
-        '// The following line won\'t really compile, as the return\n'
-        '// type has multiple template arguments.  To fix it, use a\n'
-        '// typedef for the return type.\n'
-        'MOCK_METHOD0(Bar,\nmap<int, string>());',
-        self.GenerateMethodSource(source))
-
-  def testSimpleMethodInTemplatedClass(self):
-    source = """
-template<class T>
-class Foo {
- public:
-  virtual int Bar();
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD0_T(Bar,\nint());',
-        self.GenerateMethodSource(source))
-
-  def testPointerArgWithoutNames(self):
-    source = """
-class Foo {
-  virtual int Bar(C*);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD1(Bar,\nint(C*));',
-        self.GenerateMethodSource(source))
-
-  def testReferenceArgWithoutNames(self):
-    source = """
-class Foo {
-  virtual int Bar(C&);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD1(Bar,\nint(C&));',
-        self.GenerateMethodSource(source))
-
-  def testArrayArgWithoutNames(self):
-    source = """
-class Foo {
-  virtual int Bar(C[]);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD1(Bar,\nint(C[]));',
-        self.GenerateMethodSource(source))
-
-
-class GenerateMocksTest(TestCase):
-
-  def GenerateMocks(self, cpp_source):
-    """Convert C++ source to complete Google Mock output source."""
-    # <test> is a pseudo-filename, it is not read or written.
-    filename = '<test>'
-    builder = ast.BuilderFromSource(cpp_source, filename)
-    ast_list = list(builder.Generate())
-    lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
-    return '\n'.join(lines)
-
-  def testNamespaces(self):
-    source = """
-namespace Foo {
-namespace Bar { class Forward; }
-namespace Baz {
-
-class Test {
- public:
-  virtual void Foo();
-};
-
-}  // namespace Baz
-}  // namespace Foo
-"""
-    expected = """\
-namespace Foo {
-namespace Baz {
-
-class MockTest : public Test {
-public:
-MOCK_METHOD0(Foo,
-void());
-};
-
-}  // namespace Baz
-}  // namespace Foo
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        expected, self.GenerateMocks(source))
-
-  def testClassWithStorageSpecifierMacro(self):
-    source = """
-class STORAGE_SPECIFIER Test {
- public:
-  virtual void Foo();
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD0(Foo,
-void());
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        expected, self.GenerateMocks(source))
-
-  def testTemplatedForwardDeclaration(self):
-    source = """
-template <class T> class Forward;  // Forward declaration should be ignored.
-class Test {
- public:
-  virtual void Foo();
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD0(Foo,
-void());
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        expected, self.GenerateMocks(source))
-
-  def testTemplatedClass(self):
-    source = """
-template <typename S, typename T>
-class Test {
- public:
-  virtual void Foo();
-};
-"""
-    expected = """\
-template <typename T0, typename T1>
-class MockTest : public Test<T0, T1> {
-public:
-MOCK_METHOD0_T(Foo,
-void());
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        expected, self.GenerateMocks(source))
-
-  def testTemplateInATemplateTypedef(self):
-    source = """
-class Test {
- public:
-  typedef std::vector<std::list<int>> FooType;
-  virtual void Bar(const FooType& test_arg);
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD1(Bar,
-void(const FooType& test_arg));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        expected, self.GenerateMocks(source))
-
-  def testTemplateInATemplateTypedefWithComma(self):
-    source = """
-class Test {
- public:
-  typedef std::function<void(
-      const vector<std::list<int>>&, int> FooType;
-  virtual void Bar(const FooType& test_arg);
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD1(Bar,
-void(const FooType& test_arg));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        expected, self.GenerateMocks(source))
-
-if __name__ == '__main__':
-  unittest.main()
diff --git a/testing/gmock/scripts/generator/cpp/keywords.py b/testing/gmock/scripts/generator/cpp/keywords.py
deleted file mode 100755
index f694450..0000000
--- a/testing/gmock/scripts/generator/cpp/keywords.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""C++ keywords and helper utilities for determining keywords."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-try:
-    # Python 3.x
-    import builtins
-except ImportError:
-    # Python 2.x
-    import __builtin__ as builtins
-
-
-if not hasattr(builtins, 'set'):
-    # Nominal support for Python 2.3.
-    from sets import Set as set
-
-
-TYPES = set('bool char int long short double float void wchar_t unsigned signed'.split())
-TYPE_MODIFIERS = set('auto register const inline extern static virtual volatile mutable'.split())
-ACCESS = set('public protected private friend'.split())
-
-CASTS = set('static_cast const_cast dynamic_cast reinterpret_cast'.split())
-
-OTHERS = set('true false asm class namespace using explicit this operator sizeof'.split())
-OTHER_TYPES = set('new delete typedef struct union enum typeid typename template'.split())
-
-CONTROL = set('case switch default if else return goto'.split())
-EXCEPTION = set('try catch throw'.split())
-LOOP = set('while do for break continue'.split())
-
-ALL = TYPES | TYPE_MODIFIERS | ACCESS | CASTS | OTHERS | OTHER_TYPES | CONTROL | EXCEPTION | LOOP
-
-
-def IsKeyword(token):
-    return token in ALL
-
-def IsBuiltinType(token):
-    if token in ('virtual', 'inline'):
-        # These only apply to methods, they can't be types by themselves.
-        return False
-    return token in TYPES or token in TYPE_MODIFIERS
diff --git a/testing/gmock/scripts/generator/cpp/tokenize.py b/testing/gmock/scripts/generator/cpp/tokenize.py
deleted file mode 100755
index 359d556..0000000
--- a/testing/gmock/scripts/generator/cpp/tokenize.py
+++ /dev/null
@@ -1,287 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Tokenize C++ source code."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-try:
-    # Python 3.x
-    import builtins
-except ImportError:
-    # Python 2.x
-    import __builtin__ as builtins
-
-
-import sys
-
-from cpp import utils
-
-
-if not hasattr(builtins, 'set'):
-    # Nominal support for Python 2.3.
-    from sets import Set as set
-
-
-# Add $ as a valid identifier char since so much code uses it.
-_letters = 'abcdefghijklmnopqrstuvwxyz'
-VALID_IDENTIFIER_CHARS = set(_letters + _letters.upper() + '_0123456789$')
-HEX_DIGITS = set('0123456789abcdefABCDEF')
-INT_OR_FLOAT_DIGITS = set('01234567890eE-+')
-
-
-# C++0x string preffixes.
-_STR_PREFIXES = set(('R', 'u8', 'u8R', 'u', 'uR', 'U', 'UR', 'L', 'LR'))
-
-
-# Token types.
-UNKNOWN = 'UNKNOWN'
-SYNTAX = 'SYNTAX'
-CONSTANT = 'CONSTANT'
-NAME = 'NAME'
-PREPROCESSOR = 'PREPROCESSOR'
-
-# Where the token originated from.  This can be used for backtracking.
-# It is always set to WHENCE_STREAM in this code.
-WHENCE_STREAM, WHENCE_QUEUE = range(2)
-
-
-class Token(object):
-    """Data container to represent a C++ token.
-
-    Tokens can be identifiers, syntax char(s), constants, or
-    pre-processor directives.
-
-    start contains the index of the first char of the token in the source
-    end contains the index of the last char of the token in the source
-    """
-
-    def __init__(self, token_type, name, start, end):
-        self.token_type = token_type
-        self.name = name
-        self.start = start
-        self.end = end
-        self.whence = WHENCE_STREAM
-
-    def __str__(self):
-        if not utils.DEBUG:
-            return 'Token(%r)' % self.name
-        return 'Token(%r, %s, %s)' % (self.name, self.start, self.end)
-
-    __repr__ = __str__
-
-
-def _GetString(source, start, i):
-    i = source.find('"', i+1)
-    while source[i-1] == '\\':
-        # Count the trailing backslashes.
-        backslash_count = 1
-        j = i - 2
-        while source[j] == '\\':
-            backslash_count += 1
-            j -= 1
-        # When trailing backslashes are even, they escape each other.
-        if (backslash_count % 2) == 0:
-            break
-        i = source.find('"', i+1)
-    return i + 1
-
-
-def _GetChar(source, start, i):
-    # NOTE(nnorwitz): may not be quite correct, should be good enough.
-    i = source.find("'", i+1)
-    while source[i-1] == '\\':
-        # Need to special case '\\'.
-        if (i - 2) > start and source[i-2] == '\\':
-            break
-        i = source.find("'", i+1)
-    # Try to handle unterminated single quotes (in a #if 0 block).
-    if i < 0:
-        i = start
-    return i + 1
-
-
-def GetTokens(source):
-    """Returns a sequence of Tokens.
-
-    Args:
-      source: string of C++ source code.
-
-    Yields:
-      Token that represents the next token in the source.
-    """
-    # Cache various valid character sets for speed.
-    valid_identifier_chars = VALID_IDENTIFIER_CHARS
-    hex_digits = HEX_DIGITS
-    int_or_float_digits = INT_OR_FLOAT_DIGITS
-    int_or_float_digits2 = int_or_float_digits | set('.')
-
-    # Only ignore errors while in a #if 0 block.
-    ignore_errors = False
-    count_ifs = 0
-
-    i = 0
-    end = len(source)
-    while i < end:
-        # Skip whitespace.
-        while i < end and source[i].isspace():
-            i += 1
-        if i >= end:
-            return
-
-        token_type = UNKNOWN
-        start = i
-        c = source[i]
-        if c.isalpha() or c == '_':              # Find a string token.
-            token_type = NAME
-            while source[i] in valid_identifier_chars:
-                i += 1
-            # String and character constants can look like a name if
-            # they are something like L"".
-            if (source[i] == "'" and (i - start) == 1 and
-                source[start:i] in 'uUL'):
-                # u, U, and L are valid C++0x character preffixes.
-                token_type = CONSTANT
-                i = _GetChar(source, start, i)
-            elif source[i] == "'" and source[start:i] in _STR_PREFIXES:
-                token_type = CONSTANT
-                i = _GetString(source, start, i)
-        elif c == '/' and source[i+1] == '/':    # Find // comments.
-            i = source.find('\n', i)
-            if i == -1:  # Handle EOF.
-                i = end
-            continue
-        elif c == '/' and source[i+1] == '*':    # Find /* comments. */
-            i = source.find('*/', i) + 2
-            continue
-        elif c in ':+-<>&|*=':                   # : or :: (plus other chars).
-            token_type = SYNTAX
-            i += 1
-            new_ch = source[i]
-            if new_ch == c and c != '>':         # Treat ">>" as two tokens.
-                i += 1
-            elif c == '-' and new_ch == '>':
-                i += 1
-            elif new_ch == '=':
-                i += 1
-        elif c in '()[]{}~!?^%;/.,':             # Handle single char tokens.
-            token_type = SYNTAX
-            i += 1
-            if c == '.' and source[i].isdigit():
-                token_type = CONSTANT
-                i += 1
-                while source[i] in int_or_float_digits:
-                    i += 1
-                # Handle float suffixes.
-                for suffix in ('l', 'f'):
-                    if suffix == source[i:i+1].lower():
-                        i += 1
-                        break
-        elif c.isdigit():                        # Find integer.
-            token_type = CONSTANT
-            if c == '0' and source[i+1] in 'xX':
-                # Handle hex digits.
-                i += 2
-                while source[i] in hex_digits:
-                    i += 1
-            else:
-                while source[i] in int_or_float_digits2:
-                    i += 1
-            # Handle integer (and float) suffixes.
-            for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'):
-                size = len(suffix)
-                if suffix == source[i:i+size].lower():
-                    i += size
-                    break
-        elif c == '"':                           # Find string.
-            token_type = CONSTANT
-            i = _GetString(source, start, i)
-        elif c == "'":                           # Find char.
-            token_type = CONSTANT
-            i = _GetChar(source, start, i)
-        elif c == '#':                           # Find pre-processor command.
-            token_type = PREPROCESSOR
-            got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace()
-            if got_if:
-                count_ifs += 1
-            elif source[i:i+6] == '#endif':
-                count_ifs -= 1
-                if count_ifs == 0:
-                    ignore_errors = False
-
-            # TODO(nnorwitz): handle preprocessor statements (\ continuations).
-            while 1:
-                i1 = source.find('\n', i)
-                i2 = source.find('//', i)
-                i3 = source.find('/*', i)
-                i4 = source.find('"', i)
-                # NOTE(nnorwitz): doesn't handle comments in #define macros.
-                # Get the first important symbol (newline, comment, EOF/end).
-                i = min([x for x in (i1, i2, i3, i4, end) if x != -1])
-
-                # Handle #include "dir//foo.h" properly.
-                if source[i] == '"':
-                    i = source.find('"', i+1) + 1
-                    assert i > 0
-                    continue
-                # Keep going if end of the line and the line ends with \.
-                if not (i == i1 and source[i-1] == '\\'):
-                    if got_if:
-                        condition = source[start+4:i].lstrip()
-                        if (condition.startswith('0') or
-                            condition.startswith('(0)')):
-                            ignore_errors = True
-                    break
-                i += 1
-        elif c == '\\':                          # Handle \ in code.
-            # This is different from the pre-processor \ handling.
-            i += 1
-            continue
-        elif ignore_errors:
-            # The tokenizer seems to be in pretty good shape.  This
-            # raise is conditionally disabled so that bogus code
-            # in an #if 0 block can be handled.  Since we will ignore
-            # it anyways, this is probably fine.  So disable the
-            # exception and  return the bogus char.
-            i += 1
-        else:
-            sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' %
-                             ('?', i, c, source[i-10:i+10]))
-            raise RuntimeError('unexpected token')
-
-        if i <= 0:
-            print('Invalid index, exiting now.')
-            return
-        yield Token(token_type, source[start:i], start, i)
-
-
-if __name__ == '__main__':
-    def main(argv):
-        """Driver mostly for testing purposes."""
-        for filename in argv[1:]:
-            source = utils.ReadFile(filename)
-            if source is None:
-                continue
-
-            for token in GetTokens(source):
-                print('%-12s: %s' % (token.token_type, token.name))
-                # print('\r%6.2f%%' % (100.0 * index / token.end),)
-            sys.stdout.write('\n')
-
-
-    main(sys.argv)
diff --git a/testing/gmock/scripts/generator/cpp/utils.py b/testing/gmock/scripts/generator/cpp/utils.py
deleted file mode 100755
index eab36ee..0000000
--- a/testing/gmock/scripts/generator/cpp/utils.py
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generic utilities for C++ parsing."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-
-import sys
-
-
-# Set to True to see the start/end token indices.
-DEBUG = True
-
-
-def ReadFile(filename, print_error=True):
-    """Returns the contents of a file."""
-    try:
-        fp = open(filename)
-        try:
-            return fp.read()
-        finally:
-            fp.close()
-    except IOError:
-        if print_error:
-            print('Error reading %s: %s' % (filename, sys.exc_info()[1]))
-        return None
diff --git a/testing/gmock/scripts/generator/gmock_gen.py b/testing/gmock/scripts/generator/gmock_gen.py
deleted file mode 100755
index 8cc0d13..0000000
--- a/testing/gmock/scripts/generator/gmock_gen.py
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Driver for starting up Google Mock class generator."""
-
-__author__ = 'nnorwitz@google.com (Neal Norwitz)'
-
-import os
-import sys
-
-if __name__ == '__main__':
-  # Add the directory of this script to the path so we can import gmock_class.
-  sys.path.append(os.path.dirname(__file__))
-
-  from cpp import gmock_class
-  # Fix the docstring in case they require the usage.
-  gmock_class.__doc__ = gmock_class.__doc__.replace('gmock_class.py', __file__)
-  gmock_class.main()
diff --git a/testing/gmock/scripts/gmock-config.in b/testing/gmock/scripts/gmock-config.in
deleted file mode 100755
index 2baefe9..0000000
--- a/testing/gmock/scripts/gmock-config.in
+++ /dev/null
@@ -1,303 +0,0 @@
-#!/bin/sh
-
-# These variables are automatically filled in by the configure script.
-name="@PACKAGE_TARNAME@"
-version="@PACKAGE_VERSION@"
-
-show_usage()
-{
-  echo "Usage: gmock-config [OPTIONS...]"
-}
-
-show_help()
-{
-  show_usage
-  cat <<\EOF
-
-The `gmock-config' script provides access to the necessary compile and linking
-flags to connect with Google C++ Mocking Framework, both in a build prior to
-installation, and on the system proper after installation. The installation
-overrides may be issued in combination with any other queries, but will only
-affect installation queries if called on a built but not installed gmock. The
-installation queries may not be issued with any other types of queries, and
-only one installation query may be made at a time. The version queries and
-compiler flag queries may be combined as desired but not mixed. Different
-version queries are always combined with logical "and" semantics, and only the
-last of any particular query is used while all previous ones ignored. All
-versions must be specified as a sequence of numbers separated by periods.
-Compiler flag queries output the union of the sets of flags when combined.
-
- Examples:
-  gmock-config --min-version=1.0 || echo "Insufficient Google Mock version."
-
-  g++ $(gmock-config --cppflags --cxxflags) -o foo.o -c foo.cpp
-  g++ $(gmock-config --ldflags --libs) -o foo foo.o
-
-  # When using a built but not installed Google Mock:
-  g++ $(../../my_gmock_build/scripts/gmock-config ...) ...
-
-  # When using an installed Google Mock, but with installation overrides:
-  export GMOCK_PREFIX="/opt"
-  g++ $(gmock-config --libdir="/opt/lib64" ...) ...
-
- Help:
-  --usage                    brief usage information
-  --help                     display this help message
-
- Installation Overrides:
-  --prefix=<dir>             overrides the installation prefix
-  --exec-prefix=<dir>        overrides the executable installation prefix
-  --libdir=<dir>             overrides the library installation prefix
-  --includedir=<dir>         overrides the header file installation prefix
-
- Installation Queries:
-  --prefix                   installation prefix
-  --exec-prefix              executable installation prefix
-  --libdir                   library installation directory
-  --includedir               header file installation directory
-  --version                  the version of the Google Mock installation
-
- Version Queries:
-  --min-version=VERSION      return 0 if the version is at least VERSION
-  --exact-version=VERSION    return 0 if the version is exactly VERSION
-  --max-version=VERSION      return 0 if the version is at most VERSION
-
- Compilation Flag Queries:
-  --cppflags                 compile flags specific to the C-like preprocessors
-  --cxxflags                 compile flags appropriate for C++ programs
-  --ldflags                  linker flags
-  --libs                     libraries for linking
-
-EOF
-}
-
-# This function bounds our version with a min and a max. It uses some clever
-# POSIX-compliant variable expansion to portably do all the work in the shell
-# and avoid any dependency on a particular "sed" or "awk" implementation.
-# Notable is that it will only ever compare the first 3 components of versions.
-# Further components will be cleanly stripped off. All versions must be
-# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and
-# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should
-# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than
-# continuing to maintain our own shell version.
-check_versions()
-{
-  major_version=${version%%.*}
-  minor_version="0"
-  point_version="0"
-  if test "${version#*.}" != "${version}"; then
-    minor_version=${version#*.}
-    minor_version=${minor_version%%.*}
-  fi
-  if test "${version#*.*.}" != "${version}"; then
-    point_version=${version#*.*.}
-    point_version=${point_version%%.*}
-  fi
-
-  min_version="$1"
-  min_major_version=${min_version%%.*}
-  min_minor_version="0"
-  min_point_version="0"
-  if test "${min_version#*.}" != "${min_version}"; then
-    min_minor_version=${min_version#*.}
-    min_minor_version=${min_minor_version%%.*}
-  fi
-  if test "${min_version#*.*.}" != "${min_version}"; then
-    min_point_version=${min_version#*.*.}
-    min_point_version=${min_point_version%%.*}
-  fi
-
-  max_version="$2"
-  max_major_version=${max_version%%.*}
-  max_minor_version="0"
-  max_point_version="0"
-  if test "${max_version#*.}" != "${max_version}"; then
-    max_minor_version=${max_version#*.}
-    max_minor_version=${max_minor_version%%.*}
-  fi
-  if test "${max_version#*.*.}" != "${max_version}"; then
-    max_point_version=${max_version#*.*.}
-    max_point_version=${max_point_version%%.*}
-  fi
-
-  test $(($major_version)) -lt $(($min_major_version)) && exit 1
-  if test $(($major_version)) -eq $(($min_major_version)); then
-    test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
-    if test $(($minor_version)) -eq $(($min_minor_version)); then
-      test $(($point_version)) -lt $(($min_point_version)) && exit 1
-    fi
-  fi
-
-  test $(($major_version)) -gt $(($max_major_version)) && exit 1
-  if test $(($major_version)) -eq $(($max_major_version)); then
-    test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
-    if test $(($minor_version)) -eq $(($max_minor_version)); then
-      test $(($point_version)) -gt $(($max_point_version)) && exit 1
-    fi
-  fi
-
-  exit 0
-}
-
-# Show the usage line when no arguments are specified.
-if test $# -eq 0; then
-  show_usage
-  exit 1
-fi
-
-while test $# -gt 0; do
-  case $1 in
-    --usage)          show_usage;         exit 0;;
-    --help)           show_help;          exit 0;;
-
-    # Installation overrides
-    --prefix=*)       GMOCK_PREFIX=${1#--prefix=};;
-    --exec-prefix=*)  GMOCK_EXEC_PREFIX=${1#--exec-prefix=};;
-    --libdir=*)       GMOCK_LIBDIR=${1#--libdir=};;
-    --includedir=*)   GMOCK_INCLUDEDIR=${1#--includedir=};;
-
-    # Installation queries
-    --prefix|--exec-prefix|--libdir|--includedir|--version)
-      if test -n "${do_query}"; then
-        show_usage
-        exit 1
-      fi
-      do_query=${1#--}
-      ;;
-
-    # Version checking
-    --min-version=*)
-      do_check_versions=yes
-      min_version=${1#--min-version=}
-      ;;
-    --max-version=*)
-      do_check_versions=yes
-      max_version=${1#--max-version=}
-      ;;
-    --exact-version=*)
-      do_check_versions=yes
-      exact_version=${1#--exact-version=}
-      ;;
-
-    # Compiler flag output
-    --cppflags)       echo_cppflags=yes;;
-    --cxxflags)       echo_cxxflags=yes;;
-    --ldflags)        echo_ldflags=yes;;
-    --libs)           echo_libs=yes;;
-
-    # Everything else is an error
-    *)                show_usage;         exit 1;;
-  esac
-  shift
-done
-
-# These have defaults filled in by the configure script but can also be
-# overridden by environment variables or command line parameters.
-prefix="${GMOCK_PREFIX:-@prefix@}"
-exec_prefix="${GMOCK_EXEC_PREFIX:-@exec_prefix@}"
-libdir="${GMOCK_LIBDIR:-@libdir@}"
-includedir="${GMOCK_INCLUDEDIR:-@includedir@}"
-
-# We try and detect if our binary is not located at its installed location. If
-# it's not, we provide variables pointing to the source and build tree rather
-# than to the install tree. We also locate Google Test using the configured
-# gtest-config script rather than searching the PATH and our bindir for one.
-# This allows building against a just-built gmock rather than an installed
-# gmock.
-bindir="@bindir@"
-this_relative_bindir=`dirname $0`
-this_bindir=`cd ${this_relative_bindir}; pwd -P`
-if test "${this_bindir}" = "${this_bindir%${bindir}}"; then
-  # The path to the script doesn't end in the bindir sequence from Autoconf,
-  # assume that we are in a build tree.
-  build_dir=`dirname ${this_bindir}`
-  src_dir=`cd ${this_bindir}/@top_srcdir@; pwd -P`
-
-  # TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
-  # should work to remove it, and/or remove libtool altogether, replacing it
-  # with direct references to the library and a link path.
-  gmock_libs="${build_dir}/lib/libgmock.la"
-  gmock_ldflags=""
-
-  # We provide hooks to include from either the source or build dir, where the
-  # build dir is always preferred. This will potentially allow us to write
-  # build rules for generated headers and have them automatically be preferred
-  # over provided versions.
-  gmock_cppflags="-I${build_dir}/include -I${src_dir}/include"
-  gmock_cxxflags=""
-
-  # Directly invoke the gtest-config script used during the build process.
-  gtest_config="@GTEST_CONFIG@"
-else
-  # We're using an installed gmock, although it may be staged under some
-  # prefix. Assume (as our own libraries do) that we can resolve the prefix,
-  # and are present in the dynamic link paths.
-  gmock_ldflags="-L${libdir}"
-  gmock_libs="-l${name}"
-  gmock_cppflags="-I${includedir}"
-  gmock_cxxflags=""
-
-  # We also prefer any gtest-config script installed in our prefix. Lacking
-  # one, we look in the PATH for one.
-  gtest_config="${bindir}/gtest-config"
-  if test ! -x "${gtest_config}"; then
-    gtest_config=`which gtest-config`
-  fi
-fi
-
-# Ensure that we have located a Google Test to link against.
-if ! test -x "${gtest_config}"; then
-  echo "Unable to locate Google Test, check your Google Mock configuration" \
-       "and installation" >&2
-  exit 1
-elif ! "${gtest_config}" "--exact-version=@GTEST_VERSION@"; then
-  echo "The Google Test found is not the same version as Google Mock was " \
-       "built against" >&2
-  exit 1
-fi
-
-# Add the necessary Google Test bits into the various flag variables
-gmock_cppflags="${gmock_cppflags} `${gtest_config} --cppflags`"
-gmock_cxxflags="${gmock_cxxflags} `${gtest_config} --cxxflags`"
-gmock_ldflags="${gmock_ldflags} `${gtest_config} --ldflags`"
-gmock_libs="${gmock_libs} `${gtest_config} --libs`"
-
-# Do an installation query if requested.
-if test -n "$do_query"; then
-  case $do_query in
-    prefix)           echo $prefix;       exit 0;;
-    exec-prefix)      echo $exec_prefix;  exit 0;;
-    libdir)           echo $libdir;       exit 0;;
-    includedir)       echo $includedir;   exit 0;;
-    version)          echo $version;      exit 0;;
-    *)                show_usage;         exit 1;;
-  esac
-fi
-
-# Do a version check if requested.
-if test "$do_check_versions" = "yes"; then
-  # Make sure we didn't receive a bad combination of parameters.
-  test "$echo_cppflags" = "yes" && show_usage && exit 1
-  test "$echo_cxxflags" = "yes" && show_usage && exit 1
-  test "$echo_ldflags" = "yes"  && show_usage && exit 1
-  test "$echo_libs" = "yes"     && show_usage && exit 1
-
-  if test "$exact_version" != ""; then
-    check_versions $exact_version $exact_version
-    # unreachable
-  else
-    check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
-    # unreachable
-  fi
-fi
-
-# Do the output in the correct order so that these can be used in-line of
-# a compiler invocation.
-output=""
-test "$echo_cppflags" = "yes" && output="$output $gmock_cppflags"
-test "$echo_cxxflags" = "yes" && output="$output $gmock_cxxflags"
-test "$echo_ldflags" = "yes"  && output="$output $gmock_ldflags"
-test "$echo_libs" = "yes"     && output="$output $gmock_libs"
-echo $output
-
-exit 0
diff --git a/testing/gmock/scripts/gmock_doctor.py b/testing/gmock/scripts/gmock_doctor.py
deleted file mode 100755
index 9ac4653..0000000
--- a/testing/gmock/scripts/gmock_doctor.py
+++ /dev/null
@@ -1,640 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-#     * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#     * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-#     * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""Converts compiler's errors in code using Google Mock to plain English."""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import re
-import sys
-
-_VERSION = '1.0.3'
-
-_EMAIL = 'googlemock@googlegroups.com'
-
-_COMMON_GMOCK_SYMBOLS = [
-    # Matchers
-    '_',
-    'A',
-    'AddressSatisfies',
-    'AllOf',
-    'An',
-    'AnyOf',
-    'ContainerEq',
-    'Contains',
-    'ContainsRegex',
-    'DoubleEq',
-    'ElementsAre',
-    'ElementsAreArray',
-    'EndsWith',
-    'Eq',
-    'Field',
-    'FloatEq',
-    'Ge',
-    'Gt',
-    'HasSubstr',
-    'IsInitializedProto',
-    'Le',
-    'Lt',
-    'MatcherCast',
-    'Matches',
-    'MatchesRegex',
-    'NanSensitiveDoubleEq',
-    'NanSensitiveFloatEq',
-    'Ne',
-    'Not',
-    'NotNull',
-    'Pointee',
-    'Property',
-    'Ref',
-    'ResultOf',
-    'SafeMatcherCast',
-    'StartsWith',
-    'StrCaseEq',
-    'StrCaseNe',
-    'StrEq',
-    'StrNe',
-    'Truly',
-    'TypedEq',
-    'Value',
-
-    # Actions
-    'Assign',
-    'ByRef',
-    'DeleteArg',
-    'DoAll',
-    'DoDefault',
-    'IgnoreResult',
-    'Invoke',
-    'InvokeArgument',
-    'InvokeWithoutArgs',
-    'Return',
-    'ReturnNew',
-    'ReturnNull',
-    'ReturnRef',
-    'SaveArg',
-    'SetArgReferee',
-    'SetArgPointee',
-    'SetArgumentPointee',
-    'SetArrayArgument',
-    'SetErrnoAndReturn',
-    'Throw',
-    'WithArg',
-    'WithArgs',
-    'WithoutArgs',
-
-    # Cardinalities
-    'AnyNumber',
-    'AtLeast',
-    'AtMost',
-    'Between',
-    'Exactly',
-
-    # Sequences
-    'InSequence',
-    'Sequence',
-
-    # Misc
-    'DefaultValue',
-    'Mock',
-    ]
-
-# Regex for matching source file path and line number in the compiler's errors.
-_GCC_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(\d+:)?\s+'
-_CLANG_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(?P<column>\d+):\s+'
-_CLANG_NON_GMOCK_FILE_LINE_RE = (
-    r'(?P<file>.*[/\\^](?!gmock-)[^/\\]+):(?P<line>\d+):(?P<column>\d+):\s+')
-
-
-def _FindAllMatches(regex, s):
-  """Generates all matches of regex in string s."""
-
-  r = re.compile(regex)
-  return r.finditer(s)
-
-
-def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
-  """Diagnoses the given disease by pattern matching.
-
-  Can provide different diagnoses for different patterns.
-
-  Args:
-    short_name: Short name of the disease.
-    long_name:  Long name of the disease.
-    diagnoses:  A list of pairs (regex, pattern for formatting the diagnosis
-                for matching regex).
-    msg:        Compiler's error messages.
-  Yields:
-    Tuples of the form
-      (short name of disease, long name of disease, diagnosis).
-  """
-  for regex, diagnosis in diagnoses:
-    if re.search(regex, msg):
-      diagnosis = '%(file)s:%(line)s:' + diagnosis
-      for m in _FindAllMatches(regex, msg):
-        yield (short_name, long_name, diagnosis % m.groupdict())
-
-
-def _NeedToReturnReferenceDiagnoser(msg):
-  """Diagnoses the NRR disease, given the error messages by the compiler."""
-
-  gcc_regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
-               + _GCC_FILE_LINE_RE + r'instantiated from here\n'
-               r'.*gmock-actions\.h.*error: creating array with negative size')
-  clang_regex = (r'error:.*array.*negative.*\r?\n'
-                 r'(.*\n)*?' +
-                 _CLANG_NON_GMOCK_FILE_LINE_RE +
-                 r'note: in instantiation of function template specialization '
-                 r'\'testing::internal::ReturnAction<(?P<type>.*)>'
-                 r'::operator Action<.*>\' requested here')
-  clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*'
-                r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE)
-
-  diagnosis = """
-You are using a Return() action in a function that returns a reference to
-%(type)s.  Please use ReturnRef() instead."""
-  return _GenericDiagnoser('NRR', 'Need to Return Reference',
-                           [(clang_regex, diagnosis),
-                            (clang11_re, diagnosis % {'type': 'a type'}),
-                            (gcc_regex, diagnosis % {'type': 'a type'})],
-                           msg)
-
-
-def _NeedToReturnSomethingDiagnoser(msg):
-  """Diagnoses the NRS disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
-               r'*gmock.*actions\.h.*error: void value not ignored)'
-               r'|(error: control reaches end of non-void function)')
-  clang_regex1 = (_CLANG_FILE_LINE_RE +
-                  r'error: cannot initialize return object '
-                  r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
-                  r'with an rvalue of type \'void\'')
-  clang_regex2 = (_CLANG_FILE_LINE_RE +
-                  r'error: cannot initialize return object '
-                  r'of type \'(?P<return_type>.*)\' '
-                  r'with an rvalue of type \'void\'')
-  diagnosis = """
-You are using an action that returns void, but it needs to return
-%(return_type)s.  Please tell it *what* to return.  Perhaps you can use
-the pattern DoAll(some_action, Return(some_value))?"""
-  return _GenericDiagnoser(
-      'NRS',
-      'Need to Return Something',
-      [(gcc_regex, diagnosis % {'return_type': '*something*'}),
-       (clang_regex1, diagnosis),
-       (clang_regex2, diagnosis)],
-      msg)
-
-
-def _NeedToReturnNothingDiagnoser(msg):
-  """Diagnoses the NRN disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
-               r'.*gmock-actions\.h.*error: instantiation of '
-               r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
-               r'as type \'void\'')
-  clang_regex1 = (r'error: field has incomplete type '
-                  r'\'Result\' \(aka \'void\'\)(\r)?\n'
-                  r'(.*\n)*?' +
-                  _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
-                  r'of function template specialization '
-                  r'\'testing::internal::ReturnAction<(?P<return_type>.*)>'
-                  r'::operator Action<void \(.*\)>\' requested here')
-  clang_regex2 = (r'error: field has incomplete type '
-                  r'\'Result\' \(aka \'void\'\)(\r)?\n'
-                  r'(.*\n)*?' +
-                  _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
-                  r'of function template specialization '
-                  r'\'testing::internal::DoBothAction<.*>'
-                  r'::operator Action<(?P<return_type>.*) \(.*\)>\' '
-                  r'requested here')
-  diagnosis = """
-You are using an action that returns %(return_type)s, but it needs to return
-void.  Please use a void-returning action instead.
-
-All actions but the last in DoAll(...) must return void.  Perhaps you need
-to re-arrange the order of actions in a DoAll(), if you are using one?"""
-  return _GenericDiagnoser(
-      'NRN',
-      'Need to Return Nothing',
-      [(gcc_regex, diagnosis % {'return_type': '*something*'}),
-       (clang_regex1, diagnosis),
-       (clang_regex2, diagnosis)],
-      msg)
-
-
-def _IncompleteByReferenceArgumentDiagnoser(msg):
-  """Diagnoses the IBRA disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
-               r'.*gtest-printers\.h.*error: invalid application of '
-               r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
-
-  clang_regex = (r'.*gtest-printers\.h.*error: invalid application of '
-                 r'\'sizeof\' to an incomplete type '
-                 r'\'(?P<type>.*)( const)?\'\r?\n'
-                 r'(.*\n)*?' +
-                 _CLANG_NON_GMOCK_FILE_LINE_RE +
-                 r'note: in instantiation of member function '
-                 r'\'testing::internal2::TypeWithoutFormatter<.*>::'
-                 r'PrintValue\' requested here')
-  diagnosis = """
-In order to mock this function, Google Mock needs to see the definition
-of type "%(type)s" - declaration alone is not enough.  Either #include
-the header that defines it, or change the argument to be passed
-by pointer."""
-
-  return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
-                           [(gcc_regex, diagnosis),
-                            (clang_regex, diagnosis)],
-                           msg)
-
-
-def _OverloadedFunctionMatcherDiagnoser(msg):
-  """Diagnoses the OFM disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
-               r'call to \'Truly\(<unresolved overloaded function type>\)')
-  clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for '
-                 r'call to \'Truly')
-  diagnosis = """
-The argument you gave to Truly() is an overloaded function.  Please tell
-your compiler which overloaded version you want to use.
-
-For example, if you want to use the version whose signature is
-  bool Foo(int n);
-you should write
-  Truly(static_cast<bool (*)(int n)>(Foo))"""
-  return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
-                           [(gcc_regex, diagnosis),
-                            (clang_regex, diagnosis)],
-                           msg)
-
-
-def _OverloadedFunctionActionDiagnoser(msg):
-  """Diagnoses the OFA disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to '
-               r'\'Invoke\(<unresolved overloaded function type>')
-  clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching '
-                 r'function for call to \'Invoke\'\r?\n'
-                 r'(.*\n)*?'
-                 r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+'
-                 r'note: candidate template ignored:\s+'
-                 r'couldn\'t infer template argument \'FunctionImpl\'')
-  diagnosis = """
-Function you are passing to Invoke is overloaded.  Please tell your compiler
-which overloaded version you want to use.
-
-For example, if you want to use the version whose signature is
-  bool MyFunction(int n, double x);
-you should write something like
-  Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
-  return _GenericDiagnoser('OFA', 'Overloaded Function Action',
-                           [(gcc_regex, diagnosis),
-                            (clang_regex, diagnosis)],
-                           msg)
-
-
-def _OverloadedMethodActionDiagnoser(msg):
-  """Diagnoses the OMA disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
-               r'call to \'Invoke\(.+, <unresolved overloaded function '
-               r'type>\)')
-  clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
-                 r'for call to \'Invoke\'\r?\n'
-                 r'(.*\n)*?'
-                 r'.*\bgmock-generated-actions\.h:\d+:\d+: '
-                 r'note: candidate function template not viable: '
-                 r'requires .*, but 2 (arguments )?were provided')
-  diagnosis = """
-The second argument you gave to Invoke() is an overloaded method.  Please
-tell your compiler which overloaded version you want to use.
-
-For example, if you want to use the version whose signature is
-  class Foo {
-    ...
-    bool Bar(int n, double x);
-  };
-you should write something like
-  Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
-  return _GenericDiagnoser('OMA', 'Overloaded Method Action',
-                           [(gcc_regex, diagnosis),
-                            (clang_regex, diagnosis)],
-                           msg)
-
-
-def _MockObjectPointerDiagnoser(msg):
-  """Diagnoses the MOP disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member '
-               r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
-               r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
-  clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type '
-                 r'\'(?P<class_name>.*?) *\' is a pointer; '
-                 r'(did you mean|maybe you meant) to use \'->\'\?')
-  diagnosis = """
-The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
-not a *pointer* to it.  Please write '*(%(mock_object)s)' instead of
-'%(mock_object)s' as your first argument.
-
-For example, given the mock class:
-
-  class %(class_name)s : public ... {
-    ...
-    MOCK_METHOD0(%(method)s, ...);
-  };
-
-and the following mock instance:
-
-  %(class_name)s* mock_ptr = ...
-
-you should use the EXPECT_CALL like this:
-
-  EXPECT_CALL(*mock_ptr, %(method)s(...));"""
-
-  return _GenericDiagnoser(
-      'MOP',
-      'Mock Object Pointer',
-      [(gcc_regex, diagnosis),
-       (clang_regex, diagnosis % {'mock_object': 'mock_object',
-                                  'method': 'method',
-                                  'class_name': '%(class_name)s'})],
-       msg)
-
-
-def _NeedToUseSymbolDiagnoser(msg):
-  """Diagnoses the NUS disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
-               r'(was not declared in this scope|has not been declared)')
-  clang_regex = (_CLANG_FILE_LINE_RE +
-                 r'error: (use of undeclared identifier|unknown type name|'
-                 r'no template named) \'(?P<symbol>[^\']+)\'')
-  diagnosis = """
-'%(symbol)s' is defined by Google Mock in the testing namespace.
-Did you forget to write
-  using testing::%(symbol)s;
-?"""
-  for m in (list(_FindAllMatches(gcc_regex, msg)) +
-            list(_FindAllMatches(clang_regex, msg))):
-    symbol = m.groupdict()['symbol']
-    if symbol in _COMMON_GMOCK_SYMBOLS:
-      yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
-
-
-def _NeedToUseReturnNullDiagnoser(msg):
-  """Diagnoses the NRNULL disease, given the error messages by the compiler."""
-
-  gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
-               '::operator testing::Action<Func>\(\) const.*\n' +
-               _GCC_FILE_LINE_RE + r'instantiated from here\n'
-               r'.*error: no matching function for call to \'ImplicitCast_\('
-               r'(:?long )?int&\)')
-  clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
-                 r'call to \'ImplicitCast_\'\r?\n'
-                 r'(.*\n)*?' +
-                 _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
-                 r'of function template specialization '
-                 r'\'testing::internal::ReturnAction<(int|long)>::operator '
-                 r'Action<(?P<type>.*)\(\)>\' requested here')
-  diagnosis = """
-You are probably calling Return(NULL) and the compiler isn't sure how to turn
-NULL into %(type)s. Use ReturnNull() instead.
-Note: the line number may be off; please fix all instances of Return(NULL)."""
-  return _GenericDiagnoser(
-      'NRNULL', 'Need to use ReturnNull',
-      [(clang_regex, diagnosis),
-       (gcc_regex, diagnosis % {'type': 'the right type'})],
-      msg)
-
-
-def _TypeInTemplatedBaseDiagnoser(msg):
-  """Diagnoses the TTB disease, given the error messages by the compiler."""
-
-  # This version works when the type is used as the mock function's return
-  # type.
-  gcc_4_3_1_regex_type_in_retval = (
-      r'In member function \'int .*\n' + _GCC_FILE_LINE_RE +
-      r'error: a function call cannot appear in a constant-expression')
-  gcc_4_4_0_regex_type_in_retval = (
-      r'error: a function call cannot appear in a constant-expression'
-      + _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n')
-  # This version works when the type is used as the mock function's sole
-  # parameter type.
-  gcc_regex_type_of_sole_param = (
-      _GCC_FILE_LINE_RE +
-      r'error: \'(?P<type>.+)\' was not declared in this scope\n'
-      r'.*error: template argument 1 is invalid\n')
-  # This version works when the type is used as a parameter of a mock
-  # function that has multiple parameters.
-  gcc_regex_type_of_a_param = (
-      r'error: expected `;\' before \'::\' token\n'
-      + _GCC_FILE_LINE_RE +
-      r'error: \'(?P<type>.+)\' was not declared in this scope\n'
-      r'.*error: template argument 1 is invalid\n'
-      r'.*error: \'.+\' was not declared in this scope')
-  clang_regex_type_of_retval_or_sole_param = (
-      _CLANG_FILE_LINE_RE +
-      r'error: use of undeclared identifier \'(?P<type>.*)\'\n'
-      r'(.*\n)*?'
-      r'(?P=file):(?P=line):\d+: error: '
-      r'non-friend class member \'Result\' cannot have a qualified name'
-      )
-  clang_regex_type_of_a_param = (
-      _CLANG_FILE_LINE_RE +
-      r'error: C\+\+ requires a type specifier for all declarations\n'
-      r'(.*\n)*?'
-      r'(?P=file):(?P=line):(?P=column): error: '
-      r'C\+\+ requires a type specifier for all declarations'
-      )
-  clang_regex_unknown_type = (
-      _CLANG_FILE_LINE_RE +
-      r'error: unknown type name \'(?P<type>[^\']+)\''
-      )
-
-  diagnosis = """
-In a mock class template, types or typedefs defined in the base class
-template are *not* automatically visible.  This is how C++ works.  Before
-you can use a type or typedef named %(type)s defined in base class Base<T>, you
-need to make it visible.  One way to do it is:
-
-  typedef typename Base<T>::%(type)s %(type)s;"""
-
-  for diag in _GenericDiagnoser(
-      'TTB', 'Type in Template Base',
-      [(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
-       (gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
-       (gcc_regex_type_of_sole_param, diagnosis),
-       (gcc_regex_type_of_a_param, diagnosis),
-       (clang_regex_type_of_retval_or_sole_param, diagnosis),
-       (clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})],
-      msg):
-    yield diag
-  # Avoid overlap with the NUS pattern.
-  for m in _FindAllMatches(clang_regex_unknown_type, msg):
-    type_ = m.groupdict()['type']
-    if type_ not in _COMMON_GMOCK_SYMBOLS:
-      yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict())
-
-
-def _WrongMockMethodMacroDiagnoser(msg):
-  """Diagnoses the WMM disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE +
-               r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
-               r'.*\n'
-               r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
-  clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
-                 r'error:.*array.*negative.*r?\n'
-                 r'(.*\n)*?'
-                 r'(?P=file):(?P=line):(?P=column): error: too few arguments '
-                 r'to function call, expected (?P<args>\d+), '
-                 r'have (?P<wrong_args>\d+)')
-  clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE +
-                r'.*this_method_does_not_take_'
-                r'(?P<wrong_args>\d+)_argument.*')
-  diagnosis = """
-You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
-%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
-MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
-  return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
-                           [(gcc_regex, diagnosis),
-                            (clang11_re, diagnosis % {'wrong_args': 'm',
-                                                      'args': 'n'}),
-                            (clang_regex, diagnosis)],
-                           msg)
-
-
-def _WrongParenPositionDiagnoser(msg):
-  """Diagnoses the WPP disease, given the error messages by the compiler."""
-
-  gcc_regex = (_GCC_FILE_LINE_RE +
-               r'error:.*testing::internal::MockSpec<.* has no member named \''
-               r'(?P<method>\w+)\'')
-  clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
-                 r'error: no member named \'(?P<method>\w+)\' in '
-                 r'\'testing::internal::MockSpec<.*>\'')
-  diagnosis = """
-The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
-".%(method)s".  For example, you should write:
-  EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
-instead of:
-  EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
-  return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
-                           [(gcc_regex, diagnosis),
-                            (clang_regex, diagnosis)],
-                           msg)
-
-
-_DIAGNOSERS = [
-    _IncompleteByReferenceArgumentDiagnoser,
-    _MockObjectPointerDiagnoser,
-    _NeedToReturnNothingDiagnoser,
-    _NeedToReturnReferenceDiagnoser,
-    _NeedToReturnSomethingDiagnoser,
-    _NeedToUseReturnNullDiagnoser,
-    _NeedToUseSymbolDiagnoser,
-    _OverloadedFunctionActionDiagnoser,
-    _OverloadedFunctionMatcherDiagnoser,
-    _OverloadedMethodActionDiagnoser,
-    _TypeInTemplatedBaseDiagnoser,
-    _WrongMockMethodMacroDiagnoser,
-    _WrongParenPositionDiagnoser,
-    ]
-
-
-def Diagnose(msg):
-  """Generates all possible diagnoses given the compiler error message."""
-
-  msg = re.sub(r'\x1b\[[^m]*m', '', msg)  # Strips all color formatting.
-  # Assuming the string is using the UTF-8 encoding, replaces the left and
-  # the right single quote characters with apostrophes.
-  msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg)
-
-  diagnoses = []
-  for diagnoser in _DIAGNOSERS:
-    for diag in diagnoser(msg):
-      diagnosis = '[%s - %s]\n%s' % diag
-      if not diagnosis in diagnoses:
-        diagnoses.append(diagnosis)
-  return diagnoses
-
-
-def main():
-  print ('Google Mock Doctor v%s - '
-         'diagnoses problems in code using Google Mock.' % _VERSION)
-
-  if sys.stdin.isatty():
-    print ('Please copy and paste the compiler errors here.  Press c-D when '
-           'you are done:')
-  else:
-    print 'Waiting for compiler errors on stdin . . .'
-
-  msg = sys.stdin.read().strip()
-  diagnoses = Diagnose(msg)
-  count = len(diagnoses)
-  if not count:
-    print ("""
-Your compiler complained:
-8<------------------------------------------------------------
-%s
------------------------------------------------------------->8
-
-Uh-oh, I'm not smart enough to figure out what the problem is. :-(
-However...
-If you send your source code and the compiler's error messages to
-%s, you can be helped and I can get smarter --
-win-win for us!""" % (msg, _EMAIL))
-  else:
-    print '------------------------------------------------------------'
-    print 'Your code appears to have the following',
-    if count > 1:
-      print '%s diseases:' % (count,)
-    else:
-      print 'disease:'
-    i = 0
-    for d in diagnoses:
-      i += 1
-      if count > 1:
-        print '\n#%s:' % (i,)
-      print d
-    print ("""
-How did I do?  If you think I'm wrong or unhelpful, please send your
-source code and the compiler's error messages to %s.
-Then you can be helped and I can get smarter -- I promise I won't be upset!""" %
-           _EMAIL)
-
-
-if __name__ == '__main__':
-  main()
diff --git a/testing/gmock/scripts/upload.py b/testing/gmock/scripts/upload.py
deleted file mode 100755
index 6e6f9a1..0000000
--- a/testing/gmock/scripts/upload.py
+++ /dev/null
@@ -1,1387 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Tool for uploading diffs from a version control system to the codereview app.
-
-Usage summary: upload.py [options] [-- diff_options]
-
-Diff options are passed to the diff command of the underlying system.
-
-Supported version control systems:
-  Git
-  Mercurial
-  Subversion
-
-It is important for Git/Mercurial users to specify a tree/node/branch to diff
-against by using the '--rev' option.
-"""
-# This code is derived from appcfg.py in the App Engine SDK (open source),
-# and from ASPN recipe #146306.
-
-import cookielib
-import getpass
-import logging
-import md5
-import mimetypes
-import optparse
-import os
-import re
-import socket
-import subprocess
-import sys
-import urllib
-import urllib2
-import urlparse
-
-try:
-  import readline
-except ImportError:
-  pass
-
-# The logging verbosity:
-#  0: Errors only.
-#  1: Status messages.
-#  2: Info logs.
-#  3: Debug logs.
-verbosity = 1
-
-# Max size of patch or base file.
-MAX_UPLOAD_SIZE = 900 * 1024
-
-
-def GetEmail(prompt):
-  """Prompts the user for their email address and returns it.
-
-  The last used email address is saved to a file and offered up as a suggestion
-  to the user. If the user presses enter without typing in anything the last
-  used email address is used. If the user enters a new address, it is saved
-  for next time we prompt.
-
-  """
-  last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
-  last_email = ""
-  if os.path.exists(last_email_file_name):
-    try:
-      last_email_file = open(last_email_file_name, "r")
-      last_email = last_email_file.readline().strip("\n")
-      last_email_file.close()
-      prompt += " [%s]" % last_email
-    except IOError, e:
-      pass
-  email = raw_input(prompt + ": ").strip()
-  if email:
-    try:
-      last_email_file = open(last_email_file_name, "w")
-      last_email_file.write(email)
-      last_email_file.close()
-    except IOError, e:
-      pass
-  else:
-    email = last_email
-  return email
-
-
-def StatusUpdate(msg):
-  """Print a status message to stdout.
-
-  If 'verbosity' is greater than 0, print the message.
-
-  Args:
-    msg: The string to print.
-  """
-  if verbosity > 0:
-    print msg
-
-
-def ErrorExit(msg):
-  """Print an error message to stderr and exit."""
-  print >>sys.stderr, msg
-  sys.exit(1)
-
-
-class ClientLoginError(urllib2.HTTPError):
-  """Raised to indicate there was an error authenticating with ClientLogin."""
-
-  def __init__(self, url, code, msg, headers, args):
-    urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
-    self.args = args
-    self.reason = args["Error"]
-
-
-class AbstractRpcServer(object):
-  """Provides a common interface for a simple RPC server."""
-
-  def __init__(self, host, auth_function, host_override=None, extra_headers={},
-               save_cookies=False):
-    """Creates a new HttpRpcServer.
-
-    Args:
-      host: The host to send requests to.
-      auth_function: A function that takes no arguments and returns an
-        (email, password) tuple when called. Will be called if authentication
-        is required.
-      host_override: The host header to send to the server (defaults to host).
-      extra_headers: A dict of extra headers to append to every request.
-      save_cookies: If True, save the authentication cookies to local disk.
-        If False, use an in-memory cookiejar instead.  Subclasses must
-        implement this functionality.  Defaults to False.
-    """
-    self.host = host
-    self.host_override = host_override
-    self.auth_function = auth_function
-    self.authenticated = False
-    self.extra_headers = extra_headers
-    self.save_cookies = save_cookies
-    self.opener = self._GetOpener()
-    if self.host_override:
-      logging.info("Server: %s; Host: %s", self.host, self.host_override)
-    else:
-      logging.info("Server: %s", self.host)
-
-  def _GetOpener(self):
-    """Returns an OpenerDirector for making HTTP requests.
-
-    Returns:
-      A urllib2.OpenerDirector object.
-    """
-    raise NotImplementedError()
-
-  def _CreateRequest(self, url, data=None):
-    """Creates a new urllib request."""
-    logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
-    req = urllib2.Request(url, data=data)
-    if self.host_override:
-      req.add_header("Host", self.host_override)
-    for key, value in self.extra_headers.iteritems():
-      req.add_header(key, value)
-    return req
-
-  def _GetAuthToken(self, email, password):
-    """Uses ClientLogin to authenticate the user, returning an auth token.
-
-    Args:
-      email:    The user's email address
-      password: The user's password
-
-    Raises:
-      ClientLoginError: If there was an error authenticating with ClientLogin.
-      HTTPError: If there was some other form of HTTP error.
-
-    Returns:
-      The authentication token returned by ClientLogin.
-    """
-    account_type = "GOOGLE"
-    if self.host.endswith(".google.com"):
-      # Needed for use inside Google.
-      account_type = "HOSTED"
-    req = self._CreateRequest(
-        url="https://www.google.com/accounts/ClientLogin",
-        data=urllib.urlencode({
-            "Email": email,
-            "Passwd": password,
-            "service": "ah",
-            "source": "rietveld-codereview-upload",
-            "accountType": account_type,
-        }),
-    )
-    try:
-      response = self.opener.open(req)
-      response_body = response.read()
-      response_dict = dict(x.split("=")
-                           for x in response_body.split("\n") if x)
-      return response_dict["Auth"]
-    except urllib2.HTTPError, e:
-      if e.code == 403:
-        body = e.read()
-        response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
-        raise ClientLoginError(req.get_full_url(), e.code, e.msg,
-                               e.headers, response_dict)
-      else:
-        raise
-
-  def _GetAuthCookie(self, auth_token):
-    """Fetches authentication cookies for an authentication token.
-
-    Args:
-      auth_token: The authentication token returned by ClientLogin.
-
-    Raises:
-      HTTPError: If there was an error fetching the authentication cookies.
-    """
-    # This is a dummy value to allow us to identify when we're successful.
-    continue_location = "http://localhost/"
-    args = {"continue": continue_location, "auth": auth_token}
-    req = self._CreateRequest("http://%s/_ah/login?%s" %
-                              (self.host, urllib.urlencode(args)))
-    try:
-      response = self.opener.open(req)
-    except urllib2.HTTPError, e:
-      response = e
-    if (response.code != 302 or
-        response.info()["location"] != continue_location):
-      raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
-                              response.headers, response.fp)
-    self.authenticated = True
-
-  def _Authenticate(self):
-    """Authenticates the user.
-
-    The authentication process works as follows:
-     1) We get a username and password from the user
-     2) We use ClientLogin to obtain an AUTH token for the user
-        (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
-     3) We pass the auth token to /_ah/login on the server to obtain an
-        authentication cookie. If login was successful, it tries to redirect
-        us to the URL we provided.
-
-    If we attempt to access the upload API without first obtaining an
-    authentication cookie, it returns a 401 response and directs us to
-    authenticate ourselves with ClientLogin.
-    """
-    for i in range(3):
-      credentials = self.auth_function()
-      try:
-        auth_token = self._GetAuthToken(credentials[0], credentials[1])
-      except ClientLoginError, e:
-        if e.reason == "BadAuthentication":
-          print >>sys.stderr, "Invalid username or password."
-          continue
-        if e.reason == "CaptchaRequired":
-          print >>sys.stderr, (
-              "Please go to\n"
-              "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
-              "and verify you are a human.  Then try again.")
-          break
-        if e.reason == "NotVerified":
-          print >>sys.stderr, "Account not verified."
-          break
-        if e.reason == "TermsNotAgreed":
-          print >>sys.stderr, "User has not agreed to TOS."
-          break
-        if e.reason == "AccountDeleted":
-          print >>sys.stderr, "The user account has been deleted."
-          break
-        if e.reason == "AccountDisabled":
-          print >>sys.stderr, "The user account has been disabled."
-          break
-        if e.reason == "ServiceDisabled":
-          print >>sys.stderr, ("The user's access to the service has been "
-                               "disabled.")
-          break
-        if e.reason == "ServiceUnavailable":
-          print >>sys.stderr, "The service is not available; try again later."
-          break
-        raise
-      self._GetAuthCookie(auth_token)
-      return
-
-  def Send(self, request_path, payload=None,
-           content_type="application/octet-stream",
-           timeout=None,
-           **kwargs):
-    """Sends an RPC and returns the response.
-
-    Args:
-      request_path: The path to send the request to, eg /api/appversion/create.
-      payload: The body of the request, or None to send an empty request.
-      content_type: The Content-Type header to use.
-      timeout: timeout in seconds; default None i.e. no timeout.
-        (Note: for large requests on OS X, the timeout doesn't work right.)
-      kwargs: Any keyword arguments are converted into query string parameters.
-
-    Returns:
-      The response body, as a string.
-    """
-    # TODO: Don't require authentication.  Let the server say
-    # whether it is necessary.
-    if not self.authenticated:
-      self._Authenticate()
-
-    old_timeout = socket.getdefaulttimeout()
-    socket.setdefaulttimeout(timeout)
-    try:
-      tries = 0
-      while True:
-        tries += 1
-        args = dict(kwargs)
-        url = "http://%s%s" % (self.host, request_path)
-        if args:
-          url += "?" + urllib.urlencode(args)
-        req = self._CreateRequest(url=url, data=payload)
-        req.add_header("Content-Type", content_type)
-        try:
-          f = self.opener.open(req)
-          response = f.read()
-          f.close()
-          return response
-        except urllib2.HTTPError, e:
-          if tries > 3:
-            raise
-          elif e.code == 401:
-            self._Authenticate()
-##           elif e.code >= 500 and e.code < 600:
-##             # Server Error - try again.
-##             continue
-          else:
-            raise
-    finally:
-      socket.setdefaulttimeout(old_timeout)
-
-
-class HttpRpcServer(AbstractRpcServer):
-  """Provides a simplified RPC-style interface for HTTP requests."""
-
-  def _Authenticate(self):
-    """Save the cookie jar after authentication."""
-    super(HttpRpcServer, self)._Authenticate()
-    if self.save_cookies:
-      StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
-      self.cookie_jar.save()
-
-  def _GetOpener(self):
-    """Returns an OpenerDirector that supports cookies and ignores redirects.
-
-    Returns:
-      A urllib2.OpenerDirector object.
-    """
-    opener = urllib2.OpenerDirector()
-    opener.add_handler(urllib2.ProxyHandler())
-    opener.add_handler(urllib2.UnknownHandler())
-    opener.add_handler(urllib2.HTTPHandler())
-    opener.add_handler(urllib2.HTTPDefaultErrorHandler())
-    opener.add_handler(urllib2.HTTPSHandler())
-    opener.add_handler(urllib2.HTTPErrorProcessor())
-    if self.save_cookies:
-      self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
-      self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
-      if os.path.exists(self.cookie_file):
-        try:
-          self.cookie_jar.load()
-          self.authenticated = True
-          StatusUpdate("Loaded authentication cookies from %s" %
-                       self.cookie_file)
-        except (cookielib.LoadError, IOError):
-          # Failed to load cookies - just ignore them.
-          pass
-      else:
-        # Create an empty cookie file with mode 600
-        fd = os.open(self.cookie_file, os.O_CREAT, 0600)
-        os.close(fd)
-      # Always chmod the cookie file
-      os.chmod(self.cookie_file, 0600)
-    else:
-      # Don't save cookies across runs of update.py.
-      self.cookie_jar = cookielib.CookieJar()
-    opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
-    return opener
-
-
-parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
-parser.add_option("-y", "--assume_yes", action="store_true",
-                  dest="assume_yes", default=False,
-                  help="Assume that the answer to yes/no questions is 'yes'.")
-# Logging
-group = parser.add_option_group("Logging options")
-group.add_option("-q", "--quiet", action="store_const", const=0,
-                 dest="verbose", help="Print errors only.")
-group.add_option("-v", "--verbose", action="store_const", const=2,
-                 dest="verbose", default=1,
-                 help="Print info level logs (default).")
-group.add_option("--noisy", action="store_const", const=3,
-                 dest="verbose", help="Print all logs.")
-# Review server
-group = parser.add_option_group("Review server options")
-group.add_option("-s", "--server", action="store", dest="server",
-                 default="codereview.appspot.com",
-                 metavar="SERVER",
-                 help=("The server to upload to. The format is host[:port]. "
-                       "Defaults to 'codereview.appspot.com'."))
-group.add_option("-e", "--email", action="store", dest="email",
-                 metavar="EMAIL", default=None,
-                 help="The username to use. Will prompt if omitted.")
-group.add_option("-H", "--host", action="store", dest="host",
-                 metavar="HOST", default=None,
-                 help="Overrides the Host header sent with all RPCs.")
-group.add_option("--no_cookies", action="store_false",
-                 dest="save_cookies", default=True,
-                 help="Do not save authentication cookies to local disk.")
-# Issue
-group = parser.add_option_group("Issue options")
-group.add_option("-d", "--description", action="store", dest="description",
-                 metavar="DESCRIPTION", default=None,
-                 help="Optional description when creating an issue.")
-group.add_option("-f", "--description_file", action="store",
-                 dest="description_file", metavar="DESCRIPTION_FILE",
-                 default=None,
-                 help="Optional path of a file that contains "
-                      "the description when creating an issue.")
-group.add_option("-r", "--reviewers", action="store", dest="reviewers",
-                 metavar="REVIEWERS", default=None,
-                 help="Add reviewers (comma separated email addresses).")
-group.add_option("--cc", action="store", dest="cc",
-                 metavar="CC", default=None,
-                 help="Add CC (comma separated email addresses).")
-# Upload options
-group = parser.add_option_group("Patch options")
-group.add_option("-m", "--message", action="store", dest="message",
-                 metavar="MESSAGE", default=None,
-                 help="A message to identify the patch. "
-                      "Will prompt if omitted.")
-group.add_option("-i", "--issue", type="int", action="store",
-                 metavar="ISSUE", default=None,
-                 help="Issue number to which to add. Defaults to new issue.")
-group.add_option("--download_base", action="store_true",
-                 dest="download_base", default=False,
-                 help="Base files will be downloaded by the server "
-                 "(side-by-side diffs may not work on files with CRs).")
-group.add_option("--rev", action="store", dest="revision",
-                 metavar="REV", default=None,
-                 help="Branch/tree/revision to diff against (used by DVCS).")
-group.add_option("--send_mail", action="store_true",
-                 dest="send_mail", default=False,
-                 help="Send notification email to reviewers.")
-
-
-def GetRpcServer(options):
-  """Returns an instance of an AbstractRpcServer.
-
-  Returns:
-    A new AbstractRpcServer, on which RPC calls can be made.
-  """
-
-  rpc_server_class = HttpRpcServer
-
-  def GetUserCredentials():
-    """Prompts the user for a username and password."""
-    email = options.email
-    if email is None:
-      email = GetEmail("Email (login for uploading to %s)" % options.server)
-    password = getpass.getpass("Password for %s: " % email)
-    return (email, password)
-
-  # If this is the dev_appserver, use fake authentication.
-  host = (options.host or options.server).lower()
-  if host == "localhost" or host.startswith("localhost:"):
-    email = options.email
-    if email is None:
-      email = "test@example.com"
-      logging.info("Using debug user %s.  Override with --email" % email)
-    server = rpc_server_class(
-        options.server,
-        lambda: (email, "password"),
-        host_override=options.host,
-        extra_headers={"Cookie":
-                       'dev_appserver_login="%s:False"' % email},
-        save_cookies=options.save_cookies)
-    # Don't try to talk to ClientLogin.
-    server.authenticated = True
-    return server
-
-  return rpc_server_class(options.server, GetUserCredentials,
-                          host_override=options.host,
-                          save_cookies=options.save_cookies)
-
-
-def EncodeMultipartFormData(fields, files):
-  """Encode form fields for multipart/form-data.
-
-  Args:
-    fields: A sequence of (name, value) elements for regular form fields.
-    files: A sequence of (name, filename, value) elements for data to be
-           uploaded as files.
-  Returns:
-    (content_type, body) ready for httplib.HTTP instance.
-
-  Source:
-    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
-  """
-  BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
-  CRLF = '\r\n'
-  lines = []
-  for (key, value) in fields:
-    lines.append('--' + BOUNDARY)
-    lines.append('Content-Disposition: form-data; name="%s"' % key)
-    lines.append('')
-    lines.append(value)
-  for (key, filename, value) in files:
-    lines.append('--' + BOUNDARY)
-    lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
-             (key, filename))
-    lines.append('Content-Type: %s' % GetContentType(filename))
-    lines.append('')
-    lines.append(value)
-  lines.append('--' + BOUNDARY + '--')
-  lines.append('')
-  body = CRLF.join(lines)
-  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
-  return content_type, body
-
-
-def GetContentType(filename):
-  """Helper to guess the content-type from the filename."""
-  return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
-
-
-# Use a shell for subcommands on Windows to get a PATH search.
-use_shell = sys.platform.startswith("win")
-
-def RunShellWithReturnCode(command, print_output=False,
-                           universal_newlines=True):
-  """Executes a command and returns the output from stdout and the return code.
-
-  Args:
-    command: Command to execute.
-    print_output: If True, the output is printed to stdout.
-                  If False, both stdout and stderr are ignored.
-    universal_newlines: Use universal_newlines flag (default: True).
-
-  Returns:
-    Tuple (output, return code)
-  """
-  logging.info("Running %s", command)
-  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
-                       shell=use_shell, universal_newlines=universal_newlines)
-  if print_output:
-    output_array = []
-    while True:
-      line = p.stdout.readline()
-      if not line:
-        break
-      print line.strip("\n")
-      output_array.append(line)
-    output = "".join(output_array)
-  else:
-    output = p.stdout.read()
-  p.wait()
-  errout = p.stderr.read()
-  if print_output and errout:
-    print >>sys.stderr, errout
-  p.stdout.close()
-  p.stderr.close()
-  return output, p.returncode
-
-
-def RunShell(command, silent_ok=False, universal_newlines=True,
-             print_output=False):
-  data, retcode = RunShellWithReturnCode(command, print_output,
-                                         universal_newlines)
-  if retcode:
-    ErrorExit("Got error status from %s:\n%s" % (command, data))
-  if not silent_ok and not data:
-    ErrorExit("No output from %s" % command)
-  return data
-
-
-class VersionControlSystem(object):
-  """Abstract base class providing an interface to the VCS."""
-
-  def __init__(self, options):
-    """Constructor.
-
-    Args:
-      options: Command line options.
-    """
-    self.options = options
-
-  def GenerateDiff(self, args):
-    """Return the current diff as a string.
-
-    Args:
-      args: Extra arguments to pass to the diff command.
-    """
-    raise NotImplementedError(
-        "abstract method -- subclass %s must override" % self.__class__)
-
-  def GetUnknownFiles(self):
-    """Return a list of files unknown to the VCS."""
-    raise NotImplementedError(
-        "abstract method -- subclass %s must override" % self.__class__)
-
-  def CheckForUnknownFiles(self):
-    """Show an "are you sure?" prompt if there are unknown files."""
-    unknown_files = self.GetUnknownFiles()
-    if unknown_files:
-      print "The following files are not added to version control:"
-      for line in unknown_files:
-        print line
-      prompt = "Are you sure to continue?(y/N) "
-      answer = raw_input(prompt).strip()
-      if answer != "y":
-        ErrorExit("User aborted")
-
-  def GetBaseFile(self, filename):
-    """Get the content of the upstream version of a file.
-
-    Returns:
-      A tuple (base_content, new_content, is_binary, status)
-        base_content: The contents of the base file.
-        new_content: For text files, this is empty.  For binary files, this is
-          the contents of the new file, since the diff output won't contain
-          information to reconstruct the current file.
-        is_binary: True iff the file is binary.
-        status: The status of the file.
-    """
-
-    raise NotImplementedError(
-        "abstract method -- subclass %s must override" % self.__class__)
-
-
-  def GetBaseFiles(self, diff):
-    """Helper that calls GetBase file for each file in the patch.
-
-    Returns:
-      A dictionary that maps from filename to GetBaseFile's tuple.  Filenames
-      are retrieved based on lines that start with "Index:" or
-      "Property changes on:".
-    """
-    files = {}
-    for line in diff.splitlines(True):
-      if line.startswith('Index:') or line.startswith('Property changes on:'):
-        unused, filename = line.split(':', 1)
-        # On Windows if a file has property changes its filename uses '\'
-        # instead of '/'.
-        filename = filename.strip().replace('\\', '/')
-        files[filename] = self.GetBaseFile(filename)
-    return files
-
-
-  def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
-                      files):
-    """Uploads the base files (and if necessary, the current ones as well)."""
-
-    def UploadFile(filename, file_id, content, is_binary, status, is_base):
-      """Uploads a file to the server."""
-      file_too_large = False
-      if is_base:
-        type = "base"
-      else:
-        type = "current"
-      if len(content) > MAX_UPLOAD_SIZE:
-        print ("Not uploading the %s file for %s because it's too large." %
-               (type, filename))
-        file_too_large = True
-        content = ""
-      checksum = md5.new(content).hexdigest()
-      if options.verbose > 0 and not file_too_large:
-        print "Uploading %s file for %s" % (type, filename)
-      url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
-      form_fields = [("filename", filename),
-                     ("status", status),
-                     ("checksum", checksum),
-                     ("is_binary", str(is_binary)),
-                     ("is_current", str(not is_base)),
-                    ]
-      if file_too_large:
-        form_fields.append(("file_too_large", "1"))
-      if options.email:
-        form_fields.append(("user", options.email))
-      ctype, body = EncodeMultipartFormData(form_fields,
-                                            [("data", filename, content)])
-      response_body = rpc_server.Send(url, body,
-                                      content_type=ctype)
-      if not response_body.startswith("OK"):
-        StatusUpdate("  --> %s" % response_body)
-        sys.exit(1)
-
-    patches = dict()
-    [patches.setdefault(v, k) for k, v in patch_list]
-    for filename in patches.keys():
-      base_content, new_content, is_binary, status = files[filename]
-      file_id_str = patches.get(filename)
-      if file_id_str.find("nobase") != -1:
-        base_content = None
-        file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
-      file_id = int(file_id_str)
-      if base_content != None:
-        UploadFile(filename, file_id, base_content, is_binary, status, True)
-      if new_content != None:
-        UploadFile(filename, file_id, new_content, is_binary, status, False)
-
-  def IsImage(self, filename):
-    """Returns true if the filename has an image extension."""
-    mimetype =  mimetypes.guess_type(filename)[0]
-    if not mimetype:
-      return False
-    return mimetype.startswith("image/")
-
-
-class SubversionVCS(VersionControlSystem):
-  """Implementation of the VersionControlSystem interface for Subversion."""
-
-  def __init__(self, options):
-    super(SubversionVCS, self).__init__(options)
-    if self.options.revision:
-      match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
-      if not match:
-        ErrorExit("Invalid Subversion revision %s." % self.options.revision)
-      self.rev_start = match.group(1)
-      self.rev_end = match.group(3)
-    else:
-      self.rev_start = self.rev_end = None
-    # Cache output from "svn list -r REVNO dirname".
-    # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
-    self.svnls_cache = {}
-    # SVN base URL is required to fetch files deleted in an older revision.
-    # Result is cached to not guess it over and over again in GetBaseFile().
-    required = self.options.download_base or self.options.revision is not None
-    self.svn_base = self._GuessBase(required)
-
-  def GuessBase(self, required):
-    """Wrapper for _GuessBase."""
-    return self.svn_base
-
-  def _GuessBase(self, required):
-    """Returns the SVN base URL.
-
-    Args:
-      required: If true, exits if the url can't be guessed, otherwise None is
-        returned.
-    """
-    info = RunShell(["svn", "info"])
-    for line in info.splitlines():
-      words = line.split()
-      if len(words) == 2 and words[0] == "URL:":
-        url = words[1]
-        scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
-        username, netloc = urllib.splituser(netloc)
-        if username:
-          logging.info("Removed username from base URL")
-        if netloc.endswith("svn.python.org"):
-          if netloc == "svn.python.org":
-            if path.startswith("/projects/"):
-              path = path[9:]
-          elif netloc != "pythondev@svn.python.org":
-            ErrorExit("Unrecognized Python URL: %s" % url)
-          base = "http://svn.python.org/view/*checkout*%s/" % path
-          logging.info("Guessed Python base = %s", base)
-        elif netloc.endswith("svn.collab.net"):
-          if path.startswith("/repos/"):
-            path = path[6:]
-          base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
-          logging.info("Guessed CollabNet base = %s", base)
-        elif netloc.endswith(".googlecode.com"):
-          path = path + "/"
-          base = urlparse.urlunparse(("http", netloc, path, params,
-                                      query, fragment))
-          logging.info("Guessed Google Code base = %s", base)
-        else:
-          path = path + "/"
-          base = urlparse.urlunparse((scheme, netloc, path, params,
-                                      query, fragment))
-          logging.info("Guessed base = %s", base)
-        return base
-    if required:
-      ErrorExit("Can't find URL in output from svn info")
-    return None
-
-  def GenerateDiff(self, args):
-    cmd = ["svn", "diff"]
-    if self.options.revision:
-      cmd += ["-r", self.options.revision]
-    cmd.extend(args)
-    data = RunShell(cmd)
-    count = 0
-    for line in data.splitlines():
-      if line.startswith("Index:") or line.startswith("Property changes on:"):
-        count += 1
-        logging.info(line)
-    if not count:
-      ErrorExit("No valid patches found in output from svn diff")
-    return data
-
-  def _CollapseKeywords(self, content, keyword_str):
-    """Collapses SVN keywords."""
-    # svn cat translates keywords but svn diff doesn't. As a result of this
-    # behavior patching.PatchChunks() fails with a chunk mismatch error.
-    # This part was originally written by the Review Board development team
-    # who had the same problem (http://reviews.review-board.org/r/276/).
-    # Mapping of keywords to known aliases
-    svn_keywords = {
-      # Standard keywords
-      'Date':                ['Date', 'LastChangedDate'],
-      'Revision':            ['Revision', 'LastChangedRevision', 'Rev'],
-      'Author':              ['Author', 'LastChangedBy'],
-      'HeadURL':             ['HeadURL', 'URL'],
-      'Id':                  ['Id'],
-
-      # Aliases
-      'LastChangedDate':     ['LastChangedDate', 'Date'],
-      'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
-      'LastChangedBy':       ['LastChangedBy', 'Author'],
-      'URL':                 ['URL', 'HeadURL'],
-    }
-
-    def repl(m):
-       if m.group(2):
-         return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
-       return "$%s$" % m.group(1)
-    keywords = [keyword
-                for name in keyword_str.split(" ")
-                for keyword in svn_keywords.get(name, [])]
-    return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
-
-  def GetUnknownFiles(self):
-    status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
-    unknown_files = []
-    for line in status.split("\n"):
-      if line and line[0] == "?":
-        unknown_files.append(line)
-    return unknown_files
-
-  def ReadFile(self, filename):
-    """Returns the contents of a file."""
-    file = open(filename, 'rb')
-    result = ""
-    try:
-      result = file.read()
-    finally:
-      file.close()
-    return result
-
-  def GetStatus(self, filename):
-    """Returns the status of a file."""
-    if not self.options.revision:
-      status = RunShell(["svn", "status", "--ignore-externals", filename])
-      if not status:
-        ErrorExit("svn status returned no output for %s" % filename)
-      status_lines = status.splitlines()
-      # If file is in a cl, the output will begin with
-      # "\n--- Changelist 'cl_name':\n".  See
-      # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
-      if (len(status_lines) == 3 and
-          not status_lines[0] and
-          status_lines[1].startswith("--- Changelist")):
-        status = status_lines[2]
-      else:
-        status = status_lines[0]
-    # If we have a revision to diff against we need to run "svn list"
-    # for the old and the new revision and compare the results to get
-    # the correct status for a file.
-    else:
-      dirname, relfilename = os.path.split(filename)
-      if dirname not in self.svnls_cache:
-        cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
-        out, returncode = RunShellWithReturnCode(cmd)
-        if returncode:
-          ErrorExit("Failed to get status for %s." % filename)
-        old_files = out.splitlines()
-        args = ["svn", "list"]
-        if self.rev_end:
-          args += ["-r", self.rev_end]
-        cmd = args + [dirname or "."]
-        out, returncode = RunShellWithReturnCode(cmd)
-        if returncode:
-          ErrorExit("Failed to run command %s" % cmd)
-        self.svnls_cache[dirname] = (old_files, out.splitlines())
-      old_files, new_files = self.svnls_cache[dirname]
-      if relfilename in old_files and relfilename not in new_files:
-        status = "D   "
-      elif relfilename in old_files and relfilename in new_files:
-        status = "M   "
-      else:
-        status = "A   "
-    return status
-
-  def GetBaseFile(self, filename):
-    status = self.GetStatus(filename)
-    base_content = None
-    new_content = None
-
-    # If a file is copied its status will be "A  +", which signifies
-    # "addition-with-history".  See "svn st" for more information.  We need to
-    # upload the original file or else diff parsing will fail if the file was
-    # edited.
-    if status[0] == "A" and status[3] != "+":
-      # We'll need to upload the new content if we're adding a binary file
-      # since diff's output won't contain it.
-      mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
-                          silent_ok=True)
-      base_content = ""
-      is_binary = mimetype and not mimetype.startswith("text/")
-      if is_binary and self.IsImage(filename):
-        new_content = self.ReadFile(filename)
-    elif (status[0] in ("M", "D", "R") or
-          (status[0] == "A" and status[3] == "+") or  # Copied file.
-          (status[0] == " " and status[1] == "M")):  # Property change.
-      args = []
-      if self.options.revision:
-        url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
-      else:
-        # Don't change filename, it's needed later.
-        url = filename
-        args += ["-r", "BASE"]
-      cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
-      mimetype, returncode = RunShellWithReturnCode(cmd)
-      if returncode:
-        # File does not exist in the requested revision.
-        # Reset mimetype, it contains an error message.
-        mimetype = ""
-      get_base = False
-      is_binary = mimetype and not mimetype.startswith("text/")
-      if status[0] == " ":
-        # Empty base content just to force an upload.
-        base_content = ""
-      elif is_binary:
-        if self.IsImage(filename):
-          get_base = True
-          if status[0] == "M":
-            if not self.rev_end:
-              new_content = self.ReadFile(filename)
-            else:
-              url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
-              new_content = RunShell(["svn", "cat", url],
-                                     universal_newlines=True, silent_ok=True)
-        else:
-          base_content = ""
-      else:
-        get_base = True
-
-      if get_base:
-        if is_binary:
-          universal_newlines = False
-        else:
-          universal_newlines = True
-        if self.rev_start:
-          # "svn cat -r REV delete_file.txt" doesn't work. cat requires
-          # the full URL with "@REV" appended instead of using "-r" option.
-          url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
-          base_content = RunShell(["svn", "cat", url],
-                                  universal_newlines=universal_newlines,
-                                  silent_ok=True)
-        else:
-          base_content = RunShell(["svn", "cat", filename],
-                                  universal_newlines=universal_newlines,
-                                  silent_ok=True)
-        if not is_binary:
-          args = []
-          if self.rev_start:
-            url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
-          else:
-            url = filename
-            args += ["-r", "BASE"]
-          cmd = ["svn"] + args + ["propget", "svn:keywords", url]
-          keywords, returncode = RunShellWithReturnCode(cmd)
-          if keywords and not returncode:
-            base_content = self._CollapseKeywords(base_content, keywords)
-    else:
-      StatusUpdate("svn status returned unexpected output: %s" % status)
-      sys.exit(1)
-    return base_content, new_content, is_binary, status[0:5]
-
-
-class GitVCS(VersionControlSystem):
-  """Implementation of the VersionControlSystem interface for Git."""
-
-  def __init__(self, options):
-    super(GitVCS, self).__init__(options)
-    # Map of filename -> hash of base file.
-    self.base_hashes = {}
-
-  def GenerateDiff(self, extra_args):
-    # This is more complicated than svn's GenerateDiff because we must convert
-    # the diff output to include an svn-style "Index:" line as well as record
-    # the hashes of the base files, so we can upload them along with our diff.
-    if self.options.revision:
-      extra_args = [self.options.revision] + extra_args
-    gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
-    svndiff = []
-    filecount = 0
-    filename = None
-    for line in gitdiff.splitlines():
-      match = re.match(r"diff --git a/(.*) b/.*$", line)
-      if match:
-        filecount += 1
-        filename = match.group(1)
-        svndiff.append("Index: %s\n" % filename)
-      else:
-        # The "index" line in a git diff looks like this (long hashes elided):
-        #   index 82c0d44..b2cee3f 100755
-        # We want to save the left hash, as that identifies the base file.
-        match = re.match(r"index (\w+)\.\.", line)
-        if match:
-          self.base_hashes[filename] = match.group(1)
-      svndiff.append(line + "\n")
-    if not filecount:
-      ErrorExit("No valid patches found in output from git diff")
-    return "".join(svndiff)
-
-  def GetUnknownFiles(self):
-    status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
-                      silent_ok=True)
-    return status.splitlines()
-
-  def GetBaseFile(self, filename):
-    hash = self.base_hashes[filename]
-    base_content = None
-    new_content = None
-    is_binary = False
-    if hash == "0" * 40:  # All-zero hash indicates no base file.
-      status = "A"
-      base_content = ""
-    else:
-      status = "M"
-      base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
-      if returncode:
-        ErrorExit("Got error status from 'git show %s'" % hash)
-    return (base_content, new_content, is_binary, status)
-
-
-class MercurialVCS(VersionControlSystem):
-  """Implementation of the VersionControlSystem interface for Mercurial."""
-
-  def __init__(self, options, repo_dir):
-    super(MercurialVCS, self).__init__(options)
-    # Absolute path to repository (we can be in a subdir)
-    self.repo_dir = os.path.normpath(repo_dir)
-    # Compute the subdir
-    cwd = os.path.normpath(os.getcwd())
-    assert cwd.startswith(self.repo_dir)
-    self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
-    if self.options.revision:
-      self.base_rev = self.options.revision
-    else:
-      self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
-
-  def _GetRelPath(self, filename):
-    """Get relative path of a file according to the current directory,
-    given its logical path in the repo."""
-    assert filename.startswith(self.subdir), filename
-    return filename[len(self.subdir):].lstrip(r"\/")
-
-  def GenerateDiff(self, extra_args):
-    # If no file specified, restrict to the current subdir
-    extra_args = extra_args or ["."]
-    cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
-    data = RunShell(cmd, silent_ok=True)
-    svndiff = []
-    filecount = 0
-    for line in data.splitlines():
-      m = re.match("diff --git a/(\S+) b/(\S+)", line)
-      if m:
-        # Modify line to make it look like as it comes from svn diff.
-        # With this modification no changes on the server side are required
-        # to make upload.py work with Mercurial repos.
-        # NOTE: for proper handling of moved/copied files, we have to use
-        # the second filename.
-        filename = m.group(2)
-        svndiff.append("Index: %s" % filename)
-        svndiff.append("=" * 67)
-        filecount += 1
-        logging.info(line)
-      else:
-        svndiff.append(line)
-    if not filecount:
-      ErrorExit("No valid patches found in output from hg diff")
-    return "\n".join(svndiff) + "\n"
-
-  def GetUnknownFiles(self):
-    """Return a list of files unknown to the VCS."""
-    args = []
-    status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
-        silent_ok=True)
-    unknown_files = []
-    for line in status.splitlines():
-      st, fn = line.split(" ", 1)
-      if st == "?":
-        unknown_files.append(fn)
-    return unknown_files
-
-  def GetBaseFile(self, filename):
-    # "hg status" and "hg cat" both take a path relative to the current subdir
-    # rather than to the repo root, but "hg diff" has given us the full path
-    # to the repo root.
-    base_content = ""
-    new_content = None
-    is_binary = False
-    oldrelpath = relpath = self._GetRelPath(filename)
-    # "hg status -C" returns two lines for moved/copied files, one otherwise
-    out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
-    out = out.splitlines()
-    # HACK: strip error message about missing file/directory if it isn't in
-    # the working copy
-    if out[0].startswith('%s: ' % relpath):
-      out = out[1:]
-    if len(out) > 1:
-      # Moved/copied => considered as modified, use old filename to
-      # retrieve base contents
-      oldrelpath = out[1].strip()
-      status = "M"
-    else:
-      status, _ = out[0].split(' ', 1)
-    if status != "A":
-      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
-        silent_ok=True)
-      is_binary = "\0" in base_content  # Mercurial's heuristic
-    if status != "R":
-      new_content = open(relpath, "rb").read()
-      is_binary = is_binary or "\0" in new_content
-    if is_binary and base_content:
-      # Fetch again without converting newlines
-      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
-        silent_ok=True, universal_newlines=False)
-    if not is_binary or not self.IsImage(relpath):
-      new_content = None
-    return base_content, new_content, is_binary, status
-
-
-# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
-def SplitPatch(data):
-  """Splits a patch into separate pieces for each file.
-
-  Args:
-    data: A string containing the output of svn diff.
-
-  Returns:
-    A list of 2-tuple (filename, text) where text is the svn diff output
-      pertaining to filename.
-  """
-  patches = []
-  filename = None
-  diff = []
-  for line in data.splitlines(True):
-    new_filename = None
-    if line.startswith('Index:'):
-      unused, new_filename = line.split(':', 1)
-      new_filename = new_filename.strip()
-    elif line.startswith('Property changes on:'):
-      unused, temp_filename = line.split(':', 1)
-      # When a file is modified, paths use '/' between directories, however
-      # when a property is modified '\' is used on Windows.  Make them the same
-      # otherwise the file shows up twice.
-      temp_filename = temp_filename.strip().replace('\\', '/')
-      if temp_filename != filename:
-        # File has property changes but no modifications, create a new diff.
-        new_filename = temp_filename
-    if new_filename:
-      if filename and diff:
-        patches.append((filename, ''.join(diff)))
-      filename = new_filename
-      diff = [line]
-      continue
-    if diff is not None:
-      diff.append(line)
-  if filename and diff:
-    patches.append((filename, ''.join(diff)))
-  return patches
-
-
-def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
-  """Uploads a separate patch for each file in the diff output.
-
-  Returns a list of [patch_key, filename] for each file.
-  """
-  patches = SplitPatch(data)
-  rv = []
-  for patch in patches:
-    if len(patch[1]) > MAX_UPLOAD_SIZE:
-      print ("Not uploading the patch for " + patch[0] +
-             " because the file is too large.")
-      continue
-    form_fields = [("filename", patch[0])]
-    if not options.download_base:
-      form_fields.append(("content_upload", "1"))
-    files = [("data", "data.diff", patch[1])]
-    ctype, body = EncodeMultipartFormData(form_fields, files)
-    url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
-    print "Uploading patch for " + patch[0]
-    response_body = rpc_server.Send(url, body, content_type=ctype)
-    lines = response_body.splitlines()
-    if not lines or lines[0] != "OK":
-      StatusUpdate("  --> %s" % response_body)
-      sys.exit(1)
-    rv.append([lines[1], patch[0]])
-  return rv
-
-
-def GuessVCS(options):
-  """Helper to guess the version control system.
-
-  This examines the current directory, guesses which VersionControlSystem
-  we're using, and returns an instance of the appropriate class.  Exit with an
-  error if we can't figure it out.
-
-  Returns:
-    A VersionControlSystem instance. Exits if the VCS can't be guessed.
-  """
-  # Mercurial has a command to get the base directory of a repository
-  # Try running it, but don't die if we don't have hg installed.
-  # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
-  try:
-    out, returncode = RunShellWithReturnCode(["hg", "root"])
-    if returncode == 0:
-      return MercurialVCS(options, out.strip())
-  except OSError, (errno, message):
-    if errno != 2:  # ENOENT -- they don't have hg installed.
-      raise
-
-  # Subversion has a .svn in all working directories.
-  if os.path.isdir('.svn'):
-    logging.info("Guessed VCS = Subversion")
-    return SubversionVCS(options)
-
-  # Git has a command to test if you're in a git tree.
-  # Try running it, but don't die if we don't have git installed.
-  try:
-    out, returncode = RunShellWithReturnCode(["git", "rev-parse",
-                                              "--is-inside-work-tree"])
-    if returncode == 0:
-      return GitVCS(options)
-  except OSError, (errno, message):
-    if errno != 2:  # ENOENT -- they don't have git installed.
-      raise
-
-  ErrorExit(("Could not guess version control system. "
-             "Are you in a working copy directory?"))
-
-
-def RealMain(argv, data=None):
-  """The real main function.
-
-  Args:
-    argv: Command line arguments.
-    data: Diff contents. If None (default) the diff is generated by
-      the VersionControlSystem implementation returned by GuessVCS().
-
-  Returns:
-    A 2-tuple (issue id, patchset id).
-    The patchset id is None if the base files are not uploaded by this
-    script (applies only to SVN checkouts).
-  """
-  logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
-                              "%(lineno)s %(message)s "))
-  os.environ['LC_ALL'] = 'C'
-  options, args = parser.parse_args(argv[1:])
-  global verbosity
-  verbosity = options.verbose
-  if verbosity >= 3:
-    logging.getLogger().setLevel(logging.DEBUG)
-  elif verbosity >= 2:
-    logging.getLogger().setLevel(logging.INFO)
-  vcs = GuessVCS(options)
-  if isinstance(vcs, SubversionVCS):
-    # base field is only allowed for Subversion.
-    # Note: Fetching base files may become deprecated in future releases.
-    base = vcs.GuessBase(options.download_base)
-  else:
-    base = None
-  if not base and options.download_base:
-    options.download_base = True
-    logging.info("Enabled upload of base file")
-  if not options.assume_yes:
-    vcs.CheckForUnknownFiles()
-  if data is None:
-    data = vcs.GenerateDiff(args)
-  files = vcs.GetBaseFiles(data)
-  if verbosity >= 1:
-    print "Upload server:", options.server, "(change with -s/--server)"
-  if options.issue:
-    prompt = "Message describing this patch set: "
-  else:
-    prompt = "New issue subject: "
-  message = options.message or raw_input(prompt).strip()
-  if not message:
-    ErrorExit("A non-empty message is required")
-  rpc_server = GetRpcServer(options)
-  form_fields = [("subject", message)]
-  if base:
-    form_fields.append(("base", base))
-  if options.issue:
-    form_fields.append(("issue", str(options.issue)))
-  if options.email:
-    form_fields.append(("user", options.email))
-  if options.reviewers:
-    for reviewer in options.reviewers.split(','):
-      if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
-        ErrorExit("Invalid email address: %s" % reviewer)
-    form_fields.append(("reviewers", options.reviewers))
-  if options.cc:
-    for cc in options.cc.split(','):
-      if "@" in cc and not cc.split("@")[1].count(".") == 1:
-        ErrorExit("Invalid email address: %s" % cc)
-    form_fields.append(("cc", options.cc))
-  description = options.description
-  if options.description_file:
-    if options.description:
-      ErrorExit("Can't specify description and description_file")
-    file = open(options.description_file, 'r')
-    description = file.read()
-    file.close()
-  if description:
-    form_fields.append(("description", description))
-  # Send a hash of all the base file so the server can determine if a copy
-  # already exists in an earlier patchset.
-  base_hashes = ""
-  for file, info in files.iteritems():
-    if not info[0] is None:
-      checksum = md5.new(info[0]).hexdigest()
-      if base_hashes:
-        base_hashes += "|"
-      base_hashes += checksum + ":" + file
-  form_fields.append(("base_hashes", base_hashes))
-  # If we're uploading base files, don't send the email before the uploads, so
-  # that it contains the file status.
-  if options.send_mail and options.download_base:
-    form_fields.append(("send_mail", "1"))
-  if not options.download_base:
-    form_fields.append(("content_upload", "1"))
-  if len(data) > MAX_UPLOAD_SIZE:
-    print "Patch is large, so uploading file patches separately."
-    uploaded_diff_file = []
-    form_fields.append(("separate_patches", "1"))
-  else:
-    uploaded_diff_file = [("data", "data.diff", data)]
-  ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
-  response_body = rpc_server.Send("/upload", body, content_type=ctype)
-  patchset = None
-  if not options.download_base or not uploaded_diff_file:
-    lines = response_body.splitlines()
-    if len(lines) >= 2:
-      msg = lines[0]
-      patchset = lines[1].strip()
-      patches = [x.split(" ", 1) for x in lines[2:]]
-    else:
-      msg = response_body
-  else:
-    msg = response_body
-  StatusUpdate(msg)
-  if not response_body.startswith("Issue created.") and \
-  not response_body.startswith("Issue updated."):
-    sys.exit(0)
-  issue = msg[msg.rfind("/")+1:]
-
-  if not uploaded_diff_file:
-    result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
-    if not options.download_base:
-      patches = result
-
-  if not options.download_base:
-    vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
-    if options.send_mail:
-      rpc_server.Send("/" + issue + "/mail", payload="")
-  return issue, patchset
-
-
-def main():
-  try:
-    RealMain(sys.argv)
-  except KeyboardInterrupt:
-    print
-    StatusUpdate("Interrupted.")
-    sys.exit(1)
-
-
-if __name__ == "__main__":
-  main()
diff --git a/testing/gmock/scripts/upload_gmock.py b/testing/gmock/scripts/upload_gmock.py
deleted file mode 100755
index 5dc484b..0000000
--- a/testing/gmock/scripts/upload_gmock.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2009, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-#     * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#     * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-#     * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""upload_gmock.py v0.1.0 -- uploads a Google Mock patch for review.
-
-This simple wrapper passes all command line flags and
---cc=googlemock@googlegroups.com to upload.py.
-
-USAGE: upload_gmock.py [options for upload.py]
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import sys
-
-CC_FLAG = '--cc='
-GMOCK_GROUP = 'googlemock@googlegroups.com'
-
-
-def main():
-  # Finds the path to upload.py, assuming it is in the same directory
-  # as this file.
-  my_dir = os.path.dirname(os.path.abspath(__file__))
-  upload_py_path = os.path.join(my_dir, 'upload.py')
-
-  # Adds Google Mock discussion group to the cc line if it's not there
-  # already.
-  upload_py_argv = [upload_py_path]
-  found_cc_flag = False
-  for arg in sys.argv[1:]:
-    if arg.startswith(CC_FLAG):
-      found_cc_flag = True
-      cc_line = arg[len(CC_FLAG):]
-      cc_list = [addr for addr in cc_line.split(',') if addr]
-      if GMOCK_GROUP not in cc_list:
-        cc_list.append(GMOCK_GROUP)
-      upload_py_argv.append(CC_FLAG + ','.join(cc_list))
-    else:
-      upload_py_argv.append(arg)
-
-  if not found_cc_flag:
-    upload_py_argv.append(CC_FLAG + GMOCK_GROUP)
-
-  # Invokes upload.py with the modified command line flags.
-  os.execv(upload_py_path, upload_py_argv)
-
-
-if __name__ == '__main__':
-  main()
diff --git a/testing/gmock/src/gmock-all.cc b/testing/gmock/src/gmock-all.cc
deleted file mode 100644
index 7aebce7..0000000
--- a/testing/gmock/src/gmock-all.cc
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// Google C++ Mocking Framework (Google Mock)
-//
-// This file #includes all Google Mock implementation .cc files.  The
-// purpose is to allow a user to build Google Mock by compiling this
-// file alone.
-
-// This line ensures that gmock.h can be compiled on its own, even
-// when it's fused.
-#include "gmock/gmock.h"
-
-// The following lines pull in the real gmock *.cc files.
-#include "src/gmock-cardinalities.cc"
-#include "src/gmock-internal-utils.cc"
-#include "src/gmock-matchers.cc"
-#include "src/gmock-spec-builders.cc"
-#include "src/gmock.cc"
diff --git a/testing/gmock/src/gmock-cardinalities.cc b/testing/gmock/src/gmock-cardinalities.cc
deleted file mode 100644
index e940aae..0000000
--- a/testing/gmock/src/gmock-cardinalities.cc
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements cardinalities.
-
-#include "gmock/gmock-cardinalities.h"
-
-#if !GTEST_OS_STARBOARD
-#include <limits.h>
-#endif  // !GTEST_OS_STARBOARD
-
-#include <ostream>  // NOLINT
-#include <sstream>
-#include <string>
-#include "gmock/internal/gmock-internal-utils.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-
-namespace {
-
-// Implements the Between(m, n) cardinality.
-class BetweenCardinalityImpl : public CardinalityInterface {
- public:
-  BetweenCardinalityImpl(int min, int max)
-      : min_(min >= 0 ? min : 0),
-        max_(max >= min_ ? max : min_) {
-    std::stringstream ss;
-    if (min < 0) {
-      ss << "The invocation lower bound must be >= 0, "
-         << "but is actually " << min << ".";
-      internal::Expect(false, __FILE__, __LINE__, ss.str());
-    } else if (max < 0) {
-      ss << "The invocation upper bound must be >= 0, "
-         << "but is actually " << max << ".";
-      internal::Expect(false, __FILE__, __LINE__, ss.str());
-    } else if (min > max) {
-      ss << "The invocation upper bound (" << max
-         << ") must be >= the invocation lower bound (" << min
-         << ").";
-      internal::Expect(false, __FILE__, __LINE__, ss.str());
-    }
-  }
-
-  // Conservative estimate on the lower/upper bound of the number of
-  // calls allowed.
-  virtual int ConservativeLowerBound() const { return min_; }
-  virtual int ConservativeUpperBound() const { return max_; }
-
-  virtual bool IsSatisfiedByCallCount(int call_count) const {
-    return min_ <= call_count && call_count <= max_;
-  }
-
-  virtual bool IsSaturatedByCallCount(int call_count) const {
-    return call_count >= max_;
-  }
-
-  virtual void DescribeTo(::std::ostream* os) const;
-
- private:
-  const int min_;
-  const int max_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
-};
-
-// Formats "n times" in a human-friendly way.
-inline internal::string FormatTimes(int n) {
-  if (n == 1) {
-    return "once";
-  } else if (n == 2) {
-    return "twice";
-  } else {
-    std::stringstream ss;
-    ss << n << " times";
-    return ss.str();
-  }
-}
-
-// Describes the Between(m, n) cardinality in human-friendly text.
-void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
-  if (min_ == 0) {
-    if (max_ == 0) {
-      *os << "never called";
-    } else if (max_ == INT_MAX) {
-      *os << "called any number of times";
-    } else {
-      *os << "called at most " << FormatTimes(max_);
-    }
-  } else if (min_ == max_) {
-    *os << "called " << FormatTimes(min_);
-  } else if (max_ == INT_MAX) {
-    *os << "called at least " << FormatTimes(min_);
-  } else {
-    // 0 < min_ < max_ < INT_MAX
-    *os << "called between " << min_ << " and " << max_ << " times";
-  }
-}
-
-}  // Unnamed namespace
-
-// Describes the given call count to an ostream.
-void Cardinality::DescribeActualCallCountTo(int actual_call_count,
-                                            ::std::ostream* os) {
-  if (actual_call_count > 0) {
-    *os << "called " << FormatTimes(actual_call_count);
-  } else {
-    *os << "never called";
-  }
-}
-
-// Creates a cardinality that allows at least n calls.
-GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
-
-// Creates a cardinality that allows at most n calls.
-GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
-
-// Creates a cardinality that allows any number of calls.
-GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
-
-// Creates a cardinality that allows between min and max calls.
-GTEST_API_ Cardinality Between(int min, int max) {
-  return Cardinality(new BetweenCardinalityImpl(min, max));
-}
-
-// Creates a cardinality that allows exactly n calls.
-GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
-
-}  // namespace testing
diff --git a/testing/gmock/src/gmock-internal-utils.cc b/testing/gmock/src/gmock-internal-utils.cc
deleted file mode 100644
index 0065286..0000000
--- a/testing/gmock/src/gmock-internal-utils.cc
+++ /dev/null
@@ -1,202 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file defines some utilities useful for implementing Google
-// Mock.  They are subject to change without notice, so please DO NOT
-// USE THEM IN USER CODE.
-
-#include "gmock/internal/gmock-internal-utils.h"
-
-#if GTEST_OS_STARBOARD
-#include "starboard/common/log.h"
-#endif
-#if !GTEST_OS_STARBOARD
-#include <ctype.h>
-#endif  // !GTEST_OS_STARBOARD
-
-#include <ostream>  // NOLINT
-#include <string>
-#include "gmock/gmock.h"
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace internal {
-
-// Converts an identifier name to a space-separated list of lower-case
-// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
-// treated as one word.  For example, both "FooBar123" and
-// "foo_bar_123" are converted to "foo bar 123".
-GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
-  string result;
-  char prev_char = '\0';
-  for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
-    // We don't care about the current locale as the input is
-    // guaranteed to be a valid C++ identifier name.
-    const bool starts_new_word = IsUpper(*p) ||
-                                 (!IsAlpha(prev_char) && IsLower(*p)) ||
-                                 (!IsDigit(prev_char) && IsDigit(*p));
-
-    if (IsAlNum(*p)) {
-      if (starts_new_word && result != "")
-        result += ' ';
-      result += ToLower(*p);
-    }
-  }
-  return result;
-}
-
-// This class reports Google Mock failures as Google Test failures.  A
-// user can define another class in a similar fashion if he intends to
-// use Google Mock with a testing framework other than Google Test.
-class GoogleTestFailureReporter : public FailureReporterInterface {
- public:
-  virtual void ReportFailure(FailureType type,
-                             const char* file,
-                             int line,
-                             const string& message) {
-    AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
-                                : TestPartResult::kNonFatalFailure,
-                 file, line, message.c_str()) = Message();
-    if (type == kFatal) {
-      posix::Abort();
-    }
-  }
-};
-
-// Returns the global failure reporter.  Will create a
-// GoogleTestFailureReporter and return it the first time called.
-GTEST_API_ FailureReporterInterface* GetFailureReporter() {
-  // Points to the global failure reporter used by Google Mock.  gcc
-  // guarantees that the following use of failure_reporter is
-  // thread-safe.  We may need to add additional synchronization to
-  // protect failure_reporter if we port Google Mock to other
-  // compilers.
-  static FailureReporterInterface* const failure_reporter =
-      new GoogleTestFailureReporter();
-  return failure_reporter;
-}
-
-// Protects global resources (stdout in particular) used by Log().
-static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
-
-// Returns true iff a log with the given severity is visible according
-// to the --gmock_verbose flag.
-GTEST_API_ bool LogIsVisible(LogSeverity severity) {
-  if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
-    // Always show the log if --gmock_verbose=info.
-    return true;
-  } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
-    // Always hide it if --gmock_verbose=error.
-    return false;
-  } else {
-    // If --gmock_verbose is neither "info" nor "error", we treat it
-    // as "warning" (its default value).
-    return severity == kWarning;
-  }
-}
-
-// Prints the given message to stdout iff 'severity' >= the level
-// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
-// 0, also prints the stack trace excluding the top
-// stack_frames_to_skip frames.  In opt mode, any positive
-// stack_frames_to_skip is treated as 0, since we don't know which
-// function calls will be inlined by the compiler and need to be
-// conservative.
-GTEST_API_ void Log(LogSeverity severity,
-                    const string& message,
-                    int stack_frames_to_skip) {
-  if (!LogIsVisible(severity))
-    return;
-
-  // Ensures that logs from different threads don't interleave.
-  MutexLock l(&g_log_mutex);
-
-  // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
-  // macro.
-
-  if (severity == kWarning) {
-// Prints a GMOCK WARNING marker to make the warnings easily searchable.
-#if !GTEST_OS_STARBOARD
-    std::cout << "\nGMOCK WARNING:";
-#endif
-  }
-  // Pre-pends a new-line to message if it doesn't start with one.
-  if (message.empty() || message[0] != '\n') {
-#if !GTEST_OS_STARBOARD
-    std::cout << "\n";
-#endif
-  }
-
-#if GTEST_OS_STARBOARD
-  SB_LOG(INFO) << "\nGMOCK" << ((severity == kWarning) ? " WARNING" : "")
-               << ": " << message;
-#else
-  std::cout << message;
-#endif
-  if (stack_frames_to_skip >= 0) {
-#ifdef NDEBUG
-    // In opt mode, we have to be conservative and skip no stack frame.
-    const int actual_to_skip = 0;
-#else
-    // In dbg mode, we can do what the caller tell us to do (plus one
-    // for skipping this function's stack frame).
-    const int actual_to_skip = stack_frames_to_skip + 1;
-#endif  // NDEBUG
-
-    // Appends a new-line to message if it doesn't end with one.
-    if (!message.empty() && *message.rbegin() != '\n') {
-#if GTEST_OS_STARBOARD
-      SB_LOG(INFO) << "\n";
-#else
-      std::cout << "\n";
-#endif
-    }
-
-#if GTEST_OS_STARBOARD
-    SB_LOG(INFO) << "Stack trace:\n"
-                 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
-                        ::testing::UnitTest::GetInstance(), actual_to_skip);
-  }
-  SB_LOG(INFO) << ::std::flush;
-#else
-    std::cout << "Stack trace:\n"
-              << ::testing::internal::GetCurrentOsStackTraceExceptTop(
-                     ::testing::UnitTest::GetInstance(), actual_to_skip);
-  }
-  std::cout << ::std::flush;
-#endif
-}
-
-}  // namespace internal
-}  // namespace testing
diff --git a/testing/gmock/src/gmock-matchers.cc b/testing/gmock/src/gmock-matchers.cc
deleted file mode 100644
index 5cb84b6..0000000
--- a/testing/gmock/src/gmock-matchers.cc
+++ /dev/null
@@ -1,501 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements Matcher<const string&>, Matcher<string>, and
-// utilities for defining matchers.
-
-#include "gmock/gmock-matchers.h"
-#include "gmock/gmock-generated-matchers.h"
-
-#if !GTEST_OS_STARBOARD
-#include <string.h>
-#endif  // !GTEST_OS_STARBOARD
-
-#include <sstream>
-#include <string>
-
-namespace testing {
-
-// Constructs a matcher that matches a const string& whose value is
-// equal to s.
-Matcher<const internal::string&>::Matcher(const internal::string& s) {
-  *this = Eq(s);
-}
-
-// Constructs a matcher that matches a const string& whose value is
-// equal to s.
-Matcher<const internal::string&>::Matcher(const char* s) {
-  *this = Eq(internal::string(s));
-}
-
-// Constructs a matcher that matches a string whose value is equal to s.
-Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
-
-// Constructs a matcher that matches a string whose value is equal to s.
-Matcher<internal::string>::Matcher(const char* s) {
-  *this = Eq(internal::string(s));
-}
-
-#if GTEST_HAS_STRING_PIECE_
-// Constructs a matcher that matches a const StringPiece& whose value is
-// equal to s.
-Matcher<const StringPiece&>::Matcher(const internal::string& s) {
-  *this = Eq(s);
-}
-
-// Constructs a matcher that matches a const StringPiece& whose value is
-// equal to s.
-Matcher<const StringPiece&>::Matcher(const char* s) {
-  *this = Eq(internal::string(s));
-}
-
-// Constructs a matcher that matches a const StringPiece& whose value is
-// equal to s.
-Matcher<const StringPiece&>::Matcher(StringPiece s) {
-  *this = Eq(s.ToString());
-}
-
-// Constructs a matcher that matches a StringPiece whose value is equal to s.
-Matcher<StringPiece>::Matcher(const internal::string& s) {
-  *this = Eq(s);
-}
-
-// Constructs a matcher that matches a StringPiece whose value is equal to s.
-Matcher<StringPiece>::Matcher(const char* s) {
-  *this = Eq(internal::string(s));
-}
-
-// Constructs a matcher that matches a StringPiece whose value is equal to s.
-Matcher<StringPiece>::Matcher(StringPiece s) {
-  *this = Eq(s.ToString());
-}
-#endif  // GTEST_HAS_STRING_PIECE_
-
-namespace internal {
-
-// Joins a vector of strings as if they are fields of a tuple; returns
-// the joined string.
-GTEST_API_ string JoinAsTuple(const Strings& fields) {
-  switch (fields.size()) {
-    case 0:
-      return "";
-    case 1:
-      return fields[0];
-    default:
-      string result = "(" + fields[0];
-      for (size_t i = 1; i < fields.size(); i++) {
-        result += ", ";
-        result += fields[i];
-      }
-      result += ")";
-      return result;
-  }
-}
-
-// Returns the description for a matcher defined using the MATCHER*()
-// macro where the user-supplied description string is "", if
-// 'negation' is false; otherwise returns the description of the
-// negation of the matcher.  'param_values' contains a list of strings
-// that are the print-out of the matcher's parameters.
-GTEST_API_ string FormatMatcherDescription(bool negation,
-                                           const char* matcher_name,
-                                           const Strings& param_values) {
-  string result = ConvertIdentifierNameToWords(matcher_name);
-  if (param_values.size() >= 1)
-    result += " " + JoinAsTuple(param_values);
-  return negation ? "not (" + result + ")" : result;
-}
-
-// FindMaxBipartiteMatching and its helper class.
-//
-// Uses the well-known Ford-Fulkerson max flow method to find a maximum
-// bipartite matching. Flow is considered to be from left to right.
-// There is an implicit source node that is connected to all of the left
-// nodes, and an implicit sink node that is connected to all of the
-// right nodes. All edges have unit capacity.
-//
-// Neither the flow graph nor the residual flow graph are represented
-// explicitly. Instead, they are implied by the information in 'graph' and
-// a vector<int> called 'left_' whose elements are initialized to the
-// value kUnused. This represents the initial state of the algorithm,
-// where the flow graph is empty, and the residual flow graph has the
-// following edges:
-//   - An edge from source to each left_ node
-//   - An edge from each right_ node to sink
-//   - An edge from each left_ node to each right_ node, if the
-//     corresponding edge exists in 'graph'.
-//
-// When the TryAugment() method adds a flow, it sets left_[l] = r for some
-// nodes l and r. This induces the following changes:
-//   - The edges (source, l), (l, r), and (r, sink) are added to the
-//     flow graph.
-//   - The same three edges are removed from the residual flow graph.
-//   - The reverse edges (l, source), (r, l), and (sink, r) are added
-//     to the residual flow graph, which is a directional graph
-//     representing unused flow capacity.
-//
-// When the method augments a flow (moving left_[l] from some r1 to some
-// other r2), this can be thought of as "undoing" the above steps with
-// respect to r1 and "redoing" them with respect to r2.
-//
-// It bears repeating that the flow graph and residual flow graph are
-// never represented explicitly, but can be derived by looking at the
-// information in 'graph' and in left_.
-//
-// As an optimization, there is a second vector<int> called right_ which
-// does not provide any new information. Instead, it enables more
-// efficient queries about edges entering or leaving the right-side nodes
-// of the flow or residual flow graphs. The following invariants are
-// maintained:
-//
-// left[l] == kUnused or right[left[l]] == l
-// right[r] == kUnused or left[right[r]] == r
-//
-// . [ source ]                                        .
-// .   |||                                             .
-// .   |||                                             .
-// .   ||\--> left[0]=1  ---\    right[0]=-1 ----\     .
-// .   ||                   |                    |     .
-// .   |\---> left[1]=-1    \--> right[1]=0  ---\|     .
-// .   |                                        ||     .
-// .   \----> left[2]=2  ------> right[2]=2  --\||     .
-// .                                           |||     .
-// .         elements           matchers       vvv     .
-// .                                         [ sink ]  .
-//
-// See Also:
-//   [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
-//       "Introduction to Algorithms (Second ed.)", pp. 651-664.
-//   [2] "Ford-Fulkerson algorithm", Wikipedia,
-//       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
-class MaxBipartiteMatchState {
- public:
-  explicit MaxBipartiteMatchState(const MatchMatrix& graph)
-      : graph_(&graph),
-        left_(graph_->LhsSize(), kUnused),
-        right_(graph_->RhsSize(), kUnused) {
-  }
-
-  // Returns the edges of a maximal match, each in the form {left, right}.
-  ElementMatcherPairs Compute() {
-    // 'seen' is used for path finding { 0: unseen, 1: seen }.
-    ::std::vector<char> seen;
-    // Searches the residual flow graph for a path from each left node to
-    // the sink in the residual flow graph, and if one is found, add flow
-    // to the graph. It's okay to search through the left nodes once. The
-    // edge from the implicit source node to each previously-visited left
-    // node will have flow if that left node has any path to the sink
-    // whatsoever. Subsequent augmentations can only add flow to the
-    // network, and cannot take away that previous flow unit from the source.
-    // Since the source-to-left edge can only carry one flow unit (or,
-    // each element can be matched to only one matcher), there is no need
-    // to visit the left nodes more than once looking for augmented paths.
-    // The flow is known to be possible or impossible by looking at the
-    // node once.
-    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
-      // Reset the path-marking vector and try to find a path from
-      // source to sink starting at the left_[ilhs] node.
-      GTEST_CHECK_(left_[ilhs] == kUnused)
-          << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
-      // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
-      seen.assign(graph_->RhsSize(), 0);
-      TryAugment(ilhs, &seen);
-    }
-    ElementMatcherPairs result;
-    for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
-      size_t irhs = left_[ilhs];
-      if (irhs == kUnused) continue;
-      result.push_back(ElementMatcherPair(ilhs, irhs));
-    }
-    return result;
-  }
-
- private:
-  static const size_t kUnused = static_cast<size_t>(-1);
-
-  // Perform a depth-first search from left node ilhs to the sink.  If a
-  // path is found, flow is added to the network by linking the left and
-  // right vector elements corresponding each segment of the path.
-  // Returns true if a path to sink was found, which means that a unit of
-  // flow was added to the network. The 'seen' vector elements correspond
-  // to right nodes and are marked to eliminate cycles from the search.
-  //
-  // Left nodes will only be explored at most once because they
-  // are accessible from at most one right node in the residual flow
-  // graph.
-  //
-  // Note that left_[ilhs] is the only element of left_ that TryAugment will
-  // potentially transition from kUnused to another value. Any other
-  // left_ element holding kUnused before TryAugment will be holding it
-  // when TryAugment returns.
-  //
-  bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
-    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
-      if ((*seen)[irhs])
-        continue;
-      if (!graph_->HasEdge(ilhs, irhs))
-        continue;
-      // There's an available edge from ilhs to irhs.
-      (*seen)[irhs] = 1;
-      // Next a search is performed to determine whether
-      // this edge is a dead end or leads to the sink.
-      //
-      // right_[irhs] == kUnused means that there is residual flow from
-      // right node irhs to the sink, so we can use that to finish this
-      // flow path and return success.
-      //
-      // Otherwise there is residual flow to some ilhs. We push flow
-      // along that path and call ourselves recursively to see if this
-      // ultimately leads to sink.
-      if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
-        // Add flow from left_[ilhs] to right_[irhs].
-        left_[ilhs] = irhs;
-        right_[irhs] = ilhs;
-        return true;
-      }
-    }
-    return false;
-  }
-
-  const MatchMatrix* graph_;  // not owned
-  // Each element of the left_ vector represents a left hand side node
-  // (i.e. an element) and each element of right_ is a right hand side
-  // node (i.e. a matcher). The values in the left_ vector indicate
-  // outflow from that node to a node on the the right_ side. The values
-  // in the right_ indicate inflow, and specify which left_ node is
-  // feeding that right_ node, if any. For example, left_[3] == 1 means
-  // there's a flow from element #3 to matcher #1. Such a flow would also
-  // be redundantly represented in the right_ vector as right_[1] == 3.
-  // Elements of left_ and right_ are either kUnused or mutually
-  // referent. Mutually referent means that left_[right_[i]] = i and
-  // right_[left_[i]] = i.
-  ::std::vector<size_t> left_;
-  ::std::vector<size_t> right_;
-
-  GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
-};
-
-const size_t MaxBipartiteMatchState::kUnused;
-
-GTEST_API_ ElementMatcherPairs
-FindMaxBipartiteMatching(const MatchMatrix& g) {
-  return MaxBipartiteMatchState(g).Compute();
-}
-
-static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
-                                     ::std::ostream* stream) {
-  typedef ElementMatcherPairs::const_iterator Iter;
-  ::std::ostream& os = *stream;
-  os << "{";
-  const char *sep = "";
-  for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
-    os << sep << "\n  ("
-       << "element #" << it->first << ", "
-       << "matcher #" << it->second << ")";
-    sep = ",";
-  }
-  os << "\n}";
-}
-
-// Tries to find a pairing, and explains the result.
-GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
-                            MatchResultListener* listener) {
-  ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
-
-  size_t max_flow = matches.size();
-  bool result = (max_flow == matrix.RhsSize());
-
-  if (!result) {
-    if (listener->IsInterested()) {
-      *listener << "where no permutation of the elements can "
-                   "satisfy all matchers, and the closest match is "
-                << max_flow << " of " << matrix.RhsSize()
-                << " matchers with the pairings:\n";
-      LogElementMatcherPairVec(matches, listener->stream());
-    }
-    return false;
-  }
-
-  if (matches.size() > 1) {
-    if (listener->IsInterested()) {
-      const char *sep = "where:\n";
-      for (size_t mi = 0; mi < matches.size(); ++mi) {
-        *listener << sep << " - element #" << matches[mi].first
-                  << " is matched by matcher #" << matches[mi].second;
-        sep = ",\n";
-      }
-    }
-  }
-  return true;
-}
-
-bool MatchMatrix::NextGraph() {
-  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
-    for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
-      char& b = matched_[SpaceIndex(ilhs, irhs)];
-      if (!b) {
-        b = 1;
-        return true;
-      }
-      b = 0;
-    }
-  }
-  return false;
-}
-
-void MatchMatrix::Randomize() {
-  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
-    for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
-      char& b = matched_[SpaceIndex(ilhs, irhs)];
-      b = static_cast<char>(rand() & 1);  // NOLINT
-    }
-  }
-}
-
-string MatchMatrix::DebugString() const {
-  ::std::stringstream ss;
-  const char *sep = "";
-  for (size_t i = 0; i < LhsSize(); ++i) {
-    ss << sep;
-    for (size_t j = 0; j < RhsSize(); ++j) {
-      ss << HasEdge(i, j);
-    }
-    sep = ";";
-  }
-  return ss.str();
-}
-
-void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
-    ::std::ostream* os) const {
-  if (matcher_describers_.empty()) {
-    *os << "is empty";
-    return;
-  }
-  if (matcher_describers_.size() == 1) {
-    *os << "has " << Elements(1) << " and that element ";
-    matcher_describers_[0]->DescribeTo(os);
-    return;
-  }
-  *os << "has " << Elements(matcher_describers_.size())
-      << " and there exists some permutation of elements such that:\n";
-  const char* sep = "";
-  for (size_t i = 0; i != matcher_describers_.size(); ++i) {
-    *os << sep << " - element #" << i << " ";
-    matcher_describers_[i]->DescribeTo(os);
-    sep = ", and\n";
-  }
-}
-
-void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
-    ::std::ostream* os) const {
-  if (matcher_describers_.empty()) {
-    *os << "isn't empty";
-    return;
-  }
-  if (matcher_describers_.size() == 1) {
-    *os << "doesn't have " << Elements(1)
-        << ", or has " << Elements(1) << " that ";
-    matcher_describers_[0]->DescribeNegationTo(os);
-    return;
-  }
-  *os << "doesn't have " << Elements(matcher_describers_.size())
-      << ", or there exists no permutation of elements such that:\n";
-  const char* sep = "";
-  for (size_t i = 0; i != matcher_describers_.size(); ++i) {
-    *os << sep << " - element #" << i << " ";
-    matcher_describers_[i]->DescribeTo(os);
-    sep = ", and\n";
-  }
-}
-
-// Checks that all matchers match at least one element, and that all
-// elements match at least one matcher. This enables faster matching
-// and better error reporting.
-// Returns false, writing an explanation to 'listener', if and only
-// if the success criteria are not met.
-bool UnorderedElementsAreMatcherImplBase::
-VerifyAllElementsAndMatchersAreMatched(
-    const ::std::vector<string>& element_printouts,
-    const MatchMatrix& matrix,
-    MatchResultListener* listener) const {
-  bool result = true;
-  ::std::vector<char> element_matched(matrix.LhsSize(), 0);
-  ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
-
-  for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
-    for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
-      char matched = matrix.HasEdge(ilhs, irhs);
-      element_matched[ilhs] |= matched;
-      matcher_matched[irhs] |= matched;
-    }
-  }
-
-  {
-    const char* sep =
-        "where the following matchers don't match any elements:\n";
-    for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
-      if (matcher_matched[mi])
-        continue;
-      result = false;
-      if (listener->IsInterested()) {
-        *listener << sep << "matcher #" << mi << ": ";
-        matcher_describers_[mi]->DescribeTo(listener->stream());
-        sep = ",\n";
-      }
-    }
-  }
-
-  {
-    const char* sep =
-        "where the following elements don't match any matchers:\n";
-    const char* outer_sep = "";
-    if (!result) {
-      outer_sep = "\nand ";
-    }
-    for (size_t ei = 0; ei < element_matched.size(); ++ei) {
-      if (element_matched[ei])
-        continue;
-      result = false;
-      if (listener->IsInterested()) {
-        *listener << outer_sep << sep << "element #" << ei << ": "
-                  << element_printouts[ei];
-        sep = ",\n";
-        outer_sep = "";
-      }
-    }
-  }
-  return result;
-}
-
-}  // namespace internal
-}  // namespace testing
diff --git a/testing/gmock/src/gmock-spec-builders.cc b/testing/gmock/src/gmock-spec-builders.cc
deleted file mode 100644
index 89810ff..0000000
--- a/testing/gmock/src/gmock-spec-builders.cc
+++ /dev/null
@@ -1,830 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file implements the spec builder syntax (ON_CALL and
-// EXPECT_CALL).
-
-#include "gmock/gmock-spec-builders.h"
-
-#if !GTEST_OS_STARBOARD
-#include <stdlib.h>
-#endif  // !GTEST_OS_STARBOARD
-
-#include <iostream>  // NOLINT
-#include <map>
-#include <set>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
-# include <unistd.h>  // NOLINT
-#endif
-
-namespace testing {
-namespace internal {
-
-// Protects the mock object registry (in class Mock), all function
-// mockers, and all expectations.
-GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
-
-// Logs a message including file and line number information.
-GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
-                                const char* file, int line,
-                                const string& message) {
-  ::std::ostringstream s;
-  s << file << ":" << line << ": " << message << ::std::endl;
-  Log(severity, s.str(), 0);
-}
-
-// Constructs an ExpectationBase object.
-ExpectationBase::ExpectationBase(const char* a_file,
-                                 int a_line,
-                                 const string& a_source_text)
-    : file_(a_file),
-      line_(a_line),
-      source_text_(a_source_text),
-      cardinality_specified_(false),
-      cardinality_(Exactly(1)),
-      call_count_(0),
-      retired_(false),
-      extra_matcher_specified_(false),
-      repeated_action_specified_(false),
-      retires_on_saturation_(false),
-      last_clause_(kNone),
-      action_count_checked_(false) {}
-
-// Destructs an ExpectationBase object.
-ExpectationBase::~ExpectationBase() {}
-
-// Explicitly specifies the cardinality of this expectation.  Used by
-// the subclasses to implement the .Times() clause.
-void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
-  cardinality_specified_ = true;
-  cardinality_ = a_cardinality;
-}
-
-// Retires all pre-requisites of this expectation.
-void ExpectationBase::RetireAllPreRequisites()
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-  if (is_retired()) {
-    // We can take this short-cut as we never retire an expectation
-    // until we have retired all its pre-requisites.
-    return;
-  }
-
-  for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
-       it != immediate_prerequisites_.end(); ++it) {
-    ExpectationBase* const prerequisite = it->expectation_base().get();
-    if (!prerequisite->is_retired()) {
-      prerequisite->RetireAllPreRequisites();
-      prerequisite->Retire();
-    }
-  }
-}
-
-// Returns true iff all pre-requisites of this expectation have been
-// satisfied.
-bool ExpectationBase::AllPrerequisitesAreSatisfied() const
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-  g_gmock_mutex.AssertHeld();
-  for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
-       it != immediate_prerequisites_.end(); ++it) {
-    if (!(it->expectation_base()->IsSatisfied()) ||
-        !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
-      return false;
-  }
-  return true;
-}
-
-// Adds unsatisfied pre-requisites of this expectation to 'result'.
-void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-  g_gmock_mutex.AssertHeld();
-  for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
-       it != immediate_prerequisites_.end(); ++it) {
-    if (it->expectation_base()->IsSatisfied()) {
-      // If *it is satisfied and has a call count of 0, some of its
-      // pre-requisites may not be satisfied yet.
-      if (it->expectation_base()->call_count_ == 0) {
-        it->expectation_base()->FindUnsatisfiedPrerequisites(result);
-      }
-    } else {
-      // Now that we know *it is unsatisfied, we are not so interested
-      // in whether its pre-requisites are satisfied.  Therefore we
-      // don't recursively call FindUnsatisfiedPrerequisites() here.
-      *result += *it;
-    }
-  }
-}
-
-// Describes how many times a function call matching this
-// expectation has occurred.
-void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-  g_gmock_mutex.AssertHeld();
-
-  // Describes how many times the function is expected to be called.
-  *os << "         Expected: to be ";
-  cardinality().DescribeTo(os);
-  *os << "\n           Actual: ";
-  Cardinality::DescribeActualCallCountTo(call_count(), os);
-
-  // Describes the state of the expectation (e.g. is it satisfied?
-  // is it active?).
-  *os << " - " << (IsOverSaturated() ? "over-saturated" :
-                   IsSaturated() ? "saturated" :
-                   IsSatisfied() ? "satisfied" : "unsatisfied")
-      << " and "
-      << (is_retired() ? "retired" : "active");
-}
-
-// Checks the action count (i.e. the number of WillOnce() and
-// WillRepeatedly() clauses) against the cardinality if this hasn't
-// been done before.  Prints a warning if there are too many or too
-// few actions.
-void ExpectationBase::CheckActionCountIfNotDone() const
-    GTEST_LOCK_EXCLUDED_(mutex_) {
-  bool should_check = false;
-  {
-    MutexLock l(&mutex_);
-    if (!action_count_checked_) {
-      action_count_checked_ = true;
-      should_check = true;
-    }
-  }
-
-  if (should_check) {
-    if (!cardinality_specified_) {
-      // The cardinality was inferred - no need to check the action
-      // count against it.
-      return;
-    }
-
-    // The cardinality was explicitly specified.
-    const int action_count = static_cast<int>(untyped_actions_.size());
-    const int upper_bound = cardinality().ConservativeUpperBound();
-    const int lower_bound = cardinality().ConservativeLowerBound();
-    bool too_many;  // True if there are too many actions, or false
-    // if there are too few.
-    if (action_count > upper_bound ||
-        (action_count == upper_bound && repeated_action_specified_)) {
-      too_many = true;
-    } else if (0 < action_count && action_count < lower_bound &&
-               !repeated_action_specified_) {
-      too_many = false;
-    } else {
-      return;
-    }
-
-    ::std::stringstream ss;
-    DescribeLocationTo(&ss);
-    ss << "Too " << (too_many ? "many" : "few")
-       << " actions specified in " << source_text() << "...\n"
-       << "Expected to be ";
-    cardinality().DescribeTo(&ss);
-    ss << ", but has " << (too_many ? "" : "only ")
-       << action_count << " WillOnce()"
-       << (action_count == 1 ? "" : "s");
-    if (repeated_action_specified_) {
-      ss << " and a WillRepeatedly()";
-    }
-    ss << ".";
-    Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
-  }
-}
-
-// Implements the .Times() clause.
-void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
-  if (last_clause_ == kTimes) {
-    ExpectSpecProperty(false,
-                       ".Times() cannot appear "
-                       "more than once in an EXPECT_CALL().");
-  } else {
-    ExpectSpecProperty(last_clause_ < kTimes,
-                       ".Times() cannot appear after "
-                       ".InSequence(), .WillOnce(), .WillRepeatedly(), "
-                       "or .RetiresOnSaturation().");
-  }
-  last_clause_ = kTimes;
-
-  SpecifyCardinality(a_cardinality);
-}
-
-// Points to the implicit sequence introduced by a living InSequence
-// object (if any) in the current thread or NULL.
-GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
-
-// Reports an uninteresting call (whose description is in msg) in the
-// manner specified by 'reaction'.
-void ReportUninterestingCall(CallReaction reaction, const string& msg) {
-  // Include a stack trace only if --gmock_verbose=info is specified.
-  const int stack_frames_to_skip =
-      GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
-  switch (reaction) {
-    case kAllow:
-      Log(kInfo, msg, stack_frames_to_skip);
-      break;
-    case kWarn:
-      Log(kWarning,
-          msg +
-          "\nNOTE: You can safely ignore the above warning unless this "
-          "call should not happen.  Do not suppress it by blindly adding "
-          "an EXPECT_CALL() if you don't mean to enforce the call.  "
-          "See http://code.google.com/p/googlemock/wiki/CookBook#"
-          "Knowing_When_to_Expect for details.\n",
-          stack_frames_to_skip);
-      break;
-    default:  // FAIL
-      Expect(false, NULL, -1, msg);
-  }
-}
-
-UntypedFunctionMockerBase::UntypedFunctionMockerBase()
-    : mock_obj_(NULL), name_("") {}
-
-UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
-
-// Sets the mock object this mock method belongs to, and registers
-// this information in the global mock registry.  Will be called
-// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
-// method.
-void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-  {
-    MutexLock l(&g_gmock_mutex);
-    mock_obj_ = mock_obj;
-  }
-  Mock::Register(mock_obj, this);
-}
-
-// Sets the mock object this mock method belongs to, and sets the name
-// of the mock function.  Will be called upon each invocation of this
-// mock function.
-void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
-                                                const char* name)
-    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-  // We protect name_ under g_gmock_mutex in case this mock function
-  // is called from two threads concurrently.
-  MutexLock l(&g_gmock_mutex);
-  mock_obj_ = mock_obj;
-  name_ = name;
-}
-
-// Returns the name of the function being mocked.  Must be called
-// after RegisterOwner() or SetOwnerAndName() has been called.
-const void* UntypedFunctionMockerBase::MockObject() const
-    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-  const void* mock_obj;
-  {
-    // We protect mock_obj_ under g_gmock_mutex in case this mock
-    // function is called from two threads concurrently.
-    MutexLock l(&g_gmock_mutex);
-    Assert(mock_obj_ != NULL, __FILE__, __LINE__,
-           "MockObject() must not be called before RegisterOwner() or "
-           "SetOwnerAndName() has been called.");
-    mock_obj = mock_obj_;
-  }
-  return mock_obj;
-}
-
-// Returns the name of this mock method.  Must be called after
-// SetOwnerAndName() has been called.
-const char* UntypedFunctionMockerBase::Name() const
-    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-  const char* name;
-  {
-    // We protect name_ under g_gmock_mutex in case this mock
-    // function is called from two threads concurrently.
-    MutexLock l(&g_gmock_mutex);
-    Assert(name_ != NULL, __FILE__, __LINE__,
-           "Name() must not be called before SetOwnerAndName() has "
-           "been called.");
-    name = name_;
-  }
-  return name;
-}
-
-// Calculates the result of invoking this mock function with the given
-// arguments, prints it, and returns it.  The caller is responsible
-// for deleting the result.
-UntypedActionResultHolderBase*
-UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
-    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-  if (untyped_expectations_.size() == 0) {
-    // No expectation is set on this mock method - we have an
-    // uninteresting call.
-
-    // We must get Google Mock's reaction on uninteresting calls
-    // made on this mock object BEFORE performing the action,
-    // because the action may DELETE the mock object and make the
-    // following expression meaningless.
-    const CallReaction reaction =
-        Mock::GetReactionOnUninterestingCalls(MockObject());
-
-    // True iff we need to print this call's arguments and return
-    // value.  This definition must be kept in sync with
-    // the behavior of ReportUninterestingCall().
-    const bool need_to_report_uninteresting_call =
-        // If the user allows this uninteresting call, we print it
-        // only when he wants informational messages.
-        reaction == kAllow ? LogIsVisible(kInfo) :
-        // If the user wants this to be a warning, we print it only
-        // when he wants to see warnings.
-        reaction == kWarn ? LogIsVisible(kWarning) :
-        // Otherwise, the user wants this to be an error, and we
-        // should always print detailed information in the error.
-        true;
-
-    if (!need_to_report_uninteresting_call) {
-      // Perform the action without printing the call information.
-      return this->UntypedPerformDefaultAction(untyped_args, "");
-    }
-
-    // Warns about the uninteresting call.
-    ::std::stringstream ss;
-    this->UntypedDescribeUninterestingCall(untyped_args, &ss);
-
-    // Calculates the function result.
-    UntypedActionResultHolderBase* const result =
-        this->UntypedPerformDefaultAction(untyped_args, ss.str());
-
-    // Prints the function result.
-    if (result != NULL)
-      result->PrintAsActionResult(&ss);
-
-    ReportUninterestingCall(reaction, ss.str());
-    return result;
-  }
-
-  bool is_excessive = false;
-  ::std::stringstream ss;
-  ::std::stringstream why;
-  ::std::stringstream loc;
-  const void* untyped_action = NULL;
-
-  // The UntypedFindMatchingExpectation() function acquires and
-  // releases g_gmock_mutex.
-  const ExpectationBase* const untyped_expectation =
-      this->UntypedFindMatchingExpectation(
-          untyped_args, &untyped_action, &is_excessive,
-          &ss, &why);
-  const bool found = untyped_expectation != NULL;
-
-  // True iff we need to print the call's arguments and return value.
-  // This definition must be kept in sync with the uses of Expect()
-  // and Log() in this function.
-  const bool need_to_report_call =
-      !found || is_excessive || LogIsVisible(kInfo);
-  if (!need_to_report_call) {
-    // Perform the action without printing the call information.
-    return
-        untyped_action == NULL ?
-        this->UntypedPerformDefaultAction(untyped_args, "") :
-        this->UntypedPerformAction(untyped_action, untyped_args);
-  }
-
-  ss << "    Function call: " << Name();
-  this->UntypedPrintArgs(untyped_args, &ss);
-
-  // In case the action deletes a piece of the expectation, we
-  // generate the message beforehand.
-  if (found && !is_excessive) {
-    untyped_expectation->DescribeLocationTo(&loc);
-  }
-
-  UntypedActionResultHolderBase* const result =
-      untyped_action == NULL ?
-      this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
-      this->UntypedPerformAction(untyped_action, untyped_args);
-  if (result != NULL)
-    result->PrintAsActionResult(&ss);
-  ss << "\n" << why.str();
-
-  if (!found) {
-    // No expectation matches this call - reports a failure.
-    Expect(false, NULL, -1, ss.str());
-  } else if (is_excessive) {
-    // We had an upper-bound violation and the failure message is in ss.
-    Expect(false, untyped_expectation->file(),
-           untyped_expectation->line(), ss.str());
-  } else {
-    // We had an expected call and the matching expectation is
-    // described in ss.
-    Log(kInfo, loc.str() + ss.str(), 2);
-  }
-
-  return result;
-}
-
-// Returns an Expectation object that references and co-owns exp,
-// which must be an expectation on this mock function.
-Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
-  for (UntypedExpectations::const_iterator it =
-           untyped_expectations_.begin();
-       it != untyped_expectations_.end(); ++it) {
-    if (it->get() == exp) {
-      return Expectation(*it);
-    }
-  }
-
-  Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
-  return Expectation();
-  // The above statement is just to make the code compile, and will
-  // never be executed.
-}
-
-// Verifies that all expectations on this mock function have been
-// satisfied.  Reports one or more Google Test non-fatal failures
-// and returns false if not.
-bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
-  g_gmock_mutex.AssertHeld();
-  bool expectations_met = true;
-  for (UntypedExpectations::const_iterator it =
-           untyped_expectations_.begin();
-       it != untyped_expectations_.end(); ++it) {
-    ExpectationBase* const untyped_expectation = it->get();
-    if (untyped_expectation->IsOverSaturated()) {
-      // There was an upper-bound violation.  Since the error was
-      // already reported when it occurred, there is no need to do
-      // anything here.
-      expectations_met = false;
-    } else if (!untyped_expectation->IsSatisfied()) {
-      expectations_met = false;
-      ::std::stringstream ss;
-      ss  << "Actual function call count doesn't match "
-          << untyped_expectation->source_text() << "...\n";
-      // No need to show the source file location of the expectation
-      // in the description, as the Expect() call that follows already
-      // takes care of it.
-      untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
-      untyped_expectation->DescribeCallCountTo(&ss);
-      Expect(false, untyped_expectation->file(),
-             untyped_expectation->line(), ss.str());
-    }
-  }
-
-  // Deleting our expectations may trigger other mock objects to be deleted, for
-  // example if an action contains a reference counted smart pointer to that
-  // mock object, and that is the last reference. So if we delete our
-  // expectations within the context of the global mutex we may deadlock when
-  // this method is called again. Instead, make a copy of the set of
-  // expectations to delete, clear our set within the mutex, and then clear the
-  // copied set outside of it.
-  UntypedExpectations expectations_to_delete;
-  untyped_expectations_.swap(expectations_to_delete);
-
-  g_gmock_mutex.Unlock();
-  expectations_to_delete.clear();
-  g_gmock_mutex.Lock();
-
-  return expectations_met;
-}
-
-}  // namespace internal
-
-// Class Mock.
-
-namespace {
-
-typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
-
-// The current state of a mock object.  Such information is needed for
-// detecting leaked mock objects and explicitly verifying a mock's
-// expectations.
-struct MockObjectState {
-  MockObjectState()
-      : first_used_file(NULL), first_used_line(-1), leakable(false) {}
-
-  // Where in the source file an ON_CALL or EXPECT_CALL is first
-  // invoked on this mock object.
-  const char* first_used_file;
-  int first_used_line;
-  ::std::string first_used_test_case;
-  ::std::string first_used_test;
-  bool leakable;  // true iff it's OK to leak the object.
-  FunctionMockers function_mockers;  // All registered methods of the object.
-};
-
-// A global registry holding the state of all mock objects that are
-// alive.  A mock object is added to this registry the first time
-// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
-// is removed from the registry in the mock object's destructor.
-class MockObjectRegistry {
- public:
-  // Maps a mock object (identified by its address) to its state.
-  typedef std::map<const void*, MockObjectState> StateMap;
-
-  // This destructor will be called when a program exits, after all
-  // tests in it have been run.  By then, there should be no mock
-  // object alive.  Therefore we report any living object as test
-  // failure, unless the user explicitly asked us to ignore it.
-  ~MockObjectRegistry() {
-    // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
-    // a macro.
-
-    if (!GMOCK_FLAG(catch_leaked_mocks))
-      return;
-
-    int leaked_count = 0;
-    for (StateMap::const_iterator it = states_.begin(); it != states_.end();
-         ++it) {
-      if (it->second.leakable)  // The user said it's fine to leak this object.
-        continue;
-
-      // TODO(wan@google.com): Print the type of the leaked object.
-      // This can help the user identify the leaked object.
-      std::cout << "\n";
-      const MockObjectState& state = it->second;
-      std::cout << internal::FormatFileLocation(state.first_used_file,
-                                                state.first_used_line);
-      std::cout << " ERROR: this mock object";
-      if (state.first_used_test != "") {
-        std::cout << " (used in test " << state.first_used_test_case << "."
-             << state.first_used_test << ")";
-      }
-      std::cout << " should be deleted but never is. Its address is @"
-           << it->first << ".";
-      leaked_count++;
-    }
-    if (leaked_count > 0) {
-      std::cout << "\nERROR: " << leaked_count
-           << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
-           << " found at program exit.\n";
-      std::cout.flush();
-      ::std::cerr.flush();
-      // RUN_ALL_TESTS() has already returned when this destructor is
-      // called.  Therefore we cannot use the normal Google Test
-      // failure reporting mechanism.
-#if GTEST_OS_STARBOARD
-      internal::posix::Abort();
-#else
-      _exit(1);  // We cannot call exit() as it is not reentrant and
-                 // may already have been called.
-#endif
-    }
-  }
-
-  StateMap& states() { return states_; }
-
- private:
-  StateMap states_;
-};
-
-// Protected by g_gmock_mutex.
-MockObjectRegistry g_mock_object_registry;
-
-// Maps a mock object to the reaction Google Mock should have when an
-// uninteresting method is called.  Protected by g_gmock_mutex.
-std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
-
-// Sets the reaction Google Mock should have when an uninteresting
-// method of the given mock object is called.
-void SetReactionOnUninterestingCalls(const void* mock_obj,
-                                     internal::CallReaction reaction)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  g_uninteresting_call_reaction[mock_obj] = reaction;
-}
-
-}  // namespace
-
-// Tells Google Mock to allow uninteresting calls on the given mock
-// object.
-void Mock::AllowUninterestingCalls(const void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
-}
-
-// Tells Google Mock to warn the user about uninteresting calls on the
-// given mock object.
-void Mock::WarnUninterestingCalls(const void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
-}
-
-// Tells Google Mock to fail uninteresting calls on the given mock
-// object.
-void Mock::FailUninterestingCalls(const void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
-}
-
-// Tells Google Mock the given mock object is being destroyed and its
-// entry in the call-reaction table should be removed.
-void Mock::UnregisterCallReaction(const void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  g_uninteresting_call_reaction.erase(mock_obj);
-}
-
-// Returns the reaction Google Mock will have on uninteresting calls
-// made on the given mock object.
-internal::CallReaction Mock::GetReactionOnUninterestingCalls(
-    const void* mock_obj)
-        GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
-      internal::kDefault : g_uninteresting_call_reaction[mock_obj];
-}
-
-// Tells Google Mock to ignore mock_obj when checking for leaked mock
-// objects.
-void Mock::AllowLeak(const void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  g_mock_object_registry.states()[mock_obj].leakable = true;
-}
-
-// Verifies and clears all expectations on the given mock object.  If
-// the expectations aren't satisfied, generates one or more Google
-// Test non-fatal failures and returns false.
-bool Mock::VerifyAndClearExpectations(void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  return VerifyAndClearExpectationsLocked(mock_obj);
-}
-
-// Verifies all expectations on the given mock object and clears its
-// default actions and expectations.  Returns true iff the
-// verification was successful.
-bool Mock::VerifyAndClear(void* mock_obj)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  ClearDefaultActionsLocked(mock_obj);
-  return VerifyAndClearExpectationsLocked(mock_obj);
-}
-
-// Verifies and clears all expectations on the given mock object.  If
-// the expectations aren't satisfied, generates one or more Google
-// Test non-fatal failures and returns false.
-bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
-  internal::g_gmock_mutex.AssertHeld();
-  if (g_mock_object_registry.states().count(mock_obj) == 0) {
-    // No EXPECT_CALL() was set on the given mock object.
-    return true;
-  }
-
-  // Verifies and clears the expectations on each mock method in the
-  // given mock object.
-  bool expectations_met = true;
-  FunctionMockers& mockers =
-      g_mock_object_registry.states()[mock_obj].function_mockers;
-  for (FunctionMockers::const_iterator it = mockers.begin();
-       it != mockers.end(); ++it) {
-    if (!(*it)->VerifyAndClearExpectationsLocked()) {
-      expectations_met = false;
-    }
-  }
-
-  // We don't clear the content of mockers, as they may still be
-  // needed by ClearDefaultActionsLocked().
-  return expectations_met;
-}
-
-// Registers a mock object and a mock method it owns.
-void Mock::Register(const void* mock_obj,
-                    internal::UntypedFunctionMockerBase* mocker)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
-}
-
-// Tells Google Mock where in the source code mock_obj is used in an
-// ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
-// information helps the user identify which object it is.
-void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
-                                           const char* file, int line)
-    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
-  internal::MutexLock l(&internal::g_gmock_mutex);
-  MockObjectState& state = g_mock_object_registry.states()[mock_obj];
-  if (state.first_used_file == NULL) {
-    state.first_used_file = file;
-    state.first_used_line = line;
-    const TestInfo* const test_info =
-        UnitTest::GetInstance()->current_test_info();
-    if (test_info != NULL) {
-      // TODO(wan@google.com): record the test case name when the
-      // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
-      // TearDownTestCase().
-      state.first_used_test_case = test_info->test_case_name();
-      state.first_used_test = test_info->name();
-    }
-  }
-}
-
-// Unregisters a mock method; removes the owning mock object from the
-// registry when the last mock method associated with it has been
-// unregistered.  This is called only in the destructor of
-// FunctionMockerBase.
-void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
-  internal::g_gmock_mutex.AssertHeld();
-  for (MockObjectRegistry::StateMap::iterator it =
-           g_mock_object_registry.states().begin();
-       it != g_mock_object_registry.states().end(); ++it) {
-    FunctionMockers& mockers = it->second.function_mockers;
-    if (mockers.erase(mocker) > 0) {
-      // mocker was in mockers and has been just removed.
-      if (mockers.empty()) {
-        g_mock_object_registry.states().erase(it);
-      }
-      return;
-    }
-  }
-}
-
-// Clears all ON_CALL()s set on the given mock object.
-void Mock::ClearDefaultActionsLocked(void* mock_obj)
-    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
-  internal::g_gmock_mutex.AssertHeld();
-
-  if (g_mock_object_registry.states().count(mock_obj) == 0) {
-    // No ON_CALL() was set on the given mock object.
-    return;
-  }
-
-  // Clears the default actions for each mock method in the given mock
-  // object.
-  FunctionMockers& mockers =
-      g_mock_object_registry.states()[mock_obj].function_mockers;
-  for (FunctionMockers::const_iterator it = mockers.begin();
-       it != mockers.end(); ++it) {
-    (*it)->ClearDefaultActionsLocked();
-  }
-
-  // We don't clear the content of mockers, as they may still be
-  // needed by VerifyAndClearExpectationsLocked().
-}
-
-Expectation::Expectation() {}
-
-Expectation::Expectation(
-    const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
-    : expectation_base_(an_expectation_base) {}
-
-Expectation::~Expectation() {}
-
-// Adds an expectation to a sequence.
-void Sequence::AddExpectation(const Expectation& expectation) const {
-  if (*last_expectation_ != expectation) {
-    if (last_expectation_->expectation_base() != NULL) {
-      expectation.expectation_base()->immediate_prerequisites_
-          += *last_expectation_;
-    }
-    *last_expectation_ = expectation;
-  }
-}
-
-// Creates the implicit sequence if there isn't one.
-InSequence::InSequence() {
-  if (internal::g_gmock_implicit_sequence.get() == NULL) {
-    internal::g_gmock_implicit_sequence.set(new Sequence);
-    sequence_created_ = true;
-  } else {
-    sequence_created_ = false;
-  }
-}
-
-// Deletes the implicit sequence if it was created by the constructor
-// of this object.
-InSequence::~InSequence() {
-  if (sequence_created_) {
-    delete internal::g_gmock_implicit_sequence.get();
-    internal::g_gmock_implicit_sequence.set(NULL);
-  }
-}
-
-}  // namespace testing
diff --git a/testing/gmock/src/gmock.cc b/testing/gmock/src/gmock.cc
deleted file mode 100644
index dcc6daf..0000000
--- a/testing/gmock/src/gmock.cc
+++ /dev/null
@@ -1,184 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-#include "gmock/gmock.h"
-#include "gmock/internal/gmock-port.h"
-
-namespace testing {
-
-// TODO(wan@google.com): support using environment variables to
-// control the flag values, like what Google Test does.
-
-GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
-                   "true iff Google Mock should report leaked mock objects "
-                   "as failures.");
-
-GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
-                     "Controls how verbose Google Mock's output is."
-                     "  Valid values:\n"
-                     "  info    - prints all messages.\n"
-                     "  warning - prints warnings and errors.\n"
-                     "  error   - prints errors only.");
-
-namespace internal {
-
-// Parses a string as a command line flag.  The string should have the
-// format "--gmock_flag=value".  When def_optional is true, the
-// "=value" part can be omitted.
-//
-// Returns the value of the flag, or NULL if the parsing failed.
-static const char* ParseGoogleMockFlagValue(const char* str,
-                                            const char* flag,
-                                            bool def_optional) {
-  // str and flag must not be NULL.
-  if (str == NULL || flag == NULL) return NULL;
-
-  // The flag must start with "--gmock_".
-  const std::string flag_str = std::string("--gmock_") + flag;
-  const size_t flag_len = flag_str.length();
-  if (internal::posix::StrNCmp(str, flag_str.c_str(), flag_len) != 0)
-    return NULL;
-
-  // Skips the flag name.
-  const char* flag_end = str + flag_len;
-
-  // When def_optional is true, it's OK to not have a "=value" part.
-  if (def_optional && (flag_end[0] == '\0')) {
-    return flag_end;
-  }
-
-  // If def_optional is true and there are more characters after the
-  // flag name, or if def_optional is false, there must be a '=' after
-  // the flag name.
-  if (flag_end[0] != '=') return NULL;
-
-  // Returns the string after "=".
-  return flag_end + 1;
-}
-
-// Parses a string for a Google Mock bool flag, in the form of
-// "--gmock_flag=value".
-//
-// On success, stores the value of the flag in *value, and returns
-// true.  On failure, returns false without changing *value.
-static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
-                                    bool* value) {
-  // Gets the value of the flag as a string.
-  const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
-
-  // Aborts if the parsing failed.
-  if (value_str == NULL) return false;
-
-  // Converts the string value to a bool.
-  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
-  return true;
-}
-
-// Parses a string for a Google Mock string flag, in the form of
-// "--gmock_flag=value".
-//
-// On success, stores the value of the flag in *value, and returns
-// true.  On failure, returns false without changing *value.
-template <typename String>
-static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
-                                      String* value) {
-  // Gets the value of the flag as a string.
-  const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
-
-  // Aborts if the parsing failed.
-  if (value_str == NULL) return false;
-
-  // Sets *value to the value of the flag.
-  *value = value_str;
-  return true;
-}
-
-// The internal implementation of InitGoogleMock().
-//
-// The type parameter CharType can be instantiated to either char or
-// wchar_t.
-template <typename CharType>
-void InitGoogleMockImpl(int* argc, CharType** argv) {
-  // Makes sure Google Test is initialized.  InitGoogleTest() is
-  // idempotent, so it's fine if the user has already called it.
-  InitGoogleTest(argc, argv);
-  if (*argc <= 0) return;
-
-  for (int i = 1; i != *argc; i++) {
-    const std::string arg_string = StreamableToString(argv[i]);
-    const char* const arg = arg_string.c_str();
-
-    // Do we see a Google Mock flag?
-    if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
-                                &GMOCK_FLAG(catch_leaked_mocks)) ||
-        ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
-      // Yes.  Shift the remainder of the argv list left by one.  Note
-      // that argv has (*argc + 1) elements, the last one always being
-      // NULL.  The following loop moves the trailing NULL element as
-      // well.
-      for (int j = i; j != *argc; j++) {
-        argv[j] = argv[j + 1];
-      }
-
-      // Decrements the argument count.
-      (*argc)--;
-
-      // We also need to decrement the iterator as we just removed
-      // an element.
-      i--;
-    }
-  }
-}
-
-}  // namespace internal
-
-// Initializes Google Mock.  This must be called before running the
-// tests.  In particular, it parses a command line for the flags that
-// Google Mock recognizes.  Whenever a Google Mock flag is seen, it is
-// removed from argv, and *argc is decremented.
-//
-// No value is returned.  Instead, the Google Mock flag variables are
-// updated.
-//
-// Since Google Test is needed for Google Mock to work, this function
-// also initializes Google Test and parses its flags, if that hasn't
-// been done.
-GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
-  internal::InitGoogleMockImpl(argc, argv);
-}
-
-// This overloaded version can be used in Windows programs compiled in
-// UNICODE mode.
-GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
-  internal::InitGoogleMockImpl(argc, argv);
-}
-
-}  // namespace testing
diff --git a/testing/gmock/src/gmock_main.cc b/testing/gmock/src/gmock_main.cc
deleted file mode 100644
index bd5be03..0000000
--- a/testing/gmock/src/gmock_main.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-#include <iostream>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which
-// causes a link error when _tmain is defined in a static library and UNICODE
-// is enabled. For this reason instead of _tmain, main function is used on
-// Windows. See the following link to track the current status of this bug:
-// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464  // NOLINT
-#if GTEST_OS_WINDOWS_MOBILE
-# include <tchar.h>  // NOLINT
-
-GTEST_API_ int _tmain(int argc, TCHAR** argv) {
-#else
-GTEST_API_ int main(int argc, char** argv) {
-#endif  // GTEST_OS_WINDOWS_MOBILE
-  std::cout << "Running main() from gmock_main.cc\n";
-  // Since Google Mock depends on Google Test, InitGoogleMock() is
-  // also responsible for initializing Google Test.  Therefore there's
-  // no need for calling testing::InitGoogleTest() separately.
-  testing::InitGoogleMock(&argc, argv);
-  return RUN_ALL_TESTS();
-}
diff --git a/testing/gmock/test/gmock-actions_test.cc b/testing/gmock/test/gmock-actions_test.cc
deleted file mode 100644
index a665fc5..0000000
--- a/testing/gmock/test/gmock-actions_test.cc
+++ /dev/null
@@ -1,1411 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in actions.
-
-#include "gmock/gmock-actions.h"
-#include <algorithm>
-#include <iterator>
-#include <memory>
-#include <string>
-#include "gmock/gmock.h"
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-namespace {
-
-// This list should be kept sorted.
-using testing::Action;
-using testing::ActionInterface;
-using testing::Assign;
-using testing::ByMove;
-using testing::ByRef;
-using testing::DefaultValue;
-using testing::DoDefault;
-using testing::IgnoreResult;
-using testing::Invoke;
-using testing::InvokeWithoutArgs;
-using testing::MakePolymorphicAction;
-using testing::Ne;
-using testing::PolymorphicAction;
-using testing::Return;
-using testing::ReturnNull;
-using testing::ReturnRef;
-using testing::ReturnRefOfCopy;
-using testing::SetArgPointee;
-using testing::SetArgumentPointee;
-using testing::_;
-using testing::get;
-using testing::internal::BuiltInDefaultValue;
-using testing::internal::Int64;
-using testing::internal::UInt64;
-using testing::make_tuple;
-using testing::tuple;
-using testing::tuple_element;
-
-#if !GTEST_OS_WINDOWS_MOBILE
-using testing::SetErrnoAndReturn;
-#endif
-
-#if GTEST_HAS_PROTOBUF_
-using testing::internal::TestMessage;
-#endif  // GTEST_HAS_PROTOBUF_
-
-// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
-TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
-  EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
-  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
-  EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
-}
-
-// Tests that BuiltInDefaultValue<T*>::Exists() return true.
-TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
-  EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
-}
-
-// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
-// built-in numeric type.
-TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
-  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
-#if GMOCK_HAS_SIGNED_WCHAR_T_
-  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
-#endif
-#if GMOCK_WCHAR_T_IS_NATIVE_
-  EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
-#endif
-  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());  // NOLINT
-  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
-  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());  // NOLINT
-  EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
-}
-
-// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
-// built-in numeric type.
-TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
-  EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
-#if GMOCK_HAS_SIGNED_WCHAR_T_
-  EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
-#endif
-#if GMOCK_WCHAR_T_IS_NATIVE_
-  EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
-#endif
-  EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
-}
-
-// Tests that BuiltInDefaultValue<bool>::Get() returns false.
-TEST(BuiltInDefaultValueTest, IsFalseForBool) {
-  EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
-}
-
-// Tests that BuiltInDefaultValue<bool>::Exists() returns true.
-TEST(BuiltInDefaultValueTest, BoolExists) {
-  EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
-}
-
-// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
-// string type.
-TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
-#if GTEST_HAS_GLOBAL_STRING
-  EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-  EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
-}
-
-// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
-// string type.
-TEST(BuiltInDefaultValueTest, ExistsForString) {
-#if GTEST_HAS_GLOBAL_STRING
-  EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-  EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
-}
-
-// Tests that BuiltInDefaultValue<const T>::Get() returns the same
-// value as BuiltInDefaultValue<T>::Get() does.
-TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
-  EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
-  EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
-  EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL);
-  EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
-}
-
-// A type that's default constructible.
-class MyDefaultConstructible {
- public:
-  MyDefaultConstructible() : value_(42) {}
-
-  int value() const { return value_; }
-
- private:
-  int value_;
-};
-
-// A type that's not default constructible.
-class MyNonDefaultConstructible {
- public:
-  // Does not have a default ctor.
-  explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
-
- private:
-  int value_;
-};
-
-#if GTEST_LANG_CXX11
-
-TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
-  EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
-}
-
-TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
-  EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
-}
-
-#endif  // GTEST_LANG_CXX11
-
-TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
-  EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
-}
-
-// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
-TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
-  EXPECT_DEATH_IF_SUPPORTED({
-    BuiltInDefaultValue<int&>::Get();
-  }, "");
-  EXPECT_DEATH_IF_SUPPORTED({
-    BuiltInDefaultValue<const char&>::Get();
-  }, "");
-}
-
-TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
-  EXPECT_DEATH_IF_SUPPORTED({
-    BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
-  }, "");
-}
-
-// Tests that DefaultValue<T>::IsSet() is false initially.
-TEST(DefaultValueTest, IsInitiallyUnset) {
-  EXPECT_FALSE(DefaultValue<int>::IsSet());
-  EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
-  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
-}
-
-// Tests that DefaultValue<T> can be set and then unset.
-TEST(DefaultValueTest, CanBeSetAndUnset) {
-  EXPECT_TRUE(DefaultValue<int>::Exists());
-  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
-
-  DefaultValue<int>::Set(1);
-  DefaultValue<const MyNonDefaultConstructible>::Set(
-      MyNonDefaultConstructible(42));
-
-  EXPECT_EQ(1, DefaultValue<int>::Get());
-  EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
-
-  EXPECT_TRUE(DefaultValue<int>::Exists());
-  EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
-
-  DefaultValue<int>::Clear();
-  DefaultValue<const MyNonDefaultConstructible>::Clear();
-
-  EXPECT_FALSE(DefaultValue<int>::IsSet());
-  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
-
-  EXPECT_TRUE(DefaultValue<int>::Exists());
-  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
-}
-
-// Tests that DefaultValue<T>::Get() returns the
-// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
-// false.
-TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
-  EXPECT_FALSE(DefaultValue<int>::IsSet());
-  EXPECT_TRUE(DefaultValue<int>::Exists());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
-
-  EXPECT_EQ(0, DefaultValue<int>::Get());
-
-  EXPECT_DEATH_IF_SUPPORTED({
-    DefaultValue<MyNonDefaultConstructible>::Get();
-  }, "");
-}
-
-#if GTEST_HAS_STD_UNIQUE_PTR_
-TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
-  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
-  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL);
-  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
-    return std::unique_ptr<int>(new int(42));
-  });
-  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
-  std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
-  EXPECT_EQ(42, *i);
-}
-#endif  // GTEST_HAS_STD_UNIQUE_PTR_
-
-// Tests that DefaultValue<void>::Get() returns void.
-TEST(DefaultValueTest, GetWorksForVoid) {
-  return DefaultValue<void>::Get();
-}
-
-// Tests using DefaultValue with a reference type.
-
-// Tests that DefaultValue<T&>::IsSet() is false initially.
-TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
-  EXPECT_FALSE(DefaultValue<int&>::IsSet());
-  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
-}
-
-// Tests that DefaultValue<T&>::Exists is false initiallly.
-TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
-  EXPECT_FALSE(DefaultValue<int&>::Exists());
-  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
-}
-
-// Tests that DefaultValue<T&> can be set and then unset.
-TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
-  int n = 1;
-  DefaultValue<const int&>::Set(n);
-  MyNonDefaultConstructible x(42);
-  DefaultValue<MyNonDefaultConstructible&>::Set(x);
-
-  EXPECT_TRUE(DefaultValue<const int&>::Exists());
-  EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
-
-  EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
-  EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
-
-  DefaultValue<const int&>::Clear();
-  DefaultValue<MyNonDefaultConstructible&>::Clear();
-
-  EXPECT_FALSE(DefaultValue<const int&>::Exists());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
-
-  EXPECT_FALSE(DefaultValue<const int&>::IsSet());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
-}
-
-// Tests that DefaultValue<T&>::Get() returns the
-// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
-// false.
-TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
-  EXPECT_FALSE(DefaultValue<int&>::IsSet());
-  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
-
-  EXPECT_DEATH_IF_SUPPORTED({
-    DefaultValue<int&>::Get();
-  }, "");
-  EXPECT_DEATH_IF_SUPPORTED({
-    DefaultValue<MyNonDefaultConstructible>::Get();
-  }, "");
-}
-
-// Tests that ActionInterface can be implemented by defining the
-// Perform method.
-
-typedef int MyGlobalFunction(bool, int);
-
-class MyActionImpl : public ActionInterface<MyGlobalFunction> {
- public:
-  virtual int Perform(const tuple<bool, int>& args) {
-    return get<0>(args) ? get<1>(args) : 0;
-  }
-};
-
-TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
-  MyActionImpl my_action_impl;
-  (void)my_action_impl;
-}
-
-TEST(ActionInterfaceTest, MakeAction) {
-  Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
-
-  // When exercising the Perform() method of Action<F>, we must pass
-  // it a tuple whose size and type are compatible with F's argument
-  // types.  For example, if F is int(), then Perform() takes a
-  // 0-tuple; if F is void(bool, int), then Perform() takes a
-  // tuple<bool, int>, and so on.
-  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
-}
-
-// Tests that Action<F> can be contructed from a pointer to
-// ActionInterface<F>.
-TEST(ActionTest, CanBeConstructedFromActionInterface) {
-  Action<MyGlobalFunction> action(new MyActionImpl);
-}
-
-// Tests that Action<F> delegates actual work to ActionInterface<F>.
-TEST(ActionTest, DelegatesWorkToActionInterface) {
-  const Action<MyGlobalFunction> action(new MyActionImpl);
-
-  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
-  EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
-}
-
-// Tests that Action<F> can be copied.
-TEST(ActionTest, IsCopyable) {
-  Action<MyGlobalFunction> a1(new MyActionImpl);
-  Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.
-
-  // a1 should continue to work after being copied from.
-  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
-  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
-
-  // a2 should work like the action it was copied from.
-  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
-  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
-
-  a2 = a1;  // Tests the assignment operator.
-
-  // a1 should continue to work after being copied from.
-  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
-  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
-
-  // a2 should work like the action it was copied from.
-  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
-  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
-}
-
-// Tests that an Action<From> object can be converted to a
-// compatible Action<To> object.
-
-class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
- public:
-  virtual bool Perform(const tuple<int>& arg) {
-    return get<0>(arg) != 0;
-  }
-};
-
-#if !GTEST_OS_SYMBIAN
-// Compiling this test on Nokia's Symbian compiler fails with:
-//  'Result' is not a member of class 'testing::internal::Function<int>'
-//  (point of instantiation: '@unnamed@gmock_actions_test_cc@::
-//      ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
-// with no obvious fix.
-TEST(ActionTest, CanBeConvertedToOtherActionType) {
-  const Action<bool(int)> a1(new IsNotZero);  // NOLINT
-  const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
-  EXPECT_EQ(1, a2.Perform(make_tuple('a')));
-  EXPECT_EQ(0, a2.Perform(make_tuple('\0')));
-}
-#endif  // !GTEST_OS_SYMBIAN
-
-// The following two classes are for testing MakePolymorphicAction().
-
-// Implements a polymorphic action that returns the second of the
-// arguments it receives.
-class ReturnSecondArgumentAction {
- public:
-  // We want to verify that MakePolymorphicAction() can work with a
-  // polymorphic action whose Perform() method template is either
-  // const or not.  This lets us verify the non-const case.
-  template <typename Result, typename ArgumentTuple>
-  Result Perform(const ArgumentTuple& args) { return get<1>(args); }
-};
-
-// Implements a polymorphic action that can be used in a nullary
-// function to return 0.
-class ReturnZeroFromNullaryFunctionAction {
- public:
-  // For testing that MakePolymorphicAction() works when the
-  // implementation class' Perform() method template takes only one
-  // template parameter.
-  //
-  // We want to verify that MakePolymorphicAction() can work with a
-  // polymorphic action whose Perform() method template is either
-  // const or not.  This lets us verify the const case.
-  template <typename Result>
-  Result Perform(const tuple<>&) const { return 0; }
-};
-
-// These functions verify that MakePolymorphicAction() returns a
-// PolymorphicAction<T> where T is the argument's type.
-
-PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
-  return MakePolymorphicAction(ReturnSecondArgumentAction());
-}
-
-PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
-ReturnZeroFromNullaryFunction() {
-  return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
-}
-
-// Tests that MakePolymorphicAction() turns a polymorphic action
-// implementation class into a polymorphic action.
-TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
-  Action<int(bool, int, double)> a1 = ReturnSecondArgument();  // NOLINT
-  EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0)));
-}
-
-// Tests that MakePolymorphicAction() works when the implementation
-// class' Perform() method template has only one template parameter.
-TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
-  Action<int()> a1 = ReturnZeroFromNullaryFunction();
-  EXPECT_EQ(0, a1.Perform(make_tuple()));
-
-  Action<void*()> a2 = ReturnZeroFromNullaryFunction();
-  EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
-}
-
-// Tests that Return() works as an action for void-returning
-// functions.
-TEST(ReturnTest, WorksForVoid) {
-  const Action<void(int)> ret = Return();  // NOLINT
-  return ret.Perform(make_tuple(1));
-}
-
-// Tests that Return(v) returns v.
-TEST(ReturnTest, ReturnsGivenValue) {
-  Action<int()> ret = Return(1);  // NOLINT
-  EXPECT_EQ(1, ret.Perform(make_tuple()));
-
-  ret = Return(-5);
-  EXPECT_EQ(-5, ret.Perform(make_tuple()));
-}
-
-// Tests that Return("string literal") works.
-TEST(ReturnTest, AcceptsStringLiteral) {
-  Action<const char*()> a1 = Return("Hello");
-  EXPECT_STREQ("Hello", a1.Perform(make_tuple()));
-
-  Action<std::string()> a2 = Return("world");
-  EXPECT_EQ("world", a2.Perform(make_tuple()));
-}
-
-// Test struct which wraps a vector of integers. Used in
-// 'SupportsWrapperReturnType' test.
-struct IntegerVectorWrapper {
-  std::vector<int> * v;
-  IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {}  // NOLINT
-};
-
-// Tests that Return() works when return type is a wrapper type.
-TEST(ReturnTest, SupportsWrapperReturnType) {
-  // Initialize vector of integers.
-  std::vector<int> v;
-  for (int i = 0; i < 5; ++i) v.push_back(i);
-
-  // Return() called with 'v' as argument. The Action will return the same data
-  // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
-  Action<IntegerVectorWrapper()> a = Return(v);
-  const std::vector<int>& result = *(a.Perform(make_tuple()).v);
-  EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
-}
-
-// Tests that Return(v) is covaraint.
-
-struct Base {
-  bool operator==(const Base&) { return true; }
-};
-
-struct Derived : public Base {
-  bool operator==(const Derived&) { return true; }
-};
-
-TEST(ReturnTest, IsCovariant) {
-  Base base;
-  Derived derived;
-  Action<Base*()> ret = Return(&base);
-  EXPECT_EQ(&base, ret.Perform(make_tuple()));
-
-  ret = Return(&derived);
-  EXPECT_EQ(&derived, ret.Perform(make_tuple()));
-}
-
-// Tests that the type of the value passed into Return is converted into T
-// when the action is cast to Action<T(...)> rather than when the action is
-// performed. See comments on testing::internal::ReturnAction in
-// gmock-actions.h for more information.
-class FromType {
- public:
-  explicit FromType(bool* is_converted) : converted_(is_converted) {}
-  bool* converted() const { return converted_; }
-
- private:
-  bool* const converted_;
-
-  GTEST_DISALLOW_ASSIGN_(FromType);
-};
-
-class ToType {
- public:
-  // Must allow implicit conversion due to use in ImplicitCast_<T>.
-  ToType(const FromType& x) { *x.converted() = true; }  // NOLINT
-};
-
-TEST(ReturnTest, ConvertsArgumentWhenConverted) {
-  bool converted = false;
-  FromType x(&converted);
-  Action<ToType()> action(Return(x));
-  EXPECT_TRUE(converted) << "Return must convert its argument in its own "
-                         << "conversion operator.";
-  converted = false;
-  action.Perform(tuple<>());
-  EXPECT_FALSE(converted) << "Action must NOT convert its argument "
-                          << "when performed.";
-}
-
-class DestinationType {};
-
-class SourceType {
- public:
-  // Note: a non-const typecast operator.
-  operator DestinationType() { return DestinationType(); }
-};
-
-TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
-  SourceType s;
-  Action<DestinationType()> action(Return(s));
-}
-
-// Tests that ReturnNull() returns NULL in a pointer-returning function.
-TEST(ReturnNullTest, WorksInPointerReturningFunction) {
-  const Action<int*()> a1 = ReturnNull();
-  EXPECT_TRUE(a1.Perform(make_tuple()) == NULL);
-
-  const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT
-  EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
-}
-
-#if GTEST_HAS_STD_UNIQUE_PTR_
-// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
-// functions.
-TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
-  const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
-  EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);
-
-  const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
-  EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
-}
-#endif  // GTEST_HAS_STD_UNIQUE_PTR_
-
-// Tests that ReturnRef(v) works for reference types.
-TEST(ReturnRefTest, WorksForReference) {
-  const int n = 0;
-  const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT
-
-  EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
-}
-
-// Tests that ReturnRef(v) is covariant.
-TEST(ReturnRefTest, IsCovariant) {
-  Base base;
-  Derived derived;
-  Action<Base&()> a = ReturnRef(base);
-  EXPECT_EQ(&base, &a.Perform(make_tuple()));
-
-  a = ReturnRef(derived);
-  EXPECT_EQ(&derived, &a.Perform(make_tuple()));
-}
-
-// Tests that ReturnRefOfCopy(v) works for reference types.
-TEST(ReturnRefOfCopyTest, WorksForReference) {
-  int n = 42;
-  const Action<const int&()> ret = ReturnRefOfCopy(n);
-
-  EXPECT_NE(&n, &ret.Perform(make_tuple()));
-  EXPECT_EQ(42, ret.Perform(make_tuple()));
-
-  n = 43;
-  EXPECT_NE(&n, &ret.Perform(make_tuple()));
-  EXPECT_EQ(42, ret.Perform(make_tuple()));
-}
-
-// Tests that ReturnRefOfCopy(v) is covariant.
-TEST(ReturnRefOfCopyTest, IsCovariant) {
-  Base base;
-  Derived derived;
-  Action<Base&()> a = ReturnRefOfCopy(base);
-  EXPECT_NE(&base, &a.Perform(make_tuple()));
-
-  a = ReturnRefOfCopy(derived);
-  EXPECT_NE(&derived, &a.Perform(make_tuple()));
-}
-
-// Tests that DoDefault() does the default action for the mock method.
-
-class MockClass {
- public:
-  MockClass() {}
-
-  MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT
-  MOCK_METHOD0(Foo, MyNonDefaultConstructible());
-#if GTEST_HAS_STD_UNIQUE_PTR_
-  MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
-  MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
-  MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
-#endif
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
-};
-
-// Tests that DoDefault() returns the built-in default value for the
-// return type by default.
-TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
-  MockClass mock;
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillOnce(DoDefault());
-  EXPECT_EQ(0, mock.IntFunc(true));
-}
-
-// Tests that DoDefault() throws (when exceptions are enabled) or aborts
-// the process when there is no built-in default value for the return type.
-TEST(DoDefaultDeathTest, DiesForUnknowType) {
-  MockClass mock;
-  EXPECT_CALL(mock, Foo())
-      .WillRepeatedly(DoDefault());
-#if GTEST_HAS_EXCEPTIONS
-  EXPECT_ANY_THROW(mock.Foo());
-#else
-  EXPECT_DEATH_IF_SUPPORTED({
-    mock.Foo();
-  }, "");
-#endif
-}
-
-// Tests that using DoDefault() inside a composite action leads to a
-// run-time error.
-
-void VoidFunc(bool /* flag */) {}
-
-TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
-  MockClass mock;
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillRepeatedly(DoAll(Invoke(VoidFunc),
-                            DoDefault()));
-
-  // Ideally we should verify the error message as well.  Sadly,
-  // EXPECT_DEATH() can only capture stderr, while Google Mock's
-  // errors are printed on stdout.  Therefore we have to settle for
-  // not verifying the message.
-  EXPECT_DEATH_IF_SUPPORTED({
-    mock.IntFunc(true);
-  }, "");
-}
-
-// Tests that DoDefault() returns the default value set by
-// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
-TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
-  DefaultValue<int>::Set(1);
-  MockClass mock;
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillOnce(DoDefault());
-  EXPECT_EQ(1, mock.IntFunc(false));
-  DefaultValue<int>::Clear();
-}
-
-// Tests that DoDefault() does the action specified by ON_CALL().
-TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
-  MockClass mock;
-  ON_CALL(mock, IntFunc(_))
-      .WillByDefault(Return(2));
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillOnce(DoDefault());
-  EXPECT_EQ(2, mock.IntFunc(false));
-}
-
-// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
-TEST(DoDefaultTest, CannotBeUsedInOnCall) {
-  MockClass mock;
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    ON_CALL(mock, IntFunc(_))
-      .WillByDefault(DoDefault());
-  }, "DoDefault() cannot be used in ON_CALL()");
-}
-
-// Tests that SetArgPointee<N>(v) sets the variable pointed to by
-// the N-th (0-based) argument to v.
-TEST(SetArgPointeeTest, SetsTheNthPointee) {
-  typedef void MyFunction(bool, int*, char*);
-  Action<MyFunction> a = SetArgPointee<1>(2);
-
-  int n = 0;
-  char ch = '\0';
-  a.Perform(make_tuple(true, &n, &ch));
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('\0', ch);
-
-  a = SetArgPointee<2>('a');
-  n = 0;
-  ch = '\0';
-  a.Perform(make_tuple(true, &n, &ch));
-  EXPECT_EQ(0, n);
-  EXPECT_EQ('a', ch);
-}
-
-#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
-// Tests that SetArgPointee<N>() accepts a string literal.
-// GCC prior to v4.0 and the Symbian compiler do not support this.
-TEST(SetArgPointeeTest, AcceptsStringLiteral) {
-  typedef void MyFunction(std::string*, const char**);
-  Action<MyFunction> a = SetArgPointee<0>("hi");
-  std::string str;
-  const char* ptr = NULL;
-  a.Perform(make_tuple(&str, &ptr));
-  EXPECT_EQ("hi", str);
-  EXPECT_TRUE(ptr == NULL);
-
-  a = SetArgPointee<1>("world");
-  str = "";
-  a.Perform(make_tuple(&str, &ptr));
-  EXPECT_EQ("", str);
-  EXPECT_STREQ("world", ptr);
-}
-
-TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
-  typedef void MyFunction(const wchar_t**);
-  Action<MyFunction> a = SetArgPointee<0>(L"world");
-  const wchar_t* ptr = NULL;
-  a.Perform(make_tuple(&ptr));
-  EXPECT_STREQ(L"world", ptr);
-
-# if GTEST_HAS_STD_WSTRING
-
-  typedef void MyStringFunction(std::wstring*);
-  Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
-  std::wstring str = L"";
-  a2.Perform(make_tuple(&str));
-  EXPECT_EQ(L"world", str);
-
-# endif
-}
-#endif
-
-// Tests that SetArgPointee<N>() accepts a char pointer.
-TEST(SetArgPointeeTest, AcceptsCharPointer) {
-  typedef void MyFunction(bool, std::string*, const char**);
-  const char* const hi = "hi";
-  Action<MyFunction> a = SetArgPointee<1>(hi);
-  std::string str;
-  const char* ptr = NULL;
-  a.Perform(make_tuple(true, &str, &ptr));
-  EXPECT_EQ("hi", str);
-  EXPECT_TRUE(ptr == NULL);
-
-  char world_array[] = "world";
-  char* const world = world_array;
-  a = SetArgPointee<2>(world);
-  str = "";
-  a.Perform(make_tuple(true, &str, &ptr));
-  EXPECT_EQ("", str);
-  EXPECT_EQ(world, ptr);
-}
-
-TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
-  typedef void MyFunction(bool, const wchar_t**);
-  const wchar_t* const hi = L"hi";
-  Action<MyFunction> a = SetArgPointee<1>(hi);
-  const wchar_t* ptr = NULL;
-  a.Perform(make_tuple(true, &ptr));
-  EXPECT_EQ(hi, ptr);
-
-# if GTEST_HAS_STD_WSTRING
-
-  typedef void MyStringFunction(bool, std::wstring*);
-  wchar_t world_array[] = L"world";
-  wchar_t* const world = world_array;
-  Action<MyStringFunction> a2 = SetArgPointee<1>(world);
-  std::wstring str;
-  a2.Perform(make_tuple(true, &str));
-  EXPECT_EQ(world_array, str);
-# endif
-}
-
-#if GTEST_HAS_PROTOBUF_
-
-// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
-// variable pointed to by the N-th (0-based) argument to proto_buffer.
-TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
-  TestMessage* const msg = new TestMessage;
-  msg->set_member("yes");
-  TestMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
-  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
-  // s.t. the action works even when the original proto_buffer has
-  // died.  We ensure this behavior by deleting msg before using the
-  // action.
-  delete msg;
-
-  TestMessage dest;
-  EXPECT_FALSE(orig_msg.Equals(dest));
-  a.Perform(make_tuple(true, &dest));
-  EXPECT_TRUE(orig_msg.Equals(dest));
-}
-
-// Tests that SetArgPointee<N>(proto_buffer) sets the
-// ::ProtocolMessage variable pointed to by the N-th (0-based)
-// argument to proto_buffer.
-TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
-  TestMessage* const msg = new TestMessage;
-  msg->set_member("yes");
-  TestMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
-  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
-  // s.t. the action works even when the original proto_buffer has
-  // died.  We ensure this behavior by deleting msg before using the
-  // action.
-  delete msg;
-
-  TestMessage dest;
-  ::ProtocolMessage* const dest_base = &dest;
-  EXPECT_FALSE(orig_msg.Equals(dest));
-  a.Perform(make_tuple(true, dest_base));
-  EXPECT_TRUE(orig_msg.Equals(dest));
-}
-
-// Tests that SetArgPointee<N>(proto2_buffer) sets the v2
-// protobuf variable pointed to by the N-th (0-based) argument to
-// proto2_buffer.
-TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
-  using testing::internal::FooMessage;
-  FooMessage* const msg = new FooMessage;
-  msg->set_int_field(2);
-  msg->set_string_field("hi");
-  FooMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
-  // SetArgPointee<N>(proto2_buffer) makes a copy of
-  // proto2_buffer s.t. the action works even when the original
-  // proto2_buffer has died.  We ensure this behavior by deleting msg
-  // before using the action.
-  delete msg;
-
-  FooMessage dest;
-  dest.set_int_field(0);
-  a.Perform(make_tuple(true, &dest));
-  EXPECT_EQ(2, dest.int_field());
-  EXPECT_EQ("hi", dest.string_field());
-}
-
-// Tests that SetArgPointee<N>(proto2_buffer) sets the
-// proto2::Message variable pointed to by the N-th (0-based) argument
-// to proto2_buffer.
-TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
-  using testing::internal::FooMessage;
-  FooMessage* const msg = new FooMessage;
-  msg->set_int_field(2);
-  msg->set_string_field("hi");
-  FooMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
-  // SetArgPointee<N>(proto2_buffer) makes a copy of
-  // proto2_buffer s.t. the action works even when the original
-  // proto2_buffer has died.  We ensure this behavior by deleting msg
-  // before using the action.
-  delete msg;
-
-  FooMessage dest;
-  dest.set_int_field(0);
-  ::proto2::Message* const dest_base = &dest;
-  a.Perform(make_tuple(true, dest_base));
-  EXPECT_EQ(2, dest.int_field());
-  EXPECT_EQ("hi", dest.string_field());
-}
-
-#endif  // GTEST_HAS_PROTOBUF_
-
-// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
-// the N-th (0-based) argument to v.
-TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
-  typedef void MyFunction(bool, int*, char*);
-  Action<MyFunction> a = SetArgumentPointee<1>(2);
-
-  int n = 0;
-  char ch = '\0';
-  a.Perform(make_tuple(true, &n, &ch));
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('\0', ch);
-
-  a = SetArgumentPointee<2>('a');
-  n = 0;
-  ch = '\0';
-  a.Perform(make_tuple(true, &n, &ch));
-  EXPECT_EQ(0, n);
-  EXPECT_EQ('a', ch);
-}
-
-#if GTEST_HAS_PROTOBUF_
-
-// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
-// variable pointed to by the N-th (0-based) argument to proto_buffer.
-TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
-  TestMessage* const msg = new TestMessage;
-  msg->set_member("yes");
-  TestMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
-  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
-  // s.t. the action works even when the original proto_buffer has
-  // died.  We ensure this behavior by deleting msg before using the
-  // action.
-  delete msg;
-
-  TestMessage dest;
-  EXPECT_FALSE(orig_msg.Equals(dest));
-  a.Perform(make_tuple(true, &dest));
-  EXPECT_TRUE(orig_msg.Equals(dest));
-}
-
-// Tests that SetArgumentPointee<N>(proto_buffer) sets the
-// ::ProtocolMessage variable pointed to by the N-th (0-based)
-// argument to proto_buffer.
-TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
-  TestMessage* const msg = new TestMessage;
-  msg->set_member("yes");
-  TestMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
-  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
-  // s.t. the action works even when the original proto_buffer has
-  // died.  We ensure this behavior by deleting msg before using the
-  // action.
-  delete msg;
-
-  TestMessage dest;
-  ::ProtocolMessage* const dest_base = &dest;
-  EXPECT_FALSE(orig_msg.Equals(dest));
-  a.Perform(make_tuple(true, dest_base));
-  EXPECT_TRUE(orig_msg.Equals(dest));
-}
-
-// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
-// protobuf variable pointed to by the N-th (0-based) argument to
-// proto2_buffer.
-TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
-  using testing::internal::FooMessage;
-  FooMessage* const msg = new FooMessage;
-  msg->set_int_field(2);
-  msg->set_string_field("hi");
-  FooMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
-  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
-  // proto2_buffer s.t. the action works even when the original
-  // proto2_buffer has died.  We ensure this behavior by deleting msg
-  // before using the action.
-  delete msg;
-
-  FooMessage dest;
-  dest.set_int_field(0);
-  a.Perform(make_tuple(true, &dest));
-  EXPECT_EQ(2, dest.int_field());
-  EXPECT_EQ("hi", dest.string_field());
-}
-
-// Tests that SetArgumentPointee<N>(proto2_buffer) sets the
-// proto2::Message variable pointed to by the N-th (0-based) argument
-// to proto2_buffer.
-TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
-  using testing::internal::FooMessage;
-  FooMessage* const msg = new FooMessage;
-  msg->set_int_field(2);
-  msg->set_string_field("hi");
-  FooMessage orig_msg;
-  orig_msg.CopyFrom(*msg);
-
-  Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
-  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
-  // proto2_buffer s.t. the action works even when the original
-  // proto2_buffer has died.  We ensure this behavior by deleting msg
-  // before using the action.
-  delete msg;
-
-  FooMessage dest;
-  dest.set_int_field(0);
-  ::proto2::Message* const dest_base = &dest;
-  a.Perform(make_tuple(true, dest_base));
-  EXPECT_EQ(2, dest.int_field());
-  EXPECT_EQ("hi", dest.string_field());
-}
-
-#endif  // GTEST_HAS_PROTOBUF_
-
-// Sample functions and functors for testing Invoke() and etc.
-int Nullary() { return 1; }
-
-class NullaryFunctor {
- public:
-  int operator()() { return 2; }
-};
-
-bool g_done = false;
-void VoidNullary() { g_done = true; }
-
-class VoidNullaryFunctor {
- public:
-  void operator()() { g_done = true; }
-};
-
-class Foo {
- public:
-  Foo() : value_(123) {}
-
-  int Nullary() const { return value_; }
-
- private:
-  int value_;
-};
-
-// Tests InvokeWithoutArgs(function).
-TEST(InvokeWithoutArgsTest, Function) {
-  // As an action that takes one argument.
-  Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT
-  EXPECT_EQ(1, a.Perform(make_tuple(2)));
-
-  // As an action that takes two arguments.
-  Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT
-  EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5)));
-
-  // As an action that returns void.
-  Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT
-  g_done = false;
-  a3.Perform(make_tuple(1));
-  EXPECT_TRUE(g_done);
-}
-
-// Tests InvokeWithoutArgs(functor).
-TEST(InvokeWithoutArgsTest, Functor) {
-  // As an action that takes no argument.
-  Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT
-  EXPECT_EQ(2, a.Perform(make_tuple()));
-
-  // As an action that takes three arguments.
-  Action<int(int, double, char)> a2 =  // NOLINT
-      InvokeWithoutArgs(NullaryFunctor());
-  EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a')));
-
-  // As an action that returns void.
-  Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
-  g_done = false;
-  a3.Perform(make_tuple());
-  EXPECT_TRUE(g_done);
-}
-
-// Tests InvokeWithoutArgs(obj_ptr, method).
-TEST(InvokeWithoutArgsTest, Method) {
-  Foo foo;
-  Action<int(bool, char)> a =  // NOLINT
-      InvokeWithoutArgs(&foo, &Foo::Nullary);
-  EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
-}
-
-// Tests using IgnoreResult() on a polymorphic action.
-TEST(IgnoreResultTest, PolymorphicAction) {
-  Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT
-  a.Perform(make_tuple(1));
-}
-
-// Tests using IgnoreResult() on a monomorphic action.
-
-int ReturnOne() {
-  g_done = true;
-  return 1;
-}
-
-TEST(IgnoreResultTest, MonomorphicAction) {
-  g_done = false;
-  Action<void()> a = IgnoreResult(Invoke(ReturnOne));
-  a.Perform(make_tuple());
-  EXPECT_TRUE(g_done);
-}
-
-// Tests using IgnoreResult() on an action that returns a class type.
-
-MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
-  g_done = true;
-  return MyNonDefaultConstructible(42);
-}
-
-TEST(IgnoreResultTest, ActionReturningClass) {
-  g_done = false;
-  Action<void(int)> a =
-      IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT
-  a.Perform(make_tuple(2));
-  EXPECT_TRUE(g_done);
-}
-
-TEST(AssignTest, Int) {
-  int x = 0;
-  Action<void(int)> a = Assign(&x, 5);
-  a.Perform(make_tuple(0));
-  EXPECT_EQ(5, x);
-}
-
-TEST(AssignTest, String) {
-  ::std::string x;
-  Action<void(void)> a = Assign(&x, "Hello, world");
-  a.Perform(make_tuple());
-  EXPECT_EQ("Hello, world", x);
-}
-
-TEST(AssignTest, CompatibleTypes) {
-  double x = 0;
-  Action<void(int)> a = Assign(&x, 5);
-  a.Perform(make_tuple(0));
-  EXPECT_DOUBLE_EQ(5, x);
-}
-
-#if !GTEST_OS_WINDOWS_MOBILE
-
-class SetErrnoAndReturnTest : public testing::Test {
- protected:
-  virtual void SetUp() { errno = 0; }
-  virtual void TearDown() { errno = 0; }
-};
-
-TEST_F(SetErrnoAndReturnTest, Int) {
-  Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
-  EXPECT_EQ(-5, a.Perform(make_tuple()));
-  EXPECT_EQ(ENOTTY, errno);
-}
-
-TEST_F(SetErrnoAndReturnTest, Ptr) {
-  int x;
-  Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
-  EXPECT_EQ(&x, a.Perform(make_tuple()));
-  EXPECT_EQ(ENOTTY, errno);
-}
-
-TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
-  Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
-  EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple()));
-  EXPECT_EQ(EINVAL, errno);
-}
-
-#endif  // !GTEST_OS_WINDOWS_MOBILE
-
-// Tests ByRef().
-
-// Tests that ReferenceWrapper<T> is copyable.
-TEST(ByRefTest, IsCopyable) {
-  const std::string s1 = "Hi";
-  const std::string s2 = "Hello";
-
-  ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
-      ByRef(s1);
-  const std::string& r1 = ref_wrapper;
-  EXPECT_EQ(&s1, &r1);
-
-  // Assigns a new value to ref_wrapper.
-  ref_wrapper = ByRef(s2);
-  const std::string& r2 = ref_wrapper;
-  EXPECT_EQ(&s2, &r2);
-
-  ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
-      ByRef(s1);
-  // Copies ref_wrapper1 to ref_wrapper.
-  ref_wrapper = ref_wrapper1;
-  const std::string& r3 = ref_wrapper;
-  EXPECT_EQ(&s1, &r3);
-}
-
-// Tests using ByRef() on a const value.
-TEST(ByRefTest, ConstValue) {
-  const int n = 0;
-  // int& ref = ByRef(n);  // This shouldn't compile - we have a
-                           // negative compilation test to catch it.
-  const int& const_ref = ByRef(n);
-  EXPECT_EQ(&n, &const_ref);
-}
-
-// Tests using ByRef() on a non-const value.
-TEST(ByRefTest, NonConstValue) {
-  int n = 0;
-
-  // ByRef(n) can be used as either an int&,
-  int& ref = ByRef(n);
-  EXPECT_EQ(&n, &ref);
-
-  // or a const int&.
-  const int& const_ref = ByRef(n);
-  EXPECT_EQ(&n, &const_ref);
-}
-
-// Tests explicitly specifying the type when using ByRef().
-TEST(ByRefTest, ExplicitType) {
-  int n = 0;
-  const int& r1 = ByRef<const int>(n);
-  EXPECT_EQ(&n, &r1);
-
-  // ByRef<char>(n);  // This shouldn't compile - we have a negative
-                      // compilation test to catch it.
-
-  Derived d;
-  Derived& r2 = ByRef<Derived>(d);
-  EXPECT_EQ(&d, &r2);
-
-  const Derived& r3 = ByRef<const Derived>(d);
-  EXPECT_EQ(&d, &r3);
-
-  Base& r4 = ByRef<Base>(d);
-  EXPECT_EQ(&d, &r4);
-
-  const Base& r5 = ByRef<const Base>(d);
-  EXPECT_EQ(&d, &r5);
-
-  // The following shouldn't compile - we have a negative compilation
-  // test for it.
-  //
-  // Base b;
-  // ByRef<Derived>(b);
-}
-
-// Tests that Google Mock prints expression ByRef(x) as a reference to x.
-TEST(ByRefTest, PrintsCorrectly) {
-  int n = 42;
-  ::std::stringstream expected, actual;
-  testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
-  testing::internal::UniversalPrint(ByRef(n), &actual);
-  EXPECT_EQ(expected.str(), actual.str());
-}
-
-#if GTEST_HAS_STD_UNIQUE_PTR_
-
-std::unique_ptr<int> UniquePtrSource() {
-  return std::unique_ptr<int>(new int(19));
-}
-
-std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
-  std::vector<std::unique_ptr<int>> out;
-  out.emplace_back(new int(7));
-  return out;
-}
-
-TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
-  MockClass mock;
-  std::unique_ptr<int> i(new int(19));
-  EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
-  EXPECT_CALL(mock, MakeVectorUnique())
-      .WillOnce(Return(ByMove(VectorUniquePtrSource())));
-  Derived* d = new Derived;
-  EXPECT_CALL(mock, MakeUniqueBase())
-      .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
-
-  std::unique_ptr<int> result1 = mock.MakeUnique();
-  EXPECT_EQ(19, *result1);
-
-  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
-  EXPECT_EQ(1u, vresult.size());
-  EXPECT_NE(nullptr, vresult[0]);
-  EXPECT_EQ(7, *vresult[0]);
-
-  std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
-  EXPECT_EQ(d, result2.get());
-}
-
-TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
-  testing::MockFunction<void()> mock_function;
-  MockClass mock;
-  std::unique_ptr<int> i(new int(19));
-  EXPECT_CALL(mock_function, Call());
-  EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
-      InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
-      Return(ByMove(std::move(i)))));
-
-  std::unique_ptr<int> result1 = mock.MakeUnique();
-  EXPECT_EQ(19, *result1);
-}
-
-TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
-  MockClass mock;
-
-  // Check default value
-  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
-    return std::unique_ptr<int>(new int(42));
-  });
-  EXPECT_EQ(42, *mock.MakeUnique());
-
-  EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
-  EXPECT_CALL(mock, MakeVectorUnique())
-      .WillRepeatedly(Invoke(VectorUniquePtrSource));
-  std::unique_ptr<int> result1 = mock.MakeUnique();
-  EXPECT_EQ(19, *result1);
-  std::unique_ptr<int> result2 = mock.MakeUnique();
-  EXPECT_EQ(19, *result2);
-  EXPECT_NE(result1, result2);
-
-  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
-  EXPECT_EQ(1u, vresult.size());
-  EXPECT_NE(nullptr, vresult[0]);
-  EXPECT_EQ(7, *vresult[0]);
-}
-
-#endif  // GTEST_HAS_STD_UNIQUE_PTR_
-
-}  // Unnamed namespace
diff --git a/testing/gmock/test/gmock-cardinalities_test.cc b/testing/gmock/test/gmock-cardinalities_test.cc
deleted file mode 100644
index 64815e5..0000000
--- a/testing/gmock/test/gmock-cardinalities_test.cc
+++ /dev/null
@@ -1,428 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in cardinalities.
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-namespace {
-
-using std::stringstream;
-using testing::AnyNumber;
-using testing::AtLeast;
-using testing::AtMost;
-using testing::Between;
-using testing::Cardinality;
-using testing::CardinalityInterface;
-using testing::Exactly;
-using testing::IsSubstring;
-using testing::MakeCardinality;
-
-class MockFoo {
- public:
-  MockFoo() {}
-  MOCK_METHOD0(Bar, int());  // NOLINT
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
-};
-
-// Tests that Cardinality objects can be default constructed.
-TEST(CardinalityTest, IsDefaultConstructable) {
-  Cardinality c;
-}
-
-// Tests that Cardinality objects are copyable.
-TEST(CardinalityTest, IsCopyable) {
-  // Tests the copy constructor.
-  Cardinality c = Exactly(1);
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
-
-  // Tests the assignment operator.
-  c = Exactly(2);
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
-}
-
-TEST(CardinalityTest, IsOverSaturatedByCallCountWorks) {
-  const Cardinality c = AtMost(5);
-  EXPECT_FALSE(c.IsOverSaturatedByCallCount(4));
-  EXPECT_FALSE(c.IsOverSaturatedByCallCount(5));
-  EXPECT_TRUE(c.IsOverSaturatedByCallCount(6));
-}
-
-// Tests that Cardinality::DescribeActualCallCountTo() creates the
-// correct description.
-TEST(CardinalityTest, CanDescribeActualCallCount) {
-  stringstream ss0;
-  Cardinality::DescribeActualCallCountTo(0, &ss0);
-  EXPECT_EQ("never called", ss0.str());
-
-  stringstream ss1;
-  Cardinality::DescribeActualCallCountTo(1, &ss1);
-  EXPECT_EQ("called once", ss1.str());
-
-  stringstream ss2;
-  Cardinality::DescribeActualCallCountTo(2, &ss2);
-  EXPECT_EQ("called twice", ss2.str());
-
-  stringstream ss3;
-  Cardinality::DescribeActualCallCountTo(3, &ss3);
-  EXPECT_EQ("called 3 times", ss3.str());
-}
-
-// Tests AnyNumber()
-TEST(AnyNumber, Works) {
-  const Cardinality c = AnyNumber();
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(9));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(9));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times",
-                      ss.str());
-}
-
-TEST(AnyNumberTest, HasCorrectBounds) {
-  const Cardinality c = AnyNumber();
-  EXPECT_EQ(0, c.ConservativeLowerBound());
-  EXPECT_EQ(INT_MAX, c.ConservativeUpperBound());
-}
-
-// Tests AtLeast(n).
-
-TEST(AtLeastTest, OnNegativeNumber) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    AtLeast(-1);
-  }, "The invocation lower bound must be >= 0");
-}
-
-TEST(AtLeastTest, OnZero) {
-  const Cardinality c = AtLeast(0);
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "any number of times",
-                      ss.str());
-}
-
-TEST(AtLeastTest, OnPositiveNumber) {
-  const Cardinality c = AtLeast(2);
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(2));
-
-  stringstream ss1;
-  AtLeast(1).DescribeTo(&ss1);
-  EXPECT_PRED_FORMAT2(IsSubstring, "at least once",
-                      ss1.str());
-
-  stringstream ss2;
-  c.DescribeTo(&ss2);
-  EXPECT_PRED_FORMAT2(IsSubstring, "at least twice",
-                      ss2.str());
-
-  stringstream ss3;
-  AtLeast(3).DescribeTo(&ss3);
-  EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times",
-                      ss3.str());
-}
-
-TEST(AtLeastTest, HasCorrectBounds) {
-  const Cardinality c = AtLeast(2);
-  EXPECT_EQ(2, c.ConservativeLowerBound());
-  EXPECT_EQ(INT_MAX, c.ConservativeUpperBound());
-}
-
-// Tests AtMost(n).
-
-TEST(AtMostTest, OnNegativeNumber) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    AtMost(-1);
-  }, "The invocation upper bound must be >= 0");
-}
-
-TEST(AtMostTest, OnZero) {
-  const Cardinality c = AtMost(0);
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
-                      ss.str());
-}
-
-TEST(AtMostTest, OnPositiveNumber) {
-  const Cardinality c = AtMost(2);
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(1));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
-
-  stringstream ss1;
-  AtMost(1).DescribeTo(&ss1);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most once",
-                      ss1.str());
-
-  stringstream ss2;
-  c.DescribeTo(&ss2);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice",
-                      ss2.str());
-
-  stringstream ss3;
-  AtMost(3).DescribeTo(&ss3);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times",
-                      ss3.str());
-}
-
-TEST(AtMostTest, HasCorrectBounds) {
-  const Cardinality c = AtMost(2);
-  EXPECT_EQ(0, c.ConservativeLowerBound());
-  EXPECT_EQ(2, c.ConservativeUpperBound());
-}
-
-// Tests Between(m, n).
-
-TEST(BetweenTest, OnNegativeStart) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Between(-1, 2);
-  }, "The invocation lower bound must be >= 0, but is actually -1");
-}
-
-TEST(BetweenTest, OnNegativeEnd) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Between(1, -2);
-  }, "The invocation upper bound must be >= 0, but is actually -2");
-}
-
-TEST(BetweenTest, OnStartBiggerThanEnd) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Between(2, 1);
-  }, "The invocation upper bound (1) must be >= "
-     "the invocation lower bound (2)");
-}
-
-TEST(BetweenTest, OnZeroStartAndZeroEnd) {
-  const Cardinality c = Between(0, 0);
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
-                      ss.str());
-}
-
-TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
-  const Cardinality c = Between(0, 2);
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(4));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(4));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice",
-                      ss.str());
-}
-
-TEST(BetweenTest, OnSameStartAndEnd) {
-  const Cardinality c = Between(3, 3);
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(2));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(2));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(3));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(3));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(4));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(4));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times",
-                      ss.str());
-}
-
-TEST(BetweenTest, OnDifferentStartAndEnd) {
-  const Cardinality c = Between(3, 5);
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(2));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(2));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(3));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(3));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(5));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(5));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(6));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(6));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times",
-                      ss.str());
-}
-
-TEST(BetweenTest, HasCorrectBounds) {
-  const Cardinality c = Between(3, 5);
-  EXPECT_EQ(3, c.ConservativeLowerBound());
-  EXPECT_EQ(5, c.ConservativeUpperBound());
-}
-
-// Tests Exactly(n).
-
-TEST(ExactlyTest, OnNegativeNumber) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Exactly(-1);
-  }, "The invocation lower bound must be >= 0");
-}
-
-TEST(ExactlyTest, OnZero) {
-  const Cardinality c = Exactly(0);
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(1));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
-                      ss.str());
-}
-
-TEST(ExactlyTest, OnPositiveNumber) {
-  const Cardinality c = Exactly(2);
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));
-  EXPECT_FALSE(c.IsSaturatedByCallCount(0));
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
-  EXPECT_TRUE(c.IsSaturatedByCallCount(2));
-
-  stringstream ss1;
-  Exactly(1).DescribeTo(&ss1);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called once",
-                      ss1.str());
-
-  stringstream ss2;
-  c.DescribeTo(&ss2);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called twice",
-                      ss2.str());
-
-  stringstream ss3;
-  Exactly(3).DescribeTo(&ss3);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times",
-                      ss3.str());
-}
-
-TEST(ExactlyTest, HasCorrectBounds) {
-  const Cardinality c = Exactly(3);
-  EXPECT_EQ(3, c.ConservativeLowerBound());
-  EXPECT_EQ(3, c.ConservativeUpperBound());
-}
-
-// Tests that a user can make his own cardinality by implementing
-// CardinalityInterface and calling MakeCardinality().
-
-class EvenCardinality : public CardinalityInterface {
- public:
-  // Returns true iff call_count calls will satisfy this cardinality.
-  virtual bool IsSatisfiedByCallCount(int call_count) const {
-    return (call_count % 2 == 0);
-  }
-
-  // Returns true iff call_count calls will saturate this cardinality.
-  virtual bool IsSaturatedByCallCount(int /* call_count */) const {
-    return false;
-  }
-
-  // Describes self to an ostream.
-  virtual void DescribeTo(::std::ostream* ss) const {
-    *ss << "called even number of times";
-  }
-};
-
-TEST(MakeCardinalityTest, ConstructsCardinalityFromInterface) {
-  const Cardinality c = MakeCardinality(new EvenCardinality);
-
-  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));
-  EXPECT_FALSE(c.IsSatisfiedByCallCount(3));
-
-  EXPECT_FALSE(c.IsSaturatedByCallCount(10000));
-
-  stringstream ss;
-  c.DescribeTo(&ss);
-  EXPECT_EQ("called even number of times", ss.str());
-}
-
-}  // Unnamed namespace
diff --git a/testing/gmock/test/gmock-generated-actions_test.cc b/testing/gmock/test/gmock-generated-actions_test.cc
deleted file mode 100644
index c2d2a0a..0000000
--- a/testing/gmock/test/gmock-generated-actions_test.cc
+++ /dev/null
@@ -1,1227 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in actions generated by a script.
-
-#include "gmock/gmock-generated-actions.h"
-
-#include <functional>
-#include <sstream>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace gmock_generated_actions_test {
-
-using ::std::plus;
-using ::std::string;
-using testing::get;
-using testing::make_tuple;
-using testing::tuple;
-using testing::tuple_element;
-using testing::_;
-using testing::Action;
-using testing::ActionInterface;
-using testing::ByRef;
-using testing::DoAll;
-using testing::Invoke;
-using testing::Return;
-using testing::ReturnNew;
-using testing::SetArgPointee;
-using testing::StaticAssertTypeEq;
-using testing::Unused;
-using testing::WithArgs;
-
-// For suppressing compiler warnings on conversion possibly losing precision.
-inline short Short(short n) { return n; }  // NOLINT
-inline char Char(char ch) { return ch; }
-
-// Sample functions and functors for testing various actions.
-int Nullary() { return 1; }
-
-class NullaryFunctor {
- public:
-  int operator()() { return 2; }
-};
-
-bool g_done = false;
-
-bool Unary(int x) { return x < 0; }
-
-const char* Plus1(const char* s) { return s + 1; }
-
-bool ByConstRef(const string& s) { return s == "Hi"; }
-
-const double g_double = 0;
-bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
-
-string ByNonConstRef(string& s) { return s += "+"; }  // NOLINT
-
-struct UnaryFunctor {
-  int operator()(bool x) { return x ? 1 : -1; }
-};
-
-const char* Binary(const char* input, short n) { return input + n; }  // NOLINT
-
-void VoidBinary(int, char) { g_done = true; }
-
-int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT
-
-void VoidTernary(int, char, bool) { g_done = true; }
-
-int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
-
-string Concat4(const char* s1, const char* s2, const char* s3,
-               const char* s4) {
-  return string(s1) + s2 + s3 + s4;
-}
-
-int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
-
-struct SumOf5Functor {
-  int operator()(int a, int b, int c, int d, int e) {
-    return a + b + c + d + e;
-  }
-};
-
-string Concat5(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5) {
-  return string(s1) + s2 + s3 + s4 + s5;
-}
-
-int SumOf6(int a, int b, int c, int d, int e, int f) {
-  return a + b + c + d + e + f;
-}
-
-struct SumOf6Functor {
-  int operator()(int a, int b, int c, int d, int e, int f) {
-    return a + b + c + d + e + f;
-  }
-};
-
-string Concat6(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6;
-}
-
-string Concat7(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6,
-               const char* s7) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
-}
-
-string Concat8(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6,
-               const char* s7, const char* s8) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
-}
-
-string Concat9(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6,
-               const char* s7, const char* s8, const char* s9) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
-}
-
-string Concat10(const char* s1, const char* s2, const char* s3,
-                const char* s4, const char* s5, const char* s6,
-                const char* s7, const char* s8, const char* s9,
-                const char* s10) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
-}
-
-// A helper that turns the type of a C-string literal from const
-// char[N] to const char*.
-inline const char* CharPtr(const char* s) { return s; }
-
-// Tests InvokeArgument<N>(...).
-
-// Tests using InvokeArgument with a nullary function.
-TEST(InvokeArgumentTest, Function0) {
-  Action<int(int, int(*)())> a = InvokeArgument<1>();  // NOLINT
-  EXPECT_EQ(1, a.Perform(make_tuple(2, &Nullary)));
-}
-
-// Tests using InvokeArgument with a unary function.
-TEST(InvokeArgumentTest, Functor1) {
-  Action<int(UnaryFunctor)> a = InvokeArgument<0>(true);  // NOLINT
-  EXPECT_EQ(1, a.Perform(make_tuple(UnaryFunctor())));
-}
-
-// Tests using InvokeArgument with a 5-ary function.
-TEST(InvokeArgumentTest, Function5) {
-  Action<int(int(*)(int, int, int, int, int))> a =  // NOLINT
-      InvokeArgument<0>(10000, 2000, 300, 40, 5);
-  EXPECT_EQ(12345, a.Perform(make_tuple(&SumOf5)));
-}
-
-// Tests using InvokeArgument with a 5-ary functor.
-TEST(InvokeArgumentTest, Functor5) {
-  Action<int(SumOf5Functor)> a =  // NOLINT
-      InvokeArgument<0>(10000, 2000, 300, 40, 5);
-  EXPECT_EQ(12345, a.Perform(make_tuple(SumOf5Functor())));
-}
-
-// Tests using InvokeArgument with a 6-ary function.
-TEST(InvokeArgumentTest, Function6) {
-  Action<int(int(*)(int, int, int, int, int, int))> a =  // NOLINT
-      InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
-  EXPECT_EQ(123456, a.Perform(make_tuple(&SumOf6)));
-}
-
-// Tests using InvokeArgument with a 6-ary functor.
-TEST(InvokeArgumentTest, Functor6) {
-  Action<int(SumOf6Functor)> a =  // NOLINT
-      InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
-  EXPECT_EQ(123456, a.Perform(make_tuple(SumOf6Functor())));
-}
-
-// Tests using InvokeArgument with a 7-ary function.
-TEST(InvokeArgumentTest, Function7) {
-  Action<string(string(*)(const char*, const char*, const char*,
-                          const char*, const char*, const char*,
-                          const char*))> a =
-      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
-  EXPECT_EQ("1234567", a.Perform(make_tuple(&Concat7)));
-}
-
-// Tests using InvokeArgument with a 8-ary function.
-TEST(InvokeArgumentTest, Function8) {
-  Action<string(string(*)(const char*, const char*, const char*,
-                          const char*, const char*, const char*,
-                          const char*, const char*))> a =
-      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
-  EXPECT_EQ("12345678", a.Perform(make_tuple(&Concat8)));
-}
-
-// Tests using InvokeArgument with a 9-ary function.
-TEST(InvokeArgumentTest, Function9) {
-  Action<string(string(*)(const char*, const char*, const char*,
-                          const char*, const char*, const char*,
-                          const char*, const char*, const char*))> a =
-      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
-  EXPECT_EQ("123456789", a.Perform(make_tuple(&Concat9)));
-}
-
-// Tests using InvokeArgument with a 10-ary function.
-TEST(InvokeArgumentTest, Function10) {
-  Action<string(string(*)(const char*, const char*, const char*,
-                          const char*, const char*, const char*,
-                          const char*, const char*, const char*,
-                          const char*))> a =
-      InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
-  EXPECT_EQ("1234567890", a.Perform(make_tuple(&Concat10)));
-}
-
-// Tests using InvokeArgument with a function that takes a pointer argument.
-TEST(InvokeArgumentTest, ByPointerFunction) {
-  Action<const char*(const char*(*)(const char* input, short n))> a =  // NOLINT
-      InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
-  EXPECT_STREQ("i", a.Perform(make_tuple(&Binary)));
-}
-
-// Tests using InvokeArgument with a function that takes a const char*
-// by passing it a C-string literal.
-TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
-  Action<const char*(const char*(*)(const char* input, short n))> a =  // NOLINT
-      InvokeArgument<0>("Hi", Short(1));
-  EXPECT_STREQ("i", a.Perform(make_tuple(&Binary)));
-}
-
-// Tests using InvokeArgument with a function that takes a const reference.
-TEST(InvokeArgumentTest, ByConstReferenceFunction) {
-  Action<bool(bool(*function)(const string& s))> a =  // NOLINT
-      InvokeArgument<0>(string("Hi"));
-  // When action 'a' is constructed, it makes a copy of the temporary
-  // string object passed to it, so it's OK to use 'a' later, when the
-  // temporary object has already died.
-  EXPECT_TRUE(a.Perform(make_tuple(&ByConstRef)));
-}
-
-// Tests using InvokeArgument with ByRef() and a function that takes a
-// const reference.
-TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
-  Action<bool(bool(*)(const double& x))> a =  // NOLINT
-      InvokeArgument<0>(ByRef(g_double));
-  // The above line calls ByRef() on a const value.
-  EXPECT_TRUE(a.Perform(make_tuple(&ReferencesGlobalDouble)));
-
-  double x = 0;
-  a = InvokeArgument<0>(ByRef(x));  // This calls ByRef() on a non-const.
-  EXPECT_FALSE(a.Perform(make_tuple(&ReferencesGlobalDouble)));
-}
-
-// Tests using WithArgs and with an action that takes 1 argument.
-TEST(WithArgsTest, OneArg) {
-  Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary));  // NOLINT
-  EXPECT_TRUE(a.Perform(make_tuple(1.5, -1)));
-  EXPECT_FALSE(a.Perform(make_tuple(1.5, 1)));
-}
-
-// Tests using WithArgs with an action that takes 2 arguments.
-TEST(WithArgsTest, TwoArgs) {
-  Action<const char*(const char* s, double x, short n)> a =
-      WithArgs<0, 2>(Invoke(Binary));
-  const char s[] = "Hello";
-  EXPECT_EQ(s + 2, a.Perform(make_tuple(CharPtr(s), 0.5, Short(2))));
-}
-
-// Tests using WithArgs with an action that takes 3 arguments.
-TEST(WithArgsTest, ThreeArgs) {
-  Action<int(int, double, char, short)> a =  // NOLINT
-      WithArgs<0, 2, 3>(Invoke(Ternary));
-  EXPECT_EQ(123, a.Perform(make_tuple(100, 6.5, Char(20), Short(3))));
-}
-
-// Tests using WithArgs with an action that takes 4 arguments.
-TEST(WithArgsTest, FourArgs) {
-  Action<string(const char*, const char*, double, const char*, const char*)> a =
-      WithArgs<4, 3, 1, 0>(Invoke(Concat4));
-  EXPECT_EQ("4310", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), 2.5,
-                                         CharPtr("3"), CharPtr("4"))));
-}
-
-// Tests using WithArgs with an action that takes 5 arguments.
-TEST(WithArgsTest, FiveArgs) {
-  Action<string(const char*, const char*, const char*,
-                const char*, const char*)> a =
-      WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5));
-  EXPECT_EQ("43210",
-            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
-                                 CharPtr("3"), CharPtr("4"))));
-}
-
-// Tests using WithArgs with an action that takes 6 arguments.
-TEST(WithArgsTest, SixArgs) {
-  Action<string(const char*, const char*, const char*)> a =
-      WithArgs<0, 1, 2, 2, 1, 0>(Invoke(Concat6));
-  EXPECT_EQ("012210",
-            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"))));
-}
-
-// Tests using WithArgs with an action that takes 7 arguments.
-TEST(WithArgsTest, SevenArgs) {
-  Action<string(const char*, const char*, const char*, const char*)> a =
-      WithArgs<0, 1, 2, 3, 2, 1, 0>(Invoke(Concat7));
-  EXPECT_EQ("0123210",
-            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
-                                 CharPtr("3"))));
-}
-
-// Tests using WithArgs with an action that takes 8 arguments.
-TEST(WithArgsTest, EightArgs) {
-  Action<string(const char*, const char*, const char*, const char*)> a =
-      WithArgs<0, 1, 2, 3, 0, 1, 2, 3>(Invoke(Concat8));
-  EXPECT_EQ("01230123",
-            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
-                                 CharPtr("3"))));
-}
-
-// Tests using WithArgs with an action that takes 9 arguments.
-TEST(WithArgsTest, NineArgs) {
-  Action<string(const char*, const char*, const char*, const char*)> a =
-      WithArgs<0, 1, 2, 3, 1, 2, 3, 2, 3>(Invoke(Concat9));
-  EXPECT_EQ("012312323",
-            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
-                                 CharPtr("3"))));
-}
-
-// Tests using WithArgs with an action that takes 10 arguments.
-TEST(WithArgsTest, TenArgs) {
-  Action<string(const char*, const char*, const char*, const char*)> a =
-      WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(Concat10));
-  EXPECT_EQ("0123210123",
-            a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
-                                 CharPtr("3"))));
-}
-
-// Tests using WithArgs with an action that is not Invoke().
-class SubstractAction : public ActionInterface<int(int, int)> {  // NOLINT
- public:
-  virtual int Perform(const tuple<int, int>& args) {
-    return get<0>(args) - get<1>(args);
-  }
-};
-
-TEST(WithArgsTest, NonInvokeAction) {
-  Action<int(const string&, int, int)> a =  // NOLINT
-      WithArgs<2, 1>(MakeAction(new SubstractAction));
-  EXPECT_EQ(8, a.Perform(make_tuple(string("hi"), 2, 10)));
-}
-
-// Tests using WithArgs to pass all original arguments in the original order.
-TEST(WithArgsTest, Identity) {
-  Action<int(int x, char y, short z)> a =  // NOLINT
-      WithArgs<0, 1, 2>(Invoke(Ternary));
-  EXPECT_EQ(123, a.Perform(make_tuple(100, Char(20), Short(3))));
-}
-
-// Tests using WithArgs with repeated arguments.
-TEST(WithArgsTest, RepeatedArguments) {
-  Action<int(bool, int m, int n)> a =  // NOLINT
-      WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
-  EXPECT_EQ(4, a.Perform(make_tuple(false, 1, 10)));
-}
-
-// Tests using WithArgs with reversed argument order.
-TEST(WithArgsTest, ReversedArgumentOrder) {
-  Action<const char*(short n, const char* input)> a =  // NOLINT
-      WithArgs<1, 0>(Invoke(Binary));
-  const char s[] = "Hello";
-  EXPECT_EQ(s + 2, a.Perform(make_tuple(Short(2), CharPtr(s))));
-}
-
-// Tests using WithArgs with compatible, but not identical, argument types.
-TEST(WithArgsTest, ArgsOfCompatibleTypes) {
-  Action<long(short x, char y, double z, char c)> a =  // NOLINT
-      WithArgs<0, 1, 3>(Invoke(Ternary));
-  EXPECT_EQ(123, a.Perform(make_tuple(Short(100), Char(20), 5.6, Char(3))));
-}
-
-// Tests using WithArgs with an action that returns void.
-TEST(WithArgsTest, VoidAction) {
-  Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
-  g_done = false;
-  a.Perform(make_tuple(1.5, 'a', 3));
-  EXPECT_TRUE(g_done);
-}
-
-// Tests DoAll(a1, a2).
-TEST(DoAllTest, TwoActions) {
-  int n = 0;
-  Action<int(int*)> a = DoAll(SetArgPointee<0>(1),  // NOLINT
-                              Return(2));
-  EXPECT_EQ(2, a.Perform(make_tuple(&n)));
-  EXPECT_EQ(1, n);
-}
-
-// Tests DoAll(a1, a2, a3).
-TEST(DoAllTest, ThreeActions) {
-  int m = 0, n = 0;
-  Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1),  // NOLINT
-                                    SetArgPointee<1>(2),
-                                    Return(3));
-  EXPECT_EQ(3, a.Perform(make_tuple(&m, &n)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-}
-
-// Tests DoAll(a1, a2, a3, a4).
-TEST(DoAllTest, FourActions) {
-  int m = 0, n = 0;
-  char ch = '\0';
-  Action<int(int*, int*, char*)> a =  // NOLINT
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            Return(3));
-  EXPECT_EQ(3, a.Perform(make_tuple(&m, &n, &ch)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', ch);
-}
-
-// Tests DoAll(a1, a2, a3, a4, a5).
-TEST(DoAllTest, FiveActions) {
-  int m = 0, n = 0;
-  char a = '\0', b = '\0';
-  Action<int(int*, int*, char*, char*)> action =  // NOLINT
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            SetArgPointee<3>('b'),
-            Return(3));
-  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', a);
-  EXPECT_EQ('b', b);
-}
-
-// Tests DoAll(a1, a2, ..., a6).
-TEST(DoAllTest, SixActions) {
-  int m = 0, n = 0;
-  char a = '\0', b = '\0', c = '\0';
-  Action<int(int*, int*, char*, char*, char*)> action =  // NOLINT
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            SetArgPointee<3>('b'),
-            SetArgPointee<4>('c'),
-            Return(3));
-  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', a);
-  EXPECT_EQ('b', b);
-  EXPECT_EQ('c', c);
-}
-
-// Tests DoAll(a1, a2, ..., a7).
-TEST(DoAllTest, SevenActions) {
-  int m = 0, n = 0;
-  char a = '\0', b = '\0', c = '\0', d = '\0';
-  Action<int(int*, int*, char*, char*, char*, char*)> action =  // NOLINT
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            SetArgPointee<3>('b'),
-            SetArgPointee<4>('c'),
-            SetArgPointee<5>('d'),
-            Return(3));
-  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', a);
-  EXPECT_EQ('b', b);
-  EXPECT_EQ('c', c);
-  EXPECT_EQ('d', d);
-}
-
-// Tests DoAll(a1, a2, ..., a8).
-TEST(DoAllTest, EightActions) {
-  int m = 0, n = 0;
-  char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
-  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT
-             char*)> action =
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            SetArgPointee<3>('b'),
-            SetArgPointee<4>('c'),
-            SetArgPointee<5>('d'),
-            SetArgPointee<6>('e'),
-            Return(3));
-  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', a);
-  EXPECT_EQ('b', b);
-  EXPECT_EQ('c', c);
-  EXPECT_EQ('d', d);
-  EXPECT_EQ('e', e);
-}
-
-// Tests DoAll(a1, a2, ..., a9).
-TEST(DoAllTest, NineActions) {
-  int m = 0, n = 0;
-  char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
-  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT
-             char*, char*)> action =
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            SetArgPointee<3>('b'),
-            SetArgPointee<4>('c'),
-            SetArgPointee<5>('d'),
-            SetArgPointee<6>('e'),
-            SetArgPointee<7>('f'),
-            Return(3));
-  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', a);
-  EXPECT_EQ('b', b);
-  EXPECT_EQ('c', c);
-  EXPECT_EQ('d', d);
-  EXPECT_EQ('e', e);
-  EXPECT_EQ('f', f);
-}
-
-// Tests DoAll(a1, a2, ..., a10).
-TEST(DoAllTest, TenActions) {
-  int m = 0, n = 0;
-  char a = '\0', b = '\0', c = '\0', d = '\0';
-  char e = '\0', f = '\0', g = '\0';
-  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT
-             char*, char*, char*)> action =
-      DoAll(SetArgPointee<0>(1),
-            SetArgPointee<1>(2),
-            SetArgPointee<2>('a'),
-            SetArgPointee<3>('b'),
-            SetArgPointee<4>('c'),
-            SetArgPointee<5>('d'),
-            SetArgPointee<6>('e'),
-            SetArgPointee<7>('f'),
-            SetArgPointee<8>('g'),
-            Return(3));
-  EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
-  EXPECT_EQ(1, m);
-  EXPECT_EQ(2, n);
-  EXPECT_EQ('a', a);
-  EXPECT_EQ('b', b);
-  EXPECT_EQ('c', c);
-  EXPECT_EQ('d', d);
-  EXPECT_EQ('e', e);
-  EXPECT_EQ('f', f);
-  EXPECT_EQ('g', g);
-}
-
-// The ACTION*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma.  Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-// Tests the ACTION*() macro family.
-
-// Tests that ACTION() can define an action that doesn't reference the
-// mock function arguments.
-ACTION(Return5) { return 5; }
-
-TEST(ActionMacroTest, WorksWhenNotReferencingArguments) {
-  Action<double()> a1 = Return5();
-  EXPECT_DOUBLE_EQ(5, a1.Perform(make_tuple()));
-
-  Action<int(double, bool)> a2 = Return5();
-  EXPECT_EQ(5, a2.Perform(make_tuple(1, true)));
-}
-
-// Tests that ACTION() can define an action that returns void.
-ACTION(IncrementArg1) { (*arg1)++; }
-
-TEST(ActionMacroTest, WorksWhenReturningVoid) {
-  Action<void(int, int*)> a1 = IncrementArg1();
-  int n = 0;
-  a1.Perform(make_tuple(5, &n));
-  EXPECT_EQ(1, n);
-}
-
-// Tests that the body of ACTION() can reference the type of the
-// argument.
-ACTION(IncrementArg2) {
-  StaticAssertTypeEq<int*, arg2_type>();
-  arg2_type temp = arg2;
-  (*temp)++;
-}
-
-TEST(ActionMacroTest, CanReferenceArgumentType) {
-  Action<void(int, bool, int*)> a1 = IncrementArg2();
-  int n = 0;
-  a1.Perform(make_tuple(5, false, &n));
-  EXPECT_EQ(1, n);
-}
-
-// Tests that the body of ACTION() can reference the argument tuple
-// via args_type and args.
-ACTION(Sum2) {
-  StaticAssertTypeEq<tuple<int, char, int*>, args_type>();
-  args_type args_copy = args;
-  return get<0>(args_copy) + get<1>(args_copy);
-}
-
-TEST(ActionMacroTest, CanReferenceArgumentTuple) {
-  Action<int(int, char, int*)> a1 = Sum2();
-  int dummy = 0;
-  EXPECT_EQ(11, a1.Perform(make_tuple(5, Char(6), &dummy)));
-}
-
-// Tests that the body of ACTION() can reference the mock function
-// type.
-int Dummy(bool flag) { return flag? 1 : 0; }
-
-ACTION(InvokeDummy) {
-  StaticAssertTypeEq<int(bool), function_type>();
-  function_type* fp = &Dummy;
-  return (*fp)(true);
-}
-
-TEST(ActionMacroTest, CanReferenceMockFunctionType) {
-  Action<int(bool)> a1 = InvokeDummy();
-  EXPECT_EQ(1, a1.Perform(make_tuple(true)));
-  EXPECT_EQ(1, a1.Perform(make_tuple(false)));
-}
-
-// Tests that the body of ACTION() can reference the mock function's
-// return type.
-ACTION(InvokeDummy2) {
-  StaticAssertTypeEq<int, return_type>();
-  return_type result = Dummy(true);
-  return result;
-}
-
-TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {
-  Action<int(bool)> a1 = InvokeDummy2();
-  EXPECT_EQ(1, a1.Perform(make_tuple(true)));
-  EXPECT_EQ(1, a1.Perform(make_tuple(false)));
-}
-
-// Tests that ACTION() works for arguments passed by const reference.
-ACTION(ReturnAddrOfConstBoolReferenceArg) {
-  StaticAssertTypeEq<const bool&, arg1_type>();
-  return &arg1;
-}
-
-TEST(ActionMacroTest, WorksForConstReferenceArg) {
-  Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();
-  const bool b = false;
-  EXPECT_EQ(&b, a.Perform(tuple<int, const bool&>(0, b)));
-}
-
-// Tests that ACTION() works for arguments passed by non-const reference.
-ACTION(ReturnAddrOfIntReferenceArg) {
-  StaticAssertTypeEq<int&, arg0_type>();
-  return &arg0;
-}
-
-TEST(ActionMacroTest, WorksForNonConstReferenceArg) {
-  Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();
-  int n = 0;
-  EXPECT_EQ(&n, a.Perform(tuple<int&, bool, int>(n, true, 1)));
-}
-
-// Tests that ACTION() can be used in a namespace.
-namespace action_test {
-ACTION(Sum) { return arg0 + arg1; }
-}  // namespace action_test
-
-TEST(ActionMacroTest, WorksInNamespace) {
-  Action<int(int, int)> a1 = action_test::Sum();
-  EXPECT_EQ(3, a1.Perform(make_tuple(1, 2)));
-}
-
-// Tests that the same ACTION definition works for mock functions with
-// different argument numbers.
-ACTION(PlusTwo) { return arg0 + 2; }
-
-TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {
-  Action<int(int)> a1 = PlusTwo();
-  EXPECT_EQ(4, a1.Perform(make_tuple(2)));
-
-  Action<double(float, void*)> a2 = PlusTwo();
-  int dummy;
-  EXPECT_DOUBLE_EQ(6, a2.Perform(make_tuple(4.0f, &dummy)));
-}
-
-// Tests that ACTION_P can define a parameterized action.
-ACTION_P(Plus, n) { return arg0 + n; }
-
-TEST(ActionPMacroTest, DefinesParameterizedAction) {
-  Action<int(int m, bool t)> a1 = Plus(9);
-  EXPECT_EQ(10, a1.Perform(make_tuple(1, true)));
-}
-
-// Tests that the body of ACTION_P can reference the argument types
-// and the parameter type.
-ACTION_P(TypedPlus, n) {
-  arg0_type t1 = arg0;
-  n_type t2 = n;
-  return t1 + t2;
-}
-
-TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
-  Action<int(char m, bool t)> a1 = TypedPlus(9);
-  EXPECT_EQ(10, a1.Perform(make_tuple(Char(1), true)));
-}
-
-// Tests that a parameterized action can be used in any mock function
-// whose type is compatible.
-TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
-  Action<std::string(const std::string& s)> a1 = Plus("tail");
-  const std::string re = "re";
-  EXPECT_EQ("retail", a1.Perform(make_tuple(re)));
-}
-
-// Tests that we can use ACTION*() to define actions overloaded on the
-// number of parameters.
-
-ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; }
-
-ACTION_P(OverloadedAction, default_value) {
-  return arg0 ? arg1 : default_value;
-}
-
-ACTION_P2(OverloadedAction, true_value, false_value) {
-  return arg0 ? true_value : false_value;
-}
-
-TEST(ActionMacroTest, CanDefineOverloadedActions) {
-  typedef Action<const char*(bool, const char*)> MyAction;
-
-  const MyAction a1 = OverloadedAction();
-  EXPECT_STREQ("hello", a1.Perform(make_tuple(false, CharPtr("world"))));
-  EXPECT_STREQ("world", a1.Perform(make_tuple(true, CharPtr("world"))));
-
-  const MyAction a2 = OverloadedAction("hi");
-  EXPECT_STREQ("hi", a2.Perform(make_tuple(false, CharPtr("world"))));
-  EXPECT_STREQ("world", a2.Perform(make_tuple(true, CharPtr("world"))));
-
-  const MyAction a3 = OverloadedAction("hi", "you");
-  EXPECT_STREQ("hi", a3.Perform(make_tuple(true, CharPtr("world"))));
-  EXPECT_STREQ("you", a3.Perform(make_tuple(false, CharPtr("world"))));
-}
-
-// Tests ACTION_Pn where n >= 3.
-
-ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }
-
-TEST(ActionPnMacroTest, WorksFor3Parameters) {
-  Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);
-  EXPECT_DOUBLE_EQ(3123.4, a1.Perform(make_tuple(3000, true)));
-
-  Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
-  const std::string re = "re";
-  EXPECT_EQ("retail->", a2.Perform(make_tuple(re)));
-}
-
-ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
-
-TEST(ActionPnMacroTest, WorksFor4Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(make_tuple(10)));
-}
-
-ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }
-
-TEST(ActionPnMacroTest, WorksFor5Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(make_tuple(10)));
-}
-
-ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {
-  return arg0 + p0 + p1 + p2 + p3 + p4 + p5;
-}
-
-TEST(ActionPnMacroTest, WorksFor6Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(make_tuple(10)));
-}
-
-ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {
-  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;
-}
-
-TEST(ActionPnMacroTest, WorksFor7Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(make_tuple(10)));
-}
-
-ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {
-  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;
-}
-
-TEST(ActionPnMacroTest, WorksFor8Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(make_tuple(10)));
-}
-
-ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {
-  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
-}
-
-TEST(ActionPnMacroTest, WorksFor9Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(make_tuple(10)));
-}
-
-ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {
-  arg0_type t0 = arg0;
-  last_param_type t9 = last_param;
-  return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;
-}
-
-TEST(ActionPnMacroTest, WorksFor10Parameters) {
-  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
-  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
-            a1.Perform(make_tuple(10)));
-}
-
-// Tests that the action body can promote the parameter types.
-
-ACTION_P2(PadArgument, prefix, suffix) {
-  // The following lines promote the two parameters to desired types.
-  std::string prefix_str(prefix);
-  char suffix_char = static_cast<char>(suffix);
-  return prefix_str + arg0 + suffix_char;
-}
-
-TEST(ActionPnMacroTest, SimpleTypePromotion) {
-  Action<std::string(const char*)> no_promo =
-      PadArgument(std::string("foo"), 'r');
-  Action<std::string(const char*)> promo =
-      PadArgument("foo", static_cast<int>('r'));
-  EXPECT_EQ("foobar", no_promo.Perform(make_tuple(CharPtr("ba"))));
-  EXPECT_EQ("foobar", promo.Perform(make_tuple(CharPtr("ba"))));
-}
-
-// Tests that we can partially restrict parameter types using a
-// straight-forward pattern.
-
-// Defines a generic action that doesn't restrict the types of its
-// parameters.
-ACTION_P3(ConcatImpl, a, b, c) {
-  std::stringstream ss;
-  ss << a << b << c;
-  return ss.str();
-}
-
-// Next, we try to restrict that either the first parameter is a
-// string, or the second parameter is an int.
-
-// Defines a partially specialized wrapper that restricts the first
-// parameter to std::string.
-template <typename T1, typename T2>
-// ConcatImplActionP3 is the class template ACTION_P3 uses to
-// implement ConcatImpl.  We shouldn't change the name as this
-// pattern requires the user to use it directly.
-ConcatImplActionP3<std::string, T1, T2>
-Concat(const std::string& a, T1 b, T2 c) {
-  GTEST_INTENTIONAL_CONST_COND_PUSH_()
-  if (true) {
-  GTEST_INTENTIONAL_CONST_COND_POP_()
-    // This branch verifies that ConcatImpl() can be invoked without
-    // explicit template arguments.
-    return ConcatImpl(a, b, c);
-  } else {
-    // This branch verifies that ConcatImpl() can also be invoked with
-    // explicit template arguments.  It doesn't really need to be
-    // executed as this is a compile-time verification.
-    return ConcatImpl<std::string, T1, T2>(a, b, c);
-  }
-}
-
-// Defines another partially specialized wrapper that restricts the
-// second parameter to int.
-template <typename T1, typename T2>
-ConcatImplActionP3<T1, int, T2>
-Concat(T1 a, int b, T2 c) {
-  return ConcatImpl(a, b, c);
-}
-
-TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {
-  Action<const std::string()> a1 = Concat("Hello", "1", 2);
-  EXPECT_EQ("Hello12", a1.Perform(make_tuple()));
-
-  a1 = Concat(1, 2, 3);
-  EXPECT_EQ("123", a1.Perform(make_tuple()));
-}
-
-// Verifies the type of an ACTION*.
-
-ACTION(DoFoo) {}
-ACTION_P(DoFoo, p) {}
-ACTION_P2(DoFoo, p0, p1) {}
-
-TEST(ActionPnMacroTest, TypesAreCorrect) {
-  // DoFoo() must be assignable to a DoFooAction variable.
-  DoFooAction a0 = DoFoo();
-
-  // DoFoo(1) must be assignable to a DoFooActionP variable.
-  DoFooActionP<int> a1 = DoFoo(1);
-
-  // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk
-  // variable, and so on.
-  DoFooActionP2<int, char> a2 = DoFoo(1, '2');
-  PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');
-  PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');
-  PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');
-  PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');
-  PlusActionP7<int, int, int, int, int, int, char> a7 =
-      Plus(1, 2, 3, 4, 5, 6, '7');
-  PlusActionP8<int, int, int, int, int, int, int, char> a8 =
-      Plus(1, 2, 3, 4, 5, 6, 7, '8');
-  PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =
-      Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
-  PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
-      Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
-
-  // Avoid "unused variable" warnings.
-  (void)a0;
-  (void)a1;
-  (void)a2;
-  (void)a3;
-  (void)a4;
-  (void)a5;
-  (void)a6;
-  (void)a7;
-  (void)a8;
-  (void)a9;
-  (void)a10;
-}
-
-// Tests that an ACTION_P*() action can be explicitly instantiated
-// with reference-typed parameters.
-
-ACTION_P(Plus1, x) { return x; }
-ACTION_P2(Plus2, x, y) { return x + y; }
-ACTION_P3(Plus3, x, y, z) { return x + y + z; }
-ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
-  return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;
-}
-
-TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
-  int x = 1, y = 2, z = 3;
-  const tuple<> empty = make_tuple();
-
-  Action<int()> a = Plus1<int&>(x);
-  EXPECT_EQ(1, a.Perform(empty));
-
-  a = Plus2<const int&, int&>(x, y);
-  EXPECT_EQ(3, a.Perform(empty));
-
-  a = Plus3<int&, const int&, int&>(x, y, z);
-  EXPECT_EQ(6, a.Perform(empty));
-
-  int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
-  a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
-      int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7],
-                              n[8], n[9]);
-  EXPECT_EQ(55, a.Perform(empty));
-}
-
-class NullaryConstructorClass {
- public:
-  NullaryConstructorClass() : value_(123) {}
-  int value_;
-};
-
-// Tests using ReturnNew() with a nullary constructor.
-TEST(ReturnNewTest, NoArgs) {
-  Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>();
-  NullaryConstructorClass* c = a.Perform(make_tuple());
-  EXPECT_EQ(123, c->value_);
-  delete c;
-}
-
-class UnaryConstructorClass {
- public:
-  explicit UnaryConstructorClass(int value) : value_(value) {}
-  int value_;
-};
-
-// Tests using ReturnNew() with a unary constructor.
-TEST(ReturnNewTest, Unary) {
-  Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
-  UnaryConstructorClass* c = a.Perform(make_tuple());
-  EXPECT_EQ(4000, c->value_);
-  delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
-  Action<UnaryConstructorClass*(bool, int)> a =
-      ReturnNew<UnaryConstructorClass>(4000);
-  UnaryConstructorClass* c = a.Perform(make_tuple(false, 5));
-  EXPECT_EQ(4000, c->value_);
-  delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
-  Action<const UnaryConstructorClass*()> a =
-      ReturnNew<UnaryConstructorClass>(4000);
-  const UnaryConstructorClass* c = a.Perform(make_tuple());
-  EXPECT_EQ(4000, c->value_);
-  delete c;
-}
-
-class TenArgConstructorClass {
- public:
-  TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5,
-                         int a6, int a7, int a8, int a9, int a10)
-    : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {
-  }
-  int value_;
-};
-
-// Tests using ReturnNew() with a 10-argument constructor.
-TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
-  Action<TenArgConstructorClass*()> a =
-      ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000,
-                                        4000000, 500000, 60000,
-                                        7000, 800, 90, 0);
-  TenArgConstructorClass* c = a.Perform(make_tuple());
-  EXPECT_EQ(1234567890, c->value_);
-  delete c;
-}
-
-// Tests that ACTION_TEMPLATE works when there is no value parameter.
-ACTION_TEMPLATE(CreateNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_0_VALUE_PARAMS()) {
-  return new T;
-}
-
-TEST(ActionTemplateTest, WorksWithoutValueParam) {
-  const Action<int*()> a = CreateNew<int>();
-  int* p = a.Perform(make_tuple());
-  delete p;
-}
-
-// Tests that ACTION_TEMPLATE works when there are value parameters.
-ACTION_TEMPLATE(CreateNew,
-                HAS_1_TEMPLATE_PARAMS(typename, T),
-                AND_1_VALUE_PARAMS(a0)) {
-  return new T(a0);
-}
-
-TEST(ActionTemplateTest, WorksWithValueParams) {
-  const Action<int*()> a = CreateNew<int>(42);
-  int* p = a.Perform(make_tuple());
-  EXPECT_EQ(42, *p);
-  delete p;
-}
-
-// Tests that ACTION_TEMPLATE works for integral template parameters.
-ACTION_TEMPLATE(MyDeleteArg,
-                HAS_1_TEMPLATE_PARAMS(int, k),
-                AND_0_VALUE_PARAMS()) {
-  delete get<k>(args);
-}
-
-// Resets a bool variable in the destructor.
-class BoolResetter {
- public:
-  explicit BoolResetter(bool* value) : value_(value) {}
-  ~BoolResetter() { *value_ = false; }
- private:
-  bool* value_;
-};
-
-TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
-  const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
-  int n = 0;
-  bool b = true;
-  BoolResetter* resetter = new BoolResetter(&b);
-  a.Perform(make_tuple(&n, resetter));
-  EXPECT_FALSE(b);  // Verifies that resetter is deleted.
-}
-
-// Tests that ACTION_TEMPLATES works for template template parameters.
-ACTION_TEMPLATE(ReturnSmartPointer,
-                HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
-                                      Pointer),
-                AND_1_VALUE_PARAMS(pointee)) {
-  return Pointer<pointee_type>(new pointee_type(pointee));
-}
-
-TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
-  using ::testing::internal::linked_ptr;
-  const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42);
-  linked_ptr<int> p = a.Perform(make_tuple());
-  EXPECT_EQ(42, *p);
-}
-
-// Tests that ACTION_TEMPLATE works for 10 template parameters.
-template <typename T1, typename T2, typename T3, int k4, bool k5,
-          unsigned int k6, typename T7, typename T8, typename T9>
-struct GiantTemplate {
- public:
-  explicit GiantTemplate(int a_value) : value(a_value) {}
-  int value;
-};
-
-ACTION_TEMPLATE(ReturnGiant,
-                HAS_10_TEMPLATE_PARAMS(
-                    typename, T1,
-                    typename, T2,
-                    typename, T3,
-                    int, k4,
-                    bool, k5,
-                    unsigned int, k6,
-                    class, T7,
-                    class, T8,
-                    class, T9,
-                    template <typename T> class, T10),
-                AND_1_VALUE_PARAMS(value)) {
-  return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
-}
-
-TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
-  using ::testing::internal::linked_ptr;
-  typedef GiantTemplate<linked_ptr<int>, bool, double, 5,
-      true, 6, char, unsigned, int> Giant;
-  const Action<Giant()> a = ReturnGiant<
-      int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42);
-  Giant giant = a.Perform(make_tuple());
-  EXPECT_EQ(42, giant.value);
-}
-
-// Tests that ACTION_TEMPLATE works for 10 value parameters.
-ACTION_TEMPLATE(ReturnSum,
-                HAS_1_TEMPLATE_PARAMS(typename, Number),
-                AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
-  return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
-}
-
-TEST(ActionTemplateTest, WorksFor10ValueParameters) {
-  const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
-  EXPECT_EQ(55, a.Perform(make_tuple()));
-}
-
-// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded
-// on the number of value parameters.
-
-ACTION(ReturnSum) { return 0; }
-
-ACTION_P(ReturnSum, x) { return x; }
-
-ACTION_TEMPLATE(ReturnSum,
-                HAS_1_TEMPLATE_PARAMS(typename, Number),
-                AND_2_VALUE_PARAMS(v1, v2)) {
-  return static_cast<Number>(v1) + v2;
-}
-
-ACTION_TEMPLATE(ReturnSum,
-                HAS_1_TEMPLATE_PARAMS(typename, Number),
-                AND_3_VALUE_PARAMS(v1, v2, v3)) {
-  return static_cast<Number>(v1) + v2 + v3;
-}
-
-ACTION_TEMPLATE(ReturnSum,
-                HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
-                AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
-  return static_cast<Number>(v1) + v2 + v3 + v4 + k;
-}
-
-TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
-  const Action<int()> a0 = ReturnSum();
-  const Action<int()> a1 = ReturnSum(1);
-  const Action<int()> a2 = ReturnSum<int>(1, 2);
-  const Action<int()> a3 = ReturnSum<int>(1, 2, 3);
-  const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);
-  EXPECT_EQ(0, a0.Perform(make_tuple()));
-  EXPECT_EQ(1, a1.Perform(make_tuple()));
-  EXPECT_EQ(3, a2.Perform(make_tuple()));
-  EXPECT_EQ(6, a3.Perform(make_tuple()));
-  EXPECT_EQ(12345, a4.Perform(make_tuple()));
-}
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-}  // namespace gmock_generated_actions_test
-}  // namespace testing
diff --git a/testing/gmock/test/gmock-generated-function-mockers_test.cc b/testing/gmock/test/gmock-generated-function-mockers_test.cc
deleted file mode 100644
index a86a613..0000000
--- a/testing/gmock/test/gmock-generated-function-mockers_test.cc
+++ /dev/null
@@ -1,622 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the function mocker classes.
-
-#include "gmock/gmock-generated-function-mockers.h"
-
-#if GTEST_OS_WINDOWS
-// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
-// we are getting compiler errors if we use basetyps.h, hence including
-// objbase.h for definition of STDMETHOD.
-# include <objbase.h>
-#endif  // GTEST_OS_WINDOWS
-
-#include <map>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-// There is a bug in MSVC (fixed in VS 2008) that prevents creating a
-// mock for a function with const arguments, so we don't test such
-// cases for MSVC versions older than 2008.
-#if !GTEST_OS_WINDOWS || (_MSC_VER >= 1500)
-# define GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
-#endif  // !GTEST_OS_WINDOWS || (_MSC_VER >= 1500)
-
-namespace testing {
-namespace gmock_generated_function_mockers_test {
-
-using testing::internal::string;
-using testing::_;
-using testing::A;
-using testing::An;
-using testing::AnyNumber;
-using testing::Const;
-using testing::DoDefault;
-using testing::Eq;
-using testing::Lt;
-using testing::MockFunction;
-using testing::Ref;
-using testing::Return;
-using testing::ReturnRef;
-using testing::TypedEq;
-
-class FooInterface {
- public:
-  virtual ~FooInterface() {}
-
-  virtual void VoidReturning(int x) = 0;
-
-  virtual int Nullary() = 0;
-  virtual bool Unary(int x) = 0;
-  virtual long Binary(short x, int y) = 0;  // NOLINT
-  virtual int Decimal(bool b, char c, short d, int e, long f,  // NOLINT
-                      float g, double h, unsigned i, char* j, const string& k)
-      = 0;
-
-  virtual bool TakesNonConstReference(int& n) = 0;  // NOLINT
-  virtual string TakesConstReference(const int& n) = 0;
-#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
-  virtual bool TakesConst(const int x) = 0;
-#endif  // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
-
-  virtual int OverloadedOnArgumentNumber() = 0;
-  virtual int OverloadedOnArgumentNumber(int n) = 0;
-
-  virtual int OverloadedOnArgumentType(int n) = 0;
-  virtual char OverloadedOnArgumentType(char c) = 0;
-
-  virtual int OverloadedOnConstness() = 0;
-  virtual char OverloadedOnConstness() const = 0;
-
-  virtual int TypeWithHole(int (*func)()) = 0;
-  virtual int TypeWithComma(const std::map<int, string>& a_map) = 0;
-
-#if GTEST_OS_WINDOWS
-  STDMETHOD_(int, CTNullary)() = 0;
-  STDMETHOD_(bool, CTUnary)(int x) = 0;
-  STDMETHOD_(int, CTDecimal)(bool b, char c, short d, int e, long f,  // NOLINT
-      float g, double h, unsigned i, char* j, const string& k) = 0;
-  STDMETHOD_(char, CTConst)(int x) const = 0;
-#endif  // GTEST_OS_WINDOWS
-};
-
-// Const qualifiers on arguments were once (incorrectly) considered
-// significant in determining whether two virtual functions had the same
-// signature. This was fixed in Visual Studio 2008. However, the compiler
-// still emits a warning that alerts about this change in behavior.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable : 4373)
-#endif
-class MockFoo : public FooInterface {
- public:
-  MockFoo() {}
-
-  // Makes sure that a mock function parameter can be named.
-  MOCK_METHOD1(VoidReturning, void(int n));  // NOLINT
-
-  MOCK_METHOD0(Nullary, int());  // NOLINT
-
-  // Makes sure that a mock function parameter can be unnamed.
-  MOCK_METHOD1(Unary, bool(int));  // NOLINT
-  MOCK_METHOD2(Binary, long(short, int));  // NOLINT
-  MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float,  // NOLINT
-                             double, unsigned, char*, const string& str));
-
-  MOCK_METHOD1(TakesNonConstReference, bool(int&));  // NOLINT
-  MOCK_METHOD1(TakesConstReference, string(const int&));
-
-#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
-  MOCK_METHOD1(TakesConst, bool(const int));  // NOLINT
-#endif
-
-  // Tests that the function return type can contain unprotected comma.
-  MOCK_METHOD0(ReturnTypeWithComma, std::map<int, string>());
-  MOCK_CONST_METHOD1(ReturnTypeWithComma,
-                     std::map<int, string>(int));  // NOLINT
-
-  MOCK_METHOD0(OverloadedOnArgumentNumber, int());  // NOLINT
-  MOCK_METHOD1(OverloadedOnArgumentNumber, int(int));  // NOLINT
-
-  MOCK_METHOD1(OverloadedOnArgumentType, int(int));  // NOLINT
-  MOCK_METHOD1(OverloadedOnArgumentType, char(char));  // NOLINT
-
-  MOCK_METHOD0(OverloadedOnConstness, int());  // NOLINT
-  MOCK_CONST_METHOD0(OverloadedOnConstness, char());  // NOLINT
-
-  MOCK_METHOD1(TypeWithHole, int(int (*)()));  // NOLINT
-  MOCK_METHOD1(TypeWithComma, int(const std::map<int, string>&));  // NOLINT
-
-#if GTEST_OS_WINDOWS
-  MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
-  MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));
-  MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c,
-      short d, int e, long f, float g, double h, unsigned i, char* j,
-      const string& k));
-  MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int));
-
-  // Tests that the function return type can contain unprotected comma.
-  MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
-                             std::map<int, string>());
-#endif  // GTEST_OS_WINDOWS
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
-};
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-class FunctionMockerTest : public testing::Test {
- protected:
-  FunctionMockerTest() : foo_(&mock_foo_) {}
-
-  FooInterface* const foo_;
-  MockFoo mock_foo_;
-};
-
-// Tests mocking a void-returning function.
-TEST_F(FunctionMockerTest, MocksVoidFunction) {
-  EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
-  foo_->VoidReturning(0);
-}
-
-// Tests mocking a nullary function.
-TEST_F(FunctionMockerTest, MocksNullaryFunction) {
-  EXPECT_CALL(mock_foo_, Nullary())
-      .WillOnce(DoDefault())
-      .WillOnce(Return(1));
-
-  EXPECT_EQ(0, foo_->Nullary());
-  EXPECT_EQ(1, foo_->Nullary());
-}
-
-// Tests mocking a unary function.
-TEST_F(FunctionMockerTest, MocksUnaryFunction) {
-  EXPECT_CALL(mock_foo_, Unary(Eq(2)))
-      .Times(2)
-      .WillOnce(Return(true));
-
-  EXPECT_TRUE(foo_->Unary(2));
-  EXPECT_FALSE(foo_->Unary(2));
-}
-
-// Tests mocking a binary function.
-TEST_F(FunctionMockerTest, MocksBinaryFunction) {
-  EXPECT_CALL(mock_foo_, Binary(2, _))
-      .WillOnce(Return(3));
-
-  EXPECT_EQ(3, foo_->Binary(2, 1));
-}
-
-// Tests mocking a decimal function.
-TEST_F(FunctionMockerTest, MocksDecimalFunction) {
-  EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
-                                 Lt(100), 5U, NULL, "hi"))
-      .WillOnce(Return(5));
-
-  EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
-}
-
-// Tests mocking a function that takes a non-const reference.
-TEST_F(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
-  int a = 0;
-  EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
-      .WillOnce(Return(true));
-
-  EXPECT_TRUE(foo_->TakesNonConstReference(a));
-}
-
-// Tests mocking a function that takes a const reference.
-TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
-  int a = 0;
-  EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
-      .WillOnce(Return("Hello"));
-
-  EXPECT_EQ("Hello", foo_->TakesConstReference(a));
-}
-
-#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
-// Tests mocking a function that takes a const variable.
-TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
-  EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
-      .WillOnce(DoDefault());
-
-  EXPECT_FALSE(foo_->TakesConst(5));
-}
-#endif  // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
-
-// Tests mocking functions overloaded on the number of arguments.
-TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
-  EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
-      .WillOnce(Return(1));
-  EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
-      .WillOnce(Return(2));
-
-  EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
-  EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
-}
-
-// Tests mocking functions overloaded on the types of argument.
-TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
-  EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
-      .WillOnce(Return(1));
-  EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
-      .WillOnce(Return('b'));
-
-  EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
-  EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
-}
-
-// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
-  EXPECT_CALL(mock_foo_, OverloadedOnConstness());
-  EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
-      .WillOnce(Return('a'));
-
-  EXPECT_EQ(0, foo_->OverloadedOnConstness());
-  EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
-}
-
-TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
-  const std::map<int, string> a_map;
-  EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
-      .WillOnce(Return(a_map));
-  EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
-      .WillOnce(Return(a_map));
-
-  EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
-  EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
-}
-
-#if GTEST_OS_WINDOWS
-// Tests mocking a nullary function with calltype.
-TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
-  EXPECT_CALL(mock_foo_, CTNullary())
-      .WillOnce(Return(-1))
-      .WillOnce(Return(0));
-
-  EXPECT_EQ(-1, foo_->CTNullary());
-  EXPECT_EQ(0, foo_->CTNullary());
-}
-
-// Tests mocking a unary function with calltype.
-TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
-  EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
-      .Times(2)
-      .WillOnce(Return(true))
-      .WillOnce(Return(false));
-
-  EXPECT_TRUE(foo_->CTUnary(2));
-  EXPECT_FALSE(foo_->CTUnary(2));
-}
-
-// Tests mocking a decimal function with calltype.
-TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
-  EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
-                                   Lt(100), 5U, NULL, "hi"))
-      .WillOnce(Return(10));
-
-  EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
-}
-
-// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
-  EXPECT_CALL(Const(mock_foo_), CTConst(_))
-      .WillOnce(Return('a'));
-
-  EXPECT_EQ('a', Const(*foo_).CTConst(0));
-}
-
-TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
-  const std::map<int, string> a_map;
-  EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
-      .WillOnce(Return(a_map));
-
-  EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
-}
-
-#endif  // GTEST_OS_WINDOWS
-
-class MockB {
- public:
-  MockB() {}
-
-  MOCK_METHOD0(DoB, void());
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
-};
-
-// Tests that functions with no EXPECT_CALL() ruls can be called any
-// number of times.
-TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
-  {
-    MockB b;
-  }
-
-  {
-    MockB b;
-    b.DoB();
-  }
-
-  {
-    MockB b;
-    b.DoB();
-    b.DoB();
-  }
-}
-
-// Tests mocking template interfaces.
-
-template <typename T>
-class StackInterface {
- public:
-  virtual ~StackInterface() {}
-
-  // Template parameter appears in function parameter.
-  virtual void Push(const T& value) = 0;
-  virtual void Pop() = 0;
-  virtual int GetSize() const = 0;
-  // Template parameter appears in function return type.
-  virtual const T& GetTop() const = 0;
-};
-
-template <typename T>
-class MockStack : public StackInterface<T> {
- public:
-  MockStack() {}
-
-  MOCK_METHOD1_T(Push, void(const T& elem));
-  MOCK_METHOD0_T(Pop, void());
-  MOCK_CONST_METHOD0_T(GetSize, int());  // NOLINT
-  MOCK_CONST_METHOD0_T(GetTop, const T&());
-
-  // Tests that the function return type can contain unprotected comma.
-  MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
-  MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int));  // NOLINT
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
-};
-
-// Tests that template mock works.
-TEST(TemplateMockTest, Works) {
-  MockStack<int> mock;
-
-  EXPECT_CALL(mock, GetSize())
-      .WillOnce(Return(0))
-      .WillOnce(Return(1))
-      .WillOnce(Return(0));
-  EXPECT_CALL(mock, Push(_));
-  int n = 5;
-  EXPECT_CALL(mock, GetTop())
-      .WillOnce(ReturnRef(n));
-  EXPECT_CALL(mock, Pop())
-      .Times(AnyNumber());
-
-  EXPECT_EQ(0, mock.GetSize());
-  mock.Push(5);
-  EXPECT_EQ(1, mock.GetSize());
-  EXPECT_EQ(5, mock.GetTop());
-  mock.Pop();
-  EXPECT_EQ(0, mock.GetSize());
-}
-
-TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
-  MockStack<int> mock;
-
-  const std::map<int, int> a_map;
-  EXPECT_CALL(mock, ReturnTypeWithComma())
-      .WillOnce(Return(a_map));
-  EXPECT_CALL(mock, ReturnTypeWithComma(1))
-      .WillOnce(Return(a_map));
-
-  EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
-  EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
-}
-
-#if GTEST_OS_WINDOWS
-// Tests mocking template interfaces with calltype.
-
-template <typename T>
-class StackInterfaceWithCallType {
- public:
-  virtual ~StackInterfaceWithCallType() {}
-
-  // Template parameter appears in function parameter.
-  STDMETHOD_(void, Push)(const T& value) = 0;
-  STDMETHOD_(void, Pop)() = 0;
-  STDMETHOD_(int, GetSize)() const = 0;
-  // Template parameter appears in function return type.
-  STDMETHOD_(const T&, GetTop)() const = 0;
-};
-
-template <typename T>
-class MockStackWithCallType : public StackInterfaceWithCallType<T> {
- public:
-  MockStackWithCallType() {}
-
-  MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
-  MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
-  MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
-  MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
-};
-
-// Tests that template mock with calltype works.
-TEST(TemplateMockTestWithCallType, Works) {
-  MockStackWithCallType<int> mock;
-
-  EXPECT_CALL(mock, GetSize())
-      .WillOnce(Return(0))
-      .WillOnce(Return(1))
-      .WillOnce(Return(0));
-  EXPECT_CALL(mock, Push(_));
-  int n = 5;
-  EXPECT_CALL(mock, GetTop())
-      .WillOnce(ReturnRef(n));
-  EXPECT_CALL(mock, Pop())
-      .Times(AnyNumber());
-
-  EXPECT_EQ(0, mock.GetSize());
-  mock.Push(5);
-  EXPECT_EQ(1, mock.GetSize());
-  EXPECT_EQ(5, mock.GetTop());
-  mock.Pop();
-  EXPECT_EQ(0, mock.GetSize());
-}
-#endif  // GTEST_OS_WINDOWS
-
-#define MY_MOCK_METHODS1_ \
-    MOCK_METHOD0(Overloaded, void()); \
-    MOCK_CONST_METHOD1(Overloaded, int(int n)); \
-    MOCK_METHOD2(Overloaded, bool(bool f, int n))
-
-class MockOverloadedOnArgNumber {
- public:
-  MockOverloadedOnArgNumber() {}
-
-  MY_MOCK_METHODS1_;
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
-};
-
-TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
-  MockOverloadedOnArgNumber mock;
-  EXPECT_CALL(mock, Overloaded());
-  EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
-  EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
-
-  mock.Overloaded();
-  EXPECT_EQ(2, mock.Overloaded(1));
-  EXPECT_TRUE(mock.Overloaded(true, 1));
-}
-
-#define MY_MOCK_METHODS2_ \
-    MOCK_CONST_METHOD1(Overloaded, int(int n)); \
-    MOCK_METHOD1(Overloaded, int(int n));
-
-class MockOverloadedOnConstness {
- public:
-  MockOverloadedOnConstness() {}
-
-  MY_MOCK_METHODS2_;
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
-};
-
-TEST(OverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
-  MockOverloadedOnConstness mock;
-  const MockOverloadedOnConstness* const_mock = &mock;
-  EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
-  EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));
-
-  EXPECT_EQ(2, mock.Overloaded(1));
-  EXPECT_EQ(3, const_mock->Overloaded(1));
-}
-
-TEST(MockFunctionTest, WorksForVoidNullary) {
-  MockFunction<void()> foo;
-  EXPECT_CALL(foo, Call());
-  foo.Call();
-}
-
-TEST(MockFunctionTest, WorksForNonVoidNullary) {
-  MockFunction<int()> foo;
-  EXPECT_CALL(foo, Call())
-      .WillOnce(Return(1))
-      .WillOnce(Return(2));
-  EXPECT_EQ(1, foo.Call());
-  EXPECT_EQ(2, foo.Call());
-}
-
-TEST(MockFunctionTest, WorksForVoidUnary) {
-  MockFunction<void(int)> foo;
-  EXPECT_CALL(foo, Call(1));
-  foo.Call(1);
-}
-
-TEST(MockFunctionTest, WorksForNonVoidBinary) {
-  MockFunction<int(bool, int)> foo;
-  EXPECT_CALL(foo, Call(false, 42))
-      .WillOnce(Return(1))
-      .WillOnce(Return(2));
-  EXPECT_CALL(foo, Call(true, Ge(100)))
-      .WillOnce(Return(3));
-  EXPECT_EQ(1, foo.Call(false, 42));
-  EXPECT_EQ(2, foo.Call(false, 42));
-  EXPECT_EQ(3, foo.Call(true, 120));
-}
-
-TEST(MockFunctionTest, WorksFor10Arguments) {
-  MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
-                   int a5, int a6, char a7, int a8, bool a9)> foo;
-  EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
-      .WillOnce(Return(1))
-      .WillOnce(Return(2));
-  EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));
-  EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
-}
-
-#if GTEST_HAS_STD_FUNCTION_
-TEST(MockFunctionTest, AsStdFunction) {
-  MockFunction<int(int)> foo;
-  auto call = [](const std::function<int(int)> &f, int i) {
-    return f(i);
-  };
-  EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
-  EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
-  EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
-  EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
-}
-
-TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
-  MockFunction<int&()> foo;
-  int value = 1;
-  EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
-  int& ref = foo.AsStdFunction()();
-  EXPECT_EQ(1, ref);
-  value = 2;
-  EXPECT_EQ(2, ref);
-}
-#endif  // GTEST_HAS_STD_FUNCTION_
-
-}  // namespace gmock_generated_function_mockers_test
-}  // namespace testing
diff --git a/testing/gmock/test/gmock-generated-internal-utils_test.cc b/testing/gmock/test/gmock-generated-internal-utils_test.cc
deleted file mode 100644
index e0a535a..0000000
--- a/testing/gmock/test/gmock-generated-internal-utils_test.cc
+++ /dev/null
@@ -1,127 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the internal utilities.
-
-#include "gmock/internal/gmock-generated-internal-utils.h"
-#include "gmock/internal/gmock-internal-utils.h"
-#include "gtest/gtest.h"
-
-namespace {
-
-using ::testing::tuple;
-using ::testing::Matcher;
-using ::testing::internal::CompileAssertTypesEqual;
-using ::testing::internal::MatcherTuple;
-using ::testing::internal::Function;
-using ::testing::internal::IgnoredValue;
-
-// Tests the MatcherTuple template struct.
-
-TEST(MatcherTupleTest, ForSize0) {
-  CompileAssertTypesEqual<tuple<>, MatcherTuple<tuple<> >::type>();
-}
-
-TEST(MatcherTupleTest, ForSize1) {
-  CompileAssertTypesEqual<tuple<Matcher<int> >,
-                          MatcherTuple<tuple<int> >::type>();
-}
-
-TEST(MatcherTupleTest, ForSize2) {
-  CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char> >,
-                          MatcherTuple<tuple<int, char> >::type>();
-}
-
-TEST(MatcherTupleTest, ForSize5) {
-  CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
-                                Matcher<double>, Matcher<char*> >,
-                          MatcherTuple<tuple<int, char, bool, double, char*>
-                                      >::type>();
-}
-
-// Tests the Function template struct.
-
-TEST(FunctionTest, Nullary) {
-  typedef Function<int()> F;  // NOLINT
-  CompileAssertTypesEqual<int, F::Result>();
-  CompileAssertTypesEqual<tuple<>, F::ArgumentTuple>();
-  CompileAssertTypesEqual<tuple<>, F::ArgumentMatcherTuple>();
-  CompileAssertTypesEqual<void(), F::MakeResultVoid>();
-  CompileAssertTypesEqual<IgnoredValue(), F::MakeResultIgnoredValue>();
-}
-
-TEST(FunctionTest, Unary) {
-  typedef Function<int(bool)> F;  // NOLINT
-  CompileAssertTypesEqual<int, F::Result>();
-  CompileAssertTypesEqual<bool, F::Argument1>();
-  CompileAssertTypesEqual<tuple<bool>, F::ArgumentTuple>();
-  CompileAssertTypesEqual<tuple<Matcher<bool> >, F::ArgumentMatcherTuple>();
-  CompileAssertTypesEqual<void(bool), F::MakeResultVoid>();  // NOLINT
-  CompileAssertTypesEqual<IgnoredValue(bool),  // NOLINT
-      F::MakeResultIgnoredValue>();
-}
-
-TEST(FunctionTest, Binary) {
-  typedef Function<int(bool, const long&)> F;  // NOLINT
-  CompileAssertTypesEqual<int, F::Result>();
-  CompileAssertTypesEqual<bool, F::Argument1>();
-  CompileAssertTypesEqual<const long&, F::Argument2>();  // NOLINT
-  CompileAssertTypesEqual<tuple<bool, const long&>, F::ArgumentTuple>();  // NOLINT
-  CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<const long&> >,  // NOLINT
-                          F::ArgumentMatcherTuple>();
-  CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>();  // NOLINT
-  CompileAssertTypesEqual<IgnoredValue(bool, const long&),  // NOLINT
-      F::MakeResultIgnoredValue>();
-}
-
-TEST(FunctionTest, LongArgumentList) {
-  typedef Function<char(bool, int, char*, int&, const long&)> F;  // NOLINT
-  CompileAssertTypesEqual<char, F::Result>();
-  CompileAssertTypesEqual<bool, F::Argument1>();
-  CompileAssertTypesEqual<int, F::Argument2>();
-  CompileAssertTypesEqual<char*, F::Argument3>();
-  CompileAssertTypesEqual<int&, F::Argument4>();
-  CompileAssertTypesEqual<const long&, F::Argument5>();  // NOLINT
-  CompileAssertTypesEqual<tuple<bool, int, char*, int&, const long&>,  // NOLINT
-                          F::ArgumentTuple>();
-  CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<int>, Matcher<char*>,
-                                Matcher<int&>, Matcher<const long&> >,  // NOLINT
-                          F::ArgumentMatcherTuple>();
-  CompileAssertTypesEqual<void(bool, int, char*, int&, const long&),  // NOLINT
-                          F::MakeResultVoid>();
-  CompileAssertTypesEqual<
-      IgnoredValue(bool, int, char*, int&, const long&),  // NOLINT
-      F::MakeResultIgnoredValue>();
-}
-
-}  // Unnamed namespace
diff --git a/testing/gmock/test/gmock-generated-matchers_test.cc b/testing/gmock/test/gmock-generated-matchers_test.cc
deleted file mode 100644
index 0e9f77f..0000000
--- a/testing/gmock/test/gmock-generated-matchers_test.cc
+++ /dev/null
@@ -1,1286 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in matchers generated by a script.
-
-#include "gmock/gmock-generated-matchers.h"
-
-#include <list>
-#include <map>
-#include <set>
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-namespace {
-
-using std::list;
-using std::map;
-using std::pair;
-using std::set;
-using std::stringstream;
-using std::vector;
-using testing::get;
-using testing::make_tuple;
-using testing::tuple;
-using testing::_;
-using testing::Args;
-using testing::Contains;
-using testing::ElementsAre;
-using testing::ElementsAreArray;
-using testing::Eq;
-using testing::Ge;
-using testing::Gt;
-using testing::Le;
-using testing::Lt;
-using testing::MakeMatcher;
-using testing::Matcher;
-using testing::MatcherInterface;
-using testing::MatchResultListener;
-using testing::Ne;
-using testing::Not;
-using testing::Pointee;
-using testing::PrintToString;
-using testing::Ref;
-using testing::StaticAssertTypeEq;
-using testing::StrEq;
-using testing::Value;
-using testing::internal::ElementsAreArrayMatcher;
-using testing::internal::string;
-
-// Returns the description of the given matcher.
-template <typename T>
-string Describe(const Matcher<T>& m) {
-  stringstream ss;
-  m.DescribeTo(&ss);
-  return ss.str();
-}
-
-// Returns the description of the negation of the given matcher.
-template <typename T>
-string DescribeNegation(const Matcher<T>& m) {
-  stringstream ss;
-  m.DescribeNegationTo(&ss);
-  return ss.str();
-}
-
-// Returns the reason why x matches, or doesn't match, m.
-template <typename MatcherType, typename Value>
-string Explain(const MatcherType& m, const Value& x) {
-  stringstream ss;
-  m.ExplainMatchResultTo(x, &ss);
-  return ss.str();
-}
-
-// Tests Args<k0, ..., kn>(m).
-
-TEST(ArgsTest, AcceptsZeroTemplateArg) {
-  const tuple<int, bool> t(5, true);
-  EXPECT_THAT(t, Args<>(Eq(tuple<>())));
-  EXPECT_THAT(t, Not(Args<>(Ne(tuple<>()))));
-}
-
-TEST(ArgsTest, AcceptsOneTemplateArg) {
-  const tuple<int, bool> t(5, true);
-  EXPECT_THAT(t, Args<0>(Eq(make_tuple(5))));
-  EXPECT_THAT(t, Args<1>(Eq(make_tuple(true))));
-  EXPECT_THAT(t, Not(Args<1>(Eq(make_tuple(false)))));
-}
-
-TEST(ArgsTest, AcceptsTwoTemplateArgs) {
-  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
-
-  EXPECT_THAT(t, (Args<0, 1>(Lt())));
-  EXPECT_THAT(t, (Args<1, 2>(Lt())));
-  EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
-}
-
-TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
-  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
-  EXPECT_THAT(t, (Args<0, 0>(Eq())));
-  EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
-}
-
-TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
-  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
-  EXPECT_THAT(t, (Args<2, 0>(Gt())));
-  EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
-}
-
-// The MATCHER*() macros trigger warning C4100 (unreferenced formal
-// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
-// the macro definition, as the warnings are generated when the macro
-// is expanded and macro expansion cannot contain #pragma.  Therefore
-// we suppress them here.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-#endif
-
-MATCHER(SumIsZero, "") {
-  return get<0>(arg) + get<1>(arg) + get<2>(arg) == 0;
-}
-
-TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
-  EXPECT_THAT(make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
-  EXPECT_THAT(make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
-}
-
-TEST(ArgsTest, CanBeNested) {
-  const tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
-  EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
-  EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
-}
-
-TEST(ArgsTest, CanMatchTupleByValue) {
-  typedef tuple<char, int, int> Tuple3;
-  const Matcher<Tuple3> m = Args<1, 2>(Lt());
-  EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
-  EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
-}
-
-TEST(ArgsTest, CanMatchTupleByReference) {
-  typedef tuple<char, char, int> Tuple3;
-  const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
-  EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
-  EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
-}
-
-// Validates that arg is printed as str.
-MATCHER_P(PrintsAs, str, "") {
-  return testing::PrintToString(arg) == str;
-}
-
-TEST(ArgsTest, AcceptsTenTemplateArgs) {
-  EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
-              (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
-                  PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
-  EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
-              Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
-                      PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
-}
-
-TEST(ArgsTest, DescirbesSelfCorrectly) {
-  const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt());
-  EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
-            "the first < the second",
-            Describe(m));
-}
-
-TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
-  const Matcher<const tuple<int, bool, char, int>&> m =
-      Args<0, 2, 3>(Args<2, 0>(Lt()));
-  EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
-            "whose fields (#2, #0) are a pair where the first < the second",
-            Describe(m));
-}
-
-TEST(ArgsTest, DescribesNegationCorrectly) {
-  const Matcher<tuple<int, char> > m = Args<1, 0>(Gt());
-  EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
-            "where the first > the second",
-            DescribeNegation(m));
-}
-
-TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
-  const Matcher<tuple<bool, int, int> > m = Args<1, 2>(Eq());
-  EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
-            Explain(m, make_tuple(false, 42, 42)));
-  EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
-            Explain(m, make_tuple(false, 42, 43)));
-}
-
-// For testing Args<>'s explanation.
-class LessThanMatcher : public MatcherInterface<tuple<char, int> > {
- public:
-  virtual void DescribeTo(::std::ostream* os) const {}
-
-  virtual bool MatchAndExplain(tuple<char, int> value,
-                               MatchResultListener* listener) const {
-    const int diff = get<0>(value) - get<1>(value);
-    if (diff > 0) {
-      *listener << "where the first value is " << diff
-                << " more than the second";
-    }
-    return diff < 0;
-  }
-};
-
-Matcher<tuple<char, int> > LessThan() {
-  return MakeMatcher(new LessThanMatcher);
-}
-
-TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
-  const Matcher<tuple<char, int, int> > m = Args<0, 2>(LessThan());
-  EXPECT_EQ("whose fields (#0, #2) are ('a' (97, 0x61), 42), "
-            "where the first value is 55 more than the second",
-            Explain(m, make_tuple('a', 42, 42)));
-  EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
-            Explain(m, make_tuple('\0', 42, 43)));
-}
-
-// For testing ExplainMatchResultTo().
-class GreaterThanMatcher : public MatcherInterface<int> {
- public:
-  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
-
-  virtual void DescribeTo(::std::ostream* os) const {
-    *os << "is greater than " << rhs_;
-  }
-
-  virtual bool MatchAndExplain(int lhs,
-                               MatchResultListener* listener) const {
-    const int diff = lhs - rhs_;
-    if (diff > 0) {
-      *listener << "which is " << diff << " more than " << rhs_;
-    } else if (diff == 0) {
-      *listener << "which is the same as " << rhs_;
-    } else {
-      *listener << "which is " << -diff << " less than " << rhs_;
-    }
-
-    return lhs > rhs_;
-  }
-
- private:
-  int rhs_;
-};
-
-Matcher<int> GreaterThan(int n) {
-  return MakeMatcher(new GreaterThanMatcher(n));
-}
-
-// Tests for ElementsAre().
-
-TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
-  Matcher<const vector<int>&> m = ElementsAre();
-  EXPECT_EQ("is empty", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
-  Matcher<vector<int> > m = ElementsAre(Gt(5));
-  EXPECT_EQ("has 1 element that is > 5", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
-  Matcher<list<string> > m = ElementsAre(StrEq("one"), "two");
-  EXPECT_EQ("has 2 elements where\n"
-            "element #0 is equal to \"one\",\n"
-            "element #1 is equal to \"two\"", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
-  Matcher<vector<int> > m = ElementsAre();
-  EXPECT_EQ("isn't empty", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
-  Matcher<const list<int>& > m = ElementsAre(Gt(5));
-  EXPECT_EQ("doesn't have 1 element, or\n"
-            "element #0 isn't > 5", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
-  Matcher<const list<string>& > m = ElementsAre("one", "two");
-  EXPECT_EQ("doesn't have 2 elements, or\n"
-            "element #0 isn't equal to \"one\", or\n"
-            "element #1 isn't equal to \"two\"", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
-  Matcher<const list<int>& > m = ElementsAre(1, Ne(2));
-
-  list<int> test_list;
-  test_list.push_back(1);
-  test_list.push_back(3);
-  EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
-}
-
-TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
-  Matcher<const vector<int>& > m =
-      ElementsAre(GreaterThan(1), 0, GreaterThan(2));
-
-  const int a[] = { 10, 0, 100 };
-  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n"
-            "and whose element #2 matches, which is 98 more than 2",
-            Explain(m, test_vector));
-}
-
-TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
-  Matcher<const list<int>& > m = ElementsAre(1, 3);
-
-  list<int> test_list;
-  // No need to explain when the container is empty.
-  EXPECT_EQ("", Explain(m, test_list));
-
-  test_list.push_back(1);
-  EXPECT_EQ("which has 1 element", Explain(m, test_list));
-}
-
-TEST(ElementsAreTest, CanExplainMismatchRightSize) {
-  Matcher<const vector<int>& > m = ElementsAre(1, GreaterThan(5));
-
-  vector<int> v;
-  v.push_back(2);
-  v.push_back(1);
-  EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
-
-  v[0] = 1;
-  EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
-            Explain(m, v));
-}
-
-TEST(ElementsAreTest, MatchesOneElementVector) {
-  vector<string> test_vector;
-  test_vector.push_back("test string");
-
-  EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
-}
-
-TEST(ElementsAreTest, MatchesOneElementList) {
-  list<string> test_list;
-  test_list.push_back("test string");
-
-  EXPECT_THAT(test_list, ElementsAre("test string"));
-}
-
-TEST(ElementsAreTest, MatchesThreeElementVector) {
-  vector<string> test_vector;
-  test_vector.push_back("one");
-  test_vector.push_back("two");
-  test_vector.push_back("three");
-
-  EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
-}
-
-TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
-  vector<int> test_vector;
-  test_vector.push_back(4);
-
-  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
-}
-
-TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
-  vector<int> test_vector;
-  test_vector.push_back(4);
-
-  EXPECT_THAT(test_vector, ElementsAre(_));
-}
-
-TEST(ElementsAreTest, MatchesOneElementValue) {
-  vector<int> test_vector;
-  test_vector.push_back(4);
-
-  EXPECT_THAT(test_vector, ElementsAre(4));
-}
-
-TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
-  vector<int> test_vector;
-  test_vector.push_back(1);
-  test_vector.push_back(2);
-  test_vector.push_back(3);
-
-  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
-}
-
-TEST(ElementsAreTest, MatchesTenElementVector) {
-  const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
-  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-
-  EXPECT_THAT(test_vector,
-              // The element list can contain values and/or matchers
-              // of different types.
-              ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongSize) {
-  vector<string> test_vector;
-  test_vector.push_back("test string");
-  test_vector.push_back("test string");
-
-  Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
-  EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongValue) {
-  vector<string> test_vector;
-  test_vector.push_back("other string");
-
-  Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
-  EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
-  vector<string> test_vector;
-  test_vector.push_back("one");
-  test_vector.push_back("three");
-  test_vector.push_back("two");
-
-  Matcher<vector<string> > m = ElementsAre(
-    StrEq("one"), StrEq("two"), StrEq("three"));
-  EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, WorksForNestedContainer) {
-  const char* strings[] = {
-    "Hi",
-    "world"
-  };
-
-  vector<list<char> > nested;
-  for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) {
-    nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
-  }
-
-  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
-                                  ElementsAre('w', 'o', _, _, 'd')));
-  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
-                                      ElementsAre('w', 'o', _, _, 'd'))));
-}
-
-TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
-  int a[] = { 0, 1, 2 };
-  vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
-
-  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
-  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
-}
-
-TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
-  int a[] = { 0, 1, 2 };
-  vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
-
-  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
-  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
-}
-
-TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
-  int array[] = { 0, 1, 2 };
-  EXPECT_THAT(array, ElementsAre(0, 1, _));
-  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
-  EXPECT_THAT(array, Not(ElementsAre(0, _)));
-}
-
-class NativeArrayPassedAsPointerAndSize {
- public:
-  NativeArrayPassedAsPointerAndSize() {}
-
-  MOCK_METHOD2(Helper, void(int* array, int size));
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
-};
-
-TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
-  int array[] = { 0, 1 };
-  ::testing::tuple<int*, size_t> array_as_tuple(array, 2);
-  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
-  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
-
-  NativeArrayPassedAsPointerAndSize helper;
-  EXPECT_CALL(helper, Helper(_, _))
-      .With(ElementsAre(0, 1));
-  helper.Helper(array, 2);
-}
-
-TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
-  const char a2[][3] = { "hi", "lo" };
-  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
-                              ElementsAre('l', 'o', '\0')));
-  EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
-  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
-                              ElementsAre('l', 'o', '\0')));
-}
-
-TEST(ElementsAreTest, AcceptsStringLiteral) {
-  string array[] = { "hi", "one", "two" };
-  EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
-  EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
-}
-
-#ifndef _MSC_VER
-
-// The following test passes a value of type const char[] to a
-// function template that expects const T&.  Some versions of MSVC
-// generates a compiler error C2665 for that.  We believe it's a bug
-// in MSVC.  Therefore this test is #if-ed out for MSVC.
-
-// Declared here with the size unknown.  Defined AFTER the following test.
-extern const char kHi[];
-
-TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
-  // The size of kHi is not known in this test, but ElementsAre() should
-  // still accept it.
-
-  string array1[] = { "hi" };
-  EXPECT_THAT(array1, ElementsAre(kHi));
-
-  string array2[] = { "ho" };
-  EXPECT_THAT(array2, Not(ElementsAre(kHi)));
-}
-
-const char kHi[] = "hi";
-
-#endif  // _MSC_VER
-
-TEST(ElementsAreTest, MakesCopyOfArguments) {
-  int x = 1;
-  int y = 2;
-  // This should make a copy of x and y.
-  ::testing::internal::ElementsAreMatcher<testing::tuple<int, int> >
-          polymorphic_matcher = ElementsAre(x, y);
-  // Changing x and y now shouldn't affect the meaning of the above matcher.
-  x = y = 0;
-  const int array1[] = { 1, 2 };
-  EXPECT_THAT(array1, polymorphic_matcher);
-  const int array2[] = { 0, 0 };
-  EXPECT_THAT(array2, Not(polymorphic_matcher));
-}
-
-
-// Tests for ElementsAreArray().  Since ElementsAreArray() shares most
-// of the implementation with ElementsAre(), we don't test it as
-// thoroughly here.
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
-  const int a[] = { 1, 2, 3 };
-
-  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(a));
-
-  test_vector[2] = 0;
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
-  const char* a[] = { "one", "two", "three" };
-
-  vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a)));
-
-  const char** p = a;
-  test_vector[0] = "1";
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a))));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
-  const char* a[] = { "one", "two", "three" };
-
-  vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(a));
-
-  test_vector[0] = "1";
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
-  const Matcher<string> kMatcherArray[] =
-    { StrEq("one"), StrEq("two"), StrEq("three") };
-
-  vector<string> test_vector;
-  test_vector.push_back("one");
-  test_vector.push_back("two");
-  test_vector.push_back("three");
-  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
-
-  test_vector.push_back("three");
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
-  const int a[] = { 1, 2, 3 };
-  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(expected));
-  test_vector.push_back(4);
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(ElementsAreArrayTest, TakesInitializerList) {
-  const int a[5] = { 1, 2, 3, 4, 5 };
-  EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 }));
-  EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 })));
-  EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 })));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
-  const string a[5] = { "a", "b", "c", "d", "e" };
-  EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" }));
-  EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" })));
-  EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" })));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
-  const int a[5] = { 1, 2, 3, 4, 5 };
-  EXPECT_THAT(a, ElementsAreArray(
-      { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
-  EXPECT_THAT(a, Not(ElementsAreArray(
-      { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
-}
-
-TEST(ElementsAreArrayTest,
-     TakesInitializerListOfDifferentTypedMatchers) {
-  const int a[5] = { 1, 2, 3, 4, 5 };
-  // The compiler cannot infer the type of the initializer list if its
-  // elements have different types.  We must explicitly specify the
-  // unified element type in this case.
-  EXPECT_THAT(a, ElementsAreArray<Matcher<int> >(
-      { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
-  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int> >(
-      { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
-}
-
-#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
-  const int a[] = { 1, 2, 3 };
-  const Matcher<int> kMatchers[] = { Eq(1), Eq(2), Eq(3) };
-  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  const vector<Matcher<int> > expected(
-      kMatchers, kMatchers + GTEST_ARRAY_SIZE_(kMatchers));
-  EXPECT_THAT(test_vector, ElementsAreArray(expected));
-  test_vector.push_back(4);
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
-  const int a[] = { 1, 2, 3 };
-  const vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
-  // Pointers are iterators, too.
-  EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a)));
-  // The empty range of NULL pointers should also be okay.
-  int* const null_int = NULL;
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
-  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
-}
-
-// Since ElementsAre() and ElementsAreArray() share much of the
-// implementation, we only do a sanity test for native arrays here.
-TEST(ElementsAreArrayTest, WorksWithNativeArray) {
-  ::std::string a[] = { "hi", "ho" };
-  ::std::string b[] = { "hi", "ho" };
-
-  EXPECT_THAT(a, ElementsAreArray(b));
-  EXPECT_THAT(a, ElementsAreArray(b, 2));
-  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
-}
-
-TEST(ElementsAreArrayTest, SourceLifeSpan) {
-  const int a[] = { 1, 2, 3 };
-  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
-  vector<int> expect(a, a + GTEST_ARRAY_SIZE_(a));
-  ElementsAreArrayMatcher<int> matcher_maker =
-      ElementsAreArray(expect.begin(), expect.end());
-  EXPECT_THAT(test_vector, matcher_maker);
-  // Changing in place the values that initialized matcher_maker should not
-  // affect matcher_maker anymore. It should have made its own copy of them.
-  typedef vector<int>::iterator Iter;
-  for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; }
-  EXPECT_THAT(test_vector, matcher_maker);
-  test_vector.push_back(3);
-  EXPECT_THAT(test_vector, Not(matcher_maker));
-}
-
-// Tests for the MATCHER*() macro family.
-
-// Tests that a simple MATCHER() definition works.
-
-MATCHER(IsEven, "") { return (arg % 2) == 0; }
-
-TEST(MatcherMacroTest, Works) {
-  const Matcher<int> m = IsEven();
-  EXPECT_TRUE(m.Matches(6));
-  EXPECT_FALSE(m.Matches(7));
-
-  EXPECT_EQ("is even", Describe(m));
-  EXPECT_EQ("not (is even)", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 6));
-  EXPECT_EQ("", Explain(m, 7));
-}
-
-// This also tests that the description string can reference 'negation'.
-MATCHER(IsEven2, negation ? "is odd" : "is even") {
-  if ((arg % 2) == 0) {
-    // Verifies that we can stream to result_listener, a listener
-    // supplied by the MATCHER macro implicitly.
-    *result_listener << "OK";
-    return true;
-  } else {
-    *result_listener << "% 2 == " << (arg % 2);
-    return false;
-  }
-}
-
-// This also tests that the description string can reference matcher
-// parameters.
-MATCHER_P2(EqSumOf, x, y,
-           string(negation ? "doesn't equal" : "equals") + " the sum of " +
-           PrintToString(x) + " and " + PrintToString(y)) {
-  if (arg == (x + y)) {
-    *result_listener << "OK";
-    return true;
-  } else {
-    // Verifies that we can stream to the underlying stream of
-    // result_listener.
-    if (result_listener->stream() != NULL) {
-      *result_listener->stream() << "diff == " << (x + y - arg);
-    }
-    return false;
-  }
-}
-
-// Tests that the matcher description can reference 'negation' and the
-// matcher parameters.
-TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
-  const Matcher<int> m1 = IsEven2();
-  EXPECT_EQ("is even", Describe(m1));
-  EXPECT_EQ("is odd", DescribeNegation(m1));
-
-  const Matcher<int> m2 = EqSumOf(5, 9);
-  EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
-  EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
-}
-
-// Tests explaining match result in a MATCHER* macro.
-TEST(MatcherMacroTest, CanExplainMatchResult) {
-  const Matcher<int> m1 = IsEven2();
-  EXPECT_EQ("OK", Explain(m1, 4));
-  EXPECT_EQ("% 2 == 1", Explain(m1, 5));
-
-  const Matcher<int> m2 = EqSumOf(1, 2);
-  EXPECT_EQ("OK", Explain(m2, 3));
-  EXPECT_EQ("diff == -1", Explain(m2, 4));
-}
-
-// Tests that the body of MATCHER() can reference the type of the
-// value being matched.
-
-MATCHER(IsEmptyString, "") {
-  StaticAssertTypeEq< ::std::string, arg_type>();
-  return arg == "";
-}
-
-MATCHER(IsEmptyStringByRef, "") {
-  StaticAssertTypeEq<const ::std::string&, arg_type>();
-  return arg == "";
-}
-
-TEST(MatcherMacroTest, CanReferenceArgType) {
-  const Matcher< ::std::string> m1 = IsEmptyString();
-  EXPECT_TRUE(m1.Matches(""));
-
-  const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
-  EXPECT_TRUE(m2.Matches(""));
-}
-
-// Tests that MATCHER() can be used in a namespace.
-
-namespace matcher_test {
-MATCHER(IsOdd, "") { return (arg % 2) != 0; }
-}  // namespace matcher_test
-
-TEST(MatcherMacroTest, WorksInNamespace) {
-  Matcher<int> m = matcher_test::IsOdd();
-  EXPECT_FALSE(m.Matches(4));
-  EXPECT_TRUE(m.Matches(5));
-}
-
-// Tests that Value() can be used to compose matchers.
-MATCHER(IsPositiveOdd, "") {
-  return Value(arg, matcher_test::IsOdd()) && arg > 0;
-}
-
-TEST(MatcherMacroTest, CanBeComposedUsingValue) {
-  EXPECT_THAT(3, IsPositiveOdd());
-  EXPECT_THAT(4, Not(IsPositiveOdd()));
-  EXPECT_THAT(-1, Not(IsPositiveOdd()));
-}
-
-// Tests that a simple MATCHER_P() definition works.
-
-MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
-
-TEST(MatcherPMacroTest, Works) {
-  const Matcher<int> m = IsGreaterThan32And(5);
-  EXPECT_TRUE(m.Matches(36));
-  EXPECT_FALSE(m.Matches(5));
-
-  EXPECT_EQ("is greater than 32 and 5", Describe(m));
-  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 36));
-  EXPECT_EQ("", Explain(m, 5));
-}
-
-// Tests that the description is calculated correctly from the matcher name.
-MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
-
-TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
-  const Matcher<int> m = _is_Greater_Than32and_(5);
-
-  EXPECT_EQ("is greater than 32 and 5", Describe(m));
-  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 36));
-  EXPECT_EQ("", Explain(m, 5));
-}
-
-// Tests that a MATCHER_P matcher can be explicitly instantiated with
-// a reference parameter type.
-
-class UncopyableFoo {
- public:
-  explicit UncopyableFoo(char value) : value_(value) {}
- private:
-  UncopyableFoo(const UncopyableFoo&);
-  void operator=(const UncopyableFoo&);
-
-  char value_;
-};
-
-MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
-
-TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
-  UncopyableFoo foo1('1'), foo2('2');
-  const Matcher<const UncopyableFoo&> m =
-      ReferencesUncopyable<const UncopyableFoo&>(foo1);
-
-  EXPECT_TRUE(m.Matches(foo1));
-  EXPECT_FALSE(m.Matches(foo2));
-
-  // We don't want the address of the parameter printed, as most
-  // likely it will just annoy the user.  If the address is
-  // interesting, the user should consider passing the parameter by
-  // pointer instead.
-  EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
-}
-
-
-// Tests that the body of MATCHER_Pn() can reference the parameter
-// types.
-
-MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
-  StaticAssertTypeEq<int, foo_type>();
-  StaticAssertTypeEq<long, bar_type>();  // NOLINT
-  StaticAssertTypeEq<char, baz_type>();
-  return arg == 0;
-}
-
-TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
-  EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
-}
-
-// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
-// reference parameter types.
-
-MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
-  return &arg == &variable1 || &arg == &variable2;
-}
-
-TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
-  UncopyableFoo foo1('1'), foo2('2'), foo3('3');
-  const Matcher<const UncopyableFoo&> m =
-      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
-
-  EXPECT_TRUE(m.Matches(foo1));
-  EXPECT_TRUE(m.Matches(foo2));
-  EXPECT_FALSE(m.Matches(foo3));
-}
-
-TEST(MatcherPnMacroTest,
-     GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
-  UncopyableFoo foo1('1'), foo2('2');
-  const Matcher<const UncopyableFoo&> m =
-      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
-
-  // We don't want the addresses of the parameters printed, as most
-  // likely they will just annoy the user.  If the addresses are
-  // interesting, the user should consider passing the parameters by
-  // pointers instead.
-  EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
-            Describe(m));
-}
-
-// Tests that a simple MATCHER_P2() definition works.
-
-MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
-
-TEST(MatcherPnMacroTest, Works) {
-  const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
-  EXPECT_TRUE(m.Matches(36L));
-  EXPECT_FALSE(m.Matches(15L));
-
-  EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
-  EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 36L));
-  EXPECT_EQ("", Explain(m, 15L));
-}
-
-// Tests that MATCHER*() definitions can be overloaded on the number
-// of parameters; also tests MATCHER_Pn() where n >= 3.
-
-MATCHER(EqualsSumOf, "") { return arg == 0; }
-MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
-MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
-MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
-MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
-MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
-MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
-  return arg == a + b + c + d + e + f;
-}
-MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
-  return arg == a + b + c + d + e + f + g;
-}
-MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
-  return arg == a + b + c + d + e + f + g + h;
-}
-MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
-  return arg == a + b + c + d + e + f + g + h + i;
-}
-MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
-  return arg == a + b + c + d + e + f + g + h + i + j;
-}
-
-TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
-  EXPECT_THAT(0, EqualsSumOf());
-  EXPECT_THAT(1, EqualsSumOf(1));
-  EXPECT_THAT(12, EqualsSumOf(10, 2));
-  EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
-  EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
-  EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
-  EXPECT_THAT("abcdef",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
-  EXPECT_THAT("abcdefg",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
-  EXPECT_THAT("abcdefgh",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                          "h"));
-  EXPECT_THAT("abcdefghi",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                          "h", 'i'));
-  EXPECT_THAT("abcdefghij",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                          "h", 'i', ::std::string("j")));
-
-  EXPECT_THAT(1, Not(EqualsSumOf()));
-  EXPECT_THAT(-1, Not(EqualsSumOf(1)));
-  EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
-  EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
-  EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
-  EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
-  EXPECT_THAT("abcdef ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
-  EXPECT_THAT("abcdefg ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f',
-                              'g')));
-  EXPECT_THAT("abcdefgh ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                              "h")));
-  EXPECT_THAT("abcdefghi ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                              "h", 'i')));
-  EXPECT_THAT("abcdefghij ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                              "h", 'i', ::std::string("j"))));
-}
-
-// Tests that a MATCHER_Pn() definition can be instantiated with any
-// compatible parameter types.
-TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
-  EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
-  EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
-
-  EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
-  EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
-}
-
-// Tests that the matcher body can promote the parameter types.
-
-MATCHER_P2(EqConcat, prefix, suffix, "") {
-  // The following lines promote the two parameters to desired types.
-  std::string prefix_str(prefix);
-  char suffix_char = static_cast<char>(suffix);
-  return arg == prefix_str + suffix_char;
-}
-
-TEST(MatcherPnMacroTest, SimpleTypePromotion) {
-  Matcher<std::string> no_promo =
-      EqConcat(std::string("foo"), 't');
-  Matcher<const std::string&> promo =
-      EqConcat("foo", static_cast<int>('t'));
-  EXPECT_FALSE(no_promo.Matches("fool"));
-  EXPECT_FALSE(promo.Matches("fool"));
-  EXPECT_TRUE(no_promo.Matches("foot"));
-  EXPECT_TRUE(promo.Matches("foot"));
-}
-
-// Verifies the type of a MATCHER*.
-
-TEST(MatcherPnMacroTest, TypesAreCorrect) {
-  // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
-  EqualsSumOfMatcher a0 = EqualsSumOf();
-
-  // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
-  EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
-
-  // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
-  // variable, and so on.
-  EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
-  EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
-  EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
-  EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
-      EqualsSumOf(1, 2, 3, 4, '5');
-  EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
-      EqualsSumOf(1, 2, 3, 4, 5, '6');
-  EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
-  EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
-  EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
-  EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
-
-  // Avoid "unused variable" warnings.
-  (void)a0;
-  (void)a1;
-  (void)a2;
-  (void)a3;
-  (void)a4;
-  (void)a5;
-  (void)a6;
-  (void)a7;
-  (void)a8;
-  (void)a9;
-  (void)a10;
-}
-
-// Tests that matcher-typed parameters can be used in Value() inside a
-// MATCHER_Pn definition.
-
-// Succeeds if arg matches exactly 2 of the 3 matchers.
-MATCHER_P3(TwoOf, m1, m2, m3, "") {
-  const int count = static_cast<int>(Value(arg, m1))
-      + static_cast<int>(Value(arg, m2)) + static_cast<int>(Value(arg, m3));
-  return count == 2;
-}
-
-TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
-  EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
-  EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
-}
-
-// Tests Contains().
-
-TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
-  list<int> some_list;
-  some_list.push_back(3);
-  some_list.push_back(1);
-  some_list.push_back(2);
-  EXPECT_THAT(some_list, Contains(1));
-  EXPECT_THAT(some_list, Contains(Gt(2.5)));
-  EXPECT_THAT(some_list, Contains(Eq(2.0f)));
-
-  list<string> another_list;
-  another_list.push_back("fee");
-  another_list.push_back("fie");
-  another_list.push_back("foe");
-  another_list.push_back("fum");
-  EXPECT_THAT(another_list, Contains(string("fee")));
-}
-
-TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
-  list<int> some_list;
-  some_list.push_back(3);
-  some_list.push_back(1);
-  EXPECT_THAT(some_list, Not(Contains(4)));
-}
-
-TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
-  set<int> some_set;
-  some_set.insert(3);
-  some_set.insert(1);
-  some_set.insert(2);
-  EXPECT_THAT(some_set, Contains(Eq(1.0)));
-  EXPECT_THAT(some_set, Contains(Eq(3.0f)));
-  EXPECT_THAT(some_set, Contains(2));
-
-  set<const char*> another_set;
-  another_set.insert("fee");
-  another_set.insert("fie");
-  another_set.insert("foe");
-  another_set.insert("fum");
-  EXPECT_THAT(another_set, Contains(Eq(string("fum"))));
-}
-
-TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
-  set<int> some_set;
-  some_set.insert(3);
-  some_set.insert(1);
-  EXPECT_THAT(some_set, Not(Contains(4)));
-
-  set<const char*> c_string_set;
-  c_string_set.insert("hello");
-  EXPECT_THAT(c_string_set, Not(Contains(string("hello").c_str())));
-}
-
-TEST(ContainsTest, ExplainsMatchResultCorrectly) {
-  const int a[2] = { 1, 2 };
-  Matcher<const int (&)[2]> m = Contains(2);
-  EXPECT_EQ("whose element #1 matches", Explain(m, a));
-
-  m = Contains(3);
-  EXPECT_EQ("", Explain(m, a));
-
-  m = Contains(GreaterThan(0));
-  EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
-
-  m = Contains(GreaterThan(10));
-  EXPECT_EQ("", Explain(m, a));
-}
-
-TEST(ContainsTest, DescribesItselfCorrectly) {
-  Matcher<vector<int> > m = Contains(1);
-  EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
-
-  Matcher<vector<int> > m2 = Not(m);
-  EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
-}
-
-TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
-  map<const char*, int> my_map;
-  const char* bar = "a string";
-  my_map[bar] = 2;
-  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
-
-  map<string, int> another_map;
-  another_map["fee"] = 1;
-  another_map["fie"] = 2;
-  another_map["foe"] = 3;
-  another_map["fum"] = 4;
-  EXPECT_THAT(another_map, Contains(pair<const string, int>(string("fee"), 1)));
-  EXPECT_THAT(another_map, Contains(pair<const string, int>("fie", 2)));
-}
-
-TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
-  map<int, int> some_map;
-  some_map[1] = 11;
-  some_map[2] = 22;
-  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
-}
-
-TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
-  const char* string_array[] = { "fee", "fie", "foe", "fum" };
-  EXPECT_THAT(string_array, Contains(Eq(string("fum"))));
-}
-
-TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
-  int int_array[] = { 1, 2, 3, 4 };
-  EXPECT_THAT(int_array, Not(Contains(5)));
-}
-
-TEST(ContainsTest, AcceptsMatcher) {
-  const int a[] = { 1, 2, 3 };
-  EXPECT_THAT(a, Contains(Gt(2)));
-  EXPECT_THAT(a, Not(Contains(Gt(4))));
-}
-
-TEST(ContainsTest, WorksForNativeArrayAsTuple) {
-  const int a[] = { 1, 2 };
-  const int* const pointer = a;
-  EXPECT_THAT(make_tuple(pointer, 2), Contains(1));
-  EXPECT_THAT(make_tuple(pointer, 2), Not(Contains(Gt(3))));
-}
-
-TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
-  int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
-  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
-  EXPECT_THAT(a, Contains(Contains(5)));
-  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
-  EXPECT_THAT(a, Contains(Not(Contains(5))));
-}
-
-TEST(AllOfTest, HugeMatcher) {
-  // Verify that using AllOf with many arguments doesn't cause
-  // the compiler to exceed template instantiation depth limit.
-  EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
-                                testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
-}
-
-TEST(AnyOfTest, HugeMatcher) {
-  // Verify that using AnyOf with many arguments doesn't cause
-  // the compiler to exceed template instantiation depth limit.
-  EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
-                                testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
-}
-
-namespace adl_test {
-
-// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
-// don't issue unqualified recursive calls.  If they do, the argument dependent
-// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
-// as a candidate and the compilation will break due to an ambiguous overload.
-
-// The matcher must be in the same namespace as AllOf/AnyOf to make argument
-// dependent lookup find those.
-MATCHER(M, "") { return true; }
-
-template <typename T1, typename T2>
-bool AllOf(const T1& t1, const T2& t2) { return true; }
-
-TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
-  EXPECT_THAT(42, testing::AllOf(
-      M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
-}
-
-template <typename T1, typename T2> bool
-AnyOf(const T1& t1, const T2& t2) { return true; }
-
-TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
-  EXPECT_THAT(42, testing::AnyOf(
-      M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
-}
-
-}  // namespace adl_test
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-}  // namespace
diff --git a/testing/gmock/test/gmock-internal-utils_test.cc b/testing/gmock/test/gmock-internal-utils_test.cc
deleted file mode 100644
index 4f00f0d..0000000
--- a/testing/gmock/test/gmock-internal-utils_test.cc
+++ /dev/null
@@ -1,698 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the internal utilities.
-
-#include "gmock/internal/gmock-internal-utils.h"
-#include <stdlib.h>
-#include <map>
-#include <string>
-#include <sstream>
-#include <vector>
-#include "gmock/gmock.h"
-#include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-// Indicates that this translation unit is part of Google Test's
-// implementation.  It must come before gtest-internal-inl.h is
-// included, or there will be a compiler error.  This trick is to
-// prevent a user from accidentally including gtest-internal-inl.h in
-// his code.
-#define GTEST_IMPLEMENTATION_ 1
-#include "src/gtest-internal-inl.h"
-#undef GTEST_IMPLEMENTATION_
-
-#if GTEST_OS_CYGWIN
-# include <sys/types.h>  // For ssize_t. NOLINT
-#endif
-
-class ProtocolMessage;
-
-namespace proto2 {
-class Message;
-}  // namespace proto2
-
-namespace testing {
-namespace internal {
-
-namespace {
-
-TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
-  EXPECT_EQ("", ConvertIdentifierNameToWords(""));
-  EXPECT_EQ("", ConvertIdentifierNameToWords("_"));
-  EXPECT_EQ("", ConvertIdentifierNameToWords("__"));
-}
-
-TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {
-  EXPECT_EQ("1", ConvertIdentifierNameToWords("_1"));
-  EXPECT_EQ("2", ConvertIdentifierNameToWords("2_"));
-  EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_"));
-  EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56"));
-}
-
-TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {
-  EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord"));
-  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar"));
-  EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_"));
-  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_"));
-  EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar"));
-}
-
-TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {
-  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar"));
-  EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_"));
-  EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_"));
-  EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar"));
-}
-
-TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
-  EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123"));
-  EXPECT_EQ("chapter 11 section 1",
-            ConvertIdentifierNameToWords("_Chapter11Section_1_"));
-}
-
-TEST(PointeeOfTest, WorksForSmartPointers) {
-  CompileAssertTypesEqual<const char,
-      PointeeOf<internal::linked_ptr<const char> >::type>();
-#if GTEST_HAS_STD_UNIQUE_PTR_
-  CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
-#endif  // GTEST_HAS_STD_UNIQUE_PTR_
-#if GTEST_HAS_STD_SHARED_PTR_
-  CompileAssertTypesEqual<std::string,
-                          PointeeOf<std::shared_ptr<std::string> >::type>();
-#endif  // GTEST_HAS_STD_SHARED_PTR_
-}
-
-TEST(PointeeOfTest, WorksForRawPointers) {
-  CompileAssertTypesEqual<int, PointeeOf<int*>::type>();
-  CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>();
-  CompileAssertTypesEqual<void, PointeeOf<void*>::type>();
-}
-
-TEST(GetRawPointerTest, WorksForSmartPointers) {
-#if GTEST_HAS_STD_UNIQUE_PTR_
-  const char* const raw_p1 = new const char('a');  // NOLINT
-  const std::unique_ptr<const char> p1(raw_p1);
-  EXPECT_EQ(raw_p1, GetRawPointer(p1));
-#endif  // GTEST_HAS_STD_UNIQUE_PTR_
-#if GTEST_HAS_STD_SHARED_PTR_
-  double* const raw_p2 = new double(2.5);  // NOLINT
-  const std::shared_ptr<double> p2(raw_p2);
-  EXPECT_EQ(raw_p2, GetRawPointer(p2));
-#endif  // GTEST_HAS_STD_SHARED_PTR_
-
-  const char* const raw_p4 = new const char('a');  // NOLINT
-  const internal::linked_ptr<const char> p4(raw_p4);
-  EXPECT_EQ(raw_p4, GetRawPointer(p4));
-}
-
-TEST(GetRawPointerTest, WorksForRawPointers) {
-  int* p = NULL;
-  // Don't use EXPECT_EQ as no NULL-testing magic on Symbian.
-  EXPECT_TRUE(NULL == GetRawPointer(p));
-  int n = 1;
-  EXPECT_EQ(&n, GetRawPointer(&n));
-}
-
-// Tests KindOf<T>.
-
-class Base {};
-class Derived : public Base {};
-
-TEST(KindOfTest, Bool) {
-  EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool));  // NOLINT
-}
-
-TEST(KindOfTest, Integer) {
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));  // NOLINT
-#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
-  // ssize_t is not defined on Windows and possibly some other OSes.
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));  // NOLINT
-#endif
-}
-
-TEST(KindOfTest, FloatingPoint) {
-  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));  // NOLINT
-  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));  // NOLINT
-  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));  // NOLINT
-}
-
-TEST(KindOfTest, Other) {
-  EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));  // NOLINT
-  EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));  // NOLINT
-  EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));  // NOLINT
-}
-
-// Tests LosslessArithmeticConvertible<T, U>.
-
-TEST(LosslessArithmeticConvertibleTest, BoolToBool) {
-  EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));
-}
-
-TEST(LosslessArithmeticConvertibleTest, BoolToInteger) {
-  EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));
-  EXPECT_TRUE(
-      (LosslessArithmeticConvertible<bool, unsigned long>::value));  // NOLINT
-}
-
-TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {
-  EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));
-}
-
-TEST(LosslessArithmeticConvertibleTest, IntegerToBool) {
-  EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));
-}
-
-TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
-  // Unsigned => larger signed is fine.
-  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
-
-  // Unsigned => larger unsigned is fine.
-  EXPECT_TRUE(
-      (LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT
-
-  // Signed => unsigned is not fine.
-  EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::value)); // NOLINT
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-      signed char, unsigned int>::value));  // NOLINT
-
-  // Same size and same signedness: fine too.
-  EXPECT_TRUE((LosslessArithmeticConvertible<
-               unsigned char, unsigned char>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<
-               unsigned long, unsigned long>::value));  // NOLINT
-
-  // Same size, different signedness: not fine.
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-                unsigned char, signed char>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<UInt64, Int64>::value));
-
-  // Larger size => smaller size is not fine.
-  EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value));  // NOLINT
-  EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value));
-}
-
-TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
-  // Integers cannot be losslessly converted to floating-points, as
-  // the format of the latter is implementation-defined.
-  EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-                short, long double>::value));  // NOLINT
-}
-
-TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
-  EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));
-}
-
-TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
-  EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value));  // NOLINT
-  EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
-}
-
-TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
-  // Smaller size => larger size is fine.
-  EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));
-
-  // Same size: fine.
-  EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));
-
-  // Larger size => smaller size is not fine.
-  EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
-  GTEST_INTENTIONAL_CONST_COND_PUSH_()
-  if (sizeof(double) == sizeof(long double)) {  // NOLINT
-  GTEST_INTENTIONAL_CONST_COND_POP_()
-    // In some implementations (e.g. MSVC), double and long double
-    // have the same size.
-    EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
-  } else {
-    EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));
-  }
-}
-
-// Tests the TupleMatches() template function.
-
-TEST(TupleMatchesTest, WorksForSize0) {
-  tuple<> matchers;
-  tuple<> values;
-
-  EXPECT_TRUE(TupleMatches(matchers, values));
-}
-
-TEST(TupleMatchesTest, WorksForSize1) {
-  tuple<Matcher<int> > matchers(Eq(1));
-  tuple<int> values1(1),
-      values2(2);
-
-  EXPECT_TRUE(TupleMatches(matchers, values1));
-  EXPECT_FALSE(TupleMatches(matchers, values2));
-}
-
-TEST(TupleMatchesTest, WorksForSize2) {
-  tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a'));
-  tuple<int, char> values1(1, 'a'),
-      values2(1, 'b'),
-      values3(2, 'a'),
-      values4(2, 'b');
-
-  EXPECT_TRUE(TupleMatches(matchers, values1));
-  EXPECT_FALSE(TupleMatches(matchers, values2));
-  EXPECT_FALSE(TupleMatches(matchers, values3));
-  EXPECT_FALSE(TupleMatches(matchers, values4));
-}
-
-TEST(TupleMatchesTest, WorksForSize5) {
-  tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>,  // NOLINT
-      Matcher<string> >
-      matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
-  tuple<int, char, bool, long, string>  // NOLINT
-      values1(1, 'a', true, 2L, "hi"),
-      values2(1, 'a', true, 2L, "hello"),
-      values3(2, 'a', true, 2L, "hi");
-
-  EXPECT_TRUE(TupleMatches(matchers, values1));
-  EXPECT_FALSE(TupleMatches(matchers, values2));
-  EXPECT_FALSE(TupleMatches(matchers, values3));
-}
-
-// Tests that Assert(true, ...) succeeds.
-TEST(AssertTest, SucceedsOnTrue) {
-  Assert(true, __FILE__, __LINE__, "This should succeed.");
-  Assert(true, __FILE__, __LINE__);  // This should succeed too.
-}
-
-// Tests that Assert(false, ...) generates a fatal failure.
-TEST(AssertTest, FailsFatallyOnFalse) {
-  EXPECT_DEATH_IF_SUPPORTED({
-    Assert(false, __FILE__, __LINE__, "This should fail.");
-  }, "");
-
-  EXPECT_DEATH_IF_SUPPORTED({
-    Assert(false, __FILE__, __LINE__);
-  }, "");
-}
-
-// Tests that Expect(true, ...) succeeds.
-TEST(ExpectTest, SucceedsOnTrue) {
-  Expect(true, __FILE__, __LINE__, "This should succeed.");
-  Expect(true, __FILE__, __LINE__);  // This should succeed too.
-}
-
-// Tests that Expect(false, ...) generates a non-fatal failure.
-TEST(ExpectTest, FailsNonfatallyOnFalse) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Expect(false, __FILE__, __LINE__, "This should fail.");
-  }, "This should fail");
-
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Expect(false, __FILE__, __LINE__);
-  }, "Expectation failed");
-}
-
-// Tests LogIsVisible().
-
-class LogIsVisibleTest : public ::testing::Test {
- protected:
-  virtual void SetUp() {
-    original_verbose_ = GMOCK_FLAG(verbose);
-  }
-
-  virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }
-
-  string original_verbose_;
-};
-
-TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
-  GMOCK_FLAG(verbose) = kInfoVerbosity;
-  EXPECT_TRUE(LogIsVisible(kInfo));
-  EXPECT_TRUE(LogIsVisible(kWarning));
-}
-
-TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
-  GMOCK_FLAG(verbose) = kErrorVerbosity;
-  EXPECT_FALSE(LogIsVisible(kInfo));
-  EXPECT_FALSE(LogIsVisible(kWarning));
-}
-
-TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
-  GMOCK_FLAG(verbose) = kWarningVerbosity;
-  EXPECT_FALSE(LogIsVisible(kInfo));
-  EXPECT_TRUE(LogIsVisible(kWarning));
-}
-
-#if GTEST_HAS_STREAM_REDIRECTION
-
-// Tests the Log() function.
-
-// Verifies that Log() behaves correctly for the given verbosity level
-// and log severity.
-void TestLogWithSeverity(const string& verbosity, LogSeverity severity,
-                         bool should_print) {
-  const string old_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = verbosity;
-  CaptureStdout();
-  Log(severity, "Test log.\n", 0);
-  if (should_print) {
-    EXPECT_THAT(GetCapturedStdout().c_str(),
-                ContainsRegex(
-                    severity == kWarning ?
-                    "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
-                    "^\nTest log\\.\nStack trace:\n"));
-  } else {
-    EXPECT_STREQ("", GetCapturedStdout().c_str());
-  }
-  GMOCK_FLAG(verbose) = old_flag;
-}
-
-// Tests that when the stack_frames_to_skip parameter is negative,
-// Log() doesn't include the stack trace in the output.
-TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
-  const string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = kInfoVerbosity;
-  CaptureStdout();
-  Log(kInfo, "Test log.\n", -1);
-  EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
-  GMOCK_FLAG(verbose) = saved_flag;
-}
-
-struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
-  virtual string CurrentStackTrace(int max_depth, int skip_count) {
-    return (testing::Message() << max_depth << "::" << skip_count << "\n")
-        .GetString();
-  }
-  virtual void UponLeavingGTest() {}
-};
-
-// Tests that in opt mode, a positive stack_frames_to_skip argument is
-// treated as 0.
-TEST(LogTest, NoSkippingStackFrameInOptMode) {
-  MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
-  GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);
-
-  CaptureStdout();
-  Log(kWarning, "Test log.\n", 100);
-  const string log = GetCapturedStdout();
-
-  string expected_trace =
-      (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString();
-  string expected_message =
-      "\nGMOCK WARNING:\n"
-      "Test log.\n"
-      "Stack trace:\n" +
-      expected_trace;
-  EXPECT_THAT(log, HasSubstr(expected_message));
-  int skip_count = atoi(log.substr(expected_message.size()).c_str());
-
-# if defined(NDEBUG)
-  // In opt mode, no stack frame should be skipped.
-  const int expected_skip_count = 0;
-# else
-  // In dbg mode, the stack frames should be skipped.
-  const int expected_skip_count = 100;
-# endif
-
-  // Note that each inner implementation layer will +1 the number to remove
-  // itself from the trace. This means that the value is a little higher than
-  // expected, but close enough.
-  EXPECT_THAT(skip_count,
-              AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));
-
-  // Restores the default OS stack trace getter.
-  GetUnitTestImpl()->set_os_stack_trace_getter(NULL);
-}
-
-// Tests that all logs are printed when the value of the
-// --gmock_verbose flag is "info".
-TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
-  TestLogWithSeverity(kInfoVerbosity, kInfo, true);
-  TestLogWithSeverity(kInfoVerbosity, kWarning, true);
-}
-
-// Tests that only warnings are printed when the value of the
-// --gmock_verbose flag is "warning".
-TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
-  TestLogWithSeverity(kWarningVerbosity, kInfo, false);
-  TestLogWithSeverity(kWarningVerbosity, kWarning, true);
-}
-
-// Tests that no logs are printed when the value of the
-// --gmock_verbose flag is "error".
-TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
-  TestLogWithSeverity(kErrorVerbosity, kInfo, false);
-  TestLogWithSeverity(kErrorVerbosity, kWarning, false);
-}
-
-// Tests that only warnings are printed when the value of the
-// --gmock_verbose flag is invalid.
-TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
-  TestLogWithSeverity("invalid", kInfo, false);
-  TestLogWithSeverity("invalid", kWarning, true);
-}
-
-#endif  // GTEST_HAS_STREAM_REDIRECTION
-
-TEST(TypeTraitsTest, true_type) {
-  EXPECT_TRUE(true_type::value);
-}
-
-TEST(TypeTraitsTest, false_type) {
-  EXPECT_FALSE(false_type::value);
-}
-
-TEST(TypeTraitsTest, is_reference) {
-  EXPECT_FALSE(is_reference<int>::value);
-  EXPECT_FALSE(is_reference<char*>::value);
-  EXPECT_TRUE(is_reference<const int&>::value);
-}
-
-TEST(TypeTraitsTest, is_pointer) {
-  EXPECT_FALSE(is_pointer<int>::value);
-  EXPECT_FALSE(is_pointer<char&>::value);
-  EXPECT_TRUE(is_pointer<const int*>::value);
-}
-
-TEST(TypeTraitsTest, type_equals) {
-  EXPECT_FALSE((type_equals<int, const int>::value));
-  EXPECT_FALSE((type_equals<int, int&>::value));
-  EXPECT_FALSE((type_equals<int, double>::value));
-  EXPECT_TRUE((type_equals<char, char>::value));
-}
-
-TEST(TypeTraitsTest, remove_reference) {
-  EXPECT_TRUE((type_equals<char, remove_reference<char&>::type>::value));
-  EXPECT_TRUE((type_equals<const int,
-               remove_reference<const int&>::type>::value));
-  EXPECT_TRUE((type_equals<int, remove_reference<int>::type>::value));
-  EXPECT_TRUE((type_equals<double*, remove_reference<double*>::type>::value));
-}
-
-#if GTEST_HAS_STREAM_REDIRECTION
-
-// Verifies that Log() behaves correctly for the given verbosity level
-// and log severity.
-std::string GrabOutput(void(*logger)(), const char* verbosity) {
-  const string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = verbosity;
-  CaptureStdout();
-  logger();
-  GMOCK_FLAG(verbose) = saved_flag;
-  return GetCapturedStdout();
-}
-
-class DummyMock {
- public:
-  MOCK_METHOD0(TestMethod, void());
-  MOCK_METHOD1(TestMethodArg, void(int dummy));
-};
-
-void ExpectCallLogger() {
-  DummyMock mock;
-  EXPECT_CALL(mock, TestMethod());
-  mock.TestMethod();
-};
-
-// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
-TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
-  EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
-              HasSubstr("EXPECT_CALL(mock, TestMethod())"));
-}
-
-// Verifies that EXPECT_CALL doesn't log
-// if the --gmock_verbose flag is set to "warning".
-TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
-  EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());
-}
-
-// Verifies that EXPECT_CALL doesn't log
-// if the --gmock_verbose flag is set to "error".
-TEST(ExpectCallTest,  DoesNotLogWhenVerbosityIsError) {
-  EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
-}
-
-void OnCallLogger() {
-  DummyMock mock;
-  ON_CALL(mock, TestMethod());
-};
-
-// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
-TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
-  EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
-              HasSubstr("ON_CALL(mock, TestMethod())"));
-}
-
-// Verifies that ON_CALL doesn't log
-// if the --gmock_verbose flag is set to "warning".
-TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {
-  EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());
-}
-
-// Verifies that ON_CALL doesn't log if
-// the --gmock_verbose flag is set to "error".
-TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
-  EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());
-}
-
-void OnCallAnyArgumentLogger() {
-  DummyMock mock;
-  ON_CALL(mock, TestMethodArg(_));
-}
-
-// Verifies that ON_CALL prints provided _ argument.
-TEST(OnCallTest, LogsAnythingArgument) {
-  EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
-              HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
-}
-
-#endif  // GTEST_HAS_STREAM_REDIRECTION
-
-// Tests StlContainerView.
-
-TEST(StlContainerViewTest, WorksForStlContainer) {
-  StaticAssertTypeEq<std::vector<int>,
-      StlContainerView<std::vector<int> >::type>();
-  StaticAssertTypeEq<const std::vector<double>&,
-      StlContainerView<std::vector<double> >::const_reference>();
-
-  typedef std::vector<char> Chars;
-  Chars v1;
-  const Chars& v2(StlContainerView<Chars>::ConstReference(v1));
-  EXPECT_EQ(&v1, &v2);
-
-  v1.push_back('a');
-  Chars v3 = StlContainerView<Chars>::Copy(v1);
-  EXPECT_THAT(v3, Eq(v3));
-}
-
-TEST(StlContainerViewTest, WorksForStaticNativeArray) {
-  StaticAssertTypeEq<NativeArray<int>,
-      StlContainerView<int[3]>::type>();
-  StaticAssertTypeEq<NativeArray<double>,
-      StlContainerView<const double[4]>::type>();
-  StaticAssertTypeEq<NativeArray<char[3]>,
-      StlContainerView<const char[2][3]>::type>();
-
-  StaticAssertTypeEq<const NativeArray<int>,
-      StlContainerView<int[2]>::const_reference>();
-
-  int a1[3] = { 0, 1, 2 };
-  NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
-  EXPECT_EQ(3U, a2.size());
-  EXPECT_EQ(a1, a2.begin());
-
-  const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);
-  ASSERT_EQ(3U, a3.size());
-  EXPECT_EQ(0, a3.begin()[0]);
-  EXPECT_EQ(1, a3.begin()[1]);
-  EXPECT_EQ(2, a3.begin()[2]);
-
-  // Makes sure a1 and a3 aren't aliases.
-  a1[0] = 3;
-  EXPECT_EQ(0, a3.begin()[0]);
-}
-
-TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
-  StaticAssertTypeEq<NativeArray<int>,
-      StlContainerView<tuple<const int*, size_t> >::type>();
-  StaticAssertTypeEq<NativeArray<double>,
-      StlContainerView<tuple<linked_ptr<double>, int> >::type>();
-
-  StaticAssertTypeEq<const NativeArray<int>,
-      StlContainerView<tuple<const int*, int> >::const_reference>();
-
-  int a1[3] = { 0, 1, 2 };
-  const int* const p1 = a1;
-  NativeArray<int> a2 = StlContainerView<tuple<const int*, int> >::
-      ConstReference(make_tuple(p1, 3));
-  EXPECT_EQ(3U, a2.size());
-  EXPECT_EQ(a1, a2.begin());
-
-  const NativeArray<int> a3 = StlContainerView<tuple<int*, size_t> >::
-      Copy(make_tuple(static_cast<int*>(a1), 3));
-  ASSERT_EQ(3U, a3.size());
-  EXPECT_EQ(0, a3.begin()[0]);
-  EXPECT_EQ(1, a3.begin()[1]);
-  EXPECT_EQ(2, a3.begin()[2]);
-
-  // Makes sure a1 and a3 aren't aliases.
-  a1[0] = 3;
-  EXPECT_EQ(0, a3.begin()[0]);
-}
-
-}  // namespace
-}  // namespace internal
-}  // namespace testing
diff --git a/testing/gmock/test/gmock-matchers_test.cc b/testing/gmock/test/gmock-matchers_test.cc
deleted file mode 100644
index b09acba..0000000
--- a/testing/gmock/test/gmock-matchers_test.cc
+++ /dev/null
@@ -1,5646 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests some commonly used argument matchers.
-
-#include "gmock/gmock-matchers.h"
-#include "gmock/gmock-more-matchers.h"
-
-#include <string.h>
-#include <time.h>
-#include <deque>
-#include <functional>
-#include <iostream>
-#include <iterator>
-#include <limits>
-#include <list>
-#include <map>
-#include <set>
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-#if GTEST_HAS_STD_FORWARD_LIST_
-# include <forward_list>  // NOLINT
-#endif
-
-namespace testing {
-
-namespace internal {
-GTEST_API_ string JoinAsTuple(const Strings& fields);
-}  // namespace internal
-
-namespace gmock_matchers_test {
-
-using std::greater;
-using std::less;
-using std::list;
-using std::make_pair;
-using std::map;
-using std::multimap;
-using std::multiset;
-using std::ostream;
-using std::pair;
-using std::set;
-using std::stringstream;
-using std::vector;
-using testing::A;
-using testing::AllArgs;
-using testing::AllOf;
-using testing::An;
-using testing::AnyOf;
-using testing::ByRef;
-using testing::ContainsRegex;
-using testing::DoubleEq;
-using testing::DoubleNear;
-using testing::EndsWith;
-using testing::Eq;
-using testing::ExplainMatchResult;
-using testing::Field;
-using testing::FloatEq;
-using testing::FloatNear;
-using testing::Ge;
-using testing::Gt;
-using testing::HasSubstr;
-using testing::IsEmpty;
-using testing::IsNull;
-using testing::Key;
-using testing::Le;
-using testing::Lt;
-using testing::MakeMatcher;
-using testing::MakePolymorphicMatcher;
-using testing::MatchResultListener;
-using testing::Matcher;
-using testing::MatcherCast;
-using testing::MatcherInterface;
-using testing::Matches;
-using testing::MatchesRegex;
-using testing::NanSensitiveDoubleEq;
-using testing::NanSensitiveDoubleNear;
-using testing::NanSensitiveFloatEq;
-using testing::NanSensitiveFloatNear;
-using testing::Ne;
-using testing::Not;
-using testing::NotNull;
-using testing::Pair;
-using testing::Pointee;
-using testing::Pointwise;
-using testing::PolymorphicMatcher;
-using testing::Property;
-using testing::Ref;
-using testing::ResultOf;
-using testing::SizeIs;
-using testing::StartsWith;
-using testing::StrCaseEq;
-using testing::StrCaseNe;
-using testing::StrEq;
-using testing::StrNe;
-using testing::StringMatchResultListener;
-using testing::Truly;
-using testing::TypedEq;
-using testing::UnorderedPointwise;
-using testing::Value;
-using testing::WhenSorted;
-using testing::WhenSortedBy;
-using testing::_;
-using testing::get;
-using testing::internal::DummyMatchResultListener;
-using testing::internal::ElementMatcherPair;
-using testing::internal::ElementMatcherPairs;
-using testing::internal::ExplainMatchFailureTupleTo;
-using testing::internal::FloatingEqMatcher;
-using testing::internal::FormatMatcherDescription;
-using testing::internal::IsReadableTypeName;
-using testing::internal::JoinAsTuple;
-using testing::internal::linked_ptr;
-using testing::internal::MatchMatrix;
-using testing::internal::RE;
-using testing::internal::scoped_ptr;
-using testing::internal::StreamMatchResultListener;
-using testing::internal::Strings;
-using testing::internal::linked_ptr;
-using testing::internal::scoped_ptr;
-using testing::internal::string;
-using testing::make_tuple;
-using testing::tuple;
-
-// For testing ExplainMatchResultTo().
-class GreaterThanMatcher : public MatcherInterface<int> {
- public:
-  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
-
-  virtual void DescribeTo(ostream* os) const {
-    *os << "is > " << rhs_;
-  }
-
-  virtual bool MatchAndExplain(int lhs,
-                               MatchResultListener* listener) const {
-    const int diff = lhs - rhs_;
-    if (diff > 0) {
-      *listener << "which is " << diff << " more than " << rhs_;
-    } else if (diff == 0) {
-      *listener << "which is the same as " << rhs_;
-    } else {
-      *listener << "which is " << -diff << " less than " << rhs_;
-    }
-
-    return lhs > rhs_;
-  }
-
- private:
-  int rhs_;
-};
-
-Matcher<int> GreaterThan(int n) {
-  return MakeMatcher(new GreaterThanMatcher(n));
-}
-
-string OfType(const string& type_name) {
-#if GTEST_HAS_RTTI
-  return " (of type " + type_name + ")";
-#else
-  return "";
-#endif
-}
-
-// Returns the description of the given matcher.
-template <typename T>
-string Describe(const Matcher<T>& m) {
-  stringstream ss;
-  m.DescribeTo(&ss);
-  return ss.str();
-}
-
-// Returns the description of the negation of the given matcher.
-template <typename T>
-string DescribeNegation(const Matcher<T>& m) {
-  stringstream ss;
-  m.DescribeNegationTo(&ss);
-  return ss.str();
-}
-
-// Returns the reason why x matches, or doesn't match, m.
-template <typename MatcherType, typename Value>
-string Explain(const MatcherType& m, const Value& x) {
-  StringMatchResultListener listener;
-  ExplainMatchResult(m, x, &listener);
-  return listener.str();
-}
-
-TEST(MatchResultListenerTest, StreamingWorks) {
-  StringMatchResultListener listener;
-  listener << "hi" << 5;
-  EXPECT_EQ("hi5", listener.str());
-
-  listener.Clear();
-  EXPECT_EQ("", listener.str());
-
-  listener << 42;
-  EXPECT_EQ("42", listener.str());
-
-  // Streaming shouldn't crash when the underlying ostream is NULL.
-  DummyMatchResultListener dummy;
-  dummy << "hi" << 5;
-}
-
-TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
-  EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
-  EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
-
-  EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
-}
-
-TEST(MatchResultListenerTest, IsInterestedWorks) {
-  EXPECT_TRUE(StringMatchResultListener().IsInterested());
-  EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
-
-  EXPECT_FALSE(DummyMatchResultListener().IsInterested());
-  EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
-}
-
-// Makes sure that the MatcherInterface<T> interface doesn't
-// change.
-class EvenMatcherImpl : public MatcherInterface<int> {
- public:
-  virtual bool MatchAndExplain(int x,
-                               MatchResultListener* /* listener */) const {
-    return x % 2 == 0;
-  }
-
-  virtual void DescribeTo(ostream* os) const {
-    *os << "is an even number";
-  }
-
-  // We deliberately don't define DescribeNegationTo() and
-  // ExplainMatchResultTo() here, to make sure the definition of these
-  // two methods is optional.
-};
-
-// Makes sure that the MatcherInterface API doesn't change.
-TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
-  EvenMatcherImpl m;
-}
-
-// Tests implementing a monomorphic matcher using MatchAndExplain().
-
-class NewEvenMatcherImpl : public MatcherInterface<int> {
- public:
-  virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
-    const bool match = x % 2 == 0;
-    // Verifies that we can stream to a listener directly.
-    *listener << "value % " << 2;
-    if (listener->stream() != NULL) {
-      // Verifies that we can stream to a listener's underlying stream
-      // too.
-      *listener->stream() << " == " << (x % 2);
-    }
-    return match;
-  }
-
-  virtual void DescribeTo(ostream* os) const {
-    *os << "is an even number";
-  }
-};
-
-TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
-  Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(3));
-  EXPECT_EQ("value % 2 == 0", Explain(m, 2));
-  EXPECT_EQ("value % 2 == 1", Explain(m, 3));
-}
-
-// Tests default-constructing a matcher.
-TEST(MatcherTest, CanBeDefaultConstructed) {
-  Matcher<double> m;
-}
-
-// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
-TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
-  const MatcherInterface<int>* impl = new EvenMatcherImpl;
-  Matcher<int> m(impl);
-  EXPECT_TRUE(m.Matches(4));
-  EXPECT_FALSE(m.Matches(5));
-}
-
-// Tests that value can be used in place of Eq(value).
-TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
-  Matcher<int> m1 = 5;
-  EXPECT_TRUE(m1.Matches(5));
-  EXPECT_FALSE(m1.Matches(6));
-}
-
-// Tests that NULL can be used in place of Eq(NULL).
-TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
-  Matcher<int*> m1 = NULL;
-  EXPECT_TRUE(m1.Matches(NULL));
-  int n = 0;
-  EXPECT_FALSE(m1.Matches(&n));
-}
-
-// Tests that matchers are copyable.
-TEST(MatcherTest, IsCopyable) {
-  // Tests the copy constructor.
-  Matcher<bool> m1 = Eq(false);
-  EXPECT_TRUE(m1.Matches(false));
-  EXPECT_FALSE(m1.Matches(true));
-
-  // Tests the assignment operator.
-  m1 = Eq(true);
-  EXPECT_TRUE(m1.Matches(true));
-  EXPECT_FALSE(m1.Matches(false));
-}
-
-// Tests that Matcher<T>::DescribeTo() calls
-// MatcherInterface<T>::DescribeTo().
-TEST(MatcherTest, CanDescribeItself) {
-  EXPECT_EQ("is an even number",
-            Describe(Matcher<int>(new EvenMatcherImpl)));
-}
-
-// Tests Matcher<T>::MatchAndExplain().
-TEST(MatcherTest, MatchAndExplain) {
-  Matcher<int> m = GreaterThan(0);
-  StringMatchResultListener listener1;
-  EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
-  EXPECT_EQ("which is 42 more than 0", listener1.str());
-
-  StringMatchResultListener listener2;
-  EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
-  EXPECT_EQ("which is 9 less than 0", listener2.str());
-}
-
-// Tests that a C-string literal can be implicitly converted to a
-// Matcher<string> or Matcher<const string&>.
-TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
-  Matcher<string> m1 = "hi";
-  EXPECT_TRUE(m1.Matches("hi"));
-  EXPECT_FALSE(m1.Matches("hello"));
-
-  Matcher<const string&> m2 = "hi";
-  EXPECT_TRUE(m2.Matches("hi"));
-  EXPECT_FALSE(m2.Matches("hello"));
-}
-
-// Tests that a string object can be implicitly converted to a
-// Matcher<string> or Matcher<const string&>.
-TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
-  Matcher<string> m1 = string("hi");
-  EXPECT_TRUE(m1.Matches("hi"));
-  EXPECT_FALSE(m1.Matches("hello"));
-
-  Matcher<const string&> m2 = string("hi");
-  EXPECT_TRUE(m2.Matches("hi"));
-  EXPECT_FALSE(m2.Matches("hello"));
-}
-
-#if GTEST_HAS_STRING_PIECE_
-// Tests that a C-string literal can be implicitly converted to a
-// Matcher<StringPiece> or Matcher<const StringPiece&>.
-TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
-  Matcher<StringPiece> m1 = "cats";
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const StringPiece&> m2 = "cats";
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-
-// Tests that a string object can be implicitly converted to a
-// Matcher<StringPiece> or Matcher<const StringPiece&>.
-TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
-  Matcher<StringPiece> m1 = string("cats");
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const StringPiece&> m2 = string("cats");
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-
-// Tests that a StringPiece object can be implicitly converted to a
-// Matcher<StringPiece> or Matcher<const StringPiece&>.
-TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
-  Matcher<StringPiece> m1 = StringPiece("cats");
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const StringPiece&> m2 = StringPiece("cats");
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-#endif  // GTEST_HAS_STRING_PIECE_
-
-// Tests that MakeMatcher() constructs a Matcher<T> from a
-// MatcherInterface* without requiring the user to explicitly
-// write the type.
-TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
-  const MatcherInterface<int>* dummy_impl = NULL;
-  Matcher<int> m = MakeMatcher(dummy_impl);
-}
-
-// Tests that MakePolymorphicMatcher() can construct a polymorphic
-// matcher from its implementation using the old API.
-const int g_bar = 1;
-class ReferencesBarOrIsZeroImpl {
- public:
-  template <typename T>
-  bool MatchAndExplain(const T& x,
-                       MatchResultListener* /* listener */) const {
-    const void* p = &x;
-    return p == &g_bar || x == 0;
-  }
-
-  void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "doesn't reference g_bar and is not zero";
-  }
-};
-
-// This function verifies that MakePolymorphicMatcher() returns a
-// PolymorphicMatcher<T> where T is the argument's type.
-PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
-  return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
-}
-
-TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
-  // Using a polymorphic matcher to match a reference type.
-  Matcher<const int&> m1 = ReferencesBarOrIsZero();
-  EXPECT_TRUE(m1.Matches(0));
-  // Verifies that the identity of a by-reference argument is preserved.
-  EXPECT_TRUE(m1.Matches(g_bar));
-  EXPECT_FALSE(m1.Matches(1));
-  EXPECT_EQ("g_bar or zero", Describe(m1));
-
-  // Using a polymorphic matcher to match a value type.
-  Matcher<double> m2 = ReferencesBarOrIsZero();
-  EXPECT_TRUE(m2.Matches(0.0));
-  EXPECT_FALSE(m2.Matches(0.1));
-  EXPECT_EQ("g_bar or zero", Describe(m2));
-}
-
-// Tests implementing a polymorphic matcher using MatchAndExplain().
-
-class PolymorphicIsEvenImpl {
- public:
-  void DescribeTo(ostream* os) const { *os << "is even"; }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "is odd";
-  }
-
-  template <typename T>
-  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
-    // Verifies that we can stream to the listener directly.
-    *listener << "% " << 2;
-    if (listener->stream() != NULL) {
-      // Verifies that we can stream to the listener's underlying stream
-      // too.
-      *listener->stream() << " == " << (x % 2);
-    }
-    return (x % 2) == 0;
-  }
-};
-
-PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
-  return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
-}
-
-TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
-  // Using PolymorphicIsEven() as a Matcher<int>.
-  const Matcher<int> m1 = PolymorphicIsEven();
-  EXPECT_TRUE(m1.Matches(42));
-  EXPECT_FALSE(m1.Matches(43));
-  EXPECT_EQ("is even", Describe(m1));
-
-  const Matcher<int> not_m1 = Not(m1);
-  EXPECT_EQ("is odd", Describe(not_m1));
-
-  EXPECT_EQ("% 2 == 0", Explain(m1, 42));
-
-  // Using PolymorphicIsEven() as a Matcher<char>.
-  const Matcher<char> m2 = PolymorphicIsEven();
-  EXPECT_TRUE(m2.Matches('\x42'));
-  EXPECT_FALSE(m2.Matches('\x43'));
-  EXPECT_EQ("is even", Describe(m2));
-
-  const Matcher<char> not_m2 = Not(m2);
-  EXPECT_EQ("is odd", Describe(not_m2));
-
-  EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
-TEST(MatcherCastTest, FromPolymorphicMatcher) {
-  Matcher<int> m = MatcherCast<int>(Eq(5));
-  EXPECT_TRUE(m.Matches(5));
-  EXPECT_FALSE(m.Matches(6));
-}
-
-// For testing casting matchers between compatible types.
-class IntValue {
- public:
-  // An int can be statically (although not implicitly) cast to a
-  // IntValue.
-  explicit IntValue(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
- private:
-  int value_;
-};
-
-// For testing casting matchers between compatible types.
-bool IsPositiveIntValue(const IntValue& foo) {
-  return foo.value() > 0;
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
-// can be statically converted to U.
-TEST(MatcherCastTest, FromCompatibleType) {
-  Matcher<double> m1 = Eq(2.0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(2));
-  EXPECT_FALSE(m2.Matches(3));
-
-  Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
-  Matcher<int> m4 = MatcherCast<int>(m3);
-  // In the following, the arguments 1 and 0 are statically converted
-  // to IntValue objects, and then tested by the IsPositiveIntValue()
-  // predicate.
-  EXPECT_TRUE(m4.Matches(1));
-  EXPECT_FALSE(m4.Matches(0));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
-TEST(MatcherCastTest, FromConstReferenceToNonReference) {
-  Matcher<const int&> m1 = Eq(0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
-TEST(MatcherCastTest, FromReferenceToNonReference) {
-  Matcher<int&> m1 = Eq(0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
-TEST(MatcherCastTest, FromNonReferenceToConstReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<const int&> m2 = MatcherCast<const int&>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
-TEST(MatcherCastTest, FromNonReferenceToReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int&> m2 = MatcherCast<int&>(m1);
-  int n = 0;
-  EXPECT_TRUE(m2.Matches(n));
-  n = 1;
-  EXPECT_FALSE(m2.Matches(n));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
-TEST(MatcherCastTest, FromSameType) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Implicitly convertible from any type.
-struct ConvertibleFromAny {
-  ConvertibleFromAny(int a_value) : value(a_value) {}
-  template <typename T>
-  ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
-    ADD_FAILURE() << "Conversion constructor called";
-  }
-  int value;
-};
-
-bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
-  return a.value == b.value;
-}
-
-ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
-  return os << a.value;
-}
-
-TEST(MatcherCastTest, ConversionConstructorIsUsed) {
-  Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-
-TEST(MatcherCastTest, FromConvertibleFromAny) {
-  Matcher<ConvertibleFromAny> m =
-      MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-
-struct IntReferenceWrapper {
-  IntReferenceWrapper(const int& a_value) : value(&a_value) {}
-  const int* value;
-};
-
-bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
-  return a.value == b.value;
-}
-
-TEST(MatcherCastTest, ValueIsNotCopied) {
-  int n = 42;
-  Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
-  // Verify that the matcher holds a reference to n, not to its temporary copy.
-  EXPECT_TRUE(m.Matches(n));
-}
-
-class Base {
- public:
-  virtual ~Base() {}
-  Base() {}
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
-};
-
-class Derived : public Base {
- public:
-  Derived() : Base() {}
-  int i;
-};
-
-class OtherDerived : public Base {};
-
-// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
-TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
-  Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
-  EXPECT_TRUE(m2.Matches(' '));
-  EXPECT_FALSE(m2.Matches('\n'));
-}
-
-// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
-// T and U are arithmetic types and T can be losslessly converted to
-// U.
-TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
-  Matcher<double> m1 = DoubleEq(1.0);
-  Matcher<float> m2 = SafeMatcherCast<float>(m1);
-  EXPECT_TRUE(m2.Matches(1.0f));
-  EXPECT_FALSE(m2.Matches(2.0f));
-
-  Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
-  EXPECT_TRUE(m3.Matches('a'));
-  EXPECT_FALSE(m3.Matches('b'));
-}
-
-// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
-// are pointers or references to a derived and a base class, correspondingly.
-TEST(SafeMatcherCastTest, FromBaseClass) {
-  Derived d, d2;
-  Matcher<Base*> m1 = Eq(&d);
-  Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
-  EXPECT_TRUE(m2.Matches(&d));
-  EXPECT_FALSE(m2.Matches(&d2));
-
-  Matcher<Base&> m3 = Ref(d);
-  Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
-  EXPECT_TRUE(m4.Matches(d));
-  EXPECT_FALSE(m4.Matches(d2));
-}
-
-// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
-TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
-  int n = 0;
-  Matcher<const int&> m1 = Ref(n);
-  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
-  int n1 = 0;
-  EXPECT_TRUE(m2.Matches(n));
-  EXPECT_FALSE(m2.Matches(n1));
-}
-
-// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
-TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
-TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
-  int n = 0;
-  EXPECT_TRUE(m2.Matches(n));
-  n = 1;
-  EXPECT_FALSE(m2.Matches(n));
-}
-
-// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
-TEST(SafeMatcherCastTest, FromSameType) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int> m2 = SafeMatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
-  Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-
-TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
-  Matcher<ConvertibleFromAny> m =
-      SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-
-TEST(SafeMatcherCastTest, ValueIsNotCopied) {
-  int n = 42;
-  Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
-  // Verify that the matcher holds a reference to n, not to its temporary copy.
-  EXPECT_TRUE(m.Matches(n));
-}
-
-TEST(ExpectThat, TakesLiterals) {
-  EXPECT_THAT(1, 1);
-  EXPECT_THAT(1.0, 1.0);
-  EXPECT_THAT(string(), "");
-}
-
-TEST(ExpectThat, TakesFunctions) {
-  struct Helper {
-    static void Func() {}
-  };
-  void (*func)() = Helper::Func;
-  EXPECT_THAT(func, Helper::Func);
-  EXPECT_THAT(func, &Helper::Func);
-}
-
-// Tests that A<T>() matches any value of type T.
-TEST(ATest, MatchesAnyValue) {
-  // Tests a matcher for a value type.
-  Matcher<double> m1 = A<double>();
-  EXPECT_TRUE(m1.Matches(91.43));
-  EXPECT_TRUE(m1.Matches(-15.32));
-
-  // Tests a matcher for a reference type.
-  int a = 2;
-  int b = -6;
-  Matcher<int&> m2 = A<int&>();
-  EXPECT_TRUE(m2.Matches(a));
-  EXPECT_TRUE(m2.Matches(b));
-}
-
-TEST(ATest, WorksForDerivedClass) {
-  Base base;
-  Derived derived;
-  EXPECT_THAT(&base, A<Base*>());
-  // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
-  EXPECT_THAT(&derived, A<Base*>());
-  EXPECT_THAT(&derived, A<Derived*>());
-}
-
-// Tests that A<T>() describes itself properly.
-TEST(ATest, CanDescribeSelf) {
-  EXPECT_EQ("is anything", Describe(A<bool>()));
-}
-
-// Tests that An<T>() matches any value of type T.
-TEST(AnTest, MatchesAnyValue) {
-  // Tests a matcher for a value type.
-  Matcher<int> m1 = An<int>();
-  EXPECT_TRUE(m1.Matches(9143));
-  EXPECT_TRUE(m1.Matches(-1532));
-
-  // Tests a matcher for a reference type.
-  int a = 2;
-  int b = -6;
-  Matcher<int&> m2 = An<int&>();
-  EXPECT_TRUE(m2.Matches(a));
-  EXPECT_TRUE(m2.Matches(b));
-}
-
-// Tests that An<T>() describes itself properly.
-TEST(AnTest, CanDescribeSelf) {
-  EXPECT_EQ("is anything", Describe(An<int>()));
-}
-
-// Tests that _ can be used as a matcher for any type and matches any
-// value of that type.
-TEST(UnderscoreTest, MatchesAnyValue) {
-  // Uses _ as a matcher for a value type.
-  Matcher<int> m1 = _;
-  EXPECT_TRUE(m1.Matches(123));
-  EXPECT_TRUE(m1.Matches(-242));
-
-  // Uses _ as a matcher for a reference type.
-  bool a = false;
-  const bool b = true;
-  Matcher<const bool&> m2 = _;
-  EXPECT_TRUE(m2.Matches(a));
-  EXPECT_TRUE(m2.Matches(b));
-}
-
-// Tests that _ describes itself properly.
-TEST(UnderscoreTest, CanDescribeSelf) {
-  Matcher<int> m = _;
-  EXPECT_EQ("is anything", Describe(m));
-}
-
-// Tests that Eq(x) matches any value equal to x.
-TEST(EqTest, MatchesEqualValue) {
-  // 2 C-strings with same content but different addresses.
-  const char a1[] = "hi";
-  const char a2[] = "hi";
-
-  Matcher<const char*> m1 = Eq(a1);
-  EXPECT_TRUE(m1.Matches(a1));
-  EXPECT_FALSE(m1.Matches(a2));
-}
-
-// Tests that Eq(v) describes itself properly.
-
-class Unprintable {
- public:
-  Unprintable() : c_('a') {}
-
-  bool operator==(const Unprintable& /* rhs */) { return true; }
- private:
-  char c_;
-};
-
-TEST(EqTest, CanDescribeSelf) {
-  Matcher<Unprintable> m = Eq(Unprintable());
-  EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
-}
-
-// Tests that Eq(v) can be used to match any type that supports
-// comparing with type T, where T is v's type.
-TEST(EqTest, IsPolymorphic) {
-  Matcher<int> m1 = Eq(1);
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_FALSE(m1.Matches(2));
-
-  Matcher<char> m2 = Eq(1);
-  EXPECT_TRUE(m2.Matches('\1'));
-  EXPECT_FALSE(m2.Matches('a'));
-}
-
-// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
-TEST(TypedEqTest, ChecksEqualityForGivenType) {
-  Matcher<char> m1 = TypedEq<char>('a');
-  EXPECT_TRUE(m1.Matches('a'));
-  EXPECT_FALSE(m1.Matches('b'));
-
-  Matcher<int> m2 = TypedEq<int>(6);
-  EXPECT_TRUE(m2.Matches(6));
-  EXPECT_FALSE(m2.Matches(7));
-}
-
-// Tests that TypedEq(v) describes itself properly.
-TEST(TypedEqTest, CanDescribeSelf) {
-  EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
-}
-
-// Tests that TypedEq<T>(v) has type Matcher<T>.
-
-// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
-// is a "bare" type (i.e. not in the form of const U or U&).  If v's
-// type is not T, the compiler will generate a message about
-// "undefined referece".
-template <typename T>
-struct Type {
-  static bool IsTypeOf(const T& /* v */) { return true; }
-
-  template <typename T2>
-  static void IsTypeOf(T2 v);
-};
-
-TEST(TypedEqTest, HasSpecifiedType) {
-  // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
-  Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
-  Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
-}
-
-// Tests that Ge(v) matches anything >= v.
-TEST(GeTest, ImplementsGreaterThanOrEqual) {
-  Matcher<int> m1 = Ge(0);
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_TRUE(m1.Matches(0));
-  EXPECT_FALSE(m1.Matches(-1));
-}
-
-// Tests that Ge(v) describes itself properly.
-TEST(GeTest, CanDescribeSelf) {
-  Matcher<int> m = Ge(5);
-  EXPECT_EQ("is >= 5", Describe(m));
-}
-
-// Tests that Gt(v) matches anything > v.
-TEST(GtTest, ImplementsGreaterThan) {
-  Matcher<double> m1 = Gt(0);
-  EXPECT_TRUE(m1.Matches(1.0));
-  EXPECT_FALSE(m1.Matches(0.0));
-  EXPECT_FALSE(m1.Matches(-1.0));
-}
-
-// Tests that Gt(v) describes itself properly.
-TEST(GtTest, CanDescribeSelf) {
-  Matcher<int> m = Gt(5);
-  EXPECT_EQ("is > 5", Describe(m));
-}
-
-// Tests that Le(v) matches anything <= v.
-TEST(LeTest, ImplementsLessThanOrEqual) {
-  Matcher<char> m1 = Le('b');
-  EXPECT_TRUE(m1.Matches('a'));
-  EXPECT_TRUE(m1.Matches('b'));
-  EXPECT_FALSE(m1.Matches('c'));
-}
-
-// Tests that Le(v) describes itself properly.
-TEST(LeTest, CanDescribeSelf) {
-  Matcher<int> m = Le(5);
-  EXPECT_EQ("is <= 5", Describe(m));
-}
-
-// Tests that Lt(v) matches anything < v.
-TEST(LtTest, ImplementsLessThan) {
-  Matcher<const string&> m1 = Lt("Hello");
-  EXPECT_TRUE(m1.Matches("Abc"));
-  EXPECT_FALSE(m1.Matches("Hello"));
-  EXPECT_FALSE(m1.Matches("Hello, world!"));
-}
-
-// Tests that Lt(v) describes itself properly.
-TEST(LtTest, CanDescribeSelf) {
-  Matcher<int> m = Lt(5);
-  EXPECT_EQ("is < 5", Describe(m));
-}
-
-// Tests that Ne(v) matches anything != v.
-TEST(NeTest, ImplementsNotEqual) {
-  Matcher<int> m1 = Ne(0);
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_TRUE(m1.Matches(-1));
-  EXPECT_FALSE(m1.Matches(0));
-}
-
-// Tests that Ne(v) describes itself properly.
-TEST(NeTest, CanDescribeSelf) {
-  Matcher<int> m = Ne(5);
-  EXPECT_EQ("isn't equal to 5", Describe(m));
-}
-
-// Tests that IsNull() matches any NULL pointer of any type.
-TEST(IsNullTest, MatchesNullPointer) {
-  Matcher<int*> m1 = IsNull();
-  int* p1 = NULL;
-  int n = 0;
-  EXPECT_TRUE(m1.Matches(p1));
-  EXPECT_FALSE(m1.Matches(&n));
-
-  Matcher<const char*> m2 = IsNull();
-  const char* p2 = NULL;
-  EXPECT_TRUE(m2.Matches(p2));
-  EXPECT_FALSE(m2.Matches("hi"));
-
-#if !GTEST_OS_SYMBIAN
-  // Nokia's Symbian compiler generates:
-  // gmock-matchers.h: ambiguous access to overloaded function
-  // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
-  // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
-  //     MatcherInterface<void *> *)'
-  // gmock-matchers.h:  (point of instantiation: 'testing::
-  //     gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
-  // gmock-matchers.h:   (instantiating: 'testing::PolymorphicMatc
-  Matcher<void*> m3 = IsNull();
-  void* p3 = NULL;
-  EXPECT_TRUE(m3.Matches(p3));
-  EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
-#endif
-}
-
-TEST(IsNullTest, LinkedPtr) {
-  const Matcher<linked_ptr<int> > m = IsNull();
-  const linked_ptr<int> null_p;
-  const linked_ptr<int> non_null_p(new int);
-
-  EXPECT_TRUE(m.Matches(null_p));
-  EXPECT_FALSE(m.Matches(non_null_p));
-}
-
-TEST(IsNullTest, ReferenceToConstLinkedPtr) {
-  const Matcher<const linked_ptr<double>&> m = IsNull();
-  const linked_ptr<double> null_p;
-  const linked_ptr<double> non_null_p(new double);
-
-  EXPECT_TRUE(m.Matches(null_p));
-  EXPECT_FALSE(m.Matches(non_null_p));
-}
-
-#if GTEST_LANG_CXX11
-TEST(IsNullTest, StdFunction) {
-  const Matcher<std::function<void()>> m = IsNull();
-
-  EXPECT_TRUE(m.Matches(std::function<void()>()));
-  EXPECT_FALSE(m.Matches([]{}));
-}
-#endif  // GTEST_LANG_CXX11
-
-// Tests that IsNull() describes itself properly.
-TEST(IsNullTest, CanDescribeSelf) {
-  Matcher<int*> m = IsNull();
-  EXPECT_EQ("is NULL", Describe(m));
-  EXPECT_EQ("isn't NULL", DescribeNegation(m));
-}
-
-// Tests that NotNull() matches any non-NULL pointer of any type.
-TEST(NotNullTest, MatchesNonNullPointer) {
-  Matcher<int*> m1 = NotNull();
-  int* p1 = NULL;
-  int n = 0;
-  EXPECT_FALSE(m1.Matches(p1));
-  EXPECT_TRUE(m1.Matches(&n));
-
-  Matcher<const char*> m2 = NotNull();
-  const char* p2 = NULL;
-  EXPECT_FALSE(m2.Matches(p2));
-  EXPECT_TRUE(m2.Matches("hi"));
-}
-
-TEST(NotNullTest, LinkedPtr) {
-  const Matcher<linked_ptr<int> > m = NotNull();
-  const linked_ptr<int> null_p;
-  const linked_ptr<int> non_null_p(new int);
-
-  EXPECT_FALSE(m.Matches(null_p));
-  EXPECT_TRUE(m.Matches(non_null_p));
-}
-
-TEST(NotNullTest, ReferenceToConstLinkedPtr) {
-  const Matcher<const linked_ptr<double>&> m = NotNull();
-  const linked_ptr<double> null_p;
-  const linked_ptr<double> non_null_p(new double);
-
-  EXPECT_FALSE(m.Matches(null_p));
-  EXPECT_TRUE(m.Matches(non_null_p));
-}
-
-#if GTEST_LANG_CXX11
-TEST(NotNullTest, StdFunction) {
-  const Matcher<std::function<void()>> m = NotNull();
-
-  EXPECT_TRUE(m.Matches([]{}));
-  EXPECT_FALSE(m.Matches(std::function<void()>()));
-}
-#endif  // GTEST_LANG_CXX11
-
-// Tests that NotNull() describes itself properly.
-TEST(NotNullTest, CanDescribeSelf) {
-  Matcher<int*> m = NotNull();
-  EXPECT_EQ("isn't NULL", Describe(m));
-}
-
-// Tests that Ref(variable) matches an argument that references
-// 'variable'.
-TEST(RefTest, MatchesSameVariable) {
-  int a = 0;
-  int b = 0;
-  Matcher<int&> m = Ref(a);
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_FALSE(m.Matches(b));
-}
-
-// Tests that Ref(variable) describes itself properly.
-TEST(RefTest, CanDescribeSelf) {
-  int n = 5;
-  Matcher<int&> m = Ref(n);
-  stringstream ss;
-  ss << "references the variable @" << &n << " 5";
-  EXPECT_EQ(string(ss.str()), Describe(m));
-}
-
-// Test that Ref(non_const_varialbe) can be used as a matcher for a
-// const reference.
-TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
-  int a = 0;
-  int b = 0;
-  Matcher<const int&> m = Ref(a);
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_FALSE(m.Matches(b));
-}
-
-// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
-// used wherever Ref(base) can be used (Ref(derived) is a sub-type
-// of Ref(base), but not vice versa.
-
-TEST(RefTest, IsCovariant) {
-  Base base, base2;
-  Derived derived;
-  Matcher<const Base&> m1 = Ref(base);
-  EXPECT_TRUE(m1.Matches(base));
-  EXPECT_FALSE(m1.Matches(base2));
-  EXPECT_FALSE(m1.Matches(derived));
-
-  m1 = Ref(derived);
-  EXPECT_TRUE(m1.Matches(derived));
-  EXPECT_FALSE(m1.Matches(base));
-  EXPECT_FALSE(m1.Matches(base2));
-}
-
-TEST(RefTest, ExplainsResult) {
-  int n = 0;
-  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
-              StartsWith("which is located @"));
-
-  int m = 0;
-  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
-              StartsWith("which is located @"));
-}
-
-// Tests string comparison matchers.
-
-TEST(StrEqTest, MatchesEqualString) {
-  Matcher<const char*> m = StrEq(string("Hello"));
-  EXPECT_TRUE(m.Matches("Hello"));
-  EXPECT_FALSE(m.Matches("hello"));
-  EXPECT_FALSE(m.Matches(NULL));
-
-  Matcher<const string&> m2 = StrEq("Hello");
-  EXPECT_TRUE(m2.Matches("Hello"));
-  EXPECT_FALSE(m2.Matches("Hi"));
-}
-
-TEST(StrEqTest, CanDescribeSelf) {
-  Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
-  EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
-      Describe(m));
-
-  string str("01204500800");
-  str[3] = '\0';
-  Matcher<string> m2 = StrEq(str);
-  EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
-  str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
-  Matcher<string> m3 = StrEq(str);
-  EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
-}
-
-TEST(StrNeTest, MatchesUnequalString) {
-  Matcher<const char*> m = StrNe("Hello");
-  EXPECT_TRUE(m.Matches(""));
-  EXPECT_TRUE(m.Matches(NULL));
-  EXPECT_FALSE(m.Matches("Hello"));
-
-  Matcher<string> m2 = StrNe(string("Hello"));
-  EXPECT_TRUE(m2.Matches("hello"));
-  EXPECT_FALSE(m2.Matches("Hello"));
-}
-
-TEST(StrNeTest, CanDescribeSelf) {
-  Matcher<const char*> m = StrNe("Hi");
-  EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
-}
-
-TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
-  Matcher<const char*> m = StrCaseEq(string("Hello"));
-  EXPECT_TRUE(m.Matches("Hello"));
-  EXPECT_TRUE(m.Matches("hello"));
-  EXPECT_FALSE(m.Matches("Hi"));
-  EXPECT_FALSE(m.Matches(NULL));
-
-  Matcher<const string&> m2 = StrCaseEq("Hello");
-  EXPECT_TRUE(m2.Matches("hello"));
-  EXPECT_FALSE(m2.Matches("Hi"));
-}
-
-TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
-  string str1("oabocdooeoo");
-  string str2("OABOCDOOEOO");
-  Matcher<const string&> m0 = StrCaseEq(str1);
-  EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
-
-  str1[3] = str2[3] = '\0';
-  Matcher<const string&> m1 = StrCaseEq(str1);
-  EXPECT_TRUE(m1.Matches(str2));
-
-  str1[0] = str1[6] = str1[7] = str1[10] = '\0';
-  str2[0] = str2[6] = str2[7] = str2[10] = '\0';
-  Matcher<const string&> m2 = StrCaseEq(str1);
-  str1[9] = str2[9] = '\0';
-  EXPECT_FALSE(m2.Matches(str2));
-
-  Matcher<const string&> m3 = StrCaseEq(str1);
-  EXPECT_TRUE(m3.Matches(str2));
-
-  EXPECT_FALSE(m3.Matches(str2 + "x"));
-  str2.append(1, '\0');
-  EXPECT_FALSE(m3.Matches(str2));
-  EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
-}
-
-TEST(StrCaseEqTest, CanDescribeSelf) {
-  Matcher<string> m = StrCaseEq("Hi");
-  EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
-}
-
-TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
-  Matcher<const char*> m = StrCaseNe("Hello");
-  EXPECT_TRUE(m.Matches("Hi"));
-  EXPECT_TRUE(m.Matches(NULL));
-  EXPECT_FALSE(m.Matches("Hello"));
-  EXPECT_FALSE(m.Matches("hello"));
-
-  Matcher<string> m2 = StrCaseNe(string("Hello"));
-  EXPECT_TRUE(m2.Matches(""));
-  EXPECT_FALSE(m2.Matches("Hello"));
-}
-
-TEST(StrCaseNeTest, CanDescribeSelf) {
-  Matcher<const char*> m = StrCaseNe("Hi");
-  EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
-}
-
-// Tests that HasSubstr() works for matching string-typed values.
-TEST(HasSubstrTest, WorksForStringClasses) {
-  const Matcher<string> m1 = HasSubstr("foo");
-  EXPECT_TRUE(m1.Matches(string("I love food.")));
-  EXPECT_FALSE(m1.Matches(string("tofo")));
-
-  const Matcher<const std::string&> m2 = HasSubstr("foo");
-  EXPECT_TRUE(m2.Matches(std::string("I love food.")));
-  EXPECT_FALSE(m2.Matches(std::string("tofo")));
-}
-
-// Tests that HasSubstr() works for matching C-string-typed values.
-TEST(HasSubstrTest, WorksForCStrings) {
-  const Matcher<char*> m1 = HasSubstr("foo");
-  EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
-  EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const char*> m2 = HasSubstr("foo");
-  EXPECT_TRUE(m2.Matches("I love food."));
-  EXPECT_FALSE(m2.Matches("tofo"));
-  EXPECT_FALSE(m2.Matches(NULL));
-}
-
-// Tests that HasSubstr(s) describes itself properly.
-TEST(HasSubstrTest, CanDescribeSelf) {
-  Matcher<string> m = HasSubstr("foo\n\"");
-  EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
-}
-
-TEST(KeyTest, CanDescribeSelf) {
-  Matcher<const pair<std::string, int>&> m = Key("foo");
-  EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
-  EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
-}
-
-TEST(KeyTest, ExplainsResult) {
-  Matcher<pair<int, bool> > m = Key(GreaterThan(10));
-  EXPECT_EQ("whose first field is a value which is 5 less than 10",
-            Explain(m, make_pair(5, true)));
-  EXPECT_EQ("whose first field is a value which is 5 more than 10",
-            Explain(m, make_pair(15, true)));
-}
-
-TEST(KeyTest, MatchesCorrectly) {
-  pair<int, std::string> p(25, "foo");
-  EXPECT_THAT(p, Key(25));
-  EXPECT_THAT(p, Not(Key(42)));
-  EXPECT_THAT(p, Key(Ge(20)));
-  EXPECT_THAT(p, Not(Key(Lt(25))));
-}
-
-TEST(KeyTest, SafelyCastsInnerMatcher) {
-  Matcher<int> is_positive = Gt(0);
-  Matcher<int> is_negative = Lt(0);
-  pair<char, bool> p('a', true);
-  EXPECT_THAT(p, Key(is_positive));
-  EXPECT_THAT(p, Not(Key(is_negative)));
-}
-
-TEST(KeyTest, InsideContainsUsingMap) {
-  map<int, char> container;
-  container.insert(make_pair(1, 'a'));
-  container.insert(make_pair(2, 'b'));
-  container.insert(make_pair(4, 'c'));
-  EXPECT_THAT(container, Contains(Key(1)));
-  EXPECT_THAT(container, Not(Contains(Key(3))));
-}
-
-TEST(KeyTest, InsideContainsUsingMultimap) {
-  multimap<int, char> container;
-  container.insert(make_pair(1, 'a'));
-  container.insert(make_pair(2, 'b'));
-  container.insert(make_pair(4, 'c'));
-
-  EXPECT_THAT(container, Not(Contains(Key(25))));
-  container.insert(make_pair(25, 'd'));
-  EXPECT_THAT(container, Contains(Key(25)));
-  container.insert(make_pair(25, 'e'));
-  EXPECT_THAT(container, Contains(Key(25)));
-
-  EXPECT_THAT(container, Contains(Key(1)));
-  EXPECT_THAT(container, Not(Contains(Key(3))));
-}
-
-TEST(PairTest, Typing) {
-  // Test verifies the following type conversions can be compiled.
-  Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
-  Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
-  Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
-
-  Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
-  Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
-}
-
-TEST(PairTest, CanDescribeSelf) {
-  Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
-  EXPECT_EQ("has a first field that is equal to \"foo\""
-            ", and has a second field that is equal to 42",
-            Describe(m1));
-  EXPECT_EQ("has a first field that isn't equal to \"foo\""
-            ", or has a second field that isn't equal to 42",
-            DescribeNegation(m1));
-  // Double and triple negation (1 or 2 times not and description of negation).
-  Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
-  EXPECT_EQ("has a first field that isn't equal to 13"
-            ", and has a second field that is equal to 42",
-            DescribeNegation(m2));
-}
-
-TEST(PairTest, CanExplainMatchResultTo) {
-  // If neither field matches, Pair() should explain about the first
-  // field.
-  const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
-  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
-            Explain(m, make_pair(-1, -2)));
-
-  // If the first field matches but the second doesn't, Pair() should
-  // explain about the second field.
-  EXPECT_EQ("whose second field does not match, which is 2 less than 0",
-            Explain(m, make_pair(1, -2)));
-
-  // If the first field doesn't match but the second does, Pair()
-  // should explain about the first field.
-  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
-            Explain(m, make_pair(-1, 2)));
-
-  // If both fields match, Pair() should explain about them both.
-  EXPECT_EQ("whose both fields match, where the first field is a value "
-            "which is 1 more than 0, and the second field is a value "
-            "which is 2 more than 0",
-            Explain(m, make_pair(1, 2)));
-
-  // If only the first match has an explanation, only this explanation should
-  // be printed.
-  const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
-  EXPECT_EQ("whose both fields match, where the first field is a value "
-            "which is 1 more than 0",
-            Explain(explain_first, make_pair(1, 0)));
-
-  // If only the second match has an explanation, only this explanation should
-  // be printed.
-  const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
-  EXPECT_EQ("whose both fields match, where the second field is a value "
-            "which is 1 more than 0",
-            Explain(explain_second, make_pair(0, 1)));
-}
-
-TEST(PairTest, MatchesCorrectly) {
-  pair<int, std::string> p(25, "foo");
-
-  // Both fields match.
-  EXPECT_THAT(p, Pair(25, "foo"));
-  EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
-
-  // 'first' doesnt' match, but 'second' matches.
-  EXPECT_THAT(p, Not(Pair(42, "foo")));
-  EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
-
-  // 'first' matches, but 'second' doesn't match.
-  EXPECT_THAT(p, Not(Pair(25, "bar")));
-  EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
-
-  // Neither field matches.
-  EXPECT_THAT(p, Not(Pair(13, "bar")));
-  EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
-}
-
-TEST(PairTest, SafelyCastsInnerMatchers) {
-  Matcher<int> is_positive = Gt(0);
-  Matcher<int> is_negative = Lt(0);
-  pair<char, bool> p('a', true);
-  EXPECT_THAT(p, Pair(is_positive, _));
-  EXPECT_THAT(p, Not(Pair(is_negative, _)));
-  EXPECT_THAT(p, Pair(_, is_positive));
-  EXPECT_THAT(p, Not(Pair(_, is_negative)));
-}
-
-TEST(PairTest, InsideContainsUsingMap) {
-  map<int, char> container;
-  container.insert(make_pair(1, 'a'));
-  container.insert(make_pair(2, 'b'));
-  container.insert(make_pair(4, 'c'));
-  EXPECT_THAT(container, Contains(Pair(1, 'a')));
-  EXPECT_THAT(container, Contains(Pair(1, _)));
-  EXPECT_THAT(container, Contains(Pair(_, 'a')));
-  EXPECT_THAT(container, Not(Contains(Pair(3, _))));
-}
-
-// Tests StartsWith(s).
-
-TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
-  const Matcher<const char*> m1 = StartsWith(string(""));
-  EXPECT_TRUE(m1.Matches("Hi"));
-  EXPECT_TRUE(m1.Matches(""));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const string&> m2 = StartsWith("Hi");
-  EXPECT_TRUE(m2.Matches("Hi"));
-  EXPECT_TRUE(m2.Matches("Hi Hi!"));
-  EXPECT_TRUE(m2.Matches("High"));
-  EXPECT_FALSE(m2.Matches("H"));
-  EXPECT_FALSE(m2.Matches(" Hi"));
-}
-
-TEST(StartsWithTest, CanDescribeSelf) {
-  Matcher<const std::string> m = StartsWith("Hi");
-  EXPECT_EQ("starts with \"Hi\"", Describe(m));
-}
-
-// Tests EndsWith(s).
-
-TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
-  const Matcher<const char*> m1 = EndsWith("");
-  EXPECT_TRUE(m1.Matches("Hi"));
-  EXPECT_TRUE(m1.Matches(""));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const string&> m2 = EndsWith(string("Hi"));
-  EXPECT_TRUE(m2.Matches("Hi"));
-  EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
-  EXPECT_TRUE(m2.Matches("Super Hi"));
-  EXPECT_FALSE(m2.Matches("i"));
-  EXPECT_FALSE(m2.Matches("Hi "));
-}
-
-TEST(EndsWithTest, CanDescribeSelf) {
-  Matcher<const std::string> m = EndsWith("Hi");
-  EXPECT_EQ("ends with \"Hi\"", Describe(m));
-}
-
-// Tests MatchesRegex().
-
-TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
-  const Matcher<const char*> m1 = MatchesRegex("a.*z");
-  EXPECT_TRUE(m1.Matches("az"));
-  EXPECT_TRUE(m1.Matches("abcz"));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
-  EXPECT_TRUE(m2.Matches("azbz"));
-  EXPECT_FALSE(m2.Matches("az1"));
-  EXPECT_FALSE(m2.Matches("1az"));
-}
-
-TEST(MatchesRegexTest, CanDescribeSelf) {
-  Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
-  EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
-
-  Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
-  EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
-}
-
-// Tests ContainsRegex().
-
-TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
-  const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
-  EXPECT_TRUE(m1.Matches("az"));
-  EXPECT_TRUE(m1.Matches("0abcz1"));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
-  EXPECT_TRUE(m2.Matches("azbz"));
-  EXPECT_TRUE(m2.Matches("az1"));
-  EXPECT_FALSE(m2.Matches("1a"));
-}
-
-TEST(ContainsRegexTest, CanDescribeSelf) {
-  Matcher<const std::string> m1 = ContainsRegex("Hi.*");
-  EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
-
-  Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
-  EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
-}
-
-// Tests for wide strings.
-#if GTEST_HAS_STD_WSTRING
-TEST(StdWideStrEqTest, MatchesEqual) {
-  Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"Hello"));
-  EXPECT_FALSE(m.Matches(L"hello"));
-  EXPECT_FALSE(m.Matches(NULL));
-
-  Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
-  EXPECT_TRUE(m2.Matches(L"Hello"));
-  EXPECT_FALSE(m2.Matches(L"Hi"));
-
-  Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
-  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
-  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
-
-  ::std::wstring str(L"01204500800");
-  str[3] = L'\0';
-  Matcher<const ::std::wstring&> m4 = StrEq(str);
-  EXPECT_TRUE(m4.Matches(str));
-  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
-  Matcher<const ::std::wstring&> m5 = StrEq(str);
-  EXPECT_TRUE(m5.Matches(str));
-}
-
-TEST(StdWideStrEqTest, CanDescribeSelf) {
-  Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
-  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
-    Describe(m));
-
-  Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
-  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
-    Describe(m2));
-
-  ::std::wstring str(L"01204500800");
-  str[3] = L'\0';
-  Matcher<const ::std::wstring&> m4 = StrEq(str);
-  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
-  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
-  Matcher<const ::std::wstring&> m5 = StrEq(str);
-  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
-}
-
-TEST(StdWideStrNeTest, MatchesUnequalString) {
-  Matcher<const wchar_t*> m = StrNe(L"Hello");
-  EXPECT_TRUE(m.Matches(L""));
-  EXPECT_TRUE(m.Matches(NULL));
-  EXPECT_FALSE(m.Matches(L"Hello"));
-
-  Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m2.Matches(L"hello"));
-  EXPECT_FALSE(m2.Matches(L"Hello"));
-}
-
-TEST(StdWideStrNeTest, CanDescribeSelf) {
-  Matcher<const wchar_t*> m = StrNe(L"Hi");
-  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
-}
-
-TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
-  Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"hello"));
-  EXPECT_FALSE(m.Matches(L"Hi"));
-  EXPECT_FALSE(m.Matches(NULL));
-
-  Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
-  EXPECT_TRUE(m2.Matches(L"hello"));
-  EXPECT_FALSE(m2.Matches(L"Hi"));
-}
-
-TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
-  ::std::wstring str1(L"oabocdooeoo");
-  ::std::wstring str2(L"OABOCDOOEOO");
-  Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
-  EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
-
-  str1[3] = str2[3] = L'\0';
-  Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
-  EXPECT_TRUE(m1.Matches(str2));
-
-  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
-  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
-  Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
-  str1[9] = str2[9] = L'\0';
-  EXPECT_FALSE(m2.Matches(str2));
-
-  Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
-  EXPECT_TRUE(m3.Matches(str2));
-
-  EXPECT_FALSE(m3.Matches(str2 + L"x"));
-  str2.append(1, L'\0');
-  EXPECT_FALSE(m3.Matches(str2));
-  EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
-}
-
-TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
-  Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
-  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
-}
-
-TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
-  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
-  EXPECT_TRUE(m.Matches(L"Hi"));
-  EXPECT_TRUE(m.Matches(NULL));
-  EXPECT_FALSE(m.Matches(L"Hello"));
-  EXPECT_FALSE(m.Matches(L"hello"));
-
-  Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m2.Matches(L""));
-  EXPECT_FALSE(m2.Matches(L"Hello"));
-}
-
-TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
-  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
-  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
-}
-
-// Tests that HasSubstr() works for matching wstring-typed values.
-TEST(StdWideHasSubstrTest, WorksForStringClasses) {
-  const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
-  EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
-  EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
-
-  const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
-  EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
-  EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
-}
-
-// Tests that HasSubstr() works for matching C-wide-string-typed values.
-TEST(StdWideHasSubstrTest, WorksForCStrings) {
-  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
-  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
-  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
-  EXPECT_TRUE(m2.Matches(L"I love food."));
-  EXPECT_FALSE(m2.Matches(L"tofo"));
-  EXPECT_FALSE(m2.Matches(NULL));
-}
-
-// Tests that HasSubstr(s) describes itself properly.
-TEST(StdWideHasSubstrTest, CanDescribeSelf) {
-  Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
-  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
-}
-
-// Tests StartsWith(s).
-
-TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
-  const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
-  EXPECT_TRUE(m1.Matches(L"Hi"));
-  EXPECT_TRUE(m1.Matches(L""));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
-  EXPECT_TRUE(m2.Matches(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
-  EXPECT_TRUE(m2.Matches(L"High"));
-  EXPECT_FALSE(m2.Matches(L"H"));
-  EXPECT_FALSE(m2.Matches(L" Hi"));
-}
-
-TEST(StdWideStartsWithTest, CanDescribeSelf) {
-  Matcher<const ::std::wstring> m = StartsWith(L"Hi");
-  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
-}
-
-// Tests EndsWith(s).
-
-TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
-  const Matcher<const wchar_t*> m1 = EndsWith(L"");
-  EXPECT_TRUE(m1.Matches(L"Hi"));
-  EXPECT_TRUE(m1.Matches(L""));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
-  EXPECT_TRUE(m2.Matches(L"Super Hi"));
-  EXPECT_FALSE(m2.Matches(L"i"));
-  EXPECT_FALSE(m2.Matches(L"Hi "));
-}
-
-TEST(StdWideEndsWithTest, CanDescribeSelf) {
-  Matcher<const ::std::wstring> m = EndsWith(L"Hi");
-  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
-}
-
-#endif  // GTEST_HAS_STD_WSTRING
-
-#if GTEST_HAS_GLOBAL_WSTRING
-TEST(GlobalWideStrEqTest, MatchesEqual) {
-  Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"Hello"));
-  EXPECT_FALSE(m.Matches(L"hello"));
-  EXPECT_FALSE(m.Matches(NULL));
-
-  Matcher<const ::wstring&> m2 = StrEq(L"Hello");
-  EXPECT_TRUE(m2.Matches(L"Hello"));
-  EXPECT_FALSE(m2.Matches(L"Hi"));
-
-  Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
-  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
-  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
-
-  ::wstring str(L"01204500800");
-  str[3] = L'\0';
-  Matcher<const ::wstring&> m4 = StrEq(str);
-  EXPECT_TRUE(m4.Matches(str));
-  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
-  Matcher<const ::wstring&> m5 = StrEq(str);
-  EXPECT_TRUE(m5.Matches(str));
-}
-
-TEST(GlobalWideStrEqTest, CanDescribeSelf) {
-  Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
-  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
-    Describe(m));
-
-  Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
-  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
-    Describe(m2));
-
-  ::wstring str(L"01204500800");
-  str[3] = L'\0';
-  Matcher<const ::wstring&> m4 = StrEq(str);
-  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
-  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
-  Matcher<const ::wstring&> m5 = StrEq(str);
-  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
-}
-
-TEST(GlobalWideStrNeTest, MatchesUnequalString) {
-  Matcher<const wchar_t*> m = StrNe(L"Hello");
-  EXPECT_TRUE(m.Matches(L""));
-  EXPECT_TRUE(m.Matches(NULL));
-  EXPECT_FALSE(m.Matches(L"Hello"));
-
-  Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
-  EXPECT_TRUE(m2.Matches(L"hello"));
-  EXPECT_FALSE(m2.Matches(L"Hello"));
-}
-
-TEST(GlobalWideStrNeTest, CanDescribeSelf) {
-  Matcher<const wchar_t*> m = StrNe(L"Hi");
-  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
-}
-
-TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
-  Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"hello"));
-  EXPECT_FALSE(m.Matches(L"Hi"));
-  EXPECT_FALSE(m.Matches(NULL));
-
-  Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
-  EXPECT_TRUE(m2.Matches(L"hello"));
-  EXPECT_FALSE(m2.Matches(L"Hi"));
-}
-
-TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
-  ::wstring str1(L"oabocdooeoo");
-  ::wstring str2(L"OABOCDOOEOO");
-  Matcher<const ::wstring&> m0 = StrCaseEq(str1);
-  EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
-
-  str1[3] = str2[3] = L'\0';
-  Matcher<const ::wstring&> m1 = StrCaseEq(str1);
-  EXPECT_TRUE(m1.Matches(str2));
-
-  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
-  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
-  Matcher<const ::wstring&> m2 = StrCaseEq(str1);
-  str1[9] = str2[9] = L'\0';
-  EXPECT_FALSE(m2.Matches(str2));
-
-  Matcher<const ::wstring&> m3 = StrCaseEq(str1);
-  EXPECT_TRUE(m3.Matches(str2));
-
-  EXPECT_FALSE(m3.Matches(str2 + L"x"));
-  str2.append(1, L'\0');
-  EXPECT_FALSE(m3.Matches(str2));
-  EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
-}
-
-TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
-  Matcher< ::wstring> m = StrCaseEq(L"Hi");
-  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
-}
-
-TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
-  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
-  EXPECT_TRUE(m.Matches(L"Hi"));
-  EXPECT_TRUE(m.Matches(NULL));
-  EXPECT_FALSE(m.Matches(L"Hello"));
-  EXPECT_FALSE(m.Matches(L"hello"));
-
-  Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
-  EXPECT_TRUE(m2.Matches(L""));
-  EXPECT_FALSE(m2.Matches(L"Hello"));
-}
-
-TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
-  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
-  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
-}
-
-// Tests that HasSubstr() works for matching wstring-typed values.
-TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
-  const Matcher< ::wstring> m1 = HasSubstr(L"foo");
-  EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
-  EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
-
-  const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
-  EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
-  EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
-}
-
-// Tests that HasSubstr() works for matching C-wide-string-typed values.
-TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
-  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
-  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
-  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
-  EXPECT_TRUE(m2.Matches(L"I love food."));
-  EXPECT_FALSE(m2.Matches(L"tofo"));
-  EXPECT_FALSE(m2.Matches(NULL));
-}
-
-// Tests that HasSubstr(s) describes itself properly.
-TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
-  Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
-  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
-}
-
-// Tests StartsWith(s).
-
-TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
-  const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
-  EXPECT_TRUE(m1.Matches(L"Hi"));
-  EXPECT_TRUE(m1.Matches(L""));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
-  EXPECT_TRUE(m2.Matches(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
-  EXPECT_TRUE(m2.Matches(L"High"));
-  EXPECT_FALSE(m2.Matches(L"H"));
-  EXPECT_FALSE(m2.Matches(L" Hi"));
-}
-
-TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
-  Matcher<const ::wstring> m = StartsWith(L"Hi");
-  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
-}
-
-// Tests EndsWith(s).
-
-TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
-  const Matcher<const wchar_t*> m1 = EndsWith(L"");
-  EXPECT_TRUE(m1.Matches(L"Hi"));
-  EXPECT_TRUE(m1.Matches(L""));
-  EXPECT_FALSE(m1.Matches(NULL));
-
-  const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
-  EXPECT_TRUE(m2.Matches(L"Super Hi"));
-  EXPECT_FALSE(m2.Matches(L"i"));
-  EXPECT_FALSE(m2.Matches(L"Hi "));
-}
-
-TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
-  Matcher<const ::wstring> m = EndsWith(L"Hi");
-  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
-}
-
-#endif  // GTEST_HAS_GLOBAL_WSTRING
-
-
-typedef ::testing::tuple<long, int> Tuple2;  // NOLINT
-
-// Tests that Eq() matches a 2-tuple where the first field == the
-// second field.
-TEST(Eq2Test, MatchesEqualArguments) {
-  Matcher<const Tuple2&> m = Eq();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
-}
-
-// Tests that Eq() describes itself properly.
-TEST(Eq2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Eq();
-  EXPECT_EQ("are an equal pair", Describe(m));
-}
-
-// Tests that Ge() matches a 2-tuple where the first field >= the
-// second field.
-TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
-  Matcher<const Tuple2&> m = Ge();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
-}
-
-// Tests that Ge() describes itself properly.
-TEST(Ge2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Ge();
-  EXPECT_EQ("are a pair where the first >= the second", Describe(m));
-}
-
-// Tests that Gt() matches a 2-tuple where the first field > the
-// second field.
-TEST(Gt2Test, MatchesGreaterThanArguments) {
-  Matcher<const Tuple2&> m = Gt();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
-}
-
-// Tests that Gt() describes itself properly.
-TEST(Gt2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Gt();
-  EXPECT_EQ("are a pair where the first > the second", Describe(m));
-}
-
-// Tests that Le() matches a 2-tuple where the first field <= the
-// second field.
-TEST(Le2Test, MatchesLessThanOrEqualArguments) {
-  Matcher<const Tuple2&> m = Le();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
-}
-
-// Tests that Le() describes itself properly.
-TEST(Le2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Le();
-  EXPECT_EQ("are a pair where the first <= the second", Describe(m));
-}
-
-// Tests that Lt() matches a 2-tuple where the first field < the
-// second field.
-TEST(Lt2Test, MatchesLessThanArguments) {
-  Matcher<const Tuple2&> m = Lt();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
-}
-
-// Tests that Lt() describes itself properly.
-TEST(Lt2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Lt();
-  EXPECT_EQ("are a pair where the first < the second", Describe(m));
-}
-
-// Tests that Ne() matches a 2-tuple where the first field != the
-// second field.
-TEST(Ne2Test, MatchesUnequalArguments) {
-  Matcher<const Tuple2&> m = Ne();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
-}
-
-// Tests that Ne() describes itself properly.
-TEST(Ne2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Ne();
-  EXPECT_EQ("are an unequal pair", Describe(m));
-}
-
-// Tests that Not(m) matches any value that doesn't match m.
-TEST(NotTest, NegatesMatcher) {
-  Matcher<int> m;
-  m = Not(Eq(2));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-}
-
-// Tests that Not(m) describes itself properly.
-TEST(NotTest, CanDescribeSelf) {
-  Matcher<int> m = Not(Eq(5));
-  EXPECT_EQ("isn't equal to 5", Describe(m));
-}
-
-// Tests that monomorphic matchers are safely cast by the Not matcher.
-TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
-  // greater_than_5 is a monomorphic matcher.
-  Matcher<int> greater_than_5 = Gt(5);
-
-  Matcher<const int&> m = Not(greater_than_5);
-  Matcher<int&> m2 = Not(greater_than_5);
-  Matcher<int&> m3 = Not(m);
-}
-
-// Helper to allow easy testing of AllOf matchers with num parameters.
-void AllOfMatches(int num, const Matcher<int>& m) {
-  SCOPED_TRACE(Describe(m));
-  EXPECT_TRUE(m.Matches(0));
-  for (int i = 1; i <= num; ++i) {
-    EXPECT_FALSE(m.Matches(i));
-  }
-  EXPECT_TRUE(m.Matches(num + 1));
-}
-
-// Tests that AllOf(m1, ..., mn) matches any value that matches all of
-// the given matchers.
-TEST(AllOfTest, MatchesWhenAllMatch) {
-  Matcher<int> m;
-  m = AllOf(Le(2), Ge(1));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(0));
-  EXPECT_FALSE(m.Matches(3));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
-  EXPECT_TRUE(m.Matches(4));
-  EXPECT_FALSE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
-  EXPECT_TRUE(m.Matches(0));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(3));
-
-  // The following tests for varying number of sub-matchers. Due to the way
-  // the sub-matchers are handled it is enough to test every sub-matcher once
-  // with sub-matchers using the same matcher type. Varying matcher types are
-  // checked for above.
-  AllOfMatches(2, AllOf(Ne(1), Ne(2)));
-  AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
-  AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
-  AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
-  AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
-  AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
-  AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
-                        Ne(8)));
-  AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
-                        Ne(8), Ne(9)));
-  AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
-                         Ne(9), Ne(10)));
-}
-
-#if GTEST_LANG_CXX11
-// Tests the variadic version of the AllOfMatcher.
-TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
-  // Make sure AllOf is defined in the right namespace and does not depend on
-  // ADL.
-  ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
-  Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
-                         Ne(9), Ne(10), Ne(11));
-  EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
-  AllOfMatches(11, m);
-  AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
-                         Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
-                         Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
-                         Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
-                         Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
-                         Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
-                         Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
-                         Ne(50)));
-}
-
-#endif  // GTEST_LANG_CXX11
-
-// Tests that AllOf(m1, ..., mn) describes itself properly.
-TEST(AllOfTest, CanDescribeSelf) {
-  Matcher<int> m;
-  m = AllOf(Le(2), Ge(1));
-  EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2));
-  EXPECT_EQ("(is > 0) and "
-            "((isn't equal to 1) and "
-            "(isn't equal to 2))",
-            Describe(m));
-
-
-  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
-  EXPECT_EQ("((is > 0) and "
-            "(isn't equal to 1)) and "
-            "((isn't equal to 2) and "
-            "(isn't equal to 3))",
-            Describe(m));
-
-
-  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
-  EXPECT_EQ("((is >= 0) and "
-            "(is < 10)) and "
-            "((isn't equal to 3) and "
-            "((isn't equal to 5) and "
-            "(isn't equal to 7)))",
-            Describe(m));
-}
-
-// Tests that AllOf(m1, ..., mn) describes its negation properly.
-TEST(AllOfTest, CanDescribeNegation) {
-  Matcher<int> m;
-  m = AllOf(Le(2), Ge(1));
-  EXPECT_EQ("(isn't <= 2) or "
-            "(isn't >= 1)",
-            DescribeNegation(m));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2));
-  EXPECT_EQ("(isn't > 0) or "
-            "((is equal to 1) or "
-            "(is equal to 2))",
-            DescribeNegation(m));
-
-
-  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
-  EXPECT_EQ("((isn't > 0) or "
-            "(is equal to 1)) or "
-            "((is equal to 2) or "
-            "(is equal to 3))",
-            DescribeNegation(m));
-
-
-  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
-  EXPECT_EQ("((isn't >= 0) or "
-            "(isn't < 10)) or "
-            "((is equal to 3) or "
-            "((is equal to 5) or "
-            "(is equal to 7)))",
-            DescribeNegation(m));
-}
-
-// Tests that monomorphic matchers are safely cast by the AllOf matcher.
-TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
-  // greater_than_5 and less_than_10 are monomorphic matchers.
-  Matcher<int> greater_than_5 = Gt(5);
-  Matcher<int> less_than_10 = Lt(10);
-
-  Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
-  Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
-  Matcher<int&> m3 = AllOf(greater_than_5, m2);
-
-  // Tests that BothOf works when composing itself.
-  Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
-  Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
-}
-
-TEST(AllOfTest, ExplainsResult) {
-  Matcher<int> m;
-
-  // Successful match.  Both matchers need to explain.  The second
-  // matcher doesn't give an explanation, so only the first matcher's
-  // explanation is printed.
-  m = AllOf(GreaterThan(10), Lt(30));
-  EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
-
-  // Successful match.  Both matchers need to explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
-            Explain(m, 30));
-
-  // Successful match.  All matchers need to explain.  The second
-  // matcher doesn't given an explanation.
-  m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
-  EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
-            Explain(m, 25));
-
-  // Successful match.  All matchers need to explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
-  EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
-            "and which is 10 more than 30",
-            Explain(m, 40));
-
-  // Failed match.  The first matcher, which failed, needs to
-  // explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
-
-  // Failed match.  The second matcher, which failed, needs to
-  // explain.  Since it doesn't given an explanation, nothing is
-  // printed.
-  m = AllOf(GreaterThan(10), Lt(30));
-  EXPECT_EQ("", Explain(m, 40));
-
-  // Failed match.  The second matcher, which failed, needs to
-  // explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
-}
-
-// Helper to allow easy testing of AnyOf matchers with num parameters.
-void AnyOfMatches(int num, const Matcher<int>& m) {
-  SCOPED_TRACE(Describe(m));
-  EXPECT_FALSE(m.Matches(0));
-  for (int i = 1; i <= num; ++i) {
-    EXPECT_TRUE(m.Matches(i));
-  }
-  EXPECT_FALSE(m.Matches(num + 1));
-}
-
-// Tests that AnyOf(m1, ..., mn) matches any value that matches at
-// least one of the given matchers.
-TEST(AnyOfTest, MatchesWhenAnyMatches) {
-  Matcher<int> m;
-  m = AnyOf(Le(1), Ge(3));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(4));
-  EXPECT_FALSE(m.Matches(2));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2));
-  EXPECT_TRUE(m.Matches(-1));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
-  EXPECT_TRUE(m.Matches(-1));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
-  EXPECT_TRUE(m.Matches(0));
-  EXPECT_TRUE(m.Matches(11));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-
-  // The following tests for varying number of sub-matchers. Due to the way
-  // the sub-matchers are handled it is enough to test every sub-matcher once
-  // with sub-matchers using the same matcher type. Varying matcher types are
-  // checked for above.
-  AnyOfMatches(2, AnyOf(1, 2));
-  AnyOfMatches(3, AnyOf(1, 2, 3));
-  AnyOfMatches(4, AnyOf(1, 2, 3, 4));
-  AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
-  AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
-  AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
-  AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
-  AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
-  AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
-}
-
-#if GTEST_LANG_CXX11
-// Tests the variadic version of the AnyOfMatcher.
-TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
-  // Also make sure AnyOf is defined in the right namespace and does not depend
-  // on ADL.
-  Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
-
-  EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
-  AnyOfMatches(11, m);
-  AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
-                         11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
-                         21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
-                         31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
-                         41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
-}
-
-#endif  // GTEST_LANG_CXX11
-
-// Tests that AnyOf(m1, ..., mn) describes itself properly.
-TEST(AnyOfTest, CanDescribeSelf) {
-  Matcher<int> m;
-  m = AnyOf(Le(1), Ge(3));
-  EXPECT_EQ("(is <= 1) or (is >= 3)",
-            Describe(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2));
-  EXPECT_EQ("(is < 0) or "
-            "((is equal to 1) or (is equal to 2))",
-            Describe(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
-  EXPECT_EQ("((is < 0) or "
-            "(is equal to 1)) or "
-            "((is equal to 2) or "
-            "(is equal to 3))",
-            Describe(m));
-
-  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
-  EXPECT_EQ("((is <= 0) or "
-            "(is > 10)) or "
-            "((is equal to 3) or "
-            "((is equal to 5) or "
-            "(is equal to 7)))",
-            Describe(m));
-}
-
-// Tests that AnyOf(m1, ..., mn) describes its negation properly.
-TEST(AnyOfTest, CanDescribeNegation) {
-  Matcher<int> m;
-  m = AnyOf(Le(1), Ge(3));
-  EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
-            DescribeNegation(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2));
-  EXPECT_EQ("(isn't < 0) and "
-            "((isn't equal to 1) and (isn't equal to 2))",
-            DescribeNegation(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
-  EXPECT_EQ("((isn't < 0) and "
-            "(isn't equal to 1)) and "
-            "((isn't equal to 2) and "
-            "(isn't equal to 3))",
-            DescribeNegation(m));
-
-  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
-  EXPECT_EQ("((isn't <= 0) and "
-            "(isn't > 10)) and "
-            "((isn't equal to 3) and "
-            "((isn't equal to 5) and "
-            "(isn't equal to 7)))",
-            DescribeNegation(m));
-}
-
-// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
-TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
-  // greater_than_5 and less_than_10 are monomorphic matchers.
-  Matcher<int> greater_than_5 = Gt(5);
-  Matcher<int> less_than_10 = Lt(10);
-
-  Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
-  Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
-  Matcher<int&> m3 = AnyOf(greater_than_5, m2);
-
-  // Tests that EitherOf works when composing itself.
-  Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
-  Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
-}
-
-TEST(AnyOfTest, ExplainsResult) {
-  Matcher<int> m;
-
-  // Failed match.  Both matchers need to explain.  The second
-  // matcher doesn't give an explanation, so only the first matcher's
-  // explanation is printed.
-  m = AnyOf(GreaterThan(10), Lt(0));
-  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
-
-  // Failed match.  Both matchers need to explain.
-  m = AnyOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
-            Explain(m, 5));
-
-  // Failed match.  All matchers need to explain.  The second
-  // matcher doesn't given an explanation.
-  m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
-  EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
-            Explain(m, 5));
-
-  // Failed match.  All matchers need to explain.
-  m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
-  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
-            "and which is 25 less than 30",
-            Explain(m, 5));
-
-  // Successful match.  The first matcher, which succeeded, needs to
-  // explain.
-  m = AnyOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
-
-  // Successful match.  The second matcher, which succeeded, needs to
-  // explain.  Since it doesn't given an explanation, nothing is
-  // printed.
-  m = AnyOf(GreaterThan(10), Lt(30));
-  EXPECT_EQ("", Explain(m, 0));
-
-  // Successful match.  The second matcher, which succeeded, needs to
-  // explain.
-  m = AnyOf(GreaterThan(30), GreaterThan(20));
-  EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
-}
-
-// The following predicate function and predicate functor are for
-// testing the Truly(predicate) matcher.
-
-// Returns non-zero if the input is positive.  Note that the return
-// type of this function is not bool.  It's OK as Truly() accepts any
-// unary function or functor whose return type can be implicitly
-// converted to bool.
-int IsPositive(double x) {
-  return x > 0 ? 1 : 0;
-}
-
-// This functor returns true if the input is greater than the given
-// number.
-class IsGreaterThan {
- public:
-  explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
-
-  bool operator()(int n) const { return n > threshold_; }
-
- private:
-  int threshold_;
-};
-
-// For testing Truly().
-const int foo = 0;
-
-// This predicate returns true iff the argument references foo and has
-// a zero value.
-bool ReferencesFooAndIsZero(const int& n) {
-  return (&n == &foo) && (n == 0);
-}
-
-// Tests that Truly(predicate) matches what satisfies the given
-// predicate.
-TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
-  Matcher<double> m = Truly(IsPositive);
-  EXPECT_TRUE(m.Matches(2.0));
-  EXPECT_FALSE(m.Matches(-1.5));
-}
-
-// Tests that Truly(predicate_functor) works too.
-TEST(TrulyTest, CanBeUsedWithFunctor) {
-  Matcher<int> m = Truly(IsGreaterThan(5));
-  EXPECT_TRUE(m.Matches(6));
-  EXPECT_FALSE(m.Matches(4));
-}
-
-// A class that can be implicitly converted to bool.
-class ConvertibleToBool {
- public:
-  explicit ConvertibleToBool(int number) : number_(number) {}
-  operator bool() const { return number_ != 0; }
-
- private:
-  int number_;
-};
-
-ConvertibleToBool IsNotZero(int number) {
-  return ConvertibleToBool(number);
-}
-
-// Tests that the predicate used in Truly() may return a class that's
-// implicitly convertible to bool, even when the class has no
-// operator!().
-TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
-  Matcher<int> m = Truly(IsNotZero);
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(0));
-}
-
-// Tests that Truly(predicate) can describe itself properly.
-TEST(TrulyTest, CanDescribeSelf) {
-  Matcher<double> m = Truly(IsPositive);
-  EXPECT_EQ("satisfies the given predicate",
-            Describe(m));
-}
-
-// Tests that Truly(predicate) works when the matcher takes its
-// argument by reference.
-TEST(TrulyTest, WorksForByRefArguments) {
-  Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
-  EXPECT_TRUE(m.Matches(foo));
-  int n = 0;
-  EXPECT_FALSE(m.Matches(n));
-}
-
-// Tests that Matches(m) is a predicate satisfied by whatever that
-// matches matcher m.
-TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
-  EXPECT_TRUE(Matches(Ge(0))(1));
-  EXPECT_FALSE(Matches(Eq('a'))('b'));
-}
-
-// Tests that Matches(m) works when the matcher takes its argument by
-// reference.
-TEST(MatchesTest, WorksOnByRefArguments) {
-  int m = 0, n = 0;
-  EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
-  EXPECT_FALSE(Matches(Ref(m))(n));
-}
-
-// Tests that a Matcher on non-reference type can be used in
-// Matches().
-TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
-  Matcher<int> eq5 = Eq(5);
-  EXPECT_TRUE(Matches(eq5)(5));
-  EXPECT_FALSE(Matches(eq5)(2));
-}
-
-// Tests Value(value, matcher).  Since Value() is a simple wrapper for
-// Matches(), which has been tested already, we don't spend a lot of
-// effort on testing Value().
-TEST(ValueTest, WorksWithPolymorphicMatcher) {
-  EXPECT_TRUE(Value("hi", StartsWith("h")));
-  EXPECT_FALSE(Value(5, Gt(10)));
-}
-
-TEST(ValueTest, WorksWithMonomorphicMatcher) {
-  const Matcher<int> is_zero = Eq(0);
-  EXPECT_TRUE(Value(0, is_zero));
-  EXPECT_FALSE(Value('a', is_zero));
-
-  int n = 0;
-  const Matcher<const int&> ref_n = Ref(n);
-  EXPECT_TRUE(Value(n, ref_n));
-  EXPECT_FALSE(Value(1, ref_n));
-}
-
-TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
-  StringMatchResultListener listener1;
-  EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
-  EXPECT_EQ("% 2 == 0", listener1.str());
-
-  StringMatchResultListener listener2;
-  EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
-  EXPECT_EQ("", listener2.str());
-}
-
-TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
-  const Matcher<int> is_even = PolymorphicIsEven();
-  StringMatchResultListener listener1;
-  EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
-  EXPECT_EQ("% 2 == 0", listener1.str());
-
-  const Matcher<const double&> is_zero = Eq(0);
-  StringMatchResultListener listener2;
-  EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
-  EXPECT_EQ("", listener2.str());
-}
-
-MATCHER_P(Really, inner_matcher, "") {
-  return ExplainMatchResult(inner_matcher, arg, result_listener);
-}
-
-TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
-  EXPECT_THAT(0, Really(Eq(0)));
-}
-
-TEST(AllArgsTest, WorksForTuple) {
-  EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
-  EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
-}
-
-TEST(AllArgsTest, WorksForNonTuple) {
-  EXPECT_THAT(42, AllArgs(Gt(0)));
-  EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
-}
-
-class AllArgsHelper {
- public:
-  AllArgsHelper() {}
-
-  MOCK_METHOD2(Helper, int(char x, int y));
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
-};
-
-TEST(AllArgsTest, WorksInWithClause) {
-  AllArgsHelper helper;
-  ON_CALL(helper, Helper(_, _))
-      .With(AllArgs(Lt()))
-      .WillByDefault(Return(1));
-  EXPECT_CALL(helper, Helper(_, _));
-  EXPECT_CALL(helper, Helper(_, _))
-      .With(AllArgs(Gt()))
-      .WillOnce(Return(2));
-
-  EXPECT_EQ(1, helper.Helper('\1', 2));
-  EXPECT_EQ(2, helper.Helper('a', 1));
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
-// matches the matcher.
-TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
-  ASSERT_THAT(5, Ge(2)) << "This should succeed.";
-  ASSERT_THAT("Foo", EndsWith("oo"));
-  EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
-  EXPECT_THAT("Hello", StartsWith("Hell"));
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
-// doesn't match the matcher.
-TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
-  // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
-  // which cannot reference auto variables.
-  static unsigned short n;  // NOLINT
-  n = 5;
-
-  // VC++ prior to version 8.0 SP1 has a bug where it will not see any
-  // functions declared in the namespace scope from within nested classes.
-  // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
-  // namespace-level functions invoked inside them need to be explicitly
-  // resolved.
-  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
-                       "Value of: n\n"
-                       "Expected: is > 10\n"
-                       "  Actual: 5" + OfType("unsigned short"));
-  n = 0;
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
-      "Value of: n\n"
-      "Expected: (is <= 7) and (is >= 5)\n"
-      "  Actual: 0" + OfType("unsigned short"));
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
-// has a reference type.
-TEST(MatcherAssertionTest, WorksForByRefArguments) {
-  // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
-  // reference auto variables.
-  static int n;
-  n = 0;
-  EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
-  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
-                       "Value of: n\n"
-                       "Expected: does not reference the variable @");
-  // Tests the "Actual" part.
-  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
-                       "Actual: 0" + OfType("int") + ", which is located @");
-}
-
-#if !GTEST_OS_SYMBIAN
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
-// monomorphic.
-
-// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
-// Symbian compiler: it tries to compile
-// template<T, U> class MatcherCastImpl { ...
-//   virtual bool MatchAndExplain(T x, ...) const {
-//     return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
-// with U == string and T == const char*
-// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
-// the compiler silently crashes with no output.
-// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
-// the code compiles but the converted string is bogus.
-TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
-  Matcher<const char*> starts_with_he = StartsWith("he");
-  ASSERT_THAT("hello", starts_with_he);
-
-  Matcher<const string&> ends_with_ok = EndsWith("ok");
-  ASSERT_THAT("book", ends_with_ok);
-  const string bad = "bad";
-  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
-                          "Value of: bad\n"
-                          "Expected: ends with \"ok\"\n"
-                          "  Actual: \"bad\"");
-  Matcher<int> is_greater_than_5 = Gt(5);
-  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
-                          "Value of: 5\n"
-                          "Expected: is > 5\n"
-                          "  Actual: 5" + OfType("int"));
-}
-#endif  // !GTEST_OS_SYMBIAN
-
-// Tests floating-point matchers.
-template <typename RawType>
-class FloatingPointTest : public testing::Test {
- protected:
-  typedef testing::internal::FloatingPoint<RawType> Floating;
-  typedef typename Floating::Bits Bits;
-
-  FloatingPointTest()
-      : max_ulps_(Floating::kMaxUlps),
-        zero_bits_(Floating(0).bits()),
-        one_bits_(Floating(1).bits()),
-        infinity_bits_(Floating(Floating::Infinity()).bits()),
-        close_to_positive_zero_(
-            Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
-        close_to_negative_zero_(
-            -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
-        further_from_negative_zero_(-Floating::ReinterpretBits(
-            zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
-        close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
-        further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
-        infinity_(Floating::Infinity()),
-        close_to_infinity_(
-            Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
-        further_from_infinity_(
-            Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
-        max_(Floating::Max()),
-        nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
-        nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
-  }
-
-  void TestSize() {
-    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
-  }
-
-  // A battery of tests for FloatingEqMatcher::Matches.
-  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
-  void TestMatches(
-      testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
-    Matcher<RawType> m1 = matcher_maker(0.0);
-    EXPECT_TRUE(m1.Matches(-0.0));
-    EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
-    EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
-    EXPECT_FALSE(m1.Matches(1.0));
-
-    Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
-    EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
-
-    Matcher<RawType> m3 = matcher_maker(1.0);
-    EXPECT_TRUE(m3.Matches(close_to_one_));
-    EXPECT_FALSE(m3.Matches(further_from_one_));
-
-    // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
-    EXPECT_FALSE(m3.Matches(0.0));
-
-    Matcher<RawType> m4 = matcher_maker(-infinity_);
-    EXPECT_TRUE(m4.Matches(-close_to_infinity_));
-
-    Matcher<RawType> m5 = matcher_maker(infinity_);
-    EXPECT_TRUE(m5.Matches(close_to_infinity_));
-
-    // This is interesting as the representations of infinity_ and nan1_
-    // are only 1 DLP apart.
-    EXPECT_FALSE(m5.Matches(nan1_));
-
-    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
-    // some cases.
-    Matcher<const RawType&> m6 = matcher_maker(0.0);
-    EXPECT_TRUE(m6.Matches(-0.0));
-    EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
-    EXPECT_FALSE(m6.Matches(1.0));
-
-    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
-    // cases.
-    Matcher<RawType&> m7 = matcher_maker(0.0);
-    RawType x = 0.0;
-    EXPECT_TRUE(m7.Matches(x));
-    x = 0.01f;
-    EXPECT_FALSE(m7.Matches(x));
-  }
-
-  // Pre-calculated numbers to be used by the tests.
-
-  const size_t max_ulps_;
-
-  const Bits zero_bits_;  // The bits that represent 0.0.
-  const Bits one_bits_;  // The bits that represent 1.0.
-  const Bits infinity_bits_;  // The bits that represent +infinity.
-
-  // Some numbers close to 0.0.
-  const RawType close_to_positive_zero_;
-  const RawType close_to_negative_zero_;
-  const RawType further_from_negative_zero_;
-
-  // Some numbers close to 1.0.
-  const RawType close_to_one_;
-  const RawType further_from_one_;
-
-  // Some numbers close to +infinity.
-  const RawType infinity_;
-  const RawType close_to_infinity_;
-  const RawType further_from_infinity_;
-
-  // Maximum representable value that's not infinity.
-  const RawType max_;
-
-  // Some NaNs.
-  const RawType nan1_;
-  const RawType nan2_;
-};
-
-// Tests floating-point matchers with fixed epsilons.
-template <typename RawType>
-class FloatingPointNearTest : public FloatingPointTest<RawType> {
- protected:
-  typedef FloatingPointTest<RawType> ParentType;
-
-  // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
-  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
-  void TestNearMatches(
-      testing::internal::FloatingEqMatcher<RawType>
-          (*matcher_maker)(RawType, RawType)) {
-    Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
-    EXPECT_TRUE(m1.Matches(0.0));
-    EXPECT_TRUE(m1.Matches(-0.0));
-    EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
-    EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
-    EXPECT_FALSE(m1.Matches(1.0));
-
-    Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
-    EXPECT_TRUE(m2.Matches(0.0));
-    EXPECT_TRUE(m2.Matches(-0.0));
-    EXPECT_TRUE(m2.Matches(1.0));
-    EXPECT_TRUE(m2.Matches(-1.0));
-    EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
-    EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
-
-    // Check that inf matches inf, regardless of the of the specified max
-    // absolute error.
-    Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
-    EXPECT_TRUE(m3.Matches(ParentType::infinity_));
-    EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
-    EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
-
-    Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
-    EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
-    EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
-    EXPECT_FALSE(m4.Matches(ParentType::infinity_));
-
-    // Test various overflow scenarios.
-    Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
-    EXPECT_TRUE(m5.Matches(ParentType::max_));
-    EXPECT_FALSE(m5.Matches(-ParentType::max_));
-
-    Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
-    EXPECT_FALSE(m6.Matches(ParentType::max_));
-    EXPECT_TRUE(m6.Matches(-ParentType::max_));
-
-    Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
-    EXPECT_TRUE(m7.Matches(ParentType::max_));
-    EXPECT_FALSE(m7.Matches(-ParentType::max_));
-
-    Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
-    EXPECT_FALSE(m8.Matches(ParentType::max_));
-    EXPECT_TRUE(m8.Matches(-ParentType::max_));
-
-    // The difference between max() and -max() normally overflows to infinity,
-    // but it should still match if the max_abs_error is also infinity.
-    Matcher<RawType> m9 = matcher_maker(
-        ParentType::max_, ParentType::infinity_);
-    EXPECT_TRUE(m8.Matches(-ParentType::max_));
-
-    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
-    // some cases.
-    Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
-    EXPECT_TRUE(m10.Matches(-0.0));
-    EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
-    EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
-
-    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
-    // cases.
-    Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
-    RawType x = 0.0;
-    EXPECT_TRUE(m11.Matches(x));
-    x = 1.0f;
-    EXPECT_TRUE(m11.Matches(x));
-    x = -1.0f;
-    EXPECT_TRUE(m11.Matches(x));
-    x = 1.1f;
-    EXPECT_FALSE(m11.Matches(x));
-    x = -1.1f;
-    EXPECT_FALSE(m11.Matches(x));
-  }
-};
-
-// Instantiate FloatingPointTest for testing floats.
-typedef FloatingPointTest<float> FloatTest;
-
-TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
-  TestMatches(&FloatEq);
-}
-
-TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
-  TestMatches(&NanSensitiveFloatEq);
-}
-
-TEST_F(FloatTest, FloatEqCannotMatchNaN) {
-  // FloatEq never matches NaN.
-  Matcher<float> m = FloatEq(nan1_);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
-  // NanSensitiveFloatEq will match NaN.
-  Matcher<float> m = NanSensitiveFloatEq(nan1_);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(FloatTest, FloatEqCanDescribeSelf) {
-  Matcher<float> m1 = FloatEq(2.0f);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<float> m2 = FloatEq(0.5f);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<float> m3 = FloatEq(nan1_);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
-  Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-// Instantiate FloatingPointTest for testing floats with a user-specified
-// max absolute error.
-typedef FloatingPointNearTest<float> FloatNearTest;
-
-TEST_F(FloatNearTest, FloatNearMatches) {
-  TestNearMatches(&FloatNear);
-}
-
-TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
-  TestNearMatches(&NanSensitiveFloatNear);
-}
-
-TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
-  Matcher<float> m1 = FloatNear(2.0f, 0.5f);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<float> m2 = FloatNear(0.5f, 0.5f);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<float> m3 = FloatNear(nan1_, 0.0);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
-  Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
-  // FloatNear never matches NaN.
-  Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
-  // NanSensitiveFloatNear will match NaN.
-  Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-// Instantiate FloatingPointTest for testing doubles.
-typedef FloatingPointTest<double> DoubleTest;
-
-TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
-  TestMatches(&DoubleEq);
-}
-
-TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
-  TestMatches(&NanSensitiveDoubleEq);
-}
-
-TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
-  // DoubleEq never matches NaN.
-  Matcher<double> m = DoubleEq(nan1_);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
-  // NanSensitiveDoubleEq will match NaN.
-  Matcher<double> m = NanSensitiveDoubleEq(nan1_);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
-  Matcher<double> m1 = DoubleEq(2.0);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<double> m2 = DoubleEq(0.5);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<double> m3 = DoubleEq(nan1_);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
-  Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-// Instantiate FloatingPointTest for testing floats with a user-specified
-// max absolute error.
-typedef FloatingPointNearTest<double> DoubleNearTest;
-
-TEST_F(DoubleNearTest, DoubleNearMatches) {
-  TestNearMatches(&DoubleNear);
-}
-
-TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
-  TestNearMatches(&NanSensitiveDoubleNear);
-}
-
-TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
-  Matcher<double> m1 = DoubleNear(2.0, 0.5);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<double> m2 = DoubleNear(0.5, 0.5);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<double> m3 = DoubleNear(nan1_, 0.0);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
-  EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
-  EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
-  EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
-
-  const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
-  // Different C++ implementations may print floating-point numbers
-  // slightly differently.
-  EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
-              explanation == "which is 1.2e-010 from 2.1")   // MSVC
-      << " where explanation is \"" << explanation << "\".";
-}
-
-TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
-  Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
-  // DoubleNear never matches NaN.
-  Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
-  // NanSensitiveDoubleNear will match NaN.
-  Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST(PointeeTest, RawPointer) {
-  const Matcher<int*> m = Pointee(Ge(0));
-
-  int n = 1;
-  EXPECT_TRUE(m.Matches(&n));
-  n = -1;
-  EXPECT_FALSE(m.Matches(&n));
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-TEST(PointeeTest, RawPointerToConst) {
-  const Matcher<const double*> m = Pointee(Ge(0));
-
-  double x = 1;
-  EXPECT_TRUE(m.Matches(&x));
-  x = -1;
-  EXPECT_FALSE(m.Matches(&x));
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-TEST(PointeeTest, ReferenceToConstRawPointer) {
-  const Matcher<int* const &> m = Pointee(Ge(0));
-
-  int n = 1;
-  EXPECT_TRUE(m.Matches(&n));
-  n = -1;
-  EXPECT_FALSE(m.Matches(&n));
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-TEST(PointeeTest, ReferenceToNonConstRawPointer) {
-  const Matcher<double* &> m = Pointee(Ge(0));
-
-  double x = 1.0;
-  double* p = &x;
-  EXPECT_TRUE(m.Matches(p));
-  x = -1;
-  EXPECT_FALSE(m.Matches(p));
-  p = NULL;
-  EXPECT_FALSE(m.Matches(p));
-}
-
-MATCHER_P(FieldIIs, inner_matcher, "") {
-  return ExplainMatchResult(inner_matcher, arg.i, result_listener);
-}
-
-TEST(WhenDynamicCastToTest, SameType) {
-  Derived derived;
-  derived.i = 4;
-
-  // Right type. A pointer is passed down.
-  Base* as_base_ptr = &derived;
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
-  EXPECT_THAT(as_base_ptr,
-              Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
-}
-
-TEST(WhenDynamicCastToTest, WrongTypes) {
-  Base base;
-  Derived derived;
-  OtherDerived other_derived;
-
-  // Wrong types. NULL is passed.
-  EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
-  EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
-  Base* as_base_ptr = &derived;
-  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
-  as_base_ptr = &other_derived;
-  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
-}
-
-TEST(WhenDynamicCastToTest, AlreadyNull) {
-  // Already NULL.
-  Base* as_base_ptr = NULL;
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
-}
-
-struct AmbiguousCastTypes {
-  class VirtualDerived : public virtual Base {};
-  class DerivedSub1 : public VirtualDerived {};
-  class DerivedSub2 : public VirtualDerived {};
-  class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
-};
-
-TEST(WhenDynamicCastToTest, AmbiguousCast) {
-  AmbiguousCastTypes::DerivedSub1 sub1;
-  AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
-  // Multiply derived from Base. dynamic_cast<> returns NULL.
-  Base* as_base_ptr =
-      static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
-  EXPECT_THAT(as_base_ptr,
-              WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
-  as_base_ptr = &sub1;
-  EXPECT_THAT(
-      as_base_ptr,
-      WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
-}
-
-TEST(WhenDynamicCastToTest, Describe) {
-  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
-#if GTEST_HAS_RTTI
-  const string prefix =
-      "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
-#else  // GTEST_HAS_RTTI
-  const string prefix = "when dynamic_cast, ";
-#endif  // GTEST_HAS_RTTI
-  EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
-  EXPECT_EQ(prefix + "does not point to a value that is anything",
-            DescribeNegation(matcher));
-}
-
-TEST(WhenDynamicCastToTest, Explain) {
-  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
-  Base* null = NULL;
-  EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
-  Derived derived;
-  EXPECT_TRUE(matcher.Matches(&derived));
-  EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
-
-  // With references, the matcher itself can fail. Test for that one.
-  Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
-  EXPECT_THAT(Explain(ref_matcher, derived),
-              HasSubstr("which cannot be dynamic_cast"));
-}
-
-TEST(WhenDynamicCastToTest, GoodReference) {
-  Derived derived;
-  derived.i = 4;
-  Base& as_base_ref = derived;
-  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
-  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
-}
-
-TEST(WhenDynamicCastToTest, BadReference) {
-  Derived derived;
-  Base& as_base_ref = derived;
-  EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
-}
-
-// Minimal const-propagating pointer.
-template <typename T>
-class ConstPropagatingPtr {
- public:
-  typedef T element_type;
-
-  ConstPropagatingPtr() : val_() {}
-  explicit ConstPropagatingPtr(T* t) : val_(t) {}
-  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
-
-  T* get() { return val_; }
-  T& operator*() { return *val_; }
-  // Most smart pointers return non-const T* and T& from the next methods.
-  const T* get() const { return val_; }
-  const T& operator*() const { return *val_; }
-
- private:
-  T* val_;
-};
-
-TEST(PointeeTest, WorksWithConstPropagatingPointers) {
-  const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
-  int three = 3;
-  const ConstPropagatingPtr<int> co(&three);
-  ConstPropagatingPtr<int> o(&three);
-  EXPECT_TRUE(m.Matches(o));
-  EXPECT_TRUE(m.Matches(co));
-  *o = 6;
-  EXPECT_FALSE(m.Matches(o));
-  EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
-}
-
-TEST(PointeeTest, NeverMatchesNull) {
-  const Matcher<const char*> m = Pointee(_);
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
-TEST(PointeeTest, MatchesAgainstAValue) {
-  const Matcher<int*> m = Pointee(5);
-
-  int n = 5;
-  EXPECT_TRUE(m.Matches(&n));
-  n = -1;
-  EXPECT_FALSE(m.Matches(&n));
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-TEST(PointeeTest, CanDescribeSelf) {
-  const Matcher<int*> m = Pointee(Gt(3));
-  EXPECT_EQ("points to a value that is > 3", Describe(m));
-  EXPECT_EQ("does not point to a value that is > 3",
-            DescribeNegation(m));
-}
-
-TEST(PointeeTest, CanExplainMatchResult) {
-  const Matcher<const string*> m = Pointee(StartsWith("Hi"));
-
-  EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
-
-  const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
-  long n = 3;  // NOLINT
-  EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
-            Explain(m2, &n));
-}
-
-TEST(PointeeTest, AlwaysExplainsPointee) {
-  const Matcher<int*> m = Pointee(0);
-  int n = 42;
-  EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
-}
-
-// An uncopyable class.
-class Uncopyable {
- public:
-  Uncopyable() : value_(-1) {}
-  explicit Uncopyable(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
-  void set_value(int i) { value_ = i; }
-
- private:
-  int value_;
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
-};
-
-// Returns true iff x.value() is positive.
-bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
-
-MATCHER_P(UncopyableIs, inner_matcher, "") {
-  return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
-}
-
-// A user-defined struct for testing Field().
-struct AStruct {
-  AStruct() : x(0), y(1.0), z(5), p(NULL) {}
-  AStruct(const AStruct& rhs)
-      : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
-
-  int x;           // A non-const field.
-  const double y;  // A const field.
-  Uncopyable z;    // An uncopyable field.
-  const char* p;   // A pointer field.
-
- private:
-  GTEST_DISALLOW_ASSIGN_(AStruct);
-};
-
-// A derived struct for testing Field().
-struct DerivedStruct : public AStruct {
-  char ch;
-
- private:
-  GTEST_DISALLOW_ASSIGN_(DerivedStruct);
-};
-
-// Tests that Field(&Foo::field, ...) works when field is non-const.
-TEST(FieldTest, WorksForNonConstField) {
-  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when field is const.
-TEST(FieldTest, WorksForConstField) {
-  AStruct a;
-
-  Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
-  EXPECT_TRUE(m.Matches(a));
-  m = Field(&AStruct::y, Le(0.0));
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when field is not copyable.
-TEST(FieldTest, WorksForUncopyableField) {
-  AStruct a;
-
-  Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
-  EXPECT_TRUE(m.Matches(a));
-  m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when field is a pointer.
-TEST(FieldTest, WorksForPointerField) {
-  // Matching against NULL.
-  Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.p = "hi";
-  EXPECT_FALSE(m.Matches(a));
-
-  // Matching a pointer that is not NULL.
-  m = Field(&AStruct::p, StartsWith("hi"));
-  a.p = "hill";
-  EXPECT_TRUE(m.Matches(a));
-  a.p = "hole";
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field() works when the object is passed by reference.
-TEST(FieldTest, WorksForByRefArgument) {
-  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when the argument's type
-// is a sub-type of Foo.
-TEST(FieldTest, WorksForArgumentOfSubType) {
-  // Note that the matcher expects DerivedStruct but we say AStruct
-  // inside Field().
-  Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
-
-  DerivedStruct d;
-  EXPECT_TRUE(m.Matches(d));
-  d.x = -1;
-  EXPECT_FALSE(m.Matches(d));
-}
-
-// Tests that Field(&Foo::field, m) works when field's type and m's
-// argument type are compatible but not the same.
-TEST(FieldTest, WorksForCompatibleMatcherType) {
-  // The field is an int, but the inner matcher expects a signed char.
-  Matcher<const AStruct&> m = Field(&AStruct::x,
-                                    Matcher<signed char>(Ge(0)));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field() can describe itself.
-TEST(FieldTest, CanDescribeSelf) {
-  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
-
-  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
-}
-
-// Tests that Field() can explain the match result.
-TEST(FieldTest, CanExplainMatchResult) {
-  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  a.x = 1;
-  EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
-
-  m = Field(&AStruct::x, GreaterThan(0));
-  EXPECT_EQ(
-      "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
-      Explain(m, a));
-}
-
-// Tests that Field() works when the argument is a pointer to const.
-TEST(FieldForPointerTest, WorksForPointerToConst) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(&a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Field() works when the argument is a pointer to non-const.
-TEST(FieldForPointerTest, WorksForPointerToNonConst) {
-  Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(&a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Field() works when the argument is a reference to a const pointer.
-TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
-  Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(&a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Field() does not match the NULL pointer.
-TEST(FieldForPointerTest, DoesNotMatchNull) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, _);
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-// Tests that Field(&Foo::field, ...) works when the argument's type
-// is a sub-type of const Foo*.
-TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
-  // Note that the matcher expects DerivedStruct but we say AStruct
-  // inside Field().
-  Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
-
-  DerivedStruct d;
-  EXPECT_TRUE(m.Matches(&d));
-  d.x = -1;
-  EXPECT_FALSE(m.Matches(&d));
-}
-
-// Tests that Field() can describe itself when used to match a pointer.
-TEST(FieldForPointerTest, CanDescribeSelf) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
-}
-
-// Tests that Field() can explain the result of matching a pointer.
-TEST(FieldForPointerTest, CanExplainMatchResult) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  a.x = 1;
-  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
-  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
-            Explain(m, &a));
-
-  m = Field(&AStruct::x, GreaterThan(0));
-  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
-            ", which is 1 more than 0", Explain(m, &a));
-}
-
-// A user-defined class for testing Property().
-class AClass {
- public:
-  AClass() : n_(0) {}
-
-  // A getter that returns a non-reference.
-  int n() const { return n_; }
-
-  void set_n(int new_n) { n_ = new_n; }
-
-  // A getter that returns a reference to const.
-  const string& s() const { return s_; }
-
-  void set_s(const string& new_s) { s_ = new_s; }
-
-  // A getter that returns a reference to non-const.
-  double& x() const { return x_; }
- private:
-  int n_;
-  string s_;
-
-  static double x_;
-};
-
-double AClass::x_ = 0.0;
-
-// A derived class for testing Property().
-class DerivedClass : public AClass {
- public:
-  int k() const { return k_; }
- private:
-  int k_;
-};
-
-// Tests that Property(&Foo::property, ...) works when property()
-// returns a non-reference.
-TEST(PropertyTest, WorksForNonReferenceProperty) {
-  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_TRUE(m.Matches(a));
-
-  a.set_n(-1);
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when property()
-// returns a reference to const.
-TEST(PropertyTest, WorksForReferenceToConstProperty) {
-  Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when property()
-// returns a reference to non-const.
-TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
-  double x = 0.0;
-  AClass a;
-
-  Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
-  EXPECT_FALSE(m.Matches(a));
-
-  m = Property(&AClass::x, Not(Ref(x)));
-  EXPECT_TRUE(m.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when the argument is
-// passed by value.
-TEST(PropertyTest, WorksForByValueArgument) {
-  Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when the argument's
-// type is a sub-type of Foo.
-TEST(PropertyTest, WorksForArgumentOfSubType) {
-  // The matcher expects a DerivedClass, but inside the Property() we
-  // say AClass.
-  Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
-
-  DerivedClass d;
-  d.set_n(1);
-  EXPECT_TRUE(m.Matches(d));
-
-  d.set_n(-1);
-  EXPECT_FALSE(m.Matches(d));
-}
-
-// Tests that Property(&Foo::property, m) works when property()'s type
-// and m's argument type are compatible but different.
-TEST(PropertyTest, WorksForCompatibleMatcherType) {
-  // n() returns an int but the inner matcher expects a signed char.
-  Matcher<const AClass&> m = Property(&AClass::n,
-                                      Matcher<signed char>(Ge(0)));
-
-  AClass a;
-  EXPECT_TRUE(m.Matches(a));
-  a.set_n(-1);
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Property() can describe itself.
-TEST(PropertyTest, CanDescribeSelf) {
-  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
-
-  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given property isn't >= 0",
-            DescribeNegation(m));
-}
-
-// Tests that Property() can explain the match result.
-TEST(PropertyTest, CanExplainMatchResult) {
-  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
-
-  m = Property(&AClass::n, GreaterThan(0));
-  EXPECT_EQ(
-      "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
-      Explain(m, a));
-}
-
-// Tests that Property() works when the argument is a pointer to const.
-TEST(PropertyForPointerTest, WorksForPointerToConst) {
-  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_TRUE(m.Matches(&a));
-
-  a.set_n(-1);
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Property() works when the argument is a pointer to non-const.
-TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
-  Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(&a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Property() works when the argument is a reference to a
-// const pointer.
-TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
-  Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(&a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Property() does not match the NULL pointer.
-TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
-  Matcher<const AClass*> m = Property(&AClass::x, _);
-  EXPECT_FALSE(m.Matches(NULL));
-}
-
-// Tests that Property(&Foo::property, ...) works when the argument's
-// type is a sub-type of const Foo*.
-TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
-  // The matcher expects a DerivedClass, but inside the Property() we
-  // say AClass.
-  Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
-
-  DerivedClass d;
-  d.set_n(1);
-  EXPECT_TRUE(m.Matches(&d));
-
-  d.set_n(-1);
-  EXPECT_FALSE(m.Matches(&d));
-}
-
-// Tests that Property() can describe itself when used to match a pointer.
-TEST(PropertyForPointerTest, CanDescribeSelf) {
-  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
-
-  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given property isn't >= 0",
-            DescribeNegation(m));
-}
-
-// Tests that Property() can explain the result of matching a pointer.
-TEST(PropertyForPointerTest, CanExplainMatchResult) {
-  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
-  EXPECT_EQ(
-      "which points to an object whose given property is 1" + OfType("int"),
-      Explain(m, &a));
-
-  m = Property(&AClass::n, GreaterThan(0));
-  EXPECT_EQ("which points to an object whose given property is 1" +
-            OfType("int") + ", which is 1 more than 0",
-            Explain(m, &a));
-}
-
-// Tests ResultOf.
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// function pointer.
-string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
-
-TEST(ResultOfTest, WorksForFunctionPointers) {
-  Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
-
-  EXPECT_TRUE(matcher.Matches(1));
-  EXPECT_FALSE(matcher.Matches(2));
-}
-
-// Tests that ResultOf() can describe itself.
-TEST(ResultOfTest, CanDescribeItself) {
-  Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
-
-  EXPECT_EQ("is mapped by the given callable to a value that "
-            "is equal to \"foo\"", Describe(matcher));
-  EXPECT_EQ("is mapped by the given callable to a value that "
-            "isn't equal to \"foo\"", DescribeNegation(matcher));
-}
-
-// Tests that ResultOf() can explain the match result.
-int IntFunction(int input) { return input == 42 ? 80 : 90; }
-
-TEST(ResultOfTest, CanExplainMatchResult) {
-  Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
-  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
-            Explain(matcher, 36));
-
-  matcher = ResultOf(&IntFunction, GreaterThan(85));
-  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
-            ", which is 5 more than 85", Explain(matcher, 36));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
-// returns a non-reference.
-TEST(ResultOfTest, WorksForNonReferenceResults) {
-  Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
-
-  EXPECT_TRUE(matcher.Matches(42));
-  EXPECT_FALSE(matcher.Matches(36));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
-// returns a reference to non-const.
-double& DoubleFunction(double& input) { return input; }  // NOLINT
-
-Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
-  return obj;
-}
-
-TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
-  double x = 3.14;
-  double x2 = x;
-  Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
-
-  EXPECT_TRUE(matcher.Matches(x));
-  EXPECT_FALSE(matcher.Matches(x2));
-
-  // Test that ResultOf works with uncopyable objects
-  Uncopyable obj(0);
-  Uncopyable obj2(0);
-  Matcher<Uncopyable&> matcher2 =
-      ResultOf(&RefUncopyableFunction, Ref(obj));
-
-  EXPECT_TRUE(matcher2.Matches(obj));
-  EXPECT_FALSE(matcher2.Matches(obj2));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
-// returns a reference to const.
-const string& StringFunction(const string& input) { return input; }
-
-TEST(ResultOfTest, WorksForReferenceToConstResults) {
-  string s = "foo";
-  string s2 = s;
-  Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
-
-  EXPECT_TRUE(matcher.Matches(s));
-  EXPECT_FALSE(matcher.Matches(s2));
-}
-
-// Tests that ResultOf(f, m) works when f(x) and m's
-// argument types are compatible but different.
-TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
-  // IntFunction() returns int but the inner matcher expects a signed char.
-  Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
-
-  EXPECT_TRUE(matcher.Matches(36));
-  EXPECT_FALSE(matcher.Matches(42));
-}
-
-// Tests that the program aborts when ResultOf is passed
-// a NULL function pointer.
-TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
-  EXPECT_DEATH_IF_SUPPORTED(
-      ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
-               "NULL function pointer is passed into ResultOf\\(\\)\\.");
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// function reference.
-TEST(ResultOfTest, WorksForFunctionReferences) {
-  Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
-  EXPECT_TRUE(matcher.Matches(1));
-  EXPECT_FALSE(matcher.Matches(2));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// function object.
-struct Functor : public ::std::unary_function<int, string> {
-  result_type operator()(argument_type input) const {
-    return IntToStringFunction(input);
-  }
-};
-
-TEST(ResultOfTest, WorksForFunctors) {
-  Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
-
-  EXPECT_TRUE(matcher.Matches(1));
-  EXPECT_FALSE(matcher.Matches(2));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// functor with more then one operator() defined. ResultOf() must work
-// for each defined operator().
-struct PolymorphicFunctor {
-  typedef int result_type;
-  int operator()(int n) { return n; }
-  int operator()(const char* s) { return static_cast<int>(strlen(s)); }
-};
-
-TEST(ResultOfTest, WorksForPolymorphicFunctors) {
-  Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
-
-  EXPECT_TRUE(matcher_int.Matches(10));
-  EXPECT_FALSE(matcher_int.Matches(2));
-
-  Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
-
-  EXPECT_TRUE(matcher_string.Matches("long string"));
-  EXPECT_FALSE(matcher_string.Matches("shrt"));
-}
-
-const int* ReferencingFunction(const int& n) { return &n; }
-
-struct ReferencingFunctor {
-  typedef const int* result_type;
-  result_type operator()(const int& n) { return &n; }
-};
-
-TEST(ResultOfTest, WorksForReferencingCallables) {
-  const int n = 1;
-  const int n2 = 1;
-  Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
-  EXPECT_TRUE(matcher2.Matches(n));
-  EXPECT_FALSE(matcher2.Matches(n2));
-
-  Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
-  EXPECT_TRUE(matcher3.Matches(n));
-  EXPECT_FALSE(matcher3.Matches(n2));
-}
-
-class DivisibleByImpl {
- public:
-  explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
-
-  // For testing using ExplainMatchResultTo() with polymorphic matchers.
-  template <typename T>
-  bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
-    *listener << "which is " << (n % divider_) << " modulo "
-              << divider_;
-    return (n % divider_) == 0;
-  }
-
-  void DescribeTo(ostream* os) const {
-    *os << "is divisible by " << divider_;
-  }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "is not divisible by " << divider_;
-  }
-
-  void set_divider(int a_divider) { divider_ = a_divider; }
-  int divider() const { return divider_; }
-
- private:
-  int divider_;
-};
-
-PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
-  return MakePolymorphicMatcher(DivisibleByImpl(n));
-}
-
-// Tests that when AllOf() fails, only the first failing matcher is
-// asked to explain why.
-TEST(ExplainMatchResultTest, AllOf_False_False) {
-  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
-  EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
-}
-
-// Tests that when AllOf() fails, only the first failing matcher is
-// asked to explain why.
-TEST(ExplainMatchResultTest, AllOf_False_True) {
-  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
-  EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
-}
-
-// Tests that when AllOf() fails, only the first failing matcher is
-// asked to explain why.
-TEST(ExplainMatchResultTest, AllOf_True_False) {
-  const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
-  EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
-}
-
-// Tests that when AllOf() succeeds, all matchers are asked to explain
-// why.
-TEST(ExplainMatchResultTest, AllOf_True_True) {
-  const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
-  EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
-}
-
-TEST(ExplainMatchResultTest, AllOf_True_True_2) {
-  const Matcher<int> m = AllOf(Ge(2), Le(3));
-  EXPECT_EQ("", Explain(m, 2));
-}
-
-TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
-  const Matcher<int> m = GreaterThan(5);
-  EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
-}
-
-// The following two tests verify that values without a public copy
-// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
-// with the help of ByRef().
-
-class NotCopyable {
- public:
-  explicit NotCopyable(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
-
-  bool operator==(const NotCopyable& rhs) const {
-    return value() == rhs.value();
-  }
-
-  bool operator>=(const NotCopyable& rhs) const {
-    return value() >= rhs.value();
-  }
- private:
-  int value_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
-};
-
-TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
-  const NotCopyable const_value1(1);
-  const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
-
-  const NotCopyable n1(1), n2(2);
-  EXPECT_TRUE(m.Matches(n1));
-  EXPECT_FALSE(m.Matches(n2));
-}
-
-TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
-  NotCopyable value2(2);
-  const Matcher<NotCopyable&> m = Ge(ByRef(value2));
-
-  NotCopyable n1(1), n2(2);
-  EXPECT_FALSE(m.Matches(n1));
-  EXPECT_TRUE(m.Matches(n2));
-}
-
-TEST(IsEmptyTest, ImplementsIsEmpty) {
-  vector<int> container;
-  EXPECT_THAT(container, IsEmpty());
-  container.push_back(0);
-  EXPECT_THAT(container, Not(IsEmpty()));
-  container.push_back(1);
-  EXPECT_THAT(container, Not(IsEmpty()));
-}
-
-TEST(IsEmptyTest, WorksWithString) {
-  string text;
-  EXPECT_THAT(text, IsEmpty());
-  text = "foo";
-  EXPECT_THAT(text, Not(IsEmpty()));
-  text = string("\0", 1);
-  EXPECT_THAT(text, Not(IsEmpty()));
-}
-
-TEST(IsEmptyTest, CanDescribeSelf) {
-  Matcher<vector<int> > m = IsEmpty();
-  EXPECT_EQ("is empty", Describe(m));
-  EXPECT_EQ("isn't empty", DescribeNegation(m));
-}
-
-TEST(IsEmptyTest, ExplainsResult) {
-  Matcher<vector<int> > m = IsEmpty();
-  vector<int> container;
-  EXPECT_EQ("", Explain(m, container));
-  container.push_back(0);
-  EXPECT_EQ("whose size is 1", Explain(m, container));
-}
-
-TEST(SizeIsTest, ImplementsSizeIs) {
-  vector<int> container;
-  EXPECT_THAT(container, SizeIs(0));
-  EXPECT_THAT(container, Not(SizeIs(1)));
-  container.push_back(0);
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(1));
-  container.push_back(0);
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(2));
-}
-
-TEST(SizeIsTest, WorksWithMap) {
-  map<string, int> container;
-  EXPECT_THAT(container, SizeIs(0));
-  EXPECT_THAT(container, Not(SizeIs(1)));
-  container.insert(make_pair("foo", 1));
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(1));
-  container.insert(make_pair("bar", 2));
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(2));
-}
-
-TEST(SizeIsTest, WorksWithReferences) {
-  vector<int> container;
-  Matcher<const vector<int>&> m = SizeIs(1);
-  EXPECT_THAT(container, Not(m));
-  container.push_back(0);
-  EXPECT_THAT(container, m);
-}
-
-TEST(SizeIsTest, CanDescribeSelf) {
-  Matcher<vector<int> > m = SizeIs(2);
-  EXPECT_EQ("size is equal to 2", Describe(m));
-  EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
-}
-
-TEST(SizeIsTest, ExplainsResult) {
-  Matcher<vector<int> > m1 = SizeIs(2);
-  Matcher<vector<int> > m2 = SizeIs(Lt(2u));
-  Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
-  Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
-  vector<int> container;
-  EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
-  EXPECT_EQ("whose size 0 matches", Explain(m2, container));
-  EXPECT_EQ("whose size 0 matches", Explain(m3, container));
-  EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
-            Explain(m4, container));
-  container.push_back(0);
-  container.push_back(0);
-  EXPECT_EQ("whose size 2 matches", Explain(m1, container));
-  EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
-  EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
-  EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
-            Explain(m4, container));
-}
-
-#if GTEST_HAS_TYPED_TEST
-// Tests ContainerEq with different container types, and
-// different element types.
-
-template <typename T>
-class ContainerEqTest : public testing::Test {};
-
-typedef testing::Types<
-    set<int>,
-    vector<size_t>,
-    multiset<size_t>,
-    list<int> >
-    ContainerEqTestTypes;
-
-TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
-
-// Tests that the filled container is equal to itself.
-TYPED_TEST(ContainerEqTest, EqualsSelf) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  TypeParam my_set(vals, vals + 6);
-  const Matcher<TypeParam> m = ContainerEq(my_set);
-  EXPECT_TRUE(m.Matches(my_set));
-  EXPECT_EQ("", Explain(m, my_set));
-}
-
-// Tests that missing values are reported.
-TYPED_TEST(ContainerEqTest, ValueMissing) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {2, 1, 8, 5};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 4);
-  const Matcher<TypeParam> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which doesn't have these expected elements: 3",
-            Explain(m, test_set));
-}
-
-// Tests that added values are reported.
-TYPED_TEST(ContainerEqTest, ValueAdded) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 5, 8, 46};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 6);
-  const Matcher<const TypeParam&> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
-}
-
-// Tests that added and missing values are reported together.
-TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 8, 46};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 5);
-  const Matcher<TypeParam> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 46,\n"
-            "and doesn't have these expected elements: 5",
-            Explain(m, test_set));
-}
-
-// Tests duplicated value -- expect no explanation.
-TYPED_TEST(ContainerEqTest, DuplicateDifference) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 5, 8};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 5);
-  const Matcher<const TypeParam&> m = ContainerEq(my_set);
-  // Depending on the container, match may be true or false
-  // But in any case there should be no explanation.
-  EXPECT_EQ("", Explain(m, test_set));
-}
-#endif  // GTEST_HAS_TYPED_TEST
-
-// Tests that mutliple missing values are reported.
-// Using just vector here, so order is predicatble.
-TEST(ContainerEqExtraTest, MultipleValuesMissing) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {2, 1, 5};
-  vector<int> my_set(vals, vals + 6);
-  vector<int> test_set(test_vals, test_vals + 3);
-  const Matcher<vector<int> > m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which doesn't have these expected elements: 3, 8",
-            Explain(m, test_set));
-}
-
-// Tests that added values are reported.
-// Using just vector here, so order is predicatble.
-TEST(ContainerEqExtraTest, MultipleValuesAdded) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
-  list<size_t> my_set(vals, vals + 6);
-  list<size_t> test_set(test_vals, test_vals + 7);
-  const Matcher<const list<size_t>&> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 92, 46",
-            Explain(m, test_set));
-}
-
-// Tests that added and missing values are reported together.
-TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 92, 46};
-  list<size_t> my_set(vals, vals + 6);
-  list<size_t> test_set(test_vals, test_vals + 5);
-  const Matcher<const list<size_t> > m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
-            "and doesn't have these expected elements: 5, 8",
-            Explain(m, test_set));
-}
-
-// Tests to see that duplicate elements are detected,
-// but (as above) not reported in the explanation.
-TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 5, 8};
-  vector<int> my_set(vals, vals + 6);
-  vector<int> test_set(test_vals, test_vals + 5);
-  const Matcher<vector<int> > m = ContainerEq(my_set);
-  EXPECT_TRUE(m.Matches(my_set));
-  EXPECT_FALSE(m.Matches(test_set));
-  // There is nothing to report when both sets contain all the same values.
-  EXPECT_EQ("", Explain(m, test_set));
-}
-
-// Tests that ContainerEq works for non-trivial associative containers,
-// like maps.
-TEST(ContainerEqExtraTest, WorksForMaps) {
-  map<int, std::string> my_map;
-  my_map[0] = "a";
-  my_map[1] = "b";
-
-  map<int, std::string> test_map;
-  test_map[0] = "aa";
-  test_map[1] = "b";
-
-  const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
-  EXPECT_TRUE(m.Matches(my_map));
-  EXPECT_FALSE(m.Matches(test_map));
-
-  EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
-            "and doesn't have these expected elements: (0, \"a\")",
-            Explain(m, test_map));
-}
-
-TEST(ContainerEqExtraTest, WorksForNativeArray) {
-  int a1[] = {1, 2, 3};
-  int a2[] = {1, 2, 3};
-  int b[] = {1, 2, 4};
-
-  EXPECT_THAT(a1, ContainerEq(a2));
-  EXPECT_THAT(a1, Not(ContainerEq(b)));
-}
-
-TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
-  const char a1[][3] = {"hi", "lo"};
-  const char a2[][3] = {"hi", "lo"};
-  const char b[][3] = {"lo", "hi"};
-
-  // Tests using ContainerEq() in the first dimension.
-  EXPECT_THAT(a1, ContainerEq(a2));
-  EXPECT_THAT(a1, Not(ContainerEq(b)));
-
-  // Tests using ContainerEq() in the second dimension.
-  EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
-  EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
-}
-
-TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
-  const int a1[] = {1, 2, 3};
-  const int a2[] = {1, 2, 3};
-  const int b[] = {1, 2, 3, 4};
-
-  const int* const p1 = a1;
-  EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
-  EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
-
-  const int c[] = {1, 3, 2};
-  EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
-}
-
-TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
-  std::string a1[][3] = {
-    {"hi", "hello", "ciao"},
-    {"bye", "see you", "ciao"}
-  };
-
-  std::string a2[][3] = {
-    {"hi", "hello", "ciao"},
-    {"bye", "see you", "ciao"}
-  };
-
-  const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
-  EXPECT_THAT(a1, m);
-
-  a2[0][0] = "ha";
-  EXPECT_THAT(a1, m);
-}
-
-TEST(WhenSortedByTest, WorksForEmptyContainer) {
-  const vector<int> numbers;
-  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
-  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
-}
-
-TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
-  vector<unsigned> numbers;
-  numbers.push_back(3);
-  numbers.push_back(1);
-  numbers.push_back(2);
-  numbers.push_back(2);
-  EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
-                                    ElementsAre(3, 2, 2, 1)));
-  EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
-                                        ElementsAre(1, 2, 2, 3))));
-}
-
-TEST(WhenSortedByTest, WorksForNonVectorContainer) {
-  list<string> words;
-  words.push_back("say");
-  words.push_back("hello");
-  words.push_back("world");
-  EXPECT_THAT(words, WhenSortedBy(less<string>(),
-                                  ElementsAre("hello", "say", "world")));
-  EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
-                                      ElementsAre("say", "hello", "world"))));
-}
-
-TEST(WhenSortedByTest, WorksForNativeArray) {
-  const int numbers[] = {1, 3, 2, 4};
-  const int sorted_numbers[] = {1, 2, 3, 4};
-  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
-  EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
-                                    ElementsAreArray(sorted_numbers)));
-  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
-}
-
-TEST(WhenSortedByTest, CanDescribeSelf) {
-  const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
-  EXPECT_EQ("(when sorted) has 2 elements where\n"
-            "element #0 is equal to 1,\n"
-            "element #1 is equal to 2",
-            Describe(m));
-  EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
-            "element #0 isn't equal to 1, or\n"
-            "element #1 isn't equal to 2",
-            DescribeNegation(m));
-}
-
-TEST(WhenSortedByTest, ExplainsMatchResult) {
-  const int a[] = {2, 1};
-  EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
-            Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
-  EXPECT_EQ("which is { 1, 2 } when sorted",
-            Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
-}
-
-// WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
-// need to test it as exhaustively as we test the latter.
-
-TEST(WhenSortedTest, WorksForEmptyContainer) {
-  const vector<int> numbers;
-  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
-  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
-}
-
-TEST(WhenSortedTest, WorksForNonEmptyContainer) {
-  list<string> words;
-  words.push_back("3");
-  words.push_back("1");
-  words.push_back("2");
-  words.push_back("2");
-  EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
-  EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
-}
-
-TEST(WhenSortedTest, WorksForMapTypes) {
-    map<string, int> word_counts;
-    word_counts["and"] = 1;
-    word_counts["the"] = 1;
-    word_counts["buffalo"] = 2;
-    EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
-            Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
-    EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
-            Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
-}
-
-TEST(WhenSortedTest, WorksForMultiMapTypes) {
-    multimap<int, int> ifib;
-    ifib.insert(make_pair(8, 6));
-    ifib.insert(make_pair(2, 3));
-    ifib.insert(make_pair(1, 1));
-    ifib.insert(make_pair(3, 4));
-    ifib.insert(make_pair(1, 2));
-    ifib.insert(make_pair(5, 5));
-    EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
-                                             Pair(1, 2),
-                                             Pair(2, 3),
-                                             Pair(3, 4),
-                                             Pair(5, 5),
-                                             Pair(8, 6))));
-    EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
-                                                 Pair(2, 3),
-                                                 Pair(1, 1),
-                                                 Pair(3, 4),
-                                                 Pair(1, 2),
-                                                 Pair(5, 5)))));
-}
-
-TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
-    std::deque<int> d;
-    d.push_back(2);
-    d.push_back(1);
-    EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
-    EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
-}
-
-TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
-    std::deque<int> d;
-    d.push_back(2);
-    d.push_back(1);
-    Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
-    EXPECT_THAT(d, WhenSorted(vector_match));
-    Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
-    EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
-}
-
-// Deliberately bare pseudo-container.
-// Offers only begin() and end() accessors, yielding InputIterator.
-template <typename T>
-class Streamlike {
- private:
-  class ConstIter;
- public:
-  typedef ConstIter const_iterator;
-  typedef T value_type;
-
-  template <typename InIter>
-  Streamlike(InIter first, InIter last) : remainder_(first, last) {}
-
-  const_iterator begin() const {
-    return const_iterator(this, remainder_.begin());
-  }
-  const_iterator end() const {
-    return const_iterator(this, remainder_.end());
-  }
-
- private:
-  class ConstIter : public std::iterator<std::input_iterator_tag,
-                                         value_type,
-                                         ptrdiff_t,
-                                         const value_type*,
-                                         const value_type&> {
-   public:
-    ConstIter(const Streamlike* s,
-              typename std::list<value_type>::iterator pos)
-        : s_(s), pos_(pos) {}
-
-    const value_type& operator*() const { return *pos_; }
-    const value_type* operator->() const { return &*pos_; }
-    ConstIter& operator++() {
-      s_->remainder_.erase(pos_++);
-      return *this;
-    }
-
-    // *iter++ is required to work (see std::istreambuf_iterator).
-    // (void)iter++ is also required to work.
-    class PostIncrProxy {
-     public:
-      explicit PostIncrProxy(const value_type& value) : value_(value) {}
-      value_type operator*() const { return value_; }
-     private:
-      value_type value_;
-    };
-    PostIncrProxy operator++(int) {
-      PostIncrProxy proxy(**this);
-      ++(*this);
-      return proxy;
-    }
-
-    friend bool operator==(const ConstIter& a, const ConstIter& b) {
-      return a.s_ == b.s_ && a.pos_ == b.pos_;
-    }
-    friend bool operator!=(const ConstIter& a, const ConstIter& b) {
-      return !(a == b);
-    }
-
-   private:
-    const Streamlike* s_;
-    typename std::list<value_type>::iterator pos_;
-  };
-
-  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
-    os << "[";
-    typedef typename std::list<value_type>::const_iterator Iter;
-    const char* sep = "";
-    for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
-      os << sep << *it;
-      sep = ",";
-    }
-    os << "]";
-    return os;
-  }
-
-  mutable std::list<value_type> remainder_;  // modified by iteration
-};
-
-TEST(StreamlikeTest, Iteration) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(a, a + 5);
-  Streamlike<int>::const_iterator it = s.begin();
-  const int* ip = a;
-  while (it != s.end()) {
-    SCOPED_TRACE(ip - a);
-    EXPECT_EQ(*ip++, *it++);
-  }
-}
-
-#if GTEST_HAS_STD_FORWARD_LIST_
-TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
-  std::forward_list<int> container;
-  EXPECT_THAT(container, BeginEndDistanceIs(0));
-  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
-  container.push_front(0);
-  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
-  EXPECT_THAT(container, BeginEndDistanceIs(1));
-  container.push_front(0);
-  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
-  EXPECT_THAT(container, BeginEndDistanceIs(2));
-}
-#endif  // GTEST_HAS_STD_FORWARD_LIST_
-
-TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(a, a + 5);
-  EXPECT_THAT(s, BeginEndDistanceIs(5));
-}
-
-TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
-  Matcher<vector<int> > m = BeginEndDistanceIs(2);
-  EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
-  EXPECT_EQ("distance between begin() and end() isn't equal to 2",
-            DescribeNegation(m));
-}
-
-TEST(BeginEndDistanceIsTest, ExplainsResult) {
-  Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
-  Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
-  Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
-  Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
-  vector<int> container;
-  EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
-            Explain(m1, container));
-  EXPECT_EQ("whose distance between begin() and end() 0 matches",
-            Explain(m2, container));
-  EXPECT_EQ("whose distance between begin() and end() 0 matches",
-            Explain(m3, container));
-  EXPECT_EQ(
-      "whose distance between begin() and end() 0 doesn't match, which is 1 "
-      "less than 1",
-      Explain(m4, container));
-  container.push_back(0);
-  container.push_back(0);
-  EXPECT_EQ("whose distance between begin() and end() 2 matches",
-            Explain(m1, container));
-  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
-            Explain(m2, container));
-  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
-            Explain(m3, container));
-  EXPECT_EQ(
-      "whose distance between begin() and end() 2 matches, which is 1 more "
-      "than 1",
-      Explain(m4, container));
-}
-
-TEST(WhenSortedTest, WorksForStreamlike) {
-  // Streamlike 'container' provides only minimal iterator support.
-  // Its iterators are tagged with input_iterator_tag.
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
-  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
-}
-
-TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
-  const int a[] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
-  EXPECT_THAT(s, WhenSorted(vector_match));
-  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
-}
-
-// Tests using ElementsAre() and ElementsAreArray() with stream-like
-// "containers".
-
-TEST(ElemensAreStreamTest, WorksForStreamlike) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
-  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
-}
-
-TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-
-  vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(3);
-  expected.push_back(4);
-  expected.push_back(5);
-  EXPECT_THAT(s, ElementsAreArray(expected));
-
-  expected[3] = 0;
-  EXPECT_THAT(s, Not(ElementsAreArray(expected)));
-}
-
-TEST(ElementsAreTest, WorksWithUncopyable) {
-  Uncopyable objs[2];
-  objs[0].set_value(-3);
-  objs[1].set_value(1);
-  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
-}
-
-TEST(ElementsAreTest, TakesStlContainer) {
-  const int actual[] = {3, 1, 2};
-
-  ::std::list<int> expected;
-  expected.push_back(3);
-  expected.push_back(1);
-  expected.push_back(2);
-  EXPECT_THAT(actual, ElementsAreArray(expected));
-
-  expected.push_back(4);
-  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
-}
-
-// Tests for UnorderedElementsAreArray()
-
-TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
-  const int a[] = {0, 1, 2, 3, 4};
-  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-  do {
-    StringMatchResultListener listener;
-    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
-                                   s, &listener)) << listener.str();
-  } while (std::next_permutation(s.begin(), s.end()));
-}
-
-TEST(UnorderedElementsAreArrayTest, VectorBool) {
-  const bool a[] = {0, 1, 0, 1, 1};
-  const bool b[] = {1, 0, 1, 1, 0};
-  std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
-  std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
-  StringMatchResultListener listener;
-  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
-                                 actual, &listener)) << listener.str();
-}
-
-TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
-  // Streamlike 'container' provides only minimal iterator support.
-  // Its iterators are tagged with input_iterator_tag, and it has no
-  // size() or empty() methods.
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-
-  ::std::vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(3);
-  expected.push_back(4);
-  expected.push_back(5);
-  EXPECT_THAT(s, UnorderedElementsAreArray(expected));
-
-  expected.push_back(6);
-  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
-}
-
-TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
-  const int actual[] = {3, 1, 2};
-
-  ::std::list<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(3);
-  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
-
-  expected.push_back(4);
-  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
-}
-
-TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
-  const string a[5] = {"a", "b", "c", "d", "e"};
-  EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
-}
-
-TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  EXPECT_THAT(a, UnorderedElementsAreArray(
-      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray(
-      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
-}
-
-TEST(UnorderedElementsAreArrayTest,
-     TakesInitializerListOfDifferentTypedMatchers) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  // The compiler cannot infer the type of the initializer list if its
-  // elements have different types.  We must explicitly specify the
-  // unified element type in this case.
-  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
-      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
-      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
-}
-
-#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
-
-class UnorderedElementsAreTest : public testing::Test {
- protected:
-  typedef std::vector<int> IntVec;
-};
-
-TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
-  Uncopyable objs[2];
-  objs[0].set_value(-3);
-  objs[1].set_value(1);
-  EXPECT_THAT(objs,
-              UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
-}
-
-TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
-  const int a[] = {1, 2, 3};
-  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-  do {
-    StringMatchResultListener listener;
-    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
-                                   s, &listener)) << listener.str();
-  } while (std::next_permutation(s.begin(), s.end()));
-}
-
-TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
-  const int a[] = {1, 2, 3};
-  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-  std::vector<Matcher<int> > mv;
-  mv.push_back(1);
-  mv.push_back(2);
-  mv.push_back(2);
-  // The element with value '3' matches nothing: fail fast.
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
-                                  s, &listener)) << listener.str();
-}
-
-TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
-  // Streamlike 'container' provides only minimal iterator support.
-  // Its iterators are tagged with input_iterator_tag, and it has no
-  // size() or empty() methods.
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
-
-  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
-  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
-}
-
-// One naive implementation of the matcher runs in O(N!) time, which is too
-// slow for many real-world inputs. This test shows that our matcher can match
-// 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
-// iterations and obviously effectively incomputable.
-// [ RUN      ] UnorderedElementsAreTest.Performance
-// [       OK ] UnorderedElementsAreTest.Performance (4 ms)
-TEST_F(UnorderedElementsAreTest, Performance) {
-  std::vector<int> s;
-  std::vector<Matcher<int> > mv;
-  for (int i = 0; i < 100; ++i) {
-    s.push_back(i);
-    mv.push_back(_);
-  }
-  mv[50] = Eq(0);
-  StringMatchResultListener listener;
-  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
-                                 s, &listener)) << listener.str();
-}
-
-// Another variant of 'Performance' with similar expectations.
-// [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
-// [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
-TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
-  std::vector<int> s;
-  std::vector<Matcher<int> > mv;
-  for (int i = 0; i < 100; ++i) {
-    s.push_back(i);
-    if (i & 1) {
-      mv.push_back(_);
-    } else {
-      mv.push_back(i);
-    }
-  }
-  StringMatchResultListener listener;
-  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
-                                 s, &listener)) << listener.str();
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
-  std::vector<int> v;
-  v.push_back(4);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(listener.str(), Eq("which has 1 element"));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
-  std::vector<int> v;
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(listener.str(), Eq(""));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
-  std::vector<int> v;
-  v.push_back(1);
-  v.push_back(1);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(
-      listener.str(),
-      Eq("where the following matchers don't match any elements:\n"
-         "matcher #1: is equal to 2"));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
-  std::vector<int> v;
-  v.push_back(1);
-  v.push_back(2);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(
-      listener.str(),
-      Eq("where the following elements don't match any matchers:\n"
-         "element #1: 2"));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
-  std::vector<int> v;
-  v.push_back(2);
-  v.push_back(3);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(
-      listener.str(),
-      Eq("where"
-         " the following matchers don't match any elements:\n"
-         "matcher #0: is equal to 1\n"
-         "and"
-         " where"
-         " the following elements don't match any matchers:\n"
-         "element #1: 3"));
-}
-
-// Test helper for formatting element, matcher index pairs in expectations.
-static string EMString(int element, int matcher) {
-  stringstream ss;
-  ss << "(element #" << element << ", matcher #" << matcher << ")";
-  return ss.str();
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
-  // A situation where all elements and matchers have a match
-  // associated with them, but the max matching is not perfect.
-  std::vector<string> v;
-  v.push_back("a");
-  v.push_back("b");
-  v.push_back("c");
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(
-      UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
-      << listener.str();
-
-  string prefix =
-      "where no permutation of the elements can satisfy all matchers, "
-      "and the closest match is 2 of 3 matchers with the "
-      "pairings:\n";
-
-  // We have to be a bit loose here, because there are 4 valid max matches.
-  EXPECT_THAT(
-      listener.str(),
-      AnyOf(prefix + "{\n  " + EMString(0, 0) +
-                     ",\n  " + EMString(1, 2) + "\n}",
-            prefix + "{\n  " + EMString(0, 1) +
-                     ",\n  " + EMString(1, 2) + "\n}",
-            prefix + "{\n  " + EMString(0, 0) +
-                     ",\n  " + EMString(2, 2) + "\n}",
-            prefix + "{\n  " + EMString(0, 1) +
-                     ",\n  " + EMString(2, 2) + "\n}"));
-}
-
-TEST_F(UnorderedElementsAreTest, Describe) {
-  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
-              Eq("is empty"));
-  EXPECT_THAT(
-      Describe<IntVec>(UnorderedElementsAre(345)),
-      Eq("has 1 element and that element is equal to 345"));
-  EXPECT_THAT(
-      Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
-      Eq("has 3 elements and there exists some permutation "
-         "of elements such that:\n"
-         " - element #0 is equal to 111, and\n"
-         " - element #1 is equal to 222, and\n"
-         " - element #2 is equal to 333"));
-}
-
-TEST_F(UnorderedElementsAreTest, DescribeNegation) {
-  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
-              Eq("isn't empty"));
-  EXPECT_THAT(
-      DescribeNegation<IntVec>(UnorderedElementsAre(345)),
-      Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
-  EXPECT_THAT(
-      DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
-      Eq("doesn't have 3 elements, or there exists no permutation "
-         "of elements such that:\n"
-         " - element #0 is equal to 123, and\n"
-         " - element #1 is equal to 234, and\n"
-         " - element #2 is equal to 345"));
-}
-
-namespace {
-
-// Used as a check on the more complex max flow method used in the
-// real testing::internal::FindMaxBipartiteMatching. This method is
-// compatible but runs in worst-case factorial time, so we only
-// use it in testing for small problem sizes.
-template <typename Graph>
-class BacktrackingMaxBPMState {
- public:
-  // Does not take ownership of 'g'.
-  explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
-
-  ElementMatcherPairs Compute() {
-    if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
-      return best_so_far_;
-    }
-    lhs_used_.assign(graph_->LhsSize(), kUnused);
-    rhs_used_.assign(graph_->RhsSize(), kUnused);
-    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
-      matches_.clear();
-      RecurseInto(irhs);
-      if (best_so_far_.size() == graph_->RhsSize())
-        break;
-    }
-    return best_so_far_;
-  }
-
- private:
-  static const size_t kUnused = static_cast<size_t>(-1);
-
-  void PushMatch(size_t lhs, size_t rhs) {
-    matches_.push_back(ElementMatcherPair(lhs, rhs));
-    lhs_used_[lhs] = rhs;
-    rhs_used_[rhs] = lhs;
-    if (matches_.size() > best_so_far_.size()) {
-      best_so_far_ = matches_;
-    }
-  }
-
-  void PopMatch() {
-    const ElementMatcherPair& back = matches_.back();
-    lhs_used_[back.first] = kUnused;
-    rhs_used_[back.second] = kUnused;
-    matches_.pop_back();
-  }
-
-  bool RecurseInto(size_t irhs) {
-    if (rhs_used_[irhs] != kUnused) {
-      return true;
-    }
-    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
-      if (lhs_used_[ilhs] != kUnused) {
-        continue;
-      }
-      if (!graph_->HasEdge(ilhs, irhs)) {
-        continue;
-      }
-      PushMatch(ilhs, irhs);
-      if (best_so_far_.size() == graph_->RhsSize()) {
-        return false;
-      }
-      for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
-        if (!RecurseInto(mi)) return false;
-      }
-      PopMatch();
-    }
-    return true;
-  }
-
-  const Graph* graph_;  // not owned
-  std::vector<size_t> lhs_used_;
-  std::vector<size_t> rhs_used_;
-  ElementMatcherPairs matches_;
-  ElementMatcherPairs best_so_far_;
-};
-
-template <typename Graph>
-const size_t BacktrackingMaxBPMState<Graph>::kUnused;
-
-}  // namespace
-
-// Implement a simple backtracking algorithm to determine if it is possible
-// to find one element per matcher, without reusing elements.
-template <typename Graph>
-ElementMatcherPairs
-FindBacktrackingMaxBPM(const Graph& g) {
-  return BacktrackingMaxBPMState<Graph>(&g).Compute();
-}
-
-class BacktrackingBPMTest : public ::testing::Test { };
-
-// Tests the MaxBipartiteMatching algorithm with square matrices.
-// The single int param is the # of nodes on each of the left and right sides.
-class BipartiteTest : public ::testing::TestWithParam<int> { };
-
-// Verify all match graphs up to some moderate number of edges.
-TEST_P(BipartiteTest, Exhaustive) {
-  int nodes = GetParam();
-  MatchMatrix graph(nodes, nodes);
-  do {
-    ElementMatcherPairs matches =
-        internal::FindMaxBipartiteMatching(graph);
-    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
-        << "graph: " << graph.DebugString();
-    // Check that all elements of matches are in the graph.
-    // Check that elements of first and second are unique.
-    std::vector<bool> seen_element(graph.LhsSize());
-    std::vector<bool> seen_matcher(graph.RhsSize());
-    SCOPED_TRACE(PrintToString(matches));
-    for (size_t i = 0; i < matches.size(); ++i) {
-      size_t ilhs = matches[i].first;
-      size_t irhs = matches[i].second;
-      EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
-      EXPECT_FALSE(seen_element[ilhs]);
-      EXPECT_FALSE(seen_matcher[irhs]);
-      seen_element[ilhs] = true;
-      seen_matcher[irhs] = true;
-    }
-  } while (graph.NextGraph());
-}
-
-INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
-                        ::testing::Range(0, 5));
-
-// Parameterized by a pair interpreted as (LhsSize, RhsSize).
-class BipartiteNonSquareTest
-    : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
-};
-
-TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
-  //   .......
-  // 0:-----\ :
-  // 1:---\ | :
-  // 2:---\ | :
-  // 3:-\ | | :
-  //  :.......:
-  //    0 1 2
-  MatchMatrix g(4, 3);
-  static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
-  for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
-    g.SetEdge(kEdges[i][0], kEdges[i][1], true);
-  }
-  EXPECT_THAT(FindBacktrackingMaxBPM(g),
-              ElementsAre(Pair(3, 0),
-                          Pair(AnyOf(1, 2), 1),
-                          Pair(0, 2))) << g.DebugString();
-}
-
-// Verify a few nonsquare matrices.
-TEST_P(BipartiteNonSquareTest, Exhaustive) {
-  size_t nlhs = GetParam().first;
-  size_t nrhs = GetParam().second;
-  MatchMatrix graph(nlhs, nrhs);
-  do {
-    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
-              internal::FindMaxBipartiteMatching(graph).size())
-        << "graph: " << graph.DebugString()
-        << "\nbacktracking: "
-        << PrintToString(FindBacktrackingMaxBPM(graph))
-        << "\nmax flow: "
-        << PrintToString(internal::FindMaxBipartiteMatching(graph));
-  } while (graph.NextGraph());
-}
-
-INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
-    testing::Values(
-        std::make_pair(1, 2),
-        std::make_pair(2, 1),
-        std::make_pair(3, 2),
-        std::make_pair(2, 3),
-        std::make_pair(4, 1),
-        std::make_pair(1, 4),
-        std::make_pair(4, 3),
-        std::make_pair(3, 4)));
-
-class BipartiteRandomTest
-    : public ::testing::TestWithParam<std::pair<int, int> > {
-};
-
-// Verifies a large sample of larger graphs.
-TEST_P(BipartiteRandomTest, LargerNets) {
-  int nodes = GetParam().first;
-  int iters = GetParam().second;
-  MatchMatrix graph(nodes, nodes);
-
-  testing::internal::Int32 seed = GTEST_FLAG(random_seed);
-  if (seed == 0) {
-    seed = static_cast<testing::internal::Int32>(time(NULL));
-  }
-
-  for (; iters > 0; --iters, ++seed) {
-    srand(static_cast<int>(seed));
-    graph.Randomize();
-    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
-              internal::FindMaxBipartiteMatching(graph).size())
-        << " graph: " << graph.DebugString()
-        << "\nTo reproduce the failure, rerun the test with the flag"
-           " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
-  }
-}
-
-// Test argument is a std::pair<int, int> representing (nodes, iters).
-INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
-    testing::Values(
-        std::make_pair(5, 10000),
-        std::make_pair(6, 5000),
-        std::make_pair(7, 2000),
-        std::make_pair(8, 500),
-        std::make_pair(9, 100)));
-
-// Tests IsReadableTypeName().
-
-TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
-  EXPECT_TRUE(IsReadableTypeName("int"));
-  EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
-  EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
-  EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
-}
-
-TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
-  EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
-  EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
-  EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
-}
-
-TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
-  EXPECT_FALSE(
-      IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
-  EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
-}
-
-TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
-  EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
-}
-
-// Tests JoinAsTuple().
-
-TEST(JoinAsTupleTest, JoinsEmptyTuple) {
-  EXPECT_EQ("", JoinAsTuple(Strings()));
-}
-
-TEST(JoinAsTupleTest, JoinsOneTuple) {
-  const char* fields[] = {"1"};
-  EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
-}
-
-TEST(JoinAsTupleTest, JoinsTwoTuple) {
-  const char* fields[] = {"1", "a"};
-  EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
-}
-
-TEST(JoinAsTupleTest, JoinsTenTuple) {
-  const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
-  EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
-            JoinAsTuple(Strings(fields, fields + 10)));
-}
-
-// Tests FormatMatcherDescription().
-
-TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
-  EXPECT_EQ("is even",
-            FormatMatcherDescription(false, "IsEven", Strings()));
-  EXPECT_EQ("not (is even)",
-            FormatMatcherDescription(true, "IsEven", Strings()));
-
-  const char* params[] = {"5"};
-  EXPECT_EQ("equals 5",
-            FormatMatcherDescription(false, "Equals",
-                                     Strings(params, params + 1)));
-
-  const char* params2[] = {"5", "8"};
-  EXPECT_EQ("is in range (5, 8)",
-            FormatMatcherDescription(false, "IsInRange",
-                                     Strings(params2, params2 + 2)));
-}
-
-// Tests PolymorphicMatcher::mutable_impl().
-TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
-  PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
-  DivisibleByImpl& impl = m.mutable_impl();
-  EXPECT_EQ(42, impl.divider());
-
-  impl.set_divider(0);
-  EXPECT_EQ(0, m.mutable_impl().divider());
-}
-
-// Tests PolymorphicMatcher::impl().
-TEST(PolymorphicMatcherTest, CanAccessImpl) {
-  const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
-  const DivisibleByImpl& impl = m.impl();
-  EXPECT_EQ(42, impl.divider());
-}
-
-TEST(MatcherTupleTest, ExplainsMatchFailure) {
-  stringstream ss1;
-  ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
-                             make_tuple('a', 10), &ss1);
-  EXPECT_EQ("", ss1.str());  // Successful match.
-
-  stringstream ss2;
-  ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
-                             make_tuple(2, 'b'), &ss2);
-  EXPECT_EQ("  Expected arg #0: is > 5\n"
-            "           Actual: 2, which is 3 less than 5\n"
-            "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
-            "           Actual: 'b' (98, 0x62)\n",
-            ss2.str());  // Failed match where both arguments need explanation.
-
-  stringstream ss3;
-  ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
-                             make_tuple(2, 'a'), &ss3);
-  EXPECT_EQ("  Expected arg #0: is > 5\n"
-            "           Actual: 2, which is 3 less than 5\n",
-            ss3.str());  // Failed match where only one argument needs
-                         // explanation.
-}
-
-// Tests Each().
-
-TEST(EachTest, ExplainsMatchResultCorrectly) {
-  set<int> a;  // empty
-
-  Matcher<set<int> > m = Each(2);
-  EXPECT_EQ("", Explain(m, a));
-
-  Matcher<const int(&)[1]> n = Each(1);  // NOLINT
-
-  const int b[1] = {1};
-  EXPECT_EQ("", Explain(n, b));
-
-  n = Each(3);
-  EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
-
-  a.insert(1);
-  a.insert(2);
-  a.insert(3);
-  m = Each(GreaterThan(0));
-  EXPECT_EQ("", Explain(m, a));
-
-  m = Each(GreaterThan(10));
-  EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
-            Explain(m, a));
-}
-
-TEST(EachTest, DescribesItselfCorrectly) {
-  Matcher<vector<int> > m = Each(1);
-  EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
-
-  Matcher<vector<int> > m2 = Not(m);
-  EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
-}
-
-TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
-  vector<int> some_vector;
-  EXPECT_THAT(some_vector, Each(1));
-  some_vector.push_back(3);
-  EXPECT_THAT(some_vector, Not(Each(1)));
-  EXPECT_THAT(some_vector, Each(3));
-  some_vector.push_back(1);
-  some_vector.push_back(2);
-  EXPECT_THAT(some_vector, Not(Each(3)));
-  EXPECT_THAT(some_vector, Each(Lt(3.5)));
-
-  vector<string> another_vector;
-  another_vector.push_back("fee");
-  EXPECT_THAT(another_vector, Each(string("fee")));
-  another_vector.push_back("fie");
-  another_vector.push_back("foe");
-  another_vector.push_back("fum");
-  EXPECT_THAT(another_vector, Not(Each(string("fee"))));
-}
-
-TEST(EachTest, MatchesMapWhenAllElementsMatch) {
-  map<const char*, int> my_map;
-  const char* bar = "a string";
-  my_map[bar] = 2;
-  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
-
-  map<string, int> another_map;
-  EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
-  another_map["fee"] = 1;
-  EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
-  another_map["fie"] = 2;
-  another_map["foe"] = 3;
-  another_map["fum"] = 4;
-  EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
-  EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
-  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
-}
-
-TEST(EachTest, AcceptsMatcher) {
-  const int a[] = {1, 2, 3};
-  EXPECT_THAT(a, Each(Gt(0)));
-  EXPECT_THAT(a, Not(Each(Gt(1))));
-}
-
-TEST(EachTest, WorksForNativeArrayAsTuple) {
-  const int a[] = {1, 2};
-  const int* const pointer = a;
-  EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
-  EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
-}
-
-// For testing Pointwise().
-class IsHalfOfMatcher {
- public:
-  template <typename T1, typename T2>
-  bool MatchAndExplain(const tuple<T1, T2>& a_pair,
-                       MatchResultListener* listener) const {
-    if (get<0>(a_pair) == get<1>(a_pair)/2) {
-      *listener << "where the second is " << get<1>(a_pair);
-      return true;
-    } else {
-      *listener << "where the second/2 is " << get<1>(a_pair)/2;
-      return false;
-    }
-  }
-
-  void DescribeTo(ostream* os) const {
-    *os << "are a pair where the first is half of the second";
-  }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "are a pair where the first isn't half of the second";
-  }
-};
-
-PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
-  return MakePolymorphicMatcher(IsHalfOfMatcher());
-}
-
-TEST(PointwiseTest, DescribesSelf) {
-  vector<int> rhs;
-  rhs.push_back(1);
-  rhs.push_back(2);
-  rhs.push_back(3);
-  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
-  EXPECT_EQ("contains 3 values, where each value and its corresponding value "
-            "in { 1, 2, 3 } are a pair where the first is half of the second",
-            Describe(m));
-  EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
-            "index i where x and the i-th value of { 1, 2, 3 } are a pair "
-            "where the first isn't half of the second",
-            DescribeNegation(m));
-}
-
-TEST(PointwiseTest, MakesCopyOfRhs) {
-  list<signed char> rhs;
-  rhs.push_back(2);
-  rhs.push_back(4);
-
-  int lhs[] = {1, 2};
-  const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
-  EXPECT_THAT(lhs, m);
-
-  // Changing rhs now shouldn't affect m, which made a copy of rhs.
-  rhs.push_back(6);
-  EXPECT_THAT(lhs, m);
-}
-
-TEST(PointwiseTest, WorksForLhsNativeArray) {
-  const int lhs[] = {1, 2, 3};
-  vector<int> rhs;
-  rhs.push_back(2);
-  rhs.push_back(4);
-  rhs.push_back(6);
-  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
-  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
-}
-
-TEST(PointwiseTest, WorksForRhsNativeArray) {
-  const int rhs[] = {1, 2, 3};
-  vector<int> lhs;
-  lhs.push_back(2);
-  lhs.push_back(4);
-  lhs.push_back(6);
-  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
-  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(PointwiseTest, WorksForRhsInitializerList) {
-  const vector<int> lhs{2, 4, 6};
-  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
-  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
-}
-
-#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(PointwiseTest, RejectsWrongSize) {
-  const double lhs[2] = {1, 2};
-  const int rhs[1] = {0};
-  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
-  EXPECT_EQ("which contains 2 values",
-            Explain(Pointwise(Gt(), rhs), lhs));
-
-  const int rhs2[3] = {0, 1, 2};
-  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
-}
-
-TEST(PointwiseTest, RejectsWrongContent) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 6, 4};
-  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
-  EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
-            "where the second/2 is 3",
-            Explain(Pointwise(IsHalfOf(), rhs), lhs));
-}
-
-TEST(PointwiseTest, AcceptsCorrectContent) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 4, 6};
-  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
-  EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
-}
-
-TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 4, 6};
-  const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
-  EXPECT_THAT(lhs, Pointwise(m1, rhs));
-  EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
-
-  // This type works as a tuple<const double&, const int&> can be
-  // implicitly cast to tuple<double, int>.
-  const Matcher<tuple<double, int> > m2 = IsHalfOf();
-  EXPECT_THAT(lhs, Pointwise(m2, rhs));
-  EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
-}
-
-TEST(UnorderedPointwiseTest, DescribesSelf) {
-  vector<int> rhs;
-  rhs.push_back(1);
-  rhs.push_back(2);
-  rhs.push_back(3);
-  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
-  EXPECT_EQ(
-      "has 3 elements and there exists some permutation of elements such "
-      "that:\n"
-      " - element #0 and 1 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #1 and 2 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #2 and 3 are a pair where the first is half of the second",
-      Describe(m));
-  EXPECT_EQ(
-      "doesn't have 3 elements, or there exists no permutation of elements "
-      "such that:\n"
-      " - element #0 and 1 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #1 and 2 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #2 and 3 are a pair where the first is half of the second",
-      DescribeNegation(m));
-}
-
-TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
-  list<signed char> rhs;
-  rhs.push_back(2);
-  rhs.push_back(4);
-
-  int lhs[] = {2, 1};
-  const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
-  EXPECT_THAT(lhs, m);
-
-  // Changing rhs now shouldn't affect m, which made a copy of rhs.
-  rhs.push_back(6);
-  EXPECT_THAT(lhs, m);
-}
-
-TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
-  const int lhs[] = {1, 2, 3};
-  vector<int> rhs;
-  rhs.push_back(4);
-  rhs.push_back(6);
-  rhs.push_back(2);
-  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
-}
-
-TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
-  const int rhs[] = {1, 2, 3};
-  vector<int> lhs;
-  lhs.push_back(4);
-  lhs.push_back(2);
-  lhs.push_back(6);
-  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
-}
-
-#if GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
-  const vector<int> lhs{2, 4, 6};
-  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
-}
-
-#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
-
-TEST(UnorderedPointwiseTest, RejectsWrongSize) {
-  const double lhs[2] = {1, 2};
-  const int rhs[1] = {0};
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
-  EXPECT_EQ("which has 2 elements",
-            Explain(UnorderedPointwise(Gt(), rhs), lhs));
-
-  const int rhs2[3] = {0, 1, 2};
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
-}
-
-TEST(UnorderedPointwiseTest, RejectsWrongContent) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 6, 6};
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
-  EXPECT_EQ("where the following elements don't match any matchers:\n"
-            "element #1: 2",
-            Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
-}
-
-TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 4, 6};
-  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
-}
-
-TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {6, 4, 2};
-  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
-}
-
-TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {4, 6, 2};
-  const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
-  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
-
-  // This type works as a tuple<const double&, const int&> can be
-  // implicitly cast to tuple<double, int>.
-  const Matcher<tuple<double, int> > m2 = IsHalfOf();
-  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
-}
-
-}  // namespace gmock_matchers_test
-}  // namespace testing
diff --git a/testing/gmock/test/gmock-more-actions_test.cc b/testing/gmock/test/gmock-more-actions_test.cc
deleted file mode 100644
index 9477fe9..0000000
--- a/testing/gmock/test/gmock-more-actions_test.cc
+++ /dev/null
@@ -1,705 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in actions in gmock-more-actions.h.
-
-#include "gmock/gmock-more-actions.h"
-
-#include <functional>
-#include <sstream>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "gtest/internal/gtest-linked_ptr.h"
-
-namespace testing {
-namespace gmock_more_actions_test {
-
-using ::std::plus;
-using ::std::string;
-using testing::get;
-using testing::make_tuple;
-using testing::tuple;
-using testing::tuple_element;
-using testing::_;
-using testing::Action;
-using testing::ActionInterface;
-using testing::DeleteArg;
-using testing::Invoke;
-using testing::Return;
-using testing::ReturnArg;
-using testing::ReturnPointee;
-using testing::SaveArg;
-using testing::SaveArgPointee;
-using testing::SetArgReferee;
-using testing::StaticAssertTypeEq;
-using testing::Unused;
-using testing::WithArg;
-using testing::WithoutArgs;
-using testing::internal::linked_ptr;
-
-// For suppressing compiler warnings on conversion possibly losing precision.
-inline short Short(short n) { return n; }  // NOLINT
-inline char Char(char ch) { return ch; }
-
-// Sample functions and functors for testing Invoke() and etc.
-int Nullary() { return 1; }
-
-class NullaryFunctor {
- public:
-  int operator()() { return 2; }
-};
-
-bool g_done = false;
-void VoidNullary() { g_done = true; }
-
-class VoidNullaryFunctor {
- public:
-  void operator()() { g_done = true; }
-};
-
-bool Unary(int x) { return x < 0; }
-
-const char* Plus1(const char* s) { return s + 1; }
-
-void VoidUnary(int /* n */) { g_done = true; }
-
-bool ByConstRef(const string& s) { return s == "Hi"; }
-
-const double g_double = 0;
-bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
-
-string ByNonConstRef(string& s) { return s += "+"; }  // NOLINT
-
-struct UnaryFunctor {
-  int operator()(bool x) { return x ? 1 : -1; }
-};
-
-const char* Binary(const char* input, short n) { return input + n; }  // NOLINT
-
-void VoidBinary(int, char) { g_done = true; }
-
-int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT
-
-void VoidTernary(int, char, bool) { g_done = true; }
-
-int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
-
-int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }
-
-void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
-
-string Concat4(const char* s1, const char* s2, const char* s3,
-               const char* s4) {
-  return string(s1) + s2 + s3 + s4;
-}
-
-int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
-
-struct SumOf5Functor {
-  int operator()(int a, int b, int c, int d, int e) {
-    return a + b + c + d + e;
-  }
-};
-
-string Concat5(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5) {
-  return string(s1) + s2 + s3 + s4 + s5;
-}
-
-int SumOf6(int a, int b, int c, int d, int e, int f) {
-  return a + b + c + d + e + f;
-}
-
-struct SumOf6Functor {
-  int operator()(int a, int b, int c, int d, int e, int f) {
-    return a + b + c + d + e + f;
-  }
-};
-
-string Concat6(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6;
-}
-
-string Concat7(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6,
-               const char* s7) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
-}
-
-string Concat8(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6,
-               const char* s7, const char* s8) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
-}
-
-string Concat9(const char* s1, const char* s2, const char* s3,
-               const char* s4, const char* s5, const char* s6,
-               const char* s7, const char* s8, const char* s9) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
-}
-
-string Concat10(const char* s1, const char* s2, const char* s3,
-                const char* s4, const char* s5, const char* s6,
-                const char* s7, const char* s8, const char* s9,
-                const char* s10) {
-  return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
-}
-
-class Foo {
- public:
-  Foo() : value_(123) {}
-
-  int Nullary() const { return value_; }
-
-  short Unary(long x) { return static_cast<short>(value_ + x); }  // NOLINT
-
-  string Binary(const string& str, char c) const { return str + c; }
-
-  int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
-
-  int SumOf4(int a, int b, int c, int d) const {
-    return a + b + c + d + value_;
-  }
-
-  int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; }
-
-  int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
-
-  int SumOf6(int a, int b, int c, int d, int e, int f) {
-    return a + b + c + d + e + f;
-  }
-
-  string Concat7(const char* s1, const char* s2, const char* s3,
-                 const char* s4, const char* s5, const char* s6,
-                 const char* s7) {
-    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
-  }
-
-  string Concat8(const char* s1, const char* s2, const char* s3,
-                 const char* s4, const char* s5, const char* s6,
-                 const char* s7, const char* s8) {
-    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
-  }
-
-  string Concat9(const char* s1, const char* s2, const char* s3,
-                 const char* s4, const char* s5, const char* s6,
-                 const char* s7, const char* s8, const char* s9) {
-    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
-  }
-
-  string Concat10(const char* s1, const char* s2, const char* s3,
-                  const char* s4, const char* s5, const char* s6,
-                  const char* s7, const char* s8, const char* s9,
-                  const char* s10) {
-    return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
-  }
-
- private:
-  int value_;
-};
-
-// Tests using Invoke() with a nullary function.
-TEST(InvokeTest, Nullary) {
-  Action<int()> a = Invoke(Nullary);  // NOLINT
-  EXPECT_EQ(1, a.Perform(make_tuple()));
-}
-
-// Tests using Invoke() with a unary function.
-TEST(InvokeTest, Unary) {
-  Action<bool(int)> a = Invoke(Unary);  // NOLINT
-  EXPECT_FALSE(a.Perform(make_tuple(1)));
-  EXPECT_TRUE(a.Perform(make_tuple(-1)));
-}
-
-// Tests using Invoke() with a binary function.
-TEST(InvokeTest, Binary) {
-  Action<const char*(const char*, short)> a = Invoke(Binary);  // NOLINT
-  const char* p = "Hello";
-  EXPECT_EQ(p + 2, a.Perform(make_tuple(p, Short(2))));
-}
-
-// Tests using Invoke() with a ternary function.
-TEST(InvokeTest, Ternary) {
-  Action<int(int, char, short)> a = Invoke(Ternary);  // NOLINT
-  EXPECT_EQ(6, a.Perform(make_tuple(1, '\2', Short(3))));
-}
-
-// Tests using Invoke() with a 4-argument function.
-TEST(InvokeTest, FunctionThatTakes4Arguments) {
-  Action<int(int, int, int, int)> a = Invoke(SumOf4);  // NOLINT
-  EXPECT_EQ(1234, a.Perform(make_tuple(1000, 200, 30, 4)));
-}
-
-// Tests using Invoke() with a 5-argument function.
-TEST(InvokeTest, FunctionThatTakes5Arguments) {
-  Action<int(int, int, int, int, int)> a = Invoke(SumOf5);  // NOLINT
-  EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5)));
-}
-
-// Tests using Invoke() with a 6-argument function.
-TEST(InvokeTest, FunctionThatTakes6Arguments) {
-  Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6);  // NOLINT
-  EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6)));
-}
-
-// A helper that turns the type of a C-string literal from const
-// char[N] to const char*.
-inline const char* CharPtr(const char* s) { return s; }
-
-// Tests using Invoke() with a 7-argument function.
-TEST(InvokeTest, FunctionThatTakes7Arguments) {
-  Action<string(const char*, const char*, const char*, const char*,
-                const char*, const char*, const char*)> a =
-      Invoke(Concat7);
-  EXPECT_EQ("1234567",
-            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
-                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
-                                 CharPtr("7"))));
-}
-
-// Tests using Invoke() with a 8-argument function.
-TEST(InvokeTest, FunctionThatTakes8Arguments) {
-  Action<string(const char*, const char*, const char*, const char*,
-                const char*, const char*, const char*, const char*)> a =
-      Invoke(Concat8);
-  EXPECT_EQ("12345678",
-            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
-                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
-                                 CharPtr("7"), CharPtr("8"))));
-}
-
-// Tests using Invoke() with a 9-argument function.
-TEST(InvokeTest, FunctionThatTakes9Arguments) {
-  Action<string(const char*, const char*, const char*, const char*,
-                const char*, const char*, const char*, const char*,
-                const char*)> a = Invoke(Concat9);
-  EXPECT_EQ("123456789",
-            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
-                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
-                                 CharPtr("7"), CharPtr("8"), CharPtr("9"))));
-}
-
-// Tests using Invoke() with a 10-argument function.
-TEST(InvokeTest, FunctionThatTakes10Arguments) {
-  Action<string(const char*, const char*, const char*, const char*,
-                const char*, const char*, const char*, const char*,
-                const char*, const char*)> a = Invoke(Concat10);
-  EXPECT_EQ("1234567890",
-            a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
-                                 CharPtr("4"), CharPtr("5"), CharPtr("6"),
-                                 CharPtr("7"), CharPtr("8"), CharPtr("9"),
-                                 CharPtr("0"))));
-}
-
-// Tests using Invoke() with functions with parameters declared as Unused.
-TEST(InvokeTest, FunctionWithUnusedParameters) {
-  Action<int(int, int, double, const string&)> a1 =
-      Invoke(SumOfFirst2);
-  EXPECT_EQ(12, a1.Perform(make_tuple(10, 2, 5.6, string("hi"))));
-
-  Action<int(int, int, bool, int*)> a2 =
-      Invoke(SumOfFirst2);
-  EXPECT_EQ(23, a2.Perform(make_tuple(20, 3, true, static_cast<int*>(NULL))));
-}
-
-// Tests using Invoke() with methods with parameters declared as Unused.
-TEST(InvokeTest, MethodWithUnusedParameters) {
-  Foo foo;
-  Action<int(string, bool, int, int)> a1 =
-      Invoke(&foo, &Foo::SumOfLast2);
-  EXPECT_EQ(12, a1.Perform(make_tuple(CharPtr("hi"), true, 10, 2)));
-
-  Action<int(char, double, int, int)> a2 =
-      Invoke(&foo, &Foo::SumOfLast2);
-  EXPECT_EQ(23, a2.Perform(make_tuple('a', 2.5, 20, 3)));
-}
-
-// Tests using Invoke() with a functor.
-TEST(InvokeTest, Functor) {
-  Action<long(long, int)> a = Invoke(plus<long>());  // NOLINT
-  EXPECT_EQ(3L, a.Perform(make_tuple(1, 2)));
-}
-
-// Tests using Invoke(f) as an action of a compatible type.
-TEST(InvokeTest, FunctionWithCompatibleType) {
-  Action<long(int, short, char, bool)> a = Invoke(SumOf4);  // NOLINT
-  EXPECT_EQ(4321, a.Perform(make_tuple(4000, Short(300), Char(20), true)));
-}
-
-// Tests using Invoke() with an object pointer and a method pointer.
-
-// Tests using Invoke() with a nullary method.
-TEST(InvokeMethodTest, Nullary) {
-  Foo foo;
-  Action<int()> a = Invoke(&foo, &Foo::Nullary);  // NOLINT
-  EXPECT_EQ(123, a.Perform(make_tuple()));
-}
-
-// Tests using Invoke() with a unary method.
-TEST(InvokeMethodTest, Unary) {
-  Foo foo;
-  Action<short(long)> a = Invoke(&foo, &Foo::Unary);  // NOLINT
-  EXPECT_EQ(4123, a.Perform(make_tuple(4000)));
-}
-