Revved to chromium 2a04445358913b81ed786927172647b701b73113 refs/remotes/origin/HEAD
diff --git a/DEPS b/DEPS
index b1d7a9d..d60f4db 100644
--- a/DEPS
+++ b/DEPS
@@ -30,7 +30,7 @@
   'skia_git': 'https://skia.googlesource.com',
   'boringssl_git': 'https://boringssl.googlesource.com',
   'sfntly_revision': '1bdaae8fc788a5ac8936d68bf24f37d977a13dac',
-  'skia_revision': '157f36d358814a2235aa6284b78a67b725076063',
+  'skia_revision': '5bb9700b7ef952f2664e059afb4f9f137f7d5a7d',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling Skia
   # and V8 without interference from each other.
@@ -39,7 +39,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling ANGLE
   # and whatever else without interference from each other.
-  "angle_revision": "ed13636ab93755d324d9366b2c41d343ecc5829c",
+  "angle_revision": "5e0c80adc9d9e7b4a7f5c89c4fe21be192c51774",
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling build tools
   # and whatever else without interference from each other.
diff --git a/PRESUBMIT.py b/PRESUBMIT.py
index 6751f06..444f5bb 100644
--- a/PRESUBMIT.py
+++ b/PRESUBMIT.py
@@ -9,10 +9,6 @@
 """
 
 
-import re
-import sys
-
-
 _EXCLUDED_PATHS = (
     r"^breakpad[\\\/].*",
     r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
@@ -517,6 +513,7 @@
   change. Breaking - rules is an error, breaking ! rules is a
   warning.
   """
+  import sys
   # We need to wait until we have an input_api object and use this
   # roundabout construct to import checkdeps because this file is
   # eval-ed and thus doesn't have __file__.
@@ -569,8 +566,8 @@
   """Check that all files have their permissions properly set."""
   if input_api.platform == 'win32':
     return []
-  args = [sys.executable, 'tools/checkperms/checkperms.py', '--root',
-          input_api.change.RepositoryRoot()]
+  args = [input_api.python_executable, 'tools/checkperms/checkperms.py',
+          '--root', input_api.change.RepositoryRoot()]
   for f in input_api.AffectedFiles():
     args += ['--file', f.LocalPath()]
   checkperms = input_api.subprocess.Popen(args,
@@ -969,14 +966,14 @@
 
   for f in input_api.AffectedSourceFiles(source_file_filter):
     contents = input_api.ReadFile(f, 'rb')
-    if re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
+    if input_api.re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
       log_info.append(f.LocalPath())
-    elif re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", contents):
+    elif input_api.re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", contents):
       log_info.append(f.LocalPath())
 
-    if re.search(r"\bprintf\(", contents):
+    if input_api.re.search(r"\bprintf\(", contents):
       printf.append(f.LocalPath())
-    elif re.search(r"\bfprintf\((stdout|stderr)", contents):
+    elif input_api.re.search(r"\bfprintf\((stdout|stderr)", contents):
       printf.append(f.LocalPath())
 
   if log_info:
@@ -1198,6 +1195,7 @@
 
 def _CheckJavaStyle(input_api, output_api):
   """Runs checkstyle on changed java files and returns errors if any exist."""
+  import sys
   original_sys_path = sys.path
   try:
     sys.path = sys.path + [input_api.os_path.join(
@@ -1259,6 +1257,23 @@
               (fpath.LocalPath(), line_num, deprecated_value, value)))
   return results
 
+
+def _CheckForOverrideAndFinalRules(input_api, output_api):
+  """Checks for final and override used as per C++11"""
+  problems = []
+  for f in input_api.AffectedFiles():
+    if (f.LocalPath().endswith(('.cc', '.cpp', '.h', '.mm'))):
+      for line_num, line in f.ChangedContents():
+        if (input_api.re.search(r'\b(FINAL|OVERRIDE)\b', line)):
+          problems.append('    %s:%d' % (f.LocalPath(), line_num))
+
+  if not problems:
+    return []
+  return [output_api.PresubmitError('Use C++11\'s |final| and |override| '
+                                    'rather than FINAL and OVERRIDE.',
+                                    problems)]
+
+
 def _CommonChecks(input_api, output_api):
   """Checks common to both upload and commit."""
   results = []
@@ -1300,6 +1315,7 @@
   results.extend(_CheckNoDeprecatedCSS(input_api, output_api))
   results.extend(_CheckParseErrors(input_api, output_api))
   results.extend(_CheckForIPCRules(input_api, output_api))
+  results.extend(_CheckForOverrideAndFinalRules(input_api, output_api))
 
   if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
     results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
@@ -1453,7 +1469,7 @@
     if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
       for lnum, line in f.ChangedContents():
         # Disallow Foo(*my_scoped_thing.Pass()); See crbug.com/418297.
-        if re.search(r'\*[a-zA-Z0-9_]+\.Pass\(\)', line):
+        if input_api.re.search(r'\*[a-zA-Z0-9_]+\.Pass\(\)', line):
           errors.append(output_api.PresubmitError(
             ('%s:%d uses *foo.Pass() to delete the contents of scoped_ptr. ' +
              'See crbug.com/418297.') % (f.LocalPath(), lnum)))
@@ -1647,6 +1663,7 @@
 
 
 def GetPreferredTryMasters(project, change):
+  import re
   files = change.LocalPaths()
 
   if not files or all(re.search(r'[\\\/]OWNERS$', f) for f in files):
diff --git a/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java b/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java
index a4d8e0b..2af146b 100644
--- a/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java
+++ b/base/android/java/src/org/chromium/base/ApiCompatibilityUtils.java
@@ -85,7 +85,7 @@
     }
 
     /**
-     * @see android.view.View#setTextDirection(int)
+     * @see android.view.View#setTextAlignment(int)
      */
     public static void setTextAlignment(View view, int textAlignment) {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
@@ -96,6 +96,17 @@
     }
 
     /**
+     * @see android.view.View#setTextDirection(int)
+     */
+    public static void setTextDirection(View view, int textDirection) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
+            view.setTextDirection(textDirection);
+        } else {
+            // Do nothing. RTL text isn't supported before JB MR1.
+        }
+    }
+
+    /**
      * @see android.view.ViewGroup.MarginLayoutParams#setMarginEnd(int)
      */
     public static void setMarginEnd(MarginLayoutParams layoutParams, int end) {
diff --git a/base/android/java/src/org/chromium/base/ApplicationStatus.java b/base/android/java/src/org/chromium/base/ApplicationStatus.java
index c706dfd..af02ea2 100644
--- a/base/android/java/src/org/chromium/base/ApplicationStatus.java
+++ b/base/android/java/src/org/chromium/base/ApplicationStatus.java
@@ -114,19 +114,19 @@
 
         application.registerWindowFocusChangedListener(
                 new BaseChromiumApplication.WindowFocusChangedListener() {
-            @Override
-            public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
-                if (!hasFocus || activity == sActivity) return;
+                    @Override
+                    public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
+                        if (!hasFocus || activity == sActivity) return;
 
-                int state = getStateForActivity(activity);
+                        int state = getStateForActivity(activity);
 
-                if (state != ActivityState.DESTROYED && state != ActivityState.STOPPED) {
-                    sActivity = activity;
-                }
+                        if (state != ActivityState.DESTROYED && state != ActivityState.STOPPED) {
+                            sActivity = activity;
+                        }
 
-                // TODO(dtrainor): Notify of active activity change?
-            }
-        });
+                        // TODO(dtrainor): Notify of active activity change?
+                    }
+                });
 
         application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
             @Override
diff --git a/base/android/java/src/org/chromium/base/SecureRandomInitializer.java b/base/android/java/src/org/chromium/base/SecureRandomInitializer.java
new file mode 100644
index 0000000..457e2ef
--- /dev/null
+++ b/base/android/java/src/org/chromium/base/SecureRandomInitializer.java
@@ -0,0 +1,42 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.base;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.security.SecureRandom;
+
+/**
+ * This class contains code to initialize a SecureRandom generator securely on Android platforms
+ * <= 4.3. See
+ * {@link http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html}.
+ */
+public class SecureRandomInitializer {
+    private static final int NUM_RANDOM_BYTES = 16;
+
+    private static byte[] sSeedBytes = new byte[NUM_RANDOM_BYTES];
+
+    /**
+     * Safely initializes the random number generator, by seeding it with data from /dev/urandom.
+     */
+    public static void initialize(SecureRandom generator) throws IOException {
+        FileInputStream fis = null;
+        try {
+            fis = new FileInputStream("/dev/urandom");
+            if (fis.read(sSeedBytes) != sSeedBytes.length) {
+                throw new IOException("Failed to get enough random data.");
+            }
+            generator.setSeed(sSeedBytes);
+        } finally {
+            try {
+                if (fis != null) {
+                    fis.close();
+                }
+            } catch (IOException e) {
+                // Ignore exception closing the device.
+            }
+        }
+    }
+}
diff --git a/base/android/java/src/org/chromium/base/SysUtils.java b/base/android/java/src/org/chromium/base/SysUtils.java
index 1108d9e..eabef61 100644
--- a/base/android/java/src/org/chromium/base/SysUtils.java
+++ b/base/android/java/src/org/chromium/base/SysUtils.java
@@ -106,11 +106,9 @@
         if (CommandLine.isInitialized()) {
             if (CommandLine.getInstance().hasSwitch(BaseSwitches.LOW_END_DEVICE_MODE)) {
                 int mode = Integer.parseInt(CommandLine.getInstance().getSwitchValue(
-                  BaseSwitches.LOW_END_DEVICE_MODE));
-                if (mode == 1)
-                    return true;
-                if (mode == 0)
-                    return false;
+                        BaseSwitches.LOW_END_DEVICE_MODE));
+                if (mode == 1) return true;
+                if (mode == 0) return false;
             }
         }
 
diff --git a/base/android/java/src/org/chromium/base/SystemMessageHandler.java b/base/android/java/src/org/chromium/base/SystemMessageHandler.java
index 42c8987..10f8d55 100644
--- a/base/android/java/src/org/chromium/base/SystemMessageHandler.java
+++ b/base/android/java/src/org/chromium/base/SystemMessageHandler.java
@@ -37,7 +37,7 @@
     private SystemMessageHandler(long messagePumpDelegateNative) {
         mMessagePumpDelegateNative = messagePumpDelegateNative;
         tryEnableSyncBarrierDetection();
-     }
+    }
 
     @Override
     public void handleMessage(Message msg) {
@@ -154,7 +154,7 @@
             disableSyncBarrierDetection();
         }
         return null;
-     }
+    }
 
     @CalledByNative
     private static SystemMessageHandler create(long messagePumpDelegateNative) {
diff --git a/base/android/java/src/org/chromium/base/TraceEvent.java b/base/android/java/src/org/chromium/base/TraceEvent.java
index c7b81ee..b67d32d 100644
--- a/base/android/java/src/org/chromium/base/TraceEvent.java
+++ b/base/android/java/src/org/chromium/base/TraceEvent.java
@@ -175,9 +175,9 @@
      */
     @CalledByNative
     public static void setEnabled(boolean enabled) {
-       sEnabled = enabled;
-       ThreadUtils.getUiThreadLooper().setMessageLogging(
-           enabled ? LooperMonitorHolder.sInstance : null);
+        sEnabled = enabled;
+        ThreadUtils.getUiThreadLooper().setMessageLogging(
+                enabled ? LooperMonitorHolder.sInstance : null);
     }
 
     /**
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderHelper.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderHelper.java
index 6a8f1eb..58198ae 100644
--- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderHelper.java
+++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoaderHelper.java
@@ -238,7 +238,7 @@
             if (files != null) {
                 for (File file : files) {
                     if (!file.delete()) {
-                      Log.e(TAG, "Failed to remove " + file.getAbsolutePath());
+                        Log.e(TAG, "Failed to remove " + file.getAbsolutePath());
                     }
                 }
             }
diff --git a/base/android/java/src/org/chromium/base/library_loader/Linker.java b/base/android/java/src/org/chromium/base/library_loader/Linker.java
index cc30af4..2b3cb09 100644
--- a/base/android/java/src/org/chromium/base/library_loader/Linker.java
+++ b/base/android/java/src/org/chromium/base/library_loader/Linker.java
@@ -755,8 +755,7 @@
 
             String libName = System.mapLibraryName(library);
 
-            if (sLoadedLibraries == null)
-              sLoadedLibraries = new HashMap<String, LibInfo>();
+            if (sLoadedLibraries == null) sLoadedLibraries = new HashMap<String, LibInfo>();
 
             if (sLoadedLibraries.containsKey(libName)) {
                 if (DEBUG) Log.i(TAG, "Not loading " + libName + " twice");
diff --git a/base/android/jni_generator/java/src/org/chromium/example/jni_generator/SampleForTests.java b/base/android/jni_generator/java/src/org/chromium/example/jni_generator/SampleForTests.java
index c3a1df5..732fe6e 100644
--- a/base/android/jni_generator/java/src/org/chromium/example/jni_generator/SampleForTests.java
+++ b/base/android/jni_generator/java/src/org/chromium/example/jni_generator/SampleForTests.java
@@ -91,212 +91,215 @@
 // object binds to.
 @JNINamespace("base::android")
 class SampleForTests {
-  // Classes can store their C++ pointer counter part as an int that is normally initialized by
-  // calling out a nativeInit() function.
-  long mNativeCPPObject;
+    // Classes can store their C++ pointer counter part as an int that is normally initialized by
+    // calling out a nativeInit() function.
+    long mNativeCPPObject;
 
-  // You can define methods and attributes on the java class just like any other.
-  // Methods without the @CalledByNative annotation won't be exposed to JNI.
-  public SampleForTests() {
-  }
+    // You can define methods and attributes on the java class just like any other.
+    // Methods without the @CalledByNative annotation won't be exposed to JNI.
+    public SampleForTests() {
+    }
 
-  public void startExample() {
-      // Calls native code and holds a pointer to the C++ class.
-      mNativeCPPObject = nativeInit("myParam");
-  }
+    public void startExample() {
+        // Calls native code and holds a pointer to the C++ class.
+        mNativeCPPObject = nativeInit("myParam");
+    }
 
-  public void doStuff() {
-      // This will call CPPClass::Method() using nativePtr as a pointer to the object. This must be
-      // done to:
-      // * avoid leaks.
-      // * using finalizers are not allowed to destroy the cpp class.
-      nativeMethod(mNativeCPPObject);
-  }
+    public void doStuff() {
+        // This will call CPPClass::Method() using nativePtr as a pointer to the object. This must
+        // be done to:
+        // * avoid leaks.
+        // * using finalizers are not allowed to destroy the cpp class.
+        nativeMethod(mNativeCPPObject);
+    }
 
-  public void finishExample() {
-      // We're done, so let's destroy nativePtr object.
-      nativeDestroy(mNativeCPPObject);
-  }
+    public void finishExample() {
+        // We're done, so let's destroy nativePtr object.
+        nativeDestroy(mNativeCPPObject);
+    }
 
-  // -----------------------------------------------------------------------------------------------
-  // The following methods demonstrate exporting Java methods for invocation from C++ code.
-  // Java functions are mapping into C global functions by prefixing the method name with
-  // "Java_<Class>_"
-  // This is triggered by the @CalledByNative annotation; the methods may be named as you wish.
+    // ---------------------------------------------------------------------------------------------
+    // The following methods demonstrate exporting Java methods for invocation from C++ code.
+    // Java functions are mapping into C global functions by prefixing the method name with
+    // "Java_<Class>_"
+    // This is triggered by the @CalledByNative annotation; the methods may be named as you wish.
 
-  // Exported to C++ as:
-  //   Java_Example_javaMethod(JNIEnv* env, jobject obj, jint foo, jint bar)
-  // Typically the C++ code would have obtained the jobject via the Init() call described above.
-  @CalledByNative
-  public int javaMethod(int foo,
-                        int bar) {
-      return 0;
-  }
+    // Exported to C++ as:
+    // Java_Example_javaMethod(JNIEnv* env, jobject obj, jint foo, jint bar)
+    // Typically the C++ code would have obtained the jobject via the Init() call described above.
+    @CalledByNative
+    public int javaMethod(int foo, int bar) {
+        return 0;
+    }
 
-  // Exported to C++ as Java_Example_staticJavaMethod(JNIEnv* env)
-  // Note no jobject argument, as it is static.
-  @CalledByNative
-  public static boolean staticJavaMethod() {
-      return true;
-  }
+    // Exported to C++ as Java_Example_staticJavaMethod(JNIEnv* env)
+    // Note no jobject argument, as it is static.
+    @CalledByNative
+    public static boolean staticJavaMethod() {
+        return true;
+    }
 
-  // No prefix, so this method is package private. It will still be exported.
-  @CalledByNative
-  void packagePrivateJavaMethod() {}
+    // No prefix, so this method is package private. It will still be exported.
+    @CalledByNative
+    void packagePrivateJavaMethod() {
+    }
 
-  // Note the "Unchecked" suffix. By default, @CalledByNative will always generate bindings that
-  // call CheckException(). With "@CalledByNativeUnchecked", the client C++ code is responsible to
-  // call ClearException() and act as appropriate.
-  // See more details at the "@CalledByNativeUnchecked" annotation.
-  @CalledByNativeUnchecked
-  void methodThatThrowsException() throws Exception {}
+    // Note the "Unchecked" suffix. By default, @CalledByNative will always generate bindings that
+    // call CheckException(). With "@CalledByNativeUnchecked", the client C++ code is responsible to
+    // call ClearException() and act as appropriate.
+    // See more details at the "@CalledByNativeUnchecked" annotation.
+    @CalledByNativeUnchecked
+    void methodThatThrowsException() throws Exception {}
 
-  // The generator is not confused by inline comments:
-  // @CalledByNative void thisShouldNotAppearInTheOutput();
-  // @CalledByNativeUnchecked public static void neitherShouldThis(int foo);
+    // The generator is not confused by inline comments:
+    // @CalledByNative void thisShouldNotAppearInTheOutput();
+    // @CalledByNativeUnchecked public static void neitherShouldThis(int foo);
 
-  /**
-   * The generator is not confused by block comments:
-   * @CalledByNative void thisShouldNotAppearInTheOutputEither();
-   * @CalledByNativeUnchecked public static void andDefinitelyNotThis(int foo);
-   */
+    /**
+     * The generator is not confused by block comments:
+     * @CalledByNative void thisShouldNotAppearInTheOutputEither();
+     * @CalledByNativeUnchecked public static void andDefinitelyNotThis(int foo);
+     */
 
-  // String constants that look like comments don't confuse the generator:
-  private String mArrgh = "*/*";
+    // String constants that look like comments don't confuse the generator:
+    private String mArrgh = "*/*";
 
-  //------------------------------------------------------------------------------------------------
-  // Java fields which are accessed from C++ code only must be annotated with @AccessedByNative to
-  // prevent them being eliminated when unreferenced code is stripped.
-  @AccessedByNative
-  private int mJavaField;
+    // ---------------------------------------------------------------------------------------------
+    // Java fields which are accessed from C++ code only must be annotated with @AccessedByNative to
+    // prevent them being eliminated when unreferenced code is stripped.
+    @AccessedByNative
+    private int mJavaField;
 
-  //------------------------------------------------------------------------------------------------
-  // The following methods demonstrate declaring methods to call into C++ from Java.
-  // The generator detects the "native" and "static" keywords, the type and name of the first
-  // parameter, and the "native" prefix to the function name to determine the C++ function
-  // signatures. Besides these constraints the methods can be freely named.
+    // ---------------------------------------------------------------------------------------------
+    // The following methods demonstrate declaring methods to call into C++ from Java.
+    // The generator detects the "native" and "static" keywords, the type and name of the first
+    // parameter, and the "native" prefix to the function name to determine the C++ function
+    // signatures. Besides these constraints the methods can be freely named.
 
-  // This declares a C++ function which the application code must implement:
-  //   static jint Init(JNIEnv* env, jobject obj);
-  // The jobject parameter refers back to this java side object instance.
-  // The implementation must return the pointer to the C++ object cast to jint.
-  // The caller of this method should store it, and supply it as a the nativeCPPClass param to
-  // subsequent native method calls (see the methods below that take an "int native..." as first
-  // param).
-  private native long nativeInit(String param);
+    // This declares a C++ function which the application code must implement:
+    // static jint Init(JNIEnv* env, jobject obj);
+    // The jobject parameter refers back to this java side object instance.
+    // The implementation must return the pointer to the C++ object cast to jint.
+    // The caller of this method should store it, and supply it as a the nativeCPPClass param to
+    // subsequent native method calls (see the methods below that take an "int native..." as first
+    // param).
+    private native long nativeInit(String param);
 
-  // This defines a function binding to the associated C++ class member function. The name is
-  // derived from |nativeDestroy| and |nativeCPPClass| to arrive at CPPClass::Destroy() (i.e. native
-  // prefixes stripped).
-  // The |nativeCPPClass| is automatically cast to type CPPClass* in order to obtain the object on
-  // which to invoke the member function.
-  private native void nativeDestroy(long nativeCPPClass);
+    // This defines a function binding to the associated C++ class member function. The name is
+    // derived from |nativeDestroy| and |nativeCPPClass| to arrive at CPPClass::Destroy() (i.e.
+    // native
+    // prefixes stripped).
+    // The |nativeCPPClass| is automatically cast to type CPPClass* in order to obtain the object on
+    // which to invoke the member function.
+    private native void nativeDestroy(long nativeCPPClass);
 
-  // This declares a C++ function which the application code must implement:
-  //   static jdouble GetDoubleFunction(JNIEnv* env, jobject obj);
-  // The jobject parameter refers back to this java side object instance.
-  private native double nativeGetDoubleFunction();
+    // This declares a C++ function which the application code must implement:
+    // static jdouble GetDoubleFunction(JNIEnv* env, jobject obj);
+    // The jobject parameter refers back to this java side object instance.
+    private native double nativeGetDoubleFunction();
 
-  // Similar to nativeGetDoubleFunction(), but here the C++ side will receive a jclass rather than
-  // jobject param, as the function is declared static.
-  private static native float nativeGetFloatFunction();
+    // Similar to nativeGetDoubleFunction(), but here the C++ side will receive a jclass rather than
+    // jobject param, as the function is declared static.
+    private static native float nativeGetFloatFunction();
 
-  // This function takes a non-POD datatype. We have a list mapping them to their full classpath in
-  // jni_generator.py JavaParamToJni. If you require a new datatype, make sure you add to that
-  // function.
-  private native void nativeSetNonPODDatatype(Rect rect);
+    // This function takes a non-POD datatype. We have a list mapping them to their full classpath
+    // in
+    // jni_generator.py JavaParamToJni. If you require a new datatype, make sure you add to that
+    // function.
+    private native void nativeSetNonPODDatatype(Rect rect);
 
-  // This declares a C++ function which the application code must implement:
-  //   static ScopedJavaLocalRef<jobject> GetNonPODDatatype(JNIEnv* env, jobject obj);
-  // The jobject parameter refers back to this java side object instance.
-  // Note that it returns a ScopedJavaLocalRef<jobject> so that you don' have to worry about
-  // deleting the JNI local reference.  This is similar with Strings and arrays.
-  private native Object nativeGetNonPODDatatype();
+    // This declares a C++ function which the application code must implement:
+    // static ScopedJavaLocalRef<jobject> GetNonPODDatatype(JNIEnv* env, jobject obj);
+    // The jobject parameter refers back to this java side object instance.
+    // Note that it returns a ScopedJavaLocalRef<jobject> so that you don' have to worry about
+    // deleting the JNI local reference. This is similar with Strings and arrays.
+    private native Object nativeGetNonPODDatatype();
 
-  // Similar to nativeDestroy above, this will cast nativeCPPClass into pointer of CPPClass type and
-  // call its Method member function.
-  private native int nativeMethod(long nativeCPPClass);
+    // Similar to nativeDestroy above, this will cast nativeCPPClass into pointer of CPPClass type
+    // and
+    // call its Method member function.
+    private native int nativeMethod(long nativeCPPClass);
 
-  // Similar to nativeMethod above, but here the C++ fully qualified class name is taken from the
-  // annotation rather than parameter name, which can thus be chosen freely.
-  @NativeClassQualifiedName("CPPClass::InnerClass")
-  private native double nativeMethodOtherP0(long nativePtr);
+    // Similar to nativeMethod above, but here the C++ fully qualified class name is taken from the
+    // annotation rather than parameter name, which can thus be chosen freely.
+    @NativeClassQualifiedName("CPPClass::InnerClass")
+    private native double nativeMethodOtherP0(long nativePtr);
 
-  // This "struct" will be created by the native side using |createInnerStructA|,
-  // and used by the java-side somehow.
-  // Note that |@CalledByNative| has to contain the inner class name.
-  static class InnerStructA {
-      private final long mLong;
-      private final int mInt;
-      private final String mString;
+    // This "struct" will be created by the native side using |createInnerStructA|,
+    // and used by the java-side somehow.
+    // Note that |@CalledByNative| has to contain the inner class name.
+    static class InnerStructA {
+        private final long mLong;
+        private final int mInt;
+        private final String mString;
 
-      private InnerStructA(long l, int i, String s) {
-          mLong = l;
-          mInt = i;
-          mString = s;
-      }
+        private InnerStructA(long l, int i, String s) {
+            mLong = l;
+            mInt = i;
+            mString = s;
+        }
 
-      @CalledByNative("InnerStructA")
-      private static InnerStructA create(long l, int i, String s) {
-          return new InnerStructA(l, i, s);
-      }
-  }
+        @CalledByNative("InnerStructA")
+        private static InnerStructA create(long l, int i, String s) {
+            return new InnerStructA(l, i, s);
+        }
+    }
 
-  private List<InnerStructA> mListInnerStructA = new ArrayList<InnerStructA>();
+    private List<InnerStructA> mListInnerStructA = new ArrayList<InnerStructA>();
 
-  @CalledByNative
-  private void addStructA(InnerStructA a) {
-      // Called by the native side to append another element.
-      mListInnerStructA.add(a);
-  }
+    @CalledByNative
+    private void addStructA(InnerStructA a) {
+        // Called by the native side to append another element.
+        mListInnerStructA.add(a);
+    }
 
-  @CalledByNative
-  private void iterateAndDoSomething() {
-      Iterator<InnerStructA> it = mListInnerStructA.iterator();
-      while (it.hasNext()) {
-          InnerStructA element = it.next();
-          // Now, do something with element.
-      }
-      // Done, clear the list.
-      mListInnerStructA.clear();
-  }
+    @CalledByNative
+    private void iterateAndDoSomething() {
+        Iterator<InnerStructA> it = mListInnerStructA.iterator();
+        while (it.hasNext()) {
+            InnerStructA element = it.next();
+            // Now, do something with element.
+        }
+        // Done, clear the list.
+        mListInnerStructA.clear();
+    }
 
-  // This "struct" will be created by the java side passed to native, which
-  // will use its getters.
-  // Note that |@CalledByNative| has to contain the inner class name.
-  static class InnerStructB {
-      private final long mKey;
-      private final String mValue;
+    // This "struct" will be created by the java side passed to native, which
+    // will use its getters.
+    // Note that |@CalledByNative| has to contain the inner class name.
+    static class InnerStructB {
+        private final long mKey;
+        private final String mValue;
 
-      private InnerStructB(long k, String v) {
-          mKey = k;
-          mValue = v;
-      }
+        private InnerStructB(long k, String v) {
+            mKey = k;
+            mValue = v;
+        }
 
-      @CalledByNative("InnerStructB")
-      private long getKey() {
-          return mKey;
-      }
+        @CalledByNative("InnerStructB")
+        private long getKey() {
+            return mKey;
+        }
 
-      @CalledByNative("InnerStructB")
-      private String getValue() {
-          return mValue;
-      }
-  }
+        @CalledByNative("InnerStructB")
+        private String getValue() {
+            return mValue;
+        }
+    }
 
-  List<InnerStructB> mListInnerStructB = new ArrayList<InnerStructB>();
+    List<InnerStructB> mListInnerStructB = new ArrayList<InnerStructB>();
 
-  void iterateAndDoSomethingWithMap() {
-      Iterator<InnerStructB> it = mListInnerStructB.iterator();
-      while (it.hasNext()) {
-          InnerStructB element = it.next();
-          // Now, do something with element.
-          nativeAddStructB(mNativeCPPObject, element);
-      }
-      nativeIterateAndDoSomethingWithStructB(mNativeCPPObject);
-  }
+    void iterateAndDoSomethingWithMap() {
+        Iterator<InnerStructB> it = mListInnerStructB.iterator();
+        while (it.hasNext()) {
+            InnerStructB element = it.next();
+            // Now, do something with element.
+            nativeAddStructB(mNativeCPPObject, element);
+        }
+        nativeIterateAndDoSomethingWithStructB(mNativeCPPObject);
+    }
 
-  native void nativeAddStructB(long nativeCPPClass, InnerStructB b);
-  native void nativeIterateAndDoSomethingWithStructB(long nativeCPPClass);
-  native String nativeReturnAString(long nativeCPPClass);
+    native void nativeAddStructB(long nativeCPPClass, InnerStructB b);
+    native void nativeIterateAndDoSomethingWithStructB(long nativeCPPClass);
+    native String nativeReturnAString(long nativeCPPClass);
 }
diff --git a/base/base.isolate b/base/base.isolate
index 762d915..0416935 100644
--- a/base/base.isolate
+++ b/base/base.isolate
@@ -23,12 +23,18 @@
         ],
       },
     }],
+    ['OS=="linux" and asan==1', {
+      'variables': {
+        'files': [
+          '../third_party/llvm-build/Release+Asserts/lib/libstdc++.so.6',
+        ],
+      },
+    }],
     ['asan==1', {
       'variables': {
         'files': [
           '../tools/valgrind/asan/',
           '../third_party/llvm-build/Release+Asserts/bin/llvm-symbolizer',
-          '../third_party/llvm-build/Release+Asserts/lib/libstdc++.so.6',
         ],
       },
     }],
diff --git a/base/debug/proc_maps_linux_unittest.cc b/base/debug/proc_maps_linux_unittest.cc
index fc8ced6..4be5a0f 100644
--- a/base/debug/proc_maps_linux_unittest.cc
+++ b/base/debug/proc_maps_linux_unittest.cc
@@ -167,7 +167,7 @@
          MappedMemoryRegion::EXECUTE | MappedMemoryRegion::PRIVATE},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     SCOPED_TRACE(
         base::StringPrintf("kTestCases[%zu] = %s", i, kTestCases[i].input));
 
diff --git a/base/debug/stack_trace_posix.cc b/base/debug/stack_trace_posix.cc
index ae40d7c..25acbe0 100644
--- a/base/debug/stack_trace_posix.cc
+++ b/base/debug/stack_trace_posix.cc
@@ -343,7 +343,7 @@
   const int kRegisterPadding = 16;
 #endif
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(registers); i++) {
+  for (size_t i = 0; i < arraysize(registers); i++) {
     PrintToStderr(registers[i].label);
     internal::itoa_r(registers[i].value, buf, sizeof(buf),
                      16, kRegisterPadding);
diff --git a/base/files/file_proxy_unittest.cc b/base/files/file_proxy_unittest.cc
index 0034a1c..b5ed395 100644
--- a/base/files/file_proxy_unittest.cc
+++ b/base/files/file_proxy_unittest.cc
@@ -267,7 +267,7 @@
   CreateProxy(File::FLAG_CREATE | File::FLAG_WRITE, &proxy);
 
   const char data[] = "foo!";
-  int data_bytes = ARRAYSIZE_UNSAFE(data);
+  int data_bytes = arraysize(data);
   proxy.Write(0, data, data_bytes,
               Bind(&FileProxyTest::DidWrite, weak_factory_.GetWeakPtr()));
   MessageLoop::current()->Run();
diff --git a/base/i18n/icu_string_conversions_unittest.cc b/base/i18n/icu_string_conversions_unittest.cc
index 04c3b92..107e240 100644
--- a/base/i18n/icu_string_conversions_unittest.cc
+++ b/base/i18n/icu_string_conversions_unittest.cc
@@ -234,7 +234,7 @@
 };
 
 TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndWide) {
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertCodepageCases); ++i) {
+  for (size_t i = 0; i < arraysize(kConvertCodepageCases); ++i) {
     SCOPED_TRACE(base::StringPrintf(
                      "Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i,
                      kConvertCodepageCases[i].encoded,
@@ -301,7 +301,7 @@
 }
 
 TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndUTF16) {
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertCodepageCases); ++i) {
+  for (size_t i = 0; i < arraysize(kConvertCodepageCases); ++i) {
     SCOPED_TRACE(base::StringPrintf(
                      "Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i,
                      kConvertCodepageCases[i].encoded,
@@ -355,7 +355,7 @@
 };
 TEST(ICUStringConversionsTest, ConvertToUtf8AndNormalize) {
   std::string result;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertAndNormalizeCases); ++i) {
+  for (size_t i = 0; i < arraysize(kConvertAndNormalizeCases); ++i) {
     SCOPED_TRACE(base::StringPrintf(
                      "Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i,
                      kConvertAndNormalizeCases[i].encoded,
diff --git a/base/i18n/number_formatting_unittest.cc b/base/i18n/number_formatting_unittest.cc
index da6397d..3b0718d 100644
--- a/base/i18n/number_formatting_unittest.cc
+++ b/base/i18n/number_formatting_unittest.cc
@@ -27,7 +27,7 @@
     {-42, "-42", "-42"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     i18n::SetICUDefaultLocale("en");
     testing::ResetFormatters();
     EXPECT_EQ(cases[i].expected_english,
@@ -72,7 +72,7 @@
     {-42.7, 3, "-42.700", "-42,700"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     i18n::SetICUDefaultLocale("en");
     testing::ResetFormatters();
     EXPECT_EQ(cases[i].expected_english,
diff --git a/base/i18n/rtl_unittest.cc b/base/i18n/rtl_unittest.cc
index 2d923ac..87ac87d 100644
--- a/base/i18n/rtl_unittest.cc
+++ b/base/i18n/rtl_unittest.cc
@@ -96,7 +96,7 @@
       LEFT_TO_RIGHT },
    };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].direction,
               GetFirstStrongCharacterDirection(WideToUTF16(cases[i].text)));
 }
@@ -158,7 +158,7 @@
       LEFT_TO_RIGHT },
    };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].direction,
               GetLastStrongCharacterDirection(WideToUTF16(cases[i].text)));
 }
@@ -236,7 +236,7 @@
       LEFT_TO_RIGHT },
    };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].direction,
               GetStringDirection(WideToUTF16(cases[i].text)));
 }
@@ -355,7 +355,7 @@
   for (size_t i = 0; i < 2; ++i) {
     // Toggle the application default text direction (to try each direction).
     SetRTL(!IsRTL());
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+    for (size_t i = 0; i < arraysize(cases); ++i) {
       string16 input = WideToUTF16(cases[i].path);
       string16 output = GetDisplayStringInLTRDirectionality(input);
       // Test the expected wrapping behavior for the current UI directionality.
diff --git a/base/json/string_escape_unittest.cc b/base/json/string_escape_unittest.cc
index 7d82f9b..3eb4e8e 100644
--- a/base/json/string_escape_unittest.cc
+++ b/base/json/string_escape_unittest.cc
@@ -23,7 +23,7 @@
     {"c<>d", "c\\u003C>d"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     const char* in_ptr = cases[i].to_escape;
     std::string in_str = in_ptr;
 
@@ -81,7 +81,7 @@
     {L"c<>d", "c\\u003C>d"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     string16 in = WideToUTF16(cases[i].to_escape);
 
     std::string out;
@@ -162,7 +162,7 @@
     {"\xe5\xc4\x4f\x05\xb6\xfd\0", "\\u00E5\\u00C4O\\u0005\\u00B6\\u00FD"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::string in = std::string(cases[i].to_escape);
     EXPECT_FALSE(IsStringUTF8(in));
 
@@ -173,7 +173,7 @@
   }
 
   const char kEmbedNull[] = { '\xab', '\x39', '\0', '\x9f', '\xab' };
-  std::string in(kEmbedNull, ARRAYSIZE_UNSAFE(kEmbedNull));
+  std::string in(kEmbedNull, arraysize(kEmbedNull));
   EXPECT_FALSE(IsStringUTF8(in));
   EXPECT_EQ(std::string("\\u00AB9\\u0000\\u009F\\u00AB"),
             EscapeBytesAsInvalidJSONString(in, false));
diff --git a/base/mac/mac_util_unittest.mm b/base/mac/mac_util_unittest.mm
index aae40a6..6a1acb3 100644
--- a/base/mac/mac_util_unittest.mm
+++ b/base/mac/mac_util_unittest.mm
@@ -92,7 +92,7 @@
     { "/Applications/Google Foo.app/bar/Foo Helper.app/quux/Foo Helper",
         "/Applications/Google Foo.app" },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(valid_inputs); i++) {
+  for (size_t i = 0; i < arraysize(valid_inputs); i++) {
     out = GetAppBundlePath(FilePath(valid_inputs[i].in));
     EXPECT_FALSE(out.empty()) << "loop: " << i;
     EXPECT_STREQ(valid_inputs[i].expected_out,
diff --git a/base/memory/discardable_memory_emulated.cc b/base/memory/discardable_memory_emulated.cc
index f9097b1..9820e2e 100644
--- a/base/memory/discardable_memory_emulated.cc
+++ b/base/memory/discardable_memory_emulated.cc
@@ -15,16 +15,31 @@
 const size_t kEmulatedSoftMemoryLimit = 32 * 1024 * 1024;
 const size_t kEmulatedHardMemoryLimitExpirationTimeMs = 1000;
 
-struct SharedState {
-  SharedState()
-      : manager(kEmulatedMemoryLimit,
-                kEmulatedSoftMemoryLimit,
-                TimeDelta::FromMilliseconds(
-                    kEmulatedHardMemoryLimitExpirationTimeMs)) {}
+// internal::DiscardableMemoryManager has an explicit constructor that takes
+// a number of memory limit parameters. The LeakyLazyInstanceTraits doesn't
+// handle the case. Thus, we need our own class here.
+struct DiscardableMemoryManagerLazyInstanceTraits {
+  // Leaky as discardable memory clients can use this after the exit handler
+  // has been called.
+  static const bool kRegisterOnExit = false;
+#ifndef NDEBUG
+  static const bool kAllowedToAccessOnNonjoinableThread = true;
+#endif
 
-  internal::DiscardableMemoryManager manager;
+  static internal::DiscardableMemoryManager* New(void* instance) {
+    return new (instance) internal::DiscardableMemoryManager(
+        kEmulatedMemoryLimit,
+        kEmulatedSoftMemoryLimit,
+        TimeDelta::FromMilliseconds(kEmulatedHardMemoryLimitExpirationTimeMs));
+  }
+  static void Delete(internal::DiscardableMemoryManager* instance) {
+    instance->~DiscardableMemoryManager();
+  }
 };
-LazyInstance<SharedState>::Leaky g_shared_state = LAZY_INSTANCE_INITIALIZER;
+
+LazyInstance<internal::DiscardableMemoryManager,
+             DiscardableMemoryManagerLazyInstanceTraits>
+    g_manager = LAZY_INSTANCE_INITIALIZER;
 
 }  // namespace
 
@@ -33,29 +48,29 @@
 DiscardableMemoryEmulated::DiscardableMemoryEmulated(size_t bytes)
     : bytes_(bytes),
       is_locked_(false) {
-  g_shared_state.Pointer()->manager.Register(this, bytes);
+  g_manager.Pointer()->Register(this, bytes);
 }
 
 DiscardableMemoryEmulated::~DiscardableMemoryEmulated() {
   if (is_locked_)
     Unlock();
-  g_shared_state.Pointer()->manager.Unregister(this);
+  g_manager.Pointer()->Unregister(this);
 }
 
 // static
 bool DiscardableMemoryEmulated::ReduceMemoryUsage() {
-  return g_shared_state.Pointer()->manager.ReduceMemoryUsage();
+  return g_manager.Pointer()->ReduceMemoryUsage();
 }
 
 // static
 void DiscardableMemoryEmulated::ReduceMemoryUsageUntilWithinLimit(
     size_t bytes) {
-  g_shared_state.Pointer()->manager.ReduceMemoryUsageUntilWithinLimit(bytes);
+  g_manager.Pointer()->ReduceMemoryUsageUntilWithinLimit(bytes);
 }
 
 // static
 void DiscardableMemoryEmulated::PurgeForTesting() {
-  g_shared_state.Pointer()->manager.PurgeAll();
+  g_manager.Pointer()->PurgeAll();
 }
 
 bool DiscardableMemoryEmulated::Initialize() {
@@ -66,7 +81,7 @@
   DCHECK(!is_locked_);
 
   bool purged = false;
-  if (!g_shared_state.Pointer()->manager.AcquireLock(this, &purged))
+  if (!g_manager.Pointer()->AcquireLock(this, &purged))
     return DISCARDABLE_MEMORY_LOCK_STATUS_FAILED;
 
   is_locked_ = true;
@@ -76,7 +91,7 @@
 
 void DiscardableMemoryEmulated::Unlock() {
   DCHECK(is_locked_);
-  g_shared_state.Pointer()->manager.ReleaseLock(this);
+  g_manager.Pointer()->ReleaseLock(this);
   is_locked_ = false;
 }
 
diff --git a/base/memory/discardable_memory_mach.cc b/base/memory/discardable_memory_mach.cc
index 1051569..c6681b1 100644
--- a/base/memory/discardable_memory_mach.cc
+++ b/base/memory/discardable_memory_mach.cc
@@ -19,13 +19,29 @@
 // address space usage gets too high (e.g. 512 MBytes).
 const size_t kMachMemoryLimit = 512 * 1024 * 1024;
 
-struct SharedState {
-  SharedState()
-      : manager(kMachMemoryLimit, kMachMemoryLimit, TimeDelta::Max()) {}
+// internal::DiscardableMemoryManager has an explicit constructor that takes
+// a number of memory limit parameters. The LeakyLazyInstanceTraits doesn't
+// handle the case. Thus, we need our own class here.
+struct DiscardableMemoryManagerLazyInstanceTraits {
+  // Leaky as discardable memory clients can use this after the exit handler
+  // has been called.
+  static const bool kRegisterOnExit = false;
+#ifndef NDEBUG
+  static const bool kAllowedToAccessOnNonjoinableThread = true;
+#endif
 
-  internal::DiscardableMemoryManager manager;
+  static internal::DiscardableMemoryManager* New(void* instance) {
+    return new (instance) internal::DiscardableMemoryManager(
+        kMachMemoryLimit, kMachMemoryLimit, TimeDelta::Max());
+  }
+  static void Delete(internal::DiscardableMemoryManager* instance) {
+    instance->~DiscardableMemoryManager();
+  }
 };
-LazyInstance<SharedState>::Leaky g_shared_state = LAZY_INSTANCE_INITIALIZER;
+
+LazyInstance<internal::DiscardableMemoryManager,
+             DiscardableMemoryManagerLazyInstanceTraits>
+    g_manager = LAZY_INSTANCE_INITIALIZER;
 
 // The VM subsystem allows tagging of memory and 240-255 is reserved for
 // application use (see mach/vm_statistics.h). Pick 252 (after chromium's atomic
@@ -38,13 +54,13 @@
 
 DiscardableMemoryMach::DiscardableMemoryMach(size_t bytes)
     : memory_(0, 0), bytes_(mach_vm_round_page(bytes)), is_locked_(false) {
-  g_shared_state.Pointer()->manager.Register(this, bytes);
+  g_manager.Pointer()->Register(this, bytes);
 }
 
 DiscardableMemoryMach::~DiscardableMemoryMach() {
   if (is_locked_)
     Unlock();
-  g_shared_state.Pointer()->manager.Unregister(this);
+  g_manager.Pointer()->Unregister(this);
 }
 
 // static
@@ -61,7 +77,7 @@
   DCHECK(!is_locked_);
 
   bool purged = false;
-  if (!g_shared_state.Pointer()->manager.AcquireLock(this, &purged))
+  if (!g_manager.Pointer()->AcquireLock(this, &purged))
     return DISCARDABLE_MEMORY_LOCK_STATUS_FAILED;
 
   is_locked_ = true;
@@ -71,7 +87,7 @@
 
 void DiscardableMemoryMach::Unlock() {
   DCHECK(is_locked_);
-  g_shared_state.Pointer()->manager.ReleaseLock(this);
+  g_manager.Pointer()->ReleaseLock(this);
   is_locked_ = false;
 }
 
diff --git a/base/memory/discardable_memory_unittest.cc b/base/memory/discardable_memory_unittest.cc
index a111cfc..2bdc079 100644
--- a/base/memory/discardable_memory_unittest.cc
+++ b/base/memory/discardable_memory_unittest.cc
@@ -65,13 +65,13 @@
   const scoped_ptr<DiscardableMemory> memory(CreateLockedMemory(kSize));
   ASSERT_TRUE(memory);
   void* addr = memory->Memory();
-  ASSERT_NE(static_cast<void*>(NULL), addr);
+  ASSERT_NE(nullptr, addr);
 
   memory->Unlock();
 
   EXPECT_NE(DISCARDABLE_MEMORY_LOCK_STATUS_FAILED, memory->Lock());
   addr = memory->Memory();
-  ASSERT_NE(static_cast<void*>(NULL), addr);
+  ASSERT_NE(nullptr, addr);
 
   memory->Unlock();
 }
diff --git a/base/metrics/field_trial_unittest.cc b/base/metrics/field_trial_unittest.cc
index b3a6eb3..b474ddb 100644
--- a/base/metrics/field_trial_unittest.cc
+++ b/base/metrics/field_trial_unittest.cc
@@ -963,7 +963,7 @@
     { 0.95, kDefaultGroupName },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     TestFieldTrialObserver observer;
     scoped_refptr<FieldTrial> trial(
        FieldTrial::CreateSimulatedFieldTrial(kTrialName, 100, kDefaultGroupName,
diff --git a/base/strings/OWNERS b/base/strings/OWNERS
index d6f2324..5381872 100644
--- a/base/strings/OWNERS
+++ b/base/strings/OWNERS
@@ -1 +1,2 @@
-per-file safe_sprintf*=markus@chromium.org
+per-file safe_sprintf*=jln@chromium.org
+per-file safe_sprintf*=mdempsky@chromium.org
diff --git a/base/strings/safe_sprintf.h b/base/strings/safe_sprintf.h
index cbd7d0c..2d17320 100644
--- a/base/strings/safe_sprintf.h
+++ b/base/strings/safe_sprintf.h
@@ -218,220 +218,20 @@
 
 }  // namespace internal
 
-// TODO(markus): C++11 has a much more concise and readable solution for
-//   expressing what we are doing here.
-
-template<class T0, class T1, class T2, class T3, class T4,
-         class T5, class T6, class T7, class T8, class T9>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                     T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
+template<typename... Args>
+ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args... args) {
   // Use Arg() object to record type information and then copy arguments to an
   // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
+  const internal::Arg arg_array[] = { args... };
+  return internal::SafeSNPrintf(buf, N, fmt, arg_array, sizeof...(args));
 }
 
-template<size_t N,
-         class T0, class T1, class T2, class T3, class T4,
-         class T5, class T6, class T7, class T8, class T9>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
-                    T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                    T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) {
+template<size_t N, typename... Args>
+ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, Args... args) {
   // Use Arg() object to record type information and then copy arguments to an
   // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2, class T3, class T4,
-         class T5, class T6, class T7, class T8>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                     T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N,
-         class T0, class T1, class T2, class T3, class T4, class T5,
-         class T6, class T7, class T8>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
-                    T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                    T5 arg5, T6 arg6, T7 arg7, T8 arg8) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2, class T3, class T4, class T5,
-         class T6, class T7>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                     T5 arg5, T6 arg6, T7 arg7) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N,
-         class T0, class T1, class T2, class T3, class T4, class T5,
-         class T6, class T7>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
-                    T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                    T5 arg5, T6 arg6, T7 arg7) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2, class T3, class T4, class T5,
-         class T6>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4,
-                     T5 arg5, T6 arg6) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N,
-         class T0, class T1, class T2, class T3, class T4, class T5,
-         class T6>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
-                    T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5,
-                    T6 arg6) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = {
-    arg0, arg1, arg2, arg3, arg4, arg5, arg6
-  };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2, class T3, class T4, class T5>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4, arg5 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N,
-         class T0, class T1, class T2, class T3, class T4, class T5>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
-                    T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4, arg5 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2, class T3, class T4>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N, class T0, class T1, class T2, class T3, class T4>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1,
-                    T2 arg2, T3 arg3, T4 arg4) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3, arg4 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2, class T3>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N, class T0, class T1, class T2, class T3>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt,
-                    T0 arg0, T1 arg1, T2 arg2, T3 arg3) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2, arg3 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1, class T2>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt,
-                     T0 arg0, T1 arg1, T2 arg2) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N, class T0, class T1, class T2>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1,
-                    T2 arg2) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1, arg2 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0, class T1>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, T0 arg0, T1 arg1) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N, class T0, class T1>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0, T1 arg1) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0, arg1 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<class T0>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, T0 arg0) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
-}
-
-template<size_t N, class T0>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, T0 arg0) {
-  // Use Arg() object to record type information and then copy arguments to an
-  // array to make it easier to iterate over them.
-  const internal::Arg arg_array[] = { arg0 };
-  return internal::SafeSNPrintf(buf, N, fmt, arg_array, arraysize(arg_array));
+  const internal::Arg arg_array[] = { args... };
+  return internal::SafeSNPrintf(buf, N, fmt, arg_array, sizeof...(args));
 }
 
 // Fast-path when we don't actually need to substitute any arguments.
diff --git a/base/strings/safe_sprintf_unittest.cc b/base/strings/safe_sprintf_unittest.cc
index 98ecd24..02c75f9 100644
--- a/base/strings/safe_sprintf_unittest.cc
+++ b/base/strings/safe_sprintf_unittest.cc
@@ -264,6 +264,13 @@
   EXPECT_EQ(10, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c%c%c",
                              1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
   EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12", std::string(buf));
+
+  EXPECT_EQ(11, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c%c%c",
+                            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
+  EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12\13", std::string(buf));
+  EXPECT_EQ(11, SafeSNPrintf(buf, 12, "%c%c%c%c%c%c%c%c%c%c%c",
+                             1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
+  EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12\13", std::string(buf));
 }
 
 TEST(SafeSPrintfTest, DataTypes) {
diff --git a/base/strings/string_number_conversions_unittest.cc b/base/strings/string_number_conversions_unittest.cc
index 134ba01..4787614 100644
--- a/base/strings/string_number_conversions_unittest.cc
+++ b/base/strings/string_number_conversions_unittest.cc
@@ -73,7 +73,7 @@
     {kuint64max, "18446744073709551615"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].output, Uint64ToString(cases[i].input));
 }
 
@@ -96,7 +96,7 @@
     {size_t_max, size_t_max_string},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].output, Uint64ToString(cases[i].input));
 }
 
@@ -132,7 +132,7 @@
     {"99999999999", INT_MAX, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     int output = 0;
     EXPECT_EQ(cases[i].success, StringToInt(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -196,7 +196,7 @@
     {"99999999999", UINT_MAX, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     unsigned output = 0;
     EXPECT_EQ(cases[i].success, StringToUint(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -266,7 +266,7 @@
     {"99999999999999999999", kint64max, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     int64 output = 0;
     EXPECT_EQ(cases[i].success, StringToInt64(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -333,7 +333,7 @@
     {"18446744073709551616", kuint64max, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     uint64 output = 0;
     EXPECT_EQ(cases[i].success, StringToUint64(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -402,7 +402,7 @@
     {size_t_max_string, size_t_max, true},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     size_t output = 0;
     EXPECT_EQ(cases[i].success, StringToSizeT(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -465,7 +465,7 @@
     {"0x", 0, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     int output = 0;
     EXPECT_EQ(cases[i].success, HexStringToInt(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -525,7 +525,7 @@
     {"0x", 0, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     uint32 output = 0;
     EXPECT_EQ(cases[i].success, HexStringToUInt(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -582,7 +582,7 @@
     {"0x", 0, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     int64 output = 0;
     EXPECT_EQ(cases[i].success, HexStringToInt64(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -644,7 +644,7 @@
     {"0x", 0, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     uint64 output = 0;
     EXPECT_EQ(cases[i].success, HexStringToUInt64(cases[i].input, &output));
     EXPECT_EQ(cases[i].output, output);
@@ -686,7 +686,7 @@
   };
 
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::vector<uint8> output;
     std::vector<uint8> compare;
     EXPECT_EQ(cases[i].success, HexStringToBytes(cases[i].input, &output)) <<
@@ -735,7 +735,7 @@
     {"", 0.0, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     double output;
     errno = 1;
     EXPECT_EQ(cases[i].success, StringToDouble(cases[i].input, &output));
@@ -768,7 +768,7 @@
     {1.33503e+009, "1335030000"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     EXPECT_EQ(cases[i].expected, DoubleToString(cases[i].input));
   }
 
diff --git a/base/strings/string_split_unittest.cc b/base/strings/string_split_unittest.cc
index 998b61f..32bbe28 100644
--- a/base/strings/string_split_unittest.cc
+++ b/base/strings/string_split_unittest.cc
@@ -312,7 +312,7 @@
     { "b\tat",   2, "b",  "at" },
     { "b\t at",  2, "b",  "at" },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(data); ++i) {
+  for (size_t i = 0; i < arraysize(data); ++i) {
     std::vector<std::string> results;
     SplitStringAlongWhitespace(data[i].input, &results);
     ASSERT_EQ(data[i].expected_result_count, results.size());
diff --git a/base/strings/string_util_unittest.cc b/base/strings/string_util_unittest.cc
index d46bc9b..a3e8992 100644
--- a/base/strings/string_util_unittest.cc
+++ b/base/strings/string_util_unittest.cc
@@ -539,7 +539,7 @@
     { "FOO", "foo" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(lowercase_cases); ++i) {
+  for (size_t i = 0; i < arraysize(lowercase_cases); ++i) {
     EXPECT_TRUE(LowerCaseEqualsASCII(ASCIIToUTF16(lowercase_cases[i].src_a),
                                      lowercase_cases[i].dst));
     EXPECT_TRUE(LowerCaseEqualsASCII(lowercase_cases[i].src_a,
@@ -576,7 +576,7 @@
     {100LL*1024*1024*1024, "100 GB"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     EXPECT_EQ(ASCIIToUTF16(cases[i].expected),
               FormatBytesUnlocalized(cases[i].bytes));
   }
@@ -603,7 +603,7 @@
     {"abababab", 2, "ab", "c", "abccc"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     string16 str = ASCIIToUTF16(cases[i].str);
     ReplaceSubstringsAfterOffset(&str, cases[i].start_offset,
                                  ASCIIToUTF16(cases[i].find_this),
@@ -633,7 +633,7 @@
     {"abababab", 2, "ab", "c", "abcabab"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     string16 str = ASCIIToUTF16(cases[i].str);
     ReplaceFirstSubstringAfterOffset(&str, cases[i].start_offset,
                                      ASCIIToUTF16(cases[i].find_this),
@@ -1148,7 +1148,7 @@
     { L"% 10s", false },
     { L"% 10ls", true }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].portable, base::IsWprintfFormatPortable(cases[i].input));
 }
 
@@ -1191,7 +1191,7 @@
     { "test", "t", "test", "testestest", true },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::string output;
     bool result = ReplaceChars(cases[i].input,
                                cases[i].replace_chars,
diff --git a/base/strings/utf_offset_string_conversions_unittest.cc b/base/strings/utf_offset_string_conversions_unittest.cc
index b50e1b6..529939f 100644
--- a/base/strings/utf_offset_string_conversions_unittest.cc
+++ b/base/strings/utf_offset_string_conversions_unittest.cc
@@ -34,7 +34,7 @@
     {"A\xF0\x90\x8C\x80z", 6, 4},
     {"A\xF0\x90\x8C\x80z", kNpos, kNpos},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(utf8_to_utf16_cases); ++i) {
+  for (size_t i = 0; i < arraysize(utf8_to_utf16_cases); ++i) {
     const size_t offset = utf8_to_utf16_cases[i].input_offset;
     std::vector<size_t> offsets;
     offsets.push_back(offset);
@@ -64,7 +64,7 @@
       {{'A', 0xd800, 0xdf00, 'z'}, 3, 5},
       {{'A', 0xd800, 0xdf00, 'z'}, 4, 6},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(utf16_to_utf8_cases); ++i) {
+  for (size_t i = 0; i < arraysize(utf16_to_utf8_cases); ++i) {
     size_t offset = utf16_to_utf8_cases[i].input_offset;
     std::vector<size_t> offsets;
     offsets.push_back(offset);
diff --git a/base/strings/utf_string_conversions_unittest.cc b/base/strings/utf_string_conversions_unittest.cc
index 08009c4..009af7c 100644
--- a/base/strings/utf_string_conversions_unittest.cc
+++ b/base/strings/utf_string_conversions_unittest.cc
@@ -94,7 +94,7 @@
 #endif
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(convert_cases); i++) {
+  for (size_t i = 0; i < arraysize(convert_cases); i++) {
     std::wstring converted;
     EXPECT_EQ(convert_cases[i].success,
               UTF8ToWide(convert_cases[i].utf8,
@@ -172,7 +172,7 @@
     {L"\xdc01Hello", "\xef\xbf\xbdHello", false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(convert_cases); i++) {
+  for (size_t i = 0; i < arraysize(convert_cases); i++) {
     std::string converted;
     EXPECT_EQ(convert_cases[i].success,
               WideToUTF8(convert_cases[i].utf32,
diff --git a/base/sync_socket_win.cc b/base/sync_socket_win.cc
index a8deedb..e508816 100644
--- a/base/sync_socket_win.cc
+++ b/base/sync_socket_win.cc
@@ -150,7 +150,7 @@
       if (::GetLastError() == ERROR_IO_PENDING) {
         HANDLE events[] = { io_event->handle(), cancel_event->handle() };
         const int wait_result = WaitForMultipleObjects(
-            ARRAYSIZE_UNSAFE(events), events, FALSE,
+            arraysize(events), events, FALSE,
             timeout_in_ms == INFINITE ?
                 timeout_in_ms :
                 static_cast<DWORD>(
diff --git a/base/version_unittest.cc b/base/version_unittest.cc
index 2a2309e..3119c39 100644
--- a/base/version_unittest.cc
+++ b/base/version_unittest.cc
@@ -53,7 +53,7 @@
     {"f.1", 0, false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     Version version(cases[i].input);
     EXPECT_EQ(cases[i].success, version.IsValid());
     if (cases[i].success)
@@ -78,7 +78,7 @@
     {"1.0.0", "1.0", 0},
     {"1.0.3", "1.0.20", -1},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     Version lhs(cases[i].lhs);
     Version rhs(cases[i].rhs);
     EXPECT_EQ(lhs.CompareTo(rhs), cases[i].expected) <<
@@ -108,7 +108,7 @@
     {"1.3.9", "1.3.*", 0},
     {"1.2.0.0.0.0", "1.2.*", 0},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     const Version version(cases[i].lhs);
     const int result = version.CompareToWildcardString(cases[i].rhs);
     EXPECT_EQ(result, cases[i].expected) << cases[i].lhs << "?" << cases[i].rhs;
@@ -132,7 +132,7 @@
     {"*", false},
     {"*.2", false},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     EXPECT_EQ(Version::IsValidWildcardString(cases[i].version),
         cases[i].expected) << cases[i].version << "?" << cases[i].expected;
   }
diff --git a/build/all.gyp b/build/all.gyp
index f562537..b469a22 100644
--- a/build/all.gyp
+++ b/build/all.gyp
@@ -806,7 +806,6 @@
             '../chrome/chrome.gyp:chrome_shell_uiautomator_tests',
             '../chrome/chrome.gyp:unit_tests_apk',
             '../components/components_tests.gyp:components_unittests_apk',
-            '../components/devtools_bridge.gyp:devtools_bridge_tests_apk',
             '../content/content_shell_and_tests.gyp:content_browsertests_apk',
             '../content/content_shell_and_tests.gyp:content_gl_tests_apk',
             '../content/content_shell_and_tests.gyp:content_unittests_apk',
@@ -825,6 +824,13 @@
             '../ui/events/events.gyp:events_unittests_apk',
             '../ui/gfx/gfx_tests.gyp:gfx_unittests_apk',
           ],
+          'conditions': [
+            ['"<(libpeer_target_type)"=="static_library"', {
+              'dependencies': [
+                '../components/devtools_bridge.gyp:devtools_bridge_tests_apk',
+              ],
+            }],
+          ],
         },
         {
           # WebRTC Chromium tests to run on Android.
@@ -838,13 +844,6 @@
             # Unit test bundles packaged as an apk.
             '../content/content_shell_and_tests.gyp:content_browsertests_apk',
           ],
-          'conditions': [
-            ['"<(libpeer_target_type)"=="static_library"', {
-              'dependencies': [
-                '../third_party/libjingle/libjingle.gyp:libjingle_peerconnection_javalib',
-              ],
-            }],
-          ],
         },  # target_name: android_builder_chromium_webrtc
       ], # targets
     }], # OS="android"
diff --git a/build/android/findbugs_filter/findbugs_known_bugs.txt b/build/android/findbugs_filter/findbugs_known_bugs.txt
index c82e62b..f641e15 100644
--- a/build/android/findbugs_filter/findbugs_known_bugs.txt
+++ b/build/android/findbugs_filter/findbugs_known_bugs.txt
@@ -22,3 +22,5 @@
 M M LI: Incorrect lazy initialization of static field org.chromium.chrome.browser.sync.ProfileSyncService.sSyncSetupManager in org.chromium.chrome.browser.sync.ProfileSyncService.get(Context)  At ProfileSyncService.java
 M V EI2: org.chromium.content_public.browser.LoadUrlParams.setPostData(byte[]) may expose internal representation by storing an externally mutable object into LoadUrlParams.mPostData  At LoadUrlParams.java
 M V EI: org.chromium.content_public.browser.LoadUrlParams.getPostData() may expose internal representation by returning LoadUrlParams.mPostData  At LoadUrlParams.java
+M D NP: Read of unwritten public or protected field data in org.chromium.components.devtools_bridge.SessionDependencyFactory$DataChannelObserverAdapter.onMessage(DataChannel$Buffer)  At SessionDependencyFactory.java
+M D NP: Read of unwritten public or protected field mandatory in org.chromium.components.devtools_bridge.SessionDependencyFactory.createPeerConnection(RTCConfiguration, AbstractPeerConnection$Observer)  At SessionDependencyFactory.java
diff --git a/build/android/gyp/find.py b/build/android/gyp/find.py
index 07132c7..a9f1d49 100755
--- a/build/android/gyp/find.py
+++ b/build/android/gyp/find.py
@@ -19,6 +19,9 @@
   options, directories = parser.parse_args(argv)
 
   for d in directories:
+    if not os.path.exists(d):
+      print >> sys.stderr, '%s does not exist' % d
+      return 1
     for root, _, filenames in os.walk(d):
       for f in fnmatch.filter(filenames, options.pattern):
         print os.path.join(root, f)
diff --git a/build/android/pylib/constants.py b/build/android/pylib/constants.py
index 292ff3b..35b4342 100644
--- a/build/android/pylib/constants.py
+++ b/build/android/pylib/constants.py
@@ -67,6 +67,12 @@
         None,
         None,
         None),
+    'chromecast_shell': PackageInfo(
+        'com.google.android.apps.mediashell',
+        'com.google.android.apps.mediashell.MediaShellActivity',
+        '/data/local/tmp/castshell-command-line',
+        None,
+        None),
     'content_shell': PackageInfo(
         'org.chromium.content_shell_apk',
         'org.chromium.content_shell_apk.ContentShellActivity',
diff --git a/build/android/pylib/perf/perf_control.py b/build/android/pylib/perf/perf_control.py
index d90edf4..ede1317 100644
--- a/build/android/pylib/perf/perf_control.py
+++ b/build/android/pylib/perf/perf_control.py
@@ -28,7 +28,7 @@
     self._have_mpdecision = self._device.FileExists('/system/bin/mpdecision')
 
   def SetHighPerfMode(self):
-    """Sets the highest possible performance mode for the device."""
+    """Sets the highest stable performance mode for the device."""
     if not self._device.old_interface.IsRootEnabled():
       message = 'Need root for performance mode. Results may be NOISY!!'
       logging.warning(message)
@@ -36,12 +36,23 @@
       # may be different/noisy (due to the lack of intended performance mode).
       atexit.register(logging.warning, message)
       return
+
+    product_model = self._device.old_interface.GetProductModel()
     # TODO(epenner): Enable on all devices (http://crbug.com/383566)
-    if 'Nexus 4' == self._device.old_interface.GetProductModel():
+    if 'Nexus 4' == product_model:
       self._ForceAllCpusOnline(True)
       if not self._AllCpusAreOnline():
         logging.warning('Failed to force CPUs online. Results may be NOISY!')
-    self._SetScalingGovernorInternal('performance')
+      self._SetScalingGovernorInternal('performance')
+    elif 'Nexus 5' == product_model:
+      self._ForceAllCpusOnline(True)
+      if not self._AllCpusAreOnline():
+        logging.warning('Failed to force CPUs online. Results may be NOISY!')
+      self._SetScalingGovernorInternal('performance')
+      self._SetScalingMaxFreq(1190400)
+      self._SetMaxGpuClock(200000000)
+    else:
+      self._SetScalingGovernorInternal('performance')
 
   def SetPerfProfilingMode(self):
     """Enables all cores for reliable perf profiling."""
@@ -56,11 +67,17 @@
     """Sets the performance mode for the device to its default mode."""
     if not self._device.old_interface.IsRootEnabled():
       return
-    product_model = self._device.GetProp('ro.product.model')
+    product_model = self._device.old_interface.GetProductModel()
+    if 'Nexus 5' == product_model:
+      if self._AllCpusAreOnline():
+        self._SetScalingMaxFreq(2265600)
+        self._SetMaxGpuClock(450000000)
+
     governor_mode = {
         'GT-I9300': 'pegasusq',
         'Galaxy Nexus': 'interactive',
         'Nexus 4': 'ondemand',
+        'Nexus 5': 'ondemand',
         'Nexus 7': 'interactive',
         'Nexus 10': 'interactive'
     }.get(product_model, 'ondemand')
@@ -76,6 +93,19 @@
     logging.info('Setting scaling governor mode: %s', value)
     self._device.RunShellCommand(script, as_root=True)
 
+  def _SetScalingMaxFreq(self, value):
+    cpu_cores = ' '.join([str(x) for x in range(self._num_cpu_cores)])
+    script = ('for CPU in %s; do\n'
+        '  FILE="/sys/devices/system/cpu/cpu$CPU/cpufreq/scaling_max_freq"\n'
+        '  test -e $FILE && echo %d > $FILE\n'
+        'done\n') % (cpu_cores, value)
+    self._device.RunShellCommand(script, as_root=True)
+
+  def _SetMaxGpuClock(self, value):
+    self._device.WriteFile('/sys/class/kgsl/kgsl-3d0/max_gpuclk',
+                           str(value),
+                           as_root=True)
+
   def _AllCpusAreOnline(self):
     for cpu in range(1, self._num_cpu_cores):
       online_path = PerfControl._CPU_ONLINE_FMT % cpu
@@ -113,3 +143,4 @@
     for cpu in range(self._num_cpu_cores):
       online_path = PerfControl._CPU_ONLINE_FMT % cpu
       self._device.WriteFile(online_path, '1', as_root=True)
+
diff --git a/build/android/pylib/perf/test_runner.py b/build/android/pylib/perf/test_runner.py
index d74499f..c8563a6 100644
--- a/build/android/pylib/perf/test_runner.py
+++ b/build/android/pylib/perf/test_runner.py
@@ -61,6 +61,7 @@
 from pylib import forwarder
 from pylib.base import base_test_result
 from pylib.base import base_test_runner
+from pylib.device import device_errors
 
 
 def OutputJsonList(json_input, json_output):
@@ -252,9 +253,19 @@
     logging.info('%s : exit_code=%d in %d secs at %s',
                  test_name, exit_code, (end_time - start_time).seconds,
                  self.device_serial)
-    result_type = base_test_result.ResultType.FAIL
+
     if exit_code == 0:
       result_type = base_test_result.ResultType.PASS
+    else:
+      result_type = base_test_result.ResultType.FAIL
+      # Since perf tests use device affinity, give the device a chance to
+      # recover if it is offline after a failure. Otherwise, the master sharder
+      # will remove it from the pool and future tests on this device will fail.
+      try:
+        self.device.WaitUntilFullyBooted(timeout=120)
+      except device_errors.CommandTimeoutError as e:
+        logging.error('Device failed to return after %s: %s' % (test_name, e))
+
     actual_exit_code = exit_code
     if test_name in self._flaky_tests:
       # The exit_code is used at the second stage when printing the
diff --git a/build/common.gypi b/build/common.gypi
index 20aabc2..34000ed 100644
--- a/build/common.gypi
+++ b/build/common.gypi
@@ -1593,11 +1593,6 @@
           'uk', 'vi', 'zh-CN', 'zh-TW',
         ],
 
-        # The Mac SDK is set for iOS builds and passed through to Mac
-        # sub-builds. This allows the Mac sub-build SDK in an iOS build to be
-        # overridden from the command line the same way it is for a Mac build.
-        'mac_sdk%': '<!(python <(DEPTH)/build/mac/find_sdk.py 10.6)',
-
         # iOS SDK and deployment target support.  The |ios_sdk| value is left
         # blank so that when it is set in the project files it will be the
         # "current" iOS SDK.  Forcing a specific SDK even if it is "current"
@@ -1838,7 +1833,13 @@
           # someplace that Xcode doesn't know about, set mac_sdk_path to the
           # path to the SDK; when set to a non-empty string, SDK detection
           # based on mac_sdk_min will be bypassed entirely.
-          'mac_sdk_min%': '10.6',
+          'conditions': [
+            ['OS=="ios"', {
+              'mac_sdk_min%': '10.8',
+            }, {  # else OS!="ios"
+              'mac_sdk_min%': '10.6',
+            }],
+          ],
           'mac_sdk_path%': '',
 
           'mac_deployment_target%': '10.6',
@@ -1862,9 +1863,14 @@
           }, { # else: branding!="Chrome"
             'mac_product_name%': 'Chromium',
           }],
-
-          ['branding=="Chrome" and buildtype=="Official"', {
+          # Official mac builds require a specific OS X SDK, but iOS and
+          # non-official mac builds do not.
+          ['branding=="Chrome" and buildtype=="Official" and OS=="mac"', {
             'mac_sdk%': '<!(python <(DEPTH)/build/mac/find_sdk.py --verify <(mac_sdk_min) --sdk_path=<(mac_sdk_path))',
+          }, {
+            'mac_sdk%': '<!(python <(DEPTH)/build/mac/find_sdk.py <(mac_sdk_min))',
+          }],
+          ['branding=="Chrome" and buildtype=="Official"', {
             # Enable uploading crash dumps.
             'mac_breakpad_uploads%': 1,
             # Enable dumping symbols at build time for use by Mac Breakpad.
@@ -1872,7 +1878,6 @@
             # Enable Keystone auto-update support.
             'mac_keystone%': 1,
           }, { # else: branding!="Chrome" or buildtype!="Official"
-            'mac_sdk%': '<!(python <(DEPTH)/build/mac/find_sdk.py <(mac_sdk_min))',
             'mac_breakpad_uploads%': 0,
             'mac_breakpad%': 0,
             'mac_keystone%': 0,
@@ -4500,6 +4505,16 @@
                   # TODO(eugenis): find a way to reenable this.
                   '-mllvm -asan-globals=0',
                 ],
+                'conditions': [
+                  ['target_arch=="arm"', {
+                    'ldflags': [
+                      # TODO(hans): The ASan runtime is no longer automatically
+                      # added to the link line when using -nostdlib. Can we
+                      # stop adding -nostdlib? (crbug.com/423429)
+                      '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/lib/clang/3.6.0/lib/linux/libclang_rt.asan-arm-android.so',
+                    ],
+                  }],
+                ],
               }],
               ['android_webview_build==0', {
                 'defines': [
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni
index 0c9dbf2..344202c 100644
--- a/build/config/android/rules.gni
+++ b/build/config/android/rules.gni
@@ -1203,3 +1203,12 @@
     ]
   }
 }
+
+# TODO(GYP): implement this.
+template("uiautomator_test") {
+  if (defined(invoker.testonly)) { testonly = invoker.testonly }
+  assert(target_name != "")
+  assert(invoker.deps != [] || true)
+  group(target_name) {
+  }
+}
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn
index 42c254c..dfe8af1 100644
--- a/build/config/compiler/BUILD.gn
+++ b/build/config/compiler/BUILD.gn
@@ -168,6 +168,16 @@
     } else if (cpu_arch == "x86") {
       cflags += [ "-m32" ]
       ldflags += [ "-m32" ]
+      if (is_clang) {
+        cflags += [
+          # Else building libyuv gives clang's register allocator issues,
+          # see llvm.org/PR15798 / crbug.com/233709
+          "-momit-leaf-frame-pointer",
+          # Align the stack on 16-byte boundaries, http://crbug.com/418554.
+          "-mstack-alignment=16",
+          "-mstackrealign",
+        ]
+      }
     } else if (cpu_arch == "arm") {
       # Don't set the compiler flags for the WebView build. These will come
       # from the Android build system.
@@ -253,12 +263,8 @@
       # gcc -- http://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Optimize-Options.html
       "-fuse-ld=gold",
 
-      # There seems to be a conflict of --icf and -pie in gold which can
-      # generate crashy binaries. As a security measure, -pie takes
-      # precedence for now.
       # TODO(brettw) common.gypi has this only for target toolset.
-      #"-Wl,--icf=safe",
-      "-Wl,--icf=none",
+      "-Wl,--icf=safe",
 
       # Experimentation found that using four linking threads
       # saved ~20% of link time.
diff --git a/build/config/linux/BUILD.gn b/build/config/linux/BUILD.gn
index 3ca2b73..559dfd9 100644
--- a/build/config/linux/BUILD.gn
+++ b/build/config/linux/BUILD.gn
@@ -118,23 +118,15 @@
 
 # CrOS doesn't install GTK, gconf or any gnome packages.
 if (!is_chromeos) {
-  pkg_config("gtk") {
-    # Gtk requires gmodule, but it does not list it as a dependency in some
-    # misconfigured systems.
-    packages = [ "gmodule-2.0", "gtk+-2.0", "gthread-2.0" ]
-  }
-
-  pkg_config("gtkprint") {
-    packages = [ "gtk+-unix-print-2.0" ]
-  }
-
-  pkg_config("gnome_keyring") {
-    packages = [ "gnome-keyring-1" ]
-  }
-
-  pkg_config("gconf") {
-    packages = [ "gconf-2.0" ]
-    defines = [ "USE_GCONF" ]
+  # These packages should _only_ be expected when building for a target.
+  # If these extra checks are not run, gconf is required when building host
+  # tools for a CrOS build.
+  if (current_toolchain == host_toolchain &&
+      host_toolchain == default_toolchain) {
+    pkg_config("gconf") {
+      packages = [ "gconf-2.0" ]
+      defines = [ "USE_GCONF" ]
+    }
   }
 }
 
diff --git a/build/landmines.py b/build/landmines.py
index 96bc485..a034864 100755
--- a/build/landmines.py
+++ b/build/landmines.py
@@ -15,6 +15,7 @@
 
 import difflib
 import errno
+import gyp_environment
 import logging
 import optparse
 import os
@@ -120,6 +121,7 @@
   if landmine_utils.builder() in ('dump_dependency_json', 'eclipse'):
     return 0
 
+  gyp_environment.SetEnvironment()
 
   landmines = []
   for s in landmine_scripts:
diff --git a/cc/BUILD.gn b/cc/BUILD.gn
index c1df4c9..74a3c4b 100644
--- a/cc/BUILD.gn
+++ b/cc/BUILD.gn
@@ -208,6 +208,13 @@
     "layers/ui_resource_layer.h",
     "layers/ui_resource_layer_impl.cc",
     "layers/ui_resource_layer_impl.h",
+    "layers/video_frame_provider.h",
+    "layers/video_frame_provider_client_impl.cc",
+    "layers/video_frame_provider_client_impl.h",
+    "layers/video_layer.cc",
+    "layers/video_layer.h",
+    "layers/video_layer_impl.cc",
+    "layers/video_layer_impl.h",
     "output/begin_frame_args.cc",
     "output/begin_frame_args.h",
     "output/bsp_tree.cc",
@@ -419,6 +426,8 @@
     "resources/ui_resource_client.h",
     "resources/ui_resource_request.cc",
     "resources/ui_resource_request.h",
+    "resources/video_resource_updater.cc",
+    "resources/video_resource_updater.h",
     "resources/zero_copy_raster_worker_pool.cc",
     "resources/zero_copy_raster_worker_pool.h",
     "scheduler/begin_frame_source.cc",
@@ -479,6 +488,7 @@
     "//base/third_party/dynamic_annotations",
     "//gpu",
     "//gpu/command_buffer/client:gles2_interface",
+    "//media",
     "//ui/events:events_base",
     "//ui/gfx",
     "//ui/gfx/geometry",
@@ -547,6 +557,8 @@
     "test/fake_tile_manager_client.h",
     "test/fake_ui_resource_layer_tree_host_impl.cc",
     "test/fake_ui_resource_layer_tree_host_impl.h",
+    "test/fake_video_frame_provider.cc",
+    "test/fake_video_frame_provider.h",
     "test/geometry_test_utils.cc",
     "test/geometry_test_utils.h",
     "test/test_in_process_context_provider.cc",
@@ -693,6 +705,7 @@
     "layers/tiled_layer_unittest.cc",
     "layers/ui_resource_layer_impl_unittest.cc",
     "layers/ui_resource_layer_unittest.cc",
+    "layers/video_layer_impl_unittest.cc",
     "output/begin_frame_args_unittest.cc",
     "output/delegating_renderer_unittest.cc",
     "output/filter_operations_unittest.cc",
@@ -722,6 +735,7 @@
     "resources/texture_uploader_unittest.cc",
     "resources/tile_manager_unittest.cc",
     "resources/tile_priority_unittest.cc",
+    "resources/video_resource_updater_unittest.cc",
     "scheduler/begin_frame_source_unittest.cc",
     "scheduler/delay_based_time_source_unittest.cc",
     "scheduler/scheduler_state_machine_unittest.cc",
@@ -749,6 +763,7 @@
     "trees/layer_tree_host_unittest_picture.cc",
     "trees/layer_tree_host_unittest_proxy.cc",
     "trees/layer_tree_host_unittest_scroll.cc",
+    "trees/layer_tree_host_unittest_video.cc",
     "trees/layer_tree_impl_unittest.cc",
     "trees/occlusion_tracker_unittest.cc",
     "trees/occlusion_unittest.cc",
@@ -775,6 +790,7 @@
     "//gpu:test_support",
     "//gpu/command_buffer/client:gles2_interface",
     "//gpu/command_buffer/common:gles2_utils",
+    "//media",
     "//testing/gmock",
     "//testing/gtest",
     "//ui/events:events_base",
@@ -806,6 +822,7 @@
     "//gpu",
     "//gpu:test_support",
     "//gpu/command_buffer/common:gles2_utils",
+    "//media",
     "//skia",
     "//testing/gmock",
     "//testing/gtest",
diff --git a/cc/OWNERS b/cc/OWNERS
index fb45ba6..f213e28 100644
--- a/cc/OWNERS
+++ b/cc/OWNERS
@@ -35,7 +35,6 @@
 vmpstr@chromium.org
 
 # math / geometry / layer_tree_host_common
-shawnsingh@chromium.org
 enne@chromium.org
 vollick@chromium.org
 
diff --git a/cc/PRESUBMIT.py b/cc/PRESUBMIT.py
index 6dff371..1aa48f3 100644
--- a/cc/PRESUBMIT.py
+++ b/cc/PRESUBMIT.py
@@ -150,6 +150,22 @@
       items=errors)]
   return []
 
+def CheckDoubleAngles(input_api, output_api, white_list=CC_SOURCE_FILES,
+                      black_list=None):
+  errors = []
+
+  source_file_filter = lambda x: input_api.FilterSourceFile(x,
+                                                            white_list,
+                                                            black_list)
+  for f in input_api.AffectedSourceFiles(source_file_filter):
+    contents = input_api.ReadFile(f, 'rb')
+    if ('> >') in contents:
+      errors.append(f.LocalPath())
+
+  if errors:
+    return [output_api.PresubmitError('Use >> instead of > >:', items=errors)]
+  return []
+
 def CheckScopedPtr(input_api, output_api,
                    white_list=CC_SOURCE_FILES, black_list=None):
   black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
@@ -170,9 +186,8 @@
           ('%s:%d uses explicit scoped_ptr constructor. ' +
            'Use make_scoped_ptr() instead.') % (f.LocalPath(), line_number)))
       # Disallow:
-      # return scoped_ptr<T>();
-      # bar = scoped_ptr<T>();
-      if re.search(r'(=|\breturn)\s*scoped_ptr<.*?>\(\)', line):
+      # scoped_ptr<T>()
+      if re.search(r'\bscoped_ptr<.*?>\(\)', line):
         errors.append(output_api.PresubmitError(
           '%s:%d uses scoped_ptr<T>(). Use nullptr instead.' %
           (f.LocalPath(), line_number)))
@@ -360,6 +375,7 @@
   results += CheckPassByValue(input_api, output_api)
   results += CheckChangeLintsClean(input_api, output_api)
   results += CheckTodos(input_api, output_api)
+  results += CheckDoubleAngles(input_api, output_api)
   results += CheckScopedPtr(input_api, output_api)
   results += CheckNamespace(input_api, output_api)
   results += CheckForUseOfWrongClock(input_api, output_api)
@@ -373,9 +389,4 @@
     'tryserver.blink': {
       'linux_blink_rel': set(['defaulttests']),
     },
-    'tryserver.chromium.gpu': {
-      'linux_gpu': set(['defaulttests']),
-      'mac_gpu': set(['defaulttests']),
-      'win_gpu': set(['defaulttests']),
-    },
   }
diff --git a/cc/animation/animation_delegate.h b/cc/animation/animation_delegate.h
index d2ab984..8c736b5 100644
--- a/cc/animation/animation_delegate.h
+++ b/cc/animation/animation_delegate.h
@@ -12,12 +12,13 @@
 
 class CC_EXPORT AnimationDelegate {
  public:
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) = 0;
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) = 0;
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) = 0;
+      Animation::TargetProperty target_property,
+      int group) = 0;
 
  protected:
   virtual ~AnimationDelegate() {}
diff --git a/cc/animation/keyframed_animation_curve_unittest.cc b/cc/animation/keyframed_animation_curve_unittest.cc
index 7a82fa2..32bc141 100644
--- a/cc/animation/keyframed_animation_curve_unittest.cc
+++ b/cc/animation/keyframed_animation_curve_unittest.cc
@@ -29,8 +29,7 @@
   SkColor color = SkColorSetARGB(255, 255, 255, 255);
   scoped_ptr<KeyframedColorAnimationCurve> curve(
       KeyframedColorAnimationCurve::Create());
-  curve->AddKeyframe(
-      ColorKeyframe::Create(0.0, color, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(ColorKeyframe::Create(0.0, color, nullptr));
 
   EXPECT_SKCOLOR_EQ(color, curve->GetValue(-1.f));
   EXPECT_SKCOLOR_EQ(color, curve->GetValue(0.f));
@@ -46,10 +45,8 @@
   SkColor color_midpoint = gfx::Tween::ColorValueBetween(0.5, color_a, color_b);
   scoped_ptr<KeyframedColorAnimationCurve> curve(
       KeyframedColorAnimationCurve::Create());
-  curve->AddKeyframe(
-      ColorKeyframe::Create(0.0, color_a, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      ColorKeyframe::Create(1.0, color_b, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(ColorKeyframe::Create(0.0, color_a, nullptr));
+  curve->AddKeyframe(ColorKeyframe::Create(1.0, color_b, nullptr));
 
   EXPECT_SKCOLOR_EQ(color_a, curve->GetValue(-1.f));
   EXPECT_SKCOLOR_EQ(color_a, curve->GetValue(0.f));
@@ -69,12 +66,9 @@
       gfx::Tween::ColorValueBetween(0.5, color_b, color_c);
   scoped_ptr<KeyframedColorAnimationCurve> curve(
       KeyframedColorAnimationCurve::Create());
-  curve->AddKeyframe(
-      ColorKeyframe::Create(0.0, color_a, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      ColorKeyframe::Create(1.0, color_b, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      ColorKeyframe::Create(2.0, color_c, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(ColorKeyframe::Create(0.0, color_a, nullptr));
+  curve->AddKeyframe(ColorKeyframe::Create(1.0, color_b, nullptr));
+  curve->AddKeyframe(ColorKeyframe::Create(2.0, color_c, nullptr));
 
   EXPECT_SKCOLOR_EQ(color_a, curve->GetValue(-1.f));
   EXPECT_SKCOLOR_EQ(color_a, curve->GetValue(0.f));
@@ -92,14 +86,10 @@
 
   scoped_ptr<KeyframedColorAnimationCurve> curve(
       KeyframedColorAnimationCurve::Create());
-  curve->AddKeyframe(
-      ColorKeyframe::Create(0.0, color_a, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      ColorKeyframe::Create(1.0, color_a, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      ColorKeyframe::Create(1.0, color_b, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      ColorKeyframe::Create(2.0, color_b, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(ColorKeyframe::Create(0.0, color_a, nullptr));
+  curve->AddKeyframe(ColorKeyframe::Create(1.0, color_a, nullptr));
+  curve->AddKeyframe(ColorKeyframe::Create(1.0, color_b, nullptr));
+  curve->AddKeyframe(ColorKeyframe::Create(2.0, color_b, nullptr));
 
   EXPECT_SKCOLOR_EQ(color_a, curve->GetValue(-1.f));
   EXPECT_SKCOLOR_EQ(color_a, curve->GetValue(0.f));
@@ -120,8 +110,7 @@
 TEST(KeyframedAnimationCurveTest, OneFloatKeyframe) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 2.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 2.f, nullptr));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(-1.f));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(0.f));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(0.5f));
@@ -133,10 +122,8 @@
 TEST(KeyframedAnimationCurveTest, TwoFloatKeyframe) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 2.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 4.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 2.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 4.f, nullptr));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(-1.f));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(0.f));
   EXPECT_FLOAT_EQ(3.f, curve->GetValue(0.5f));
@@ -148,12 +135,9 @@
 TEST(KeyframedAnimationCurveTest, ThreeFloatKeyframe) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 2.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 4.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(2.0, 8.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 2.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 4.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(2.0, 8.f, nullptr));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(-1.f));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(0.f));
   EXPECT_FLOAT_EQ(3.f, curve->GetValue(0.5f));
@@ -167,14 +151,10 @@
 TEST(KeyframedAnimationCurveTest, RepeatedFloatKeyTimes) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 4.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 4.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 6.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(2.0, 6.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 4.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 4.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 6.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(2.0, 6.f, nullptr));
 
   EXPECT_FLOAT_EQ(4.f, curve->GetValue(-1.f));
   EXPECT_FLOAT_EQ(4.f, curve->GetValue(0.f));
@@ -195,8 +175,7 @@
       KeyframedTransformAnimationCurve::Create());
   TransformOperations operations;
   operations.AppendTranslate(2.f, 0.f, 0.f);
-  curve->AddKeyframe(
-      TransformKeyframe::Create(0.f, operations, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.f, operations, nullptr));
 
   ExpectTranslateX(2.f, curve->GetValue(-1.f));
   ExpectTranslateX(2.f, curve->GetValue(0.f));
@@ -214,10 +193,8 @@
   TransformOperations operations2;
   operations2.AppendTranslate(4.f, 0.f, 0.f);
 
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.f, operations1, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(TransformKeyframe::Create(
-      1.f, operations2, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.f, operations1, nullptr));
+  curve->AddKeyframe(TransformKeyframe::Create(1.f, operations2, nullptr));
   ExpectTranslateX(2.f, curve->GetValue(-1.f));
   ExpectTranslateX(2.f, curve->GetValue(0.f));
   ExpectTranslateX(3.f, curve->GetValue(0.5f));
@@ -235,12 +212,9 @@
   operations2.AppendTranslate(4.f, 0.f, 0.f);
   TransformOperations operations3;
   operations3.AppendTranslate(8.f, 0.f, 0.f);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.f, operations1, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(TransformKeyframe::Create(
-      1.f, operations2, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(TransformKeyframe::Create(
-      2.f, operations3, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.f, operations1, nullptr));
+  curve->AddKeyframe(TransformKeyframe::Create(1.f, operations2, nullptr));
+  curve->AddKeyframe(TransformKeyframe::Create(2.f, operations3, nullptr));
   ExpectTranslateX(2.f, curve->GetValue(-1.f));
   ExpectTranslateX(2.f, curve->GetValue(0.f));
   ExpectTranslateX(3.f, curve->GetValue(0.5f));
@@ -264,14 +238,10 @@
   operations3.AppendTranslate(6.f, 0.f, 0.f);
   TransformOperations operations4;
   operations4.AppendTranslate(6.f, 0.f, 0.f);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.f, operations1, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(TransformKeyframe::Create(
-      1.f, operations2, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(TransformKeyframe::Create(
-      1.f, operations3, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(TransformKeyframe::Create(
-      2.f, operations4, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.f, operations1, nullptr));
+  curve->AddKeyframe(TransformKeyframe::Create(1.f, operations2, nullptr));
+  curve->AddKeyframe(TransformKeyframe::Create(1.f, operations3, nullptr));
+  curve->AddKeyframe(TransformKeyframe::Create(2.f, operations4, nullptr));
 
   ExpectTranslateX(4.f, curve->GetValue(-1.f));
   ExpectTranslateX(4.f, curve->GetValue(0.f));
@@ -293,8 +263,7 @@
       KeyframedFilterAnimationCurve::Create());
   FilterOperations operations;
   operations.Append(FilterOperation::CreateBrightnessFilter(2.f));
-  curve->AddKeyframe(
-      FilterKeyframe::Create(0.f, operations, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(0.f, operations, nullptr));
 
   ExpectBrightness(2.f, curve->GetValue(-1.f));
   ExpectBrightness(2.f, curve->GetValue(0.f));
@@ -312,10 +281,8 @@
   FilterOperations operations2;
   operations2.Append(FilterOperation::CreateBrightnessFilter(4.f));
 
-  curve->AddKeyframe(FilterKeyframe::Create(
-      0.f, operations1, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      1.f, operations2, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(0.f, operations1, nullptr));
+  curve->AddKeyframe(FilterKeyframe::Create(1.f, operations2, nullptr));
   ExpectBrightness(2.f, curve->GetValue(-1.f));
   ExpectBrightness(2.f, curve->GetValue(0.f));
   ExpectBrightness(3.f, curve->GetValue(0.5f));
@@ -333,12 +300,9 @@
   operations2.Append(FilterOperation::CreateBrightnessFilter(4.f));
   FilterOperations operations3;
   operations3.Append(FilterOperation::CreateBrightnessFilter(8.f));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      0.f, operations1, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      1.f, operations2, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      2.f, operations3, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(0.f, operations1, nullptr));
+  curve->AddKeyframe(FilterKeyframe::Create(1.f, operations2, nullptr));
+  curve->AddKeyframe(FilterKeyframe::Create(2.f, operations3, nullptr));
   ExpectBrightness(2.f, curve->GetValue(-1.f));
   ExpectBrightness(2.f, curve->GetValue(0.f));
   ExpectBrightness(3.f, curve->GetValue(0.5f));
@@ -362,14 +326,10 @@
   operations3.Append(FilterOperation::CreateBrightnessFilter(6.f));
   FilterOperations operations4;
   operations4.Append(FilterOperation::CreateBrightnessFilter(6.f));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      0.f, operations1, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      1.f, operations2, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      1.f, operations3, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FilterKeyframe::Create(
-      2.f, operations4, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(0.f, operations1, nullptr));
+  curve->AddKeyframe(FilterKeyframe::Create(1.f, operations2, nullptr));
+  curve->AddKeyframe(FilterKeyframe::Create(1.f, operations3, nullptr));
+  curve->AddKeyframe(FilterKeyframe::Create(2.f, operations4, nullptr));
 
   ExpectBrightness(4.f, curve->GetValue(-1.f));
   ExpectBrightness(4.f, curve->GetValue(0.f));
@@ -391,12 +351,9 @@
 TEST(KeyframedAnimationCurveTest, UnsortedKeyframes) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(2.0, 8.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 2.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 4.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(2.0, 8.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 2.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 4.f, nullptr));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(-1.f));
   EXPECT_FLOAT_EQ(2.f, curve->GetValue(0.f));
   EXPECT_FLOAT_EQ(3.f, curve->GetValue(0.5f));
@@ -412,8 +369,7 @@
       KeyframedFloatAnimationCurve::Create());
   curve->AddKeyframe(FloatKeyframe::Create(
       0.0, 0.f, CubicBezierTimingFunction::Create(0.25f, 0.f, 0.75f, 1.f)));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 1.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 1.f, nullptr));
 
   EXPECT_FLOAT_EQ(0.f, curve->GetValue(0.f));
   EXPECT_LT(0.f, curve->GetValue(0.25f));
@@ -430,11 +386,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendTranslate(2.0, 3.0, -1.0);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.5, operations1, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.5, operations1, nullptr));
   TransformOperations operations2;
   operations2.AppendTranslate(4.0, 1.0, 2.0);
   curve->AddKeyframe(TransformKeyframe::Create(
@@ -454,27 +408,23 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendTranslate(2.0, 3.0, -1.0);
   TransformOperations operations2;
   operations2.AppendTranslate(4.0, 1.0, 2.0);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   EXPECT_FALSE(curve->AffectsScale());
 
   TransformOperations operations3;
   operations3.AppendScale(2.f, 2.f, 2.f);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      2.0, operations3, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(2.0, operations3, nullptr));
 
   EXPECT_TRUE(curve->AffectsScale());
 
   TransformOperations operations4;
   operations3.AppendTranslate(2.f, 2.f, 2.f);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      3.0, operations4, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(3.0, operations4, nullptr));
 
   EXPECT_TRUE(curve->AffectsScale());
 }
@@ -485,27 +435,23 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendTranslate(2.0, 3.0, -1.0);
   TransformOperations operations2;
   operations2.AppendTranslate(4.0, 1.0, 2.0);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   EXPECT_TRUE(curve->IsTranslation());
 
   TransformOperations operations3;
   operations3.AppendScale(2.f, 2.f, 2.f);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      2.0, operations3, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(2.0, operations3, nullptr));
 
   EXPECT_FALSE(curve->IsTranslation());
 
   TransformOperations operations4;
   operations3.AppendTranslate(2.f, 2.f, 2.f);
-  curve->AddKeyframe(TransformKeyframe::Create(
-      3.0, operations4, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(3.0, operations4, nullptr));
 
   EXPECT_FALSE(curve->IsTranslation());
 }
@@ -516,8 +462,7 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendScale(2.f, -3.f, 1.f);
   curve->AddKeyframe(TransformKeyframe::Create(
       1.0, operations1, EaseTimingFunction::Create()));
@@ -565,10 +510,8 @@
 TEST(KeyframedAnimationCurveTest, CurveTiming) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 0.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 1.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 0.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 1.f, nullptr));
   curve->SetTimingFunction(
       CubicBezierTimingFunction::Create(0.75f, 0.f, 0.25f, 1.f).Pass());
   EXPECT_FLOAT_EQ(0.f, curve->GetValue(-1.f));
@@ -589,8 +532,7 @@
       0.0,
       0.f,
       CubicBezierTimingFunction::Create(0.35f, 0.f, 0.65f, 1.f).Pass()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 1.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 1.f, nullptr));
   // Curve timing function producing outputs outside of range [0,1].
   curve->SetTimingFunction(
       CubicBezierTimingFunction::Create(0.5f, -0.5f, 0.5f, 1.5f).Pass());
@@ -610,16 +552,11 @@
 TEST(KeyframedAnimationCurveTest, CurveTimingMultipleKeyframes) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 0.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 1.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(2.0, 3.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(3.0, 6.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(4.0, 9.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 0.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 1.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(2.0, 3.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(3.0, 6.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(4.0, 9.f, nullptr));
   curve->SetTimingFunction(
       CubicBezierTimingFunction::Create(0.5f, 0.f, 0.5f, 1.f).Pass());
   EXPECT_FLOAT_EQ(0.f, curve->GetValue(-1.f));
@@ -637,16 +574,11 @@
 TEST(KeyframedAnimationCurveTest, CurveTimingOvershootMultipeKeyframes) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve(
       KeyframedFloatAnimationCurve::Create());
-  curve->AddKeyframe(
-      FloatKeyframe::Create(0.0, 0.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(1.0, 1.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(2.0, 3.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(3.0, 6.f, scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(
-      FloatKeyframe::Create(4.0, 9.f, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 0.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 1.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(2.0, 3.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(3.0, 6.f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(4.0, 9.f, nullptr));
   // Curve timing function producing outputs outside of range [0,1].
   curve->SetTimingFunction(
       CubicBezierTimingFunction::Create(0.5f, -0.5f, 0.5f, 1.5f).Pass());
diff --git a/cc/animation/layer_animation_controller.cc b/cc/animation/layer_animation_controller.cc
index 3aad9d6..ab6db10 100644
--- a/cc/animation/layer_animation_controller.cc
+++ b/cc/animation/layer_animation_controller.cc
@@ -315,8 +315,8 @@
     FOR_EACH_OBSERVER(LayerAnimationEventObserver, event_observers_,
                       OnAnimationStarted(event));
     if (layer_animation_delegate_)
-      layer_animation_delegate_->NotifyAnimationStarted(event.monotonic_time,
-                                                        event.target_property);
+      layer_animation_delegate_->NotifyAnimationStarted(
+          event.monotonic_time, event.target_property, event.group_id);
     return;
   }
 
@@ -332,7 +332,7 @@
                         OnAnimationStarted(event));
       if (layer_animation_delegate_)
         layer_animation_delegate_->NotifyAnimationStarted(
-            event.monotonic_time, event.target_property);
+            event.monotonic_time, event.target_property, event.group_id);
 
       return;
     }
@@ -343,8 +343,8 @@
     const AnimationEvent& event) {
   if (event.is_impl_only) {
     if (layer_animation_delegate_)
-      layer_animation_delegate_->NotifyAnimationFinished(event.monotonic_time,
-                                                         event.target_property);
+      layer_animation_delegate_->NotifyAnimationFinished(
+          event.monotonic_time, event.target_property, event.group_id);
     return;
   }
 
@@ -354,7 +354,7 @@
       animations_[i]->set_received_finished_event(true);
       if (layer_animation_delegate_)
         layer_animation_delegate_->NotifyAnimationFinished(
-            event.monotonic_time, event.target_property);
+            event.monotonic_time, event.target_property, event.group_id);
 
       return;
     }
diff --git a/cc/animation/layer_animation_controller_unittest.cc b/cc/animation/layer_animation_controller_unittest.cc
index 92456fa..a5a2965 100644
--- a/cc/animation/layer_animation_controller_unittest.cc
+++ b/cc/animation/layer_animation_controller_unittest.cc
@@ -510,11 +510,9 @@
 
   // Create simple Transform animation.
   TransformOperations operations;
-  curve->AddKeyframe(
-      TransformKeyframe::Create(0, operations, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(0, operations, nullptr));
   operations.AppendTranslate(delta_x, delta_y, 0);
-  curve->AddKeyframe(
-      TransformKeyframe::Create(1, operations, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(1, operations, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve.Pass(), 1, 0, Animation::Transform));
@@ -561,12 +559,10 @@
 
   FilterOperations start_filters;
   start_filters.Append(FilterOperation::CreateBrightnessFilter(1.f));
-  curve->AddKeyframe(
-      FilterKeyframe::Create(0, start_filters, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(0, start_filters, nullptr));
   FilterOperations end_filters;
   end_filters.Append(FilterOperation::CreateBrightnessFilter(2.f));
-  curve->AddKeyframe(
-      FilterKeyframe::Create(1, end_filters, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(1, end_filters, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve.Pass(), 1, 0, Animation::Filter));
@@ -610,12 +606,10 @@
   // Create simple Filter animation.
   FilterOperations start_filters;
   start_filters.Append(FilterOperation::CreateBrightnessFilter(1.f));
-  curve->AddKeyframe(
-      FilterKeyframe::Create(0, start_filters, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(0, start_filters, nullptr));
   FilterOperations end_filters;
   end_filters.Append(FilterOperation::CreateBrightnessFilter(2.f));
-  curve->AddKeyframe(
-      FilterKeyframe::Create(1, end_filters, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(1, end_filters, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve.Pass(), 1, 0, Animation::Filter));
@@ -865,15 +859,16 @@
       : started_(false),
         finished_(false) {}
 
-  virtual void NotifyAnimationStarted(
-      TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+  virtual void NotifyAnimationStarted(TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override {
     started_ = true;
   }
 
   virtual void NotifyAnimationFinished(
       TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+      Animation::TargetProperty target_property,
+      int group) override {
     finished_ = true;
   }
 
@@ -1477,11 +1472,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendTranslate(10.0, 15.0, 0.0);
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(1.0, operations1, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve1.Pass(), 1, 1, Animation::Transform));
@@ -1491,11 +1484,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations2;
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(0.0, operations2, nullptr));
   operations2.AppendScale(2.0, 3.0, 4.0);
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   animation = Animation::Create(curve2.Pass(), 2, 2, Animation::Transform);
   controller_impl->AddAnimation(animation.Pass());
@@ -1527,11 +1518,9 @@
   TransformOperations operations3;
   gfx::Transform transform3;
   transform3.Scale3d(1.0, 2.0, 3.0);
-  curve3->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations3, scoped_ptr<TimingFunction>()));
+  curve3->AddKeyframe(TransformKeyframe::Create(0.0, operations3, nullptr));
   operations3.AppendMatrix(transform3);
-  curve3->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations3, scoped_ptr<TimingFunction>()));
+  curve3->AddKeyframe(TransformKeyframe::Create(1.0, operations3, nullptr));
   animation = Animation::Create(curve3.Pass(), 3, 3, Animation::Transform);
   controller_impl->AddAnimation(animation.Pass());
   EXPECT_FALSE(controller_impl->TransformAnimationBoundsForBox(box, &bounds));
@@ -1799,11 +1788,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendTranslate(10.0, 15.0, 0.0);
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(1.0, operations1, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve1.Pass(), 2, 2, Animation::Transform));
@@ -1816,11 +1803,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations2;
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(0.0, operations2, nullptr));
   operations2.AppendScale(2.0, 3.0, 4.0);
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   animation = Animation::Create(curve2.Pass(), 3, 3, Animation::Transform);
   controller_impl->AddAnimation(animation.Pass());
@@ -1853,11 +1838,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendTranslate(10.0, 15.0, 0.0);
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(1.0, operations1, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve1.Pass(), 2, 2, Animation::Transform));
@@ -1870,11 +1853,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations2;
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(0.0, operations2, nullptr));
   operations2.AppendScale(2.0, 3.0, 4.0);
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   animation = Animation::Create(curve2.Pass(), 3, 3, Animation::Transform);
   controller_impl->AddAnimation(animation.Pass());
@@ -1902,11 +1883,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations1;
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   operations1.AppendScale(2.0, 3.0, 4.0);
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(1.0, operations1, nullptr));
 
   scoped_ptr<Animation> animation(
       Animation::Create(curve1.Pass(), 1, 1, Animation::Transform));
@@ -1919,11 +1898,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations2;
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(0.0, operations2, nullptr));
   operations2.AppendScale(6.0, 5.0, 4.0);
-  curve2->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve2->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   animation = Animation::Create(curve2.Pass(), 2, 2, Animation::Transform);
   controller_impl->AddAnimation(animation.Pass());
@@ -1935,11 +1912,9 @@
       KeyframedTransformAnimationCurve::Create());
 
   TransformOperations operations3;
-  curve3->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations3, scoped_ptr<TimingFunction>()));
+  curve3->AddKeyframe(TransformKeyframe::Create(0.0, operations3, nullptr));
   operations3.AppendPerspective(6.0);
-  curve3->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations3, scoped_ptr<TimingFunction>()));
+  curve3->AddKeyframe(TransformKeyframe::Create(1.0, operations3, nullptr));
 
   animation = Animation::Create(curve3.Pass(), 3, 3, Animation::Transform);
   controller_impl->AddAnimation(animation.Pass());
@@ -1965,12 +1940,10 @@
       KeyframedTransformAnimationCurve::Create());
   TransformOperations operations1;
   operations1.AppendScale(1.0, 2.0, 3.0);
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      0.0, operations1, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(0.0, operations1, nullptr));
   TransformOperations operations2;
   operations2.AppendScale(4.0, 5.0, 6.0);
-  curve1->AddKeyframe(TransformKeyframe::Create(
-      1.0, operations2, scoped_ptr<TimingFunction>()));
+  curve1->AddKeyframe(TransformKeyframe::Create(1.0, operations2, nullptr));
 
   scoped_ptr<Animation> animation_owned(
       Animation::Create(curve1.Pass(), 1, 1, Animation::Transform));
diff --git a/cc/animation/scrollbar_animation_controller_linear_fade.cc b/cc/animation/scrollbar_animation_controller_linear_fade.cc
index f65fd72..1b5dfd9 100644
--- a/cc/animation/scrollbar_animation_controller_linear_fade.cc
+++ b/cc/animation/scrollbar_animation_controller_linear_fade.cc
@@ -64,7 +64,7 @@
     ScrollbarLayerImplBase* scrollbar = *it;
 
     if (scrollbar->is_overlay_scrollbar())
-      scrollbar->SetOpacity(scrollbar->can_scroll_orientation() ? opacity : 0);
+      scrollbar->SetOpacity(scrollbar->CanScrollOrientation() ? opacity : 0);
   }
 }
 
diff --git a/cc/animation/scrollbar_animation_controller_thinning.cc b/cc/animation/scrollbar_animation_controller_thinning.cc
index e95b599..0405074 100644
--- a/cc/animation/scrollbar_animation_controller_thinning.cc
+++ b/cc/animation/scrollbar_animation_controller_thinning.cc
@@ -146,7 +146,7 @@
     ScrollbarLayerImplBase* scrollbar = *it;
     if (scrollbar->is_overlay_scrollbar()) {
       float effectiveOpacity =
-          scrollbar->can_scroll_orientation()
+          scrollbar->CanScrollOrientation()
               ? AdjustScale(opacity, scrollbar->opacity(), opacity_change_)
               : 0;
 
diff --git a/cc/animation/transform_operations_unittest.cc b/cc/animation/transform_operations_unittest.cc
index 208f81a..cf29e97 100644
--- a/cc/animation/transform_operations_unittest.cc
+++ b/cc/animation/transform_operations_unittest.cc
@@ -927,16 +927,6 @@
   EXPECT_EQ(box.ToString(), bounds.ToString());
 }
 
-// This would have been best as anonymous structs, but |arraysize| does not get
-// along with anonymous structs (and using ARRAYSIZE_UNSAFE seemed like a worse
-// option).
-struct ProblematicAxisTest {
-  float x;
-  float y;
-  float z;
-  gfx::BoxF expected;
-};
-
 TEST(TransformOperationTest, BlendedBoundsForRotationProblematicAxes) {
   // Zeros in the components of the axis of rotation turned out to be tricky to
   // deal with in practice. This function tests some potentially problematic
@@ -947,15 +937,18 @@
   float dim2 = sqrt(2.f);
   float dim3 = 2.f * dim2;
 
-  ProblematicAxisTest tests[] = {
-    { 0.f, 0.f, 0.f, gfx::BoxF(1.f, 1.f, 1.f, 0.f, 0.f, 0.f) },
-    { 1.f, 0.f, 0.f, gfx::BoxF(1.f, -dim2, -dim2, 0.f, dim3, dim3) },
-    { 0.f, 1.f, 0.f, gfx::BoxF(-dim2, 1.f, -dim2, dim3, 0.f, dim3) },
-    { 0.f, 0.f, 1.f, gfx::BoxF(-dim2, -dim2, 1.f, dim3, dim3, 0.f) },
-    { 1.f, 1.f, 0.f, gfx::BoxF(dim1, dim1, -1.f, dim2, dim2, 2.f) },
-    { 0.f, 1.f, 1.f, gfx::BoxF(-1.f, dim1, dim1, 2.f, dim2, dim2) },
-    { 1.f, 0.f, 1.f, gfx::BoxF(dim1, -1.f, dim1, dim2, 2.f, dim2) }
-  };
+  struct {
+    float x;
+    float y;
+    float z;
+    gfx::BoxF expected;
+  } tests[] = {{0.f, 0.f, 0.f, gfx::BoxF(1.f, 1.f, 1.f, 0.f, 0.f, 0.f)},
+               {1.f, 0.f, 0.f, gfx::BoxF(1.f, -dim2, -dim2, 0.f, dim3, dim3)},
+               {0.f, 1.f, 0.f, gfx::BoxF(-dim2, 1.f, -dim2, dim3, 0.f, dim3)},
+               {0.f, 0.f, 1.f, gfx::BoxF(-dim2, -dim2, 1.f, dim3, dim3, 0.f)},
+               {1.f, 1.f, 0.f, gfx::BoxF(dim1, dim1, -1.f, dim2, dim2, 2.f)},
+               {0.f, 1.f, 1.f, gfx::BoxF(-1.f, dim1, dim1, 2.f, dim2, dim2)},
+               {1.f, 0.f, 1.f, gfx::BoxF(dim1, -1.f, dim1, dim2, 2.f, dim2)}};
 
   for (size_t i = 0; i < arraysize(tests); ++i) {
     float x = tests[i].x;
@@ -974,25 +967,6 @@
   }
 }
 
-// These would have been best as anonymous structs, but |arraysize| does not get
-// along with anonymous structs (and using ARRAYSIZE_UNSAFE seemed like a worse
-// option).
-struct TestAxis {
-  float x;
-  float y;
-  float z;
-};
-
-struct TestAngles {
-  float theta_from;
-  float theta_to;
-};
-
-struct TestProgress {
-  float min_progress;
-  float max_progress;
-};
-
 static void ExpectBoxesApproximatelyEqual(const gfx::BoxF& lhs,
                                           const gfx::BoxF& rhs,
                                           float tolerance) {
@@ -1071,44 +1045,49 @@
   // empirically tests that the transformed bounds are indeed contained by the
   // computed bounding box.
 
-  TestAxis axes[] = {
-    { 1.f, 1.f, 1.f },
-    { -1.f, -1.f, -1.f },
-    { -1.f, 2.f, 3.f },
-    { 1.f, -2.f, 3.f },
-    { 1.f, 2.f, -3.f },
-    { 0.f, 0.f, 0.f },
-    { 1.f, 0.f, 0.f },
-    { 0.f, 1.f, 0.f },
-    { 0.f, 0.f, 1.f },
-    { 1.f, 1.f, 0.f },
-    { 0.f, 1.f, 1.f },
-    { 1.f, 0.f, 1.f },
-    { -1.f, 0.f, 0.f },
-    { 0.f, -1.f, 0.f },
-    { 0.f, 0.f, -1.f },
-    { -1.f, -1.f, 0.f },
-    { 0.f, -1.f, -1.f },
-    { -1.f, 0.f, -1.f }
-  };
+  struct {
+    float x;
+    float y;
+    float z;
+  } axes[] = {{1.f, 1.f, 1.f},
+              {-1.f, -1.f, -1.f},
+              {-1.f, 2.f, 3.f},
+              {1.f, -2.f, 3.f},
+              {1.f, 2.f, -3.f},
+              {0.f, 0.f, 0.f},
+              {1.f, 0.f, 0.f},
+              {0.f, 1.f, 0.f},
+              {0.f, 0.f, 1.f},
+              {1.f, 1.f, 0.f},
+              {0.f, 1.f, 1.f},
+              {1.f, 0.f, 1.f},
+              {-1.f, 0.f, 0.f},
+              {0.f, -1.f, 0.f},
+              {0.f, 0.f, -1.f},
+              {-1.f, -1.f, 0.f},
+              {0.f, -1.f, -1.f},
+              {-1.f, 0.f, -1.f}};
 
-  TestAngles angles[] = {
-    { 5.f, 10.f },
-    { 10.f, 5.f },
-    { 0.f, 360.f },
-    { 20.f, 180.f },
-    { -20.f, -180.f },
-    { 180.f, -220.f },
-    { 220.f, 320.f }
-  };
+  struct {
+    float theta_from;
+    float theta_to;
+  } angles[] = {{5.f, 10.f},
+                {10.f, 5.f},
+                {0.f, 360.f},
+                {20.f, 180.f},
+                {-20.f, -180.f},
+                {180.f, -220.f},
+                {220.f, 320.f}};
 
   // We can go beyond the range [0, 1] (the bezier might slide out of this range
   // at either end), but since the first and last knots are at (0, 0) and (1, 1)
   // we will never go within it, so these tests are sufficient.
-  TestProgress progress[] = {
-    { 0.f, 1.f },
-    { -.25f, 1.25f },
-  };
+  struct {
+    float min_progress;
+    float max_progress;
+  } progress[] = {
+        {0.f, 1.f}, {-.25f, 1.25f},
+    };
 
   for (size_t i = 0; i < arraysize(axes); ++i) {
     for (size_t j = 0; j < arraysize(angles); ++j) {
@@ -1156,22 +1135,22 @@
     }
 }
 
-struct TestPerspectiveDepths {
-  float from_depth;
-  float to_depth;
-};
-
 TEST(TransformOperationTest, BlendedBoundsForPerspective) {
-  TestPerspectiveDepths perspective_depths[] = {
-    { 600.f, 400.f },
-    { 800.f, 1000.f },
-    { 800.f, std::numeric_limits<float>::infinity() },
-  };
+  struct {
+    float from_depth;
+    float to_depth;
+  } perspective_depths[] = {
+        {600.f, 400.f},
+        {800.f, 1000.f},
+        {800.f, std::numeric_limits<float>::infinity()},
+    };
 
-  TestProgress progress[] = {
-    { 0.f, 1.f },
-    { -0.1f, 1.1f },
-  };
+  struct {
+    float min_progress;
+    float max_progress;
+  } progress[] = {
+        {0.f, 1.f}, {-0.1f, 1.1f},
+    };
 
   for (size_t i = 0; i < arraysize(perspective_depths); ++i) {
     for (size_t j = 0; j < arraysize(progress); ++j) {
@@ -1187,23 +1166,22 @@
   }
 }
 
-struct TestSkews {
-  float from_x;
-  float from_y;
-  float to_x;
-  float to_y;
-};
-
 TEST(TransformOperationTest, BlendedBoundsForSkew) {
-  TestSkews skews[] = {
-    { 1.f, 0.5f, 0.5f, 1.f },
-    { 2.f, 1.f, 0.5f, 0.5f },
-  };
+  struct {
+    float from_x;
+    float from_y;
+    float to_x;
+    float to_y;
+  } skews[] = {
+        {1.f, 0.5f, 0.5f, 1.f}, {2.f, 1.f, 0.5f, 0.5f},
+    };
 
-  TestProgress progress[] = {
-    { 0.f, 1.f },
-    { -0.1f, 1.1f },
-  };
+  struct {
+    float min_progress;
+    float max_progress;
+  } progress[] = {
+        {0.f, 1.f}, {-0.1f, 1.1f},
+    };
 
   for (size_t i = 0; i < arraysize(skews); ++i) {
     for (size_t j = 0; j < arraysize(progress); ++j) {
diff --git a/cc/base/tiling_data_unittest.cc b/cc/base/tiling_data_unittest.cc
index 9c2f944..855cd2a 100644
--- a/cc/base/tiling_data_unittest.cc
+++ b/cc/base/tiling_data_unittest.cc
@@ -1038,7 +1038,7 @@
   EXPECT_LT(expect_right, data.num_tiles_x());
   EXPECT_LT(expect_bottom, data.num_tiles_y());
 
-  std::vector<std::pair<int, int> > original_expected;
+  std::vector<std::pair<int, int>> original_expected;
   for (int x = 0; x < data.num_tiles_x(); ++x) {
     for (int y = 0; y < data.num_tiles_y(); ++y) {
       gfx::Rect bounds;
@@ -1058,7 +1058,7 @@
 
   // Verify with vanilla iterator.
   {
-    std::vector<std::pair<int, int> > expected = original_expected;
+    std::vector<std::pair<int, int>> expected = original_expected;
     for (TilingData::Iterator iter(&data, rect, include_borders); iter;
          ++iter) {
       bool found = false;
@@ -1078,7 +1078,7 @@
   // Make sure this also works with a difference iterator and an empty ignore.
   // The difference iterator never includes borders, so ignore it otherwise.
   if (!include_borders) {
-    std::vector<std::pair<int, int> > expected = original_expected;
+    std::vector<std::pair<int, int>> expected = original_expected;
     for (TilingData::DifferenceIterator iter(&data, rect, gfx::Rect()); iter;
          ++iter) {
       bool found = false;
@@ -1244,7 +1244,7 @@
               gfx::Rect consider,
               gfx::Rect ignore,
               size_t num_tiles) {
-  std::vector<std::pair<int, int> > expected;
+  std::vector<std::pair<int, int>> expected;
   for (int y = 0; y < data.num_tiles_y(); ++y) {
     for (int x = 0; x < data.num_tiles_x(); ++x) {
       gfx::Rect bounds = data.TileBounds(x, y);
@@ -1373,8 +1373,8 @@
                        const gfx::Rect& consider,
                        const gfx::Rect& ignore,
                        const gfx::Rect& center,
-                       const std::vector<std::pair<int, int> >& expected) {
-  std::vector<std::pair<int, int> > actual;
+                       const std::vector<std::pair<int, int>>& expected) {
+  std::vector<std::pair<int, int>> actual;
   for (TilingData::SpiralDifferenceIterator it(
            &tiling_data, consider, ignore, center);
        it;
@@ -1396,7 +1396,7 @@
   TilingData tiling_data(gfx::Size(10, 10), gfx::Size(30, 30), false);
   gfx::Rect consider(30, 30);
   gfx::Rect ignore;
-  std::vector<std::pair<int, int> > expected;
+  std::vector<std::pair<int, int>> expected;
 
   // Center is in the center of the tiling.
   gfx::Rect center(15, 15, 1, 1);
@@ -1507,7 +1507,7 @@
 TEST(TilingDataTest, SpiralDifferenceIteratorSmallConsider) {
   TilingData tiling_data(gfx::Size(10, 10), gfx::Size(50, 50), false);
   gfx::Rect ignore;
-  std::vector<std::pair<int, int> > expected;
+  std::vector<std::pair<int, int>> expected;
   gfx::Rect center(15, 15, 1, 1);
 
   // Consider is one cell.
@@ -1567,7 +1567,7 @@
 TEST(TilingDataTest, SpiralDifferenceIteratorHasIgnore) {
   TilingData tiling_data(gfx::Size(10, 10), gfx::Size(50, 50), false);
   gfx::Rect consider(50, 50);
-  std::vector<std::pair<int, int> > expected;
+  std::vector<std::pair<int, int>> expected;
   gfx::Rect center(15, 15, 1, 1);
 
   // Full ignore.
@@ -1641,7 +1641,7 @@
 TEST(TilingDataTest, SpiralDifferenceIteratorRectangleCenter) {
   TilingData tiling_data(gfx::Size(10, 10), gfx::Size(50, 50), false);
   gfx::Rect consider(50, 50);
-  std::vector<std::pair<int, int> > expected;
+  std::vector<std::pair<int, int>> expected;
   gfx::Rect ignore;
 
   // Two cell center
@@ -1762,7 +1762,7 @@
 
 TEST(TilingDataTest, SpiralDifferenceIteratorEdgeCases) {
   TilingData tiling_data(gfx::Size(10, 10), gfx::Size(30, 30), false);
-  std::vector<std::pair<int, int> > expected;
+  std::vector<std::pair<int, int>> expected;
   gfx::Rect center;
   gfx::Rect consider;
   gfx::Rect ignore;
diff --git a/cc/blink/web_animation_impl.cc b/cc/blink/web_animation_impl.cc
index 4989c07..24fa4ec 100644
--- a/cc/blink/web_animation_impl.cc
+++ b/cc/blink/web_animation_impl.cc
@@ -73,6 +73,10 @@
   return animation_->id();
 }
 
+int WebCompositorAnimationImpl::group() {
+  return animation_->group();
+}
+
 blink::WebCompositorAnimation::TargetProperty
 WebCompositorAnimationImpl::targetProperty() const {
   return static_cast<WebCompositorAnimationImpl::TargetProperty>(
diff --git a/cc/blink/web_animation_impl.h b/cc/blink/web_animation_impl.h
index e3925d6..585df6a 100644
--- a/cc/blink/web_animation_impl.h
+++ b/cc/blink/web_animation_impl.h
@@ -30,6 +30,7 @@
 
   // blink::WebCompositorAnimation implementation
   virtual int id();
+  virtual int group();
   virtual TargetProperty targetProperty() const;
   virtual double iterations() const;
   virtual void setIterations(double iterations);
diff --git a/cc/blink/web_compositor_support_impl.cc b/cc/blink/web_compositor_support_impl.cc
index 8073846..ae098fc 100644
--- a/cc/blink/web_compositor_support_impl.cc
+++ b/cc/blink/web_compositor_support_impl.cc
@@ -94,8 +94,15 @@
 WebCompositorAnimation* WebCompositorSupportImpl::createAnimation(
     const blink::WebCompositorAnimationCurve& curve,
     blink::WebCompositorAnimation::TargetProperty target,
+#ifdef WEB_COMPOSITOR_SUPPORT_CREATE_ANIMATION_SUPPORTS_GROUP
+    int group_id,
+#endif
     int animation_id) {
+#ifdef WEB_COMPOSITOR_SUPPORT_CREATE_ANIMATION_SUPPORTS_GROUP
+  return new WebCompositorAnimationImpl(curve, target, animation_id, group_id);
+#else
   return new WebCompositorAnimationImpl(curve, target, animation_id, 0);
+#endif
 }
 
 WebFilterAnimationCurve*
diff --git a/cc/blink/web_compositor_support_impl.h b/cc/blink/web_compositor_support_impl.h
index 2cf21ee..0f6371a 100644
--- a/cc/blink/web_compositor_support_impl.h
+++ b/cc/blink/web_compositor_support_impl.h
@@ -44,6 +44,9 @@
   virtual blink::WebCompositorAnimation* createAnimation(
       const blink::WebCompositorAnimationCurve& curve,
       blink::WebCompositorAnimation::TargetProperty target,
+#ifdef WEB_COMPOSITOR_SUPPORT_CREATE_ANIMATION_SUPPORTS_GROUP
+      int group_id,
+#endif
       int animation_id);
   virtual blink::WebFilterAnimationCurve* createFilterAnimationCurve();
   virtual blink::WebFloatAnimationCurve* createFloatAnimationCurve();
diff --git a/cc/blink/web_layer_impl.cc b/cc/blink/web_layer_impl.cc
index e638ae4..b4b9f29 100644
--- a/cc/blink/web_layer_impl.cc
+++ b/cc/blink/web_layer_impl.cc
@@ -77,10 +77,6 @@
   return layer_->id();
 }
 
-void WebLayerImpl::invalidateRect(const blink::WebFloatRect& rect) {
-  layer_->SetNeedsDisplayRect(gfx::ToEnclosingRect(rect));
-}
-
 void WebLayerImpl::invalidateRect(const blink::WebRect& rect) {
   layer_->SetNeedsDisplayRect(rect);
 }
diff --git a/cc/blink/web_layer_impl.h b/cc/blink/web_layer_impl.h
index 0a5cd12..cc94344 100644
--- a/cc/blink/web_layer_impl.h
+++ b/cc/blink/web_layer_impl.h
@@ -57,8 +57,6 @@
 
   // WebLayer implementation.
   virtual int id() const;
-  // TODO(danakj): Remove WebFloatRect version.
-  virtual void invalidateRect(const blink::WebFloatRect&);
   virtual void invalidateRect(const blink::WebRect&);
   virtual void invalidate();
   virtual void addChild(blink::WebLayer* child);
diff --git a/cc/blink/web_layer_impl_fixed_bounds.cc b/cc/blink/web_layer_impl_fixed_bounds.cc
index e9e11c1..e7ecb34 100644
--- a/cc/blink/web_layer_impl_fixed_bounds.cc
+++ b/cc/blink/web_layer_impl_fixed_bounds.cc
@@ -23,12 +23,6 @@
 WebLayerImplFixedBounds::~WebLayerImplFixedBounds() {
 }
 
-void WebLayerImplFixedBounds::invalidateRect(const blink::WebFloatRect& rect) {
-  // Partial invalidations seldom occur for such layers.
-  // Simply invalidate the whole layer to avoid transformation of coordinates.
-  invalidate();
-}
-
 void WebLayerImplFixedBounds::invalidateRect(const blink::WebRect& rect) {
   // Partial invalidations seldom occur for such layers.
   // Simply invalidate the whole layer to avoid transformation of coordinates.
diff --git a/cc/blink/web_layer_impl_fixed_bounds.h b/cc/blink/web_layer_impl_fixed_bounds.h
index 52f54cf..907975a 100644
--- a/cc/blink/web_layer_impl_fixed_bounds.h
+++ b/cc/blink/web_layer_impl_fixed_bounds.h
@@ -19,18 +19,18 @@
 class WebLayerImplFixedBounds : public WebLayerImpl {
  public:
   CC_BLINK_EXPORT WebLayerImplFixedBounds();
-  CC_BLINK_EXPORT explicit WebLayerImplFixedBounds(scoped_refptr<cc::Layer>);
+  CC_BLINK_EXPORT explicit WebLayerImplFixedBounds(
+      scoped_refptr<cc::Layer> layer);
   virtual ~WebLayerImplFixedBounds();
 
   // WebLayerImpl overrides.
-  virtual void invalidateRect(const blink::WebFloatRect& rect) override;
   virtual void invalidateRect(const blink::WebRect& rect) override;
   virtual void setTransformOrigin(
-      const blink::WebFloatPoint3D& transform_origin);
-  virtual void setBounds(const blink::WebSize& bounds);
-  virtual blink::WebSize bounds() const;
-  virtual void setTransform(const SkMatrix44& transform);
-  virtual SkMatrix44 transform() const;
+      const blink::WebFloatPoint3D& transform_origin) override;
+  virtual void setBounds(const blink::WebSize& bounds) override;
+  virtual blink::WebSize bounds() const override;
+  virtual void setTransform(const SkMatrix44& transform) override;
+  virtual SkMatrix44 transform() const override;
 
   CC_BLINK_EXPORT void SetFixedBounds(gfx::Size bounds);
 
diff --git a/cc/blink/web_to_cc_animation_delegate_adapter.cc b/cc/blink/web_to_cc_animation_delegate_adapter.cc
index 840cd4f..fcec11f 100644
--- a/cc/blink/web_to_cc_animation_delegate_adapter.cc
+++ b/cc/blink/web_to_cc_animation_delegate_adapter.cc
@@ -14,20 +14,30 @@
 
 void WebToCCAnimationDelegateAdapter::NotifyAnimationStarted(
     base::TimeTicks monotonic_time,
-    cc::Animation::TargetProperty target_property) {
+    cc::Animation::TargetProperty target_property,
+    int group) {
   delegate_->notifyAnimationStarted(
       (monotonic_time - base::TimeTicks()).InSecondsF(),
+#if WEB_COMPOSITOR_ANIMATION_DELEGATE_TAKES_GROUP
+      group);
+#else
       static_cast<blink::WebCompositorAnimation::TargetProperty>(
           target_property));
+#endif
 }
 
 void WebToCCAnimationDelegateAdapter::NotifyAnimationFinished(
     base::TimeTicks monotonic_time,
-    cc::Animation::TargetProperty target_property) {
+    cc::Animation::TargetProperty target_property,
+    int group) {
   delegate_->notifyAnimationFinished(
       (monotonic_time - base::TimeTicks()).InSecondsF(),
+#if WEB_COMPOSITOR_ANIMATION_DELEGATE_TAKES_GROUP
+      group);
+#else
       static_cast<blink::WebCompositorAnimation::TargetProperty>(
           target_property));
+#endif
 }
 
 }  // namespace cc_blink
diff --git a/cc/blink/web_to_cc_animation_delegate_adapter.h b/cc/blink/web_to_cc_animation_delegate_adapter.h
index c7e7c56..b52a758 100644
--- a/cc/blink/web_to_cc_animation_delegate_adapter.h
+++ b/cc/blink/web_to_cc_animation_delegate_adapter.h
@@ -23,10 +23,12 @@
  private:
   virtual void NotifyAnimationStarted(
       base::TimeTicks monotonic_time,
-      cc::Animation::TargetProperty target_property) override;
+      cc::Animation::TargetProperty target_property,
+      int group) override;
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      cc::Animation::TargetProperty target_property) override;
+      cc::Animation::TargetProperty target_property,
+      int group) override;
 
   blink::WebCompositorAnimationDelegate* delegate_;
 
diff --git a/cc/debug/micro_benchmark_controller_unittest.cc b/cc/debug/micro_benchmark_controller_unittest.cc
index 527e850..a5683c4 100644
--- a/cc/debug/micro_benchmark_controller_unittest.cc
+++ b/cc/debug/micro_benchmark_controller_unittest.cc
@@ -54,14 +54,14 @@
 
 TEST_F(MicroBenchmarkControllerTest, ScheduleFail) {
   int id = layer_tree_host_->ScheduleMicroBenchmark(
-      "non_existant_benchmark", scoped_ptr<base::Value>(), base::Bind(&Noop));
+      "non_existant_benchmark", nullptr, base::Bind(&Noop));
   EXPECT_EQ(id, 0);
 }
 
 TEST_F(MicroBenchmarkControllerTest, CommitScheduled) {
   EXPECT_FALSE(layer_tree_host_->needs_commit());
   int id = layer_tree_host_->ScheduleMicroBenchmark(
-      "unittest_only_benchmark", scoped_ptr<base::Value>(), base::Bind(&Noop));
+      "unittest_only_benchmark", nullptr, base::Bind(&Noop));
   EXPECT_GT(id, 0);
   EXPECT_TRUE(layer_tree_host_->needs_commit());
 }
@@ -70,7 +70,7 @@
   int run_count = 0;
   int id = layer_tree_host_->ScheduleMicroBenchmark(
       "unittest_only_benchmark",
-      scoped_ptr<base::Value>(),
+      nullptr,
       base::Bind(&IncrementCallCount, base::Unretained(&run_count)));
   EXPECT_GT(id, 0);
 
@@ -85,12 +85,12 @@
   int run_count = 0;
   int id = layer_tree_host_->ScheduleMicroBenchmark(
       "unittest_only_benchmark",
-      scoped_ptr<base::Value>(),
+      nullptr,
       base::Bind(&IncrementCallCount, base::Unretained(&run_count)));
   EXPECT_GT(id, 0);
   id = layer_tree_host_->ScheduleMicroBenchmark(
       "unittest_only_benchmark",
-      scoped_ptr<base::Value>(),
+      nullptr,
       base::Bind(&IncrementCallCount, base::Unretained(&run_count)));
   EXPECT_GT(id, 0);
 
@@ -102,12 +102,12 @@
 
   id = layer_tree_host_->ScheduleMicroBenchmark(
       "unittest_only_benchmark",
-      scoped_ptr<base::Value>(),
+      nullptr,
       base::Bind(&IncrementCallCount, base::Unretained(&run_count)));
   EXPECT_GT(id, 0);
   id = layer_tree_host_->ScheduleMicroBenchmark(
       "unittest_only_benchmark",
-      scoped_ptr<base::Value>(),
+      nullptr,
       base::Bind(&IncrementCallCount, base::Unretained(&run_count)));
   EXPECT_GT(id, 0);
 
@@ -155,7 +155,7 @@
   int run_count = 0;
   int id = layer_tree_host_->ScheduleMicroBenchmark(
       "unittest_only_benchmark",
-      scoped_ptr<base::Value>(),
+      nullptr,
       base::Bind(&IncrementCallCount, base::Unretained(&run_count)));
   EXPECT_GT(id, 0);
 
diff --git a/cc/debug/picture_record_benchmark.h b/cc/debug/picture_record_benchmark.h
index 42404b1..472f660 100644
--- a/cc/debug/picture_record_benchmark.h
+++ b/cc/debug/picture_record_benchmark.h
@@ -31,7 +31,7 @@
 
   typedef std::pair<base::TimeDelta, unsigned> TotalTime;
   std::map<std::pair<int, int>, TotalTime> times_;
-  std::vector<std::pair<int, int> > dimensions_;
+  std::vector<std::pair<int, int>> dimensions_;
 };
 
 }  // namespace cc
diff --git a/cc/debug/unittest_only_benchmark.cc b/cc/debug/unittest_only_benchmark.cc
index aa81439..2bd5be9 100644
--- a/cc/debug/unittest_only_benchmark.cc
+++ b/cc/debug/unittest_only_benchmark.cc
@@ -33,7 +33,7 @@
 }
 
 void UnittestOnlyBenchmark::DidUpdateLayers(LayerTreeHost* host) {
-  NotifyDone(scoped_ptr<base::Value>());
+  NotifyDone(nullptr);
 }
 
 bool UnittestOnlyBenchmark::ProcessMessage(scoped_ptr<base::Value> value) {
diff --git a/cc/debug/unittest_only_benchmark_impl.cc b/cc/debug/unittest_only_benchmark_impl.cc
index b249ce3..a3b040f 100644
--- a/cc/debug/unittest_only_benchmark_impl.cc
+++ b/cc/debug/unittest_only_benchmark_impl.cc
@@ -18,7 +18,7 @@
 UnittestOnlyBenchmarkImpl::~UnittestOnlyBenchmarkImpl() {}
 
 void UnittestOnlyBenchmarkImpl::DidCompleteCommit(LayerTreeHostImpl* host) {
-  NotifyDone(scoped_ptr<base::Value>());
+  NotifyDone(nullptr);
 }
 
 }  // namespace cc
diff --git a/cc/input/top_controls_manager.cc b/cc/input/top_controls_manager.cc
index 79353f2..18a93a5 100644
--- a/cc/input/top_controls_manager.cc
+++ b/cc/input/top_controls_manager.cc
@@ -202,8 +202,7 @@
   double start_time =
       (gfx::FrameTime::Now() - base::TimeTicks()).InMillisecondsF();
   top_controls_animation_->AddKeyframe(
-      FloatKeyframe::Create(start_time, client_->ControlsTopOffset(),
-                            scoped_ptr<TimingFunction>()));
+      FloatKeyframe::Create(start_time, client_->ControlsTopOffset(), nullptr));
   float max_ending_offset =
       (direction == SHOWING_CONTROLS ? 1 : -1) * top_controls_height_;
   top_controls_animation_->AddKeyframe(
diff --git a/cc/layers/delegated_renderer_layer_impl_unittest.cc b/cc/layers/delegated_renderer_layer_impl_unittest.cc
index 26e0aec..e66cc76 100644
--- a/cc/layers/delegated_renderer_layer_impl_unittest.cc
+++ b/cc/layers/delegated_renderer_layer_impl_unittest.cc
@@ -589,7 +589,8 @@
                              gfx::Rect(5, 5, 7, 7),  // visible_rect
                              RenderPassId(10, 7),    // render_pass_id
                              0,                      // mask_resource_id
-                             gfx::RectF(),           // mask_uv_rect
+                             gfx::Vector2dF(),       // mask_uv_scale
+                             gfx::Size(),            // mask_texture_size
                              FilterOperations(),     // filters
                              gfx::Vector2dF(),       // filters_scale
                              FilterOperations());    // background_filters
@@ -1021,7 +1022,8 @@
                              gfx::Rect(5, 5, 7, 7),  // visible_quad_rect
                              RenderPassId(10, 7),    // render_pass_id
                              0,                      // mask_resource_id
-                             gfx::RectF(),           // mask_uv_rect
+                             gfx::Vector2dF(),       // mask_uv_scale
+                             gfx::Size(),            // mask_texture_size,
                              FilterOperations(),     // filters
                              gfx::Vector2dF(),       // filters_scale
                              FilterOperations());    // background_filters
diff --git a/cc/layers/layer.h b/cc/layers/layer.h
index dd41669..5af7195 100644
--- a/cc/layers/layer.h
+++ b/cc/layers/layer.h
@@ -618,10 +618,10 @@
   FilterOperations background_filters_;
   LayerPositionConstraint position_constraint_;
   Layer* scroll_parent_;
-  scoped_ptr<std::set<Layer*> > scroll_children_;
+  scoped_ptr<std::set<Layer*>> scroll_children_;
 
   Layer* clip_parent_;
-  scoped_ptr<std::set<Layer*> > clip_children_;
+  scoped_ptr<std::set<Layer*>> clip_children_;
 
   gfx::Transform transform_;
   gfx::Point3F transform_origin_;
diff --git a/cc/layers/layer_impl.cc b/cc/layers/layer_impl.cc
index a361772..4c16da7 100644
--- a/cc/layers/layer_impl.cc
+++ b/cc/layers/layer_impl.cc
@@ -349,9 +349,10 @@
   return RenderPassId(0, 0);
 }
 
-ResourceProvider::ResourceId LayerImpl::ContentsResourceId() const {
+void LayerImpl::GetContentsResourceId(ResourceProvider::ResourceId* resource_id,
+                                      gfx::Size* resource_size) const {
   NOTREACHED();
-  return 0;
+  *resource_id = 0;
 }
 
 void LayerImpl::SetSentScrollDelta(const gfx::Vector2dF& sent_scroll_delta) {
@@ -1579,7 +1580,8 @@
 
 void LayerImpl::NotifyAnimationFinished(
     base::TimeTicks monotonic_time,
-    Animation::TargetProperty target_property) {
+    Animation::TargetProperty target_property,
+    int group) {
   if (target_property == Animation::ScrollOffset)
     layer_tree_impl_->InputScrollAnimationFinished();
 }
diff --git a/cc/layers/layer_impl.h b/cc/layers/layer_impl.h
index 76427a1..210b392 100644
--- a/cc/layers/layer_impl.h
+++ b/cc/layers/layer_impl.h
@@ -111,12 +111,13 @@
   virtual bool IsActive() const override;
 
   // AnimationDelegate implementation.
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override{};
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override{};
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override;
+      Animation::TargetProperty target_property,
+      int group) override;
 
   // Tree structure.
   LayerImpl* parent() { return parent_; }
@@ -200,7 +201,8 @@
                            AppendQuadsData* append_quads_data) {}
   virtual void DidDraw(ResourceProvider* resource_provider);
 
-  virtual ResourceProvider::ResourceId ContentsResourceId() const;
+  virtual void GetContentsResourceId(ResourceProvider::ResourceId* resource_id,
+                                     gfx::Size* resource_size) const;
 
   virtual bool HasDelegatedContent() const;
   virtual bool HasContributingDelegatedRenderPasses() const;
@@ -601,10 +603,10 @@
   // used. If this pointer turns out to be too heavy, we could have this (and
   // the scroll parent above) be stored in a LayerImpl -> scroll_info
   // map somewhere.
-  scoped_ptr<std::set<LayerImpl*> > scroll_children_;
+  scoped_ptr<std::set<LayerImpl*>> scroll_children_;
 
   LayerImpl* clip_parent_;
-  scoped_ptr<std::set<LayerImpl*> > clip_children_;
+  scoped_ptr<std::set<LayerImpl*>> clip_children_;
 
   // mask_layer_ can be temporarily stolen during tree sync, we need this ID to
   // confirm newly assigned layer is still the previous one
diff --git a/cc/layers/layer_lists.h b/cc/layers/layer_lists.h
index c0f7bbf..9a4084b 100644
--- a/cc/layers/layer_lists.h
+++ b/cc/layers/layer_lists.h
@@ -15,7 +15,7 @@
 class Layer;
 class LayerImpl;
 
-typedef std::vector<scoped_refptr<Layer> > LayerList;
+typedef std::vector<scoped_refptr<Layer>> LayerList;
 
 typedef ScopedPtrVector<LayerImpl> OwnedLayerImplList;
 typedef std::vector<LayerImpl*> LayerImplList;
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc
index a3ef621..bd832be 100644
--- a/cc/layers/layer_unittest.cc
+++ b/cc/layers/layer_unittest.cc
@@ -133,7 +133,7 @@
   FakeLayerTreeHostImpl host_impl_;
 
   FakeLayerTreeHostClient fake_client_;
-  scoped_ptr<StrictMock<MockLayerTreeHost> > layer_tree_host_;
+  scoped_ptr<StrictMock<MockLayerTreeHost>> layer_tree_host_;
   scoped_refptr<Layer> parent_;
   scoped_refptr<Layer> child1_;
   scoped_refptr<Layer> child2_;
@@ -1141,12 +1141,8 @@
 static bool AddTestAnimation(Layer* layer) {
   scoped_ptr<KeyframedFloatAnimationCurve> curve =
       KeyframedFloatAnimationCurve::Create();
-  curve->AddKeyframe(FloatKeyframe::Create(0.0,
-                                           0.3f,
-                                           scoped_ptr<TimingFunction>()));
-  curve->AddKeyframe(FloatKeyframe::Create(1.0,
-                                           0.7f,
-                                           scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(0.0, 0.3f, nullptr));
+  curve->AddKeyframe(FloatKeyframe::Create(1.0, 0.7f, nullptr));
   scoped_ptr<Animation> animation =
       Animation::Create(curve.Pass(), 0, 0, Animation::Opacity);
 
diff --git a/cc/layers/picture_layer_impl.cc b/cc/layers/picture_layer_impl.cc
index d31aa8c..fd8a507 100644
--- a/cc/layers/picture_layer_impl.cc
+++ b/cc/layers/picture_layer_impl.cc
@@ -806,14 +806,18 @@
   }
 }
 
-ResourceProvider::ResourceId PictureLayerImpl::ContentsResourceId() const {
-  gfx::Rect content_rect(content_bounds());
+void PictureLayerImpl::GetContentsResourceId(
+    ResourceProvider::ResourceId* resource_id,
+    gfx::Size* resource_size) const {
+  gfx::Rect content_rect(bounds());
   PictureLayerTilingSet::CoverageIterator iter(
       tilings_.get(), 1.f, content_rect, ideal_contents_scale_);
 
   // Mask resource not ready yet.
-  if (!iter || !*iter)
-    return 0;
+  if (!iter || !*iter) {
+    *resource_id = 0;
+    return;
+  }
 
   // Masks only supported if they fit on exactly one tile.
   DCHECK(iter.geometry_rect() == content_rect)
@@ -822,10 +826,13 @@
 
   const ManagedTileState::DrawInfo& draw_info = iter->draw_info();
   if (!draw_info.IsReadyToDraw() ||
-      draw_info.mode() != ManagedTileState::DrawInfo::RESOURCE_MODE)
-    return 0;
+      draw_info.mode() != ManagedTileState::DrawInfo::RESOURCE_MODE) {
+    *resource_id = 0;
+    return;
+  }
 
-  return draw_info.get_resource_id();
+  *resource_id = draw_info.get_resource_id();
+  *resource_size = iter.texture_size();
 }
 
 void PictureLayerImpl::DoPostCommitInitialization() {
@@ -1362,6 +1369,8 @@
 }
 
 bool PictureLayerImpl::AllTilesRequiredForActivationAreReadyToDraw() const {
+  TRACE_EVENT0("cc",
+               "PictureLayerImpl::AllTilesRequiredForActivationAreReadyToDraw");
   if (!layer_tree_impl()->IsPendingTree())
     return true;
 
@@ -1396,8 +1405,14 @@
       // be out of date. It is updated in the raster/eviction iterators.
       // TODO(vmpstr): Remove the comment once you can't access this information
       // from the tile.
-      if (tiling->IsTileRequiredForActivation(tile) && !tile->IsReadyToDraw())
+      if (tiling->IsTileRequiredForActivation(tile) && !tile->IsReadyToDraw()) {
+        TRACE_EVENT_INSTANT0("cc",
+                             "PictureLayerImpl::"
+                             "AllTilesRequiredForActivationAreReadyToDraw not "
+                             "ready to activate",
+                             TRACE_EVENT_SCOPE_THREAD);
         return false;
+      }
     }
   }
 
diff --git a/cc/layers/picture_layer_impl.h b/cc/layers/picture_layer_impl.h
index 2fb877e..967b930 100644
--- a/cc/layers/picture_layer_impl.h
+++ b/cc/layers/picture_layer_impl.h
@@ -139,7 +139,8 @@
   void SyncTiling(const PictureLayerTiling* tiling);
 
   // Mask-related functions.
-  virtual ResourceProvider::ResourceId ContentsResourceId() const override;
+  virtual void GetContentsResourceId(ResourceProvider::ResourceId* resource_id,
+                                     gfx::Size* resource_size) const override;
 
   virtual size_t GPUMemoryUsageInBytes() const override;
 
diff --git a/cc/layers/picture_layer_impl_unittest.cc b/cc/layers/picture_layer_impl_unittest.cc
index 135695b..9b767ce 100644
--- a/cc/layers/picture_layer_impl_unittest.cc
+++ b/cc/layers/picture_layer_impl_unittest.cc
@@ -1202,7 +1202,11 @@
   // Mask layers have a tiling with a single tile in it.
   EXPECT_EQ(1u, active_layer_->HighResTiling()->AllTilesForTesting().size());
   // The mask resource exists.
-  EXPECT_NE(0u, active_layer_->ContentsResourceId());
+  ResourceProvider::ResourceId mask_resource_id;
+  gfx::Size mask_texture_size;
+  active_layer_->GetContentsResourceId(&mask_resource_id, &mask_texture_size);
+  EXPECT_NE(0u, mask_resource_id);
+  EXPECT_EQ(mask_texture_size, active_layer_->bounds());
 
   // Resize larger than the max texture size.
   int max_texture_size = host_impl_.GetRendererCapabilities().max_texture_size;
@@ -1225,7 +1229,41 @@
   // Mask layers have a tiling, but there should be no tiles in it.
   EXPECT_EQ(0u, active_layer_->HighResTiling()->AllTilesForTesting().size());
   // The mask resource is empty.
-  EXPECT_EQ(0u, active_layer_->ContentsResourceId());
+  active_layer_->GetContentsResourceId(&mask_resource_id, &mask_texture_size);
+  EXPECT_EQ(0u, mask_resource_id);
+}
+
+TEST_F(PictureLayerImplTest, ScaledMaskLayer) {
+  gfx::Size tile_size(100, 100);
+
+  scoped_refptr<FakePicturePileImpl> valid_pile =
+      FakePicturePileImpl::CreateFilledPile(tile_size, gfx::Size(1000, 1000));
+  valid_pile->set_is_mask(true);
+  SetupPendingTree(valid_pile);
+
+  float ideal_contents_scale = 1.3f;
+  SetupDrawPropertiesAndUpdateTiles(
+      pending_layer_, ideal_contents_scale, 1.f, 1.f, 1.f, false);
+  EXPECT_EQ(ideal_contents_scale,
+            pending_layer_->HighResTiling()->contents_scale());
+  EXPECT_EQ(1u, pending_layer_->num_tilings());
+
+  pending_layer_->HighResTiling()->CreateAllTilesForTesting();
+  host_impl_.tile_manager()->InitializeTilesWithResourcesForTesting(
+      pending_layer_->HighResTiling()->AllTilesForTesting());
+
+  ActivateTree();
+
+  // Mask layers have a tiling with a single tile in it.
+  EXPECT_EQ(1u, active_layer_->HighResTiling()->AllTilesForTesting().size());
+  // The mask resource exists.
+  ResourceProvider::ResourceId mask_resource_id;
+  gfx::Size mask_texture_size;
+  active_layer_->GetContentsResourceId(&mask_resource_id, &mask_texture_size);
+  EXPECT_NE(0u, mask_resource_id);
+  gfx::Size expected_mask_texture_size = gfx::ToCeiledSize(
+      gfx::ScaleSize(active_layer_->bounds(), ideal_contents_scale));
+  EXPECT_EQ(mask_texture_size, expected_mask_texture_size);
 }
 
 TEST_F(PictureLayerImplTest, ReleaseResources) {
diff --git a/cc/layers/render_surface_impl.cc b/cc/layers/render_surface_impl.cc
index 18d50c5..ecb97a3 100644
--- a/cc/layers/render_surface_impl.cc
+++ b/cc/layers/render_surface_impl.cc
@@ -193,8 +193,11 @@
       mask_layer = nullptr;
   }
 
-  gfx::RectF mask_uv_rect(0.f, 0.f, 1.f, 1.f);
+  ResourceProvider::ResourceId mask_resource_id = 0;
+  gfx::Size mask_texture_size;
+  gfx::Vector2dF mask_uv_scale;
   if (mask_layer) {
+    mask_layer->GetContentsResourceId(&mask_resource_id, &mask_texture_size);
     gfx::Vector2dF owning_layer_draw_scale =
         MathUtil::ComputeTransform2dScaleComponents(
             owning_layer_->draw_transform(), 1.f);
@@ -202,22 +205,11 @@
         owning_layer_->content_bounds(),
         owning_layer_draw_scale.x(),
         owning_layer_draw_scale.y());
-
-    float uv_scale_x =
-        content_rect_.width() / unclipped_mask_target_size.width();
-    float uv_scale_y =
-        content_rect_.height() / unclipped_mask_target_size.height();
-
-    mask_uv_rect = gfx::RectF(
-        uv_scale_x * content_rect_.x() / content_rect_.width(),
-        uv_scale_y * content_rect_.y() / content_rect_.height(),
-        uv_scale_x,
-        uv_scale_y);
+    mask_uv_scale = gfx::Vector2dF(
+        content_rect_.width() / unclipped_mask_target_size.width(),
+        content_rect_.height() / unclipped_mask_target_size.height());
   }
 
-  ResourceProvider::ResourceId mask_resource_id =
-      mask_layer ? mask_layer->ContentsResourceId() : 0;
-
   DCHECK(owning_layer_->draw_properties().target_space_transform.IsScale2d());
   gfx::Vector2dF owning_layer_to_target_scale =
       owning_layer_->draw_properties().target_space_transform.Scale2d();
@@ -231,7 +223,8 @@
                visible_content_rect,
                render_pass_id,
                mask_resource_id,
-               mask_uv_rect,
+               mask_uv_scale,
+               mask_texture_size,
                owning_layer_->filters(),
                owning_layer_to_target_scale,
                owning_layer_->background_filters());
diff --git a/cc/layers/scrollbar_layer_impl_base.cc b/cc/layers/scrollbar_layer_impl_base.cc
index b11e981..8d93a54 100644
--- a/cc/layers/scrollbar_layer_impl_base.cc
+++ b/cc/layers/scrollbar_layer_impl_base.cc
@@ -122,7 +122,7 @@
   return true;
 }
 
-bool ScrollbarLayerImplBase::can_scroll_orientation() const {
+bool ScrollbarLayerImplBase::CanScrollOrientation() const {
   if (!scroll_layer_)
     return false;
   return scroll_layer_->user_scrollable(orientation()) && (0 < maximum());
diff --git a/cc/layers/scrollbar_layer_impl_base.h b/cc/layers/scrollbar_layer_impl_base.h
index 91cff32..85dc643 100644
--- a/cc/layers/scrollbar_layer_impl_base.h
+++ b/cc/layers/scrollbar_layer_impl_base.h
@@ -44,7 +44,7 @@
     return is_left_side_vertical_scrollbar_;
   }
 
-  bool can_scroll_orientation() const;
+  bool CanScrollOrientation() const;
 
   virtual void PushPropertiesTo(LayerImpl* layer) override;
   virtual ScrollbarLayerImplBase* ToScrollbarLayer() override;
diff --git a/cc/layers/texture_layer.cc b/cc/layers/texture_layer.cc
index 122aa3b..d53cfbe 100644
--- a/cc/layers/texture_layer.cc
+++ b/cc/layers/texture_layer.cc
@@ -51,7 +51,7 @@
 }
 
 void TextureLayer::ClearTexture() {
-  SetTextureMailbox(TextureMailbox(), scoped_ptr<SingleReleaseCallback>());
+  SetTextureMailbox(TextureMailbox(), nullptr);
 }
 
 scoped_ptr<LayerImpl> TextureLayer::CreateLayerImpl(LayerTreeImpl* tree_impl) {
diff --git a/cc/layers/texture_layer_unittest.cc b/cc/layers/texture_layer_unittest.cc
index 9b59b96..99c1e9e 100644
--- a/cc/layers/texture_layer_unittest.cc
+++ b/cc/layers/texture_layer_unittest.cc
@@ -343,8 +343,7 @@
                       test_data_.sync_point2_,
                       false))
       .Times(1);
-  test_layer->SetTextureMailbox(TextureMailbox(),
-                                scoped_ptr<SingleReleaseCallback>());
+  test_layer->SetTextureMailbox(TextureMailbox(), nullptr);
   Mock::VerifyAndClearExpectations(layer_tree_host_.get());
   Mock::VerifyAndClearExpectations(&test_data_.mock_callback_);
 
@@ -360,8 +359,7 @@
               Release2(test_data_.shared_memory_.get(),
                        0, false))
       .Times(1);
-  test_layer->SetTextureMailbox(TextureMailbox(),
-                                scoped_ptr<SingleReleaseCallback>());
+  test_layer->SetTextureMailbox(TextureMailbox(), nullptr);
   Mock::VerifyAndClearExpectations(layer_tree_host_.get());
   Mock::VerifyAndClearExpectations(&test_data_.mock_callback_);
 
@@ -773,8 +771,7 @@
         EXPECT_EQ(3, callback_count_);
         // Case #4: release mailbox that was committed but never drawn. The
         // old mailbox should be released during the next commit.
-        layer_->SetTextureMailbox(TextureMailbox(),
-                                  scoped_ptr<SingleReleaseCallback>());
+        layer_->SetTextureMailbox(TextureMailbox(), nullptr);
         break;
       case 4:
         if (layer_tree_host()->settings().impl_side_painting) {
@@ -813,8 +810,7 @@
       case 8:
         EXPECT_EQ(4, callback_count_);
         // Resetting the mailbox will call the callback now.
-        layer_->SetTextureMailbox(TextureMailbox(),
-                                  scoped_ptr<SingleReleaseCallback>());
+        layer_->SetTextureMailbox(TextureMailbox(), nullptr);
         EXPECT_EQ(5, callback_count_);
         EndTest();
         break;
@@ -975,8 +971,7 @@
   {
     scoped_ptr<TextureLayerImpl> impl_layer =
         TextureLayerImpl::Create(host_impl_.active_tree(), 1);
-    impl_layer->SetTextureMailbox(TextureMailbox(),
-                                  scoped_ptr<SingleReleaseCallbackImpl>());
+    impl_layer->SetTextureMailbox(TextureMailbox(), nullptr);
     EXPECT_FALSE(WillDraw(impl_layer.get(), DRAW_MODE_HARDWARE));
   }
 
@@ -1003,8 +998,7 @@
   {
     scoped_ptr<TextureLayerImpl> impl_layer =
         TextureLayerImpl::Create(host_impl_.active_tree(), 1);
-    impl_layer->SetTextureMailbox(TextureMailbox(),
-                                  scoped_ptr<SingleReleaseCallbackImpl>());
+    impl_layer->SetTextureMailbox(TextureMailbox(), nullptr);
     EXPECT_FALSE(WillDraw(impl_layer.get(), DRAW_MODE_SOFTWARE));
   }
 
@@ -1072,8 +1066,7 @@
   // Test resetting the mailbox.
   EXPECT_CALL(test_data_.mock_callback_,
               ReleaseImpl(test_data_.mailbox_name1_, _, false, _)).Times(1);
-  pending_layer->SetTextureMailbox(TextureMailbox(),
-                                   scoped_ptr<SingleReleaseCallbackImpl>());
+  pending_layer->SetTextureMailbox(TextureMailbox(), nullptr);
   pending_layer->PushPropertiesTo(active_layer.get());
   active_layer->DidBecomeActive();
   Mock::VerifyAndClearExpectations(&test_data_.mock_callback_);
@@ -1103,8 +1096,7 @@
   EXPECT_TRUE(impl_layer->WillDraw(
       DRAW_MODE_HARDWARE, host_impl_.active_tree()->resource_provider()));
   impl_layer->DidDraw(host_impl_.active_tree()->resource_provider());
-  impl_layer->SetTextureMailbox(TextureMailbox(),
-                                scoped_ptr<SingleReleaseCallbackImpl>());
+  impl_layer->SetTextureMailbox(TextureMailbox(), nullptr);
 }
 
 TEST_F(TextureLayerImplWithMailboxTest, TestCallbackOnInUseResource) {
diff --git a/cc/layers/tiled_layer_impl.cc b/cc/layers/tiled_layer_impl.cc
index 5a0e81d..6052591 100644
--- a/cc/layers/tiled_layer_impl.cc
+++ b/cc/layers/tiled_layer_impl.cc
@@ -53,21 +53,25 @@
 TiledLayerImpl::~TiledLayerImpl() {
 }
 
-ResourceProvider::ResourceId TiledLayerImpl::ContentsResourceId() const {
+void TiledLayerImpl::GetContentsResourceId(
+    ResourceProvider::ResourceId* resource_id,
+    gfx::Size* resource_size) const {
   // This function is only valid for single texture layers, e.g. masks.
   DCHECK(tiler_);
   // It's possible the mask layer is created but has no size or otherwise
   // can't draw.
-  if (tiler_->num_tiles_x() == 0 || tiler_->num_tiles_y() == 0)
-    return 0;
+  if (tiler_->num_tiles_x() == 0 || tiler_->num_tiles_y() == 0) {
+    *resource_id = 0;
+    return;
+  }
 
   // Any other number of tiles other than 0 or 1 is incorrect for masks.
   DCHECK_EQ(tiler_->num_tiles_x(), 1);
   DCHECK_EQ(tiler_->num_tiles_y(), 1);
 
   DrawableTile* tile = TileAt(0, 0);
-  ResourceProvider::ResourceId resource_id = tile ? tile->resource_id() : 0;
-  return resource_id;
+  *resource_id = tile ? tile->resource_id() : 0;
+  *resource_size = tiler_->tile_size();
 }
 
 bool TiledLayerImpl::HasTileAt(int i, int j) const {
diff --git a/cc/layers/tiled_layer_impl.h b/cc/layers/tiled_layer_impl.h
index 0a65a96..fb6502c 100644
--- a/cc/layers/tiled_layer_impl.h
+++ b/cc/layers/tiled_layer_impl.h
@@ -32,7 +32,8 @@
                            const Occlusion& occlusion_in_content_space,
                            AppendQuadsData* append_quads_data) override;
 
-  virtual ResourceProvider::ResourceId ContentsResourceId() const override;
+  virtual void GetContentsResourceId(ResourceProvider::ResourceId* resource_id,
+                                     gfx::Size* resource_size) const override;
 
   void set_skips_draw(bool skips_draw) { skips_draw_ = skips_draw; }
   void SetTilingData(const LayerTilingData& tiler);
diff --git a/cc/layers/tiled_layer_impl_unittest.cc b/cc/layers/tiled_layer_impl_unittest.cc
index 3d34b9f..1becc6e 100644
--- a/cc/layers/tiled_layer_impl_unittest.cc
+++ b/cc/layers/tiled_layer_impl_unittest.cc
@@ -304,7 +304,10 @@
   scoped_ptr<TiledLayerImpl> layer =
       CreateLayer(tile_size, layer_size, LayerTilingData::NO_BORDER_TEXELS);
 
-  EXPECT_EQ(0u, layer->ContentsResourceId());
+  ResourceProvider::ResourceId mask_resource_id;
+  gfx::Size mask_texture_size;
+  layer->GetContentsResourceId(&mask_resource_id, &mask_texture_size);
+  EXPECT_EQ(0u, mask_resource_id);
   EXPECT_EQ(0, layer->TilingForTesting()->num_tiles_x());
   EXPECT_EQ(0, layer->TilingForTesting()->num_tiles_y());
 }
diff --git a/cc/layers/video_frame_provider.h b/cc/layers/video_frame_provider.h
new file mode 100644
index 0000000..784d951
--- /dev/null
+++ b/cc/layers/video_frame_provider.h
@@ -0,0 +1,63 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CC_LAYERS_VIDEO_FRAME_PROVIDER_H_
+#define CC_LAYERS_VIDEO_FRAME_PROVIDER_H_
+
+#include "base/memory/ref_counted.h"
+
+namespace media {
+class VideoFrame;
+}
+
+namespace cc {
+
+// Threading notes: This class may be used in a multi threaded manner.
+// Specifically, the implementation may call GetCurrentFrame() or
+// PutCurrentFrame() from the compositor thread. If so, the caller is
+// responsible for making sure Client::DidReceiveFrame() and
+// Client::DidUpdateMatrix() are only called from this same thread.
+class VideoFrameProvider {
+ public:
+  virtual ~VideoFrameProvider() {}
+
+  class Client {
+   public:
+    // Provider will call this method to tell the client to stop using it.
+    // StopUsingProvider() may be called from any thread. The client should
+    // block until it has PutCurrentFrame() any outstanding frames.
+    virtual void StopUsingProvider() = 0;
+
+    // Notifies the provider's client that a call to GetCurrentFrame() will
+    // return new data.
+    virtual void DidReceiveFrame() = 0;
+
+    // Notifies the provider's client of a new UV transform matrix to be used.
+    virtual void DidUpdateMatrix(const float* matrix) = 0;
+
+   protected:
+    virtual ~Client() {}
+  };
+
+  // May be called from any thread, but there must be some external guarantee
+  // that the provider is not destroyed before this call returns.
+  virtual void SetVideoFrameProviderClient(Client* client) = 0;
+
+  // This function places a lock on the current frame and returns a pointer to
+  // it. Calls to this method should always be followed with a call to
+  // PutCurrentFrame().
+  // Only the current provider client should call this function.
+  virtual scoped_refptr<media::VideoFrame> GetCurrentFrame() = 0;
+
+  // This function releases the lock on the video frame. It should always be
+  // called after GetCurrentFrame(). Frames passed into this method
+  // should no longer be referenced after the call is made. Only the current
+  // provider client should call this function.
+  virtual void PutCurrentFrame(
+      const scoped_refptr<media::VideoFrame>& frame) = 0;
+};
+
+}  // namespace cc
+
+#endif  // CC_LAYERS_VIDEO_FRAME_PROVIDER_H_
diff --git a/cc/layers/video_frame_provider_client_impl.cc b/cc/layers/video_frame_provider_client_impl.cc
new file mode 100644
index 0000000..50333c1
--- /dev/null
+++ b/cc/layers/video_frame_provider_client_impl.cc
@@ -0,0 +1,95 @@
+// Copyright 2013 The Chromium 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 "cc/layers/video_frame_provider_client_impl.h"
+
+#include "base/debug/trace_event.h"
+#include "cc/base/math_util.h"
+#include "cc/layers/video_layer_impl.h"
+#include "media/base/video_frame.h"
+
+namespace cc {
+
+// static
+scoped_refptr<VideoFrameProviderClientImpl>
+    VideoFrameProviderClientImpl::Create(
+        VideoFrameProvider* provider) {
+  return make_scoped_refptr(
+      new VideoFrameProviderClientImpl(provider));
+}
+
+VideoFrameProviderClientImpl::~VideoFrameProviderClientImpl() {}
+
+VideoFrameProviderClientImpl::VideoFrameProviderClientImpl(
+    VideoFrameProvider* provider)
+    : active_video_layer_(nullptr), provider_(provider) {
+  // This only happens during a commit on the compositor thread while the main
+  // thread is blocked. That makes this a thread-safe call to set the video
+  // frame provider client that does not require a lock. The same is true of
+  // the call to Stop().
+  provider_->SetVideoFrameProviderClient(this);
+
+  // This matrix is the default transformation for stream textures, and flips
+  // on the Y axis.
+  stream_texture_matrix_ = gfx::Transform(
+      1.0, 0.0, 0.0, 0.0,
+      0.0, -1.0, 0.0, 1.0,
+      0.0, 0.0, 1.0, 0.0,
+      0.0, 0.0, 0.0, 1.0);
+}
+
+void VideoFrameProviderClientImpl::Stop() {
+  if (!provider_)
+    return;
+  provider_->SetVideoFrameProviderClient(nullptr);
+  provider_ = nullptr;
+}
+
+scoped_refptr<media::VideoFrame>
+VideoFrameProviderClientImpl::AcquireLockAndCurrentFrame() {
+  provider_lock_.Acquire();  // Balanced by call to ReleaseLock().
+  if (!provider_)
+    return nullptr;
+
+  return provider_->GetCurrentFrame();
+}
+
+void VideoFrameProviderClientImpl::PutCurrentFrame(
+    const scoped_refptr<media::VideoFrame>& frame) {
+  provider_lock_.AssertAcquired();
+  provider_->PutCurrentFrame(frame);
+}
+
+void VideoFrameProviderClientImpl::ReleaseLock() {
+  provider_lock_.AssertAcquired();
+  provider_lock_.Release();
+}
+
+void VideoFrameProviderClientImpl::StopUsingProvider() {
+  // Block the provider from shutting down until this client is done
+  // using the frame.
+  base::AutoLock locker(provider_lock_);
+  provider_ = nullptr;
+}
+
+void VideoFrameProviderClientImpl::DidReceiveFrame() {
+  TRACE_EVENT1("cc",
+               "VideoFrameProviderClientImpl::DidReceiveFrame",
+               "active_video_layer",
+               !!active_video_layer_);
+  if (active_video_layer_)
+    active_video_layer_->SetNeedsRedraw();
+}
+
+void VideoFrameProviderClientImpl::DidUpdateMatrix(const float* matrix) {
+  stream_texture_matrix_ = gfx::Transform(
+      matrix[0], matrix[4], matrix[8], matrix[12],
+      matrix[1], matrix[5], matrix[9], matrix[13],
+      matrix[2], matrix[6], matrix[10], matrix[14],
+      matrix[3], matrix[7], matrix[11], matrix[15]);
+  if (active_video_layer_)
+    active_video_layer_->SetNeedsRedraw();
+}
+
+}  // namespace cc
diff --git a/cc/output/gl_renderer.cc b/cc/output/gl_renderer.cc
index 4e99db1..e8a2c9d 100644
--- a/cc/output/gl_renderer.cc
+++ b/cc/output/gl_renderer.cc
@@ -13,6 +13,7 @@
 #include "base/debug/trace_event.h"
 #include "base/logging.h"
 #include "cc/base/math_util.h"
+#include "cc/layers/video_layer_impl.h"
 #include "cc/output/compositor_frame.h"
 #include "cc/output/compositor_frame_metadata.h"
 #include "cc/output/context_provider.h"
@@ -660,10 +661,9 @@
   desc.fHeight = source.height();
   desc.fConfig = kSkia8888_GrPixelConfig;
   desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
-  GrAutoScratchTexture scratch_texture(
-      use_gr_context->context(), desc, GrContext::kExact_ScratchTexMatch);
   skia::RefPtr<GrTexture> backing_store =
-      skia::AdoptRef(scratch_texture.detach());
+      skia::AdoptRef(use_gr_context->context()->refScratchTexture(
+          desc, GrContext::kExact_ScratchTexMatch));
   if (!backing_store) {
     TRACE_EVENT_INSTANT0("cc",
                          "ApplyImageFilter scratch texture allocation failed",
@@ -822,10 +822,9 @@
   desc.fHeight = source.height();
   desc.fConfig = kSkia8888_GrPixelConfig;
   desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
-  GrAutoScratchTexture scratch_texture(
-      use_gr_context->context(), desc, GrContext::kExact_ScratchTexMatch);
   skia::RefPtr<GrTexture> backing_store =
-      skia::AdoptRef(scratch_texture.detach());
+      skia::AdoptRef(use_gr_context->context()->refScratchTexture(
+          desc, GrContext::kExact_ScratchTexMatch));
   if (!backing_store) {
     TRACE_EVENT_INSTANT0(
         "cc",
@@ -1090,7 +1089,7 @@
 
   // TODO(senorblanco): Cache this value so that we don't have to do it for both
   // the surface and its replica.  Apply filters to the contents texture.
-  skia::RefPtr<SkImage> filter_bitmap;
+  skia::RefPtr<SkImage> filter_image;
   SkScalar color_matrix[20];
   bool use_color_matrix = false;
   if (!quad->filters.IsEmpty()) {
@@ -1110,13 +1109,12 @@
         // in the compositor.
         use_color_matrix = true;
       } else {
-        filter_bitmap =
-            ApplyImageFilter(ScopedUseGrContext::Create(this, frame),
-                             resource_provider_,
-                             quad->rect.origin(),
-                             quad->filters_scale,
-                             filter.get(),
-                             contents_texture);
+        filter_image = ApplyImageFilter(ScopedUseGrContext::Create(this, frame),
+                                        resource_provider_,
+                                        quad->rect.origin(),
+                                        quad->filters_scale,
+                                        filter.get(),
+                                        contents_texture);
       }
     }
   }
@@ -1143,10 +1141,10 @@
       // If blending is applied using shaders, the background texture with
       // filters will be used as backdrop for blending operation, so we don't
       // need to copy it to the frame buffer.
-      filter_bitmap =
+      filter_image =
           ApplyBlendModeWithBackdrop(ScopedUseGrContext::Create(this, frame),
                                      resource_provider_,
-                                     filter_bitmap,
+                                     filter_image,
                                      contents_texture,
                                      background_texture.get(),
                                      quad->shared_quad_state->blend_mode);
@@ -1169,20 +1167,22 @@
     device_layer_edges.InflateAntiAliasingDistance();
   }
 
-  scoped_ptr<ResourceProvider::ScopedReadLockGL> mask_resource_lock;
+  scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
   unsigned mask_texture_id = 0;
+  SamplerType mask_sampler = SamplerTypeNA;
   if (quad->mask_resource_id) {
-    mask_resource_lock.reset(new ResourceProvider::ScopedReadLockGL(
-        resource_provider_, quad->mask_resource_id));
+    mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
+        resource_provider_, quad->mask_resource_id, GL_TEXTURE1, GL_LINEAR));
     mask_texture_id = mask_resource_lock->texture_id();
+    mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
   }
 
   // TODO(danakj): use the background_texture and blend the background in with
   // this draw instead of having a separate copy of the background texture.
 
   scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
-  if (filter_bitmap) {
-    GrTexture* texture = filter_bitmap->getTexture();
+  if (filter_image) {
+    GrTexture* texture = filter_image->getTexture();
     DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
     gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
   } else {
@@ -1369,29 +1369,22 @@
   if (shader_mask_sampler_location != -1) {
     DCHECK_NE(shader_mask_tex_coord_scale_location, 1);
     DCHECK_NE(shader_mask_tex_coord_offset_location, 1);
+    DCHECK_EQ(SamplerType2D, mask_sampler);
     GLC(gl_, gl_->Uniform1i(shader_mask_sampler_location, 1));
 
-    float mask_tex_scale_x = quad->mask_uv_rect.width() / tex_scale_x;
-    float mask_tex_scale_y = quad->mask_uv_rect.height() / tex_scale_y;
+    gfx::RectF mask_uv_rect = quad->MaskUVRect();
 
     // Mask textures are oriented vertically flipped relative to the framebuffer
     // and the RenderPass contents texture, so we flip the tex coords from the
     // RenderPass texture to find the mask texture coords.
     GLC(gl_,
         gl_->Uniform2f(shader_mask_tex_coord_offset_location,
-                       quad->mask_uv_rect.x(),
-                       quad->mask_uv_rect.y() + quad->mask_uv_rect.height()));
+                       mask_uv_rect.x(),
+                       mask_uv_rect.bottom()));
     GLC(gl_,
         gl_->Uniform2f(shader_mask_tex_coord_scale_location,
-                       mask_tex_scale_x,
-                       -mask_tex_scale_y));
-    shader_mask_sampler_lock = make_scoped_ptr(
-        new ResourceProvider::ScopedSamplerGL(resource_provider_,
-                                              quad->mask_resource_id,
-                                              GL_TEXTURE1,
-                                              GL_LINEAR));
-    DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
-              shader_mask_sampler_lock->target());
+                       mask_uv_rect.width() / tex_scale_x,
+                       -mask_uv_rect.height() / tex_scale_y));
   }
 
   if (shader_edge_location != -1) {
@@ -1440,7 +1433,7 @@
 
   // Flush the compositor context before the filter bitmap goes out of
   // scope, so the draw gets processed before the filter texture gets deleted.
-  if (filter_bitmap)
+  if (filter_image)
     GLC(gl_, gl_->Flush());
 
   if (CanApplyBlendModeUsingBlendFunc(blend_mode))
diff --git a/cc/output/renderer_pixeltest.cc b/cc/output/renderer_pixeltest.cc
index 17d9d5d..3fe1caf 100644
--- a/cc/output/renderer_pixeltest.cc
+++ b/cc/output/renderer_pixeltest.cc
@@ -12,6 +12,7 @@
 #include "cc/test/fake_picture_pile_impl.h"
 #include "cc/test/pixel_test.h"
 #include "gpu/command_buffer/client/gles2_interface.h"
+#include "media/base/video_frame.h"
 #include "third_party/skia/include/core/SkColorPriv.h"
 #include "third_party/skia/include/core/SkImageFilter.h"
 #include "third_party/skia/include/core/SkMatrix.h"
@@ -102,11 +103,12 @@
                rect,
                rect,
                pass_id,
-               0,                     // mask_resource_id
-               gfx::RectF(1.f, 1.f),  // mask_uv_rect
-               FilterOperations(),    // foreground filters
-               gfx::Vector2dF(),      // filters scale
-               FilterOperations());   // background filters
+               0,                    // mask_resource_id
+               gfx::Vector2dF(),     // mask_uv_scale
+               gfx::Size(),          // mask_texture_size
+               FilterOperations(),   // foreground filters
+               gfx::Vector2dF(),     // filters scale
+               FilterOperations());  // background filters
 }
 
 void CreateTestTextureDrawQuad(const gfx::Rect& rect,
@@ -383,6 +385,346 @@
       FuzzyPixelOffByOneComparator(true)));
 }
 
+class VideoGLRendererPixelTest : public GLRendererPixelTest {
+ protected:
+  void CreateTestYUVVideoDrawQuad_Striped(const SharedQuadState* shared_state,
+                                          media::VideoFrame::Format format,
+                                          bool is_transparent,
+                                          const gfx::RectF& tex_coord_rect,
+                                          RenderPass* render_pass) {
+    const gfx::Rect rect(this->device_viewport_size_);
+
+    scoped_refptr<media::VideoFrame> video_frame =
+        media::VideoFrame::CreateFrame(
+            format, rect.size(), rect, rect.size(), base::TimeDelta());
+
+    // YUV values representing a striped pattern, for validating texture
+    // coordinates for sampling.
+    uint8_t y_value = 0;
+    uint8_t u_value = 0;
+    uint8_t v_value = 0;
+    for (int i = 0; i < video_frame->rows(media::VideoFrame::kYPlane); ++i) {
+      uint8_t* y_row = video_frame->data(media::VideoFrame::kYPlane) +
+                       video_frame->stride(media::VideoFrame::kYPlane) * i;
+      for (int j = 0; j < video_frame->row_bytes(media::VideoFrame::kYPlane);
+           ++j) {
+        y_row[j] = (y_value += 1);
+      }
+    }
+    for (int i = 0; i < video_frame->rows(media::VideoFrame::kUPlane); ++i) {
+      uint8_t* u_row = video_frame->data(media::VideoFrame::kUPlane) +
+                       video_frame->stride(media::VideoFrame::kUPlane) * i;
+      uint8_t* v_row = video_frame->data(media::VideoFrame::kVPlane) +
+                       video_frame->stride(media::VideoFrame::kVPlane) * i;
+      for (int j = 0; j < video_frame->row_bytes(media::VideoFrame::kUPlane);
+           ++j) {
+        u_row[j] = (u_value += 3);
+        v_row[j] = (v_value += 5);
+      }
+    }
+    CreateTestYUVVideoDrawQuad_FromVideoFrame(
+        shared_state, video_frame, is_transparent, tex_coord_rect, render_pass);
+  }
+
+  void CreateTestYUVVideoDrawQuad_Solid(const SharedQuadState* shared_state,
+                                        media::VideoFrame::Format format,
+                                        bool is_transparent,
+                                        const gfx::RectF& tex_coord_rect,
+                                        uint8 y,
+                                        uint8 u,
+                                        uint8 v,
+                                        RenderPass* render_pass) {
+    const gfx::Rect rect(this->device_viewport_size_);
+
+    scoped_refptr<media::VideoFrame> video_frame =
+        media::VideoFrame::CreateFrame(
+            format, rect.size(), rect, rect.size(), base::TimeDelta());
+
+    // YUV values of a solid, constant, color. Useful for testing that color
+    // space/color range are being handled properly.
+    memset(video_frame->data(media::VideoFrame::kYPlane),
+           y,
+           video_frame->stride(media::VideoFrame::kYPlane) *
+               video_frame->rows(media::VideoFrame::kYPlane));
+    memset(video_frame->data(media::VideoFrame::kUPlane),
+           u,
+           video_frame->stride(media::VideoFrame::kUPlane) *
+               video_frame->rows(media::VideoFrame::kUPlane));
+    memset(video_frame->data(media::VideoFrame::kVPlane),
+           v,
+           video_frame->stride(media::VideoFrame::kVPlane) *
+               video_frame->rows(media::VideoFrame::kVPlane));
+
+    CreateTestYUVVideoDrawQuad_FromVideoFrame(
+        shared_state, video_frame, is_transparent, tex_coord_rect, render_pass);
+  }
+
+  void CreateTestYUVVideoDrawQuad_FromVideoFrame(
+      const SharedQuadState* shared_state,
+      scoped_refptr<media::VideoFrame> video_frame,
+      bool is_transparent,
+      const gfx::RectF& tex_coord_rect,
+      RenderPass* render_pass) {
+    const bool with_alpha = (video_frame->format() == media::VideoFrame::YV12A);
+    const YUVVideoDrawQuad::ColorSpace color_space =
+        (video_frame->format() == media::VideoFrame::YV12J
+             ? YUVVideoDrawQuad::REC_601_JPEG
+             : YUVVideoDrawQuad::REC_601);
+    const gfx::Rect rect(this->device_viewport_size_);
+    const gfx::Rect opaque_rect(0, 0, 0, 0);
+
+    if (with_alpha)
+      memset(video_frame->data(media::VideoFrame::kAPlane),
+             is_transparent ? 0 : 128,
+             video_frame->stride(media::VideoFrame::kAPlane) *
+                 video_frame->rows(media::VideoFrame::kAPlane));
+
+    VideoFrameExternalResources resources =
+        video_resource_updater_->CreateExternalResourcesFromVideoFrame(
+            video_frame);
+
+    EXPECT_EQ(VideoFrameExternalResources::YUV_RESOURCE, resources.type);
+    EXPECT_EQ(media::VideoFrame::NumPlanes(video_frame->format()),
+              resources.mailboxes.size());
+    EXPECT_EQ(media::VideoFrame::NumPlanes(video_frame->format()),
+              resources.release_callbacks.size());
+
+    ResourceProvider::ResourceId y_resource =
+        resource_provider_->CreateResourceFromTextureMailbox(
+            resources.mailboxes[media::VideoFrame::kYPlane],
+            SingleReleaseCallbackImpl::Create(
+                resources.release_callbacks[media::VideoFrame::kYPlane]));
+    ResourceProvider::ResourceId u_resource =
+        resource_provider_->CreateResourceFromTextureMailbox(
+            resources.mailboxes[media::VideoFrame::kUPlane],
+            SingleReleaseCallbackImpl::Create(
+                resources.release_callbacks[media::VideoFrame::kUPlane]));
+    ResourceProvider::ResourceId v_resource =
+        resource_provider_->CreateResourceFromTextureMailbox(
+            resources.mailboxes[media::VideoFrame::kVPlane],
+            SingleReleaseCallbackImpl::Create(
+                resources.release_callbacks[media::VideoFrame::kVPlane]));
+    ResourceProvider::ResourceId a_resource = 0;
+    if (with_alpha) {
+      a_resource = resource_provider_->CreateResourceFromTextureMailbox(
+          resources.mailboxes[media::VideoFrame::kAPlane],
+          SingleReleaseCallbackImpl::Create(
+              resources.release_callbacks[media::VideoFrame::kAPlane]));
+    }
+
+    YUVVideoDrawQuad* yuv_quad =
+        render_pass->CreateAndAppendDrawQuad<YUVVideoDrawQuad>();
+    yuv_quad->SetNew(shared_state,
+                     rect,
+                     opaque_rect,
+                     rect,
+                     tex_coord_rect,
+                     y_resource,
+                     u_resource,
+                     v_resource,
+                     a_resource,
+                     color_space);
+  }
+
+  virtual void SetUp() override {
+    GLRendererPixelTest::SetUp();
+    video_resource_updater_.reset(new VideoResourceUpdater(
+        output_surface_->context_provider(), resource_provider_.get()));
+  }
+
+ private:
+  scoped_ptr<VideoResourceUpdater> video_resource_updater_;
+};
+
+TEST_F(VideoGLRendererPixelTest, SimpleYUVRect) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  CreateTestYUVVideoDrawQuad_Striped(shared_state,
+                                     media::VideoFrame::YV12,
+                                     false,
+                                     gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
+                                     pass.get());
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  EXPECT_TRUE(
+      this->RunPixelTest(&pass_list,
+                         base::FilePath(FILE_PATH_LITERAL("yuv_stripes.png")),
+                         FuzzyPixelOffByOneComparator(true)));
+}
+
+TEST_F(VideoGLRendererPixelTest, OffsetYUVRect) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  // Intentionally sets frame format to I420 for testing coverage.
+  CreateTestYUVVideoDrawQuad_Striped(shared_state,
+                                     media::VideoFrame::I420,
+                                     false,
+                                     gfx::RectF(0.125f, 0.25f, 0.75f, 0.5f),
+                                     pass.get());
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  EXPECT_TRUE(this->RunPixelTest(
+      &pass_list,
+      base::FilePath(FILE_PATH_LITERAL("yuv_stripes_offset.png")),
+      FuzzyPixelOffByOneComparator(true)));
+}
+
+TEST_F(VideoGLRendererPixelTest, SimpleYUVRectBlack) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  // In MPEG color range YUV values of (15,128,128) should produce black.
+  CreateTestYUVVideoDrawQuad_Solid(shared_state,
+                                   media::VideoFrame::YV12,
+                                   false,
+                                   gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
+                                   15,
+                                   128,
+                                   128,
+                                   pass.get());
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  // If we didn't get black out of the YUV values above, then we probably have a
+  // color range issue.
+  EXPECT_TRUE(this->RunPixelTest(&pass_list,
+                                 base::FilePath(FILE_PATH_LITERAL("black.png")),
+                                 FuzzyPixelOffByOneComparator(true)));
+}
+
+TEST_F(VideoGLRendererPixelTest, SimpleYUVJRect) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  // YUV of (149,43,21) should be green (0,255,0) in RGB.
+  CreateTestYUVVideoDrawQuad_Solid(shared_state,
+                                   media::VideoFrame::YV12J,
+                                   false,
+                                   gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
+                                   149,
+                                   43,
+                                   21,
+                                   pass.get());
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  EXPECT_TRUE(this->RunPixelTest(&pass_list,
+                                 base::FilePath(FILE_PATH_LITERAL("green.png")),
+                                 FuzzyPixelOffByOneComparator(true)));
+}
+
+TEST_F(VideoGLRendererPixelTest, SimpleYUVJRectGrey) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  // Dark grey in JPEG color range (in MPEG, this is black).
+  CreateTestYUVVideoDrawQuad_Solid(shared_state,
+                                   media::VideoFrame::YV12J,
+                                   false,
+                                   gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
+                                   15,
+                                   128,
+                                   128,
+                                   pass.get());
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  EXPECT_TRUE(
+      this->RunPixelTest(&pass_list,
+                         base::FilePath(FILE_PATH_LITERAL("dark_grey.png")),
+                         FuzzyPixelOffByOneComparator(true)));
+}
+
+TEST_F(VideoGLRendererPixelTest, SimpleYUVARect) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  CreateTestYUVVideoDrawQuad_Striped(shared_state,
+                                     media::VideoFrame::YV12A,
+                                     false,
+                                     gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
+                                     pass.get());
+
+  SolidColorDrawQuad* color_quad =
+      pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
+  color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false);
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  EXPECT_TRUE(this->RunPixelTest(
+      &pass_list,
+      base::FilePath(FILE_PATH_LITERAL("yuv_stripes_alpha.png")),
+      FuzzyPixelOffByOneComparator(true)));
+}
+
+TEST_F(VideoGLRendererPixelTest, FullyTransparentYUVARect) {
+  gfx::Rect rect(this->device_viewport_size_);
+
+  RenderPassId id(1, 1);
+  scoped_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
+
+  SharedQuadState* shared_state =
+      CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
+
+  CreateTestYUVVideoDrawQuad_Striped(shared_state,
+                                     media::VideoFrame::YV12A,
+                                     true,
+                                     gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
+                                     pass.get());
+
+  SolidColorDrawQuad* color_quad =
+      pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
+  color_quad->SetNew(shared_state, rect, rect, SK_ColorBLACK, false);
+
+  RenderPassList pass_list;
+  pass_list.push_back(pass.Pass());
+
+  EXPECT_TRUE(this->RunPixelTest(
+      &pass_list,
+      base::FilePath(FILE_PATH_LITERAL("black.png")),
+      ExactPixelComparator(true)));
+}
+
 TYPED_TEST(RendererPixelTest, FastPassColorFilterAlpha) {
   gfx::Rect viewport_rect(this->device_viewport_size_);
 
@@ -457,7 +799,8 @@
                            pass_rect,
                            child_pass_id,
                            0,
-                           gfx::RectF(),
+                           gfx::Vector2dF(),
+                           gfx::Size(),
                            filters,
                            gfx::Vector2dF(),
                            FilterOperations());
@@ -528,7 +871,8 @@
                            pass_rect,
                            child_pass_id,
                            0,
-                           gfx::RectF(),
+                           gfx::Vector2dF(),
+                           gfx::Size(),
                            filters,
                            gfx::Vector2dF(),
                            FilterOperations());
@@ -598,7 +942,8 @@
                            pass_rect,
                            child_pass_id,
                            0,
-                           gfx::RectF(),
+                           gfx::Vector2dF(),
+                           gfx::Size(),
                            filters,
                            gfx::Vector2dF(),
                            FilterOperations());
@@ -690,7 +1035,8 @@
                            pass_rect,
                            child_pass_id,
                            0,
-                           gfx::RectF(),
+                           gfx::Vector2dF(),
+                           gfx::Size(),
                            filters,
                            gfx::Vector2dF(),
                            FilterOperations());
@@ -896,10 +1242,11 @@
                     sub_rect,
                     child_pass_id,
                     mask_resource_id,
-                    gfx::RectF(0.5f, 0.5f, 2.f, 1.f),  // mask_uv_rect
-                    FilterOperations(),                // foreground filters
-                    gfx::Vector2dF(),                  // filters scale
-                    FilterOperations());               // background filters
+                    gfx::Vector2dF(2.f, 1.f),     // mask_uv_scale
+                    gfx::Size(mask_rect.size()),  // mask_texture_size
+                    FilterOperations(),           // foreground filters
+                    gfx::Vector2dF(),             // filters scale
+                    FilterOperations());          // background filters
 
   // White background behind the masked render pass.
   SolidColorDrawQuad* white =
@@ -963,16 +1310,16 @@
                                     filter_pass.get());
       RenderPassDrawQuad* filter_pass_quad =
           root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
-      filter_pass_quad->SetNew(
-          shared_state,
-          filter_pass_content_rect_,
-          filter_pass_content_rect_,
-          filter_pass_id,
-          0,                          // mask_resource_id
-          gfx::RectF(),               // mask_uv_rect
-          FilterOperations(),         // filters
-          gfx::Vector2dF(),           // filters_scale
-          this->background_filters_);
+      filter_pass_quad->SetNew(shared_state,
+                               filter_pass_content_rect_,
+                               filter_pass_content_rect_,
+                               filter_pass_id,
+                               0,                   // mask_resource_id
+                               gfx::Vector2dF(),    // mask_uv_scale
+                               gfx::Size(),         // mask_texture_size
+                               FilterOperations(),  // filters
+                               gfx::Vector2dF(),    // filters_scale
+                               this->background_filters_);
     }
 
     const int kColumnWidth = device_viewport_rect.width() / 3;
diff --git a/cc/output/shader.cc b/cc/output/shader.cc
index 72d89d2..8a25214 100644
--- a/cc/output/shader.cc
+++ b/cc/output/shader.cc
@@ -13,8 +13,9 @@
 
 #define SHADER0(Src) #Src
 #define VERTEX_SHADER(Src) SetVertexTexCoordPrecision(SHADER0(Src))
-#define FRAGMENT_SHADER(Src) SetFragmentTexCoordPrecision( \
-    precision, SetFragmentSamplerType(sampler, SHADER0(Src)))
+#define FRAGMENT_SHADER(Src)              \
+  SetFragmentTexCoordPrecision(precision, \
+                               SetFragmentSamplerType(sampler, SHADER0(Src)))
 
 using gpu::gles2::GLES2Interface;
 
@@ -35,21 +36,20 @@
 }
 
 static std::string SetFragmentTexCoordPrecision(
-    TexCoordPrecision requested_precision, std::string shader_string) {
+    TexCoordPrecision requested_precision,
+    std::string shader_string) {
   switch (requested_precision) {
     case TexCoordPrecisionHigh:
       DCHECK_NE(shader_string.find("TexCoordPrecision"), std::string::npos);
-      return
-          "#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
-          "  #define TexCoordPrecision highp\n"
-          "#else\n"
-          "  #define TexCoordPrecision mediump\n"
-          "#endif\n" +
-          shader_string;
+      return "#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
+             "  #define TexCoordPrecision highp\n"
+             "#else\n"
+             "  #define TexCoordPrecision mediump\n"
+             "#endif\n" +
+             shader_string;
     case TexCoordPrecisionMedium:
       DCHECK_NE(shader_string.find("TexCoordPrecision"), std::string::npos);
-      return "#define TexCoordPrecision mediump\n" +
-          shader_string;
+      return "#define TexCoordPrecision mediump\n" + shader_string;
     case TexCoordPrecisionNA:
       DCHECK_EQ(shader_string.find("TexCoordPrecision"), std::string::npos);
       DCHECK_EQ(shader_string.find("texture2D"), std::string::npos);
@@ -67,24 +67,24 @@
   // we are unlikely to be vertex shader bound when drawing large quads.
   // Also, some vertex shaders mutate the texture coordinate in such a
   // way that the effective precision might be lower than expected.
-  return "#define TexCoordPrecision highp\n" +
-      std::string(shader_string);
+  return "#define TexCoordPrecision highp\n" + std::string(shader_string);
 }
 
 TexCoordPrecision TexCoordPrecisionRequired(GLES2Interface* context,
-                                            int *highp_threshold_cache,
+                                            int* highp_threshold_cache,
                                             int highp_threshold_min,
-                                            int x, int y) {
+                                            int x,
+                                            int y) {
   if (*highp_threshold_cache == 0) {
     // Initialize range and precision with minimum spec values for when
     // GetShaderPrecisionFormat is a test stub.
     // TODO(brianderson): Implement better stubs of GetShaderPrecisionFormat
     // everywhere.
-    GLint range[2] = { 14, 14 };
+    GLint range[2] = {14, 14};
     GLint precision = 10;
-    GLC(context, context->GetShaderPrecisionFormat(GL_FRAGMENT_SHADER,
-                                                   GL_MEDIUM_FLOAT,
-                                                   range, &precision));
+    GLC(context,
+        context->GetShaderPrecisionFormat(
+            GL_FRAGMENT_SHADER, GL_MEDIUM_FLOAT, range, &precision));
     *highp_threshold_cache = 1 << precision;
   }
 
@@ -94,32 +94,29 @@
   return TexCoordPrecisionMedium;
 }
 
-static std::string SetFragmentSamplerType(
-    SamplerType requested_type, std::string shader_string) {
+static std::string SetFragmentSamplerType(SamplerType requested_type,
+                                          std::string shader_string) {
   switch (requested_type) {
     case SamplerType2D:
       DCHECK_NE(shader_string.find("SamplerType"), std::string::npos);
       DCHECK_NE(shader_string.find("TextureLookup"), std::string::npos);
-      return
-          "#define SamplerType sampler2D\n"
-          "#define TextureLookup texture2D\n" +
-          shader_string;
+      return "#define SamplerType sampler2D\n"
+             "#define TextureLookup texture2D\n" +
+             shader_string;
     case SamplerType2DRect:
       DCHECK_NE(shader_string.find("SamplerType"), std::string::npos);
       DCHECK_NE(shader_string.find("TextureLookup"), std::string::npos);
-      return
-          "#extension GL_ARB_texture_rectangle : require\n"
-          "#define SamplerType sampler2DRect\n"
-          "#define TextureLookup texture2DRect\n" +
-          shader_string;
+      return "#extension GL_ARB_texture_rectangle : require\n"
+             "#define SamplerType sampler2DRect\n"
+             "#define TextureLookup texture2DRect\n" +
+             shader_string;
     case SamplerTypeExternalOES:
       DCHECK_NE(shader_string.find("SamplerType"), std::string::npos);
       DCHECK_NE(shader_string.find("TextureLookup"), std::string::npos);
-      return
-          "#extension GL_OES_EGL_image_external : require\n"
-          "#define SamplerType samplerExternalOES\n"
-          "#define TextureLookup texture2D\n" +
-          shader_string;
+      return "#extension GL_OES_EGL_image_external : require\n"
+             "#define SamplerType samplerExternalOES\n"
+             "#define TextureLookup texture2D\n" +
+             shader_string;
     case SamplerTypeNA:
       DCHECK_EQ(shader_string.find("SamplerType"), std::string::npos);
       DCHECK_EQ(shader_string.find("TextureLookup"), std::string::npos);
@@ -138,21 +135,25 @@
                                             int highp_threshold_min,
                                             const gfx::Point& max_coordinate) {
   return TexCoordPrecisionRequired(context,
-                                   highp_threshold_cache, highp_threshold_min,
-                                   max_coordinate.x(), max_coordinate.y());
+                                   highp_threshold_cache,
+                                   highp_threshold_min,
+                                   max_coordinate.x(),
+                                   max_coordinate.y());
 }
 
 TexCoordPrecision TexCoordPrecisionRequired(GLES2Interface* context,
-                                            int *highp_threshold_cache,
+                                            int* highp_threshold_cache,
                                             int highp_threshold_min,
                                             const gfx::Size& max_size) {
   return TexCoordPrecisionRequired(context,
-                                   highp_threshold_cache, highp_threshold_min,
-                                   max_size.width(), max_size.height());
+                                   highp_threshold_cache,
+                                   highp_threshold_min,
+                                   max_size.width(),
+                                   max_size.height());
 }
 
-VertexShaderPosTex::VertexShaderPosTex()
-      : matrix_location_(-1) {}
+VertexShaderPosTex::VertexShaderPosTex() : matrix_location_(-1) {
+}
 
 void VertexShaderPosTex::Init(GLES2Interface* context,
                               unsigned program,
@@ -172,28 +173,31 @@
 }
 
 std::string VertexShaderPosTex::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute vec4 a_position;
-    attribute TexCoordPrecision vec2 a_texCoord;
-    uniform mat4 matrix;
-    varying TexCoordPrecision vec2 v_texCoord;
-    void main() {
-      gl_Position = matrix * a_position;
-      v_texCoord = a_texCoord;
-    }
+      // clang-format on
+      attribute vec4 a_position;
+      attribute TexCoordPrecision vec2 a_texCoord;
+      uniform mat4 matrix;
+      varying TexCoordPrecision vec2 v_texCoord;
+      void main() {
+        gl_Position = matrix * a_position;
+        v_texCoord = a_texCoord;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderPosTexYUVStretchOffset::VertexShaderPosTexYUVStretchOffset()
-    : matrix_location_(-1), tex_scale_location_(-1), tex_offset_location_(-1) {}
+    : matrix_location_(-1), tex_scale_location_(-1), tex_offset_location_(-1) {
+}
 
 void VertexShaderPosTexYUVStretchOffset::Init(GLES2Interface* context,
                                               unsigned program,
                                               int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "texScale",
-    "texOffset",
+      "matrix", "texScale", "texOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -209,23 +213,27 @@
 }
 
 std::string VertexShaderPosTexYUVStretchOffset::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    precision mediump float;
-    attribute vec4 a_position;
-    attribute TexCoordPrecision vec2 a_texCoord;
-    uniform mat4 matrix;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform TexCoordPrecision vec2 texScale;
-    uniform TexCoordPrecision vec2 texOffset;
-    void main() {
+      // clang-format on
+      precision mediump float;
+      attribute vec4 a_position;
+      attribute TexCoordPrecision vec2 a_texCoord;
+      uniform mat4 matrix;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform TexCoordPrecision vec2 texScale;
+      uniform TexCoordPrecision vec2 texOffset;
+      void main() {
         gl_Position = matrix * a_position;
         v_texCoord = a_texCoord * texScale + texOffset;
-    }
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
-VertexShaderPos::VertexShaderPos()
-    : matrix_location_(-1) {}
+VertexShaderPos::VertexShaderPos() : matrix_location_(-1) {
+}
 
 void VertexShaderPos::Init(GLES2Interface* context,
                            unsigned program,
@@ -245,27 +253,28 @@
 }
 
 std::string VertexShaderPos::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute vec4 a_position;
-    uniform mat4 matrix;
-    void main() {
-        gl_Position = matrix * a_position;
-    }
+      // clang-format on
+      attribute vec4 a_position;
+      uniform mat4 matrix;
+      void main() { gl_Position = matrix * a_position; }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderPosTexTransform::VertexShaderPosTexTransform()
     : matrix_location_(-1),
       tex_transform_location_(-1),
-      vertex_opacity_location_(-1) {}
+      vertex_opacity_location_(-1) {
+}
 
 void VertexShaderPosTexTransform::Init(GLES2Interface* context,
                                        unsigned program,
                                        int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "texTransform",
-    "opacity",
+      "matrix", "texTransform", "opacity",
   };
   int locations[arraysize(uniforms)];
 
@@ -281,46 +290,53 @@
 }
 
 std::string VertexShaderPosTexTransform::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute vec4 a_position;
-    attribute TexCoordPrecision vec2 a_texCoord;
-    attribute float a_index;
-    uniform mat4 matrix[8];
-    uniform TexCoordPrecision vec4 texTransform[8];
-    uniform float opacity[32];
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying float v_alpha;
-    void main() {
-      int quad_index = int(a_index * 0.25);  // NOLINT
-      gl_Position = matrix[quad_index] * a_position;
-      TexCoordPrecision vec4 texTrans = texTransform[quad_index];
-      v_texCoord = a_texCoord * texTrans.zw + texTrans.xy;
-      v_alpha = opacity[int(a_index)]; // NOLINT
-    }
+      // clang-format on
+      attribute vec4 a_position;
+      attribute TexCoordPrecision vec2 a_texCoord;
+      attribute float a_index;
+      uniform mat4 matrix[8];
+      uniform TexCoordPrecision vec4 texTransform[8];
+      uniform float opacity[32];
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying float v_alpha;
+      void main() {
+        int quad_index = int(a_index * 0.25);  // NOLINT
+        gl_Position = matrix[quad_index] * a_position;
+        TexCoordPrecision vec4 texTrans = texTransform[quad_index];
+        v_texCoord = a_texCoord * texTrans.zw + texTrans.xy;
+        v_alpha = opacity[int(a_index)];  // NOLINT
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string VertexShaderPosTexIdentity::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute vec4 a_position;
-    varying TexCoordPrecision vec2 v_texCoord;
-    void main() {
-      gl_Position = a_position;
-      v_texCoord = (a_position.xy + vec2(1.0)) * 0.5;
-    }
+      // clang-format on
+      attribute vec4 a_position;
+      varying TexCoordPrecision vec2 v_texCoord;
+      void main() {
+        gl_Position = a_position;
+        v_texCoord = (a_position.xy + vec2(1.0)) * 0.5;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderQuad::VertexShaderQuad()
-    : matrix_location_(-1),
-      quad_location_(-1) {}
+    : matrix_location_(-1), quad_location_(-1) {
+}
 
 void VertexShaderQuad::Init(GLES2Interface* context,
                             unsigned program,
                             int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "quad",
+      "matrix", "quad",
   };
   int locations[arraysize(uniforms)];
 
@@ -336,33 +352,41 @@
 
 std::string VertexShaderQuad::GetShaderString() const {
 #if defined(OS_ANDROID)
-// TODO(epenner): Find the cause of this 'quad' uniform
-// being missing if we don't add dummy variables.
-// http://crbug.com/240602
+  // TODO(epenner): Find the cause of this 'quad' uniform
+  // being missing if we don't add dummy variables.
+  // http://crbug.com/240602
+  // clang-format off
   return VERTEX_SHADER(
-    attribute TexCoordPrecision vec4 a_position;
-    attribute float a_index;
-    uniform mat4 matrix;
-    uniform TexCoordPrecision vec2 quad[4];
-    uniform TexCoordPrecision vec2 dummy_uniform;
-    varying TexCoordPrecision vec2 dummy_varying;
-    void main() {
-      vec2 pos = quad[int(a_index)];  // NOLINT
-      gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
-      dummy_varying = dummy_uniform;
-    }
+      // clang-format on
+      attribute TexCoordPrecision vec4 a_position;
+      attribute float a_index;
+      uniform mat4 matrix;
+      uniform TexCoordPrecision vec2 quad[4];
+      uniform TexCoordPrecision vec2 dummy_uniform;
+      varying TexCoordPrecision vec2 dummy_varying;
+      void main() {
+        vec2 pos = quad[int(a_index)];  // NOLINT
+        gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
+        dummy_varying = dummy_uniform;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+// clang-format on
 #else
+  // clang-format off
   return VERTEX_SHADER(
-    attribute TexCoordPrecision vec4 a_position;
-    attribute float a_index;
-    uniform mat4 matrix;
-    uniform TexCoordPrecision vec2 quad[4];
-    void main() {
-      vec2 pos = quad[int(a_index)];  // NOLINT
-      gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
-    }
+      // clang-format on
+      attribute TexCoordPrecision vec4 a_position;
+      attribute float a_index;
+      uniform mat4 matrix;
+      uniform TexCoordPrecision vec2 quad[4];
+      void main() {
+        vec2 pos = quad[int(a_index)];  // NOLINT
+        gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+// clang-format on
 #endif
 }
 
@@ -370,16 +394,14 @@
     : matrix_location_(-1),
       viewport_location_(-1),
       quad_location_(-1),
-      edge_location_(-1) {}
+      edge_location_(-1) {
+}
 
 void VertexShaderQuadAA::Init(GLES2Interface* context,
-                            unsigned program,
-                            int* base_uniform_index) {
+                              unsigned program,
+                              int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "viewport",
-    "quad",
-    "edge",
+      "matrix", "viewport", "quad", "edge",
   };
   int locations[arraysize(uniforms)];
 
@@ -396,30 +418,36 @@
 }
 
 std::string VertexShaderQuadAA::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute TexCoordPrecision vec4 a_position;
-    attribute float a_index;
-    uniform mat4 matrix;
-    uniform vec4 viewport;
-    uniform TexCoordPrecision vec2 quad[4];
-    uniform TexCoordPrecision vec3 edge[8];
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      attribute TexCoordPrecision vec4 a_position;
+      attribute float a_index;
+      uniform mat4 matrix;
+      uniform vec4 viewport;
+      uniform TexCoordPrecision vec2 quad[4];
+      uniform TexCoordPrecision vec3 edge[8];
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec2 pos = quad[int(a_index)];  // NOLINT
-      gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
-      vec2 ndc_pos = 0.5 * (1.0 + gl_Position.xy / gl_Position.w);
-      vec3 screen_pos = vec3(viewport.xy + viewport.zw * ndc_pos, 1.0);
-      edge_dist[0] = vec4(dot(edge[0], screen_pos),
-                          dot(edge[1], screen_pos),
-                          dot(edge[2], screen_pos),
-                          dot(edge[3], screen_pos)) * gl_Position.w;
-      edge_dist[1] = vec4(dot(edge[4], screen_pos),
-                          dot(edge[5], screen_pos),
-                          dot(edge[6], screen_pos),
-                          dot(edge[7], screen_pos)) * gl_Position.w;
-    }
+      void main() {
+        vec2 pos = quad[int(a_index)];  // NOLINT
+        gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
+        vec2 ndc_pos = 0.5 * (1.0 + gl_Position.xy / gl_Position.w);
+        vec3 screen_pos = vec3(viewport.xy + viewport.zw * ndc_pos, 1.0);
+        edge_dist[0] = vec4(dot(edge[0], screen_pos),
+                            dot(edge[1], screen_pos),
+                            dot(edge[2], screen_pos),
+                            dot(edge[3], screen_pos)) *
+                       gl_Position.w;
+        edge_dist[1] = vec4(dot(edge[4], screen_pos),
+                            dot(edge[5], screen_pos),
+                            dot(edge[6], screen_pos),
+                            dot(edge[7], screen_pos)) *
+                       gl_Position.w;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderQuadTexTransformAA::VertexShaderQuadTexTransformAA()
@@ -427,17 +455,14 @@
       viewport_location_(-1),
       quad_location_(-1),
       edge_location_(-1),
-      tex_transform_location_(-1) {}
+      tex_transform_location_(-1) {
+}
 
 void VertexShaderQuadTexTransformAA::Init(GLES2Interface* context,
-                                        unsigned program,
-                                        int* base_uniform_index) {
+                                          unsigned program,
+                                          int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "viewport",
-    "quad",
-    "edge",
-    "texTrans",
+      "matrix", "viewport", "quad", "edge", "texTrans",
   };
   int locations[arraysize(uniforms)];
 
@@ -455,47 +480,52 @@
 }
 
 std::string VertexShaderQuadTexTransformAA::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute TexCoordPrecision vec4 a_position;
-    attribute float a_index;
-    uniform mat4 matrix;
-    uniform vec4 viewport;
-    uniform TexCoordPrecision vec2 quad[4];
-    uniform TexCoordPrecision vec3 edge[8];
-    uniform TexCoordPrecision vec4 texTrans;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      attribute TexCoordPrecision vec4 a_position;
+      attribute float a_index;
+      uniform mat4 matrix;
+      uniform vec4 viewport;
+      uniform TexCoordPrecision vec2 quad[4];
+      uniform TexCoordPrecision vec3 edge[8];
+      uniform TexCoordPrecision vec4 texTrans;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec2 pos = quad[int(a_index)];  // NOLINT
-      gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
-      vec2 ndc_pos = 0.5 * (1.0 + gl_Position.xy / gl_Position.w);
-      vec3 screen_pos = vec3(viewport.xy + viewport.zw * ndc_pos, 1.0);
-      edge_dist[0] = vec4(dot(edge[0], screen_pos),
-                          dot(edge[1], screen_pos),
-                          dot(edge[2], screen_pos),
-                          dot(edge[3], screen_pos)) * gl_Position.w;
-      edge_dist[1] = vec4(dot(edge[4], screen_pos),
-                          dot(edge[5], screen_pos),
-                          dot(edge[6], screen_pos),
-                          dot(edge[7], screen_pos)) * gl_Position.w;
-      v_texCoord = (pos.xy + vec2(0.5)) * texTrans.zw + texTrans.xy;
-    }
+      void main() {
+        vec2 pos = quad[int(a_index)];  // NOLINT
+        gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
+        vec2 ndc_pos = 0.5 * (1.0 + gl_Position.xy / gl_Position.w);
+        vec3 screen_pos = vec3(viewport.xy + viewport.zw * ndc_pos, 1.0);
+        edge_dist[0] = vec4(dot(edge[0], screen_pos),
+                            dot(edge[1], screen_pos),
+                            dot(edge[2], screen_pos),
+                            dot(edge[3], screen_pos)) *
+                       gl_Position.w;
+        edge_dist[1] = vec4(dot(edge[4], screen_pos),
+                            dot(edge[5], screen_pos),
+                            dot(edge[6], screen_pos),
+                            dot(edge[7], screen_pos)) *
+                       gl_Position.w;
+        v_texCoord = (pos.xy + vec2(0.5)) * texTrans.zw + texTrans.xy;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderTile::VertexShaderTile()
     : matrix_location_(-1),
       quad_location_(-1),
-      vertex_tex_transform_location_(-1) {}
+      vertex_tex_transform_location_(-1) {
+}
 
 void VertexShaderTile::Init(GLES2Interface* context,
                             unsigned program,
                             int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "quad",
-    "vertexTexTransform",
+      "matrix", "quad", "vertexTexTransform",
   };
   int locations[arraysize(uniforms)];
 
@@ -511,19 +541,23 @@
 }
 
 std::string VertexShaderTile::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute TexCoordPrecision vec4 a_position;
-    attribute float a_index;
-    uniform mat4 matrix;
-    uniform TexCoordPrecision vec2 quad[4];
-    uniform TexCoordPrecision vec4 vertexTexTransform;
-    varying TexCoordPrecision vec2 v_texCoord;
-    void main() {
-      vec2 pos = quad[int(a_index)];  // NOLINT
-      gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
-      v_texCoord = pos.xy * vertexTexTransform.zw + vertexTexTransform.xy;
-    }
+      // clang-format on
+      attribute TexCoordPrecision vec4 a_position;
+      attribute float a_index;
+      uniform mat4 matrix;
+      uniform TexCoordPrecision vec2 quad[4];
+      uniform TexCoordPrecision vec4 vertexTexTransform;
+      varying TexCoordPrecision vec2 v_texCoord;
+      void main() {
+        vec2 pos = quad[int(a_index)];  // NOLINT
+        gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
+        v_texCoord = pos.xy * vertexTexTransform.zw + vertexTexTransform.xy;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderTileAA::VertexShaderTileAA()
@@ -531,17 +565,14 @@
       viewport_location_(-1),
       quad_location_(-1),
       edge_location_(-1),
-      vertex_tex_transform_location_(-1) {}
+      vertex_tex_transform_location_(-1) {
+}
 
 void VertexShaderTileAA::Init(GLES2Interface* context,
                               unsigned program,
                               int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "viewport",
-    "quad",
-    "edge",
-    "vertexTexTransform",
+      "matrix", "viewport", "quad", "edge", "vertexTexTransform",
   };
   int locations[arraysize(uniforms)];
 
@@ -559,45 +590,50 @@
 }
 
 std::string VertexShaderTileAA::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute TexCoordPrecision vec4 a_position;
-    attribute float a_index;
-    uniform mat4 matrix;
-    uniform vec4 viewport;
-    uniform TexCoordPrecision vec2 quad[4];
-    uniform TexCoordPrecision vec3 edge[8];
-    uniform TexCoordPrecision vec4 vertexTexTransform;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      attribute TexCoordPrecision vec4 a_position;
+      attribute float a_index;
+      uniform mat4 matrix;
+      uniform vec4 viewport;
+      uniform TexCoordPrecision vec2 quad[4];
+      uniform TexCoordPrecision vec3 edge[8];
+      uniform TexCoordPrecision vec4 vertexTexTransform;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec2 pos = quad[int(a_index)];  // NOLINT
-      gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
-      vec2 ndc_pos = 0.5 * (1.0 + gl_Position.xy / gl_Position.w);
-      vec3 screen_pos = vec3(viewport.xy + viewport.zw * ndc_pos, 1.0);
-      edge_dist[0] = vec4(dot(edge[0], screen_pos),
-                          dot(edge[1], screen_pos),
-                          dot(edge[2], screen_pos),
-                          dot(edge[3], screen_pos)) * gl_Position.w;
-      edge_dist[1] = vec4(dot(edge[4], screen_pos),
-                          dot(edge[5], screen_pos),
-                          dot(edge[6], screen_pos),
-                          dot(edge[7], screen_pos)) * gl_Position.w;
-      v_texCoord = pos.xy * vertexTexTransform.zw + vertexTexTransform.xy;
-    }
+      void main() {
+        vec2 pos = quad[int(a_index)];  // NOLINT
+        gl_Position = matrix * vec4(pos, a_position.z, a_position.w);
+        vec2 ndc_pos = 0.5 * (1.0 + gl_Position.xy / gl_Position.w);
+        vec3 screen_pos = vec3(viewport.xy + viewport.zw * ndc_pos, 1.0);
+        edge_dist[0] = vec4(dot(edge[0], screen_pos),
+                            dot(edge[1], screen_pos),
+                            dot(edge[2], screen_pos),
+                            dot(edge[3], screen_pos)) *
+                       gl_Position.w;
+        edge_dist[1] = vec4(dot(edge[4], screen_pos),
+                            dot(edge[5], screen_pos),
+                            dot(edge[6], screen_pos),
+                            dot(edge[7], screen_pos)) *
+                       gl_Position.w;
+        v_texCoord = pos.xy * vertexTexTransform.zw + vertexTexTransform.xy;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 VertexShaderVideoTransform::VertexShaderVideoTransform()
-    : matrix_location_(-1),
-      tex_matrix_location_(-1) {}
+    : matrix_location_(-1), tex_matrix_location_(-1) {
+}
 
 void VertexShaderVideoTransform::Init(GLES2Interface* context,
                                       unsigned program,
                                       int* base_uniform_index) {
   static const char* uniforms[] = {
-    "matrix",
-    "texMatrix",
+      "matrix", "texMatrix",
   };
   int locations[arraysize(uniforms)];
 
@@ -612,30 +648,33 @@
 }
 
 std::string VertexShaderVideoTransform::GetShaderString() const {
+  // clang-format off
   return VERTEX_SHADER(
-    attribute vec4 a_position;
-    attribute TexCoordPrecision vec2 a_texCoord;
-    uniform mat4 matrix;
-    uniform TexCoordPrecision mat4 texMatrix;
-    varying TexCoordPrecision vec2 v_texCoord;
-    void main() {
+      // clang-format on
+      attribute vec4 a_position;
+      attribute TexCoordPrecision vec2 a_texCoord;
+      uniform mat4 matrix;
+      uniform TexCoordPrecision mat4 texMatrix;
+      varying TexCoordPrecision vec2 v_texCoord;
+      void main() {
         gl_Position = matrix * a_position;
         v_texCoord =
             vec2(texMatrix * vec4(a_texCoord.x, 1.0 - a_texCoord.y, 0.0, 1.0));
-    }
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentTexAlphaBinding::FragmentTexAlphaBinding()
-    : sampler_location_(-1),
-      alpha_location_(-1) {}
+    : sampler_location_(-1), alpha_location_(-1) {
+}
 
 void FragmentTexAlphaBinding::Init(GLES2Interface* context,
                                    unsigned program,
                                    int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "alpha",
+      "s_texture", "alpha",
   };
   int locations[arraysize(uniforms)];
 
@@ -653,16 +692,14 @@
     : sampler_location_(-1),
       alpha_location_(-1),
       color_matrix_location_(-1),
-      color_offset_location_(-1) {}
+      color_offset_location_(-1) {
+}
 
 void FragmentTexColorMatrixAlphaBinding::Init(GLES2Interface* context,
                                               unsigned program,
                                               int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "alpha",
-    "colorMatrix",
-    "colorOffset",
+      "s_texture", "alpha", "colorMatrix", "colorOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -678,14 +715,14 @@
   color_offset_location_ = locations[3];
 }
 
-FragmentTexOpaqueBinding::FragmentTexOpaqueBinding()
-    : sampler_location_(-1) {}
+FragmentTexOpaqueBinding::FragmentTexOpaqueBinding() : sampler_location_(-1) {
+}
 
 void FragmentTexOpaqueBinding::Init(GLES2Interface* context,
                                     unsigned program,
                                     int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
+      "s_texture",
   };
   int locations[arraysize(uniforms)];
 
@@ -699,80 +736,98 @@
 }
 
 std::string FragmentShaderRGBATexAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      gl_FragColor = texColor * alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        gl_FragColor = texColor * alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexColorMatrixAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    uniform mat4 colorMatrix;
-    uniform vec4 colorOffset;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      float nonZeroAlpha = max(texColor.a, 0.00001);
-      texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
-      texColor = colorMatrix * texColor + colorOffset;
-      texColor.rgb *= texColor.a;
-      texColor = clamp(texColor, 0.0, 1.0);
-      gl_FragColor = texColor * alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      uniform mat4 colorMatrix;
+      uniform vec4 colorOffset;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        float nonZeroAlpha = max(texColor.a, 0.00001);
+        texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
+        texColor = colorMatrix * texColor + colorOffset;
+        texColor.rgb *= texColor.a;
+        texColor = clamp(texColor, 0.0, 1.0);
+        gl_FragColor = texColor * alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexVaryingAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying float v_alpha;
-    uniform SamplerType s_texture;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      gl_FragColor = texColor * v_alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying float v_alpha;
+      uniform SamplerType s_texture;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        gl_FragColor = texColor * v_alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexPremultiplyAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying float v_alpha;
-    uniform SamplerType s_texture;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      texColor.rgb *= texColor.a;
-      gl_FragColor = texColor * v_alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying float v_alpha;
+      uniform SamplerType s_texture;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        texColor.rgb *= texColor.a;
+        gl_FragColor = texColor * v_alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentTexBackgroundBinding::FragmentTexBackgroundBinding()
-    : background_color_location_(-1),
-      sampler_location_(-1) {
+    : background_color_location_(-1), sampler_location_(-1) {
 }
 
 void FragmentTexBackgroundBinding::Init(GLES2Interface* context,
                                         unsigned program,
                                         int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "background_color",
+      "s_texture", "background_color",
   };
   int locations[arraysize(uniforms)];
 
@@ -791,101 +846,127 @@
 }
 
 std::string FragmentShaderTexBackgroundVaryingAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying float v_alpha;
-    uniform vec4 background_color;
-    uniform SamplerType s_texture;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      texColor += background_color * (1.0 - texColor.a);
-      gl_FragColor = texColor * v_alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying float v_alpha;
+      uniform vec4 background_color;
+      uniform SamplerType s_texture;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        texColor += background_color * (1.0 - texColor.a);
+        gl_FragColor = texColor * v_alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderTexBackgroundPremultiplyAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying float v_alpha;
-    uniform vec4 background_color;
-    uniform SamplerType s_texture;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      texColor.rgb *= texColor.a;
-      texColor += background_color * (1.0 - texColor.a);
-      gl_FragColor = texColor * v_alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying float v_alpha;
+      uniform vec4 background_color;
+      uniform SamplerType s_texture;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        texColor.rgb *= texColor.a;
+        texColor += background_color * (1.0 - texColor.a);
+        gl_FragColor = texColor * v_alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexOpaque::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      gl_FragColor = vec4(texColor.rgb, 1.0);
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        gl_FragColor = vec4(texColor.rgb, 1.0);
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
-std::string FragmentShaderRGBATex::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+std::string FragmentShaderRGBATex::GetShaderString(TexCoordPrecision precision,
+                                                   SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    void main() {
-      gl_FragColor = TextureLookup(s_texture, v_texCoord);
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      void main() { gl_FragColor = TextureLookup(s_texture, v_texCoord); }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexSwizzleAlpha::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    void main() {
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      void main() {
         vec4 texColor = TextureLookup(s_texture, v_texCoord);
         gl_FragColor =
             vec4(texColor.z, texColor.y, texColor.x, texColor.w) * alpha;
-    }
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexSwizzleOpaque::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, 1.0);
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, 1.0);
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderRGBATexAlphaAA::FragmentShaderRGBATexAlphaAA()
-    : sampler_location_(-1),
-      alpha_location_(-1) {}
+    : sampler_location_(-1), alpha_location_(-1) {
+}
 
 void FragmentShaderRGBATexAlphaAA::Init(GLES2Interface* context,
                                         unsigned program,
                                         int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "alpha",
+      "s_texture", "alpha",
   };
   int locations[arraysize(uniforms)];
 
@@ -900,36 +981,40 @@
 }
 
 std::string FragmentShaderRGBATexAlphaAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = texColor * alpha * aa;
-    }
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor = texColor * alpha * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentTexClampAlphaAABinding::FragmentTexClampAlphaAABinding()
     : sampler_location_(-1),
       alpha_location_(-1),
-      fragment_tex_transform_location_(-1) {}
+      fragment_tex_transform_location_(-1) {
+}
 
 void FragmentTexClampAlphaAABinding::Init(GLES2Interface* context,
                                           unsigned program,
                                           int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "alpha",
-    "fragmentTexTransform",
+      "s_texture", "alpha", "fragmentTexTransform",
   };
   int locations[arraysize(uniforms)];
 
@@ -945,67 +1030,74 @@
 }
 
 std::string FragmentShaderRGBATexClampAlphaAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    uniform TexCoordPrecision vec4 fragmentTexTransform;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      uniform TexCoordPrecision vec4 fragmentTexTransform;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      TexCoordPrecision vec2 texCoord =
-          clamp(v_texCoord, 0.0, 1.0) * fragmentTexTransform.zw +
-          fragmentTexTransform.xy;
-      vec4 texColor = TextureLookup(s_texture, texCoord);
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = texColor * alpha * aa;
-    }
+      void main() {
+        TexCoordPrecision vec2 texCoord =
+            clamp(v_texCoord, 0.0, 1.0) * fragmentTexTransform.zw +
+            fragmentTexTransform.xy;
+        vec4 texColor = TextureLookup(s_texture, texCoord);
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor = texColor * alpha * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 std::string FragmentShaderRGBATexClampSwizzleAlphaAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    uniform TexCoordPrecision vec4 fragmentTexTransform;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      uniform TexCoordPrecision vec4 fragmentTexTransform;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      TexCoordPrecision vec2 texCoord =
-          clamp(v_texCoord, 0.0, 1.0) * fragmentTexTransform.zw +
-          fragmentTexTransform.xy;
-      vec4 texColor = TextureLookup(s_texture, texCoord);
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, texColor.w) *
-          alpha * aa;
-    }
+      void main() {
+        TexCoordPrecision vec2 texCoord =
+            clamp(v_texCoord, 0.0, 1.0) * fragmentTexTransform.zw +
+            fragmentTexTransform.xy;
+        vec4 texColor = TextureLookup(s_texture, texCoord);
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor =
+            vec4(texColor.z, texColor.y, texColor.x, texColor.w) * alpha * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderRGBATexAlphaMask::FragmentShaderRGBATexAlphaMask()
     : sampler_location_(-1),
       mask_sampler_location_(-1),
       alpha_location_(-1),
-      mask_tex_coord_scale_location_(-1) {}
+      mask_tex_coord_scale_location_(-1) {
+}
 
 void FragmentShaderRGBATexAlphaMask::Init(GLES2Interface* context,
                                           unsigned program,
                                           int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "s_mask",
-    "alpha",
-    "maskTexCoordScale",
-    "maskTexCoordOffset",
+      "s_texture", "s_mask", "alpha", "maskTexCoordScale", "maskTexCoordOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -1023,24 +1115,29 @@
 }
 
 std::string FragmentShaderRGBATexAlphaMask::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    uniform SamplerType s_mask;
-    uniform TexCoordPrecision vec2 maskTexCoordScale;
-    uniform TexCoordPrecision vec2 maskTexCoordOffset;
-    uniform float alpha;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      TexCoordPrecision vec2 maskTexCoord =
-          vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
-               maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
-      vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
-      gl_FragColor = texColor * alpha * maskColor.w;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      uniform SamplerType s_mask;
+      uniform TexCoordPrecision vec2 maskTexCoordScale;
+      uniform TexCoordPrecision vec2 maskTexCoordOffset;
+      uniform float alpha;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        TexCoordPrecision vec2 maskTexCoord =
+            vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
+                 maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
+        vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
+        gl_FragColor = texColor * alpha * maskColor.w;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderRGBATexAlphaMaskAA::FragmentShaderRGBATexAlphaMaskAA()
@@ -1048,17 +1145,14 @@
       mask_sampler_location_(-1),
       alpha_location_(-1),
       mask_tex_coord_scale_location_(-1),
-      mask_tex_coord_offset_location_(-1) {}
+      mask_tex_coord_offset_location_(-1) {
+}
 
 void FragmentShaderRGBATexAlphaMaskAA::Init(GLES2Interface* context,
                                             unsigned program,
                                             int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "s_mask",
-    "alpha",
-    "maskTexCoordScale",
-    "maskTexCoordOffset",
+      "s_texture", "s_mask", "alpha", "maskTexCoordScale", "maskTexCoordOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -1076,52 +1170,58 @@
 }
 
 std::string FragmentShaderRGBATexAlphaMaskAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform SamplerType s_texture;
-    uniform SamplerType s_mask;
-    uniform TexCoordPrecision vec2 maskTexCoordScale;
-    uniform TexCoordPrecision vec2 maskTexCoordOffset;
-    uniform float alpha;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform SamplerType s_texture;
+      uniform SamplerType s_mask;
+      uniform TexCoordPrecision vec2 maskTexCoordScale;
+      uniform TexCoordPrecision vec2 maskTexCoordOffset;
+      uniform float alpha;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      TexCoordPrecision vec2 maskTexCoord =
-          vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
-               maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
-      vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = texColor * alpha * maskColor.w * aa;
-    }
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        TexCoordPrecision vec2 maskTexCoord =
+            vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
+                 maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
+        vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor = texColor * alpha * maskColor.w * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderRGBATexAlphaMaskColorMatrixAA::
     FragmentShaderRGBATexAlphaMaskColorMatrixAA()
-        : sampler_location_(-1),
-          mask_sampler_location_(-1),
-          alpha_location_(-1),
-          mask_tex_coord_scale_location_(-1),
-          color_matrix_location_(-1),
-          color_offset_location_(-1) {}
+    : sampler_location_(-1),
+      mask_sampler_location_(-1),
+      alpha_location_(-1),
+      mask_tex_coord_scale_location_(-1),
+      color_matrix_location_(-1),
+      color_offset_location_(-1) {
+}
 
 void FragmentShaderRGBATexAlphaMaskColorMatrixAA::Init(
     GLES2Interface* context,
     unsigned program,
     int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "s_mask",
-    "alpha",
-    "maskTexCoordScale",
-    "maskTexCoordOffset",
-    "colorMatrix",
-    "colorOffset",
+      "s_texture",
+      "s_mask",
+      "alpha",
+      "maskTexCoordScale",
+      "maskTexCoordOffset",
+      "colorMatrix",
+      "colorOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -1141,54 +1241,56 @@
 }
 
 std::string FragmentShaderRGBATexAlphaMaskColorMatrixAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform SamplerType s_texture;
-    uniform SamplerType s_mask;
-    uniform vec2 maskTexCoordScale;
-    uniform vec2 maskTexCoordOffset;
-    uniform mat4 colorMatrix;
-    uniform vec4 colorOffset;
-    uniform float alpha;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform SamplerType s_texture;
+      uniform SamplerType s_mask;
+      uniform vec2 maskTexCoordScale;
+      uniform vec2 maskTexCoordOffset;
+      uniform mat4 colorMatrix;
+      uniform vec4 colorOffset;
+      uniform float alpha;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      float nonZeroAlpha = max(texColor.a, 0.00001);
-      texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
-      texColor = colorMatrix * texColor + colorOffset;
-      texColor.rgb *= texColor.a;
-      texColor = clamp(texColor, 0.0, 1.0);
-      TexCoordPrecision vec2 maskTexCoord =
-          vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
-               maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
-      vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = texColor * alpha * maskColor.w * aa;
-    }
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        float nonZeroAlpha = max(texColor.a, 0.00001);
+        texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
+        texColor = colorMatrix * texColor + colorOffset;
+        texColor.rgb *= texColor.a;
+        texColor = clamp(texColor, 0.0, 1.0);
+        TexCoordPrecision vec2 maskTexCoord =
+            vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
+                 maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
+        vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor = texColor * alpha * maskColor.w * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderRGBATexAlphaColorMatrixAA::
     FragmentShaderRGBATexAlphaColorMatrixAA()
-        : sampler_location_(-1),
-          alpha_location_(-1),
-          color_matrix_location_(-1),
-          color_offset_location_(-1) {}
+    : sampler_location_(-1),
+      alpha_location_(-1),
+      color_matrix_location_(-1),
+      color_offset_location_(-1) {
+}
 
-void FragmentShaderRGBATexAlphaColorMatrixAA::Init(
-      GLES2Interface* context,
-      unsigned program,
-      int* base_uniform_index) {
+void FragmentShaderRGBATexAlphaColorMatrixAA::Init(GLES2Interface* context,
+                                                   unsigned program,
+                                                   int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "alpha",
-    "colorMatrix",
-    "colorOffset",
+      "s_texture", "alpha", "colorMatrix", "colorOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -1205,50 +1307,55 @@
 }
 
 std::string FragmentShaderRGBATexAlphaColorMatrixAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform SamplerType s_texture;
-    uniform float alpha;
-    uniform mat4 colorMatrix;
-    uniform vec4 colorOffset;
-    varying TexCoordPrecision vec2 v_texCoord;
-    varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform SamplerType s_texture;
+      uniform float alpha;
+      uniform mat4 colorMatrix;
+      uniform vec4 colorOffset;
+      varying TexCoordPrecision vec2 v_texCoord;
+      varying TexCoordPrecision vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      float nonZeroAlpha = max(texColor.a, 0.00001);
-      texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
-      texColor = colorMatrix * texColor + colorOffset;
-      texColor.rgb *= texColor.a;
-      texColor = clamp(texColor, 0.0, 1.0);
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = texColor * alpha * aa;
-    }
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        float nonZeroAlpha = max(texColor.a, 0.00001);
+        texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
+        texColor = colorMatrix * texColor + colorOffset;
+        texColor.rgb *= texColor.a;
+        texColor = clamp(texColor, 0.0, 1.0);
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor = texColor * alpha * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderRGBATexAlphaMaskColorMatrix::
     FragmentShaderRGBATexAlphaMaskColorMatrix()
-        : sampler_location_(-1),
-          mask_sampler_location_(-1),
-          alpha_location_(-1),
-          mask_tex_coord_scale_location_(-1) {}
+    : sampler_location_(-1),
+      mask_sampler_location_(-1),
+      alpha_location_(-1),
+      mask_tex_coord_scale_location_(-1) {
+}
 
-void FragmentShaderRGBATexAlphaMaskColorMatrix::Init(
-    GLES2Interface* context,
-    unsigned program,
-    int* base_uniform_index) {
+void FragmentShaderRGBATexAlphaMaskColorMatrix::Init(GLES2Interface* context,
+                                                     unsigned program,
+                                                     int* base_uniform_index) {
   static const char* uniforms[] = {
-    "s_texture",
-    "s_mask",
-    "alpha",
-    "maskTexCoordScale",
-    "maskTexCoordOffset",
-    "colorMatrix",
-    "colorOffset",
+      "s_texture",
+      "s_mask",
+      "alpha",
+      "maskTexCoordScale",
+      "maskTexCoordOffset",
+      "colorMatrix",
+      "colorOffset",
   };
   int locations[arraysize(uniforms)];
 
@@ -1268,31 +1375,36 @@
 }
 
 std::string FragmentShaderRGBATexAlphaMaskColorMatrix::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType s_texture;
-    uniform SamplerType s_mask;
-    uniform vec2 maskTexCoordScale;
-    uniform vec2 maskTexCoordOffset;
-    uniform mat4 colorMatrix;
-    uniform vec4 colorOffset;
-    uniform float alpha;
-    void main() {
-      vec4 texColor = TextureLookup(s_texture, v_texCoord);
-      float nonZeroAlpha = max(texColor.a, 0.00001);
-      texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
-      texColor = colorMatrix * texColor + colorOffset;
-      texColor.rgb *= texColor.a;
-      texColor = clamp(texColor, 0.0, 1.0);
-      TexCoordPrecision vec2 maskTexCoord =
-          vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
-               maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
-      vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
-      gl_FragColor = texColor * alpha * maskColor.w;
-    }
+      // clang-format on
+      precision mediump float;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType s_texture;
+      uniform SamplerType s_mask;
+      uniform vec2 maskTexCoordScale;
+      uniform vec2 maskTexCoordOffset;
+      uniform mat4 colorMatrix;
+      uniform vec4 colorOffset;
+      uniform float alpha;
+      void main() {
+        vec4 texColor = TextureLookup(s_texture, v_texCoord);
+        float nonZeroAlpha = max(texColor.a, 0.00001);
+        texColor = vec4(texColor.rgb / nonZeroAlpha, nonZeroAlpha);
+        texColor = colorMatrix * texColor + colorOffset;
+        texColor.rgb *= texColor.a;
+        texColor = clamp(texColor, 0.0, 1.0);
+        TexCoordPrecision vec2 maskTexCoord =
+            vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x,
+                 maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y);
+        vec4 maskColor = TextureLookup(s_mask, maskTexCoord);
+        gl_FragColor = texColor * alpha * maskColor.w;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderYUVVideo::FragmentShaderYUVVideo()
@@ -1301,18 +1413,14 @@
       v_texture_location_(-1),
       alpha_location_(-1),
       yuv_matrix_location_(-1),
-      yuv_adj_location_(-1) {}
+      yuv_adj_location_(-1) {
+}
 
 void FragmentShaderYUVVideo::Init(GLES2Interface* context,
                                   unsigned program,
                                   int* base_uniform_index) {
   static const char* uniforms[] = {
-    "y_texture",
-    "u_texture",
-    "v_texture",
-    "alpha",
-    "yuv_matrix",
-    "yuv_adj",
+      "y_texture", "u_texture", "v_texture", "alpha", "yuv_matrix", "yuv_adj",
   };
   int locations[arraysize(uniforms)];
 
@@ -1330,27 +1438,31 @@
   yuv_adj_location_ = locations[5];
 }
 
-std::string FragmentShaderYUVVideo::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+std::string FragmentShaderYUVVideo::GetShaderString(TexCoordPrecision precision,
+                                                    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    precision mediump int;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType y_texture;
-    uniform SamplerType u_texture;
-    uniform SamplerType v_texture;
-    uniform float alpha;
-    uniform vec3 yuv_adj;
-    uniform mat3 yuv_matrix;
-    void main() {
-      float y_raw = TextureLookup(y_texture, v_texCoord).x;
-      float u_unsigned = TextureLookup(u_texture, v_texCoord).x;
-      float v_unsigned = TextureLookup(v_texture, v_texCoord).x;
-      vec3 yuv = vec3(y_raw, u_unsigned, v_unsigned) + yuv_adj;
-      vec3 rgb = yuv_matrix * yuv;
-      gl_FragColor = vec4(rgb, 1.0) * alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      precision mediump int;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType y_texture;
+      uniform SamplerType u_texture;
+      uniform SamplerType v_texture;
+      uniform float alpha;
+      uniform vec3 yuv_adj;
+      uniform mat3 yuv_matrix;
+      void main() {
+        float y_raw = TextureLookup(y_texture, v_texCoord).x;
+        float u_unsigned = TextureLookup(u_texture, v_texCoord).x;
+        float v_unsigned = TextureLookup(v_texture, v_texCoord).x;
+        vec3 yuv = vec3(y_raw, u_unsigned, v_unsigned) + yuv_adj;
+        vec3 rgb = yuv_matrix * yuv;
+        gl_FragColor = vec4(rgb, 1.0) * alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderYUVAVideo::FragmentShaderYUVAVideo()
@@ -1393,38 +1505,43 @@
 }
 
 std::string FragmentShaderYUVAVideo::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    precision mediump int;
-    varying TexCoordPrecision vec2 v_texCoord;
-    uniform SamplerType y_texture;
-    uniform SamplerType u_texture;
-    uniform SamplerType v_texture;
-    uniform SamplerType a_texture;
-    uniform float alpha;
-    uniform vec3 yuv_adj;
-    uniform mat3 yuv_matrix;
-    void main() {
-      float y_raw = TextureLookup(y_texture, v_texCoord).x;
-      float u_unsigned = TextureLookup(u_texture, v_texCoord).x;
-      float v_unsigned = TextureLookup(v_texture, v_texCoord).x;
-      float a_raw = TextureLookup(a_texture, v_texCoord).x;
-      vec3 yuv = vec3(y_raw, u_unsigned, v_unsigned) + yuv_adj;
-      vec3 rgb = yuv_matrix * yuv;
-      gl_FragColor = vec4(rgb, 1.0) * (alpha * a_raw);
-    }
+      // clang-format on
+      precision mediump float;
+      precision mediump int;
+      varying TexCoordPrecision vec2 v_texCoord;
+      uniform SamplerType y_texture;
+      uniform SamplerType u_texture;
+      uniform SamplerType v_texture;
+      uniform SamplerType a_texture;
+      uniform float alpha;
+      uniform vec3 yuv_adj;
+      uniform mat3 yuv_matrix;
+      void main() {
+        float y_raw = TextureLookup(y_texture, v_texCoord).x;
+        float u_unsigned = TextureLookup(u_texture, v_texCoord).x;
+        float v_unsigned = TextureLookup(v_texture, v_texCoord).x;
+        float a_raw = TextureLookup(a_texture, v_texCoord).x;
+        vec3 yuv = vec3(y_raw, u_unsigned, v_unsigned) + yuv_adj;
+        vec3 rgb = yuv_matrix * yuv;
+        gl_FragColor = vec4(rgb, 1.0) * (alpha * a_raw);
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
-FragmentShaderColor::FragmentShaderColor()
-    : color_location_(-1) {}
+FragmentShaderColor::FragmentShaderColor() : color_location_(-1) {
+}
 
 void FragmentShaderColor::Init(GLES2Interface* context,
                                unsigned program,
                                int* base_uniform_index) {
   static const char* uniforms[] = {
-    "color",
+      "color",
   };
   int locations[arraysize(uniforms)];
 
@@ -1437,25 +1554,27 @@
   color_location_ = locations[0];
 }
 
-std::string FragmentShaderColor::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+std::string FragmentShaderColor::GetShaderString(TexCoordPrecision precision,
+                                                 SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform vec4 color;
-    void main() {
-      gl_FragColor = color;
-    }
+      // clang-format on
+      precision mediump float;
+      uniform vec4 color;
+      void main() { gl_FragColor = color; }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
-FragmentShaderColorAA::FragmentShaderColorAA()
-    : color_location_(-1) {}
+FragmentShaderColorAA::FragmentShaderColorAA() : color_location_(-1) {
+}
 
 void FragmentShaderColorAA::Init(GLES2Interface* context,
                                  unsigned program,
                                  int* base_uniform_index) {
   static const char* uniforms[] = {
-    "color",
+      "color",
   };
   int locations[arraysize(uniforms)];
 
@@ -1468,35 +1587,37 @@
   color_location_ = locations[0];
 }
 
-std::string FragmentShaderColorAA::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+std::string FragmentShaderColorAA::GetShaderString(TexCoordPrecision precision,
+                                                   SamplerType sampler) const {
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    uniform vec4 color;
-    varying vec4 edge_dist[2];  // 8 edge distances.
+      // clang-format on
+      precision mediump float;
+      uniform vec4 color;
+      varying vec4 edge_dist[2];  // 8 edge distances.
 
-    void main() {
-      vec4 d4 = min(edge_dist[0], edge_dist[1]);
-      vec2 d2 = min(d4.xz, d4.yw);
-      float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
-      gl_FragColor = color * aa;
-    }
+      void main() {
+        vec4 d4 = min(edge_dist[0], edge_dist[1]);
+        vec2 d2 = min(d4.xz, d4.yw);
+        float aa = clamp(gl_FragCoord.w * min(d2.x, d2.y), 0.0, 1.0);
+        gl_FragColor = color * aa;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 FragmentShaderCheckerboard::FragmentShaderCheckerboard()
     : alpha_location_(-1),
       tex_transform_location_(-1),
-      frequency_location_(-1) {}
+      frequency_location_(-1) {
+}
 
 void FragmentShaderCheckerboard::Init(GLES2Interface* context,
                                       unsigned program,
                                       int* base_uniform_index) {
   static const char* uniforms[] = {
-    "alpha",
-    "texTransform",
-    "frequency",
-    "color",
+      "alpha", "texTransform", "frequency", "color",
   };
   int locations[arraysize(uniforms)];
 
@@ -1513,27 +1634,32 @@
 }
 
 std::string FragmentShaderCheckerboard::GetShaderString(
-    TexCoordPrecision precision, SamplerType sampler) const {
+    TexCoordPrecision precision,
+    SamplerType sampler) const {
   // Shader based on Example 13-17 of "OpenGL ES 2.0 Programming Guide"
   // by Munshi, Ginsburg, Shreiner.
+  // clang-format off
   return FRAGMENT_SHADER(
-    precision mediump float;
-    precision mediump int;
-    varying vec2 v_texCoord;
-    uniform float alpha;
-    uniform float frequency;
-    uniform vec4 texTransform;
-    uniform vec4 color;
-    void main() {
-      vec4 color1 = vec4(1.0, 1.0, 1.0, 1.0);
-      vec4 color2 = color;
-      vec2 texCoord =
-          clamp(v_texCoord, 0.0, 1.0) * texTransform.zw + texTransform.xy;
-      vec2 coord = mod(floor(texCoord * frequency * 2.0), 2.0);
-      float picker = abs(coord.x - coord.y);  // NOLINT
-      gl_FragColor = mix(color1, color2, picker) * alpha;
-    }
+      // clang-format on
+      precision mediump float;
+      precision mediump int;
+      varying vec2 v_texCoord;
+      uniform float alpha;
+      uniform float frequency;
+      uniform vec4 texTransform;
+      uniform vec4 color;
+      void main() {
+        vec4 color1 = vec4(1.0, 1.0, 1.0, 1.0);
+        vec4 color2 = color;
+        vec2 texCoord =
+            clamp(v_texCoord, 0.0, 1.0) * texTransform.zw + texTransform.xy;
+        vec2 coord = mod(floor(texCoord * frequency * 2.0), 2.0);
+        float picker = abs(coord.x - coord.y);  // NOLINT
+        gl_FragColor = mix(color1, color2, picker) * alpha;
+      }
+      // clang-format off
   );  // NOLINT(whitespace/parens)
+  // clang-format on
 }
 
 }  // namespace cc
diff --git a/cc/output/software_renderer.cc b/cc/output/software_renderer.cc
index ae58b63..c3cb828 100644
--- a/cc/output/software_renderer.cc
+++ b/cc/output/software_renderer.cc
@@ -518,11 +518,11 @@
 
     const SkBitmap* mask = mask_lock.sk_bitmap();
 
-    SkRect mask_rect = SkRect::MakeXYWH(
-        quad->mask_uv_rect.x() * mask->width(),
-        quad->mask_uv_rect.y() * mask->height(),
-        quad->mask_uv_rect.width() * mask->width(),
-        quad->mask_uv_rect.height() * mask->height());
+    // Scale normalized uv rect into absolute texel coordinates.
+    SkRect mask_rect =
+        gfx::RectFToSkRect(gfx::ScaleRect(quad->MaskUVRect(),
+                                          quad->mask_texture_size.width(),
+                                          quad->mask_texture_size.height()));
 
     SkMatrix mask_mat;
     mask_mat.setRectToRect(mask_rect, dest_rect, SkMatrix::kFill_ScaleToFit);
diff --git a/cc/quads/draw_quad_unittest.cc b/cc/quads/draw_quad_unittest.cc
index e3697ec..308f084 100644
--- a/cc/quads/draw_quad_unittest.cc
+++ b/cc/quads/draw_quad_unittest.cc
@@ -328,7 +328,7 @@
   }                                                        \
   SETUP_AND_COPY_QUAD_ALL(Type, quad_all);
 
-#define CREATE_QUAD_ALL_RP(Type, a, b, c, d, e, f, copy_a)       \
+#define CREATE_QUAD_ALL_RP(Type, a, b, c, d, e, f, g, copy_a)    \
   Type* quad_all = render_pass->CreateAndAppendDrawQuad<Type>(); \
   {                                                              \
     QUAD_DATA quad_all->SetAll(shared_state,                     \
@@ -341,15 +341,17 @@
                                c,                                \
                                d,                                \
                                e,                                \
-                               f);                               \
+                               f,                                \
+                               g);                               \
   }                                                              \
   SETUP_AND_COPY_QUAD_ALL_RP(Type, quad_all, copy_a);
 
-#define CREATE_QUAD_NEW_RP(Type, a, b, c, d, e, f, g, copy_a)                 \
-  Type* quad_new = render_pass->CreateAndAppendDrawQuad<Type>();              \
-  {                                                                           \
-    QUAD_DATA quad_new->SetNew(shared_state, quad_rect, a, b, c, d, e, f, g); \
-  }                                                                           \
+#define CREATE_QUAD_NEW_RP(Type, a, b, c, d, e, f, g, h, copy_a) \
+  Type* quad_new = render_pass->CreateAndAppendDrawQuad<Type>(); \
+  {                                                              \
+    QUAD_DATA quad_new->SetNew(                                  \
+        shared_state, quad_rect, a, b, c, d, e, f, g, h);        \
+  }                                                              \
   SETUP_AND_COPY_QUAD_NEW_RP(Type, quad_new, copy_a);
 
 TEST(DrawQuadTest, CopyCheckerboardDrawQuad) {
@@ -417,7 +419,8 @@
   gfx::Rect visible_rect(40, 50, 30, 20);
   RenderPassId render_pass_id(22, 64);
   ResourceProvider::ResourceId mask_resource_id = 78;
-  gfx::RectF mask_u_v_rect(-45.f, -21.f, 33.f, 19.f);
+  gfx::Vector2dF mask_uv_scale(33.f, 19.f);
+  gfx::Size mask_texture_size(128, 134);
   FilterOperations filters;
   filters.Append(FilterOperation::CreateBlurFilter(1.f));
   gfx::Vector2dF filters_scale;
@@ -432,7 +435,8 @@
                      visible_rect,
                      render_pass_id,
                      mask_resource_id,
-                     mask_u_v_rect,
+                     mask_uv_scale,
+                     mask_texture_size,
                      filters,
                      filters_scale,
                      background_filters,
@@ -441,7 +445,9 @@
   EXPECT_RECT_EQ(visible_rect, copy_quad->visible_rect);
   EXPECT_EQ(copied_render_pass_id, copy_quad->render_pass_id);
   EXPECT_EQ(mask_resource_id, copy_quad->mask_resource_id);
-  EXPECT_EQ(mask_u_v_rect.ToString(), copy_quad->mask_uv_rect.ToString());
+  EXPECT_EQ(mask_uv_scale.ToString(), copy_quad->mask_uv_scale.ToString());
+  EXPECT_EQ(mask_texture_size.ToString(),
+            copy_quad->mask_texture_size.ToString());
   EXPECT_EQ(filters, copy_quad->filters);
   EXPECT_EQ(filters_scale, copy_quad->filters_scale);
   EXPECT_EQ(background_filters, copy_quad->background_filters);
@@ -449,7 +455,8 @@
   CREATE_QUAD_ALL_RP(RenderPassDrawQuad,
                      render_pass_id,
                      mask_resource_id,
-                     mask_u_v_rect,
+                     mask_uv_scale,
+                     mask_texture_size,
                      filters,
                      filters_scale,
                      background_filters,
@@ -457,7 +464,9 @@
   EXPECT_EQ(DrawQuad::RENDER_PASS, copy_quad->material);
   EXPECT_EQ(copied_render_pass_id, copy_quad->render_pass_id);
   EXPECT_EQ(mask_resource_id, copy_quad->mask_resource_id);
-  EXPECT_EQ(mask_u_v_rect.ToString(), copy_quad->mask_uv_rect.ToString());
+  EXPECT_EQ(mask_uv_scale.ToString(), copy_quad->mask_uv_scale.ToString());
+  EXPECT_EQ(mask_texture_size.ToString(),
+            copy_quad->mask_texture_size.ToString());
   EXPECT_EQ(filters, copy_quad->filters);
   EXPECT_EQ(filters_scale, copy_quad->filters_scale);
   EXPECT_EQ(background_filters, copy_quad->background_filters);
@@ -756,7 +765,8 @@
   gfx::Rect visible_rect(40, 50, 30, 20);
   RenderPassId render_pass_id(22, 64);
   ResourceProvider::ResourceId mask_resource_id = 78;
-  gfx::RectF mask_u_v_rect(-45.f, -21.f, 33.f, 19.f);
+  gfx::Vector2dF mask_uv_scale(33.f, 19.f);
+  gfx::Size mask_texture_size(128, 134);
   FilterOperations filters;
   filters.Append(FilterOperation::CreateBlurFilter(1.f));
   gfx::Vector2dF filters_scale(2.f, 3.f);
@@ -771,7 +781,8 @@
                      visible_rect,
                      render_pass_id,
                      mask_resource_id,
-                     mask_u_v_rect,
+                     mask_uv_scale,
+                     mask_texture_size,
                      filters,
                      filters_scale,
                      background_filters,
diff --git a/cc/quads/render_pass_draw_quad.cc b/cc/quads/render_pass_draw_quad.cc
index 005aed5..88f608d 100644
--- a/cc/quads/render_pass_draw_quad.cc
+++ b/cc/quads/render_pass_draw_quad.cc
@@ -25,7 +25,8 @@
                                 const gfx::Rect& visible_rect,
                                 RenderPassId render_pass_id,
                                 ResourceProvider::ResourceId mask_resource_id,
-                                const gfx::RectF& mask_uv_rect,
+                                const gfx::Vector2dF& mask_uv_scale,
+                                const gfx::Size& mask_texture_size,
                                 const FilterOperations& filters,
                                 const gfx::Vector2dF& filters_scale,
                                 const FilterOperations& background_filters) {
@@ -41,7 +42,8 @@
          needs_blending,
          render_pass_id,
          mask_resource_id,
-         mask_uv_rect,
+         mask_uv_scale,
+         mask_texture_size,
          filters,
          filters_scale,
          background_filters);
@@ -54,7 +56,8 @@
                                 bool needs_blending,
                                 RenderPassId render_pass_id,
                                 ResourceProvider::ResourceId mask_resource_id,
-                                const gfx::RectF& mask_uv_rect,
+                                const gfx::Vector2dF& mask_uv_scale,
+                                const gfx::Size& mask_texture_size,
                                 const FilterOperations& filters,
                                 const gfx::Vector2dF& filters_scale,
                                 const FilterOperations& background_filters) {
@@ -65,7 +68,8 @@
                    visible_rect, needs_blending);
   this->render_pass_id = render_pass_id;
   this->mask_resource_id = mask_resource_id;
-  this->mask_uv_rect = mask_uv_rect;
+  this->mask_uv_scale = mask_uv_scale;
+  this->mask_texture_size = mask_texture_size;
   this->filters = filters;
   this->filters_scale = filters_scale;
   this->background_filters = background_filters;
@@ -77,6 +81,14 @@
     mask_resource_id = callback.Run(mask_resource_id);
 }
 
+gfx::RectF RenderPassDrawQuad::MaskUVRect() const {
+  gfx::RectF mask_uv_rect((mask_uv_scale.x() * rect.x()) / rect.width(),
+                          (mask_uv_scale.y() * rect.y()) / rect.height(),
+                          mask_uv_scale.x(),
+                          mask_uv_scale.y());
+  return mask_uv_rect;
+}
+
 const RenderPassDrawQuad* RenderPassDrawQuad::MaterialCast(
     const DrawQuad* quad) {
   DCHECK_EQ(quad->material, DrawQuad::RENDER_PASS);
@@ -87,8 +99,12 @@
   TracedValue::SetIDRef(render_pass_id.AsTracingId(), value, "render_pass_id");
   value->SetInteger("mask_resource_id", mask_resource_id);
 
-  value->BeginArray("mask_uv_rect");
-  MathUtil::AddToTracedValue(mask_uv_rect, value);
+  value->BeginArray("mask_texture_size");
+  MathUtil::AddToTracedValue(mask_texture_size, value);
+  value->EndArray();
+
+  value->BeginArray("mask_uv_scale");
+  MathUtil::AddToTracedValue(mask_uv_scale, value);
   value->EndArray();
 
   value->BeginDictionary("filters");
diff --git a/cc/quads/render_pass_draw_quad.h b/cc/quads/render_pass_draw_quad.h
index 587c7ec..25417f6 100644
--- a/cc/quads/render_pass_draw_quad.h
+++ b/cc/quads/render_pass_draw_quad.h
@@ -25,7 +25,8 @@
               const gfx::Rect& visible_rect,
               RenderPassId render_pass_id,
               ResourceProvider::ResourceId mask_resource_id,
-              const gfx::RectF& mask_uv_rect,
+              const gfx::Vector2dF& mask_uv_scale,
+              const gfx::Size& mask_texture_size,
               const FilterOperations& filters,
               const gfx::Vector2dF& filters_scale,
               const FilterOperations& background_filters);
@@ -37,14 +38,16 @@
               bool needs_blending,
               RenderPassId render_pass_id,
               ResourceProvider::ResourceId mask_resource_id,
-              const gfx::RectF& mask_uv_rect,
+              const gfx::Vector2dF& mask_uv_scale,
+              const gfx::Size& mask_texture_size,
               const FilterOperations& filters,
               const gfx::Vector2dF& filters_scale,
               const FilterOperations& background_filters);
 
   RenderPassId render_pass_id;
   ResourceProvider::ResourceId mask_resource_id;
-  gfx::RectF mask_uv_rect;
+  gfx::Vector2dF mask_uv_scale;
+  gfx::Size mask_texture_size;
 
   // Post-processing filters, applied to the pixels in the render pass' texture.
   FilterOperations filters;
@@ -59,6 +62,9 @@
   // background of the render pass, from behind it.
   FilterOperations background_filters;
 
+  // Helper function to generate the normalized uv rect.
+  gfx::RectF MaskUVRect() const;
+
   virtual void IterateResources(const ResourceIteratorCallback& callback)
       override;
 
diff --git a/cc/quads/render_pass_unittest.cc b/cc/quads/render_pass_unittest.cc
index 81a3d31..4c3753f 100644
--- a/cc/quads/render_pass_unittest.cc
+++ b/cc/quads/render_pass_unittest.cc
@@ -219,10 +219,11 @@
                     contrib_output_rect,
                     contrib_output_rect,
                     contrib_id,
-                    0,      // mask_resource_id
-                    gfx::RectF(),  // mask_uv_rect
+                    0,
+                    gfx::Vector2dF(),
+                    gfx::Size(),
                     FilterOperations(),
-                    gfx::Vector2dF(),  // filters_scale
+                    gfx::Vector2dF(),
                     FilterOperations());
 
   pass_list.push_back(pass.Pass());
diff --git a/cc/quads/yuv_video_draw_quad.h b/cc/quads/yuv_video_draw_quad.h
index 1460458..e0fc758 100644
--- a/cc/quads/yuv_video_draw_quad.h
+++ b/cc/quads/yuv_video_draw_quad.h
@@ -8,6 +8,7 @@
 #include "base/basictypes.h"
 #include "base/memory/scoped_ptr.h"
 #include "cc/base/cc_export.h"
+#include "cc/layers/video_layer_impl.h"
 #include "cc/quads/draw_quad.h"
 
 namespace cc {
diff --git a/cc/resources/picture_layer_tiling.h b/cc/resources/picture_layer_tiling.h
index 3b60edd..a12b1d2 100644
--- a/cc/resources/picture_layer_tiling.h
+++ b/cc/resources/picture_layer_tiling.h
@@ -182,8 +182,8 @@
       UpdateTileAndTwinPriority(it->second.get());
   }
 
-  std::vector<scoped_refptr<Tile> > AllRefTilesForTesting() const {
-    std::vector<scoped_refptr<Tile> > all_tiles;
+  std::vector<scoped_refptr<Tile>> AllRefTilesForTesting() const {
+    std::vector<scoped_refptr<Tile>> all_tiles;
     for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it)
       all_tiles.push_back(it->second);
     return all_tiles;
@@ -296,7 +296,7 @@
   friend class TilingEvictionTileIterator;
 
   typedef std::pair<int, int> TileMapKey;
-  typedef base::hash_map<TileMapKey, scoped_refptr<Tile> > TileMap;
+  typedef base::hash_map<TileMapKey, scoped_refptr<Tile>> TileMap;
 
   PictureLayerTiling(float contents_scale,
                      const gfx::Size& layer_bounds,
diff --git a/cc/resources/picture_layer_tiling_perftest.cc b/cc/resources/picture_layer_tiling_perftest.cc
index 33ee5f8..9cc3a59 100644
--- a/cc/resources/picture_layer_tiling_perftest.cc
+++ b/cc/resources/picture_layer_tiling_perftest.cc
@@ -260,7 +260,7 @@
          ++tile_it) {
       Tile* tile = *tile_it;
       ManagedTileState::DrawInfo& draw_info = tile->draw_info();
-      draw_info.SetResourceForTesting(scoped_ptr<ScopedResource>());
+      draw_info.SetResourceForTesting(nullptr);
     }
 
     perf_test::PrintResult(
diff --git a/cc/resources/picture_layer_tiling_set_unittest.cc b/cc/resources/picture_layer_tiling_set_unittest.cc
index f8cba03..f4059e4 100644
--- a/cc/resources/picture_layer_tiling_set_unittest.cc
+++ b/cc/resources/picture_layer_tiling_set_unittest.cc
@@ -515,7 +515,7 @@
   }
 
   std::vector<Tile*> old_tiles = target_->tiling_at(0)->AllTilesForTesting();
-  std::map<gfx::Point, scoped_refptr<Tile> > old_tile_map;
+  std::map<gfx::Point, scoped_refptr<Tile>> old_tile_map;
   for (size_t i = 0; i < old_tiles.size(); ++i)
     old_tile_map[old_tiles[i]->content_rect().origin()] = old_tiles[i];
 
@@ -525,7 +525,7 @@
   std::vector<Tile*> new_tiles = target_->tiling_at(0)->AllTilesForTesting();
   for (size_t i = 0; i < new_tiles.size(); ++i) {
     const Tile* tile = new_tiles[i];
-    std::map<gfx::Point, scoped_refptr<Tile> >::iterator find =
+    std::map<gfx::Point, scoped_refptr<Tile>>::iterator find =
         old_tile_map.find(tile->content_rect().origin());
     if (content_invalidation.Intersects(tile->content_rect()))
       EXPECT_NE(tile, find->second.get());
diff --git a/cc/resources/picture_pile.cc b/cc/resources/picture_pile.cc
index 1b6a50c..93464f6 100644
--- a/cc/resources/picture_pile.cc
+++ b/cc/resources/picture_pile.cc
@@ -149,7 +149,9 @@
 
 namespace cc {
 
-PicturePile::PicturePile() : is_suitable_for_gpu_rasterization_(true) {
+PicturePile::PicturePile()
+    : is_suitable_for_gpu_rasterization_(true),
+      pixel_record_distance_(kPixelDistanceToRecord) {
 }
 
 PicturePile::~PicturePile() {
@@ -180,11 +182,7 @@
   }
 
   gfx::Rect interest_rect = visible_layer_rect;
-  interest_rect.Inset(
-      -kPixelDistanceToRecord,
-      -kPixelDistanceToRecord,
-      -kPixelDistanceToRecord,
-      -kPixelDistanceToRecord);
+  interest_rect.Inset(-pixel_record_distance_, -pixel_record_distance_);
   recorded_viewport_ = interest_rect;
   recorded_viewport_.Intersect(gfx::Rect(tiling_size()));
 
@@ -385,23 +383,31 @@
     for (auto& it : picture_map_)
       updated = it.second.Invalidate(frame_number) || updated;
   } else {
-    // Expand invalidation that is outside tiles that intersect the interest
-    // rect. These tiles are no longer valid and should be considerered fully
-    // invalid, so we can know to not keep around raster tiles that intersect
-    // with these recording tiles.
+    // Expand invalidation that is on tiles that aren't in the interest rect and
+    // will not be re-recorded below. These tiles are no longer valid and should
+    // be considerered fully invalid, so we can know to not keep around raster
+    // tiles that intersect with these recording tiles.
     Region invalidation_expanded_to_full_tiles;
 
     for (Region::Iterator i(*invalidation); i.has_rect(); i.next()) {
       gfx::Rect invalid_rect = i.rect();
 
-      gfx::Rect invalid_rect_outside_interest_rect_tiles = invalid_rect;
+      // This rect covers the bounds (excluding borders) of all tiles whose
+      // bounds (including borders) touch the |interest_rect|. This matches
+      // the iteration of the |invalid_rect| below which includes borders when
+      // calling Invalidate() on pictures.
+      gfx::Rect invalid_rect_outside_interest_rect_tiles =
+          tiling_.ExpandRectToTileBounds(invalid_rect);
+      // We subtract the |interest_rect_over_tiles| which represents the bounds
+      // of tiles that will be re-recorded below. This matches the iteration of
+      // |interest_rect| below which includes borders.
       // TODO(danakj): We should have a Rect-subtract-Rect-to-2-rects operator
       // instead of using Rect::Subtract which gives you the bounding box of the
       // subtraction.
       invalid_rect_outside_interest_rect_tiles.Subtract(
           interest_rect_over_tiles);
-      invalidation_expanded_to_full_tiles.Union(tiling_.ExpandRectToTileBounds(
-          invalid_rect_outside_interest_rect_tiles));
+      invalidation_expanded_to_full_tiles.Union(
+          invalid_rect_outside_interest_rect_tiles);
 
       // Split this inflated invalidation across tile boundaries and apply it
       // to all tiles that it touches.
diff --git a/cc/resources/picture_pile.h b/cc/resources/picture_pile.h
index 0e8dca6..5395843 100644
--- a/cc/resources/picture_pile.h
+++ b/cc/resources/picture_pile.h
@@ -51,6 +51,8 @@
     is_suitable_for_gpu_rasterization_ = false;
   }
 
+  void SetPixelRecordDistanceForTesting(int d) { pixel_record_distance_ = d; }
+
  protected:
   virtual ~PicturePile();
 
@@ -60,6 +62,7 @@
   void DetermineIfSolidColor();
 
   bool is_suitable_for_gpu_rasterization_;
+  int pixel_record_distance_;
 
   DISALLOW_COPY_AND_ASSIGN(PicturePile);
 };
diff --git a/cc/resources/picture_pile_unittest.cc b/cc/resources/picture_pile_unittest.cc
index 8d798d9..338d5a6 100644
--- a/cc/resources/picture_pile_unittest.cc
+++ b/cc/resources/picture_pile_unittest.cc
@@ -99,6 +99,82 @@
   virtual void SetUp() override { InitializeData(); }
 };
 
+TEST_F(PicturePileTest, InvalidationOnTileBorderOutsideInterestRect) {
+  // Don't expand the interest rect past what we invalidate.
+  pile_->SetPixelRecordDistanceForTesting(0);
+
+  gfx::Size tile_size(100, 100);
+  pile_->tiling().SetMaxTextureSize(tile_size);
+
+  gfx::Size pile_size(400, 400);
+  SetTilingSize(pile_size);
+
+  // We have multiple tiles.
+  EXPECT_GT(pile_->tiling().num_tiles_x(), 2);
+  EXPECT_GT(pile_->tiling().num_tiles_y(), 2);
+
+  // Record everything.
+  Region invalidation(tiling_rect());
+  UpdateAndExpandInvalidation(&invalidation, tiling_size(), tiling_rect());
+
+  // +----------+-----------------+-----------+
+  // |          |     VVVV     1,0|           |
+  // |          |     VVVV        |           |
+  // |          |     VVVV        |           |
+  // |       ...|.................|...        |
+  // |       ...|.................|...        |
+  // +----------+-----------------+-----------+
+  // |       ...|                 |...        |
+  // |       ...|                 |...        |
+  // |       ...|                 |...        |
+  // |       ...|                 |...        |
+  // |       ...|              1,1|...        |
+  // +----------+-----------------+-----------+
+  // |       ...|.................|...        |
+  // |       ...|.................|...        |
+  // +----------+-----------------+-----------+
+  //
+  // .. = border pixels for tile 1,1
+  // VV = interest rect (what we will record)
+  //
+  // The first invalidation is inside VV, so it does not touch border pixels of
+  // tile 1,1.
+  //
+  // The second invalidation goes below VV into the .. border pixels of 1,1.
+
+  // This is the VV interest rect which will be entirely inside 1,0 and not
+  // touch the border of 1,1.
+  gfx::Rect interest_rect(
+      pile_->tiling().TilePositionX(1) + pile_->tiling().border_texels(),
+      0,
+      10,
+      pile_->tiling().TileSizeY(0) - pile_->tiling().border_texels());
+
+  // Invalidate tile 1,0 only. This is a rect that avoids the borders of any
+  // other tiles.
+  gfx::Rect invalidate_tile = interest_rect;
+  // This should cause the tile 1,0 to be invalidated and re-recorded. The
+  // invalidation did not need to be expanded.
+  invalidation = invalidate_tile;
+  UpdateAndExpandInvalidation(&invalidation, tiling_size(), interest_rect);
+  EXPECT_EQ(invalidate_tile, invalidation);
+
+  // Invalidate tile 1,0 and 1,1 by invalidating something that only touches the
+  // border of 1,1 (and is inside the tile bounds of 1,0). This is a 10px wide
+  // strip from the top of the tiling onto the border pixels of tile 1,1 that
+  // avoids border pixels of any other tiles.
+  gfx::Rect invalidate_border = interest_rect;
+  invalidate_border.Inset(0, 0, 0, -1);
+  // This should cause the tile 1,0 and 1,1 to be invalidated. The 1,1 tile will
+  // not be re-recorded since it does not touch the interest rect, so the
+  // invalidation should be expanded to cover all of 1,1.
+  invalidation = invalidate_border;
+  UpdateAndExpandInvalidation(&invalidation, tiling_size(), interest_rect);
+  Region expected_invalidation = invalidate_border;
+  expected_invalidation.Union(pile_->tiling().TileBounds(1, 1));
+  EXPECT_EQ(expected_invalidation.ToString(), invalidation.ToString());
+}
+
 TEST_F(PicturePileTest, SmallInvalidateInflated) {
   // Invalidate something inside a tile.
   Region invalidate_rect(gfx::Rect(50, 50, 1, 1));
diff --git a/cc/resources/pixel_buffer_raster_worker_pool.h b/cc/resources/pixel_buffer_raster_worker_pool.h
index 65fcdad..78933aa 100644
--- a/cc/resources/pixel_buffer_raster_worker_pool.h
+++ b/cc/resources/pixel_buffer_raster_worker_pool.h
@@ -75,7 +75,7 @@
     TaskSetCollection task_sets;
   };
 
-  typedef std::deque<scoped_refptr<RasterTask> > RasterTaskDeque;
+  typedef std::deque<scoped_refptr<RasterTask>> RasterTaskDeque;
 
   PixelBufferRasterWorkerPool(base::SequencedTaskRunner* task_runner,
                               TaskGraphRunner* task_graph_runner,
diff --git a/cc/resources/raster_tile_priority_queue.cc b/cc/resources/raster_tile_priority_queue.cc
index 3eee941..daf4567 100644
--- a/cc/resources/raster_tile_priority_queue.cc
+++ b/cc/resources/raster_tile_priority_queue.cc
@@ -169,9 +169,19 @@
       has_both_layers(layer_pair.active && layer_pair.pending) {
   if (has_both_layers)
     SkipTilesReturnedByTwin(tree_priority);
+  TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
+                       "PairedPictureLayerQueue::PairedPictureLayerQueue",
+                       TRACE_EVENT_SCOPE_THREAD,
+                       "state",
+                       StateAsValue());
 }
 
 RasterTilePriorityQueue::PairedPictureLayerQueue::~PairedPictureLayerQueue() {
+  TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
+                       "PairedPictureLayerQueue::~PairedPictureLayerQueue",
+                       TRACE_EVENT_SCOPE_THREAD,
+                       "state",
+                       StateAsValue());
 }
 
 bool RasterTilePriorityQueue::PairedPictureLayerQueue::IsEmpty() const {
@@ -249,4 +259,35 @@
       tree_priority, &active_iterator, &pending_iterator, nullptr);
 }
 
+scoped_refptr<base::debug::ConvertableToTraceFormat>
+RasterTilePriorityQueue::PairedPictureLayerQueue::StateAsValue() const {
+  scoped_refptr<base::debug::TracedValue> state =
+      new base::debug::TracedValue();
+  state->BeginDictionary("active_iterator");
+  TilePriority::PriorityBin active_priority_bin =
+      active_iterator ? (*active_iterator)->priority(ACTIVE_TREE).priority_bin
+                      : TilePriority::EVENTUALLY;
+  TilePriority::PriorityBin pending_priority_bin =
+      active_iterator ? (*active_iterator)->priority(PENDING_TREE).priority_bin
+                      : TilePriority::EVENTUALLY;
+  state->SetBoolean("has_tile", !!active_iterator);
+  state->SetInteger("active_priority_bin", active_priority_bin);
+  state->SetInteger("pending_priority_bin", pending_priority_bin);
+  state->EndDictionary();
+
+  state->BeginDictionary("pending_iterator");
+  active_priority_bin =
+      pending_iterator ? (*pending_iterator)->priority(ACTIVE_TREE).priority_bin
+                       : TilePriority::EVENTUALLY;
+  pending_priority_bin =
+      pending_iterator
+          ? (*pending_iterator)->priority(PENDING_TREE).priority_bin
+          : TilePriority::EVENTUALLY;
+  state->SetBoolean("has_tile", !!pending_iterator);
+  state->SetInteger("active_priority_bin", active_priority_bin);
+  state->SetInteger("pending_priority_bin", pending_priority_bin);
+  state->EndDictionary();
+  return state;
+}
+
 }  // namespace cc
diff --git a/cc/resources/raster_tile_priority_queue.h b/cc/resources/raster_tile_priority_queue.h
index 5b3b565..3f04e97 100644
--- a/cc/resources/raster_tile_priority_queue.h
+++ b/cc/resources/raster_tile_priority_queue.h
@@ -30,6 +30,8 @@
     WhichTree NextTileIteratorTree(TreePriority tree_priority) const;
     void SkipTilesReturnedByTwin(TreePriority tree_priority);
 
+    scoped_refptr<base::debug::ConvertableToTraceFormat> StateAsValue() const;
+
     PictureLayerImpl::LayerRasterTileIterator active_iterator;
     PictureLayerImpl::LayerRasterTileIterator pending_iterator;
     bool has_both_layers;
diff --git a/cc/resources/raster_worker_pool_perftest.cc b/cc/resources/raster_worker_pool_perftest.cc
index b491e9b..c4e43ac 100644
--- a/cc/resources/raster_worker_pool_perftest.cc
+++ b/cc/resources/raster_worker_pool_perftest.cc
@@ -165,7 +165,7 @@
 
 class RasterWorkerPoolPerfTestBase {
  public:
-  typedef std::vector<scoped_refptr<RasterTask> > RasterTaskVector;
+  typedef std::vector<scoped_refptr<RasterTask>> RasterTaskVector;
 
   enum NamedTaskSet { REQUIRED_FOR_ACTIVATION = 0, ALL = 1 };
 
diff --git a/cc/resources/raster_worker_pool_unittest.cc b/cc/resources/raster_worker_pool_unittest.cc
index e652cd6..7e3d1f9 100644
--- a/cc/resources/raster_worker_pool_unittest.cc
+++ b/cc/resources/raster_worker_pool_unittest.cc
@@ -120,7 +120,7 @@
     bool canceled;
   };
 
-  typedef std::vector<scoped_refptr<RasterTask> > RasterTaskVector;
+  typedef std::vector<scoped_refptr<RasterTask>> RasterTaskVector;
 
   enum NamedTaskSet { REQUIRED_FOR_ACTIVATION = 0, ALL = 1 };
 
diff --git a/cc/resources/rasterizer.h b/cc/resources/rasterizer.h
index 5d2eeee..8013593 100644
--- a/cc/resources/rasterizer.h
+++ b/cc/resources/rasterizer.h
@@ -30,7 +30,7 @@
 
 class CC_EXPORT RasterizerTask : public Task {
  public:
-  typedef std::vector<scoped_refptr<RasterizerTask> > Vector;
+  typedef std::vector<scoped_refptr<RasterizerTask>> Vector;
 
   virtual void ScheduleOnOriginThread(RasterizerTaskClient* client) = 0;
   virtual void CompleteOnOriginThread(RasterizerTaskClient* client) = 0;
@@ -58,7 +58,7 @@
 
 class CC_EXPORT ImageDecodeTask : public RasterizerTask {
  public:
-  typedef std::vector<scoped_refptr<ImageDecodeTask> > Vector;
+  typedef std::vector<scoped_refptr<ImageDecodeTask>> Vector;
 
   // Overridden from RasterizerTask:
   virtual ImageDecodeTask* AsImageDecodeTask() override;
@@ -70,7 +70,7 @@
 
 class CC_EXPORT RasterTask : public RasterizerTask {
  public:
-  typedef std::vector<scoped_refptr<RasterTask> > Vector;
+  typedef std::vector<scoped_refptr<RasterTask>> Vector;
 
   // Overridden from RasterizerTask:
   virtual RasterTask* AsRasterTask() override;
diff --git a/cc/resources/resource_provider.cc b/cc/resources/resource_provider.cc
index ded3477..578c2e9 100644
--- a/cc/resources/resource_provider.cc
+++ b/cc/resources/resource_provider.cc
@@ -1440,7 +1440,7 @@
   int child_id = 0;
   ResourceIdArray resources_for_child;
 
-  std::vector<std::pair<ReturnedResource, ResourceMap::iterator> >
+  std::vector<std::pair<ReturnedResource, ResourceMap::iterator>>
       sorted_resources;
 
   for (ReturnedResourceArray::const_iterator it = resources.begin();
diff --git a/cc/resources/resource_provider_unittest.cc b/cc/resources/resource_provider_unittest.cc
index 25ca028..3daef66 100644
--- a/cc/resources/resource_provider_unittest.cc
+++ b/cc/resources/resource_provider_unittest.cc
@@ -158,7 +158,7 @@
 
   uint32 next_sync_point_;
   unsigned next_mailbox_;
-  typedef base::hash_map<unsigned, scoped_refptr<TestTexture> > TextureMap;
+  typedef base::hash_map<unsigned, scoped_refptr<TestTexture>> TextureMap;
   TextureMap textures_;
   base::hash_map<unsigned, uint32> sync_point_for_mailbox_;
 };
diff --git a/cc/resources/task_graph_runner.h b/cc/resources/task_graph_runner.h
index 0ed7140..2ff085d 100644
--- a/cc/resources/task_graph_runner.h
+++ b/cc/resources/task_graph_runner.h
@@ -17,7 +17,7 @@
 
 class CC_EXPORT Task : public base::RefCountedThreadSafe<Task> {
  public:
-  typedef std::vector<scoped_refptr<Task> > Vector;
+  typedef std::vector<scoped_refptr<Task>> Vector;
 
   virtual void RunOnWorkerThread() = 0;
 
diff --git a/cc/resources/task_graph_runner_perftest.cc b/cc/resources/task_graph_runner_perftest.cc
index 999043f..2ce6dc8 100644
--- a/cc/resources/task_graph_runner_perftest.cc
+++ b/cc/resources/task_graph_runner_perftest.cc
@@ -22,7 +22,7 @@
 
 class PerfTaskImpl : public Task {
  public:
-  typedef std::vector<scoped_refptr<PerfTaskImpl> > Vector;
+  typedef std::vector<scoped_refptr<PerfTaskImpl>> Vector;
 
   PerfTaskImpl() {}
 
diff --git a/cc/resources/tile_manager.cc b/cc/resources/tile_manager.cc
index 84a925f..7fa2e3e 100644
--- a/cc/resources/tile_manager.cc
+++ b/cc/resources/tile_manager.cc
@@ -357,17 +357,19 @@
     // ensures that we activate even when OOM. Note that we have to rebuilt the
     // queue in case the last AssignGpuMemoryToTiles evicted some tiles that
     // would otherwise not be picked up by the old raster queue.
-    raster_priority_queue_.Reset();
     client_->BuildRasterQueue(&raster_priority_queue_,
                               global_state_.tree_priority);
+    bool ready_to_activate = true;
     while (!raster_priority_queue_.IsEmpty()) {
       Tile* tile = raster_priority_queue_.Top();
       ManagedTileState& mts = tile->managed_state();
 
       if (tile->required_for_activation() && !mts.draw_info.IsReadyToDraw()) {
         // If we can't raster on demand, give up early (and don't activate).
-        if (!allow_rasterize_on_demand)
-          return;
+        if (!allow_rasterize_on_demand) {
+          ready_to_activate = false;
+          break;
+        }
 
         mts.draw_info.set_rasterize_on_demand();
         client_->NotifyTileStateChanged(tile);
@@ -375,8 +377,11 @@
       raster_priority_queue_.Pop();
     }
 
-    DCHECK(IsReadyToActivate());
-    ready_to_activate_check_notifier_.Schedule();
+    if (ready_to_activate) {
+      DCHECK(IsReadyToActivate());
+      ready_to_activate_check_notifier_.Schedule();
+    }
+    raster_priority_queue_.Reset();
     return;
   }
 
@@ -459,6 +464,10 @@
 }
 
 void TileManager::RebuildEvictionQueueIfNeeded() {
+  TRACE_EVENT1("cc",
+               "TileManager::RebuildEvictionQueueIfNeeded",
+               "eviction_priority_queue_is_up_to_date",
+               eviction_priority_queue_is_up_to_date_);
   if (eviction_priority_queue_is_up_to_date_)
     return;
 
@@ -523,7 +532,7 @@
 
 void TileManager::AssignGpuMemoryToTiles(
     TileVector* tiles_that_need_to_be_rasterized) {
-  TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
+  TRACE_EVENT_BEGIN0("cc", "TileManager::AssignGpuMemoryToTiles");
 
   // Maintain the list of released resources that can potentially be re-used
   // or deleted.
@@ -546,7 +555,6 @@
                            resource_pool_->acquired_resource_count());
 
   eviction_priority_queue_is_up_to_date_ = false;
-  raster_priority_queue_.Reset();
   client_->BuildRasterQueue(&raster_priority_queue_,
                             global_state_.tree_priority);
 
@@ -554,8 +562,13 @@
     Tile* tile = raster_priority_queue_.Top();
     TilePriority priority = tile->combined_priority();
 
-    if (TilePriorityViolatesMemoryPolicy(priority))
+    if (TilePriorityViolatesMemoryPolicy(priority)) {
+      TRACE_EVENT_INSTANT0(
+          "cc",
+          "TileManager::AssignGpuMemory tile violates memory policy",
+          TRACE_EVENT_SCOPE_THREAD);
       break;
+    }
 
     // We won't be able to schedule this tile, so break out early.
     if (tiles_that_need_to_be_rasterized->size() >=
@@ -622,6 +635,15 @@
   memory_stats_from_last_assign_.total_bytes_used = memory_usage.memory_bytes();
   memory_stats_from_last_assign_.had_enough_memory =
       had_enough_memory_to_schedule_tiles_needed_now;
+
+  raster_priority_queue_.Reset();
+
+  TRACE_EVENT_END2("cc",
+                   "TileManager::AssignGpuMemoryToTiles",
+                   "all_tiles_that_need_to_be_rasterized_are_scheduled",
+                   all_tiles_that_need_to_be_rasterized_are_scheduled_,
+                   "had_enough_memory_to_schedule_tiles_needed_now",
+                   had_enough_memory_to_schedule_tiles_needed_now);
 }
 
 void TileManager::FreeResourcesForTile(Tile* tile) {
diff --git a/cc/resources/tile_manager.h b/cc/resources/tile_manager.h
index 94f1033..03fb6e1 100644
--- a/cc/resources/tile_manager.h
+++ b/cc/resources/tile_manager.h
@@ -249,7 +249,7 @@
   bool did_check_for_completed_tasks_since_last_schedule_tasks_;
   bool did_oom_on_last_assign_;
 
-  typedef base::hash_map<uint32_t, scoped_refptr<ImageDecodeTask> >
+  typedef base::hash_map<uint32_t, scoped_refptr<ImageDecodeTask>>
       PixelRefTaskMap;
   typedef base::hash_map<int, PixelRefTaskMap> LayerPixelRefTaskMap;
   LayerPixelRefTaskMap image_decode_tasks_;
@@ -266,7 +266,7 @@
   // Queue used when scheduling raster tasks.
   RasterTaskQueue raster_queue_;
 
-  std::vector<scoped_refptr<RasterTask> > orphan_raster_tasks_;
+  std::vector<scoped_refptr<RasterTask>> orphan_raster_tasks_;
 
   UniqueNotifier ready_to_activate_check_notifier_;
 
diff --git a/cc/scheduler/scheduler.cc b/cc/scheduler/scheduler.cc
index 5b15a5a..88c27c1 100644
--- a/cc/scheduler/scheduler.cc
+++ b/cc/scheduler/scheduler.cc
@@ -73,6 +73,7 @@
     const SchedulerSettings& scheduler_settings,
     int layer_tree_host_id,
     const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
+    base::PowerMonitor* power_monitor,
     SchedulerFrameSourcesConstructor* frame_sources_constructor)
     : frame_source_(),
       primary_frame_source_(NULL),
@@ -84,6 +85,7 @@
       client_(client),
       layer_tree_host_id_(layer_tree_host_id),
       task_runner_(task_runner),
+      power_monitor_(power_monitor),
       begin_retro_frame_posted_(false),
       state_machine_(scheduler_settings),
       inside_process_scheduled_actions_(false),
@@ -117,9 +119,12 @@
   background_frame_source_ =
       frame_sources_constructor->ConstructBackgroundFrameSource(this);
   frame_source_->AddSource(background_frame_source_);
+
+  SetupPowerMonitoring();
 }
 
 Scheduler::~Scheduler() {
+  TeardownPowerMonitoring();
 }
 
 base::TimeTicks Scheduler::Now() const {
@@ -131,6 +136,27 @@
   return now;
 }
 
+void Scheduler::SetupPowerMonitoring() {
+  if (settings_.disable_hi_res_timer_tasks_on_battery) {
+    DCHECK(power_monitor_);
+    power_monitor_->AddObserver(this);
+    state_machine_.SetImplLatencyTakesPriorityOnBattery(
+        power_monitor_->IsOnBatteryPower());
+  }
+}
+
+void Scheduler::TeardownPowerMonitoring() {
+  if (settings_.disable_hi_res_timer_tasks_on_battery) {
+    DCHECK(power_monitor_);
+    power_monitor_->RemoveObserver(this);
+  }
+}
+
+void Scheduler::OnPowerStateChange(bool on_battery_power) {
+  DCHECK(settings_.disable_hi_res_timer_tasks_on_battery);
+  state_machine_.SetImplLatencyTakesPriorityOnBattery(on_battery_power);
+}
+
 void Scheduler::CommitVSyncParameters(base::TimeTicks timebase,
                                       base::TimeDelta interval) {
   // TODO(brianderson): We should not be receiving 0 intervals.
diff --git a/cc/scheduler/scheduler.h b/cc/scheduler/scheduler.h
index 2ef10a4..6da951c 100644
--- a/cc/scheduler/scheduler.h
+++ b/cc/scheduler/scheduler.h
@@ -11,6 +11,8 @@
 #include "base/basictypes.h"
 #include "base/cancelable_callback.h"
 #include "base/memory/scoped_ptr.h"
+#include "base/power_monitor/power_monitor.h"
+#include "base/power_monitor/power_observer.h"
 #include "base/time/time.h"
 #include "cc/base/cc_export.h"
 #include "cc/output/begin_frame_args.h"
@@ -71,23 +73,29 @@
   friend class Scheduler;
 };
 
-class CC_EXPORT Scheduler : public BeginFrameObserverMixIn {
+class CC_EXPORT Scheduler : public BeginFrameObserverMixIn,
+                            public base::PowerObserver {
  public:
   static scoped_ptr<Scheduler> Create(
       SchedulerClient* client,
       const SchedulerSettings& scheduler_settings,
       int layer_tree_host_id,
-      const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) {
+      const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
+      base::PowerMonitor* power_monitor) {
     SchedulerFrameSourcesConstructor frame_sources_constructor;
     return make_scoped_ptr(new Scheduler(client,
                                          scheduler_settings,
                                          layer_tree_host_id,
                                          task_runner,
+                                         power_monitor,
                                          &frame_sources_constructor));
   }
 
   virtual ~Scheduler();
 
+  // base::PowerObserver method.
+  virtual void OnPowerStateChange(bool on_battery_power) override;
+
   const SchedulerSettings& settings() const { return settings_; }
 
   void CommitVSyncParameters(base::TimeTicks timebase,
@@ -164,6 +172,7 @@
             const SchedulerSettings& scheduler_settings,
             int layer_tree_host_id,
             const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
+            base::PowerMonitor* power_monitor,
             SchedulerFrameSourcesConstructor* frame_sources_constructor);
 
   // virtual for testing - Don't call these in the constructor or
@@ -185,6 +194,8 @@
   int layer_tree_host_id_;
   scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
 
+  base::PowerMonitor* power_monitor_;
+
   base::TimeDelta estimated_parent_draw_time_;
 
   bool begin_retro_frame_posted_;
@@ -223,6 +234,8 @@
   void OnBeginImplFrameDeadline();
   void PollForAnticipatedDrawTriggers();
   void PollToAdvanceCommitState();
+  void SetupPowerMonitoring();
+  void TeardownPowerMonitoring();
 
   base::TimeDelta EstimatedParentDrawTime() {
     return estimated_parent_draw_time_;
diff --git a/cc/scheduler/scheduler_settings.cc b/cc/scheduler/scheduler_settings.cc
index d763536..ab9add0 100644
--- a/cc/scheduler/scheduler_settings.cc
+++ b/cc/scheduler/scheduler_settings.cc
@@ -16,7 +16,8 @@
       timeout_and_draw_when_animation_checkerboards(true),
       maximum_number_of_failed_draws_before_draw_is_forced_(3),
       using_synchronous_renderer_compositor(false),
-      throttle_frame_production(true) {
+      throttle_frame_production(true),
+      disable_hi_res_timer_tasks_on_battery(false) {
 }
 
 SchedulerSettings::SchedulerSettings(const LayerTreeSettings& settings)
@@ -30,7 +31,9 @@
           settings.maximum_number_of_failed_draws_before_draw_is_forced_),
       using_synchronous_renderer_compositor(
           settings.using_synchronous_renderer_compositor),
-      throttle_frame_production(settings.throttle_frame_production) {
+      throttle_frame_production(settings.throttle_frame_production),
+      disable_hi_res_timer_tasks_on_battery(
+          settings.disable_hi_res_timer_tasks_on_battery) {
 }
 
 SchedulerSettings::~SchedulerSettings() {}
@@ -51,6 +54,8 @@
   state->SetBoolean("using_synchronous_renderer_compositor",
                     using_synchronous_renderer_compositor);
   state->SetBoolean("throttle_frame_production", throttle_frame_production);
+  state->SetBoolean("disable_hi_res_timer_tasks_on_battery",
+                    disable_hi_res_timer_tasks_on_battery);
   return state;
 }
 
diff --git a/cc/scheduler/scheduler_settings.h b/cc/scheduler/scheduler_settings.h
index 30c5530..8607991 100644
--- a/cc/scheduler/scheduler_settings.h
+++ b/cc/scheduler/scheduler_settings.h
@@ -31,6 +31,7 @@
   int maximum_number_of_failed_draws_before_draw_is_forced_;
   bool using_synchronous_renderer_compositor;
   bool throttle_frame_production;
+  bool disable_hi_res_timer_tasks_on_battery;
 
   scoped_refptr<base::debug::ConvertableToTraceFormat> AsValue() const;
 };
diff --git a/cc/scheduler/scheduler_state_machine.cc b/cc/scheduler/scheduler_state_machine.cc
index a6904ae..6a412dc 100644
--- a/cc/scheduler/scheduler_state_machine.cc
+++ b/cc/scheduler/scheduler_state_machine.cc
@@ -47,7 +47,8 @@
       impl_latency_takes_priority_(false),
       skip_next_begin_main_frame_to_reduce_latency_(false),
       skip_begin_main_frame_to_reduce_latency_(false),
-      continuous_painting_(false) {
+      continuous_painting_(false),
+      impl_latency_takes_priority_on_battery_(false) {
 }
 
 const char* SchedulerStateMachine::OutputSurfaceStateToString(
@@ -236,6 +237,8 @@
   state->SetBoolean("skip_next_begin_main_frame_to_reduce_latency",
                     skip_next_begin_main_frame_to_reduce_latency_);
   state->SetBoolean("continuous_painting", continuous_painting_);
+  state->SetBoolean("impl_latency_takes_priority_on_battery",
+                    impl_latency_takes_priority_on_battery_);
   state->EndDictionary();
 }
 
@@ -871,6 +874,11 @@
   if (impl_latency_takes_priority_)
     return true;
 
+  // If we are on battery power and want to prioritize impl latency because
+  // we don't trust deadline tasks to execute at the right time.
+  if (impl_latency_takes_priority_on_battery_)
+    return true;
+
   return false;
 }
 
diff --git a/cc/scheduler/scheduler_state_machine.h b/cc/scheduler/scheduler_state_machine.h
index 018f10e..0bcb323 100644
--- a/cc/scheduler/scheduler_state_machine.h
+++ b/cc/scheduler/scheduler_state_machine.h
@@ -238,6 +238,12 @@
 
   bool CouldSendBeginMainFrame() const;
 
+  void SetImplLatencyTakesPriorityOnBattery(
+      bool impl_latency_takes_priority_on_battery) {
+    impl_latency_takes_priority_on_battery_ =
+        impl_latency_takes_priority_on_battery;
+  }
+
   // TODO(zmo): This is temporary for debugging crbug.com/393331.
   // We should remove it afterwards.
   std::string GetStatesForDebugging() const;
@@ -312,6 +318,7 @@
   bool skip_next_begin_main_frame_to_reduce_latency_;
   bool skip_begin_main_frame_to_reduce_latency_;
   bool continuous_painting_;
+  bool impl_latency_takes_priority_on_battery_;
 
  private:
   DISALLOW_COPY_AND_ASSIGN(SchedulerStateMachine);
diff --git a/cc/scheduler/scheduler_unittest.cc b/cc/scheduler/scheduler_unittest.cc
index add50ca..84d9fa3 100644
--- a/cc/scheduler/scheduler_unittest.cc
+++ b/cc/scheduler/scheduler_unittest.cc
@@ -10,6 +10,8 @@
 #include "base/logging.h"
 #include "base/memory/scoped_vector.h"
 #include "base/message_loop/message_loop.h"
+#include "base/power_monitor/power_monitor.h"
+#include "base/power_monitor/power_monitor_source.h"
 #include "base/run_loop.h"
 #include "base/time/time.h"
 #include "cc/test/begin_frame_args_test.h"
@@ -63,12 +65,38 @@
     }
   };
 
+  class FakePowerMonitorSource : public base::PowerMonitorSource {
+   public:
+    FakePowerMonitorSource() {}
+    virtual ~FakePowerMonitorSource() {}
+    void GeneratePowerStateEvent(bool on_battery_power) {
+      on_battery_power_impl_ = on_battery_power;
+      ProcessPowerEvent(POWER_STATE_EVENT);
+      base::MessageLoop::current()->RunUntilIdle();
+    }
+    virtual bool IsOnBatteryPowerImpl() override {
+      return on_battery_power_impl_;
+    }
+
+   private:
+    bool on_battery_power_impl_;
+  };
+
   FakeSchedulerClient()
       : automatic_swap_ack_(true),
         swap_contains_incomplete_tile_(false),
         redraw_will_happen_if_update_visible_tiles_happens_(false),
         now_src_(TestNowSource::Create()),
-        fake_frame_source_(this) {
+        task_runner_(new OrderedSimpleTaskRunner(now_src_, true)),
+        fake_frame_source_(this),
+        fake_power_monitor_source_(new FakePowerMonitorSource),
+        power_monitor_(make_scoped_ptr<base::PowerMonitorSource>(
+            fake_power_monitor_source_)),
+        scheduler_(nullptr) {
+    // A bunch of tests require Now() to be > BeginFrameArgs::DefaultInterval()
+    now_src_->AdvanceNow(base::TimeDelta::FromMilliseconds(100));
+    // Fail if we need to run 100 tasks in a row.
+    task_runner_->SetRunTaskLimit(100);
     Reset();
   }
 
@@ -82,10 +110,9 @@
   }
 
   TestScheduler* CreateScheduler(const SchedulerSettings& settings) {
-    scheduler_ = TestScheduler::Create(now_src_, this, settings, 0);
+    scheduler_ = TestScheduler::Create(
+        now_src_, this, settings, 0, task_runner_, &power_monitor_);
     DCHECK(scheduler_);
-    // Fail if we need to run 100 tasks in a row.
-    task_runner().SetRunTaskLimit(100);
     return scheduler_.get();
   }
 
@@ -111,6 +138,12 @@
     return &fake_frame_source_;
   }
 
+  base::PowerMonitor* PowerMonitor() { return &power_monitor_; }
+
+  FakePowerMonitorSource* PowerMonitorSource() {
+    return fake_power_monitor_source_;
+  }
+
   void AdvanceFrame() {
     TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"),
                  "FakeSchedulerClient::AdvanceFrame");
@@ -128,7 +161,7 @@
     EXPECT_TRUE(scheduler_->BeginImplFrameDeadlinePending());
   }
 
-  OrderedSimpleTaskRunner& task_runner() { return scheduler_->task_runner(); }
+  OrderedSimpleTaskRunner& task_runner() { return *task_runner_; }
   TestNowSource* now_src() { return now_src_.get(); }
 
   int ActionIndex(const char* action) const {
@@ -256,10 +289,13 @@
   bool redraw_will_happen_if_update_visible_tiles_happens_;
   base::TimeTicks posted_begin_impl_frame_deadline_;
   std::vector<const char*> actions_;
-  std::vector<scoped_refptr<base::debug::ConvertableToTraceFormat> > states_;
-  scoped_ptr<TestScheduler> scheduler_;
+  std::vector<scoped_refptr<base::debug::ConvertableToTraceFormat>> states_;
   scoped_refptr<TestNowSource> now_src_;
+  scoped_refptr<OrderedSimpleTaskRunner> task_runner_;
   FakeBeginFrameSourceForFakeSchedulerClient fake_frame_source_;
+  FakePowerMonitorSource* fake_power_monitor_source_;
+  base::PowerMonitor power_monitor_;
+  scoped_ptr<TestScheduler> scheduler_;
 };
 
 void InitializeOutputSurfaceAndFirstCommit(Scheduler* scheduler,
@@ -1967,5 +2003,152 @@
   EXPECT_ACTION("ScheduledActionActivateSyncTree", client, 1, 2);
 }
 
+TEST(SchedulerTest, SchedulerPowerMonitoring) {
+  FakeSchedulerClient client;
+  SchedulerSettings settings;
+  settings.disable_hi_res_timer_tasks_on_battery = true;
+  TestScheduler* scheduler = client.CreateScheduler(settings);
+
+  base::TimeTicks before_deadline, after_deadline;
+
+  scheduler->SetCanStart();
+  scheduler->SetVisible(true);
+  scheduler->SetCanDraw(true);
+
+  InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
+
+  scheduler->SetNeedsCommit();
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  // On non-battery power
+  EXPECT_FALSE(client.PowerMonitor()->IsOnBatteryPower());
+
+  client.AdvanceFrame();
+  client.Reset();
+
+  before_deadline = client.now_src()->Now();
+  EXPECT_TRUE(client.task_runner().RunTasksWhile(
+      client.ImplFrameDeadlinePending(true)));
+  after_deadline = client.now_src()->Now();
+
+  // We post a non-zero deadline task when not on battery
+  EXPECT_LT(before_deadline, after_deadline);
+
+  // Switch to battery power
+  client.PowerMonitorSource()->GeneratePowerStateEvent(true);
+  EXPECT_TRUE(client.PowerMonitor()->IsOnBatteryPower());
+
+  client.AdvanceFrame();
+  scheduler->SetNeedsCommit();
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  before_deadline = client.now_src()->Now();
+  EXPECT_TRUE(client.task_runner().RunTasksWhile(
+      client.ImplFrameDeadlinePending(true)));
+  after_deadline = client.now_src()->Now();
+
+  // We post a zero deadline task when on battery
+  EXPECT_EQ(before_deadline, after_deadline);
+
+  // Switch to non-battery power
+  client.PowerMonitorSource()->GeneratePowerStateEvent(false);
+  EXPECT_FALSE(client.PowerMonitor()->IsOnBatteryPower());
+
+  client.AdvanceFrame();
+  scheduler->SetNeedsCommit();
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  // Same as before
+  before_deadline = client.now_src()->Now();
+  EXPECT_TRUE(client.task_runner().RunTasksWhile(
+      client.ImplFrameDeadlinePending(true)));
+  after_deadline = client.now_src()->Now();
+}
+
+TEST(SchedulerTest,
+     SimulateWindowsLowResolutionTimerOnBattery_PrioritizeImplLatencyOff) {
+  FakeSchedulerClient client;
+  SchedulerSettings settings;
+  TestScheduler* scheduler = client.CreateScheduler(settings);
+
+  scheduler->SetCanStart();
+  scheduler->SetVisible(true);
+  scheduler->SetCanDraw(true);
+
+  InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
+
+  // Set needs commit so that the scheduler tries to wait for the main thread
+  scheduler->SetNeedsCommit();
+  // Set needs redraw so that the scheduler doesn't wait too long
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  // Switch to battery power
+  client.PowerMonitorSource()->GeneratePowerStateEvent(true);
+  EXPECT_TRUE(client.PowerMonitor()->IsOnBatteryPower());
+
+  client.AdvanceFrame();
+  scheduler->SetNeedsCommit();
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  // Disable auto-advancing of now_src
+  client.task_runner().SetAutoAdvanceNowToPendingTasks(false);
+
+  // Deadline task is pending
+  EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
+  client.task_runner().RunPendingTasks();
+  // Deadline task is still pending
+  EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
+
+  // Advance now by 15 ms - same as windows low res timer
+  client.now_src()->AdvanceNowMicroseconds(15000);
+  EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
+  client.task_runner().RunPendingTasks();
+  // Deadline task finally completes
+  EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
+}
+
+TEST(SchedulerTest,
+     SimulateWindowsLowResolutionTimerOnBattery_PrioritizeImplLatencyOn) {
+  FakeSchedulerClient client;
+  SchedulerSettings settings;
+  settings.disable_hi_res_timer_tasks_on_battery = true;
+  TestScheduler* scheduler = client.CreateScheduler(settings);
+
+  scheduler->SetCanStart();
+  scheduler->SetVisible(true);
+  scheduler->SetCanDraw(true);
+
+  InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
+
+  // Set needs commit so that the scheduler tries to wait for the main thread
+  scheduler->SetNeedsCommit();
+  // Set needs redraw so that the scheduler doesn't wait too long
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  // Switch to battery power
+  client.PowerMonitorSource()->GeneratePowerStateEvent(true);
+  EXPECT_TRUE(client.PowerMonitor()->IsOnBatteryPower());
+
+  client.AdvanceFrame();
+  scheduler->SetNeedsCommit();
+  scheduler->SetNeedsRedraw();
+  client.Reset();
+
+  // Disable auto-advancing of now_src
+  client.task_runner().SetAutoAdvanceNowToPendingTasks(false);
+
+  // Deadline task is pending
+  EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
+  client.task_runner().RunPendingTasks();
+  // Deadline task runs immediately
+  EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
+}
+
 }  // namespace
 }  // namespace cc
diff --git a/cc/surfaces/surface.cc b/cc/surfaces/surface.cc
index 4d32d72..07c5ae6 100644
--- a/cc/surfaces/surface.cc
+++ b/cc/surfaces/surface.cc
@@ -23,12 +23,7 @@
 }
 
 Surface::~Surface() {
-  for (ScopedPtrVector<CopyOutputRequest>::iterator it = copy_requests_.begin();
-       it != copy_requests_.end();
-       ++it) {
-    (*it)->SendEmptyResult();
-  }
-  copy_requests_.clear();
+  ClearCopyRequests();
   if (current_frame_ && factory_) {
     ReturnedResourceArray current_resources;
     TransferableResource::ReturnResources(
@@ -41,13 +36,7 @@
 void Surface::QueueFrame(scoped_ptr<CompositorFrame> frame,
                          const base::Closure& callback) {
   DCHECK(factory_);
-  for (ScopedPtrVector<CopyOutputRequest>::iterator it = copy_requests_.begin();
-       it != copy_requests_.end();
-       ++it) {
-    (*it)->SendEmptyResult();
-  }
-  copy_requests_.clear();
-
+  ClearCopyRequests();
   TakeLatencyInfo(&frame->metadata.latency_info);
   scoped_ptr<CompositorFrame> previous_frame = current_frame_.Pass();
   current_frame_ = frame.Pass();
@@ -70,13 +59,29 @@
 }
 
 void Surface::RequestCopyOfOutput(scoped_ptr<CopyOutputRequest> copy_request) {
-  copy_requests_.push_back(copy_request.Pass());
+  if (current_frame_ &&
+      !current_frame_->delegated_frame_data->render_pass_list.empty())
+    current_frame_->delegated_frame_data->render_pass_list.back()
+        ->copy_requests.push_back(copy_request.Pass());
+  else
+    copy_request->SendEmptyResult();
 }
 
 void Surface::TakeCopyOutputRequests(
-    ScopedPtrVector<CopyOutputRequest>* copy_requests) {
+    std::multimap<RenderPassId, CopyOutputRequest*>* copy_requests) {
   DCHECK(copy_requests->empty());
-  copy_requests->swap(copy_requests_);
+  if (current_frame_) {
+    for (auto* render_pass :
+         current_frame_->delegated_frame_data->render_pass_list) {
+      while (!render_pass->copy_requests.empty()) {
+        scoped_ptr<CopyOutputRequest> request =
+            render_pass->copy_requests.take_back();
+        render_pass->copy_requests.pop_back();
+        copy_requests->insert(
+            std::make_pair(render_pass->id, request.release()));
+      }
+    }
+  }
 }
 
 const CompositorFrame* Surface::GetEligibleFrame() {
@@ -104,4 +109,14 @@
   }
 }
 
+void Surface::ClearCopyRequests() {
+  if (current_frame_) {
+    for (auto* render_pass :
+         current_frame_->delegated_frame_data->render_pass_list) {
+      for (auto* copy_request : render_pass->copy_requests)
+        copy_request->SendEmptyResult();
+    }
+  }
+}
+
 }  // namespace cc
diff --git a/cc/surfaces/surface.h b/cc/surfaces/surface.h
index 0df5c17..c55dfe8 100644
--- a/cc/surfaces/surface.h
+++ b/cc/surfaces/surface.h
@@ -5,6 +5,7 @@
 #ifndef CC_SURFACES_SURFACE_H_
 #define CC_SURFACES_SURFACE_H_
 
+#include <map>
 #include <vector>
 
 #include "base/callback.h"
@@ -14,6 +15,7 @@
 #include "base/memory/weak_ptr.h"
 #include "cc/base/scoped_ptr_vector.h"
 #include "cc/output/copy_output_request.h"
+#include "cc/quads/render_pass_id.h"
 #include "cc/surfaces/surface_id.h"
 #include "cc/surfaces/surfaces_export.h"
 #include "ui/gfx/size.h"
@@ -40,8 +42,10 @@
   void QueueFrame(scoped_ptr<CompositorFrame> frame,
                   const base::Closure& draw_callback);
   void RequestCopyOfOutput(scoped_ptr<CopyOutputRequest> copy_request);
+  // Adds each CopyOutputRequest in the current frame to copy_requests. The
+  // caller takes ownership of them.
   void TakeCopyOutputRequests(
-      ScopedPtrVector<CopyOutputRequest>* copy_requests);
+      std::multimap<RenderPassId, CopyOutputRequest*>* copy_requests);
   // Returns the most recent frame that is eligible to be rendered.
   const CompositorFrame* GetEligibleFrame();
 
@@ -54,13 +58,14 @@
   base::WeakPtr<SurfaceFactory> factory() { return factory_; }
 
  private:
+  void ClearCopyRequests();
+
   SurfaceId surface_id_;
   gfx::Size size_;
   base::WeakPtr<SurfaceFactory> factory_;
   // TODO(jamesr): Support multiple frames in flight.
   scoped_ptr<CompositorFrame> current_frame_;
   int frame_index_;
-  ScopedPtrVector<CopyOutputRequest> copy_requests_;
 
   base::Closure draw_callback_;
 
diff --git a/cc/surfaces/surface_aggregator.cc b/cc/surfaces/surface_aggregator.cc
index 620ada7..f6bf6d6 100644
--- a/cc/surfaces/surface_aggregator.cc
+++ b/cc/surfaces/surface_aggregator.cc
@@ -21,6 +21,22 @@
 #include "cc/trees/blocking_task_runner.h"
 
 namespace cc {
+namespace {
+
+void MoveMatchingRequests(
+    RenderPassId id,
+    std::multimap<RenderPassId, CopyOutputRequest*>* copy_requests,
+    ScopedPtrVector<CopyOutputRequest>* output_requests) {
+  auto request_range = copy_requests->equal_range(id);
+  for (auto it = request_range.first; it != request_range.second; ++it) {
+    DCHECK(it->second);
+    output_requests->push_back(scoped_ptr<CopyOutputRequest>(it->second));
+    it->second = nullptr;
+  }
+  copy_requests->erase(request_range.first, request_range.second);
+}
+
+}  // namespace
 
 SurfaceAggregator::SurfaceAggregator(SurfaceManager* manager,
                                      ResourceProvider* provider)
@@ -165,16 +181,21 @@
   if (!frame_data)
     return;
 
+  std::multimap<RenderPassId, CopyOutputRequest*> copy_requests;
+  surface->TakeCopyOutputRequests(&copy_requests);
+
   RenderPassList render_pass_list;
   bool invalid_frame = TakeResources(surface, frame_data, &render_pass_list);
-  if (invalid_frame)
+  if (invalid_frame) {
+    for (auto& request : copy_requests) {
+      request.second->SendEmptyResult();
+      delete request.second;
+    }
     return;
+  }
 
   SurfaceSet::iterator it = referenced_surfaces_.insert(surface_id).first;
 
-  ScopedPtrVector<CopyOutputRequest> copy_requests;
-  surface->TakeCopyOutputRequests(&copy_requests);
-
   bool merge_pass = copy_requests.empty();
 
   const RenderPassList& referenced_passes = render_pass_list;
@@ -195,6 +216,8 @@
                       source.transform_to_root_target,
                       source.has_transparent_background);
 
+    MoveMatchingRequests(source.id, &copy_requests, &copy_pass->copy_requests);
+
     // Contributing passes aggregated in to the pass list need to take the
     // transform of the surface quad into account to update their transform to
     // the root surface.
@@ -226,8 +249,6 @@
   } else {
     RenderPassId remapped_pass_id = RemapPassId(last_pass.id, surface_id);
 
-    dest_pass_list_->back()->copy_requests.swap(copy_requests);
-
     SharedQuadState* shared_quad_state =
         dest_pass->CreateAndAppendSharedQuadState();
     shared_quad_state->CopyFrom(surface_quad->shared_quad_state);
@@ -238,7 +259,8 @@
                  surface_quad->visible_rect,
                  remapped_pass_id,
                  0,
-                 gfx::RectF(),
+                 gfx::Vector2dF(),
+                 gfx::Size(),
                  FilterOperations(),
                  gfx::Vector2dF(),
                  FilterOperations());
@@ -319,8 +341,18 @@
   }
 }
 
-void SurfaceAggregator::CopyPasses(const RenderPassList& source_pass_list,
-                                   const Surface* surface) {
+void SurfaceAggregator::CopyPasses(const DelegatedFrameData* frame_data,
+                                   Surface* surface) {
+  RenderPassList source_pass_list;
+
+  // The root surface is allowed to have copy output requests, so grab them
+  // off its render passes.
+  std::multimap<RenderPassId, CopyOutputRequest*> copy_requests;
+  surface->TakeCopyOutputRequests(&copy_requests);
+
+  bool invalid_frame = TakeResources(surface, frame_data, &source_pass_list);
+  DCHECK(!invalid_frame);
+
   for (size_t i = 0; i < source_pass_list.size(); ++i) {
     const RenderPass& source = *source_pass_list[i];
 
@@ -328,6 +360,8 @@
     size_t dq_size = source.quad_list.size();
     scoped_ptr<RenderPass> copy_pass(RenderPass::Create(sqs_size, dq_size));
 
+    MoveMatchingRequests(source.id, &copy_requests, &copy_pass->copy_requests);
+
     RenderPassId remapped_pass_id =
         RemapPassId(source.id, surface->surface_id());
 
@@ -361,20 +395,12 @@
 
   DCHECK(root_surface_frame->delegated_frame_data);
 
-  RenderPassList source_pass_list;
-
   SurfaceSet::iterator it = referenced_surfaces_.insert(surface_id).first;
 
   dest_resource_list_ = &frame->delegated_frame_data->resource_list;
   dest_pass_list_ = &frame->delegated_frame_data->render_pass_list;
 
-  bool invalid_frame =
-      TakeResources(surface,
-                    root_surface_frame->delegated_frame_data.get(),
-                    &source_pass_list);
-  DCHECK(!invalid_frame);
-
-  CopyPasses(source_pass_list, surface);
+  CopyPasses(root_surface_frame->delegated_frame_data.get(), surface);
 
   referenced_surfaces_.erase(it);
   DCHECK(referenced_surfaces_.empty());
diff --git a/cc/surfaces/surface_aggregator.h b/cc/surfaces/surface_aggregator.h
index 5e91c87..64c10e1 100644
--- a/cc/surfaces/surface_aggregator.h
+++ b/cc/surfaces/surface_aggregator.h
@@ -50,8 +50,7 @@
                        const gfx::Transform& content_to_target_transform,
                        RenderPass* dest_pass,
                        SurfaceId surface_id);
-  void CopyPasses(const RenderPassList& source_pass_list,
-                  const Surface* surface);
+  void CopyPasses(const DelegatedFrameData* frame_data, Surface* surface);
 
   bool TakeResources(Surface* surface,
                      const DelegatedFrameData* frame_data,
diff --git a/cc/surfaces/surface_aggregator_test_helpers.cc b/cc/surfaces/surface_aggregator_test_helpers.cc
index c6a7aa0..a40b2c2 100644
--- a/cc/surfaces/surface_aggregator_test_helpers.cc
+++ b/cc/surfaces/surface_aggregator_test_helpers.cc
@@ -69,7 +69,8 @@
                output_rect,
                render_pass_id,
                0,
-               gfx::RectF(),
+               gfx::Vector2dF(),
+               gfx::Size(),
                FilterOperations(),
                gfx::Vector2dF(),
                FilterOperations());
diff --git a/cc/surfaces/surface_aggregator_unittest.cc b/cc/surfaces/surface_aggregator_unittest.cc
index 00e5b4d..243a9a4 100644
--- a/cc/surfaces/surface_aggregator_unittest.cc
+++ b/cc/surfaces/surface_aggregator_unittest.cc
@@ -252,6 +252,94 @@
   factory_.Destroy(embedded_surface_id);
 }
 
+// Root surface may contain copy requests.
+TEST_F(SurfaceAggregatorValidSurfaceTest, RootCopyRequest) {
+  SurfaceId embedded_surface_id = allocator_.GenerateId();
+  factory_.Create(embedded_surface_id, SurfaceSize());
+
+  test::Quad embedded_quads[] = {test::Quad::SolidColorQuad(SK_ColorGREEN)};
+  test::Pass embedded_passes[] = {
+      test::Pass(embedded_quads, arraysize(embedded_quads))};
+
+  SubmitFrame(embedded_passes, arraysize(embedded_passes), embedded_surface_id);
+  scoped_ptr<CopyOutputRequest> copy_request(
+      CopyOutputRequest::CreateEmptyRequest());
+  CopyOutputRequest* copy_request_ptr = copy_request.get();
+  scoped_ptr<CopyOutputRequest> copy_request2(
+      CopyOutputRequest::CreateEmptyRequest());
+  CopyOutputRequest* copy_request2_ptr = copy_request2.get();
+
+  test::Quad root_quads[] = {test::Quad::SolidColorQuad(SK_ColorWHITE),
+                             test::Quad::SurfaceQuad(embedded_surface_id),
+                             test::Quad::SolidColorQuad(SK_ColorBLACK)};
+  test::Quad root_quads2[] = {test::Quad::SolidColorQuad(SK_ColorRED)};
+  test::Pass root_passes[] = {
+      test::Pass(root_quads, arraysize(root_quads), RenderPassId(1, 1)),
+      test::Pass(root_quads2, arraysize(root_quads2), RenderPassId(1, 2))};
+  {
+    RenderPassList pass_list;
+    AddPasses(&pass_list,
+              gfx::Rect(SurfaceSize()),
+              root_passes,
+              arraysize(root_passes));
+    pass_list[0]->copy_requests.push_back(copy_request.Pass());
+    pass_list[1]->copy_requests.push_back(copy_request2.Pass());
+
+    scoped_ptr<DelegatedFrameData> frame_data(new DelegatedFrameData);
+    pass_list.swap(frame_data->render_pass_list);
+
+    scoped_ptr<CompositorFrame> frame(new CompositorFrame);
+    frame->delegated_frame_data = frame_data.Pass();
+
+    factory_.SubmitFrame(root_surface_id_, frame.Pass(), base::Closure());
+  }
+
+  scoped_ptr<CompositorFrame> aggregated_frame =
+      aggregator_.Aggregate(root_surface_id_);
+
+  ASSERT_TRUE(aggregated_frame);
+  ASSERT_TRUE(aggregated_frame->delegated_frame_data);
+
+  DelegatedFrameData* frame_data = aggregated_frame->delegated_frame_data.get();
+
+  test::Quad expected_quads[] = {test::Quad::SolidColorQuad(SK_ColorWHITE),
+                                 test::Quad::SolidColorQuad(SK_ColorGREEN),
+                                 test::Quad::SolidColorQuad(SK_ColorBLACK)};
+  test::Pass expected_passes[] = {
+      test::Pass(expected_quads, arraysize(expected_quads)),
+      test::Pass(root_quads2, arraysize(root_quads2))};
+  TestPassesMatchExpectations(expected_passes,
+                              arraysize(expected_passes),
+                              &frame_data->render_pass_list);
+  ASSERT_EQ(2u, frame_data->render_pass_list.size());
+  ASSERT_EQ(1u, frame_data->render_pass_list[0]->copy_requests.size());
+  DCHECK_EQ(copy_request_ptr,
+            frame_data->render_pass_list[0]->copy_requests[0]);
+  ASSERT_EQ(1u, frame_data->render_pass_list[1]->copy_requests.size());
+  DCHECK_EQ(copy_request2_ptr,
+            frame_data->render_pass_list[1]->copy_requests[0]);
+
+  SurfaceId surface_ids[] = {root_surface_id_, embedded_surface_id};
+  EXPECT_EQ(arraysize(surface_ids),
+            aggregator_.previous_contained_surfaces().size());
+  for (size_t i = 0; i < arraysize(surface_ids); i++) {
+    EXPECT_TRUE(
+        aggregator_.previous_contained_surfaces().find(surface_ids[i]) !=
+        aggregator_.previous_contained_surfaces().end());
+  }
+
+  // Ensure copy requests have been removed from root surface.
+  const CompositorFrame* original_frame =
+      manager_.GetSurfaceForId(root_surface_id_)->GetEligibleFrame();
+  RenderPassList& original_pass_list =
+      original_frame->delegated_frame_data->render_pass_list;
+  ASSERT_EQ(2u, original_pass_list.size());
+  DCHECK(original_pass_list[0]->copy_requests.empty());
+  DCHECK(original_pass_list[1]->copy_requests.empty());
+
+  factory_.Destroy(embedded_surface_id);
+}
+
 // This tests referencing a surface that has multiple render passes.
 TEST_F(SurfaceAggregatorValidSurfaceTest, MultiPassSurfaceReference) {
   SurfaceId embedded_surface_id = allocator_.GenerateId();
diff --git a/cc/test/animation_test_common.cc b/cc/test/animation_test_common.cc
index 7c1b3f6..5ab8942 100644
--- a/cc/test/animation_test_common.cc
+++ b/cc/test/animation_test_common.cc
@@ -36,8 +36,7 @@
     func = EaseTimingFunction::Create();
   if (duration > 0.0)
     curve->AddKeyframe(FloatKeyframe::Create(0.0, start_opacity, func.Pass()));
-  curve->AddKeyframe(FloatKeyframe::Create(
-      duration, end_opacity, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FloatKeyframe::Create(duration, end_opacity, nullptr));
 
   int id = AnimationIdProvider::NextAnimationId();
 
@@ -61,12 +60,11 @@
       curve(KeyframedTransformAnimationCurve::Create());
 
   if (duration > 0.0) {
-    curve->AddKeyframe(TransformKeyframe::Create(
-        0.0, start_operations, scoped_ptr<TimingFunction>()));
+    curve->AddKeyframe(
+        TransformKeyframe::Create(0.0, start_operations, nullptr));
   }
 
-  curve->AddKeyframe(TransformKeyframe::Create(
-      duration, operations, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(TransformKeyframe::Create(duration, operations, nullptr));
 
   int id = AnimationIdProvider::NextAnimationId();
 
@@ -108,14 +106,12 @@
     FilterOperations start_filters;
     start_filters.Append(
         FilterOperation::CreateBrightnessFilter(start_brightness));
-    curve->AddKeyframe(FilterKeyframe::Create(
-        0.0, start_filters, scoped_ptr<TimingFunction>()));
+    curve->AddKeyframe(FilterKeyframe::Create(0.0, start_filters, nullptr));
   }
 
   FilterOperations filters;
   filters.Append(FilterOperation::CreateBrightnessFilter(end_brightness));
-  curve->AddKeyframe(
-      FilterKeyframe::Create(duration, filters, scoped_ptr<TimingFunction>()));
+  curve->AddKeyframe(FilterKeyframe::Create(duration, filters, nullptr));
 
   int id = AnimationIdProvider::NextAnimationId();
 
diff --git a/cc/test/fake_content_layer_client.h b/cc/test/fake_content_layer_client.h
index 3ae031a..b74860d 100644
--- a/cc/test/fake_content_layer_client.h
+++ b/cc/test/fake_content_layer_client.h
@@ -59,7 +59,7 @@
   }
 
  private:
-  typedef std::vector<std::pair<gfx::RectF, SkPaint> > RectPaintVector;
+  typedef std::vector<std::pair<gfx::RectF, SkPaint>> RectPaintVector;
   typedef std::vector<BitmapData> BitmapVector;
 
   bool fill_with_nonsolid_color_;
diff --git a/cc/test/fake_painted_scrollbar_layer.cc b/cc/test/fake_painted_scrollbar_layer.cc
index 88dd010..e74581a 100644
--- a/cc/test/fake_painted_scrollbar_layer.cc
+++ b/cc/test/fake_painted_scrollbar_layer.cc
@@ -47,7 +47,7 @@
   ++push_properties_count_;
 }
 
-scoped_ptr<base::AutoReset<bool> >
+scoped_ptr<base::AutoReset<bool>>
 FakePaintedScrollbarLayer::IgnoreSetNeedsCommit() {
   return make_scoped_ptr(
       new base::AutoReset<bool>(&ignore_set_needs_commit_, true));
diff --git a/cc/test/fake_painted_scrollbar_layer.h b/cc/test/fake_painted_scrollbar_layer.h
index f531299..0fb3437 100644
--- a/cc/test/fake_painted_scrollbar_layer.h
+++ b/cc/test/fake_painted_scrollbar_layer.h
@@ -25,7 +25,7 @@
 
   virtual void PushPropertiesTo(LayerImpl* layer) override;
 
-  scoped_ptr<base::AutoReset<bool> > IgnoreSetNeedsCommit();
+  scoped_ptr<base::AutoReset<bool>> IgnoreSetNeedsCommit();
 
   size_t push_properties_count() const { return push_properties_count_; }
   void reset_push_properties_count() { push_properties_count_ = 0; }
diff --git a/cc/test/layer_tree_host_common_test.h b/cc/test/layer_tree_host_common_test.h
index f5dc48e..38b57d4 100644
--- a/cc/test/layer_tree_host_common_test.h
+++ b/cc/test/layer_tree_host_common_test.h
@@ -122,7 +122,7 @@
 
  private:
   scoped_ptr<RenderSurfaceLayerList> render_surface_layer_list_;
-  scoped_ptr<std::vector<LayerImpl*> > render_surface_layer_list_impl_;
+  scoped_ptr<std::vector<LayerImpl*>> render_surface_layer_list_impl_;
 
   FakeLayerTreeHostClient client_;
   int render_surface_layer_list_count_;
diff --git a/cc/test/layer_tree_pixel_test.cc b/cc/test/layer_tree_pixel_test.cc
index ed14e33..2f293f7 100644
--- a/cc/test/layer_tree_pixel_test.cc
+++ b/cc/test/layer_tree_pixel_test.cc
@@ -130,8 +130,7 @@
   // Drop TextureMailboxes on the main thread so that they can be cleaned up and
   // the pending callbacks will fire.
   for (size_t i = 0; i < texture_layers_.size(); ++i) {
-    texture_layers_[i]->SetTextureMailbox(TextureMailbox(),
-                                          scoped_ptr<SingleReleaseCallback>());
+    texture_layers_[i]->SetTextureMailbox(TextureMailbox(), nullptr);
   }
 
   TryEndTest();
diff --git a/cc/test/layer_tree_pixel_test.h b/cc/test/layer_tree_pixel_test.h
index a29e0f1..eae283b 100644
--- a/cc/test/layer_tree_pixel_test.h
+++ b/cc/test/layer_tree_pixel_test.h
@@ -100,7 +100,7 @@
   Layer* readback_target_;
   base::FilePath ref_file_;
   scoped_ptr<SkBitmap> result_bitmap_;
-  std::vector<scoped_refptr<TextureLayer> > texture_layers_;
+  std::vector<scoped_refptr<TextureLayer>> texture_layers_;
   int pending_texture_mailbox_callbacks_;
   bool impl_side_painting_;
 };
diff --git a/cc/test/layer_tree_test.h b/cc/test/layer_tree_test.h
index 9350680..a36fee4 100644
--- a/cc/test/layer_tree_test.h
+++ b/cc/test/layer_tree_test.h
@@ -91,11 +91,12 @@
 
   // Implementation of AnimationDelegate:
   virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
-                                      Animation::TargetProperty target_property)
-      override {}
+                                      Animation::TargetProperty target_property,
+                                      int group) override {}
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {}
+      Animation::TargetProperty target_property,
+      int group) override {}
 
   virtual void RequestNewOutputSurface(bool fallback) = 0;
 };
diff --git a/cc/test/ordered_simple_task_runner.cc b/cc/test/ordered_simple_task_runner.cc
index 48afd9b..9cad797 100644
--- a/cc/test/ordered_simple_task_runner.cc
+++ b/cc/test/ordered_simple_task_runner.cc
@@ -157,13 +157,13 @@
 
 bool OrderedSimpleTaskRunner::RunTasksWhile(
     base::Callback<bool(void)> condition) {
-  std::vector<base::Callback<bool(void)> > conditions(1);
+  std::vector<base::Callback<bool(void)>> conditions(1);
   conditions[0] = condition;
   return RunTasksWhile(conditions);
 }
 
 bool OrderedSimpleTaskRunner::RunTasksWhile(
-    const std::vector<base::Callback<bool(void)> >& conditions) {
+    const std::vector<base::Callback<bool(void)>>& conditions) {
   TRACE_EVENT2("cc",
                "OrderedSimpleTaskRunner::RunPendingTasks",
                "this",
@@ -179,7 +179,7 @@
                                                       true);
 
   // Make a copy so we can append some extra run checks.
-  std::vector<base::Callback<bool(void)> > modifiable_conditions(conditions);
+  std::vector<base::Callback<bool(void)>> modifiable_conditions(conditions);
 
   // Provide a timeout base on number of tasks run so this doesn't loop
   // forever.
@@ -195,7 +195,7 @@
   while (pending_tasks_.size() > 0) {
     // Check if we should continue to run pending tasks.
     bool condition_success = true;
-    for (std::vector<base::Callback<bool(void)> >::iterator it =
+    for (std::vector<base::Callback<bool(void)>>::iterator it =
              modifiable_conditions.begin();
          it != modifiable_conditions.end();
          it++) {
@@ -231,7 +231,7 @@
 }
 
 bool OrderedSimpleTaskRunner::RunUntilIdle() {
-  return RunTasksWhile(std::vector<base::Callback<bool(void)> >());
+  return RunTasksWhile(std::vector<base::Callback<bool(void)>>());
 }
 
 bool OrderedSimpleTaskRunner::RunUntilTime(base::TimeTicks time) {
diff --git a/cc/test/ordered_simple_task_runner.h b/cc/test/ordered_simple_task_runner.h
index 68c9587..ee80efe 100644
--- a/cc/test/ordered_simple_task_runner.h
+++ b/cc/test/ordered_simple_task_runner.h
@@ -87,8 +87,7 @@
   // calling all remaining conditions. Conditions can have side effects,
   // including modifying the task queue.
   // Returns true if there are still pending tasks left.
-  bool RunTasksWhile(
-      const std::vector<base::Callback<bool(void)> >& conditions);
+  bool RunTasksWhile(const std::vector<base::Callback<bool(void)>>& conditions);
 
   // Convenience functions to run tasks with common conditions.
 
diff --git a/cc/test/ordered_texture_map.h b/cc/test/ordered_texture_map.h
index 4797c59..2aa3111 100644
--- a/cc/test/ordered_texture_map.h
+++ b/cc/test/ordered_texture_map.h
@@ -32,8 +32,7 @@
   GLuint IdAt(size_t index);
 
  private:
-  typedef base::hash_map<GLuint, scoped_refptr<TestTexture> >
-      TextureMap;
+  typedef base::hash_map<GLuint, scoped_refptr<TestTexture>> TextureMap;
   typedef std::vector<GLuint> TextureList;
 
   TextureMap textures_;
diff --git a/cc/test/render_pass_test_common.cc b/cc/test/render_pass_test_common.cc
index dd5bb90..a667dce 100644
--- a/cc/test/render_pass_test_common.cc
+++ b/cc/test/render_pass_test_common.cc
@@ -58,8 +58,9 @@
       ResourceProvider::TextureHintImmutable,
       resource_provider->best_texture_format());
   resource_provider->AllocateForTesting(resource4);
+  gfx::Size resource5_size(73, 26);
   ResourceProvider::ResourceId resource5 = resource_provider->CreateResource(
-      gfx::Size(73, 26),
+      resource5_size,
       GL_CLAMP_TO_EDGE,
       ResourceProvider::TextureHintImmutable,
       resource_provider->best_texture_format());
@@ -124,7 +125,8 @@
                              visible_rect,
                              child_pass,
                              resource5,
-                             gfx::RectF(),
+                             gfx::Vector2dF(1.f, 1.f),
+                             resource5_size,
                              FilterOperations(),
                              gfx::Vector2dF(),
                              FilterOperations());
@@ -136,7 +138,8 @@
                                      visible_rect,
                                      child_pass,
                                      resource5,
-                                     gfx::RectF(),
+                                     gfx::Vector2dF(1.f, 1.f),
+                                     resource5_size,
                                      FilterOperations(),
                                      gfx::Vector2dF(),
                                      FilterOperations());
diff --git a/cc/test/render_pass_test_utils.cc b/cc/test/render_pass_test_utils.cc
index 1f21316..519c74a 100644
--- a/cc/test/render_pass_test_utils.cc
+++ b/cc/test/render_pass_test_utils.cc
@@ -100,7 +100,8 @@
                output_rect,
                contributing_pass->id,
                0,
-               gfx::RectF(),
+               gfx::Vector2dF(),
+               gfx::Size(),
                FilterOperations(),
                gfx::Vector2dF(),
                FilterOperations());
@@ -123,12 +124,14 @@
                        0);
   RenderPassDrawQuad* quad =
       to_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
+  gfx::Size arbitrary_nonzero_size(1, 1);
   quad->SetNew(shared_state,
                output_rect,
                output_rect,
                contributing_pass->id,
                mask_resource_id,
-               gfx::RectF(),
+               gfx::Vector2dF(1.f, 1.f),
+               arbitrary_nonzero_size,
                filters,
                gfx::Vector2dF(),
                FilterOperations());
diff --git a/cc/test/scheduler_test_common.cc b/cc/test/scheduler_test_common.cc
index 2aa896b..ef4cefd 100644
--- a/cc/test/scheduler_test_common.cc
+++ b/cc/test/scheduler_test_common.cc
@@ -127,14 +127,15 @@
     const SchedulerSettings& scheduler_settings,
     int layer_tree_host_id,
     const scoped_refptr<OrderedSimpleTaskRunner>& test_task_runner,
+    base::PowerMonitor* power_monitor,
     TestSchedulerFrameSourcesConstructor* frame_sources_constructor)
     : Scheduler(client,
                 scheduler_settings,
                 layer_tree_host_id,
                 test_task_runner,
+                power_monitor,
                 frame_sources_constructor),
-      now_src_(now_src),
-      test_task_runner_(test_task_runner.get()) {
+      now_src_(now_src) {
 }
 
 base::TimeTicks TestScheduler::Now() const {
diff --git a/cc/test/scheduler_test_common.h b/cc/test/scheduler_test_common.h
index 2cb878a..a91fd01 100644
--- a/cc/test/scheduler_test_common.h
+++ b/cc/test/scheduler_test_common.h
@@ -161,19 +161,17 @@
       scoped_refptr<TestNowSource> now_src,
       SchedulerClient* client,
       const SchedulerSettings& scheduler_settings,
-      int layer_tree_host_id) {
-    // A bunch of tests require Now() to be > BeginFrameArgs::DefaultInterval()
-    now_src->AdvanceNow(base::TimeDelta::FromMilliseconds(100));
-
-    scoped_refptr<OrderedSimpleTaskRunner> test_task_runner =
-        new OrderedSimpleTaskRunner(now_src, true);
+      int layer_tree_host_id,
+      const scoped_refptr<OrderedSimpleTaskRunner>& task_runner,
+      base::PowerMonitor* power_monitor) {
     TestSchedulerFrameSourcesConstructor frame_sources_constructor(
-        test_task_runner.get(), now_src.get());
+        task_runner.get(), now_src.get());
     return make_scoped_ptr(new TestScheduler(now_src,
                                              client,
                                              scheduler_settings,
                                              layer_tree_host_id,
-                                             test_task_runner,
+                                             task_runner,
+                                             power_monitor,
                                              &frame_sources_constructor));
   }
 
@@ -183,7 +181,6 @@
   }
 
   BeginFrameSource& frame_source() { return *frame_source_; }
-  OrderedSimpleTaskRunner& task_runner() { return *test_task_runner_; }
 
   virtual ~TestScheduler();
 
@@ -198,10 +195,10 @@
       const SchedulerSettings& scheduler_settings,
       int layer_tree_host_id,
       const scoped_refptr<OrderedSimpleTaskRunner>& test_task_runner,
+      base::PowerMonitor* power_monitor,
       TestSchedulerFrameSourcesConstructor* frame_sources_constructor);
 
   scoped_refptr<TestNowSource> now_src_;
-  OrderedSimpleTaskRunner* test_task_runner_;
 };
 
 }  // namespace cc
diff --git a/cc/trees/damage_tracker_unittest.cc b/cc/trees/damage_tracker_unittest.cc
index dffe90a..90b5b8a 100644
--- a/cc/trees/damage_tracker_unittest.cc
+++ b/cc/trees/damage_tracker_unittest.cc
@@ -1105,7 +1105,7 @@
   // CASE 3: removing the reflection should cause the entire region including
   //         reflection to damage the target surface.
   ClearDamageForAllSurfaces(root.get());
-  grand_child1->SetReplicaLayer(scoped_ptr<LayerImpl>());
+  grand_child1->SetReplicaLayer(nullptr);
   EmulateDrawingOneFrame(root.get());
   ASSERT_EQ(old_content_rect.width(),
             child1->render_surface()->content_rect().width());
@@ -1202,7 +1202,7 @@
 
   // Then test mask removal.
   ClearDamageForAllSurfaces(root.get());
-  child->SetMaskLayer(scoped_ptr<LayerImpl>());
+  child->SetMaskLayer(nullptr);
   ASSERT_TRUE(child->LayerPropertyChanged());
   EmulateDrawingOneFrame(root.get());
 
@@ -1270,7 +1270,7 @@
   //         target surface.
   //
   ClearDamageForAllSurfaces(root.get());
-  grand_child1_replica->SetMaskLayer(scoped_ptr<LayerImpl>());
+  grand_child1_replica->SetMaskLayer(nullptr);
   EmulateDrawingOneFrame(root.get());
 
   grand_child_damage_rect =
diff --git a/cc/trees/layer_tree_host_common.cc b/cc/trees/layer_tree_host_common.cc
index c7381b3..4e80fc6 100644
--- a/cc/trees/layer_tree_host_common.cc
+++ b/cc/trees/layer_tree_host_common.cc
@@ -242,7 +242,7 @@
 void UpdateAccumulatedSurfaceState(
     LayerType* layer,
     const gfx::Rect& drawable_content_rect,
-    std::vector<AccumulatedSurfaceState<LayerType> >*
+    std::vector<AccumulatedSurfaceState<LayerType>>*
         accumulated_surface_state) {
   if (IsRootLayer(layer))
     return;
@@ -284,7 +284,7 @@
   // We must have at least one entry in the vector for the root.
   DCHECK_LT(0ul, accumulated_surface_state->size());
 
-  typedef typename std::vector<AccumulatedSurfaceState<LayerType> >
+  typedef typename std::vector<AccumulatedSurfaceState<LayerType>>
       AccumulatedSurfaceStateVector;
   typedef typename AccumulatedSurfaceStateVector::reverse_iterator
       AccumulatedSurfaceStateIterator;
@@ -1451,7 +1451,7 @@
     const DataForRecursion<LayerType>& data_from_ancestor,
     typename LayerType::RenderSurfaceListType* render_surface_layer_list,
     typename LayerType::LayerListType* layer_list,
-    std::vector<AccumulatedSurfaceState<LayerType> >* accumulated_surface_state,
+    std::vector<AccumulatedSurfaceState<LayerType>>* accumulated_surface_state,
     int current_render_surface_layer_list_id) {
   // This function computes the new matrix transformations recursively for this
   // layer and all its descendants. It also computes the appropriate render
@@ -2398,7 +2398,7 @@
 
   PreCalculateMetaInformationRecursiveData recursive_data;
   PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
-  std::vector<AccumulatedSurfaceState<Layer> > accumulated_surface_state;
+  std::vector<AccumulatedSurfaceState<Layer>> accumulated_surface_state;
   CalculateDrawPropertiesInternal<Layer>(
       inputs->root_layer,
       globals,
@@ -2427,8 +2427,7 @@
 
   PreCalculateMetaInformationRecursiveData recursive_data;
   PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
-  std::vector<AccumulatedSurfaceState<LayerImpl> >
-      accumulated_surface_state;
+  std::vector<AccumulatedSurfaceState<LayerImpl>> accumulated_surface_state;
   CalculateDrawPropertiesInternal<LayerImpl>(
       inputs->root_layer,
       globals,
diff --git a/cc/trees/layer_tree_host_common_unittest.cc b/cc/trees/layer_tree_host_common_unittest.cc
index 17dd4a8..83e6800 100644
--- a/cc/trees/layer_tree_host_common_unittest.cc
+++ b/cc/trees/layer_tree_host_common_unittest.cc
@@ -4,6 +4,7 @@
 
 #include "cc/trees/layer_tree_host_common.h"
 
+#include <algorithm>
 #include <set>
 
 #include "cc/animation/layer_animation_controller.h"
@@ -7505,7 +7506,7 @@
   scroll_parent_clip->SetMasksToBounds(true);
 
   scroll_child->SetScrollParent(scroll_parent.get());
-  scoped_ptr<std::set<LayerImpl*> > scroll_children(new std::set<LayerImpl*>);
+  scoped_ptr<std::set<LayerImpl*>> scroll_children(new std::set<LayerImpl*>);
   scroll_children->insert(scroll_child.get());
   scroll_parent->SetScrollChildren(scroll_children.release());
 
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc
index c5b9566..6380647 100644
--- a/cc/trees/layer_tree_host_impl.cc
+++ b/cc/trees/layer_tree_host_impl.cc
@@ -1307,6 +1307,7 @@
 
 void LayerTreeHostImpl::BuildRasterQueue(RasterTilePriorityQueue* queue,
                                          TreePriority tree_priority) {
+  TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildRasterQueue");
   picture_layer_pairs_.clear();
   GetPictureLayerImplPairs(&picture_layer_pairs_);
   queue->Build(picture_layer_pairs_, tree_priority);
@@ -1314,6 +1315,7 @@
 
 void LayerTreeHostImpl::BuildEvictionQueue(EvictionTilePriorityQueue* queue,
                                            TreePriority tree_priority) {
+  TRACE_EVENT0("cc", "LayerTreeHostImpl::BuildEvictionQueue");
   picture_layer_pairs_.clear();
   GetPictureLayerImplPairs(&picture_layer_pairs_);
   queue->Build(picture_layer_pairs_, tree_priority);
diff --git a/cc/trees/layer_tree_host_impl_unittest.cc b/cc/trees/layer_tree_host_impl_unittest.cc
index 19bc9c9..a7f902c 100644
--- a/cc/trees/layer_tree_host_impl_unittest.cc
+++ b/cc/trees/layer_tree_host_impl_unittest.cc
@@ -26,6 +26,7 @@
 #include "cc/layers/solid_color_scrollbar_layer_impl.h"
 #include "cc/layers/texture_layer_impl.h"
 #include "cc/layers/tiled_layer_impl.h"
+#include "cc/layers/video_layer_impl.h"
 #include "cc/output/begin_frame_args.h"
 #include "cc/output/compositor_frame_ack.h"
 #include "cc/output/compositor_frame_metadata.h"
@@ -46,6 +47,7 @@
 #include "cc/test/fake_picture_pile_impl.h"
 #include "cc/test/fake_proxy.h"
 #include "cc/test/fake_rendering_stats_instrumentation.h"
+#include "cc/test/fake_video_frame_provider.h"
 #include "cc/test/geometry_test_utils.h"
 #include "cc/test/layer_test_common.h"
 #include "cc/test/render_pass_test_common.h"
@@ -54,6 +56,7 @@
 #include "cc/test/test_web_graphics_context_3d.h"
 #include "cc/trees/layer_tree_impl.h"
 #include "cc/trees/single_thread_proxy.h"
+#include "media/base/media.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 #include "third_party/skia/include/core/SkMallocPixelRef.h"
@@ -67,6 +70,7 @@
 using ::testing::AnyNumber;
 using ::testing::AtLeast;
 using ::testing::_;
+using media::VideoFrame;
 
 namespace cc {
 namespace {
@@ -91,6 +95,7 @@
         reduce_memory_result_(true),
         current_limit_bytes_(0),
         current_priority_cutoff_value_(0) {
+    media::InitializeMediaLibraryForTesting();
   }
 
   LayerTreeSettings DefaultSettings() {
@@ -322,7 +327,7 @@
     on_can_draw_state_changed_called_ = false;
 
     // Toggle the root layer to make sure it toggles can_draw
-    host_impl_->active_tree()->SetRootLayer(scoped_ptr<LayerImpl>());
+    host_impl_->active_tree()->SetRootLayer(nullptr);
     EXPECT_FALSE(host_impl_->CanDraw());
     EXPECT_TRUE(on_can_draw_state_changed_called_);
     on_can_draw_state_changed_called_ = false;
@@ -5070,6 +5075,18 @@
       LayerImpl::Create(host_impl_->active_tree(), 1);
   root_layer->SetBounds(gfx::Size(10, 10));
 
+  scoped_refptr<VideoFrame> softwareFrame =
+      media::VideoFrame::CreateColorFrame(
+          gfx::Size(4, 4), 0x80, 0x80, 0x80, base::TimeDelta());
+  FakeVideoFrameProvider provider;
+  provider.set_frame(softwareFrame);
+  scoped_ptr<VideoLayerImpl> video_layer = VideoLayerImpl::Create(
+      host_impl_->active_tree(), 4, &provider, media::VIDEO_ROTATION_0);
+  video_layer->SetBounds(gfx::Size(10, 10));
+  video_layer->SetContentBounds(gfx::Size(10, 10));
+  video_layer->SetDrawsContent(true);
+  root_layer->AddChild(video_layer.Pass());
+
   scoped_ptr<IOSurfaceLayerImpl> io_surface_layer =
       IOSurfaceLayerImpl::Create(host_impl_->active_tree(), 5);
   io_surface_layer->SetBounds(gfx::Size(10, 10));
@@ -5273,8 +5290,9 @@
     return make_scoped_ptr(new FakeMaskLayerImpl(tree_impl, id));
   }
 
-  virtual ResourceProvider::ResourceId ContentsResourceId() const override {
-    return 0;
+  virtual void GetContentsResourceId(ResourceProvider::ResourceId* resource_id,
+                                     gfx::Size* resource_size) const override {
+    *resource_id = 0;
   }
 
  private:
@@ -5356,7 +5374,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5385,7 +5405,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 200, 200).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5416,7 +5438,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 200, 200).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5477,7 +5501,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 50, 50).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5505,7 +5531,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5536,7 +5564,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5562,7 +5592,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               render_pass_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5627,7 +5659,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 50, 50).ToString(),
               replica_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              replica_quad->mask_uv_rect.ToString());
+              replica_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              replica_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5654,7 +5688,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               replica_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              replica_quad->mask_uv_rect.ToString());
+              replica_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              replica_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5684,7 +5720,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               replica_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              replica_quad->mask_uv_rect.ToString());
+              replica_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              replica_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5709,7 +5747,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(),
               replica_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 1.f, 1.f).ToString(),
-              replica_quad->mask_uv_rect.ToString());
+              replica_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(1.f, 1.f).ToString(),
+              replica_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5795,7 +5835,9 @@
     EXPECT_EQ(gfx::Rect(0, 0, 100, 50).ToString(),
               replica_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(0.f, 0.f, 2.f, 1.f).ToString(),
-              replica_quad->mask_uv_rect.ToString());
+              replica_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(2.f, 1.f).ToString(),
+              replica_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5828,7 +5870,9 @@
     EXPECT_EQ(gfx::Rect(-50, 0, 100, 50).ToString(),
               replica_quad->rect.ToString());
     EXPECT_EQ(gfx::RectF(-1.f, 0.f, 2.f, 1.f).ToString(),
-              replica_quad->mask_uv_rect.ToString());
+              replica_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(2.f, 1.f).ToString(),
+              replica_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -5912,14 +5956,15 @@
             frame.render_passes[0]->quad_list.front());
     EXPECT_EQ(gfx::Rect(20, 10, 10, 20).ToString(),
               render_pass_quad->rect.ToString());
-
     // The masked layer is 50x50, but the surface size is 10x20. So the texture
     // coords in the mask are scaled by 10/50 and 20/50.
     // The surface is clipped to (20,10) so the mask texture coords are offset
     // by 20/50 and 10/50
-    EXPECT_EQ(gfx::ScaleRect(gfx::RectF(20.f, 10.f, 10.f, 20.f),
-                             1.f / 50.f).ToString(),
-              render_pass_quad->mask_uv_rect.ToString());
+    EXPECT_EQ(gfx::ScaleRect(gfx::RectF(20.f, 10.f, 10.f, 20.f), 1.f / 50.f)
+                  .ToString(),
+              render_pass_quad->MaskUVRect().ToString());
+    EXPECT_EQ(gfx::Vector2dF(10.f / 50.f, 20.f / 50.f).ToString(),
+              render_pass_quad->mask_uv_scale.ToString());
 
     host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
     host_impl_->DidDrawAllLayers(frame);
@@ -6105,6 +6150,16 @@
   scoped_ptr<SolidColorLayerImpl> root_layer =
       SolidColorLayerImpl::Create(host_impl_->active_tree(), 1);
 
+  // VideoLayerImpl will not be drawn.
+  FakeVideoFrameProvider provider;
+  scoped_ptr<VideoLayerImpl> video_layer = VideoLayerImpl::Create(
+      host_impl_->active_tree(), 2, &provider, media::VIDEO_ROTATION_0);
+  video_layer->SetBounds(gfx::Size(10, 10));
+  video_layer->SetContentBounds(gfx::Size(10, 10));
+  video_layer->SetDrawsContent(true);
+  root_layer->AddChild(video_layer.Pass());
+  SetupRootLayerImpl(root_layer.Pass());
+
   LayerTreeHostImpl::FrameData frame;
   EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(&frame));
   host_impl_->DrawLayers(&frame, gfx::FrameTime::Now());
@@ -6722,7 +6777,7 @@
   scoped_ptr<LayerImpl> container =
       LayerImpl::Create(host_impl_->active_tree(), container_id);
 
-  scoped_ptr<std::set<LayerImpl*> > scroll_children(new std::set<LayerImpl*>());
+  scoped_ptr<std::set<LayerImpl*>> scroll_children(new std::set<LayerImpl*>);
   scroll_children->insert(scroll_child.get());
   invisible_scroll->SetScrollChildren(scroll_children.release());
 
diff --git a/cc/trees/layer_tree_host_perftest.cc b/cc/trees/layer_tree_host_perftest.cc
index a516a50..47d7789 100644
--- a/cc/trees/layer_tree_host_perftest.cc
+++ b/cc/trees/layer_tree_host_perftest.cc
@@ -305,8 +305,7 @@
   }
 
   void CleanUpAndEndTestOnMainThread() {
-    tab_contents_->SetTextureMailbox(TextureMailbox(),
-                                     scoped_ptr<SingleReleaseCallback>());
+    tab_contents_->SetTextureMailbox(TextureMailbox(), nullptr);
     EndTest();
   }
 
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc
index 28dcfa3..c5dbe0d 100644
--- a/cc/trees/layer_tree_host_unittest.cc
+++ b/cc/trees/layer_tree_host_unittest.cc
@@ -18,6 +18,7 @@
 #include "cc/layers/painted_scrollbar_layer.h"
 #include "cc/layers/picture_layer.h"
 #include "cc/layers/solid_color_layer.h"
+#include "cc/layers/video_layer.h"
 #include "cc/output/begin_frame_args.h"
 #include "cc/output/compositor_frame_ack.h"
 #include "cc/output/copy_output_request.h"
@@ -38,6 +39,7 @@
 #include "cc/test/fake_picture_layer_impl.h"
 #include "cc/test/fake_proxy.h"
 #include "cc/test/fake_scoped_ui_resource.h"
+#include "cc/test/fake_video_frame_provider.h"
 #include "cc/test/geometry_test_utils.h"
 #include "cc/test/layer_tree_test.h"
 #include "cc/test/test_shared_bitmap_manager.h"
@@ -3385,7 +3387,7 @@
         // avoid causing a second commit to be scheduled. If a property change
         // is made during this, however, it needs to be pushed in the upcoming
         // commit.
-        scoped_ptr<base::AutoReset<bool> > ignore =
+        scoped_ptr<base::AutoReset<bool>> ignore =
             scrollbar_layer_->IgnoreSetNeedsCommit();
 
         scrollbar_layer_->SetBounds(gfx::Size(30, 30));
@@ -3985,6 +3987,28 @@
   int num_draws_;
 };
 
+// VideoLayer must support being invalidated and then passing that along
+// to the compositor thread, even though no resources are updated in
+// response to that invalidation.
+class LayerTreeHostTestVideoLayerInvalidate : public LayerInvalidateCausesDraw {
+ public:
+  virtual void SetupTree() override {
+    LayerTreeHostTest::SetupTree();
+    scoped_refptr<VideoLayer> video_layer =
+        VideoLayer::Create(&provider_, media::VIDEO_ROTATION_0);
+    video_layer->SetBounds(gfx::Size(10, 10));
+    video_layer->SetIsDrawable(true);
+    layer_tree_host()->root_layer()->AddChild(video_layer);
+
+    invalidate_layer_ = video_layer;
+  }
+
+ private:
+  FakeVideoFrameProvider provider_;
+};
+
+SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostTestVideoLayerInvalidate);
+
 // IOSurfaceLayer must support being invalidated and then passing that along
 // to the compositor thread, even though no resources are updated in
 // response to that invalidation.
diff --git a/cc/trees/layer_tree_host_unittest_animation.cc b/cc/trees/layer_tree_host_unittest_animation.cc
index 3bd55e5..f3bbe0a 100644
--- a/cc/trees/layer_tree_host_unittest_animation.cc
+++ b/cc/trees/layer_tree_host_unittest_animation.cc
@@ -146,9 +146,9 @@
     }
   }
 
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override {
     received_animation_started_notification_ = true;
     start_time_ = monotonic_time;
     if (num_begin_frames_) {
@@ -241,7 +241,8 @@
 
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+      Animation::TargetProperty target_property,
+      int group) override {
     // Animations on the impl-side controller only get deleted during a commit,
     // so we need to schedule a commit.
     layer_tree_host()->SetNeedsCommit();
@@ -368,7 +369,8 @@
 
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+      Animation::TargetProperty target_property,
+      int group) override {
     // Replace animated commits with an empty tree.
     layer_tree_host()->SetRootLayer(make_scoped_refptr<Layer>(NULL));
   }
@@ -560,9 +562,9 @@
     PostAddAnimationToMainThread(content_.get());
   }
 
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override {
     LayerAnimationController* controller =
         layer_tree_host()->root_layer()->children()[0]->
         layer_animation_controller();
@@ -621,7 +623,8 @@
 
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+      Animation::TargetProperty target_property,
+      int group) override {
     LayerAnimationController* controller =
         layer_tree_host()->root_layer()->layer_animation_controller();
     Animation* animation =
@@ -858,15 +861,16 @@
     PostAddAnimationToMainThread(content_.get());
   }
 
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override {
     started_times_++;
   }
 
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+      Animation::TargetProperty target_property,
+      int group) override {
     EndTest();
   }
 
@@ -908,16 +912,17 @@
     layer_tree_host()->SetVisible(false);
   }
 
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override {
     EXPECT_FALSE(visible_);
     started_times_++;
   }
 
   virtual void NotifyAnimationFinished(
       base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+      Animation::TargetProperty target_property,
+      int group) override {
     EXPECT_FALSE(visible_);
     EXPECT_EQ(1, started_times_);
     EndTest();
@@ -991,9 +996,9 @@
     }
   }
 
-  virtual void NotifyAnimationStarted(
-      base::TimeTicks monotonic_time,
-      Animation::TargetProperty target_property) override {
+  virtual void NotifyAnimationStarted(base::TimeTicks monotonic_time,
+                                      Animation::TargetProperty target_property,
+                                      int group) override {
     if (TestEnded())
       return;
     started_times_++;
diff --git a/cc/trees/layer_tree_host_unittest_context.cc b/cc/trees/layer_tree_host_unittest_context.cc
index 687d7cf..a72b12e 100644
--- a/cc/trees/layer_tree_host_unittest_context.cc
+++ b/cc/trees/layer_tree_host_unittest_context.cc
@@ -15,6 +15,8 @@
 #include "cc/layers/picture_layer.h"
 #include "cc/layers/texture_layer.h"
 #include "cc/layers/texture_layer_impl.h"
+#include "cc/layers/video_layer.h"
+#include "cc/layers/video_layer_impl.h"
 #include "cc/output/filter_operations.h"
 #include "cc/resources/single_release_callback.h"
 #include "cc/test/fake_content_layer.h"
@@ -30,6 +32,7 @@
 #include "cc/test/fake_picture_layer_impl.h"
 #include "cc/test/fake_scoped_ui_resource.h"
 #include "cc/test/fake_scrollbar.h"
+#include "cc/test/fake_video_frame_provider.h"
 #include "cc/test/layer_tree_test.h"
 #include "cc/test/render_pass_test_common.h"
 #include "cc/test/test_context_provider.h"
@@ -39,6 +42,9 @@
 #include "cc/trees/layer_tree_impl.h"
 #include "cc/trees/single_thread_proxy.h"
 #include "gpu/GLES2/gl2extchromium.h"
+#include "media/base/media.h"
+
+using media::VideoFrame;
 
 namespace cc {
 namespace {
@@ -59,6 +65,7 @@
         context_should_support_io_surface_(false),
         fallback_context_works_(false),
         async_output_surface_creation_(false) {
+    media::InitializeMediaLibraryForTesting();
   }
 
   void LoseContext() {
@@ -1019,6 +1026,49 @@
     layer_with_mask->SetMaskLayer(mask.get());
     root->AddChild(layer_with_mask);
 
+    scoped_refptr<VideoLayer> video_color =
+        VideoLayer::Create(&color_frame_provider_, media::VIDEO_ROTATION_0);
+    video_color->SetBounds(gfx::Size(10, 10));
+    video_color->SetIsDrawable(true);
+    root->AddChild(video_color);
+
+    scoped_refptr<VideoLayer> video_hw =
+        VideoLayer::Create(&hw_frame_provider_, media::VIDEO_ROTATION_0);
+    video_hw->SetBounds(gfx::Size(10, 10));
+    video_hw->SetIsDrawable(true);
+    root->AddChild(video_hw);
+
+    scoped_refptr<VideoLayer> video_scaled_hw =
+        VideoLayer::Create(&scaled_hw_frame_provider_, media::VIDEO_ROTATION_0);
+    video_scaled_hw->SetBounds(gfx::Size(10, 10));
+    video_scaled_hw->SetIsDrawable(true);
+    root->AddChild(video_scaled_hw);
+
+    color_video_frame_ = VideoFrame::CreateColorFrame(
+        gfx::Size(4, 4), 0x80, 0x80, 0x80, base::TimeDelta());
+    hw_video_frame_ =
+        VideoFrame::WrapNativeTexture(make_scoped_ptr(new gpu::MailboxHolder(
+                                          mailbox, GL_TEXTURE_2D, sync_point)),
+                                      media::VideoFrame::ReleaseMailboxCB(),
+                                      gfx::Size(4, 4),
+                                      gfx::Rect(0, 0, 4, 4),
+                                      gfx::Size(4, 4),
+                                      base::TimeDelta(),
+                                      VideoFrame::ReadPixelsCB());
+    scaled_hw_video_frame_ =
+        VideoFrame::WrapNativeTexture(make_scoped_ptr(new gpu::MailboxHolder(
+                                          mailbox, GL_TEXTURE_2D, sync_point)),
+                                      media::VideoFrame::ReleaseMailboxCB(),
+                                      gfx::Size(4, 4),
+                                      gfx::Rect(0, 0, 3, 2),
+                                      gfx::Size(4, 4),
+                                      base::TimeDelta(),
+                                      VideoFrame::ReadPixelsCB());
+
+    color_frame_provider_.set_frame(color_video_frame_);
+    hw_frame_provider_.set_frame(hw_video_frame_);
+    scaled_hw_frame_provider_.set_frame(scaled_hw_video_frame_);
+
     if (!delegating_renderer()) {
       // TODO(danakj): IOSurface layer can not be transported. crbug.com/239335
       scoped_refptr<IOSurfaceLayer> io_surface = IOSurfaceLayer::Create();
@@ -1048,6 +1098,14 @@
 
   virtual void CommitCompleteOnThread(LayerTreeHostImpl* host_impl) override {
     LayerTreeHostContextTest::CommitCompleteOnThread(host_impl);
+
+    if (host_impl->active_tree()->source_frame_number() == 3) {
+      // On the third commit we're recovering from context loss. Hardware
+      // video frames should not be reused by the VideoFrameProvider, but
+      // software frames can be.
+      hw_frame_provider_.set_frame(NULL);
+      scaled_hw_frame_provider_.set_frame(NULL);
+    }
   }
 
   virtual DrawResult PrepareToDrawOnThread(
@@ -1098,6 +1156,14 @@
   scoped_refptr<DelegatedFrameResourceCollection>
       delegated_resource_collection_;
   scoped_refptr<DelegatedFrameProvider> delegated_frame_provider_;
+
+  scoped_refptr<VideoFrame> color_video_frame_;
+  scoped_refptr<VideoFrame> hw_video_frame_;
+  scoped_refptr<VideoFrame> scaled_hw_video_frame_;
+
+  FakeVideoFrameProvider color_frame_provider_;
+  FakeVideoFrameProvider hw_frame_provider_;
+  FakeVideoFrameProvider scaled_hw_frame_provider_;
 };
 
 SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostContextTestDontUseLostResources);
diff --git a/cc/trees/layer_tree_host_unittest_delegated.cc b/cc/trees/layer_tree_host_unittest_delegated.cc
index 095513b..018df87 100644
--- a/cc/trees/layer_tree_host_unittest_delegated.cc
+++ b/cc/trees/layer_tree_host_unittest_delegated.cc
@@ -190,8 +190,9 @@
                  output_rect,
                  output_rect,
                  id,
-                 0,      // mask_resource_id
-                 gfx::Rect(0, 0, 1, 1),  // mask_uv_rect
+                 0,
+                 gfx::Vector2dF(),
+                 gfx::Size(),
                  filters,
                  gfx::Vector2dF(),
                  background_filters);
diff --git a/cc/trees/layer_tree_host_unittest_occlusion.cc b/cc/trees/layer_tree_host_unittest_occlusion.cc
index 943299d..3e22f04 100644
--- a/cc/trees/layer_tree_host_unittest_occlusion.cc
+++ b/cc/trees/layer_tree_host_unittest_occlusion.cc
@@ -584,7 +584,7 @@
   virtual void SetupTree() override {
     // We create enough RenderSurfaces that it will trigger Vector reallocation
     // while computing occlusion.
-    std::vector<scoped_refptr<TestLayer> > layers;
+    std::vector<scoped_refptr<TestLayer>> layers;
     int num_surfaces = 200;
     int root_width = 400;
     int root_height = 400;
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc
index 3316855..5fc01fc 100644
--- a/cc/trees/layer_tree_impl.cc
+++ b/cc/trees/layer_tree_impl.cc
@@ -510,7 +510,7 @@
                  IsActiveTree(),
                  "SourceFrameNumber",
                  source_frame_number_);
-    scoped_ptr<OcclusionTracker<LayerImpl> > occlusion_tracker;
+    scoped_ptr<OcclusionTracker<LayerImpl>> occlusion_tracker;
     if (settings().use_occlusion_for_tile_prioritization) {
       occlusion_tracker.reset(new OcclusionTracker<LayerImpl>(
           root_layer()->render_surface()->content_rect()));
diff --git a/cc/trees/layer_tree_settings.cc b/cc/trees/layer_tree_settings.cc
index a304cba..6e2fcec 100644
--- a/cc/trees/layer_tree_settings.cc
+++ b/cc/trees/layer_tree_settings.cc
@@ -20,6 +20,7 @@
       begin_frame_scheduling_enabled(false),
       main_frame_before_activation_enabled(false),
       using_synchronous_renderer_compositor(false),
+      disable_hi_res_timer_tasks_on_battery(false),
       report_overscroll_only_for_scrollable_axes(false),
       per_tile_painting_enabled(false),
       partial_swap_enabled(false),
diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h
index cd3eb42..6646120 100644
--- a/cc/trees/layer_tree_settings.h
+++ b/cc/trees/layer_tree_settings.h
@@ -25,6 +25,7 @@
   bool begin_frame_scheduling_enabled;
   bool main_frame_before_activation_enabled;
   bool using_synchronous_renderer_compositor;
+  bool disable_hi_res_timer_tasks_on_battery;
   bool report_overscroll_only_for_scrollable_axes;
   bool per_tile_painting_enabled;
   bool partial_swap_enabled;
diff --git a/cc/trees/single_thread_proxy.cc b/cc/trees/single_thread_proxy.cc
index 1b57b35..1e422ca 100644
--- a/cc/trees/single_thread_proxy.cc
+++ b/cc/trees/single_thread_proxy.cc
@@ -86,7 +86,8 @@
     scheduler_on_impl_thread_ = Scheduler::Create(this,
                                                   scheduler_settings,
                                                   layer_tree_host_->id(),
-                                                  MainThreadTaskRunner());
+                                                  MainThreadTaskRunner(),
+                                                  base::PowerMonitor::Get());
     scheduler_on_impl_thread_->SetCanStart();
     scheduler_on_impl_thread_->SetVisible(layer_tree_host_impl_->visible());
   }
diff --git a/cc/trees/thread_proxy.cc b/cc/trees/thread_proxy.cc
index 34283c9..24286e1 100644
--- a/cc/trees/thread_proxy.cc
+++ b/cc/trees/thread_proxy.cc
@@ -1183,7 +1183,8 @@
   impl().scheduler = Scheduler::Create(this,
                                        scheduler_settings,
                                        impl().layer_tree_host_id,
-                                       ImplThreadTaskRunner());
+                                       ImplThreadTaskRunner(),
+                                       base::PowerMonitor::Get());
   impl().scheduler->SetVisible(impl().layer_tree_host_impl->visible());
 
   impl_thread_weak_ptr_ = impl().weak_factory.GetWeakPtr();
diff --git a/cc/trees/tree_synchronizer_unittest.cc b/cc/trees/tree_synchronizer_unittest.cc
index fbb19be..2b8f5df 100644
--- a/cc/trees/tree_synchronizer_unittest.cc
+++ b/cc/trees/tree_synchronizer_unittest.cc
@@ -202,9 +202,8 @@
 // return a null tree.
 TEST_F(TreeSynchronizerTest, SyncNullTree) {
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(static_cast<Layer*>(NULL),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          static_cast<Layer*>(NULL), nullptr, host_->active_tree());
 
   EXPECT_TRUE(!layer_impl_tree_root.get());
 }
@@ -219,9 +218,8 @@
   host_->SetRootLayer(layer_tree_root);
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
 
   ExpectTreesAreIdentical(layer_tree_root.get(),
                           layer_impl_tree_root.get(),
@@ -241,9 +239,8 @@
   host_->SetRootLayer(layer_tree_root);
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
   ExpectTreesAreIdentical(layer_tree_root.get(),
                           layer_impl_tree_root.get(),
                           host_->active_tree());
@@ -289,9 +286,8 @@
   host_->SetRootLayer(layer_tree_root);
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
   ExpectTreesAreIdentical(layer_tree_root.get(),
                           layer_impl_tree_root.get(),
                           host_->active_tree());
@@ -342,9 +338,8 @@
   layer_tree_root->children()[1]->SavePaintProperties();
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
   ExpectTreesAreIdentical(layer_tree_root.get(),
                           layer_impl_tree_root.get(),
                           host_->active_tree());
@@ -393,9 +388,8 @@
   host_->SetRootLayer(layer_tree_root);
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
   ExpectTreesAreIdentical(layer_tree_root.get(),
                           layer_impl_tree_root.get(),
                           host_->active_tree());
@@ -450,9 +444,8 @@
   int old_tree_second_child_layer_id = old_layer_tree_root->children()[1]->id();
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(old_layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          old_layer_tree_root.get(), nullptr, host_->active_tree());
   ExpectTreesAreIdentical(old_layer_tree_root.get(),
                           layer_impl_tree_root.get(),
                           host_->active_tree());
@@ -517,9 +510,8 @@
   host_->SetRootLayer(layer_tree_root);
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
 
   ExpectTreesAreIdentical(layer_tree_root.get(),
                           layer_impl_tree_root.get(),
@@ -582,9 +574,8 @@
       layer_tree_root->layer_animation_controller())->SynchronizedAnimations());
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_->active_tree());
   TreeSynchronizer::PushProperties(layer_tree_root.get(),
                                    layer_impl_tree_root.get());
   layer_impl_tree_root =
@@ -625,9 +616,8 @@
   layer_tree_root->children()[2]->SetScrollParent(scroll_parent.get());
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_impl->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_impl->active_tree());
   TreeSynchronizer::PushProperties(layer_tree_root.get(),
                                    layer_impl_tree_root.get());
   {
@@ -703,9 +693,8 @@
   clip_child2->SetClipParent(clip_parent.get());
 
   scoped_ptr<LayerImpl> layer_impl_tree_root =
-      TreeSynchronizer::SynchronizeTrees(layer_tree_root.get(),
-                                         scoped_ptr<LayerImpl>(),
-                                         host_impl->active_tree());
+      TreeSynchronizer::SynchronizeTrees(
+          layer_tree_root.get(), nullptr, host_impl->active_tree());
   TreeSynchronizer::PushProperties(layer_tree_root.get(),
                                    layer_impl_tree_root.get());
   ExpectTreesAreIdentical(layer_tree_root.get(),
diff --git a/gin/test/expect.js b/gin/test/expect.js
index b5e0f21..597b5b1 100644
--- a/gin/test/expect.js
+++ b/gin/test/expect.js
@@ -82,7 +82,7 @@
     aStack.push(a);
     bStack.push(b);
     var size = 0, result = true;
-    // Recursively compare objects and arrays.
+    // Recursively compare Maps, objects and arrays.
     if (className == '[object Array]' || isArrayBufferClass(className)) {
       // Compare array lengths to determine if a deep comparison is necessary.
       size = a.length;
@@ -94,6 +94,16 @@
             break;
         }
       }
+    } else if (className == '[object Map]') {
+      result = a.size == b.size;
+      if (result) {
+        var entries = a.entries();
+        for (var e = entries.next(); result && !e.done; e = entries.next()) {
+          var key = e.value[0];
+          var value = e.value[1];
+          result = b.has(key) && eq(value, b.get(key), aStack, bStack);
+        }
+      }
     } else {
       // Deep compare objects.
       for (var key in a) {
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn
index b77dfca..8239940 100644
--- a/gpu/BUILD.gn
+++ b/gpu/BUILD.gn
@@ -43,6 +43,7 @@
     "//gpu/command_buffer/common",
     "//gpu/command_buffer/service",
     "//gpu/config",
+    "//gpu/ipc",
   ]
 }
 
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc
index 20c4da8..f52c10e 100644
--- a/gpu/command_buffer/service/gles2_cmd_decoder.cc
+++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -1571,6 +1571,7 @@
       error::Error* error, GLint* real_location, GLuint* service_id,
       void** result, GLenum* result_type);
 
+  void MaybeExitOnContextLost();
   virtual bool WasContextLost() override;
   virtual bool WasContextLostByRobustnessExtension() override;
   virtual void LoseContext(uint32 reset_status) override;
@@ -3051,16 +3052,7 @@
   if (!context_->MakeCurrent(surface_.get()) || WasContextLost()) {
     LOG(ERROR) << "  GLES2DecoderImpl: Context lost during MakeCurrent.";
 
-    // Some D3D drivers cannot recover from device lost in the GPU process
-    // sandbox. Allow a new GPU process to launch.
-    if (workarounds().exit_on_context_lost) {
-      LOG(ERROR) << "Exiting GPU process because some drivers cannot reset"
-                 << " a D3D device in the Chrome GPU process sandbox.";
-#if defined(OS_WIN)
-      base::win::SetShouldCrashOnProcessDetach(false);
-#endif
-      exit(0);
-    }
+    MaybeExitOnContextLost();
 
     return false;
   }
@@ -4366,6 +4358,7 @@
     translated_attachments[i] = attachment;
   }
 
+  ScopedRenderTo do_render(framebuffer);
   glDiscardFramebufferEXT(target, numAttachments, translated_attachments.get());
 }
 
@@ -5007,6 +5000,7 @@
   DCHECK(!ShouldDeferDraws());
   if (CheckBoundFramebuffersValid("glClear")) {
     ApplyDirtyState();
+    ScopedRenderTo do_render(framebuffer_state_.bound_draw_framebuffer.get());
     glClear(mask);
   }
   return error::kNoError;
@@ -5308,6 +5302,7 @@
   }
 
   state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
+  ScopedRenderTo do_render(framebuffer_state_.bound_draw_framebuffer.get());
   BlitFramebufferHelper(
       srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
   state_.SetDeviceCapabilityState(GL_SCISSOR_TEST,
@@ -9660,8 +9655,22 @@
   return error::kUnknown;
 }
 
+void GLES2DecoderImpl::MaybeExitOnContextLost() {
+  // Some D3D drivers cannot recover from device lost in the GPU process
+  // sandbox. Allow a new GPU process to launch.
+  if (workarounds().exit_on_context_lost) {
+    LOG(ERROR) << "Exiting GPU process because some drivers cannot reset"
+               << " a D3D device in the Chrome GPU process sandbox.";
+#if defined(OS_WIN)
+    base::win::SetShouldCrashOnProcessDetach(false);
+#endif
+    exit(0);
+  }
+}
+
 bool GLES2DecoderImpl::WasContextLost() {
   if (reset_status_ != GL_NO_ERROR) {
+    MaybeExitOnContextLost();
     return true;
   }
   if (context_->WasAllocatedUsingRobustnessExtension()) {
@@ -9675,6 +9684,7 @@
       LOG(ERROR) << (surface_->IsOffscreen() ? "Offscreen" : "Onscreen")
                  << " context lost via ARB/EXT_robustness. Reset status = "
                  << GLES2Util::GetStringEnum(status);
+      MaybeExitOnContextLost();
       return true;
     }
   }
diff --git a/gpu/command_buffer/service/in_process_command_buffer.cc b/gpu/command_buffer/service/in_process_command_buffer.cc
index 1d0ce6a..310fced 100644
--- a/gpu/command_buffer/service/in_process_command_buffer.cc
+++ b/gpu/command_buffer/service/in_process_command_buffer.cc
@@ -747,7 +747,9 @@
 
 void PostCallback(const scoped_refptr<base::MessageLoopProxy>& loop,
                          const base::Closure& callback) {
-  if (!loop->BelongsToCurrentThread()) {
+  // The loop.get() check is to support using InProcessCommandBuffer on a thread
+  // without a message loop.
+  if (loop.get() && !loop->BelongsToCurrentThread()) {
     loop->PostTask(FROM_HERE, callback);
   } else {
     callback.Run();
diff --git a/gpu/config/gpu_info.cc b/gpu/config/gpu_info.cc
index f560dcb..c7951f9 100644
--- a/gpu/config/gpu_info.cc
+++ b/gpu/config/gpu_info.cc
@@ -17,6 +17,19 @@
   enumerator->EndGPUDevice();
 }
 
+void EnumerateVideoEncodeAcceleratorSupportedProfile(
+    gpu::GPUInfo::Enumerator* enumerator,
+    const media::VideoEncodeAccelerator::SupportedProfile profile) {
+  enumerator->BeginVideoEncodeAcceleratorSupportedProfile();
+  enumerator->AddInt("profile", profile.profile);
+  enumerator->AddInt("maxResolutionWidth", profile.max_resolution.width());
+  enumerator->AddInt("maxResolutionHeight", profile.max_resolution.height());
+  enumerator->AddInt("maxFramerateNumerator", profile.max_framerate_numerator);
+  enumerator->AddInt("maxFramerateDenominator",
+                     profile.max_framerate_denominator);
+  enumerator->EndVideoEncodeAcceleratorSupportedProfile();
+}
+
 }  // namespace
 
 namespace gpu {
@@ -88,6 +101,8 @@
     CollectInfoResult dx_diagnostics_info_state;
     DxDiagNode dx_diagnostics;
 #endif
+    std::vector<media::VideoEncodeAccelerator::SupportedProfile>
+        video_encode_accelerator_supported_profiles;
   };
 
   // If this assert fails then most likely something below needs to be updated.
@@ -142,6 +157,12 @@
 #if defined(OS_WIN)
   enumerator->AddInt("DxDiagnosticsInfoState", dx_diagnostics_info_state);
 #endif
+  // TODO(kbr): add dx_diagnostics on Windows.
+  for (size_t ii = 0; ii < video_encode_accelerator_supported_profiles.size();
+       ++ii) {
+    EnumerateVideoEncodeAcceleratorSupportedProfile(
+        enumerator, video_encode_accelerator_supported_profiles[ii]);
+  }
   enumerator->EndAuxAttributes();
 }
 
diff --git a/gpu/config/gpu_info.h b/gpu/config/gpu_info.h
index 8f5479b..bdbb205 100644
--- a/gpu/config/gpu_info.h
+++ b/gpu/config/gpu_info.h
@@ -18,6 +18,7 @@
 #include "gpu/config/dx_diag_node.h"
 #include "gpu/config/gpu_performance_stats.h"
 #include "gpu/gpu_export.h"
+#include "media/video/video_encode_accelerator.h"
 
 namespace gpu {
 
@@ -177,6 +178,8 @@
   DxDiagNode dx_diagnostics;
 #endif
 
+  std::vector<media::VideoEncodeAccelerator::SupportedProfile>
+      video_encode_accelerator_supported_profiles;
   // Note: when adding new members, please remember to update EnumerateFields
   // in gpu_info.cc.
 
diff --git a/gpu/config/gpu_info_collector.cc b/gpu/config/gpu_info_collector.cc
index 78dfe22..5d25546 100644
--- a/gpu/config/gpu_info_collector.cc
+++ b/gpu/config/gpu_info_collector.cc
@@ -156,6 +156,8 @@
   basic_gpu_info->direct_rendering = context_gpu_info.direct_rendering;
   basic_gpu_info->context_info_state = context_gpu_info.context_info_state;
   basic_gpu_info->initialization_time = context_gpu_info.initialization_time;
+  basic_gpu_info->video_encode_accelerator_supported_profiles =
+      context_gpu_info.video_encode_accelerator_supported_profiles;
 }
 
 }  // namespace gpu
diff --git a/gpu/config/gpu_info_unittest.cc b/gpu/config/gpu_info_unittest.cc
index 48d476f..71d4e5c 100644
--- a/gpu/config/gpu_info_unittest.cc
+++ b/gpu/config/gpu_info_unittest.cc
@@ -32,6 +32,7 @@
 #if defined(OS_WIN)
   EXPECT_EQ(gpu_info.dx_diagnostics_info_state, kCollectInfoNone);
 #endif
+  EXPECT_EQ(gpu_info.video_encode_accelerator_supported_profiles.size(), 0u);
 }
 
 }  // namespace gpu
diff --git a/mojo/BUILD.gn b/mojo/BUILD.gn
index 1b88cd4..8f58fc1 100644
--- a/mojo/BUILD.gn
+++ b/mojo/BUILD.gn
@@ -12,6 +12,8 @@
   }
   deps = [
     ":tests",
+    "//mojo/apps/js:mojo_js_content_handler",
+    "//mojo/apps/js:mojo_js_standalone",
     "//mojo/common",
     "//mojo/examples",
     "//mojo/public",
@@ -42,6 +44,8 @@
   testonly = true
   deps = [
     "//mojo/application_manager:mojo_application_manager_unittests",
+    "//mojo/apps/js/test:mojo_apps_js_unittests",
+    "//mojo/bindings/js/tests:mojo_js_unittests",
     "//mojo/common:mojo_common_unittests",
     "//mojo/converters/surfaces/tests:mojo_surfaces_lib_unittests",
     "//mojo/edk/system:mojo_message_pipe_perftests",
diff --git a/mojo/android/javatests/src/org/chromium/mojo/bindings/ValidationTest.java b/mojo/android/javatests/src/org/chromium/mojo/bindings/ValidationTest.java
index d0d63bb..8bf5e21 100644
--- a/mojo/android/javatests/src/org/chromium/mojo/bindings/ValidationTest.java
+++ b/mojo/android/javatests/src/org/chromium/mojo/bindings/ValidationTest.java
@@ -62,10 +62,11 @@
 
     private static String getStringContent(File f) throws FileNotFoundException {
         Scanner scanner = new Scanner(f).useDelimiter("\\Z");
-        if (scanner.hasNext()) {
-            return scanner.next();
+        StringBuilder result = new StringBuilder();
+        while (scanner.hasNext()) {
+            result.append(scanner.next());
         }
-        return "";
+        return result.toString().trim();
     }
 
     private static List<TestData> getTestData(String prefix)
@@ -97,7 +98,9 @@
             throws FileNotFoundException {
         List<TestData> testData = getTestData(prefix);
         for (TestData test : testData) {
-            assertNull(test.inputData.getErrorMessage());
+            assertNull("Unable to read: " + test.dataFile.getName() +
+                    ": " + test.inputData.getErrorMessage(),
+                    test.inputData.getErrorMessage());
             List<Handle> handles = new ArrayList<Handle>();
             for (int i = 0; i < test.inputData.getHandlesCount(); ++i) {
                 handles.add(new HandleMock());
diff --git a/mojo/application/application_runner_chromium.cc b/mojo/application/application_runner_chromium.cc
index fa139c7..e49b8e2 100644
--- a/mojo/application/application_runner_chromium.cc
+++ b/mojo/application/application_runner_chromium.cc
@@ -6,6 +6,7 @@
 
 #include "base/at_exit.h"
 #include "base/command_line.h"
+#include "base/debug/stack_trace.h"
 #include "base/memory/scoped_ptr.h"
 #include "base/message_loop/message_loop.h"
 #include "mojo/common/message_pump_mojo.h"
@@ -45,6 +46,10 @@
   base::AtExitManager at_exit;
 #endif
 
+#ifndef NDEBUG
+  base::debug::EnableInProcessStackDumping();
+#endif
+
   {
     scoped_ptr<base::MessageLoop> loop;
     if (message_loop_type_ == base::MessageLoop::TYPE_CUSTOM)
diff --git a/mojo/application_manager/application_manager.cc b/mojo/application_manager/application_manager.cc
index b183d9f..38ee972 100644
--- a/mojo/application_manager/application_manager.cc
+++ b/mojo/application_manager/application_manager.cc
@@ -259,7 +259,7 @@
   InterfaceRequest<ServiceProvider> spir;
   spir.Bind(service_provider.PassMessagePipe());
   connection->content_handler->OnConnect(
-      content_url.spec(), url_response.Pass(), spir.Pass());
+      requestor_url.spec(), url_response.Pass(), spir.Pass());
 }
 
 void ApplicationManager::SetLoaderForURL(scoped_ptr<ApplicationLoader> loader,
diff --git a/mojo/apps/js/content_handler_impl.cc b/mojo/apps/js/content_handler_impl.cc
index f3dffa7..01897a0 100644
--- a/mojo/apps/js/content_handler_impl.cc
+++ b/mojo/apps/js/content_handler_impl.cc
@@ -14,22 +14,19 @@
 class ContentHandlerJSApp : public JSApp {
  public:
   ContentHandlerJSApp(ApplicationDelegateImpl* app_delegate_impl,
-                      const std::string& url,
                       URLResponsePtr content)
       : JSApp(app_delegate_impl),
-        url_(url),
         content_(content.Pass()) {
   }
 
   virtual bool Load(std::string* source, std::string* file_name) override {
-    *file_name = url_;
+    *file_name = content_->url;
     if (content_.is_null())
       return false;
     return common::BlockingCopyToString(content_->body.Pass(), source);
   }
 
  private:
-  std::string url_;
   URLResponsePtr content_;
 };
 
@@ -42,13 +39,11 @@
 }
 
 void ContentHandlerImpl::OnConnect(
-    const mojo::String& url,
+    const mojo::String& requestor_url,
     URLResponsePtr content,
     InterfaceRequest<ServiceProvider> service_provider) {
   scoped_ptr<JSApp> js_app(
-      new ContentHandlerJSApp(app_delegate_impl_,
-                              url.To<std::string>(),
-                              content.Pass()));
+      new ContentHandlerJSApp(app_delegate_impl_, content.Pass()));
   app_delegate_impl_->StartJSApp(js_app.Pass());
 }
 
diff --git a/mojo/converters/surfaces/surfaces_type_converters.cc b/mojo/converters/surfaces/surfaces_type_converters.cc
index d034b27..fadbb97 100644
--- a/mojo/converters/surfaces/surfaces_type_converters.cc
+++ b/mojo/converters/surfaces/surfaces_type_converters.cc
@@ -71,6 +71,8 @@
           render_pass->CreateAndAppendDrawQuad<cc::RenderPassDrawQuad>();
       RenderPassQuadState* render_pass_quad_state =
           input->render_pass_quad_state.get();
+      gfx::PointF mask_uv_scale_as_point =
+          render_pass_quad_state->mask_uv_scale.To<gfx::PointF>();
       gfx::PointF filter_scale_as_point =
           render_pass_quad_state->filters_scale.To<gfx::PointF>();
       render_pass_quad->SetAll(
@@ -81,9 +83,10 @@
           input->needs_blending,
           render_pass_quad_state->render_pass_id.To<cc::RenderPassId>(),
           render_pass_quad_state->mask_resource_id,
-          render_pass_quad_state->mask_uv_rect.To<gfx::RectF>(),
+          mask_uv_scale_as_point.OffsetFromOrigin(),
+          render_pass_quad_state->mask_texture_size.To<gfx::Size>(),
           cc::FilterOperations(),  // TODO(jamesr): filters
-          gfx::Vector2dF(filter_scale_as_point.x(), filter_scale_as_point.y()),
+          filter_scale_as_point.OffsetFromOrigin(),
           cc::FilterOperations());  // TODO(jamesr): background_filters
       break;
     }
@@ -248,7 +251,10 @@
       pass_state->render_pass_id =
           RenderPassId::From(render_pass_quad->render_pass_id);
       pass_state->mask_resource_id = render_pass_quad->mask_resource_id;
-      pass_state->mask_uv_rect = RectF::From(render_pass_quad->mask_uv_rect);
+      pass_state->mask_uv_scale = PointF::From(
+          gfx::PointAtOffsetFromOrigin(render_pass_quad->mask_uv_scale));
+      pass_state->mask_texture_size =
+          Size::From(render_pass_quad->mask_texture_size);
       // TODO(jamesr): pass_state->filters
       pass_state->filters_scale = PointF::From(
           gfx::PointAtOffsetFromOrigin(render_pass_quad->filters_scale));
diff --git a/mojo/examples/BUILD.gn b/mojo/examples/BUILD.gn
index f89dcd9..bdd09f7 100644
--- a/mojo/examples/BUILD.gn
+++ b/mojo/examples/BUILD.gn
@@ -12,6 +12,7 @@
     "//mojo/examples/content_handler_demo",
     "//mojo/examples/echo",
     "//mojo/examples/http_server",
+    "//mojo/examples/pepper_container_app",
     "//mojo/examples/png_viewer",
     "//mojo/examples/sample_app",
     "//mojo/examples/surfaces_app",
diff --git a/mojo/examples/browser/BUILD.gn b/mojo/examples/browser/BUILD.gn
index 3228870..b0b1780 100644
--- a/mojo/examples/browser/BUILD.gn
+++ b/mojo/examples/browser/BUILD.gn
@@ -29,7 +29,7 @@
     "//mojo/services/public/interfaces/input_events",
     "//mojo/services/public/interfaces/navigation",
     "//mojo/services/public/interfaces/view_manager",
-    "//mojo/views",
+    "//mojo/views:views",
     "//third_party/icu",
     "//ui/aura",
     "//ui/base",
diff --git a/mojo/examples/content_handler_demo/content_handler_demo.cc b/mojo/examples/content_handler_demo/content_handler_demo.cc
index a98fea9..3abf0f7 100644
--- a/mojo/examples/content_handler_demo/content_handler_demo.cc
+++ b/mojo/examples/content_handler_demo/content_handler_demo.cc
@@ -23,7 +23,7 @@
 
  private:
   virtual void OnConnect(
-      const mojo::String& url,
+      const mojo::String& requestor_url,
       URLResponsePtr response,
       InterfaceRequest<ServiceProvider> service_provider) override;
 
@@ -72,11 +72,11 @@
 };
 
 void ContentHandlerImpl::OnConnect(
-    const mojo::String& url,
+    const mojo::String& requestor_url,
     URLResponsePtr response,
     InterfaceRequest<ServiceProvider> service_provider) {
-  printf("ContentHandler::OnConnect - url:%s - body follows\n\n",
-         url.To<std::string>().c_str());
+  printf("ContentHandler::OnConnect - requestor_url:%s - body follows\n\n",
+         requestor_url.To<std::string>().c_str());
   content_handler_app_->PrintResponse(response->body.Pass());
 }
 
diff --git a/mojo/examples/demo_launcher/demo_launcher.cc b/mojo/examples/demo_launcher/demo_launcher.cc
index ec46265..2165e2e 100644
--- a/mojo/examples/demo_launcher/demo_launcher.cc
+++ b/mojo/examples/demo_launcher/demo_launcher.cc
@@ -2,16 +2,9 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/run_loop.h"
 #include "mojo/application/application_runner_chromium.h"
 #include "mojo/public/c/system/main.h"
-#include "mojo/public/cpp/application/application_connection.h"
 #include "mojo/public/cpp/application/application_delegate.h"
-#include "mojo/public/cpp/application/application_impl.h"
-#include "mojo/public/cpp/application/service_provider_impl.h"
-#include "mojo/public/interfaces/application/service_provider.mojom.h"
 #include "mojo/services/public/cpp/view_manager/view_manager.h"
 #include "mojo/services/public/cpp/view_manager/view_manager_context.h"
 
diff --git a/mojo/examples/keyboard/BUILD.gn b/mojo/examples/keyboard/BUILD.gn
index 19c5ab0..2feabcc 100644
--- a/mojo/examples/keyboard/BUILD.gn
+++ b/mojo/examples/keyboard/BUILD.gn
@@ -34,7 +34,7 @@
     "//mojo/services/public/interfaces/geometry",
     "//mojo/services/public/interfaces/navigation",
     "//mojo/services/public/interfaces/view_manager",
-    "//mojo/views",
+    "//mojo/views:views",
     "//third_party/icu",
     "//ui/aura",
     "//ui/base",
diff --git a/mojo/examples/media_viewer/BUILD.gn b/mojo/examples/media_viewer/BUILD.gn
index cbac84d..b251b2d 100644
--- a/mojo/examples/media_viewer/BUILD.gn
+++ b/mojo/examples/media_viewer/BUILD.gn
@@ -24,7 +24,7 @@
     "//mojo/services/public/cpp/view_manager",
     "//mojo/services/public/interfaces/navigation",
     "//mojo/services/public/interfaces/view_manager",
-    "//mojo/views",
+    "//mojo/views:views",
     "//skia",
     "//ui/gfx",
     "//ui/gfx/geometry",
diff --git a/mojo/examples/png_viewer/png_viewer.cc b/mojo/examples/png_viewer/png_viewer.cc
index bb6e321..b1110e0 100644
--- a/mojo/examples/png_viewer/png_viewer.cc
+++ b/mojo/examples/png_viewer/png_viewer.cc
@@ -201,7 +201,7 @@
  private:
   // Overridden from ContentHandler:
   virtual void OnConnect(
-      const mojo::String& url,
+      const mojo::String& requestor_url,
       URLResponsePtr response,
       InterfaceRequest<ServiceProvider> service_provider) override {
     ServiceProviderImpl* exported_services = new ServiceProviderImpl();
diff --git a/mojo/examples/window_manager/BUILD.gn b/mojo/examples/window_manager/BUILD.gn
index a6283c9..72bdd9d 100644
--- a/mojo/examples/window_manager/BUILD.gn
+++ b/mojo/examples/window_manager/BUILD.gn
@@ -34,7 +34,7 @@
     "//mojo/services/public/interfaces/input_events",
     "//mojo/services/public/interfaces/navigation",
     "//mojo/services/window_manager:lib",
-    "//mojo/views",
+    "//mojo/views:views",
     "//ui/aura",
     "//ui/base",
     "//ui/gfx",
diff --git a/mojo/examples/wm_flow/BUILD.gn b/mojo/examples/wm_flow/BUILD.gn
index 50ce507..9a4c498 100644
--- a/mojo/examples/wm_flow/BUILD.gn
+++ b/mojo/examples/wm_flow/BUILD.gn
@@ -7,7 +7,7 @@
 
 assert(use_aura)
 
-group("wm_flow" ) {
+group("wm_flow") {
   deps = [
     ":app",
     ":embedded",
@@ -28,11 +28,16 @@
 
   deps = [
     "//base",
+    "//skia",
+    "//ui/aura",
+    "//ui/views",
+    "//ui/wm:wm",
     "//mojo/application",
     "//mojo/public/c/system:for_shared_library",
     "//mojo/services/public/cpp/view_manager",
+    "//mojo/services/public/interfaces/input_events",
     "//mojo/services/window_manager:lib",
-    "//mojo/views",
+    "//mojo/views:views",
   ]
 }
 
@@ -46,8 +51,11 @@
 
   deps = [
     "//base",
+    "//ui/gfx",
+    "//ui/gfx/geometry",
     "//mojo/application",
     "//mojo/public/c/system:for_shared_library",
+    "//mojo/public/interfaces/application:application",
     "//mojo/services/public/cpp/view_manager",
     "//mojo/services/public/interfaces/view_manager",
   ]
@@ -68,6 +76,7 @@
     "//mojo/application",
     "//mojo/examples/bitmap_uploader",
     "//mojo/public/c/system:for_shared_library",
+    "//mojo/public/interfaces/application:application",
     "//mojo/services/public/cpp/view_manager",
     "//mojo/services/window_manager:lib",
   ]
diff --git a/mojo/examples/wm_flow/init/init.cc b/mojo/examples/wm_flow/init/init.cc
index ba17b44..daef4ea 100644
--- a/mojo/examples/wm_flow/init/init.cc
+++ b/mojo/examples/wm_flow/init/init.cc
@@ -2,13 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "base/bind.h"
 #include "mojo/application/application_runner_chromium.h"
 #include "mojo/public/c/system/main.h"
 #include "mojo/public/cpp/application/application_delegate.h"
 #include "mojo/public/cpp/application/application_impl.h"
-#include "mojo/public/cpp/application/service_provider_impl.h"
-#include "mojo/public/interfaces/application/service_provider.mojom.h"
 #include "mojo/services/public/cpp/view_manager/view_manager.h"
 #include "mojo/services/public/cpp/view_manager/view_manager_context.h"
 
diff --git a/mojo/examples/wm_flow/wm/wm.cc b/mojo/examples/wm_flow/wm/wm.cc
index b781f60..228f04f 100644
--- a/mojo/examples/wm_flow/wm/wm.cc
+++ b/mojo/examples/wm_flow/wm/wm.cc
@@ -102,6 +102,10 @@
  private:
   // Overridden from mojo::ApplicationDelegate:
   virtual void Initialize(mojo::ApplicationImpl* impl) override {
+    // Create views_init here as we need ApplicationRunnerChromium to install
+    // an AtExitManager and CommandLine.
+    if (!views_init_.get())
+      views_init_.reset(new mojo::ViewsInit);
     shell_ = impl->shell();
     window_manager_app_->Initialize(impl);
   }
@@ -183,6 +187,8 @@
 
   mojo::Shell* shell_;
 
+  scoped_ptr<mojo::ViewsInit> views_init_;
+
   scoped_ptr<mojo::WindowManagerApp> window_manager_app_;
 
   mojo::ViewManager* view_manager_;
@@ -197,7 +203,6 @@
 }  // namespace examples
 
 MojoResult MojoMain(MojoHandle shell_handle) {
-  mojo::ViewsInit views_init;
   mojo::ApplicationRunnerChromium runner(new examples::SimpleWM);
   return runner.Run(shell_handle);
 }
diff --git a/mojo/mojo.gyp b/mojo/mojo.gyp
index 0f5e11b..e3c769f 100644
--- a/mojo/mojo.gyp
+++ b/mojo/mojo.gyp
@@ -16,7 +16,6 @@
   'includes': [
     'mojo_apps.gypi',
     'mojo_converters.gypi',
-    'mojo_examples.gypi',
     'mojo_services.gypi',
     'mojo_variables.gypi',
   ],
@@ -33,11 +32,6 @@
         'mojo_base.gyp:mojo_base',
         'mojo_clipboard',
         'mojo_clipboard_unittests',
-        'mojo_content_handler_demo',
-        'mojo_echo_client',
-        'mojo_echo_service',
-        'mojo_example_apptests',
-        'mojo_example_service',
         'mojo_geometry_lib',
         'mojo_html_viewer',
         'mojo_input_events_lib',
@@ -46,46 +40,25 @@
         'mojo_js_unittests',
         'mojo_native_viewport_service',
         'mojo_network_service',
-        'mojo_pepper_container_app',
-        'mojo_png_viewer',
-        'mojo_sample_app',
         'mojo_shell',
         'mojo_shell_lib',
         'mojo_shell_tests',
-        'mojo_surfaces_app',
-        'mojo_surfaces_app',
-        'mojo_surfaces_child_app',
-        'mojo_surfaces_child_gl_app',
         'mojo_surfaces_lib',
         'mojo_surfaces_lib_unittests',
         'mojo_surfaces_service',
         'mojo_test_app',
         'mojo_test_request_tracker_app',
         'mojo_view_manager_lib_unittests',
-        'mojo_wget',
         'services/public/mojo_services_public.gyp:mojo_services_public',
         'public/mojo_public.gyp:mojo_public',
       ],
       'conditions': [
         ['use_aura==1', {
           'dependencies': [
-            'mojo_aura_demo',
-            'mojo_aura_demo_init',
-            'mojo_browser',
             'mojo_core_window_manager',
             'mojo_core_window_manager_unittests',
-            'mojo_demo_launcher',
-            'mojo_embedded_app',
-            'mojo_keyboard',
-            'mojo_media_viewer',
-            'mojo_nesting_app',
             'mojo_view_manager',
             'mojo_view_manager_unittests',
-            'mojo_window_manager',
-            'mojo_wm_flow_app',
-            'mojo_wm_flow_embedded',
-            'mojo_wm_flow_init',
-            'mojo_wm_flow_wm',
           ],
         }],
         ['OS == "linux"', {
@@ -559,21 +532,22 @@
           ],
         },
         {
-          # GN version: //mojo/views
+          # GN version: //mojo/views:views
           'target_name': 'mojo_views_support',
           'type': 'static_library',
           'dependencies': [
             '../base/base.gyp:base',
             '../base/base.gyp:base_i18n',
+            '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',
             '../skia/skia.gyp:skia',
             '../third_party/icu/icu.gyp:icui18n',
             '../third_party/icu/icu.gyp:icuuc',
             '../ui/aura/aura.gyp:aura',
             '../ui/base/ui_base.gyp:ui_base',
+            '../ui/gfx/gfx.gyp:gfx',
             '../ui/views/views.gyp:views',
             '../ui/wm/wm.gyp:wm',
             'mojo_aura_support',
-            'mojo_views_support_internal',
             'mojo_view_manager_lib',
             'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
           ],
@@ -587,29 +561,6 @@
           ],
         },
         {
-          # GN version: //mojo/views:views_internal
-          'target_name': 'mojo_views_support_internal',
-          'type': '<(component)',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../base/base.gyp:base_i18n',
-            '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',
-            '../skia/skia.gyp:skia',
-            '../third_party/icu/icu.gyp:icui18n',
-            '../third_party/icu/icu.gyp:icuuc',
-            '../ui/base/ui_base.gyp:ui_base',
-            '../ui/gfx/gfx.gyp:gfx',
-          ],
-          'sources': [
-            'views/mojo_views_export.h',
-            'views/views_init_internal.cc',
-            'views/views_init_internal.h',
-          ],
-          'defines': [
-            'MOJO_VIEWS_IMPLEMENTATION',
-          ],
-        },
-        {
           # GN version: //mojo/services/public/cpp/view_manager/lib:run_unittests
           'target_name': 'mojo_view_manager_run_unittests',
           'type': 'static_library',
diff --git a/mojo/mojo_examples.gypi b/mojo/mojo_examples.gypi
deleted file mode 100644
index 087f5cc..0000000
--- a/mojo/mojo_examples.gypi
+++ /dev/null
@@ -1,896 +0,0 @@
-# Copyright 2013 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
-  'targets': [
-    {
-      # GN version: //mojo/examples/echo:client
-      'target_name': 'mojo_echo_client',
-      'type': 'loadable_module',
-      'dependencies': [
-        'mojo_echo_service_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/echo/echo_client.cc',
-      ],
-    },
-    {
-      'target_name': 'package_mojo_echo_client',
-      'variables': {
-        'app_name': 'mojo_echo_client',
-      },
-      'includes': [ 'build/package_app.gypi' ],
-    },
-    {
-      # GN version: //mojo/examples/echo:bindings
-      'target_name': 'mojo_echo_service_bindings',
-      'type': 'static_library',
-      'sources': [
-        'examples/echo/echo_service.mojom',
-      ],
-      'dependencies': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-      'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-      'export_dependent_settings': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/echo:service
-      'target_name': 'mojo_echo_service',
-      'type': 'loadable_module',
-      'dependencies': [
-        'mojo_echo_service_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/echo/echo_service.cc',
-      ],
-    },
-    {
-      'target_name': 'package_mojo_echo_service',
-      'variables': {
-        'app_name': 'mojo_echo_service',
-      },
-      'includes': [ 'build/package_app.gypi' ],
-    },
-    {
-      # GN version: //mojo/examples/sample_app
-      'target_name': 'mojo_sample_app',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../base/base.gyp:base',
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_gpu_bindings',
-        'services/public/mojo_services_public.gyp:mojo_native_viewport_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'includes': [
-        'mojo_public_gles2_for_loadable_module.gypi',
-      ],
-      'sources': [
-        'examples/sample_app/gles2_client_impl.cc',
-        'examples/sample_app/gles2_client_impl.h',
-        'examples/sample_app/sample_app.cc',
-        'examples/sample_app/spinning_cube.cc',
-        'examples/sample_app/spinning_cube.h',
-      ],
-    },
-    {
-      'target_name': 'package_mojo_sample_app',
-      'variables': {
-        'app_name': 'mojo_sample_app',
-      },
-      'includes': [ 'build/package_app.gypi' ],
-    },
-    {
-      # GN version: //mojo/examples/apptest:bindings
-      'target_name': 'mojo_example_service_bindings',
-      'type': 'static_library',
-      'sources': [
-        'examples/apptest/example_service.mojom',
-      ],
-      'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-      'export_dependent_settings': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-      'dependencies': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/apptest:service
-      'target_name': 'mojo_example_service',
-      'type': 'loadable_module',
-      'dependencies': [
-        'mojo_example_service_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone', # For ApplicationDelegate.
-        'public/mojo_public.gyp:mojo_cpp_bindings',           # For *.mojom.h
-        'public/mojo_public.gyp:mojo_utility',                # For RunLoop.
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/apptest/example_service_application.cc',
-        'examples/apptest/example_service_application.h',
-        'examples/apptest/example_service_impl.cc',
-        'examples/apptest/example_service_impl.h',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/apptest:apptests
-      'target_name': 'mojo_example_apptests',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../testing/gtest.gyp:gtest',
-        'mojo_example_service',
-        'mojo_example_service_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone', # For ApplicationDelegate.
-        'public/mojo_public.gyp:mojo_utility',                # For RunLoop.
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/apptest/example_apptest.cc',
-        'examples/apptest/example_client_application.cc',
-        'examples/apptest/example_client_application.h',
-        'examples/apptest/example_client_impl.cc',
-        'examples/apptest/example_client_impl.h',
-      ],
-    },
-    {
-      'target_name': 'package_mojo_example_apptests',
-      'variables': {
-        'app_name': 'mojo_example_apptests',
-      },
-      'includes': [ 'build/package_app.gypi' ],
-    },
-    {
-      # GN version: //mojo/examples/http_server
-      'target_name': 'mojo_http_server',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../base/base.gyp:base',
-        'public/mojo_public.gyp:mojo_application_standalone',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        'services/public/mojo_services_public.gyp:mojo_network_bindings',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/http_server/http_server.cc',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/wget
-      'target_name': 'mojo_wget',
-      'type': 'loadable_module',
-      'dependencies': [
-        'services/public/mojo_services_public.gyp:mojo_network_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone', # For ApplicationDelegate.
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/wget/wget.cc',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/content_handler_demo
-      'target_name': 'mojo_content_handler_demo',
-      'type': 'loadable_module',
-      'dependencies': [
-        'services/public/mojo_services_public.gyp:mojo_content_handler_bindings',
-        'public/mojo_public.gyp:mojo_application_standalone', # For ApplicationDelegate.
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/content_handler_demo/content_handler_demo.cc',
-      ],
-    },
-    {
-      'target_name': 'package_mojo_wget',
-      'variables': {
-        'app_name': 'mojo_wget',
-      },
-      'includes': [ 'build/package_app.gypi' ],
-    },
-    {
-      # GN version: //mojo/examples/media_viewer:bindings
-      'target_name': 'mojo_media_viewer_bindings',
-      'type': 'static_library',
-      'sources': [
-        'examples/media_viewer/media_viewer.mojom',
-      ],
-      'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-      'export_dependent_settings': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-      'dependencies': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/png_viewer
-      'target_name': 'mojo_png_viewer',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../skia/skia.gyp:skia',
-        '../ui/gfx/gfx.gyp:gfx',
-        'mojo_base.gyp:mojo_application_chromium',
-        'mojo_bitmap_uploader',
-        'mojo_media_viewer_bindings',
-        'services/public/mojo_services_public.gyp:mojo_content_handler_bindings',
-        'services/public/mojo_services_public.gyp:mojo_network_bindings',
-        'mojo_view_manager_lib',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        'public/mojo_public.gyp:mojo_utility',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/png_viewer/png_viewer.cc',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/pepper_container_app
-      'target_name': 'mojo_pepper_container_app',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../base/base.gyp:base',
-        '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',
-        '../gpu/gpu.gyp:command_buffer_common',
-        '../ppapi/ppapi.gyp:ppapi_c',
-        '../ppapi/ppapi_internal.gyp:ppapi_example_gles2_spinning_cube',
-        '../ui/events/events.gyp:events_base',
-        'mojo_base.gyp:mojo_application_chromium',
-        'mojo_base.gyp:mojo_common_lib',
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_gpu_bindings',
-        'services/public/mojo_services_public.gyp:mojo_native_viewport_bindings',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'includes': [
-        'mojo_public_gles2_for_loadable_module.gypi',
-      ],
-      'defines': [
-        # We don't really want to export. We could change how
-        # ppapi_{shared,thunk}_export.h are defined to avoid this.
-        'PPAPI_SHARED_IMPLEMENTATION',
-        'PPAPI_THUNK_IMPLEMENTATION',
-      ],
-      'sources': [
-        # Source files from ppapi/.
-        # An alternative is to depend on
-        # '../ppapi/ppapi_internal.gyp:ppapi_shared', but that target includes
-        # a lot of things that we don't need.
-        # TODO(yzshen): Consider extracting these files into a separate target
-        # which mojo_pepper_container_app and ppapi_shared both depend on.
-        '../ppapi/shared_impl/api_id.h',
-        '../ppapi/shared_impl/callback_tracker.cc',
-        '../ppapi/shared_impl/callback_tracker.h',
-        '../ppapi/shared_impl/host_resource.cc',
-        '../ppapi/shared_impl/host_resource.h',
-        '../ppapi/shared_impl/id_assignment.cc',
-        '../ppapi/shared_impl/id_assignment.h',
-        '../ppapi/shared_impl/ppapi_globals.cc',
-        '../ppapi/shared_impl/ppapi_globals.h',
-        '../ppapi/shared_impl/ppapi_shared_export.h',
-        '../ppapi/shared_impl/ppb_message_loop_shared.cc',
-        '../ppapi/shared_impl/ppb_message_loop_shared.h',
-        '../ppapi/shared_impl/ppb_view_shared.cc',
-        '../ppapi/shared_impl/ppb_view_shared.h',
-        '../ppapi/shared_impl/proxy_lock.cc',
-        '../ppapi/shared_impl/proxy_lock.h',
-        '../ppapi/shared_impl/resource.cc',
-        '../ppapi/shared_impl/resource.h',
-        '../ppapi/shared_impl/resource_tracker.cc',
-        '../ppapi/shared_impl/resource_tracker.h',
-        '../ppapi/shared_impl/scoped_pp_resource.cc',
-        '../ppapi/shared_impl/scoped_pp_resource.h',
-        '../ppapi/shared_impl/singleton_resource_id.h',
-        '../ppapi/shared_impl/tracked_callback.cc',
-        '../ppapi/shared_impl/tracked_callback.h',
-        '../ppapi/thunk/enter.cc',
-        '../ppapi/thunk/enter.h',
-        '../ppapi/thunk/interfaces_ppb_private.h',
-        '../ppapi/thunk/interfaces_ppb_private_flash.h',
-        '../ppapi/thunk/interfaces_ppb_private_no_permissions.h',
-        '../ppapi/thunk/interfaces_ppb_public_dev.h',
-        '../ppapi/thunk/interfaces_ppb_public_dev_channel.h',
-        '../ppapi/thunk/interfaces_ppb_public_stable.h',
-        '../ppapi/thunk/interfaces_preamble.h',
-        '../ppapi/thunk/ppapi_thunk_export.h',
-        '../ppapi/thunk/ppb_graphics_3d_api.h',
-        '../ppapi/thunk/ppb_graphics_3d_thunk.cc',
-        '../ppapi/thunk/ppb_instance_api.h',
-        '../ppapi/thunk/ppb_instance_thunk.cc',
-        '../ppapi/thunk/ppb_message_loop_api.h',
-        '../ppapi/thunk/ppb_view_api.h',
-        '../ppapi/thunk/ppb_view_thunk.cc',
-        '../ppapi/thunk/resource_creation_api.h',
-        '../ppapi/thunk/thunk.h',
-
-        'examples/pepper_container_app/graphics_3d_resource.cc',
-        'examples/pepper_container_app/graphics_3d_resource.h',
-        'examples/pepper_container_app/interface_list.cc',
-        'examples/pepper_container_app/interface_list.h',
-        'examples/pepper_container_app/mojo_ppapi_globals.cc',
-        'examples/pepper_container_app/mojo_ppapi_globals.h',
-        'examples/pepper_container_app/pepper_container_app.cc',
-        'examples/pepper_container_app/plugin_instance.cc',
-        'examples/pepper_container_app/plugin_instance.h',
-        'examples/pepper_container_app/plugin_module.cc',
-        'examples/pepper_container_app/plugin_module.h',
-        'examples/pepper_container_app/ppb_core_thunk.cc',
-        'examples/pepper_container_app/ppb_opengles2_thunk.cc',
-        'examples/pepper_container_app/resource_creation_impl.cc',
-        'examples/pepper_container_app/resource_creation_impl.h',
-        'examples/pepper_container_app/thunk.h',
-        'examples/pepper_container_app/type_converters.h',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/surfaces_app:parent_app
-      'target_name': 'mojo_surfaces_app',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../base/base.gyp:base',
-        '../cc/cc.gyp:cc',
-        '../cc/cc.gyp:cc_surfaces',
-        '../skia/skia.gyp:skia',
-        '../ui/gfx/gfx.gyp:gfx',
-        '../ui/gfx/gfx.gyp:gfx_geometry',
-        'mojo_base.gyp:mojo_application_chromium',
-        'mojo_base.gyp:mojo_common_lib',
-        'mojo_geometry_lib',
-        'mojo_surfaces_app_bindings',
-        'mojo_surfaces_lib',
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_gpu_bindings',
-        'services/public/mojo_services_public.gyp:mojo_native_viewport_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surfaces_bindings',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/surfaces_app/embedder.cc',
-        'examples/surfaces_app/embedder.h',
-        'examples/surfaces_app/surfaces_app.cc',
-        'examples/surfaces_app/surfaces_util.cc',
-        'examples/surfaces_app/surfaces_util.h',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/surfaces_app:bindings
-      'target_name': 'mojo_surfaces_app_bindings',
-      'type': 'static_library',
-      'sources': [
-        'examples/surfaces_app/child.mojom',
-      ],
-      'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-      'export_dependent_settings': [
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-      'dependencies': [
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surfaces_bindings',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-      ],
-    },
-    {
-      'target_name': 'package_mojo_surfaces_app',
-      'variables': {
-        'app_name': 'mojo_surfaces_app',
-      },
-      'includes': [ 'build/package_app.gypi' ],
-    },
-    {
-      # GN version: //mojo/examples/surfaces_app:child_app
-      'target_name': 'mojo_surfaces_child_app',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../base/base.gyp:base',
-        '../cc/cc.gyp:cc',
-        '../cc/cc.gyp:cc_surfaces',
-        '../skia/skia.gyp:skia',
-        '../ui/gfx/gfx.gyp:gfx',
-        '../ui/gfx/gfx.gyp:gfx_geometry',
-        'mojo_base.gyp:mojo_application_chromium',
-        'mojo_base.gyp:mojo_common_lib',
-        'mojo_geometry_lib',
-        'mojo_surfaces_app_bindings',
-        'mojo_surfaces_lib',
-        'services/public/mojo_services_public.gyp:mojo_surface_id_bindings',
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surfaces_bindings',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'sources': [
-        'examples/surfaces_app/child_app.cc',
-        'examples/surfaces_app/child_impl.cc',
-        'examples/surfaces_app/child_impl.h',
-        'examples/surfaces_app/surfaces_util.cc',
-        'examples/surfaces_app/surfaces_util.h',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/surfaces_app:child_gl_app
-      'target_name': 'mojo_surfaces_child_gl_app',
-      'type': 'loadable_module',
-      'dependencies': [
-        '../base/base.gyp:base',
-        '../cc/cc.gyp:cc',
-        '../cc/cc.gyp:cc_surfaces',
-        '../gpu/gpu.gyp:gpu',
-        '../skia/skia.gyp:skia',
-        '../ui/gfx/gfx.gyp:gfx',
-        '../ui/gfx/gfx.gyp:gfx_geometry',
-        'mojo_base.gyp:mojo_application_chromium',
-        'mojo_base.gyp:mojo_common_lib',
-        'mojo_geometry_lib',
-        'mojo_surfaces_app_bindings',
-        'mojo_surfaces_lib',
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_gpu_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surfaces_bindings',
-        'public/mojo_public.gyp:mojo_cpp_bindings',
-        '<(mojo_system_for_loadable_module)',
-      ],
-      'includes': [
-        'mojo_public_gles2_for_loadable_module.gypi',
-      ],
-      'sources': [
-        'examples/surfaces_app/child_gl_app.cc',
-        'examples/surfaces_app/child_gl_impl.cc',
-        'examples/surfaces_app/child_gl_impl.h',
-        'examples/surfaces_app/surfaces_util.cc',
-        'examples/surfaces_app/surfaces_util.h',
-        'examples/sample_app/spinning_cube.cc',
-        'examples/sample_app/spinning_cube.h',
-      ],
-    },
-    {
-      # GN version: //mojo/examples/bitmap_uploader
-      'target_name': 'mojo_bitmap_uploader',
-      'type': 'static_library',
-      'dependencies': [
-        '../base/base.gyp:base',
-        '../cc/cc.gyp:cc_surfaces',
-        '../gpu/gpu.gyp:gpu',
-        '../skia/skia.gyp:skia',
-        '../ui/gfx/gfx.gyp:gfx',
-        '../ui/gfx/gfx.gyp:gfx_geometry',
-        '../third_party/khronos/khronos.gyp:khronos_headers',
-        'mojo_base.gyp:mojo_application_chromium',
-        'mojo_geometry_lib',
-        'mojo_surfaces_lib',
-        'public/mojo_public.gyp:mojo_application_bindings',
-        'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-        'services/public/mojo_services_public.gyp:mojo_gpu_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surface_id_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surfaces_bindings',
-        'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-      ],
-      'includes': [
-        'mojo_public_gles2_for_loadable_module.gypi',
-      ],
-      'sources': [
-        'examples/bitmap_uploader/bitmap_uploader.cc',
-        'examples/bitmap_uploader/bitmap_uploader.h',
-      ],
-      'export_dependent_settings': [
-        'services/public/mojo_services_public.gyp:mojo_gpu_bindings',
-        'services/public/mojo_services_public.gyp:mojo_surfaces_bindings',
-        'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-      ],
-    },
-  ],
-  'conditions': [
-    ['use_aura==1', {
-      'targets': [
-        {
-          # GN version: //mojo/examples/aura_demo:mojo_aura_demo
-          'target_name': 'mojo_aura_demo',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../cc/cc.gyp:cc',
-            '../ui/aura/aura.gyp:aura',
-            '../ui/base/ui_base.gyp:ui_base',
-            '../ui/compositor/compositor.gyp:compositor',
-            '../ui/gfx/gfx.gyp:gfx',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            'mojo_aura_support',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_base.gyp:mojo_common_lib',
-            'mojo_geometry_lib',
-            'mojo_view_manager_lib',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/aura_demo/aura_demo.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/aura_demo:init
-          'target_name': 'mojo_aura_demo_init',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            'mojo_base.gyp:mojo_application_chromium',
-            'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-            'mojo_view_manager_lib',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/aura_demo/view_manager_init.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/browser
-          'target_name': 'mojo_browser',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../cc/cc.gyp:cc',
-            '../third_party/icu/icu.gyp:icui18n',
-            '../third_party/icu/icu.gyp:icuuc',
-            '../ui/aura/aura.gyp:aura',
-            '../ui/base/ui_base.gyp:ui_base',
-            '../ui/compositor/compositor.gyp:compositor',
-            '../ui/gfx/gfx.gyp:gfx',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            '../ui/resources/ui_resources.gyp:ui_resources',
-            '../ui/resources/ui_resources.gyp:ui_test_pak',
-            '../ui/views/views.gyp:views',
-            '../url/url.gyp:url_lib',
-            'mojo_aura_support',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_base.gyp:mojo_common_lib',
-            'mojo_geometry_lib',
-            'mojo_input_events_lib',
-            'mojo_view_manager_lib',
-            'mojo_views_support',
-            'mojo_window_manager_bindings',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'services/public/mojo_services_public.gyp:mojo_navigation_bindings',
-            'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/browser/browser.cc',
-          ],
-        },
-        {
-          'target_name': 'package_mojo_aura_demo',
-          'variables': {
-            'app_name': 'mojo_aura_demo',
-          },
-          'includes': [ 'build/package_app.gypi' ],
-        },
-        {
-          # GYP version: //mojo/examples/demo_launcher
-          'target_name': 'mojo_demo_launcher',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../skia/skia.gyp:skia',
-            '../ui/gfx/gfx.gyp:gfx',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            'mojo_base.gyp:mojo_application_chromium',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-            'mojo_view_manager_lib',
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-            'public/mojo_public.gyp:mojo_utility',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'includes': [
-            'mojo_public_gles2_for_loadable_module.gypi',
-          ],
-          'sources': [
-            'examples/demo_launcher/demo_launcher.cc',
-          ],
-        },
-        {
-          # GYP version: //mojo/examples/keyboard
-          'target_name': 'mojo_keyboard',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../cc/cc.gyp:cc',
-            '../third_party/icu/icu.gyp:icui18n',
-            '../third_party/icu/icu.gyp:icuuc',
-            '../ui/aura/aura.gyp:aura',
-            '../ui/base/ui_base.gyp:ui_base',
-            '../ui/compositor/compositor.gyp:compositor',
-            '../ui/gfx/gfx.gyp:gfx',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            '../ui/resources/ui_resources.gyp:ui_resources',
-            '../ui/resources/ui_resources.gyp:ui_test_pak',
-            '../ui/views/views.gyp:views',
-            '../url/url.gyp:url_lib',
-            'mojo_aura_support',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_base.gyp:mojo_common_lib',
-            'mojo_geometry_lib',
-            'mojo_input_events_lib',
-            'mojo_keyboard_bindings',
-            'mojo_view_manager_lib',
-            'mojo_views_support',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'services/public/mojo_services_public.gyp:mojo_navigation_bindings',
-            'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/keyboard/keyboard_delegate.h',
-            'examples/keyboard/keyboard_view.cc',
-            'examples/keyboard/keyboard_view.h',
-            'examples/keyboard/keyboard.cc',
-            'examples/keyboard/keys.cc',
-            'examples/keyboard/keys.h',
-          ],
-        },
-        {
-          # GYP version: //mojo/examples/keyboard:bindings
-          'target_name': 'mojo_keyboard_bindings',
-          'type': 'static_library',
-          'sources': [
-            'examples/keyboard/keyboard.mojom',
-          ],
-          'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-          'export_dependent_settings': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-          'dependencies': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/window_manager:bindings
-          'target_name': 'mojo_window_manager_bindings',
-          'type': 'static_library',
-          'sources': [
-            'examples/window_manager/window_manager.mojom',
-          ],
-          'dependencies': [
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-          'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-          'export_dependent_settings': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/window_manager
-          'target_name': 'mojo_window_manager',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../ui/aura/aura.gyp:aura',
-            '../ui/base/ui_base.gyp:ui_base',
-            '../ui/gfx/gfx.gyp:gfx',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            '../ui/resources/ui_resources.gyp:ui_resources',
-            '../ui/resources/ui_resources.gyp:ui_test_pak',
-            '../ui/views/views.gyp:views',
-            '../ui/wm/wm.gyp:wm',
-            'mojo_aura_support',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_core_window_manager_lib',
-            'mojo_geometry_lib',
-            'mojo_input_events_lib',
-            'mojo_keyboard_bindings',
-            'mojo_view_manager_lib',
-            'mojo_views_support',
-            'mojo_window_manager_bindings',
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-            'public/mojo_public.gyp:mojo_utility',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'services/public/mojo_services_public.gyp:mojo_navigation_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'includes': [
-            'mojo_public_gles2_for_loadable_module.gypi',
-          ],
-          'sources': [
-            'examples/window_manager/debug_panel.h',
-            'examples/window_manager/debug_panel.cc',
-            'examples/window_manager/window_manager.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/embedded_app
-          'target_name': 'mojo_embedded_app',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            '../url/url.gyp:url_lib',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_bitmap_uploader',
-            'mojo_view_manager_lib',
-            'mojo_window_manager_bindings',
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-            'public/mojo_public.gyp:mojo_utility',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'services/public/mojo_services_public.gyp:mojo_navigation_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'includes': [
-            'mojo_public_gles2_for_loadable_module.gypi',
-          ],
-          'sources': [
-            'examples/embedded_app/embedded_app.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/nesting_app
-          'target_name': 'mojo_nesting_app',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            '../url/url.gyp:url_lib',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_bitmap_uploader',
-            'mojo_view_manager_lib',
-            'mojo_window_manager_bindings',
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-            'public/mojo_public.gyp:mojo_utility',
-            'services/public/mojo_services_public.gyp:mojo_geometry_bindings',
-            'services/public/mojo_services_public.gyp:mojo_navigation_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'includes': [
-            'mojo_public_gles2_for_loadable_module.gypi',
-          ],
-          'sources': [
-            'examples/nesting_app/nesting_app.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/media_viewer
-          'target_name': 'mojo_media_viewer',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../skia/skia.gyp:skia',
-            '../ui/gfx/gfx.gyp:gfx',
-            '../ui/gfx/gfx.gyp:gfx_geometry',
-            '../ui/views/views.gyp:views',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_input_events_lib',
-            'mojo_media_viewer_bindings',
-            'mojo_view_manager_lib',
-            'mojo_views_support',
-            'services/public/mojo_services_public.gyp:mojo_navigation_bindings',
-            'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/media_viewer/media_viewer.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/wm_flow
-          'target_name': 'mojo_wm_flow_wm',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            '../skia/skia.gyp:skia',
-            '../ui/views/views.gyp:views',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_core_window_manager_lib',
-            'mojo_view_manager_lib',
-            'mojo_views_support',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/wm_flow/wm/frame_controller.cc',
-            'examples/wm_flow/wm/frame_controller.h',
-            'examples/wm_flow/wm/wm.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/wm_flow:init
-          'target_name': 'mojo_wm_flow_init',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            'mojo_base.gyp:mojo_application_chromium',
-            'services/public/mojo_services_public.gyp:mojo_view_manager_bindings',
-            'mojo_view_manager_lib',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/wm_flow/init/init.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/wm_flow:embedder_bindings
-          'target_name': 'mojo_wm_flow_embedder_bindings',
-          'type': 'static_library',
-          'sources': [
-            'examples/wm_flow/app/embedder.mojom',
-          ],
-          'dependencies': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-          'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-          'export_dependent_settings': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/wm_flow:embeddee_bindings
-          'target_name': 'mojo_wm_flow_embeddee_bindings',
-          'type': 'static_library',
-          'sources': [
-            'examples/wm_flow/embedded/embeddee.mojom',
-          ],
-          'dependencies': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-          'includes': [ 'public/tools/bindings/mojom_bindings_generator.gypi' ],
-          'export_dependent_settings': [
-            'public/mojo_public.gyp:mojo_cpp_bindings',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/wm_flow:app
-          'target_name': 'mojo_wm_flow_app',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_bitmap_uploader',
-            'mojo_view_manager_lib',
-            'mojo_wm_flow_embeddee_bindings',
-            'mojo_wm_flow_embedder_bindings',
-            'services/public/mojo_services_public.gyp:mojo_core_window_manager_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/wm_flow/app/app.cc',
-          ],
-        },
-        {
-          # GN version: //mojo/examples/wm_flow:embedded
-          'target_name': 'mojo_wm_flow_embedded',
-          'type': 'loadable_module',
-          'dependencies': [
-            '../base/base.gyp:base',
-            'mojo_base.gyp:mojo_application_chromium',
-            'mojo_bitmap_uploader',
-            'mojo_view_manager_lib',
-            'mojo_wm_flow_embeddee_bindings',
-            'mojo_wm_flow_embedder_bindings',
-            'services/public/mojo_services_public.gyp:mojo_core_window_manager_bindings',
-            '<(mojo_system_for_loadable_module)',
-          ],
-          'sources': [
-            'examples/wm_flow/embedded/embedded.cc',
-          ],
-        },
-      ],
-    }],
-  ],
-}
diff --git a/mojo/public/BUILD.gn b/mojo/public/BUILD.gn
index 5aa0de2..b661383 100644
--- a/mojo/public/BUILD.gn
+++ b/mojo/public/BUILD.gn
@@ -38,6 +38,7 @@
     "//mojo/public/cpp/environment:standalone",
     "//mojo/public/cpp/utility",
     "//mojo/public/interfaces/application",
+    "//mojo/public/js/bindings",
   ]
 }
 
diff --git a/mojo/public/cpp/bindings/lib/map_internal.h b/mojo/public/cpp/bindings/lib/map_internal.h
index aa0fe7e..f006cd0 100644
--- a/mojo/public/cpp/bindings/lib/map_internal.h
+++ b/mojo/public/cpp/bindings/lib/map_internal.h
@@ -57,7 +57,7 @@
   static inline ValueRefType at(std::map<KeyStorageType, ValueStorageType>* m,
                                 KeyForwardType key) {
     // We don't have C++11 library support yet, so we have to emulate the crash
-    // on a non-existant key.
+    // on a non-existent key.
     auto it = m->find(key);
     MOJO_CHECK(it != m->end());
     return it->second;
@@ -66,11 +66,17 @@
       const std::map<KeyStorageType, ValueStorageType>* m,
       KeyForwardType key) {
     // We don't have C++11 library support yet, so we have to emulate the crash
-    // on a non-existant key.
+    // on a non-existent key.
     auto it = m->find(key);
     MOJO_CHECK(it != m->end());
     return it->second;
   }
+  static inline ValueRefType GetOrInsert(
+      std::map<KeyStorageType, ValueStorageType>* m,
+      KeyForwardType key) {
+    // This is the backing for the index operator (operator[]).
+    return (*m)[key];
+  }
   static inline void Insert(std::map<KeyStorageType, ValueStorageType>* m,
                             KeyForwardType key,
                             ValueForwardType value) {
@@ -146,7 +152,7 @@
   static inline ValueRefType at(std::map<KeyStorageType, ValueStorageType>* m,
                                 KeyForwardType key) {
     // We don't have C++11 library support yet, so we have to emulate the crash
-    // on a non-existant key.
+    // on a non-existent key.
     auto it = m->find(key);
     MOJO_CHECK(it != m->end());
     return GetValue(it);
@@ -155,11 +161,23 @@
       const std::map<KeyStorageType, ValueStorageType>* m,
       KeyForwardType key) {
     // We don't have C++11 library support yet, so we have to emulate the crash
-    // on a non-existant key.
+    // on a non-existent key.
     auto it = m->find(key);
     MOJO_CHECK(it != m->end());
     return GetValue(it);
   }
+  static inline ValueRefType GetOrInsert(
+      std::map<KeyStorageType, ValueStorageType>* m,
+      KeyForwardType key) {
+    // This is the backing for the index operator (operator[]).
+    auto it = m->find(key);
+    if (it == m->end()) {
+      it = m->insert(std::make_pair(key, ValueStorageType())).first;
+      new (it->second.buf) Value();
+    }
+
+    return GetValue(it);
+  }
   static inline void Insert(std::map<KeyStorageType, ValueStorageType>* m,
                             KeyForwardType key,
                             ValueRefType value) {
diff --git a/mojo/public/cpp/bindings/map.h b/mojo/public/cpp/bindings/map.h
index f09937a..7aa7b6f 100644
--- a/mojo/public/cpp/bindings/map.h
+++ b/mojo/public/cpp/bindings/map.h
@@ -88,6 +88,11 @@
     return Traits::at(&map_, key);
   }
 
+  ValueRefType operator[](KeyForwardType key) {
+    is_null_ = false;
+    return Traits::GetOrInsert(&map_, key);
+  }
+
   void Swap(Map<Key, Value>* other) {
     std::swap(is_null_, other->is_null_);
     map_.swap(other->map_);
diff --git a/mojo/public/cpp/bindings/tests/map_unittest.cc b/mojo/public/cpp/bindings/tests/map_unittest.cc
index 159afb9..6f7db16 100644
--- a/mojo/public/cpp/bindings/tests/map_unittest.cc
+++ b/mojo/public/cpp/bindings/tests/map_unittest.cc
@@ -50,6 +50,49 @@
   }
 }
 
+TEST_F(MapTest, TestIndexOperator) {
+  Map<String, int> map;
+  for (size_t i = 0; i < kStringIntDataSize; ++i)
+    map[kStringIntData[i].string_data] = kStringIntData[i].int_data;
+
+  for (size_t i = 0; i < kStringIntDataSize; ++i) {
+    EXPECT_EQ(kStringIntData[i].int_data,
+              map.at(kStringIntData[i].string_data));
+  }
+}
+
+TEST_F(MapTest, TestIndexOperatorAsRValue) {
+  Map<String, int> map;
+  for (size_t i = 0; i < kStringIntDataSize; ++i)
+    map.insert(kStringIntData[i].string_data, kStringIntData[i].int_data);
+
+  for (size_t i = 0; i < kStringIntDataSize; ++i) {
+    EXPECT_EQ(kStringIntData[i].int_data, map[kStringIntData[i].string_data]);
+  }
+}
+
+TEST_F(MapTest, TestIndexOperatorMoveOnly) {
+  ASSERT_EQ(0u, MoveOnlyType::num_instances());
+  mojo::Map<mojo::String, mojo::Array<int32_t>> map;
+  std::vector<MoveOnlyType*> value_ptrs;
+
+  for (size_t i = 0; i < kStringIntDataSize; ++i) {
+    const char* key = kStringIntData[i].string_data;
+    Array<int32_t> array(1);
+    array[0] = kStringIntData[i].int_data;
+    map[key] = array.Pass();
+    EXPECT_TRUE(map);
+  }
+
+  // We now read back that data, to test the behavior of operator[].
+  for (size_t i = 0; i < kStringIntDataSize; ++i) {
+    auto it = map.find(kStringIntData[i].string_data);
+    ASSERT_TRUE(it != map.end());
+    ASSERT_EQ(1u, it.GetValue().size());
+    EXPECT_EQ(kStringIntData[i].int_data, it.GetValue()[0]);
+  }
+}
+
 TEST_F(MapTest, ConstructedFromArray) {
   Array<String> keys(kStringIntDataSize);
   Array<int> values(kStringIntDataSize);
@@ -153,7 +196,33 @@
   // a lot more boring.
 
   map.reset();
-  EXPECT_EQ(0u, CopyableType::num_instances());
+  EXPECT_EQ(0u, MoveOnlyType::num_instances());
+}
+
+TEST_F(MapTest, IndexOperator_MoveOnly) {
+  ASSERT_EQ(0u, MoveOnlyType::num_instances());
+  mojo::Map<mojo::String, MoveOnlyType> map;
+  std::vector<MoveOnlyType*> value_ptrs;
+
+  for (size_t i = 0; i < kStringIntDataSize; ++i) {
+    const char* key = kStringIntData[i].string_data;
+    MoveOnlyType value;
+    value_ptrs.push_back(value.ptr());
+    map[key] = value.Pass();
+    ASSERT_EQ(i + 1, map.size());
+    ASSERT_EQ(i + 1, value_ptrs.size());
+    EXPECT_EQ(map.size() + 1, MoveOnlyType::num_instances());
+    EXPECT_TRUE(map.at(key).moved());
+    EXPECT_EQ(value_ptrs[i], map.at(key).ptr());
+    map.at(key).ResetMoved();
+    EXPECT_TRUE(map);
+  }
+
+  // std::map doesn't have a capacity() method like std::vector so this test is
+  // a lot more boring.
+
+  map.reset();
+  EXPECT_EQ(0u, MoveOnlyType::num_instances());
 }
 
 TEST_F(MapTest, STLToMojo) {
diff --git a/mojo/public/html/convert_amd_modules_to_html.py b/mojo/public/html/convert_amd_modules_to_html.py
index 043bf80..20254b8 100755
--- a/mojo/public/html/convert_amd_modules_to_html.py
+++ b/mojo/public/html/convert_amd_modules_to_html.py
@@ -70,7 +70,7 @@
         AddImportNames(module, m.group(1))
         state = "body"
         continue
-      raise Exception, "Unknown import declaration"
+      raise Exception, "Unknown import declaration:" + line
     if state == "body":
       if end_body_regexp.search(line):
         module.body = "\n".join(body_lines)
diff --git a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_good.data b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_good.data
index d6562af..9a983a7 100644
--- a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_good.data
+++ b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_good.data
@@ -27,6 +27,13 @@
 
 [anchr]param1_ptr
 [dist4]array_param     // num_bytes
-[u4]5                  // num_elements
-0 1 2 3 4
+[u4]2                  // num_elements
+[u8]0                  // A null pointer, which is okay.
+[dist8]array_element_ptr
 [anchr]array_param
+
+[anchr]array_element_ptr
+[dist4]array_element   // num_bytes
+[u4]3                  // num_elements
+0 1 2
+[anchr]array_element
diff --git a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unexpected_null_fixed_array.data b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unexpected_null_fixed_array.data
index ab69175..b3adbc1 100644
--- a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unexpected_null_fixed_array.data
+++ b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unexpected_null_fixed_array.data
@@ -18,6 +18,7 @@
 
 [anchr]param1_ptr
 [dist4]array_param     // num_bytes
-[u4]5                  // num_elements
-0 1 2 3 4
+[u4]2                  // num_elements
+[u8]0                  // A null pointer, which is okay.
+[u8]0                  // A null pointer, which is okay.
 [anchr]array_param
diff --git a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.data b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements.data
similarity index 82%
rename from mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.data
rename to mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements.data
index bf1ddd5..5be7deb 100644
--- a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.data
+++ b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements.data
@@ -26,6 +26,7 @@
 
 [anchr]param1_ptr
 [dist4]array_param     // num_bytes
-[u4]5                  // num_elements
-0 1 2 3 4
+[u4]2                  // num_elements
+[u8]0                  // A null pointer, which is okay.
+[u8]0                  // A null pointer, which is okay.
 [anchr]array_param
diff --git a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.expected b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements.expected
similarity index 100%
rename from mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.expected
rename to mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements.expected
diff --git a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.data b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements_nested.data
similarity index 61%
copy from mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.data
copy to mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements_nested.data
index bf1ddd5..f1756dd 100644
--- a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.data
+++ b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements_nested.data
@@ -18,14 +18,21 @@
 
 [anchr]array_ptr
 [dist4]array_member    // num_bytes
-[u4]2                  // num_elements: Too few elements.
-0 1
+[u4]3                  // num_elements
+0 1 3
 [anchr]array_member
 
-[u4]0 [u1]0 [u1]0      // Padding for alignment of next array.
+[u4]0 [u1]0            // Padding for alignment of next array.
 
 [anchr]param1_ptr
 [dist4]array_param     // num_bytes
-[u4]5                  // num_elements
-0 1 2 3 4
+[u4]2                  // num_elements
+[dist8]array_element_ptr
+[u8]0                  // A null pointer, which is okay.
 [anchr]array_param
+
+[anchr]array_element_ptr
+[dist4]array_element   // num_bytes
+[u4]4                  // num_elements: Too many elements.
+0 1 2 3
+[anchr]array_element
diff --git a/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.expected b/mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements_nested.expected
similarity index 100%
copy from mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_too_few_array_elements.expected
copy to mojo/public/interfaces/bindings/tests/data/validation/conformance_mthd7_unmatched_array_elements_nested.expected
diff --git a/mojo/public/interfaces/bindings/tests/test_structs.mojom b/mojo/public/interfaces/bindings/tests/test_structs.mojom
index 6af0086..2063149 100644
--- a/mojo/public/interfaces/bindings/tests/test_structs.mojom
+++ b/mojo/public/interfaces/bindings/tests/test_structs.mojom
@@ -108,4 +108,34 @@
   int32 f6 = ALSO_TEN;
 };
 
+// Used to verify that all possible Map key field types can be encoded and
+// decoded successfully.
+
+struct MapKeyTypes {
+  map<bool, bool> f0;
+  map<int8, int8> f1;
+  map<uint8, uint8> f2;
+  map<int16, int16> f3;
+  map<uint16, uint16> f4;
+  map<int32, int32> f5;
+  map<uint32, uint32> f6;
+  map<int64, int64> f7;
+  map<uint64, uint64> f8;
+  map<float, float> f9;
+  map<double, double> f10;
+  map<string, string> f11;
+};
+
+// Used to verify that some common or difficult value types can be encoded and
+// decoded successfully.
+
+struct MapValueTypes {
+  map<string, array<string>> f0;
+  map<string, array<string>?> f1;
+  map<string, array<string?>> f2;
+  map<string, array<string, 2>> f3;
+  map<string, array<array<string, 2>?>> f4;
+  map<string, array<array<string, 2>, 1>> f5;
+};
+
 }
diff --git a/mojo/public/interfaces/bindings/tests/validation_test_interfaces.mojom b/mojo/public/interfaces/bindings/tests/validation_test_interfaces.mojom
index 5cd9d0b..1d0a9ef 100644
--- a/mojo/public/interfaces/bindings/tests/validation_test_interfaces.mojom
+++ b/mojo/public/interfaces/bindings/tests/validation_test_interfaces.mojom
@@ -39,7 +39,7 @@
   Method4(StructC param0, array<uint8> param1);
   Method5(StructE param0, handle<data_pipe_producer> param1);
   Method6(array<array<uint8>> param0);
-  Method7(StructF param0, array<uint8, 5> param1);
+  Method7(StructF param0, array<array<uint8, 3>?, 2> param1);
   Method8(array<array<string>?> param0);
   Method9(array<array<handle?>>? param0);
 };
diff --git a/mojo/public/js/bindings/codec.js b/mojo/public/js/bindings/codec.js
index b922a82..b84dc28 100644
--- a/mojo/public/js/bindings/codec.js
+++ b/mojo/public/js/bindings/codec.js
@@ -27,6 +27,7 @@
   var kStructHeaderSize = 8;
   var kMessageHeaderSize = 16;
   var kMessageWithRequestIDHeaderSize = 24;
+  var kMapStructPayloadSize = 16;
 
   var kStructHeaderNumBytesOffset = 0;
   var kStructHeaderNumFieldsOffset = 4;
@@ -180,6 +181,26 @@
     return this.decodeAndCreateDecoder(pointer).decodeString();
   };
 
+  Decoder.prototype.decodeMap = function(keyClass, valueClass) {
+    this.skip(4); // numberOfBytes
+    this.skip(4); // numberOfFields
+    var keys = this.decodeArrayPointer(keyClass);
+    var values = this.decodeArrayPointer(valueClass);
+    var val = new Map();
+    for (var i = 0; i < keys.length; i++)
+      val.set(keys[i], values[i]);
+    return val;
+  };
+
+  Decoder.prototype.decodeMapPointer = function(keyClass, valueClass) {
+    var pointer = this.decodePointer();
+    if (!pointer) {
+      return null;
+    }
+    var decoder = this.decodeAndCreateDecoder(pointer);
+    return decoder.decodeMap(keyClass, valueClass);
+  };
+
   // Encoder ------------------------------------------------------------------
 
   function Encoder(buffer, handles, base) {
@@ -349,6 +370,31 @@
     encoder.encodeString(val);
   };
 
+  Encoder.prototype.encodeMap = function(keyClass, valueClass, val) {
+    var keys = new Array(val.size);
+    var values = new Array(val.size);
+    var i = 0;
+    val.forEach(function(value, key) {
+      values[i] = value;
+      keys[i++] = key;
+    });
+    this.writeUint32(kStructHeaderSize + kMapStructPayloadSize);
+    this.writeUint32(2); // two fields: keys, values
+    this.encodeArrayPointer(keyClass, keys);
+    this.encodeArrayPointer(valueClass, values);
+  }
+
+  Encoder.prototype.encodeMapPointer = function(keyClass, valueClass, val) {
+    if (val == null) {
+      // Also handles undefined, since undefined == null.
+      this.encodePointer(val);
+      return;
+    }
+    var encodedSize = kStructHeaderSize + kMapStructPayloadSize;
+    var encoder = this.createAndEncodeEncoder(encodedSize);
+    encoder.encodeMap(keyClass, valueClass, val);
+  };
+
   // Message ------------------------------------------------------------------
 
   var kMessageNameOffset = kStructHeaderSize;
@@ -660,12 +706,18 @@
 
   NullablePointerTo.prototype = Object.create(PointerTo.prototype);
 
-  function ArrayOf(cls) {
+  function ArrayOf(cls, length) {
     this.cls = cls;
+    this.length = length || 0;
   }
 
   ArrayOf.prototype.encodedSize = 8;
 
+  ArrayOf.prototype.dimensions = function() {
+    return [this.length].concat(
+      (this.cls instanceof ArrayOf) ? this.cls.dimensions() : []);
+  }
+
   ArrayOf.prototype.decode = function(decoder) {
     return decoder.decodeArrayPointer(this.cls);
   };
@@ -710,6 +762,7 @@
   exports.MessageWithRequestIDBuilder = MessageWithRequestIDBuilder;
   exports.MessageReader = MessageReader;
   exports.kArrayHeaderSize = kArrayHeaderSize;
+  exports.kMapStructPayloadSize = kMapStructPayloadSize;
   exports.kStructHeaderSize = kStructHeaderSize;
   exports.kEncodedInvalidHandleValue = kEncodedInvalidHandleValue;
   exports.kMessageHeaderSize = kMessageHeaderSize;
diff --git a/mojo/public/js/bindings/struct_unittests.js b/mojo/public/js/bindings/struct_unittests.js
index 2d7abe5..b32b63a 100644
--- a/mojo/public/js/bindings/struct_unittests.js
+++ b/mojo/public/js/bindings/struct_unittests.js
@@ -5,10 +5,14 @@
 define([
     "gin/test/expect",
     "mojo/public/interfaces/bindings/tests/rect.mojom",
-    "mojo/public/interfaces/bindings/tests/test_structs.mojom"
+    "mojo/public/interfaces/bindings/tests/test_structs.mojom",
+    "mojo/public/js/bindings/codec",
+    "mojo/public/js/bindings/validator",
 ], function(expect,
             rect,
-            testStructs) {
+            testStructs,
+            codec,
+            validator) {
 
   function testConstructors() {
     var r = new rect.Rect();
@@ -93,9 +97,73 @@
     expect(s.f6).toEqual(10);
   }
 
+  function structEncodeDecode(struct) {
+    var structClass = struct.constructor;
+    var builder = new codec.MessageBuilder(1234, structClass.encodedSize);
+    builder.encodeStruct(structClass, struct);
+    var message = builder.finish();
+
+    var messageValidator = new validator.Validator(message);
+    var err = structClass.validate(messageValidator, codec.kMessageHeaderSize);
+    expect(err).toEqual(validator.validationError.NONE);
+
+    var reader = new codec.MessageReader(message);
+    return reader.decodeStruct(structClass);
+  }
+
+  function testMapKeyTypes() {
+    var mapFieldsStruct = new testStructs.MapKeyTypes({
+      f0: new Map([[true, false], [false, true]]),  // map<bool, bool>
+      f1: new Map([[0, 0], [1, 127], [-1, -128]]),  // map<int8, int8>
+      f2: new Map([[0, 0], [1, 127], [2, 255]]),  // map<uint8, uint8>
+      f3: new Map([[0, 0], [1, 32767], [2, -32768]]),  // map<int16, int16>
+      f4: new Map([[0, 0], [1, 32768], [2, 0xFFFF]]),  // map<uint16, uint16>
+      f5: new Map([[0, 0], [1, 32767], [2, -32768]]),  // map<int32, int32>
+      f6: new Map([[0, 0], [1, 32768], [2, 0xFFFF]]),  // map<uint32, uint32>
+      f7: new Map([[0, 0], [1, 32767], [2, -32768]]),  // map<int64, int64>
+      f8: new Map([[0, 0], [1, 32768], [2, 0xFFFF]]),  // map<uint64, uint64>
+      f9: new Map([[1000.5, -50000], [100.5, 5000]]),  // map<float, float>
+      f10: new Map([[-100.5, -50000], [0, 50000000]]),  // map<double, double>
+      f11: new Map([["one", "two"], ["free", "four"]]),  // map<string, string>
+    });
+    var decodedStruct = structEncodeDecode(mapFieldsStruct);
+    expect(decodedStruct.f0).toEqual(mapFieldsStruct.f0);
+    expect(decodedStruct.f1).toEqual(mapFieldsStruct.f1);
+    expect(decodedStruct.f2).toEqual(mapFieldsStruct.f2);
+    expect(decodedStruct.f3).toEqual(mapFieldsStruct.f3);
+    expect(decodedStruct.f4).toEqual(mapFieldsStruct.f4);
+    expect(decodedStruct.f5).toEqual(mapFieldsStruct.f5);
+    expect(decodedStruct.f6).toEqual(mapFieldsStruct.f6);
+    expect(decodedStruct.f7).toEqual(mapFieldsStruct.f7);
+    expect(decodedStruct.f8).toEqual(mapFieldsStruct.f8);
+    expect(decodedStruct.f9).toEqual(mapFieldsStruct.f9);
+    expect(decodedStruct.f10).toEqual(mapFieldsStruct.f10);
+    expect(decodedStruct.f11).toEqual(mapFieldsStruct.f11);
+  }
+
+  function testMapValueTypes() {
+    var mapFieldsStruct = new testStructs.MapValueTypes({
+      f0: new Map([["a", ["b", "c"]], ["d", ["e"]]]),  // array<string>>
+      f1: new Map([["a", null], ["b", ["c", "d"]]]),  // array<string>?>
+      f2: new Map([["a", [null]], ["b", [null, "d"]]]),  // array<string?>>
+      f3: new Map([["a", ["1", "2"]], ["b", ["1", "2"]]]),  // array<string,2>>
+      f4: new Map([["a", [["1"]]], ["b", [null]]]),  // array<array<string, 1>?>
+      f5: new Map([["a", [["1", "2"]]]]),  // array<array<string, 2>, 1>>
+    });
+    var decodedStruct = structEncodeDecode(mapFieldsStruct);
+    expect(decodedStruct.f0).toEqual(mapFieldsStruct.f0);
+    expect(decodedStruct.f1).toEqual(mapFieldsStruct.f1);
+    expect(decodedStruct.f2).toEqual(mapFieldsStruct.f2);
+    expect(decodedStruct.f3).toEqual(mapFieldsStruct.f3);
+    expect(decodedStruct.f4).toEqual(mapFieldsStruct.f4);
+    expect(decodedStruct.f5).toEqual(mapFieldsStruct.f5);
+  }
+
   testConstructors();
   testNoDefaultFieldValues();
   testDefaultFieldValues();
   testScopedConstants();
+  testMapKeyTypes();
+  testMapValueTypes();
   this.result = "PASS";
-});
\ No newline at end of file
+});
diff --git a/mojo/public/js/bindings/validator.js b/mojo/public/js/bindings/validator.js
index de75656..26759fd 100644
--- a/mojo/public/js/bindings/validator.js
+++ b/mojo/public/js/bindings/validator.js
@@ -19,7 +19,9 @@
     MESSAGE_HEADER_INVALID_FLAG_COMBINATION:
         'VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAG_COMBINATION',
     MESSAGE_HEADER_MISSING_REQUEST_ID:
-        'VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID'
+        'VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID',
+    DIFFERENT_SIZED_ARRAYS_IN_MAP:
+        'VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP',
   };
 
   var NULL_MOJO_POINTER = "NULL_MOJO_POINTER";
@@ -162,7 +164,8 @@
   }
 
   Validator.prototype.validateArrayPointer = function(
-      offset, elementSize, expectedElementCount, elementType, nullable) {
+      offset, elementSize, elementType, nullable, expectedDimensionSizes,
+      currentDimension) {
     var arrayOffset = this.decodePointer(offset);
     if (arrayOffset === null)
       return validationError.ILLEGAL_POINTER;
@@ -171,12 +174,12 @@
       return nullable ?
           validationError.NONE : validationError.UNEXPECTED_NULL_POINTER;
 
-    return this.validateArray(
-        arrayOffset, elementSize, expectedElementCount, elementType);
+    return this.validateArray(arrayOffset, elementSize, elementType,
+                              expectedDimensionSizes, currentDimension);
   }
 
   Validator.prototype.validateStructPointer = function(
-        offset, structClass, nullable) {
+      offset, structClass, nullable) {
     var structOffset = this.decodePointer(offset);
     if (structOffset === null)
       return validationError.ILLEGAL_POINTER;
@@ -188,16 +191,73 @@
     return structClass.validate(this, structOffset);
   }
 
+  // This method assumes that the array at arrayPointerOffset has
+  // been validated.
+
+  Validator.prototype.arrayLength = function(arrayPointerOffset) {
+    var arrayOffset = this.decodePointer(arrayPointerOffset);
+    return this.message.buffer.getUint32(arrayOffset + 4);
+  }
+
+  Validator.prototype.validateMapPointer = function(
+      offset, mapIsNullable, keyClass, valueClass, valueIsNullable) {
+    // Validate the implicit map struct:
+    // struct {array<keyClass> keys; array<valueClass> values};
+    var structOffset = this.decodePointer(offset);
+    if (structOffset === null)
+      return validationError.ILLEGAL_POINTER;
+
+    if (structOffset === NULL_MOJO_POINTER)
+      return mapIsNullable ?
+          validationError.NONE : validationError.UNEXPECTED_NULL_POINTER;
+
+    var mapEncodedSize = codec.kStructHeaderSize + codec.kMapStructPayloadSize;
+    var err = this.validateStructHeader(structOffset, mapEncodedSize, 2);
+    if (err !== validationError.NONE)
+        return err;
+
+    // Validate the keys array.
+    var keysArrayPointerOffset = structOffset + codec.kStructHeaderSize;
+    err = this.validateArrayPointer(
+        keysArrayPointerOffset, keyClass.encodedSize, keyClass, false, [0], 0);
+    if (err !== validationError.NONE)
+        return err;
+
+    // Validate the values array.
+    var valuesArrayPointerOffset = keysArrayPointerOffset + 8;
+    var valuesArrayDimensions = [0]; // Validate the actual length below.
+    if (valueClass instanceof codec.ArrayOf)
+      valuesArrayDimensions =
+          valuesArrayDimensions.concat(valueClass.dimensions());
+    var err = this.validateArrayPointer(valuesArrayPointerOffset,
+                                        valueClass.encodedSize,
+                                        valueClass,
+                                        valueIsNullable,
+                                        valuesArrayDimensions,
+                                        0);
+    if (err !== validationError.NONE)
+        return err;
+
+    // Validate the lengths of the keys and values arrays.
+    var keysArrayLength = this.arrayLength(keysArrayPointerOffset);
+    var valuesArrayLength = this.arrayLength(valuesArrayPointerOffset);
+    if (keysArrayLength != valuesArrayLength)
+      return validationError.DIFFERENT_SIZED_ARRAYS_IN_MAP;
+
+    return validationError.NONE;
+  }
+
   Validator.prototype.validateStringPointer = function(offset, nullable) {
     return this.validateArrayPointer(
-        offset, codec.Uint8.encodedSize, 0, codec.Uint8, nullable);
+        offset, codec.Uint8.encodedSize, codec.Uint8, nullable, [0], 0);
   }
 
   // Similar to Array_Data<T>::Validate()
   // mojo/public/cpp/bindings/lib/array_internal.h
 
   Validator.prototype.validateArray =
-      function (offset, elementSize, expectedElementCount, elementType) {
+      function (offset, elementSize, elementType, expectedDimensionSizes,
+                currentDimension) {
     if (!codec.isAligned(offset))
       return validationError.MISALIGNED_OBJECT;
 
@@ -215,8 +275,10 @@
     if (numBytes < codec.kArrayHeaderSize + elementsTotalSize)
       return validationError.UNEXPECTED_ARRAY_HEADER;
 
-    if (expectedElementCount != 0 && numElements != expectedElementCount)
+    if (expectedDimensionSizes[currentDimension] != 0 &&
+        numElements != expectedDimensionSizes[currentDimension]) {
       return validationError.UNEXPECTED_ARRAY_HEADER;
+    }
 
     if (!this.claimRange(offset, numBytes))
       return validationError.ILLEGAL_MEMORY_RANGE;
@@ -230,13 +292,14 @@
       return this.validateHandleElements(elementsOffset, numElements, nullable);
     if (isStringClass(elementType))
       return this.validateArrayElements(
-          elementsOffset, numElements, codec.Uint8, nullable)
+          elementsOffset, numElements, codec.Uint8, nullable, [0], 0);
     if (elementType instanceof codec.PointerTo)
       return this.validateStructElements(
           elementsOffset, numElements, elementType.cls, nullable);
     if (elementType instanceof codec.ArrayOf)
       return this.validateArrayElements(
-          elementsOffset, numElements, elementType.cls, nullable);
+          elementsOffset, numElements, elementType.cls, nullable,
+          expectedDimensionSizes, currentDimension + 1);
 
     return validationError.NONE;
   }
@@ -259,12 +322,14 @@
 
   // The elementClass parameter is the element type of the element arrays.
   Validator.prototype.validateArrayElements =
-      function(offset, numElements, elementClass, nullable) {
+      function(offset, numElements, elementClass, nullable,
+               expectedDimensionSizes, currentDimension) {
     var elementSize = codec.PointerTo.prototype.encodedSize;
     for (var i = 0; i < numElements; i++) {
       var elementOffset = offset + i * elementSize;
       var err = this.validateArrayPointer(
-          elementOffset, elementClass.encodedSize, 0, elementClass, nullable);
+          elementOffset, elementClass.encodedSize, elementClass, nullable,
+          expectedDimensionSizes, currentDimension);
       if (err != validationError.NONE)
         return err;
     }
diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl
index ea2750b..afdaf1a 100644
--- a/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl
+++ b/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl
@@ -52,7 +52,7 @@
 {#--- Sets #}
 {%   for param in parameters %}
 {%-     if param.kind|is_object_kind %}
-{%-       if param.kind|is_any_array_kind %}
+{%-       if param.kind|is_array_kind %}
   mojo::SerializeArray_<{{param.kind|get_array_validate_params|indent(24)}}>(
       mojo::internal::Forward(in_{{param.name}}), builder.buffer(), &params->{{param.name}}.ptr);
 {%-       elif param.kind|is_map_kind %}
diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl
index c65d3e4..623ebb4 100644
--- a/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl
+++ b/mojo/public/tools/bindings/generators/cpp_templates/struct_macros.tmpl
@@ -28,7 +28,7 @@
     ReportValidationError(mojo::internal::VALIDATION_ERROR_ILLEGAL_POINTER);
     return false;
   }
-{%-       if kind|is_any_array_kind or kind|is_string_kind %}
+{%-       if kind|is_array_kind or kind|is_string_kind %}
   if (!{{wrapper_type}}::Data_::Validate<
           {{kind|get_array_validate_params|indent(10)}}>(
               mojo::internal::DecodePointerRaw(&object->{{name}}.offset),
diff --git a/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl
index f765f20..1612bbe 100644
--- a/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl
+++ b/mojo/public/tools/bindings/generators/cpp_templates/struct_serialization_definition.tmpl
@@ -15,7 +15,7 @@
         internal::{{struct.name}}_Data::New(buf);
 {%- for pf in struct.packed.packed_fields %}
 {%-   if pf.field.kind|is_object_kind %}
-{%-     if pf.field.kind|is_any_array_kind %}
+{%-     if pf.field.kind|is_array_kind %}
     mojo::SerializeArray_<{{pf.field.kind|get_array_validate_params|indent(26)}}>(
         mojo::internal::Forward(input->{{pf.field.name}}), buf, &result->{{pf.field.name}}.ptr);
 {%-     elif pf.field.kind|is_map_kind %}
diff --git a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl
index cb5a5fa..da93e07 100644
--- a/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl
+++ b/mojo/public/tools/bindings/generators/cpp_templates/wrapper_class_definition.tmpl
@@ -18,7 +18,7 @@
 {{struct.name}}Ptr {{struct.name}}::Clone() const {
   {{struct.name}}Ptr rv(New());
 {%-   for field in struct.fields %}
-{%-     if field.kind|is_struct_kind or field.kind|is_any_array_kind or field.kind|is_map_kind %}
+{%-     if field.kind|is_struct_kind or field.kind|is_array_kind or field.kind|is_map_kind %}
   rv->{{field.name}} = {{field.name}}.Clone();
 {%-     else %}
   rv->{{field.name}} = {{field.name}};
diff --git a/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl
index d95a4d4..f187dc1 100644
--- a/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl
+++ b/mojo/public/tools/bindings/generators/java_templates/struct_definition.tmpl
@@ -1,12 +1,16 @@
 {% from "constant_definition.tmpl" import constant_def %}
 {% from "enum_definition.tmpl" import enum_def %}
 
-{% macro encode(variable, kind, offset, bit, level=0) %}
+{% macro encode(variable, kind, offset, bit, level=0, check_for_null=True) %}
 {% if kind|is_pointer_array_kind %}
 {% set sub_kind = kind.kind %}
+{%   if check_for_null %}
 if ({{variable}} == null) {
     encoder{{level}}.encodeNullPointer({{offset}}, {{kind|is_nullable_kind|java_true_false}});
 } else {
+{%   else %}
+{
+{%   endif %}
     org.chromium.mojo.bindings.Encoder encoder{{level + 1}} = encoder{{level}}.encodePointerArray({{variable}}.length, {{offset}}, {{kind|array_expected_length}});
     for (int i{{level}} = 0; i{{level}} < {{variable}}.length; ++i{{level}}) {
         {{encode(variable~'[i'~level~']', sub_kind, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i'~level, 0, level+1)|indent(8)}}
@@ -24,9 +28,10 @@
     for (java.util.Map.Entry<{{kind.key_kind|java_type(true)}}, {{kind.value_kind|java_type(true)}}> entry{{level}} : {{variable}}.entrySet()) {
         keys{{level}}[index{{level}}] = entry{{level}}.getKey();
         values{{level}}[index{{level}}] = entry{{level}}.getValue();
+        ++index{{level}};
     }
-    {{encode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1)|indent(4)}}
-    {{encode('values'~level, kind.value_kind|array, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1)|indent(4)}}
+    {{encode('keys'~level, kind.key_kind|array, 'DataHeader.HEADER_SIZE', 0, level+1, False)|indent(4)}}
+    {{encode('values'~level, kind.value_kind|array, 'DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE', 0, level+1, False)|indent(4)}}
 }
 {% else %}
 encoder{{level}}.{{kind|encode_method(variable, offset, bit)}};
@@ -39,9 +44,13 @@
 {%   if kind|is_struct_kind %}
 {{variable}} = {{kind|java_type}}.decode(decoder{{level+1}});
 {%   else %}{# kind|is_pointer_array_kind or is_map_kind #}
+{%     if kind|is_nullable_kind %}
 if (decoder{{level+1}} == null) {
     {{variable}} = null;
 } else {
+{%     else %}
+{
+{%     endif %}
 {%     if kind|is_map_kind %}
     decoder{{level+1}}.readDataHeaderForMap();
     {{kind.key_kind|java_type}}[] keys{{level}};
diff --git a/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl b/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl
index c0d8793..62b497c 100644
--- a/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl
+++ b/mojo/public/tools/bindings/generators/js_templates/struct_definition.tmpl
@@ -55,6 +55,10 @@
     // validate {{struct.name}}.{{field_name}}
     err = messageValidator.validateStructPointer({{packed_field|validate_struct_params}});
     {{check_err()}}
+{%-   elif packed_field.field|is_map_pointer_field %}
+    // validate {{struct.name}}.{{field_name}}
+    err = messageValidator.validateMapPointer({{packed_field|validate_map_params}});
+    {{check_err()}}
 {%-   elif packed_field.field|is_handle_field %}
     // validate {{struct.name}}.{{field_name}}
     err = messageValidator.validateHandle({{packed_field|validate_handle_params}})
diff --git a/mojo/public/tools/bindings/generators/mojom_cpp_generator.py b/mojo/public/tools/bindings/generators/mojom_cpp_generator.py
index c7fd50e..a2618a4 100644
--- a/mojo/public/tools/bindings/generators/mojom_cpp_generator.py
+++ b/mojo/public/tools/bindings/generators/mojom_cpp_generator.py
@@ -68,7 +68,7 @@
   return "::".join(parts)
 
 def GetCppType(kind):
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "mojo::internal::Array_Data<%s>*" % GetCppType(kind.kind)
   if mojom.IsMapKind(kind):
     return "mojo::internal::Map_Data<%s, %s>*" % (
@@ -93,7 +93,7 @@
     return GetNameForKind(kind)
   if mojom.IsStructKind(kind):
     return "%sPtr" % GetNameForKind(kind)
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "mojo::Array<%s> " % GetCppArrayArgWrapperType(kind.kind)
   if mojom.IsMapKind(kind):
     return "mojo::Map<%s, %s> " % (GetCppArrayArgWrapperType(kind.key_kind),
@@ -121,7 +121,7 @@
     return GetNameForKind(kind)
   if mojom.IsStructKind(kind):
     return "%sPtr" % GetNameForKind(kind)
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "mojo::Array<%s>" % GetCppArrayArgWrapperType(kind.kind)
   if mojom.IsMapKind(kind):
     return "mojo::Map<%s, %s>" % (GetCppArrayArgWrapperType(kind.key_kind),
@@ -149,7 +149,7 @@
     return GetNameForKind(kind)
   if mojom.IsStructKind(kind):
     return "%sPtr" % GetNameForKind(kind)
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "mojo::Array<%s>" % GetCppArrayArgWrapperType(kind.kind)
   if mojom.IsMapKind(kind):
     return "mojo::Map<%s, %s>" % (GetCppArrayArgWrapperType(kind.key_kind),
@@ -175,7 +175,7 @@
 def GetCppConstWrapperType(kind):
   if mojom.IsStructKind(kind):
     return "%sPtr" % GetNameForKind(kind)
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "mojo::Array<%s>" % GetCppArrayArgWrapperType(kind.kind)
   if mojom.IsMapKind(kind):
     return "mojo::Map<%s, %s>" % (GetCppArrayArgWrapperType(kind.key_kind),
@@ -206,7 +206,7 @@
   if mojom.IsStructKind(kind):
     return ("mojo::internal::StructPointer<%s_Data>" %
         GetNameForKind(kind, internal=True))
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "mojo::internal::ArrayPointer<%s>" % GetCppType(kind.kind)
   if mojom.IsMapKind(kind):
     return ("mojo::internal::StructPointer<mojo::internal::Map_Data<%s, %s>>" %
@@ -269,7 +269,7 @@
   return True
 
 def GetArrayValidateParams(kind):
-  if (not mojom.IsAnyArrayKind(kind) and not mojom.IsMapKind(kind) and
+  if (not mojom.IsArrayKind(kind) and not mojom.IsMapKind(kind) and
       not mojom.IsStringKind(kind)):
     return "mojo::internal::NoValidateParams"
 
@@ -282,7 +282,7 @@
     element_is_nullable = mojom.IsNullableKind(kind.value_kind)
     element_validate_params = GetArrayValidateParams(kind.value_kind)
   else:
-    expected_num_elements = generator.ExpectedArraySize(kind)
+    expected_num_elements = generator.ExpectedArraySize(kind) or 0
     element_is_nullable = mojom.IsNullableKind(kind.kind)
     element_validate_params = GetArrayValidateParams(kind.kind)
 
@@ -312,7 +312,6 @@
     "cpp_type": GetCppType,
     "cpp_wrapper_type": GetCppWrapperType,
     "default_value": DefaultValue,
-    "expected_array_size": generator.ExpectedArraySize,
     "expression_to_text": ExpressionToText,
     "get_array_validate_params": GetArrayValidateParams,
     "get_map_validate_params": GetMapValidateParams,
@@ -320,7 +319,7 @@
     "get_pad": pack.GetPad,
     "has_callbacks": mojom.HasCallbacks,
     "should_inline": ShouldInlineStruct,
-    "is_any_array_kind": mojom.IsAnyArrayKind,
+    "is_array_kind": mojom.IsArrayKind,
     "is_cloneable_kind": mojom.IsCloneableKind,
     "is_enum_kind": mojom.IsEnumKind,
     "is_move_only_kind": mojom.IsMoveOnlyKind,
diff --git a/mojo/public/tools/bindings/generators/mojom_java_generator.py b/mojo/public/tools/bindings/generators/mojom_java_generator.py
index 542b32e..4ee6ce3 100644
--- a/mojo/public/tools/bindings/generators/mojom_java_generator.py
+++ b/mojo/public/tools/bindings/generators/mojom_java_generator.py
@@ -151,7 +151,7 @@
     nullability information about both the array itself, as well as the array
     element type there.
     """
-    assert mojom.IsAnyArrayKind(kind)
+    assert mojom.IsArrayKind(kind)
     ARRAY_NULLABLE   = \
         'org.chromium.mojo.bindings.BindingsHelper.ARRAY_NULLABLE'
     ELEMENT_NULLABLE = \
@@ -176,15 +176,15 @@
   if (kind == mojom.BOOL):
     params.append(str(bit))
   if mojom.IsReferenceKind(kind):
-    if mojom.IsAnyArrayKind(kind):
+    if mojom.IsArrayKind(kind):
       params.append(GetArrayNullabilityFlags(kind))
     else:
       params.append(GetJavaTrueFalse(mojom.IsNullableKind(kind)))
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     params.append(GetArrayExpectedLength(kind))
   if mojom.IsInterfaceKind(kind):
     params.append('%s.MANAGER' % GetJavaType(context, kind))
-  if mojom.IsAnyArrayKind(kind) and mojom.IsInterfaceKind(kind.kind):
+  if mojom.IsArrayKind(kind) and mojom.IsInterfaceKind(kind.kind):
     params.append('%s.MANAGER' % GetJavaType(context, kind.kind))
   return params
 
@@ -192,7 +192,7 @@
 @contextfilter
 def DecodeMethod(context, kind, offset, bit):
   def _DecodeMethodName(kind):
-    if mojom.IsAnyArrayKind(kind):
+    if mojom.IsArrayKind(kind):
       return _DecodeMethodName(kind.kind) + 's'
     if mojom.IsEnumKind(kind):
       return _DecodeMethodName(mojom.INT32)
@@ -253,7 +253,7 @@
     return 'java.util.Map<%s, %s>' % (
         GetBoxedJavaType(context, kind.key_kind),
         GetBoxedJavaType(context, kind.value_kind))
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return '%s[]' % GetJavaType(context, kind.kind)
   if mojom.IsEnumKind(kind):
     return 'int'
@@ -277,7 +277,7 @@
 
 @contextfilter
 def NewArray(context, kind, size):
-  if mojom.IsAnyArrayKind(kind.kind):
+  if mojom.IsArrayKind(kind.kind):
     return NewArray(context, kind.kind, size) + '[]'
   return 'new %s[%s]' % (GetJavaType(context, kind.kind), size)
 
@@ -327,18 +327,18 @@
   if size is None:
     return mojom.Array(kind)
   else:
-    array = mojom.FixedArray(0, kind)
+    array = mojom.Array(kind, 0)
     array.java_map_size = size
     return array
 
 def GetArrayExpectedLength(kind):
-  if mojom.IsFixedArrayKind(kind):
+  if mojom.IsArrayKind(kind) and kind.length is not None:
     return getattr(kind, 'java_map_size', str(kind.length))
   else:
     return 'org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH'
 
 def IsPointerArrayKind(kind):
-  if not mojom.IsAnyArrayKind(kind):
+  if not mojom.IsArrayKind(kind):
     return False
   sub_kind = kind.kind
   return mojom.IsObjectKind(sub_kind)
@@ -403,7 +403,6 @@
     'encode_method': EncodeMethod,
     'has_method_with_response': HasMethodWithResponse,
     'has_method_without_response': HasMethodWithoutResponse,
-    'is_fixed_array_kind': mojom.IsFixedArrayKind,
     'is_handle': mojom.IsNonInterfaceHandleKind,
     'is_map_kind': mojom.IsMapKind,
     'is_nullable_kind': mojom.IsNullableKind,
diff --git a/mojo/public/tools/bindings/generators/mojom_js_generator.py b/mojo/public/tools/bindings/generators/mojom_js_generator.py
index c56561c..d1a6147 100644
--- a/mojo/public/tools/bindings/generators/mojom_js_generator.py
+++ b/mojo/public/tools/bindings/generators/mojom_js_generator.py
@@ -52,7 +52,9 @@
     return _kind_to_javascript_default_value[field.kind]
   if mojom.IsStructKind(field.kind):
     return "null"
-  if mojom.IsAnyArrayKind(field.kind):
+  if mojom.IsArrayKind(field.kind):
+    return "null"
+  if mojom.IsMapKind(field.kind):
     return "null"
   if mojom.IsInterfaceKind(field.kind) or \
      mojom.IsInterfaceRequestKind(field.kind):
@@ -105,26 +107,32 @@
     pointer_type = "NullablePointerTo" if mojom.IsNullableKind(kind) \
         else "PointerTo"
     return "new codec.%s(%s)" % (pointer_type, JavaScriptType(kind))
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     array_type = "NullableArrayOf" if mojom.IsNullableKind(kind) else "ArrayOf"
+    array_length = "" if kind.length is None else ", %d" % kind.length
     element_type = "codec.PackedBool" if mojom.IsBoolKind(kind.kind) \
         else CodecType(kind.kind)
-    return "new codec.%s(%s)" % (array_type, element_type)
+    return "new codec.%s(%s%s)" % (array_type, element_type, array_length)
   if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind):
     return CodecType(mojom.MSGPIPE)
   if mojom.IsEnumKind(kind):
     return _kind_to_codec_type[mojom.INT32]
   return kind
 
+def MapCodecType(kind):
+  return "codec.PackedBool" if mojom.IsBoolKind(kind) else CodecType(kind)
 
 def JavaScriptDecodeSnippet(kind):
   if kind in mojom.PRIMITIVES:
     return "decodeStruct(%s)" % CodecType(kind)
   if mojom.IsStructKind(kind):
     return "decodeStructPointer(%s)" % JavaScriptType(kind)
-  if mojom.IsAnyArrayKind(kind) and mojom.IsBoolKind(kind.kind):
+  if mojom.IsMapKind(kind):
+    return "decodeMapPointer(%s, %s)" % \
+        (MapCodecType(kind.key_kind), MapCodecType(kind.value_kind))
+  if mojom.IsArrayKind(kind) and mojom.IsBoolKind(kind.kind):
     return "decodeArrayPointer(codec.PackedBool)"
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "decodeArrayPointer(%s)" % CodecType(kind.kind)
   if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind):
     return JavaScriptDecodeSnippet(mojom.MSGPIPE)
@@ -137,9 +145,12 @@
     return "encodeStruct(%s, " % CodecType(kind)
   if mojom.IsStructKind(kind):
     return "encodeStructPointer(%s, " % JavaScriptType(kind)
-  if mojom.IsAnyArrayKind(kind) and mojom.IsBoolKind(kind.kind):
+  if mojom.IsMapKind(kind):
+    return "encodeMapPointer(%s, %s, " % \
+        (MapCodecType(kind.key_kind), MapCodecType(kind.value_kind))
+  if mojom.IsArrayKind(kind) and mojom.IsBoolKind(kind.kind):
     return "encodeArrayPointer(codec.PackedBool, ";
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return "encodeArrayPointer(%s, " % CodecType(kind.kind)
   if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind):
     return JavaScriptEncodeSnippet(mojom.MSGPIPE)
@@ -155,16 +166,29 @@
   return "true" if mojom.IsNullableKind(packed_field.field.kind) else "false"
 
 
+def GetArrayExpectedDimensionSizes(kind):
+  expected_dimension_sizes = []
+  while mojom.IsArrayKind(kind):
+    expected_dimension_sizes.append(generator.ExpectedArraySize(kind) or 0)
+    kind = kind.kind
+  # Strings are serialized as variable-length arrays.
+  if (mojom.IsStringKind(kind)):
+    expected_dimension_sizes.append(0)
+  return expected_dimension_sizes
+
+
 def JavaScriptValidateArrayParams(packed_field):
   nullable = JavaScriptNullableParam(packed_field)
   field_offset = JavaScriptFieldOffset(packed_field)
   element_kind = packed_field.field.kind.kind
   element_size = pack.PackedField.GetSizeForKind(element_kind)
-  element_count = generator.ExpectedArraySize(packed_field.field.kind)
+  expected_dimension_sizes = GetArrayExpectedDimensionSizes(
+      packed_field.field.kind)
   element_type = "codec.PackedBool" if mojom.IsBoolKind(element_kind) \
       else CodecType(element_kind)
-  return "%s, %s, %s, %s, %s" % \
-      (field_offset, element_size, element_count, element_type, nullable)
+  return "%s, %s, %s, %s, %s, 0" % \
+      (field_offset, element_size, element_type, nullable,
+       expected_dimension_sizes)
 
 
 def JavaScriptValidateStructParams(packed_field):
@@ -174,6 +198,17 @@
   return "%s, %s, %s" % (field_offset, struct_type, nullable)
 
 
+def JavaScriptValidateMapParams(packed_field):
+  nullable = JavaScriptNullableParam(packed_field)
+  field_offset = JavaScriptFieldOffset(packed_field)
+  keys_type = MapCodecType(packed_field.field.kind.key_kind)
+  values_kind = packed_field.field.kind.value_kind;
+  values_type = MapCodecType(values_kind)
+  values_nullable = "true" if mojom.IsNullableKind(values_kind) else "false"
+  return "%s, %s, %s, %s, %s" % \
+      (field_offset, nullable, keys_type, values_type, values_nullable)
+
+
 def JavaScriptValidateStringParams(packed_field):
   nullable = JavaScriptNullableParam(packed_field)
   return "%s, %s" % (JavaScriptFieldOffset(packed_field), nullable)
@@ -216,7 +251,7 @@
 
 
 def IsArrayPointerField(field):
-  return mojom.IsAnyArrayKind(field.kind)
+  return mojom.IsArrayKind(field.kind)
 
 def IsStringPointerField(field):
   return mojom.IsStringKind(field.kind)
@@ -224,6 +259,9 @@
 def IsStructPointerField(field):
   return mojom.IsStructKind(field.kind)
 
+def IsMapPointerField(field):
+  return mojom.IsMapKind(field.kind)
+
 def IsHandleField(field):
   return mojom.IsAnyHandleKind(field.kind)
 
@@ -239,6 +277,7 @@
     "field_offset": JavaScriptFieldOffset,
     "has_callbacks": mojom.HasCallbacks,
     "is_array_pointer_field": IsArrayPointerField,
+    "is_map_pointer_field": IsMapPointerField,
     "is_struct_pointer_field": IsStructPointerField,
     "is_string_pointer_field": IsStringPointerField,
     "is_handle_field": IsHandleField,
@@ -246,6 +285,7 @@
     "stylize_method": generator.StudlyCapsToCamel,
     "validate_array_params": JavaScriptValidateArrayParams,
     "validate_handle_params": JavaScriptValidateHandleParams,
+    "validate_map_params": JavaScriptValidateMapParams,
     "validate_string_params": JavaScriptValidateStringParams,
     "validate_struct_params": JavaScriptValidateStructParams,
   }
diff --git a/mojo/public/tools/bindings/generators/mojom_python_generator.py b/mojo/public/tools/bindings/generators/mojom_python_generator.py
index 684eda2..db5e8b6 100644
--- a/mojo/public/tools/bindings/generators/mojom_python_generator.py
+++ b/mojo/public/tools/bindings/generators/mojom_python_generator.py
@@ -128,7 +128,7 @@
   return '.'.join(name)
 
 def GetFieldType(kind, field=None):
-  if mojom.IsAnyArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     arguments = []
     if kind.kind in _kind_to_typecode_for_native_array:
       arguments.append('%r' %_kind_to_typecode_for_native_array[kind.kind])
@@ -136,7 +136,7 @@
       arguments.append(GetFieldType(kind.kind))
     if mojom.IsNullableKind(kind):
       arguments.append('nullable=True')
-    if mojom.IsFixedArrayKind(kind):
+    if kind.length is not None:
       arguments.append('length=%d' % kind.length)
     array_type = 'GenericArrayType'
     if kind.kind == mojom.BOOL:
diff --git a/mojo/public/tools/bindings/pylib/mojom/generate/data.py b/mojo/public/tools/bindings/pylib/mojom/generate/data.py
index 829f3b2..85c9105 100644
--- a/mojo/public/tools/bindings/pylib/mojom/generate/data.py
+++ b/mojo/public/tools/bindings/pylib/mojom/generate/data.py
@@ -121,6 +121,10 @@
     kind = KindFromData(kinds, data[1:], scope).MakeNullableKind()
   elif data.startswith('a:'):
     kind = mojom.Array(KindFromData(kinds, data[2:], scope))
+  elif data.startswith('a'):
+    colon = data.find(':')
+    length = int(data[1:colon])
+    kind = mojom.Array(KindFromData(kinds, data[colon+1:], scope), length)
   elif data.startswith('r:'):
     kind = mojom.InterfaceRequest(KindFromData(kinds, data[2:], scope))
   elif data.startswith('m['):
@@ -129,10 +133,6 @@
     second_kind = data[data.rfind('[')+1:data.rfind(']')]
     kind = mojom.Map(KindFromData(kinds, first_kind, scope),
                      KindFromData(kinds, second_kind, scope))
-  elif data.startswith('a'):
-    colon = data.find(':')
-    length = int(data[1:colon])
-    kind = mojom.FixedArray(length, KindFromData(kinds, data[colon+1:], scope))
   else:
     kind = mojom.Kind(data)
 
diff --git a/mojo/public/tools/bindings/pylib/mojom/generate/generator.py b/mojo/public/tools/bindings/pylib/mojom/generate/generator.py
index 4f7f86e..af14ead 100644
--- a/mojo/public/tools/bindings/pylib/mojom/generate/generator.py
+++ b/mojo/public/tools/bindings/pylib/mojom/generate/generator.py
@@ -36,9 +36,9 @@
   return struct
 
 def ExpectedArraySize(kind):
-  if mojom.IsFixedArrayKind(kind):
+  if mojom.IsArrayKind(kind):
     return kind.length
-  return 0
+  return None
 
 def StudlyCapsToCamel(studly):
   return studly[0].lower() + studly[1:]
diff --git a/mojo/public/tools/bindings/pylib/mojom/generate/module.py b/mojo/public/tools/bindings/pylib/mojom/generate/module.py
index 4f87b35..24b4959 100644
--- a/mojo/public/tools/bindings/pylib/mojom/generate/module.py
+++ b/mojo/public/tools/bindings/pylib/mojom/generate/module.py
@@ -206,22 +206,16 @@
 
 class Array(ReferenceKind):
   ReferenceKind.AddSharedProperty('kind')
-
-  def __init__(self, kind=None):
-    if kind is not None:
-      ReferenceKind.__init__(self, 'a:' + kind.spec)
-    else:
-      ReferenceKind.__init__(self)
-    self.kind = kind
-
-
-class FixedArray(ReferenceKind):
-  ReferenceKind.AddSharedProperty('kind')
   ReferenceKind.AddSharedProperty('length')
 
-  def __init__(self, length=-1, kind=None):
+  def __init__(self, kind=None, length=None):
     if kind is not None:
-      ReferenceKind.__init__(self, 'a%d:%s' % (length, kind.spec))
+      if length is not None:
+        spec = 'a%d:%s' % (length, kind.spec)
+      else:
+        spec = 'a:%s' % kind.spec
+
+      ReferenceKind.__init__(self, spec)
     else:
       ReferenceKind.__init__(self)
     self.kind = kind
@@ -246,7 +240,7 @@
         raise Exception("Structs can not be keys in maps.")
       if IsAnyHandleKind(key_kind):
         raise Exception("Handles can not be keys in maps.")
-      if IsAnyArrayKind(key_kind):
+      if IsArrayKind(key_kind):
         raise Exception("Arrays can not be keys in maps.")
     else:
       ReferenceKind.__init__(self)
@@ -348,7 +342,8 @@
     self.interfaces = []
 
   def AddInterface(self, name):
-    self.interfaces.append(Interface(name, module=self))
+    interface = Interface(name, module=self)
+    self.interfaces.append(interface)
     return interface
 
   def AddStruct(self, name):
@@ -398,10 +393,6 @@
   return isinstance(kind, Array)
 
 
-def IsFixedArrayKind(kind):
-  return isinstance(kind, FixedArray)
-
-
 def IsInterfaceKind(kind):
   return isinstance(kind, Interface)
 
@@ -422,16 +413,12 @@
   return IsReferenceKind(kind) and kind.is_nullable
 
 
-def IsAnyArrayKind(kind):
-  return IsArrayKind(kind) or IsFixedArrayKind(kind)
-
-
 def IsMapKind(kind):
   return isinstance(kind, Map)
 
 
 def IsObjectKind(kind):
-  return (IsStructKind(kind) or IsAnyArrayKind(kind) or IsStringKind(kind) or
+  return (IsStructKind(kind) or IsArrayKind(kind) or IsStringKind(kind) or
           IsMapKind(kind))
 
 
@@ -461,7 +448,7 @@
     visited_kinds.add(kind)
     if IsAnyHandleKind(kind):
       return True
-    if IsAnyArrayKind(kind):
+    if IsArrayKind(kind):
       return ContainsHandles(kind.kind, visited_kinds)
     if IsStructKind(kind):
       for field in kind.fields:
diff --git a/mojo/public/tools/bindings/pylib/mojom/generate/pack.py b/mojo/public/tools/bindings/pylib/mojom/generate/pack.py
index 50b7098..8f7bb3b 100644
--- a/mojo/public/tools/bindings/pylib/mojom/generate/pack.py
+++ b/mojo/public/tools/bindings/pylib/mojom/generate/pack.py
@@ -40,8 +40,7 @@
 
   @classmethod
   def GetSizeForKind(cls, kind):
-    if isinstance(kind, (mojom.Array, mojom.Map, mojom.Struct,
-                         mojom.FixedArray)):
+    if isinstance(kind, (mojom.Array, mojom.Map, mojom.Struct)):
       return 8
     if isinstance(kind, mojom.Interface) or \
        isinstance(kind, mojom.InterfaceRequest):
diff --git a/mojo/public/tools/bindings/pylib/mojom/generate/pack_tests.py b/mojo/public/tools/bindings/pylib/mojom/generate/pack_tests.py
index a0f664b..14f699d 100644
--- a/mojo/public/tools/bindings/pylib/mojom/generate/pack_tests.py
+++ b/mojo/public/tools/bindings/pylib/mojom/generate/pack_tests.py
@@ -95,7 +95,7 @@
            mojom.DCPIPE.MakeNullableKind(),
            mojom.Array().MakeNullableKind(),
            mojom.DPPIPE.MakeNullableKind(),
-           mojom.FixedArray(5).MakeNullableKind(),
+           mojom.Array(length=5).MakeNullableKind(),
            mojom.MSGPIPE.MakeNullableKind(),
            mojom.Interface('test_inteface').MakeNullableKind(),
            mojom.SHAREDBUFFER.MakeNullableKind(),
diff --git a/mojo/public/tools/bindings/pylib/mojom/parse/translate.py b/mojo/public/tools/bindings/pylib/mojom/parse/translate.py
index 958b0c4..d87d5fd 100644
--- a/mojo/public/tools/bindings/pylib/mojom/parse/translate.py
+++ b/mojo/public/tools/bindings/pylib/mojom/parse/translate.py
@@ -5,8 +5,6 @@
 """Translates parse tree to Mojom IR."""
 
 
-import re
-
 from . import ast
 
 
@@ -16,8 +14,6 @@
     return []
   return [func(subtree) for subtree in tree if isinstance(subtree, type_to_map)]
 
-_FIXED_ARRAY_REGEXP = re.compile(r'\[[0-9]+\]')
-
 def _MapKind(kind):
   map_to_kind = {'bool': 'b',
                  'int8': 'i8',
@@ -49,16 +45,9 @@
     lbracket = kind.rfind('{')
     value = kind[0:lbracket]
     return 'm[' + _MapKind(kind[lbracket+1:-1]) + '][' + _MapKind(value) + ']'
-  if kind.endswith('[]'):
-    typename = kind[0:-2]
-    if _FIXED_ARRAY_REGEXP.search(typename):
-      raise Exception('Arrays of fixed sized arrays not supported')
-    return 'a:' + _MapKind(typename)
   if kind.endswith(']'):
     lbracket = kind.rfind('[')
     typename = kind[0:lbracket]
-    if typename.find('[') != -1:
-      raise Exception('Fixed sized arrays of arrays not supported')
     return 'a' + kind[lbracket+1:-1] + ':' + _MapKind(typename)
   if kind.endswith('&'):
     return 'r:' + _MapKind(kind[0:-1])
diff --git a/mojo/public/tools/bindings/pylib/mojom_tests/parse/parser_unittest.py b/mojo/public/tools/bindings/pylib/mojom_tests/parse/parser_unittest.py
index 9218b3d..b27217a 100644
--- a/mojo/public/tools/bindings/pylib/mojom_tests/parse/parser_unittest.py
+++ b/mojo/public/tools/bindings/pylib/mojom_tests/parse/parser_unittest.py
@@ -617,6 +617,7 @@
           array<int32> normal_array;
           array<int32, 1> fixed_size_array_one_entry;
           array<int32, 10> fixed_size_array_ten_entries;
+          array<array<array<int32, 1>>, 2> nested_arrays;
         };
         """
     expected = ast.Mojom(
@@ -630,7 +631,9 @@
                  ast.StructField('fixed_size_array_one_entry', None, 'int32[1]',
                                  None),
                  ast.StructField('fixed_size_array_ten_entries', None,
-                                 'int32[10]', None)]))])
+                                 'int32[10]', None),
+                 ast.StructField('nested_arrays', None,
+                                 'int32[1][][2]', None)]))])
     self.assertEquals(parser.Parse(source, "my_file.mojom"), expected)
 
   def testValidNestedArray(self):
diff --git a/mojo/services/BUILD.gn b/mojo/services/BUILD.gn
index 537fb49..fdddd3d 100644
--- a/mojo/services/BUILD.gn
+++ b/mojo/services/BUILD.gn
@@ -8,6 +8,7 @@
   deps = [
     "//mojo/services/clipboard",
     "//mojo/services/gles2:lib",
+    "//mojo/services/html_viewer",
     "//mojo/services/network",
     "//mojo/services/public/interfaces/clipboard",
     "//mojo/services/public/interfaces/content_handler",
diff --git a/mojo/services/clipboard/clipboard_standalone_impl.cc b/mojo/services/clipboard/clipboard_standalone_impl.cc
index e1c7e2c..404eded 100644
--- a/mojo/services/clipboard/clipboard_standalone_impl.cc
+++ b/mojo/services/clipboard/clipboard_standalone_impl.cc
@@ -1,12 +1,12 @@
-// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Copyright 2014 The Chromium 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 "mojo/services/clipboard/clipboard_standalone_impl.h"
 
-namespace mojo {
+#include <string.h>
 
-typedef std::vector<uint8_t> ByteVector;
+namespace mojo {
 
 // ClipboardData contains data copied to the Clipboard for a variety of formats.
 // It mostly just provides APIs to cleanly access and manipulate this data.
@@ -15,35 +15,25 @@
   ClipboardData() {}
   ~ClipboardData() {}
 
-  std::vector<std::string> GetMimeTypes() const {
-    std::vector<std::string> types;
-    for (std::map<std::string, ByteVector>::const_iterator it =
-             data_types_.begin();
-         it != data_types_.end();
-         ++it) {
-      types.push_back(it->first);
-    }
+  Array<String> GetMimeTypes() const {
+    Array<String> types(data_types_.size());
+    int i = 0;
+    for (auto it = data_types_.begin(); it != data_types_.end(); ++it, ++i)
+      types[i] = it.GetKey();
 
-    return types;
+    return types.Pass();
   }
 
-  void SetData(std::map<std::string, ByteVector>* data) {
-    std::swap(data_types_, *data);
-  }
+  void SetData(Map<String, Array<uint8_t>> data) { data_types_ = data.Pass(); }
 
-  bool GetData(const std::string& mime_type, ByteVector* data) const {
-    std::map<std::string, ByteVector>::const_iterator it =
-        data_types_.find(mime_type);
-    if (it != data_types_.end()) {
-      *data = it->second;
-      return true;
-    }
-
-    return false;
+  void GetData(const String& mime_type, mojo::Array<uint8_t>* data) const {
+    auto it = data_types_.find(mime_type);
+    if (it != data_types_.end())
+      *data = it.GetValue().Clone();
   }
 
  private:
-  std::map<std::string, ByteVector> data_types_;
+  Map<String, Array<uint8_t>> data_types_;
 
   DISALLOW_COPY_AND_ASSIGN(ClipboardData);
 };
@@ -67,34 +57,23 @@
 void ClipboardStandaloneImpl::GetAvailableMimeTypes(
     Clipboard::Type clipboard_type,
     const mojo::Callback<void(mojo::Array<mojo::String>)>& callback) {
-  mojo::Array<mojo::String> types = mojo::Array<mojo::String>::From(
-      clipboard_state_[clipboard_type]->GetMimeTypes());
-  callback.Run(types.Pass());
+  callback.Run(clipboard_state_[clipboard_type]->GetMimeTypes().Pass());
 }
 
 void ClipboardStandaloneImpl::ReadMimeType(
     Clipboard::Type clipboard_type,
     const mojo::String& mime_type,
     const mojo::Callback<void(mojo::Array<uint8_t>)>& callback) {
-  ByteVector mime_data;
-  if (clipboard_state_[clipboard_type]->GetData(
-          mime_type.To<std::string>(), &mime_data)) {
-    callback.Run(mojo::Array<uint8_t>::From(mime_data).Pass());
-    return;
-  }
-
-  callback.Run(mojo::Array<uint8_t>().Pass());
+  mojo::Array<uint8_t> mime_data;
+  clipboard_state_[clipboard_type]->GetData(mime_type, &mime_data);
+  callback.Run(mime_data.Pass());
 }
 
 void ClipboardStandaloneImpl::WriteClipboardData(
     Clipboard::Type clipboard_type,
-    mojo::Array<MimeTypePairPtr> data) {
-  std::map<std::string, ByteVector> mime_data;
-  for (size_t i = 0; i < data.size(); ++i)
-    mime_data[data[i]->mime_type] = data[i]->data;
-
+    mojo::Map<mojo::String, mojo::Array<uint8_t>> data) {
   sequence_number_[clipboard_type]++;
-  clipboard_state_[clipboard_type]->SetData(&mime_data);
+  clipboard_state_[clipboard_type]->SetData(data.Pass());
 }
 
 }  // namespace mojo
diff --git a/mojo/services/clipboard/clipboard_standalone_impl.h b/mojo/services/clipboard/clipboard_standalone_impl.h
index 09d7424..ccb8c54 100644
--- a/mojo/services/clipboard/clipboard_standalone_impl.h
+++ b/mojo/services/clipboard/clipboard_standalone_impl.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Copyright 2014 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
@@ -38,8 +38,9 @@
       Clipboard::Type clipboard_type,
       const mojo::String& mime_type,
       const mojo::Callback<void(mojo::Array<uint8_t>)>& callback) override;
-  virtual void WriteClipboardData(Clipboard::Type clipboard_type,
-                                  mojo::Array<MimeTypePairPtr> data) override;
+  virtual void WriteClipboardData(
+      Clipboard::Type clipboard_type,
+      mojo::Map<mojo::String, mojo::Array<uint8_t>> data) override;
 
  private:
   uint64_t sequence_number_[kNumClipboards];
diff --git a/mojo/services/clipboard/clipboard_standalone_unittest.cc b/mojo/services/clipboard/clipboard_standalone_unittest.cc
index c297b94..cdf0087 100644
--- a/mojo/services/clipboard/clipboard_standalone_unittest.cc
+++ b/mojo/services/clipboard/clipboard_standalone_unittest.cc
@@ -1,4 +1,4 @@
-// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Copyright 2014 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
@@ -89,11 +89,8 @@
   }
 
   void SetStringText(const std::string& data) {
-    Array<MimeTypePairPtr> mime_data;
-    MimeTypePairPtr text_data(MimeTypePair::New());
-    text_data->mime_type = mojo::Clipboard::MIME_TYPE_TEXT;
-    text_data->data = Array<uint8_t>::From(data).Pass();
-    mime_data.push_back(text_data.Pass());
+    Map<String, Array<uint8_t>> mime_data;
+    mime_data[mojo::Clipboard::MIME_TYPE_TEXT] = Array<uint8_t>::From(data);
     clipboard_->WriteClipboardData(mojo::Clipboard::TYPE_COPY_PASTE,
                                    mime_data.Pass());
   }
@@ -127,16 +124,11 @@
 }
 
 TEST_F(ClipboardStandaloneTest, CanSetMultipleDataTypesAtOnce) {
-  Array<MimeTypePairPtr> mime_data;
-  MimeTypePairPtr text_data(MimeTypePair::New());
-  text_data->mime_type = mojo::Clipboard::MIME_TYPE_TEXT;
-  text_data->data = Array<uint8_t>::From(std::string(kPlainTextData)).Pass();
-  mime_data.push_back(text_data.Pass());
-
-  MimeTypePairPtr html_data(MimeTypePair::New());
-  html_data->mime_type = mojo::Clipboard::MIME_TYPE_HTML;
-  html_data->data = Array<uint8_t>::From(std::string(kHtmlData)).Pass();
-  mime_data.push_back(html_data.Pass());
+  Map<String, Array<uint8_t>> mime_data;
+  mime_data[mojo::Clipboard::MIME_TYPE_TEXT] =
+      Array<uint8_t>::From(std::string(kPlainTextData));
+  mime_data[mojo::Clipboard::MIME_TYPE_HTML] =
+      Array<uint8_t>::From(std::string(kHtmlData));
 
   clipboard_->WriteClipboardData(mojo::Clipboard::TYPE_COPY_PASTE,
                                  mime_data.Pass());
@@ -150,22 +142,6 @@
   EXPECT_EQ(kHtmlData, data);
 }
 
-TEST_F(ClipboardStandaloneTest, CanClearClipboardWithNull) {
-  std::string data;
-  SetStringText(kPlainTextData);
-  EXPECT_EQ(1ul, GetSequenceNumber());
-
-  EXPECT_TRUE(GetDataOfType(mojo::Clipboard::MIME_TYPE_TEXT, &data));
-  EXPECT_EQ(kPlainTextData, data);
-
-  Array<MimeTypePairPtr> mime_data;
-  clipboard_->WriteClipboardData(mojo::Clipboard::TYPE_COPY_PASTE,
-                                 mime_data.Pass());
-
-  EXPECT_EQ(2ul, GetSequenceNumber());
-  EXPECT_FALSE(GetDataOfType(mojo::Clipboard::MIME_TYPE_TEXT, &data));
-}
-
 TEST_F(ClipboardStandaloneTest, CanClearClipboardWithZeroArray) {
   std::string data;
   SetStringText(kPlainTextData);
@@ -174,7 +150,7 @@
   EXPECT_TRUE(GetDataOfType(mojo::Clipboard::MIME_TYPE_TEXT, &data));
   EXPECT_EQ(kPlainTextData, data);
 
-  Array<MimeTypePairPtr> mime_data(0);
+  Map<String, Array<uint8_t>> mime_data;
   clipboard_->WriteClipboardData(mojo::Clipboard::TYPE_COPY_PASTE,
                                  mime_data.Pass());
 
diff --git a/mojo/services/html_viewer/html_viewer.cc b/mojo/services/html_viewer/html_viewer.cc
index ebde85f..a26651a 100644
--- a/mojo/services/html_viewer/html_viewer.cc
+++ b/mojo/services/html_viewer/html_viewer.cc
@@ -41,7 +41,7 @@
  private:
   // Overridden from ContentHandler:
   virtual void OnConnect(
-      const mojo::String& url,
+      const mojo::String& requestor_url,
       URLResponsePtr response,
       InterfaceRequest<ServiceProvider> service_provider_request) override {
     new HTMLDocumentView(response.Pass(),
diff --git a/mojo/services/html_viewer/webclipboard_impl.cc b/mojo/services/html_viewer/webclipboard_impl.cc
index 94b16ca..9b7ebff 100644
--- a/mojo/services/html_viewer/webclipboard_impl.cc
+++ b/mojo/services/html_viewer/webclipboard_impl.cc
@@ -168,11 +168,8 @@
 }
 
 void WebClipboardImpl::writePlainText(const blink::WebString& text) {
-  Array<MimeTypePairPtr> data;
-  MimeTypePairPtr text_data(MimeTypePair::New());
-  text_data->mime_type = mojo::Clipboard::MIME_TYPE_TEXT;
-  text_data->data = Array<uint8_t>::From(text).Pass();
-  data.push_back(text_data.Pass());
+  Map<String, Array<uint8_t>> data;
+  data[mojo::Clipboard::MIME_TYPE_TEXT] = Array<uint8_t>::From(text);
 
   clipboard_->WriteClipboardData(mojo::Clipboard::TYPE_COPY_PASTE, data.Pass());
 }
@@ -181,28 +178,13 @@
                                  const blink::WebURL& url,
                                  const blink::WebString& plainText,
                                  bool writeSmartPaste) {
-  Array<MimeTypePairPtr> data;
-  MimeTypePairPtr text_data(MimeTypePair::New());
-  text_data->mime_type = mojo::Clipboard::MIME_TYPE_TEXT;
-  text_data->data = Array<uint8_t>::From(plainText).Pass();
-  data.push_back(text_data.Pass());
+  Map<String, Array<uint8_t>> data;
+  data[mojo::Clipboard::MIME_TYPE_TEXT] = Array<uint8_t>::From(plainText);
+  data[mojo::Clipboard::MIME_TYPE_HTML] = Array<uint8_t>::From(htmlText);
+  data[mojo::Clipboard::MIME_TYPE_URL] = Array<uint8_t>::From(url.string());
 
-  MimeTypePairPtr html_data(MimeTypePair::New());
-  text_data->mime_type = mojo::Clipboard::MIME_TYPE_HTML;
-  text_data->data = Array<uint8_t>::From(htmlText).Pass();
-  data.push_back(html_data.Pass());
-
-  MimeTypePairPtr url_data(MimeTypePair::New());
-  url_data->mime_type = mojo::Clipboard::MIME_TYPE_URL;
-  url_data->data = Array<uint8_t>::From(url.string()).Pass();
-  data.push_back(url_data.Pass());
-
-  if (writeSmartPaste) {
-    MimeTypePairPtr smart_paste(MimeTypePair::New());
-    url_data->mime_type = kMimeTypeWebkitSmartPaste;
-    url_data->data = Array<uint8_t>::From(blink::WebString()).Pass();
-    data.push_back(smart_paste.Pass());
-  }
+  if (writeSmartPaste)
+    data[kMimeTypeWebkitSmartPaste] = Array<uint8_t>::From(blink::WebString());
 
   clipboard_->WriteClipboardData(mojo::Clipboard::TYPE_COPY_PASTE, data.Pass());
 }
diff --git a/mojo/services/native_viewport/android/src/org/chromium/mojo/PlatformViewportAndroid.java b/mojo/services/native_viewport/android/src/org/chromium/mojo/PlatformViewportAndroid.java
index c3f8075..4a7d96e 100644
--- a/mojo/services/native_viewport/android/src/org/chromium/mojo/PlatformViewportAndroid.java
+++ b/mojo/services/native_viewport/android/src/org/chromium/mojo/PlatformViewportAndroid.java
@@ -76,16 +76,16 @@
 
     private static native void nativeDestroy(long nativePlatformViewportAndroid);
     private static native void nativeSurfaceCreated(
-        long nativePlatformViewportAndroid, Surface surface);
+            long nativePlatformViewportAndroid, Surface surface);
     private static native void nativeSurfaceDestroyed(
-        long nativePlatformViewportAndroid);
+            long nativePlatformViewportAndroid);
     private static native void nativeSurfaceSetSize(
-        long nativePlatformViewportAndroid,
-        int width, int height);
+            long nativePlatformViewportAndroid,
+            int width, int height);
     private static native boolean nativeTouchEvent(
-        long nativePlatformViewportAndroid,
-        int pointerId,
-        int action,
-        float x, float y,
-        long timeMs);
+            long nativePlatformViewportAndroid,
+            int pointerId,
+            int action,
+            float x, float y,
+            long timeMs);
 };
diff --git a/mojo/services/network/net_address_type_converters.cc b/mojo/services/network/net_address_type_converters.cc
index 573c0ff..31dc9d9 100644
--- a/mojo/services/network/net_address_type_converters.cc
+++ b/mojo/services/network/net_address_type_converters.cc
@@ -4,8 +4,6 @@
 
 #include "mojo/services/network/net_address_type_converters.h"
 
-#include "base/sys_byteorder.h"
-
 namespace mojo {
 
 // static
@@ -18,14 +16,12 @@
     case NET_ADDRESS_FAMILY_IPV4:
       if (!obj->ipv4)
         break;
-      return net::IPEndPoint(
-          obj->ipv4->addr.storage(), base::NetToHost16(obj->ipv4->port));
+      return net::IPEndPoint(obj->ipv4->addr.storage(), obj->ipv4->port);
 
     case NET_ADDRESS_FAMILY_IPV6:
       if (!obj->ipv6)
         break;
-      return net::IPEndPoint(
-          obj->ipv6->addr.storage(), base::NetToHost16(obj->ipv6->port));
+      return net::IPEndPoint(obj->ipv6->addr.storage(), obj->ipv6->port);
 
     default:
       break;
@@ -43,15 +39,13 @@
     case net::ADDRESS_FAMILY_IPV4:
       net_address->family = NET_ADDRESS_FAMILY_IPV4;
       net_address->ipv4 = NetAddressIPv4::New();
-      net_address->ipv4->port =
-          base::HostToNet16(static_cast<uint16>(obj.port()));
+      net_address->ipv4->port = static_cast<uint16>(obj.port());
       net_address->ipv4->addr = Array<uint8_t>::From(obj.address());
       break;
     case NET_ADDRESS_FAMILY_IPV6:
       net_address->ipv6 = NetAddressIPv6::New();
       net_address->family = NET_ADDRESS_FAMILY_IPV6;
-      net_address->ipv6->port =
-          base::HostToNet16(static_cast<uint16>(obj.port()));
+      net_address->ipv6->port = static_cast<uint16>(obj.port());
       net_address->ipv6->addr = Array<uint8_t>::From(obj.address());
       break;
     default:
diff --git a/mojo/services/public/cpp/native_viewport/lib/args.cc b/mojo/services/public/cpp/native_viewport/lib/args.cc
index 7831cad..cf0617d 100644
--- a/mojo/services/public/cpp/native_viewport/lib/args.cc
+++ b/mojo/services/public/cpp/native_viewport/lib/args.cc
@@ -8,8 +8,8 @@
 
 // Loads an app from the specified directory and launches it.
 // Force gl to be initialized in test mode.
-const char kUseTestConfig[] = "use-test-config";
+const char kUseTestConfig[] = "--use-test-config";
 // Create native viewport in headless mode.
-const char kUseHeadlessConfig[] = "use-headless-config";
+const char kUseHeadlessConfig[] = "--use-headless-config";
 
 }  // namespace mojo
diff --git a/mojo/services/public/interfaces/clipboard/clipboard.mojom b/mojo/services/public/interfaces/clipboard/clipboard.mojom
index eca47b9..92ef822 100644
--- a/mojo/services/public/interfaces/clipboard/clipboard.mojom
+++ b/mojo/services/public/interfaces/clipboard/clipboard.mojom
@@ -4,13 +4,6 @@
 
 module mojo {
 
-// A wrapper type which is just a Key/Value pair. Workaround until we get
-// proper maps in mojom.
-struct MimeTypePair {
-  string mime_type;
-  array<uint8> data;
-};
-
 interface Clipboard {
   enum Type {
     COPY_PASTE = 0,
@@ -44,9 +37,9 @@
   ReadMimeType(Type clipboard_type, string mime_type) => (array<uint8>? data);
 
   // Writes a set of mime types to the clipboard. This will increment the
-  // sequence number. In the case of an empty or NULL list, this will just
+  // sequence number. In the case of an empty or null map, this will just
   // clear the clipboard.
-  WriteClipboardData(Type clipboard_type, array<MimeTypePair>? data);
+  WriteClipboardData(Type clipboard_type, map<string, array<uint8>>? data);
 };
 
 }  // module mojo
diff --git a/mojo/services/public/interfaces/content_handler/content_handler.mojom b/mojo/services/public/interfaces/content_handler/content_handler.mojom
index 4383401..b9c1c04 100644
--- a/mojo/services/public/interfaces/content_handler/content_handler.mojom
+++ b/mojo/services/public/interfaces/content_handler/content_handler.mojom
@@ -8,7 +8,7 @@
 module mojo {
 
 interface ContentHandler {
-  OnConnect(string url,
+  OnConnect(string requestor_url,
             URLResponse response,
             ServiceProvider&? service_provider);
 };
diff --git a/mojo/services/public/interfaces/network/net_address.mojom b/mojo/services/public/interfaces/network/net_address.mojom
index a358e9e..d858242 100644
--- a/mojo/services/public/interfaces/network/net_address.mojom
+++ b/mojo/services/public/interfaces/network/net_address.mojom
@@ -10,17 +10,22 @@
   IPV6
 };
 
-// All members are expressed in network byte order, i.e., the most significant
-// byte is stored in the smallest address. For example, if we store 127.0.0.1 in
-// |addr|, 127 should be at index 0.
 struct NetAddressIPv4 {
+  // The port number. This is in the local machine's endianness.
   uint16 port;
+
+  // The address is expressed in network byte order, so the most significant
+  // byte ("127" in the address "127.0.0.1") will be at index 0.
   array<uint8, 4> addr;
 };
 
 // All members are expressed in network byte order.
 struct NetAddressIPv6 {
+  // The port number. This is in the local machine's endianness.
   uint16 port;
+
+  // The address is expressed in network byte order, so the most significant
+  // byte is at index 0.
   array<uint8, 16> addr;
 };
 
diff --git a/mojo/services/public/interfaces/network/udp_socket.mojom b/mojo/services/public/interfaces/network/udp_socket.mojom
index 526a454..0816ace 100644
--- a/mojo/services/public/interfaces/network/udp_socket.mojom
+++ b/mojo/services/public/interfaces/network/udp_socket.mojom
@@ -25,7 +25,7 @@
 
   // Binds the socket to the given address.
   // |bound_addr| is non-NULL on success. It might not be the same as |addr|.
-  // For example, if port 0 is used in |addr|, a random port is picked and
+  // For example, if port 0 is used in |addr|, an available port is picked and
   // returned in |bound_addr|.
   Bind(NetAddress addr) => (NetworkError result, NetAddress? bound_addr);
 
diff --git a/mojo/services/public/interfaces/surfaces/quads.mojom b/mojo/services/public/interfaces/surfaces/quads.mojom
index 6d5cccd..7625faa 100644
--- a/mojo/services/public/interfaces/surfaces/quads.mojom
+++ b/mojo/services/public/interfaces/surfaces/quads.mojom
@@ -28,7 +28,8 @@
 
   // If nonzero, resource id of mask to use when drawing this pass.
   uint32 mask_resource_id;
-  RectF mask_uv_rect;
+  PointF mask_uv_scale;
+  Size mask_texture_size;
 
   // Post-processing filters, applied to the pixels in the render pass' texture.
   // TODO(jamesr): Support
diff --git a/mojo/services/window_manager/BUILD.gn b/mojo/services/window_manager/BUILD.gn
index 02f3a8e..98a8b36 100644
--- a/mojo/services/window_manager/BUILD.gn
+++ b/mojo/services/window_manager/BUILD.gn
@@ -40,21 +40,18 @@
   ]
   deps = [
     "//base",
-    "//mojo/application",
-    "//mojo/common",
-    "//mojo/converters/input_events",
-    "//mojo/environment:chromium",
-    "//mojo/public/cpp/bindings",
-    "//mojo/public/interfaces/application:application",
-    "//mojo/services/public/cpp/view_manager",
-    "//mojo/services/public/interfaces/window_manager",
-    "//mojo/services/public/interfaces/window_manager2",
-    "//ui/aura",
     "//ui/base",
-    "//ui/events",
     "//ui/gfx",
     "//ui/gfx/geometry",
     "//ui/wm",
+    "//mojo/aura",
+    "//mojo/application",
+    "//mojo/common",
+    "//mojo/converters/input_events",
+    "//mojo/services/public/cpp/view_manager",
+    "//mojo/public/interfaces/application:application",
+    "//mojo/services/public/interfaces/window_manager",
+    "//mojo/services/public/interfaces/window_manager2",
   ]
 }
 
diff --git a/mojo/views/BUILD.gn b/mojo/views/BUILD.gn
index 506a7ed..af47764 100644
--- a/mojo/views/BUILD.gn
+++ b/mojo/views/BUILD.gn
@@ -7,7 +7,7 @@
 assert(use_aura)
 
 # GYP version: mojo/mojo.gyp:mojo_views_support
-source_set("views") {
+static_library("views") {
   sources = [
     "input_method_mojo_linux.cc",
     "input_method_mojo_linux.h",
@@ -26,36 +26,14 @@
   ]
 
   deps = [
-    ":views_internal",
-    "//base",
-    "//base:i18n",
-    "//third_party/icu",
-    "//ui/aura",
-    "//ui/wm",
-  ]
-}
-
-# GYP version: mojo/mojo.gyp:mojo_views_support_internal
-component("views_internal") {
-  output_name = "mojo_views_support_internal"
-
-  visibility = [ ":views" ]
-
-  sources = [
-    "mojo_views_export.h",
-    "views_init_internal.cc",
-    "views_init_internal.h",
-  ]
-
-  defines = [ "MOJO_VIEWS_IMPLEMENTATION" ]
-
-  deps = [
     "//base",
     "//base:i18n",
     "//base/third_party/dynamic_annotations",
     "//skia",
     "//third_party/icu",
+    "//ui/aura",
     "//ui/base",
     "//ui/gfx",
+    "//ui/wm",
   ]
 }
diff --git a/mojo/views/mojo_views_export.h b/mojo/views/mojo_views_export.h
deleted file mode 100644
index 0ca8985..0000000
--- a/mojo/views/mojo_views_export.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef MOJO_VIEWS_MOJO_VIEWS_EXPORT_H_
-#define MOJO_VIEWS_MOJO_VIEWS_EXPORT_H_
-
-#if defined(COMPONENT_BUILD)
-#if defined(WIN32)
-
-#if defined(MOJO_VIEWS_IMPLEMENTATION)
-#define MOJO_VIEWS_EXPORT __declspec(dllexport)
-#else
-#define MOJO_VIEWS_EXPORT __declspec(dllimport)
-#endif  // defined(MOJO_VIEWS_IMPLEMENTATION)
-
-#else  // defined(WIN32)
-#if defined(MOJO_VIEWS_IMPLEMENTATION)
-#define MOJO_VIEWS_EXPORT __attribute__((visibility("default")))
-#else
-#define MOJO_VIEWS_EXPORT
-#endif
-#endif
-
-#else  // defined(COMPONENT_BUILD)
-#define MOJO_VIEWS_EXPORT
-#endif
-
-#endif  // MOJO_VIEWS_MOJO_VIEWS_EXPORT_H_
diff --git a/mojo/views/views_init.cc b/mojo/views/views_init.cc
index edd8af3..fa2ef54 100644
--- a/mojo/views/views_init.cc
+++ b/mojo/views/views_init.cc
@@ -4,10 +4,46 @@
 
 #include "mojo/views/views_init.h"
 
-#include "mojo/views/views_init_internal.h"
+#include "base/i18n/icu_util.h"
+#include "base/lazy_instance.h"
+#include "base/path_service.h"
+#include "ui/base/resource/resource_bundle.h"
+#include "ui/base/ui_base_paths.h"
 
 namespace mojo {
+namespace {
 
+// Used to ensure we only init once.
+class Setup {
+ public:
+  Setup() {
+    base::i18n::InitializeICU();
+
+    ui::RegisterPathProvider();
+
+    base::FilePath ui_test_pak_path;
+    CHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
+    ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
+
+    // There is a bunch of static state in gfx::Font, by running this now,
+    // before any other apps load, we ensure all the state is set up.
+    gfx::Font();
+  }
+
+  ~Setup() {
+  }
+
+ private:
+  DISALLOW_COPY_AND_ASSIGN(Setup);
+};
+
+static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
+
+}  // namespace
+
+void InitViews() {
+  setup.Get();
+}
 ViewsInit::ViewsInit() {
   InitViews();
 }
diff --git a/mojo/views/views_init_internal.cc b/mojo/views/views_init_internal.cc
deleted file mode 100644
index 6d92c7c..0000000
--- a/mojo/views/views_init_internal.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2014 The Chromium 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 "mojo/views/views_init_internal.h"
-
-#include "base/i18n/icu_util.h"
-#include "base/lazy_instance.h"
-#include "base/path_service.h"
-#include "ui/base/resource/resource_bundle.h"
-#include "ui/base/ui_base_paths.h"
-
-namespace mojo {
-
-namespace {
-
-// Used to ensure we only init once.
-class Setup {
- public:
-  Setup() {
-    base::i18n::InitializeICU();
-
-    ui::RegisterPathProvider();
-
-    base::FilePath ui_test_pak_path;
-    CHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
-    ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
-
-    // There is a bunch of static state in gfx::Font, by running this now,
-    // before any other apps load, we ensure all the state is set up.
-    gfx::Font();
-  }
-
-  ~Setup() {
-  }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(Setup);
-};
-
-static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-void InitViews() {
-  setup.Get();
-}
-
-}  // namespace mojo
diff --git a/mojo/views/views_init_internal.h b/mojo/views/views_init_internal.h
deleted file mode 100644
index 5ec66e7..0000000
--- a/mojo/views/views_init_internal.h
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef MOJO_VIEWS_VIEWS_INIT_INTERNAL_H_
-#define MOJO_VIEWS_VIEWS_INIT_INTERNAL_H_
-
-#include "mojo/views/mojo_views_export.h"
-
-namespace mojo {
-
-// This is in a separate target so that we only initialize some common state
-// once.
-// Do not use this, it is called internally by ViewsInit.
-MOJO_VIEWS_EXPORT void InitViews();
-
-}  // namespace mojo
-
-#endif  // MOJO_VIEWS_VIEWS_INIT_INTERNAL_H_
diff --git a/net/BUILD.gn b/net/BUILD.gn
index 81d59c8..3dcfa6b 100644
--- a/net/BUILD.gn
+++ b/net/BUILD.gn
@@ -551,8 +551,6 @@
   ]
 }
 
-if (false) {
-
 static_library("extras") {
   sources = gypi_values.net_extras_sources
   configs += [ "//build/config/compiler:wexit_time_destructors" ]
@@ -562,8 +560,6 @@
   ]
 }
 
-} # if (false)
-
 static_library("http_server") {
   sources = [
     "server/http_connection.cc",
@@ -1107,14 +1103,11 @@
 test("net_unittests") {
   sources = gypi_values.net_test_sources
 
-  sources -= [
-    "extras/sqlite/sqlite_channel_id_store_unittest.cc",
-  ]
-
   configs += [ ":net_win_size_truncation" ]
   defines = []
 
   deps = [
+    ":extras",
     ":http_server",
     ":net",
     ":quic_tools",
diff --git a/net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java b/net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java
index 472c0f7..6b91318 100644
--- a/net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java
+++ b/net/android/java/src/org/chromium/net/AndroidNetworkLibrary.java
@@ -245,12 +245,10 @@
      */
     @CalledByNative
     private static String getNetworkCountryIso(Context context) {
-      TelephonyManager telephonyManager =
-          (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
-      if (telephonyManager != null) {
+        TelephonyManager telephonyManager =
+                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+        if (telephonyManager == null) return "";
         return telephonyManager.getNetworkCountryIso();
-      }
-      return "";
     }
 
     /**
@@ -259,12 +257,10 @@
      */
     @CalledByNative
     private static String getNetworkOperator(Context context) {
-      TelephonyManager telephonyManager =
-          (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
-      if (telephonyManager != null) {
+        TelephonyManager telephonyManager =
+                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+        if (telephonyManager == null) return "";
         return telephonyManager.getNetworkOperator();
-      }
-      return "";
     }
 
 }
diff --git a/net/android/java/src/org/chromium/net/DefaultAndroidKeyStore.java b/net/android/java/src/org/chromium/net/DefaultAndroidKeyStore.java
index 3ee1029..60f910c 100644
--- a/net/android/java/src/org/chromium/net/DefaultAndroidKeyStore.java
+++ b/net/android/java/src/org/chromium/net/DefaultAndroidKeyStore.java
@@ -83,7 +83,7 @@
         return null;
     }
 
-   @Override
+    @Override
     public byte[] getPrivateKeyEncodedBytes(AndroidPrivateKey key) {
         PrivateKey javaKey = ((DefaultAndroidPrivateKey) key).getJavaKey();
         return javaKey.getEncoded();
diff --git a/net/android/java/src/org/chromium/net/ProxyChangeListener.java b/net/android/java/src/org/chromium/net/ProxyChangeListener.java
index be09be4..68cc329 100644
--- a/net/android/java/src/org/chromium/net/ProxyChangeListener.java
+++ b/net/android/java/src/org/chromium/net/ProxyChangeListener.java
@@ -142,18 +142,16 @@
                 }
                 // TODO(xunjieli): rewrite this once the API is public.
                 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
-                    Method getPacFileUrlMethod =
-                        cls.getDeclaredMethod(getPacFileUrl);
+                    Method getPacFileUrlMethod = cls.getDeclaredMethod(getPacFileUrl);
                     String pacFileUrl = (String) getPacFileUrlMethod.invoke(props);
                     if (!TextUtils.isEmpty(pacFileUrl)) {
-                       return new ProxyConfig(host, port, pacFileUrl, exclusionList);
+                        return new ProxyConfig(host, port, pacFileUrl, exclusionList);
                     }
                 } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
-                    Method getPacFileUrlMethod =
-                        cls.getDeclaredMethod(getPacFileUrl);
+                    Method getPacFileUrlMethod = cls.getDeclaredMethod(getPacFileUrl);
                     Uri pacFileUrl = (Uri) getPacFileUrlMethod.invoke(props);
                     if (!Uri.EMPTY.equals(pacFileUrl)) {
-                      return new ProxyConfig(host, port, pacFileUrl.toString(), exclusionList);
+                        return new ProxyConfig(host, port, pacFileUrl.toString(), exclusionList);
                     }
                 }
                 return new ProxyConfig(host, port, null, exclusionList);
diff --git a/net/android/java/src/org/chromium/net/RemoteAndroidKeyStore.java b/net/android/java/src/org/chromium/net/RemoteAndroidKeyStore.java
index d0da2c4..3d22d71 100644
--- a/net/android/java/src/org/chromium/net/RemoteAndroidKeyStore.java
+++ b/net/android/java/src/org/chromium/net/RemoteAndroidKeyStore.java
@@ -52,7 +52,7 @@
             e.printStackTrace();
             return null;
         }
-     }
+    }
 
     @Override
     public byte[] getDSAKeyParamQ(AndroidPrivateKey key) {
diff --git a/net/android/java/src/org/chromium/net/X509Util.java b/net/android/java/src/org/chromium/net/X509Util.java
index 35ebdb7..3f6c70d 100644
--- a/net/android/java/src/org/chromium/net/X509Util.java
+++ b/net/android/java/src/org/chromium/net/X509Util.java
@@ -332,15 +332,14 @@
     private static boolean isKnownRoot(X509Certificate root)
             throws NoSuchAlgorithmException, KeyStoreException {
         // Could not find the system key store. Conservatively report false.
-        if (sSystemKeyStore == null)
-            return false;
+        if (sSystemKeyStore == null) return false;
 
         // Check the in-memory cache first; avoid decoding the anchor from disk
         // if it has been seen before.
-        Pair<X500Principal, PublicKey> key =
-            new Pair<X500Principal, PublicKey>(root.getSubjectX500Principal(), root.getPublicKey());
-        if (sSystemTrustAnchorCache.contains(key))
-            return true;
+        Pair<X500Principal, PublicKey> key = new Pair<X500Principal, PublicKey>(
+                root.getSubjectX500Principal(), root.getPublicKey());
+
+        if (sSystemTrustAnchorCache.contains(key)) return true;
 
         // Note: It is not sufficient to call sSystemKeyStore.getCertificiateAlias. If the server
         // supplies a copy of a trust anchor, X509TrustManagerExtensions returns the server's
@@ -355,16 +354,14 @@
         String hash = hashPrincipal(root.getSubjectX500Principal());
         for (int i = 0; true; i++) {
             String alias = hash + '.' + i;
-            if (!new File(sSystemCertificateDirectory, alias).exists())
-                break;
+            if (!new File(sSystemCertificateDirectory, alias).exists()) break;
 
             Certificate anchor = sSystemKeyStore.getCertificate("system:" + alias);
             // It is possible for this to return null if the user deleted a trust anchor. In
             // that case, the certificate remains in the system directory but is also added to
             // another file. Continue iterating as there may be further collisions after the
             // deleted anchor.
-            if (anchor == null)
-                continue;
+            if (anchor == null) continue;
 
             if (!(anchor instanceof X509Certificate)) {
                 // This should never happen.
@@ -376,7 +373,7 @@
             // If the subject and public key match, this is a system root.
             X509Certificate anchorX509 = (X509Certificate) anchor;
             if (root.getSubjectX500Principal().equals(anchorX509.getSubjectX500Principal()) &&
-                root.getPublicKey().equals(anchorX509.getPublicKey())) {
+                    root.getPublicKey().equals(anchorX509.getPublicKey())) {
                 sSystemTrustAnchorCache.add(key);
                 return true;
             }
@@ -405,14 +402,13 @@
             // See http://crbug.com/233610
             return false;
         }
-        if (ekuOids == null)
-            return true;
+        if (ekuOids == null) return true;
 
         for (String ekuOid : ekuOids) {
             if (ekuOid.equals(OID_TLS_SERVER_AUTH) ||
-                ekuOid.equals(OID_ANY_EKU) ||
-                ekuOid.equals(OID_SERVER_GATED_NETSCAPE) ||
-                ekuOid.equals(OID_SERVER_GATED_MICROSOFT)) {
+                    ekuOid.equals(OID_ANY_EKU) ||
+                    ekuOid.equals(OID_SERVER_GATED_NETSCAPE) ||
+                    ekuOid.equals(OID_SERVER_GATED_MICROSOFT)) {
                 return true;
             }
         }
@@ -509,7 +505,7 @@
      * Record histograms on the platform's certificate verification capabilities.
      */
     private static native void nativeRecordCertVerifyCapabilitiesHistogram(
-        boolean foundSystemTrustRoots);
+            boolean foundSystemTrustRoots);
 
     /**
      * Returns the application context.
diff --git a/net/android/javatests/src/org/chromium/net/X509UtilTest.java b/net/android/javatests/src/org/chromium/net/X509UtilTest.java
index 612f886..075ce95 100644
--- a/net/android/javatests/src/org/chromium/net/X509UtilTest.java
+++ b/net/android/javatests/src/org/chromium/net/X509UtilTest.java
@@ -22,7 +22,7 @@
  */
 public class X509UtilTest extends InstrumentationTestCase {
     private static final String CERTS_DIRECTORY =
-        PathUtils.getExternalStorageDirectory() + "/net/data/ssl/certificates/";
+            PathUtils.getExternalStorageDirectory() + "/net/data/ssl/certificates/";
     private static final String BAD_EKU_TEST_ROOT = "eku-test-root.pem";
     private static final String CRITICAL_CODE_SIGNING_EE = "crit-codeSigning-chain.pem";
     private static final String NON_CRITICAL_CODE_SIGNING_EE = "non-crit-codeSigning-chain.pem";
@@ -74,20 +74,20 @@
         X509Util.addTestRootCertificate(pemToDer(CERTS_DIRECTORY + GOOD_ROOT_CA));
 
         assertFalse(X509Util.verifyKeyUsage(
-            X509Util.createCertificateFromBytes(
-                pemToDer(CERTS_DIRECTORY + CRITICAL_CODE_SIGNING_EE))));
+                X509Util.createCertificateFromBytes(
+                        pemToDer(CERTS_DIRECTORY + CRITICAL_CODE_SIGNING_EE))));
 
         assertFalse(X509Util.verifyKeyUsage(
-            X509Util.createCertificateFromBytes(
-                pemToDer(CERTS_DIRECTORY + NON_CRITICAL_CODE_SIGNING_EE))));
+                X509Util.createCertificateFromBytes(
+                        pemToDer(CERTS_DIRECTORY + NON_CRITICAL_CODE_SIGNING_EE))));
 
         assertFalse(X509Util.verifyKeyUsage(
-            X509Util.createCertificateFromBytes(
-                readFileBytes(CERTS_DIRECTORY + WEB_CLIENT_AUTH_EE))));
+                X509Util.createCertificateFromBytes(
+                        readFileBytes(CERTS_DIRECTORY + WEB_CLIENT_AUTH_EE))));
 
         assertTrue(X509Util.verifyKeyUsage(
-            X509Util.createCertificateFromBytes(
-                pemToDer(CERTS_DIRECTORY + OK_CERT))));
+                X509Util.createCertificateFromBytes(
+                        pemToDer(CERTS_DIRECTORY + OK_CERT))));
 
         try {
             X509Util.clearTestRootCertificates();
diff --git a/net/base/address_list_unittest.cc b/net/base/address_list_unittest.cc
index 32c3e52..e559788 100644
--- a/net/base/address_list_unittest.cc
+++ b/net/base/address_list_unittest.cc
@@ -121,7 +121,7 @@
 
   // Construct a list of ip addresses.
   IPAddressList ip_list;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     IPAddressNumber ip_number;
     ASSERT_TRUE(ParseIPLiteralToNumber(tests[i].ip_address, &ip_number));
     ip_list.push_back(ip_number);
@@ -131,7 +131,7 @@
                                                                kCanonicalName);
   std::string canonical_name;
   EXPECT_EQ(kCanonicalName, test_list.canonical_name());
-  EXPECT_EQ(ARRAYSIZE_UNSAFE(tests), test_list.size());
+  EXPECT_EQ(arraysize(tests), test_list.size());
 }
 
 }  // namespace
diff --git a/net/base/escape.cc b/net/base/escape.cc
index 7ce21a1..1798b6c 100644
--- a/net/base/escape.cc
+++ b/net/base/escape.cc
@@ -244,7 +244,7 @@
     { '\'', "&#39;" },
   };
   size_t k;
-  for (k = 0; k < ARRAYSIZE_UNSAFE(kCharsToEscape); ++k) {
+  for (k = 0; k < arraysize(kCharsToEscape); ++k) {
     if (c == kCharsToEscape[k].key) {
       const char* p = kCharsToEscape[k].replacement;
       while (*p)
@@ -252,7 +252,7 @@
       break;
     }
   }
-  if (k == ARRAYSIZE_UNSAFE(kCharsToEscape))
+  if (k == arraysize(kCharsToEscape))
     output->push_back(c);
 }
 
@@ -385,14 +385,14 @@
   if (input.find(base::ASCIIToUTF16("&")) == std::string::npos)
     return input;
 
-  base::string16 ampersand_chars[ARRAYSIZE_UNSAFE(kEscapeToChars)];
+  base::string16 ampersand_chars[arraysize(kEscapeToChars)];
   base::string16 text(input);
   for (base::string16::iterator iter = text.begin();
        iter != text.end(); ++iter) {
     if (*iter == '&') {
       // Potential ampersand encode char.
       size_t index = iter - text.begin();
-      for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEscapeToChars); i++) {
+      for (size_t i = 0; i < arraysize(kEscapeToChars); i++) {
         if (ampersand_chars[i].empty()) {
           ampersand_chars[i] =
               base::ASCIIToUTF16(kEscapeToChars[i].ampersand_code);
diff --git a/net/base/file_stream_context.cc b/net/base/file_stream_context.cc
index 3e2c2e5..b242eba 100644
--- a/net/base/file_stream_context.cc
+++ b/net/base/file_stream_context.cc
@@ -7,6 +7,7 @@
 #include "base/files/file_path.h"
 #include "base/location.h"
 #include "base/message_loop/message_loop_proxy.h"
+#include "base/profiler/scoped_profile.h"
 #include "base/task_runner.h"
 #include "base/task_runner_util.h"
 #include "base/threading/thread_restrictions.h"
@@ -149,6 +150,11 @@
 
 FileStream::Context::OpenResult FileStream::Context::OpenFileImpl(
     const base::FilePath& path, int open_flags) {
+  // TODO(vadimt): Remove ScopedProfile below once crbug.com/423948 is fixed.
+  tracked_objects::ScopedProfile tracking_profile(
+      FROM_HERE_WITH_EXPLICIT_FUNCTION(
+          "423948 FileStream::Context::OpenFileImpl"));
+
 #if defined(OS_POSIX)
   // Always use blocking IO.
   open_flags &= ~base::File::FLAG_ASYNC;
@@ -195,8 +201,14 @@
 void FileStream::Context::OnOpenCompleted(const CompletionCallback& callback,
                                           OpenResult open_result) {
   file_ = open_result.file.Pass();
-  if (file_.IsValid() && !orphaned_)
+  if (file_.IsValid() && !orphaned_) {
+    // TODO(vadimt): Remove ScopedProfile below once crbug.com/423948 is fixed.
+    tracked_objects::ScopedProfile tracking_profile(
+        FROM_HERE_WITH_EXPLICIT_FUNCTION(
+            "423948 FileStream::Context::OnOpenCompleted"));
+
     OnFileOpened();
+  }
 
   OnAsyncCompleted(IntToInt64(callback), open_result.error_code);
 }
diff --git a/net/base/filename_util_unittest.cc b/net/base/filename_util_unittest.cc
index 2201033..965169a 100644
--- a/net/base/filename_util_unittest.cc
+++ b/net/base/filename_util_unittest.cc
@@ -183,7 +183,7 @@
 
   // First, we'll test that we can round-trip all of the above cases of URLs
   base::FilePath output;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(round_trip_cases); i++) {
+  for (size_t i = 0; i < arraysize(round_trip_cases); i++) {
     // convert to the file URL
     GURL file_url(FilePathToFileURL(
                       WStringAsFilePath(round_trip_cases[i].file)));
@@ -228,7 +228,7 @@
     //{L"/foo%5Cbar.txt", "file://foo\\bar.txt"},
 #endif
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(url_cases); i++) {
+  for (size_t i = 0; i < arraysize(url_cases); i++) {
     FileURLToFilePath(GURL(url_cases[i].url), &output);
     EXPECT_EQ(url_cases[i].file, FilePathAsWString(output));
   }
@@ -409,7 +409,7 @@
 #endif  // !defined(OS_WIN)
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(safe_tests); ++i) {
+  for (size_t i = 0; i < arraysize(safe_tests); ++i) {
     base::FilePath file_path(safe_tests[i].filename);
     GenerateSafeFileName(safe_tests[i].mime_type, false, &file_path);
     EXPECT_EQ(safe_tests[i].expected_filename, file_path.value())
@@ -1651,13 +1651,13 @@
 #endif
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(selection_tests); ++i)
+  for (size_t i = 0; i < arraysize(selection_tests); ++i)
     RunGenerateFileNameTestCase(&selection_tests[i]);
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(generation_tests); ++i)
+  for (size_t i = 0; i < arraysize(generation_tests); ++i)
     RunGenerateFileNameTestCase(&generation_tests[i]);
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(generation_tests); ++i) {
+  for (size_t i = 0; i < arraysize(generation_tests); ++i) {
     GenerateFilenameCase test_case = generation_tests[i];
     test_case.referrer_charset = "GBK";
     RunGenerateFileNameTestCase(&test_case);
diff --git a/net/base/ip_endpoint_unittest.cc b/net/base/ip_endpoint_unittest.cc
index f10e8e9..5698cc4 100644
--- a/net/base/ip_endpoint_unittest.cc
+++ b/net/base/ip_endpoint_unittest.cc
@@ -29,7 +29,7 @@
   { "::1", "[::1]", true },
   { "2001:db8:0::42", "[2001:db8::42]", true },
 };
-int test_count = ARRAYSIZE_UNSAFE(tests);
+int test_count = arraysize(tests);
 
 class IPEndPointTest : public PlatformTest {
  public:
diff --git a/net/base/mime_util_unittest.cc b/net/base/mime_util_unittest.cc
index 08a3dfd..49c4661 100644
--- a/net/base/mime_util_unittest.cc
+++ b/net/base/mime_util_unittest.cc
@@ -33,7 +33,7 @@
   std::string mime_type;
   bool rv;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     rv = GetMimeTypeFromExtension(tests[i].extension, &mime_type);
     EXPECT_EQ(tests[i].valid, rv);
     if (rv)
@@ -58,7 +58,7 @@
   std::string mime_type;
   bool rv;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     rv = GetMimeTypeFromFile(base::FilePath(tests[i].file_path),
                                   &mime_type);
     EXPECT_EQ(tests[i].valid, rv);
@@ -274,7 +274,7 @@
     { ",",                          2, { "", "" }             },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::vector<std::string> codecs_out;
     ParseCodecString(tests[i].original, &codecs_out, true);
     ASSERT_EQ(tests[i].expected_size, codecs_out.size());
@@ -401,7 +401,7 @@
     { "aUDIo/*",    6, "wav" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::vector<base::FilePath::StringType> extensions;
     GetExtensionsForMimeType(tests[i].mime_type, &extensions);
     ASSERT_TRUE(tests[i].min_expected_size <= extensions.size());
diff --git a/net/base/net_log_logger.cc b/net/base/net_log_logger.cc
index 0c0f1c9..76b5b32 100644
--- a/net/base/net_log_logger.cc
+++ b/net/base/net_log_logger.cc
@@ -117,7 +117,7 @@
   {
     base::DictionaryValue* dict = new base::DictionaryValue();
 
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kCertStatusFlags); i++)
+    for (size_t i = 0; i < arraysize(kCertStatusFlags); i++)
       dict->SetInteger(kCertStatusFlags[i].name, kCertStatusFlags[i].constant);
 
     constants_dict->Set("certStatusFlag", dict);
@@ -128,7 +128,7 @@
   {
     base::DictionaryValue* dict = new base::DictionaryValue();
 
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kLoadFlags); i++)
+    for (size_t i = 0; i < arraysize(kLoadFlags); i++)
       dict->SetInteger(kLoadFlags[i].name, kLoadFlags[i].constant);
 
     constants_dict->Set("loadFlag", dict);
@@ -139,7 +139,7 @@
   {
     base::DictionaryValue* dict = new base::DictionaryValue();
 
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kLoadStateTable); i++)
+    for (size_t i = 0; i < arraysize(kLoadStateTable); i++)
       dict->SetInteger(kLoadStateTable[i].name, kLoadStateTable[i].constant);
 
     constants_dict->Set("loadState", dict);
@@ -150,7 +150,7 @@
   {
     base::DictionaryValue* dict = new base::DictionaryValue();
 
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kNetErrors); i++)
+    for (size_t i = 0; i < arraysize(kNetErrors); i++)
       dict->SetInteger(ErrorToShortString(kNetErrors[i]), kNetErrors[i]);
 
     constants_dict->Set("netError", dict);
diff --git a/net/base/net_util_icu_unittest.cc b/net/base/net_util_icu_unittest.cc
index 9beb434..d92b9d1 100644
--- a/net/base/net_util_icu_unittest.cc
+++ b/net/base/net_util_icu_unittest.cc
@@ -411,7 +411,7 @@
 }  // anonymous namespace
 
 TEST(NetUtilTest, IDNToUnicodeFast) {
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(idn_cases); i++) {
+  for (size_t i = 0; i < arraysize(idn_cases); i++) {
     for (size_t j = 0; j < arraysize(kLanguages); j++) {
       // ja || zh-TW,en || ko,ja -> IDNToUnicodeSlow
       if (j == 3 || j == 17 || j == 18)
@@ -427,7 +427,7 @@
 }
 
 TEST(NetUtilTest, IDNToUnicodeSlow) {
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(idn_cases); i++) {
+  for (size_t i = 0; i < arraysize(idn_cases); i++) {
     for (size_t j = 0; j < arraysize(kLanguages); j++) {
       // !(ja || zh-TW,en || ko,ja) -> IDNToUnicodeFast
       if (!(j == 3 || j == 17 || j == 18))
@@ -506,7 +506,7 @@
          ",0,\"9.8 kB\",\"\");</script>\n"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const std::string results = GetDirectoryListingEntry(
         WideToUTF16(test_cases[i].name),
         test_cases[i].raw_bytes,
diff --git a/net/base/net_util_unittest.cc b/net/base/net_util_unittest.cc
index 0e17f1a..4883ff2 100644
--- a/net/base/net_util_unittest.cc
+++ b/net/base/net_util_unittest.cc
@@ -118,7 +118,7 @@
       "p&ssword",
     },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i,
                                     tests[i].input_url));
     GURL url(tests[i].input_url);
@@ -180,14 +180,14 @@
   };
 
   // Test first with google_headers.
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string result =
         GetSpecificHeader(google_headers, tests[i].header_name);
     EXPECT_EQ(result, tests[i].expected);
   }
 
   // Test again with empty headers.
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string result = GetSpecificHeader(std::string(), tests[i].header_name);
     EXPECT_EQ(result, std::string());
   }
@@ -224,7 +224,7 @@
     {"1.2.3.4.5.", true},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(compliant_host_cases); ++i) {
+  for (size_t i = 0; i < arraysize(compliant_host_cases); ++i) {
     EXPECT_EQ(compliant_host_cases[i].expected_output,
               IsCanonicalizedHostCompliant(compliant_host_cases[i].host));
   }
@@ -274,7 +274,7 @@
     {"[]", false, "", -1},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string host;
     int port;
     bool ok = ParseHostAndPort(tests[i].input, &host, &port);
@@ -300,7 +300,7 @@
     { GURL("http://[1::2]/x"), "[1::2]:80"},
     { GURL("http://[::a]:33/x"), "[::a]:33"},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string host_and_port = GetHostAndPort(tests[i].url);
     EXPECT_EQ(std::string(tests[i].expected_host_and_port), host_and_port);
   }
@@ -318,7 +318,7 @@
     { GURL("http://[1::2]/x"), "[1::2]"},
     { GURL("http://[::a]:33/x"), "[::a]:33"},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string host_and_port = GetHostAndOptionalPort(tests[i].url);
     EXPECT_EQ(std::string(tests[i].expected_host_and_port), host_and_port);
   }
@@ -358,7 +358,7 @@
     {{192, 168, 0, 1}, "192.168.0.1"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SockaddrStorage storage;
     MakeIPv4Address(tests[i].addr, 80, &storage);
     std::string result = NetAddressToString(storage.addr, storage.addr_len);
@@ -376,7 +376,7 @@
      "fedc:ba98:7654:3210:fedc:ba98:7654:3210"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SockaddrStorage storage;
     MakeIPv6Address(tests[i].addr, 80, &storage);
     EXPECT_EQ(std::string(tests[i].result),
@@ -452,7 +452,7 @@
       "foobar://user:pass@google.com:80/sup?yo",
     },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s", i,
                                     tests[i].input_url));
     GURL input_url(GURL(tests[i].input_url));
@@ -465,12 +465,12 @@
   std::string invalid[] = { "1,2,a", "'1','2'", "1, 2, 3", "1 0,11,12" };
   std::string valid[] = { "", "1", "1,2", "1,2,3", "10,11,12,13" };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(invalid); ++i) {
+  for (size_t i = 0; i < arraysize(invalid); ++i) {
     SetExplicitlyAllowedPorts(invalid[i]);
     EXPECT_EQ(0, static_cast<int>(GetCountOfExplicitlyAllowedPorts()));
   }
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(valid); ++i) {
+  for (size_t i = 0; i < arraysize(valid); ++i) {
     SetExplicitlyAllowedPorts(valid[i]);
     EXPECT_EQ(i, GetCountOfExplicitlyAllowedPorts());
   }
@@ -683,7 +683,7 @@
       false
     },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s, %s", i,
                                     tests[i].cidr_literal,
                                     tests[i].ip_literal));
diff --git a/net/base/upload_file_element_reader.cc b/net/base/upload_file_element_reader.cc
index 6878564..857bef2 100644
--- a/net/base/upload_file_element_reader.cc
+++ b/net/base/upload_file_element_reader.cc
@@ -7,6 +7,7 @@
 #include "base/bind.h"
 #include "base/files/file_util.h"
 #include "base/location.h"
+#include "base/profiler/scoped_profile.h"
 #include "base/task_runner_util.h"
 #include "net/base/file_stream.h"
 #include "net/base/io_buffer.h"
@@ -103,6 +104,11 @@
 void UploadFileElementReader::OnOpenCompleted(
     const CompletionCallback& callback,
     int result) {
+  // TODO(vadimt): Remove ScopedProfile below once crbug.com/423948 is fixed.
+  tracked_objects::ScopedProfile tracking_profile(
+      FROM_HERE_WITH_EXPLICIT_FUNCTION(
+          "423948 UploadFileElementReader::OnOpenCompleted"));
+
   DCHECK(!callback.is_null());
 
   if (result < 0) {
diff --git a/net/cert/multi_threaded_cert_verifier_unittest.cc b/net/cert/multi_threaded_cert_verifier_unittest.cc
index 651f78e..cdf9b1d 100644
--- a/net/cert/multi_threaded_cert_verifier_unittest.cc
+++ b/net/cert/multi_threaded_cert_verifier_unittest.cc
@@ -383,7 +383,7 @@
       -1,
     },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));
 
     const MultiThreadedCertVerifier::RequestParams& key1 = tests[i].key1;
diff --git a/net/cookies/cookie_monster_perftest.cc b/net/cookies/cookie_monster_perftest.cc
index 2bc0be8..6e799ad 100644
--- a/net/cookies/cookie_monster_perftest.cc
+++ b/net/cookies/cookie_monster_perftest.cc
@@ -363,7 +363,7 @@
       0,
     },
   };
-  for (int ci = 0; ci < static_cast<int>(ARRAYSIZE_UNSAFE(test_cases)); ++ci) {
+  for (int ci = 0; ci < static_cast<int>(arraysize(test_cases)); ++ci) {
     const TestCase& test_case(test_cases[ci]);
     scoped_refptr<CookieMonster> cm(
         CreateMonsterFromStoreForGC(
diff --git a/net/cookies/cookie_monster_unittest.cc b/net/cookies/cookie_monster_unittest.cc
index a328487..34a50bb 100644
--- a/net/cookies/cookie_monster_unittest.cc
+++ b/net/cookies/cookie_monster_unittest.cc
@@ -1958,7 +1958,7 @@
   {
     scoped_refptr<CookieMonster> cmout(new CookieMonster(store.get(), NULL));
     for (const CookiesInputInfo* p = input_info;
-         p < &input_info[ARRAYSIZE_UNSAFE(input_info)];
+         p < &input_info[arraysize(input_info)];
          p++) {
       EXPECT_TRUE(SetCookieWithDetails(cmout.get(),
                                        p->url,
@@ -2112,7 +2112,7 @@
     }
   };
 
-  for (int ci = 0; ci < static_cast<int>(ARRAYSIZE_UNSAFE(test_cases)); ++ci) {
+  for (int ci = 0; ci < static_cast<int>(arraysize(test_cases)); ++ci) {
     const TestCase *test_case = &test_cases[ci];
     scoped_refptr<CookieMonster> cm(
         CreateMonsterFromStoreForGC(
diff --git a/net/cookies/cookie_util_unittest.cc b/net/cookies/cookie_util_unittest.cc
index 98c2061..fc27631 100644
--- a/net/cookies/cookie_util_unittest.cc
+++ b/net/cookies/cookie_util_unittest.cc
@@ -55,7 +55,7 @@
     { ".google.com",    false }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     EXPECT_EQ(tests[i].is_host_only,
               net::cookie_util::DomainIsHostOnly(tests[i].str));
   }
@@ -138,7 +138,7 @@
   };
 
   base::Time parsed_time;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     parsed_time = net::cookie_util::ParseCookieTime(tests[i].str);
     if (!tests[i].valid) {
       EXPECT_FALSE(!parsed_time.is_null()) << tests[i].str;
diff --git a/net/disk_cache/disk_cache_test_base.cc b/net/disk_cache/disk_cache_test_base.cc
index c3d94e6..2e9bd7f 100644
--- a/net/disk_cache/disk_cache_test_base.cc
+++ b/net/disk_cache/disk_cache_test_base.cc
@@ -308,7 +308,7 @@
     int rv = simple_backend->Init(cb.callback());
     ASSERT_EQ(net::OK, cb.GetResult(rv));
     simple_cache_impl_ = simple_backend.get();
-    cache_ = simple_backend.PassAs<disk_cache::Backend>();
+    cache_ = simple_backend.Pass();
     if (simple_cache_wait_for_index_) {
       net::TestCompletionCallback wait_for_index_cb;
       rv = simple_cache_impl_->index()->ExecuteWhenReady(
diff --git a/net/disk_cache/memory/mem_backend_impl.cc b/net/disk_cache/memory/mem_backend_impl.cc
index 3a90075..046623f 100644
--- a/net/disk_cache/memory/mem_backend_impl.cc
+++ b/net/disk_cache/memory/mem_backend_impl.cc
@@ -47,10 +47,10 @@
   scoped_ptr<MemBackendImpl> cache(new MemBackendImpl(net_log));
   cache->SetMaxSize(max_bytes);
   if (cache->Init())
-    return cache.PassAs<Backend>();
+    return cache.Pass();
 
   LOG(ERROR) << "Unable to create cache";
-  return scoped_ptr<Backend>();
+  return nullptr;
 }
 
 bool MemBackendImpl::Init() {
diff --git a/net/disk_cache/simple/simple_index_unittest.cc b/net/disk_cache/simple/simple_index_unittest.cc
index 0bb10d3..43e99ad 100644
--- a/net/disk_cache/simple/simple_index_unittest.cc
+++ b/net/disk_cache/simple/simple_index_unittest.cc
@@ -105,8 +105,8 @@
   virtual void SetUp() override {
     scoped_ptr<MockSimpleIndexFile> index_file(new MockSimpleIndexFile());
     index_file_ = index_file->AsWeakPtr();
-    index_.reset(new SimpleIndex(NULL, this, net::DISK_CACHE,
-                                 index_file.PassAs<SimpleIndexFile>()));
+    index_.reset(
+        new SimpleIndex(NULL, this, net::DISK_CACHE, index_file.Pass()));
 
     index_->Initialize(base::Time());
   }
diff --git a/net/dns/dns_hosts_unittest.cc b/net/dns/dns_hosts_unittest.cc
index 9074899..1bce190 100644
--- a/net/dns/dns_hosts_unittest.cc
+++ b/net/dns/dns_hosts_unittest.cc
@@ -66,7 +66,7 @@
   };
 
   DnsHosts expected_hosts, actual_hosts;
-  PopulateExpectedHosts(kEntries, ARRAYSIZE_UNSAFE(kEntries), &expected_hosts);
+  PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts);
   ParseHosts(kContents, &actual_hosts);
   ASSERT_EQ(expected_hosts, actual_hosts);
 }
@@ -79,7 +79,7 @@
   };
 
   DnsHosts expected_hosts, actual_hosts;
-  PopulateExpectedHosts(kEntries, ARRAYSIZE_UNSAFE(kEntries), &expected_hosts);
+  PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts);
   ParseHostsWithCommaModeForTesting(
       kContents, &actual_hosts, PARSE_HOSTS_COMMA_IS_TOKEN);
   ASSERT_EQ(expected_hosts, actual_hosts);
@@ -94,7 +94,7 @@
   };
 
   DnsHosts expected_hosts, actual_hosts;
-  PopulateExpectedHosts(kEntries, ARRAYSIZE_UNSAFE(kEntries), &expected_hosts);
+  PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts);
   ParseHostsWithCommaModeForTesting(
       kContents, &actual_hosts, PARSE_HOSTS_COMMA_IS_WHITESPACE);
   ASSERT_EQ(expected_hosts, actual_hosts);
@@ -116,7 +116,7 @@
 #endif
 
   DnsHosts expected_hosts, actual_hosts;
-  PopulateExpectedHosts(kEntries, ARRAYSIZE_UNSAFE(kEntries), &expected_hosts);
+  PopulateExpectedHosts(kEntries, arraysize(kEntries), &expected_hosts);
   ParseHosts(kContents, &actual_hosts);
   ASSERT_EQ(expected_hosts, actual_hosts);
 }
diff --git a/net/dns/dns_response_unittest.cc b/net/dns/dns_response_unittest.cc
index 12b0377..6ecfac4 100644
--- a/net/dns/dns_response_unittest.cc
+++ b/net/dns/dns_response_unittest.cc
@@ -441,7 +441,7 @@
       },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     const TestCase& t = cases[i];
     DnsResponse response(t.response_data, t.response_size, t.query_size);
     AddressList addr_list;
@@ -565,7 +565,7 @@
 
   const size_t kQuerySize = 12 + 7;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     const TestCase& t = cases[i];
 
     DnsResponse response(t.data, t.size, kQuerySize);
diff --git a/net/dns/dns_session_unittest.cc b/net/dns/dns_session_unittest.cc
index e6f1230..166abef 100644
--- a/net/dns/dns_session_unittest.cc
+++ b/net/dns/dns_session_unittest.cc
@@ -194,7 +194,7 @@
   scoped_ptr<MockUDPClientSocket> socket(
       new MockUDPClientSocket(data_provider, net_log));
   data_provider->set_socket(socket.get());
-  return socket.PassAs<DatagramClientSocket>();
+  return socket.Pass();
 }
 
 TestClientSocketFactory::~TestClientSocketFactory() {
diff --git a/net/dns/dns_transaction_unittest.cc b/net/dns/dns_transaction_unittest.cc
index 908f915..e074966 100644
--- a/net/dns/dns_transaction_unittest.cc
+++ b/net/dns/dns_transaction_unittest.cc
@@ -198,7 +198,7 @@
     scoped_ptr<TestUDPClientSocket> socket(
         new TestUDPClientSocket(this, data_provider, net_log));
     data_provider->set_socket(socket.get());
-    return socket.PassAs<DatagramClientSocket>();
+    return socket.Pass();
   }
 
   void OnConnect(const IPEndPoint& endpoint) {
diff --git a/net/dns/host_cache_unittest.cc b/net/dns/host_cache_unittest.cc
index 34309c1..838fedc 100644
--- a/net/dns/host_cache_unittest.cc
+++ b/net/dns/host_cache_unittest.cc
@@ -360,7 +360,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));
 
     const HostCache::Key& key1 = tests[i].key1;
diff --git a/net/dns/mapped_host_resolver_unittest.cc b/net/dns/mapped_host_resolver_unittest.cc
index fbbfde8..05cde24 100644
--- a/net/dns/mapped_host_resolver_unittest.cc
+++ b/net/dns/mapped_host_resolver_unittest.cc
@@ -32,7 +32,7 @@
 
   // Create a remapped resolver that uses |resolver_impl|.
   scoped_ptr<MappedHostResolver> resolver(
-      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));
+      new MappedHostResolver(resolver_impl.Pass()));
 
   int rv;
   AddressList address_list;
@@ -106,7 +106,7 @@
 
   // Create a remapped resolver that uses |resolver_impl|.
   scoped_ptr<MappedHostResolver> resolver(
-      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));
+      new MappedHostResolver(resolver_impl.Pass()));
 
   int rv;
   AddressList address_list;
@@ -153,7 +153,7 @@
 
   // Create a remapped resolver that uses |resolver_impl|.
   scoped_ptr<MappedHostResolver> resolver(
-      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));
+      new MappedHostResolver(resolver_impl.Pass()));
 
   int rv;
   AddressList address_list;
@@ -210,7 +210,7 @@
   resolver_impl->rules()->AddRule("*", "192.168.1.5");
 
   scoped_ptr<MappedHostResolver> resolver(
-      new MappedHostResolver(resolver_impl.PassAs<HostResolver>()));
+      new MappedHostResolver(resolver_impl.Pass()));
 
   int rv;
   AddressList address_list;
diff --git a/net/dns/mdns_client.cc b/net/dns/mdns_client.cc
index c55de6e..ac00352 100644
--- a/net/dns/mdns_client.cc
+++ b/net/dns/mdns_client.cc
@@ -96,7 +96,7 @@
     VLOG(1) << "Bind failed, endpoint=" << multicast_addr.ToStringWithoutPort()
             << ", error=" << rv;
   }
-  return socket.PassAs<DatagramServerSocket>();
+  return socket.Pass();
 }
 
 }  // namespace net
diff --git a/net/ftp/ftp_directory_listing_parser.cc b/net/ftp/ftp_directory_listing_parser.cc
index d19e4a2..fa6e8a5 100644
--- a/net/ftp/ftp_directory_listing_parser.cc
+++ b/net/ftp/ftp_directory_listing_parser.cc
@@ -77,7 +77,7 @@
     }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(parsers); i++) {
+  for (size_t i = 0; i < arraysize(parsers); i++) {
     entries->clear();
     if (parsers[i].callback.Run()) {
       *server_type = parsers[i].server_type;
diff --git a/net/ftp/ftp_util_unittest.cc b/net/ftp/ftp_util_unittest.cc
index 5851e88..a2b2849 100644
--- a/net/ftp/ftp_util_unittest.cc
+++ b/net/ftp/ftp_util_unittest.cc
@@ -34,7 +34,7 @@
     { "a/b/c",      "[.a.b]c"     },
     { "a/b/c/d",    "[.a.b.c]d"   },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); i++) {
+  for (size_t i = 0; i < arraysize(kTestCases); i++) {
     EXPECT_EQ(kTestCases[i].expected_output,
               net::FtpUtil::UnixFilePathToVMS(kTestCases[i].input))
         << kTestCases[i].input;
@@ -67,7 +67,7 @@
     { "a/b/c/d",     "[.a.b.c.d]"  },
     { "a/b/c/d/",    "[.a.b.c.d]"  },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); i++) {
+  for (size_t i = 0; i < arraysize(kTestCases); i++) {
     EXPECT_EQ(kTestCases[i].expected_output,
               net::FtpUtil::UnixDirectoryPathToVMS(kTestCases[i].input))
         << kTestCases[i].input;
@@ -107,7 +107,7 @@
     { "/a/b/c",      "/a/b/c"     },
     { "/a/b/c/d",    "/a/b/c/d"   },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); i++) {
+  for (size_t i = 0; i < arraysize(kTestCases); i++) {
     EXPECT_EQ(kTestCases[i].expected_output,
               net::FtpUtil::VMSPathToUnix(kTestCases[i].input))
         << kTestCases[i].input;
@@ -163,7 +163,7 @@
     { "Sep", "02", "09:00", 1994, 9, 2, 9, 0 },
     { "Dec", "06", "21:00", 1993, 12, 6, 21, 0 },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); i++) {
+  for (size_t i = 0; i < arraysize(kTestCases); i++) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s %s %s", i,
                                     kTestCases[i].month, kTestCases[i].day,
                                     kTestCases[i].rest));
@@ -204,7 +204,7 @@
 
     { "11-01-2007", "12:42", 2007, 11, 1, 12, 42 },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); i++) {
+  for (size_t i = 0; i < arraysize(kTestCases); i++) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s %s", i,
                                     kTestCases[i].date, kTestCases[i].time));
 
@@ -243,7 +243,7 @@
     { "  foo   abc ", 1, "abc" },
     { "  foo   abc ", 2, "" },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); i++) {
+  for (size_t i = 0; i < arraysize(kTestCases); i++) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %s %d", i,
                                     kTestCases[i].text, kTestCases[i].column));
 
diff --git a/net/http/http_auth_handler_basic_unittest.cc b/net/http/http_auth_handler_basic_unittest.cc
index 6f112b1..a369df3 100644
--- a/net/http/http_auth_handler_basic_unittest.cc
+++ b/net/http/http_auth_handler_basic_unittest.cc
@@ -32,7 +32,7 @@
   };
   GURL origin("http://www.example.com");
   HttpAuthHandlerBasic::Factory factory;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string challenge = "Basic realm=\"Atlantis\"";
     scoped_ptr<HttpAuthHandler> basic;
     EXPECT_EQ(OK, factory.CreateAuthHandlerFromString(
@@ -90,7 +90,7 @@
       tests[0].challenge, HttpAuth::AUTH_SERVER, origin,
       BoundNetLog(), &basic));
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string challenge(tests[i].challenge);
     HttpAuthChallengeTokenizer tok(challenge.begin(),
                                    challenge.end());
@@ -183,7 +183,7 @@
   };
   HttpAuthHandlerBasic::Factory factory;
   GURL origin("http://www.example.com");
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string challenge = tests[i].challenge;
     scoped_ptr<HttpAuthHandler> basic;
     int rv = factory.CreateAuthHandlerFromString(
diff --git a/net/http/http_auth_handler_digest_unittest.cc b/net/http/http_auth_handler_digest_unittest.cc
index 5c3941c..8b5179e 100644
--- a/net/http/http_auth_handler_digest_unittest.cc
+++ b/net/http/http_auth_handler_digest_unittest.cc
@@ -351,7 +351,7 @@
   GURL origin("http://www.example.com");
   scoped_ptr<HttpAuthHandlerDigest::Factory> factory(
       new HttpAuthHandlerDigest::Factory());
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     scoped_ptr<HttpAuthHandler> handler;
     int rv = factory->CreateAuthHandlerFromString(tests[i].challenge,
                                                   HttpAuth::AUTH_SERVER,
@@ -516,7 +516,7 @@
   GURL origin("http://www.example.com");
   scoped_ptr<HttpAuthHandlerDigest::Factory> factory(
       new HttpAuthHandlerDigest::Factory());
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     scoped_ptr<HttpAuthHandler> handler;
     int rv = factory->CreateAuthHandlerFromString(tests[i].challenge,
                                                   HttpAuth::AUTH_SERVER,
diff --git a/net/http/http_auth_unittest.cc b/net/http/http_auth_unittest.cc
index cf68fa8..52e8294 100644
--- a/net/http/http_auth_unittest.cc
+++ b/net/http/http_auth_unittest.cc
@@ -129,7 +129,7 @@
   http_auth_handler_factory->SetURLSecurityManager(
       "negotiate", &url_security_manager);
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     // Make a HttpResponseHeaders object.
     std::string headers_with_status_line("HTTP/1.1 401 Unauthorized\n");
     headers_with_status_line += tests[i].headers;
diff --git a/net/http/http_byte_range_unittest.cc b/net/http/http_byte_range_unittest.cc
index 5dc6e52..d075294 100644
--- a/net/http/http_byte_range_unittest.cc
+++ b/net/http/http_byte_range_unittest.cc
@@ -23,7 +23,7 @@
     {  -1, -1, 100000, true },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::HttpByteRange range;
     range.set_first_byte_position(tests[i].first_byte_position);
     range.set_last_byte_position(tests[i].last_byte_position);
@@ -55,7 +55,7 @@
     {  10, 10000, -1, 1000000, true, 10, 10000 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::HttpByteRange range;
     range.set_first_byte_position(tests[i].first_byte_position);
     range.set_last_byte_position(tests[i].last_byte_position);
@@ -86,7 +86,7 @@
                {net::HttpByteRange::Bounded(0, -1),      "bytes=0-"},
                {net::HttpByteRange::RightUnbounded(100), "bytes=100-"},
                {net::HttpByteRange::Suffix(100),         "bytes=-100"}, };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     EXPECT_EQ(tests[i].expected, tests[i].range.GetHeaderValue());
   }
 }
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc
index ddd0481..5441e90 100644
--- a/net/http/http_cache_transaction.cc
+++ b/net/http/http_cache_transaction.cc
@@ -2015,7 +2015,7 @@
   if (request_->extra_headers.HasHeader(HttpRequestHeaders::kRange))
     range_found = true;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kSpecialHeaders); ++i) {
+  for (size_t i = 0; i < arraysize(kSpecialHeaders); ++i) {
     if (HeaderMatches(request_->extra_headers, kSpecialHeaders[i].search)) {
       effective_load_flags_ |= kSpecialHeaders[i].load_flag;
       break;
diff --git a/net/http/http_content_disposition_unittest.cc b/net/http/http_content_disposition_unittest.cc
index 43fef9d..e617c6c 100644
--- a/net/http/http_content_disposition_unittest.cc
+++ b/net/http/http_content_disposition_unittest.cc
@@ -195,7 +195,7 @@
     {"attachment; foobar=x; filename=\"foo.html\"", "",
       L"foo.html"},
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     HttpContentDisposition header(tests[i].header, tests[i].referrer_charset);
     EXPECT_EQ(tests[i].expected,
         base::UTF8ToWide(header.filename()))
@@ -503,7 +503,7 @@
     // TODO(abarth): http://greenbytes.de/tech/tc2231/#attrfc2047token
     // TODO(abarth): http://greenbytes.de/tech/tc2231/#attrfc2047quoted
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     HttpContentDisposition header(tests[i].header, std::string());
     EXPECT_EQ(tests[i].expected_type, header.type())
         << "Failed on input: " << tests[i].header;
@@ -576,7 +576,7 @@
       HttpContentDisposition::HAS_NAME },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     const ParseResultTestCase& test_case = kTestCases[i];
     HttpContentDisposition content_disposition(test_case.header, "utf-8");
     int result = content_disposition.parse_result_flags();
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc
index 7531c91..ca26d6f 100644
--- a/net/http/http_network_transaction_unittest.cc
+++ b/net/http/http_network_transaction_unittest.cc
@@ -7601,7 +7601,7 @@
 
   session_deps_.use_alternate_protocols = true;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     session_deps_.proxy_service.reset(
         ProxyService::CreateFixed(tests[i].proxy_server));
     scoped_refptr<HttpNetworkSession> session(
@@ -7616,8 +7616,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetTransportSocketPool(transport_conn_pool);
     mock_pool_manager->SetSSLSocketPool(ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
 
     EXPECT_EQ(ERR_IO_PENDING,
               GroupNameTransactionHelper(tests[i].url, session));
@@ -7665,7 +7664,7 @@
 
   session_deps_.use_alternate_protocols = true;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     session_deps_.proxy_service.reset(
         ProxyService::CreateFixed(tests[i].proxy_server));
     scoped_refptr<HttpNetworkSession> session(
@@ -7683,8 +7682,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetSocketPoolForHTTPProxy(proxy_host, http_proxy_pool);
     mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
 
     EXPECT_EQ(ERR_IO_PENDING,
               GroupNameTransactionHelper(tests[i].url, session));
@@ -7736,7 +7734,7 @@
 
   session_deps_.use_alternate_protocols = true;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     session_deps_.proxy_service.reset(
         ProxyService::CreateFixed(tests[i].proxy_server));
     scoped_refptr<HttpNetworkSession> session(
@@ -7754,8 +7752,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetSocketPoolForSOCKSProxy(proxy_host, socks_conn_pool);
     mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
 
     scoped_ptr<HttpTransaction> trans(
         new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
@@ -9655,7 +9652,7 @@
         TestRound(kGetAuth, kFailure, kAuthErr)}},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_configs); ++i) {
+  for (size_t i = 0; i < arraysize(test_configs); ++i) {
     HttpAuthHandlerMock::Factory* auth_factory(
         new HttpAuthHandlerMock::Factory());
     session_deps_.http_auth_handler_factory.reset(auth_factory);
@@ -9808,8 +9805,7 @@
   scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
       new MockClientSocketPoolManager);
   mock_pool_manager->SetTransportSocketPool(transport_pool);
-  session_peer.SetClientSocketPoolManager(
-      mock_pool_manager.PassAs<ClientSocketPoolManager>());
+  session_peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
 
   scoped_ptr<HttpTransaction> trans(
       new HttpNetworkTransaction(DEFAULT_PRIORITY, session.get()));
diff --git a/net/http/http_proxy_client_socket_pool.cc b/net/http/http_proxy_client_socket_pool.cc
index 213a682..c963d2c 100644
--- a/net/http/http_proxy_client_socket_pool.cc
+++ b/net/http/http_proxy_client_socket_pool.cc
@@ -302,7 +302,7 @@
 int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result) {
   if (result == OK || result == ERR_PROXY_AUTH_REQUESTED ||
       result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
-    SetSocket(transport_socket_.PassAs<StreamSocket>());
+    SetSocket(transport_socket_.Pass());
   }
 
   return result;
diff --git a/net/http/http_stream_factory_impl_unittest.cc b/net/http/http_stream_factory_impl_unittest.cc
index a93e9b0..c1c42c3 100644
--- a/net/http/http_stream_factory_impl_unittest.cc
+++ b/net/http/http_stream_factory_impl_unittest.cc
@@ -450,8 +450,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetTransportSocketPool(transport_conn_pool);
     mock_pool_manager->SetSSLSocketPool(ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
     PreconnectHelper(kTests[i], session.get());
     if (kTests[i].ssl)
       EXPECT_EQ(kTests[i].num_streams, ssl_conn_pool->last_num_streams());
@@ -480,8 +479,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetSocketPoolForHTTPProxy(proxy_host, http_proxy_pool);
     mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
     PreconnectHelper(kTests[i], session.get());
     if (kTests[i].ssl)
       EXPECT_EQ(kTests[i].num_streams, ssl_conn_pool->last_num_streams());
@@ -510,8 +508,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetSocketPoolForSOCKSProxy(proxy_host, socks_proxy_pool);
     mock_pool_manager->SetSocketPoolForSSLWithProxy(proxy_host, ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
     PreconnectHelper(kTests[i], session.get());
     if (kTests[i].ssl)
       EXPECT_EQ(kTests[i].num_streams, ssl_conn_pool->last_num_streams());
@@ -546,8 +543,7 @@
         new MockClientSocketPoolManager);
     mock_pool_manager->SetTransportSocketPool(transport_conn_pool);
     mock_pool_manager->SetSSLSocketPool(ssl_conn_pool);
-    peer.SetClientSocketPoolManager(
-        mock_pool_manager.PassAs<ClientSocketPoolManager>());
+    peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
     PreconnectHelper(kTests[i], session.get());
     // We shouldn't be preconnecting if we have an existing session, which is
     // the case for https://www.google.com.
@@ -577,8 +573,7 @@
   scoped_ptr<MockClientSocketPoolManager> mock_pool_manager(
       new MockClientSocketPoolManager);
   mock_pool_manager->SetTransportSocketPool(transport_conn_pool);
-  peer.SetClientSocketPoolManager(
-      mock_pool_manager.PassAs<ClientSocketPoolManager>());
+  peer.SetClientSocketPoolManager(mock_pool_manager.Pass());
 
   PreconnectHelperForURL(1, GURL("http://www.google.com:7"), session.get());
 
diff --git a/net/http/http_stream_parser_unittest.cc b/net/http/http_stream_parser_unittest.cc
index ef83638..01d4e12 100644
--- a/net/http/http_stream_parser_unittest.cc
+++ b/net/http/http_stream_parser_unittest.cc
@@ -236,7 +236,7 @@
   ASSERT_EQ(OK, rv);
 
   scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
-  socket_handle->SetSocket(transport.PassAs<StreamSocket>());
+  socket_handle->SetSocket(transport.Pass());
 
   HttpRequestInfo request_info;
   request_info.method = "GET";
@@ -391,7 +391,7 @@
       ASSERT_EQ(OK, rv);
 
       scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
-      socket_handle->SetSocket(transport.PassAs<StreamSocket>());
+      socket_handle->SetSocket(transport.Pass());
 
       HttpRequestInfo request_info;
       request_info.method = "GET";
@@ -460,7 +460,7 @@
   ASSERT_EQ(OK, rv);
 
   scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
-  socket_handle->SetSocket(transport.PassAs<StreamSocket>());
+  socket_handle->SetSocket(transport.Pass());
 
   HttpRequestInfo request_info;
   request_info.method = "GET";
@@ -530,7 +530,7 @@
     rv = callback.GetResult(rv);
     ASSERT_EQ(OK, rv);
 
-    socket_handle_->SetSocket(transport_.PassAs<StreamSocket>());
+    socket_handle_->SetSocket(transport_.Pass());
 
     request_info_.method = "GET";
     request_info_.url = GURL("http://localhost");
@@ -835,7 +835,7 @@
   ASSERT_EQ(OK, transport->Connect(callback.callback()));
 
   scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
-  socket_handle->SetSocket(transport.PassAs<StreamSocket>());
+  socket_handle->SetSocket(transport.Pass());
 
   scoped_ptr<HttpRequestInfo> request_info(new HttpRequestInfo());
   request_info->method = "GET";
diff --git a/net/http/http_util_unittest.cc b/net/http/http_util_unittest.cc
index 54acf68..acb2693 100644
--- a/net/http/http_util_unittest.cc
+++ b/net/http/http_util_unittest.cc
@@ -114,7 +114,7 @@
     { "fOO: 1\r\nbar: 2", "foo", true },
     { "g: 0\r\nfoo: 1\r\nbar: 2", "foo", true },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     bool result = HttpUtil::HasHeader(tests[i].headers, tests[i].name);
     EXPECT_EQ(tests[i].expected_result, result);
   }
@@ -272,7 +272,7 @@
     { "foo\nbar\n\r\njunk", 10 },
     { "foo\nbar\r\n\njunk", 10 },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     int input_len = static_cast<int>(strlen(tests[i].input));
     int eoh = HttpUtil::LocateEndOfHeaders(tests[i].input, input_len);
     EXPECT_EQ(tests[i].expected_result, eoh);
@@ -582,7 +582,7 @@
       "HTTP/1.0 200 OK|Foo: 1Foo2: 3|Bar: 2||"
     },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string input = tests[i].input;
     std::replace(input.begin(), input.end(), '|', '\0');
     std::string raw = HttpUtil::AssembleRawHeaders(input.data(), input.size());
@@ -629,7 +629,7 @@
       "/foobar?query=1"
     }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     GURL url(GURL(tests[i].url));
     std::string expected_spec(tests[i].expected_spec);
     std::string expected_path(tests[i].expected_path);
@@ -725,7 +725,7 @@
     },
     // TODO(abarth): Add more interesting test cases.
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::string mime_type;
     std::string charset;
     bool had_charset = false;
@@ -853,7 +853,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     std::vector<net::HttpByteRange> ranges;
     bool return_value = HttpUtil::ParseRanges(std::string(tests[i].headers),
                                               &ranges);
diff --git a/net/ocsp/nss_ocsp_unittest.cc b/net/ocsp/nss_ocsp_unittest.cc
index 3df446e..acbb785 100644
--- a/net/ocsp/nss_ocsp_unittest.cc
+++ b/net/ocsp/nss_ocsp_unittest.cc
@@ -91,9 +91,7 @@
     handler_ = handler.get();
 
     URLRequestFilter::GetInstance()->AddHostnameInterceptor(
-        "http",
-        kAiaHost,
-        handler.PassAs<URLRequestInterceptor>());
+        "http", kAiaHost, handler.Pass());
 
     SetURLRequestContextForNSSHttpIO(&context_);
     EnsureNSSHttpIOInit();
diff --git a/net/proxy/proxy_bypass_rules_unittest.cc b/net/proxy/proxy_bypass_rules_unittest.cc
index 40758fd..c099ad6 100644
--- a/net/proxy/proxy_bypass_rules_unittest.cc
+++ b/net/proxy/proxy_bypass_rules_unittest.cc
@@ -275,7 +275,7 @@
   ProxyBypassRules rules;
   rules.ParseFromString("<local>");
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf(
         "Test[%d]: %s", static_cast<int>(i), tests[i].url));
     EXPECT_EQ(tests[i].expected_is_local, rules.Matches(GURL(tests[i].url)));
diff --git a/net/proxy/proxy_config_service_linux_unittest.cc b/net/proxy/proxy_config_service_linux_unittest.cc
index cfb0cff..3e6b966 100644
--- a/net/proxy/proxy_config_service_linux_unittest.cc
+++ b/net/proxy/proxy_config_service_linux_unittest.cc
@@ -681,7 +681,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "] %s", i,
                                     tests[i].description.c_str()));
     MockEnvironment* env = new MockEnvironment;
@@ -989,7 +989,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "] %s", i,
                                     tests[i].description.c_str()));
     MockEnvironment* env = new MockEnvironment;
@@ -1493,7 +1493,7 @@
 
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "] %s", i,
                                     tests[i].description.c_str()));
     MockEnvironment* env = new MockEnvironment;
diff --git a/net/proxy/proxy_config_service_win_unittest.cc b/net/proxy/proxy_config_service_win_unittest.cc
index f133500..0248638 100644
--- a/net/proxy/proxy_config_service_win_unittest.cc
+++ b/net/proxy/proxy_config_service_win_unittest.cc
@@ -196,7 +196,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = {
         tests[i].ie_config.auto_detect,
         const_cast<wchar_t*>(tests[i].ie_config.auto_config_url),
diff --git a/net/proxy/proxy_config_source.cc b/net/proxy/proxy_config_source.cc
index 5695b9b..f47c2f6 100644
--- a/net/proxy/proxy_config_source.cc
+++ b/net/proxy/proxy_config_source.cc
@@ -22,7 +22,7 @@
   "CUSTOM",
   "TEST"
 };
-COMPILE_ASSERT(ARRAYSIZE_UNSAFE(kSourceNames) == NUM_PROXY_CONFIG_SOURCES,
+COMPILE_ASSERT(arraysize(kSourceNames) == NUM_PROXY_CONFIG_SOURCES,
                source_names_incorrect_size);
 
 }  // namespace
diff --git a/net/proxy/proxy_config_unittest.cc b/net/proxy/proxy_config_unittest.cc
index 4b041b3..fb349b3 100644
--- a/net/proxy/proxy_config_unittest.cc
+++ b/net/proxy/proxy_config_unittest.cc
@@ -308,7 +308,7 @@
 
   ProxyConfig config;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     config.proxy_rules().ParseFromString(tests[i].proxy_rules);
 
     EXPECT_EQ(tests[i].type, config.proxy_rules().type);
diff --git a/net/proxy/proxy_list_unittest.cc b/net/proxy/proxy_list_unittest.cc
index 23b823f..5b759b1 100644
--- a/net/proxy/proxy_list_unittest.cc
+++ b/net/proxy/proxy_list_unittest.cc
@@ -58,7 +58,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     ProxyList list;
     list.SetFromPacString(tests[i].pac_input);
     EXPECT_EQ(tests[i].pac_output, list.ToPacString());
@@ -84,7 +84,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     ProxyList list;
     list.SetFromPacString(tests[i].pac_input);
     list.RemoveProxiesWithoutScheme(tests[i].filter);
diff --git a/net/proxy/proxy_server_unittest.cc b/net/proxy/proxy_server_unittest.cc
index 7646467..2471b59 100644
--- a/net/proxy/proxy_server_unittest.cc
+++ b/net/proxy/proxy_server_unittest.cc
@@ -159,7 +159,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::ProxyServer uri =
         net::ProxyServer::FromURI(tests[i].input_uri,
                                   net::ProxyServer::SCHEME_HTTP);
@@ -202,7 +202,7 @@
     "http:",  // ambiguous, but will fail because of bad port.
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::ProxyServer uri =
         net::ProxyServer::FromURI(tests[i], net::ProxyServer::SCHEME_HTTP);
     EXPECT_FALSE(uri.is_valid());
@@ -220,7 +220,7 @@
     "  \tfoopy:80  ",
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::ProxyServer uri =
         net::ProxyServer::FromURI(tests[i], net::ProxyServer::SCHEME_HTTP);
     EXPECT_EQ("foopy:80", uri.ToURI());
@@ -279,7 +279,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::ProxyServer uri = net::ProxyServer::FromPacString(tests[i].input_pac);
     EXPECT_TRUE(uri.is_valid());
     EXPECT_EQ(tests[i].expected_uri, uri.ToURI());
@@ -295,7 +295,7 @@
     "DIRECT foopy:10",  // direct cannot have host/port.
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     net::ProxyServer uri = net::ProxyServer::FromPacString(tests[i]);
     EXPECT_FALSE(uri.is_valid());
   }
@@ -335,7 +335,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     // Parse the expected inputs to ProxyServer instances.
     const net::ProxyServer server1 =
         net::ProxyServer::FromURI(
diff --git a/net/quic/crypto/crypto_utils_test.cc b/net/quic/crypto/crypto_utils_test.cc
index fd9f005..882a9b5 100644
--- a/net/quic/crypto/crypto_utils_test.cc
+++ b/net/quic/crypto/crypto_utils_test.cc
@@ -39,7 +39,7 @@
     { "www.google.com........", "www.google.com", },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     EXPECT_EQ(std::string(tests[i].expected),
               CryptoUtils::NormalizeHostname(tests[i].input));
   }
@@ -93,7 +93,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_vector); i++) {
+  for (size_t i = 0; i < arraysize(test_vector); i++) {
     // Decode the test vector.
     string subkey_secret;
     string label;
diff --git a/net/quic/iovector_test.cc b/net/quic/iovector_test.cc
index e6cc058..37a1523 100644
--- a/net/quic/iovector_test.cc
+++ b/net/quic/iovector_test.cc
@@ -23,7 +23,7 @@
 
 TEST(IOVectorTest, CopyConstructor) {
   IOVector iov1;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     iov1.Append(const_cast<char*>(test_data[i]), strlen(test_data[i]));
   }
   IOVector iov2 = iov1;
@@ -37,7 +37,7 @@
 
 TEST(IOVectorTest, AssignmentOperator) {
   IOVector iov1;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     iov1.Append(const_cast<char*>(test_data[i]), strlen(test_data[i]));
   }
   IOVector iov2;
@@ -60,7 +60,7 @@
 
   ASSERT_EQ(0u, iov.Size());
   ASSERT_TRUE(iov2 == nullptr);
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     const int str_len = strlen(test_data[i]);
     const int append_len = str_len / 2;
     // This should append a new block
@@ -91,8 +91,8 @@
     {const_cast<char*>("bar"), 3},
     {const_cast<char*>("buzzzz"), 6}
   };
-  iov.AppendIovec(test_iov, ARRAYSIZE_UNSAFE(test_iov));
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_iov); ++i) {
+  iov.AppendIovec(test_iov, arraysize(test_iov));
+  for (size_t i = 0; i < arraysize(test_iov); ++i) {
     EXPECT_EQ(test_iov[i].iov_base, iov.iovec()[i].iov_base);
     EXPECT_EQ(test_iov[i].iov_len, iov.iovec()[i].iov_len);
   }
@@ -100,14 +100,13 @@
   // Test AppendIovecAtMostBytes.
   iov.Clear();
   // Stop in the middle of a block.
-  EXPECT_EQ(5u, iov.AppendIovecAtMostBytes(test_iov, ARRAYSIZE_UNSAFE(test_iov),
-                                           5));
+  EXPECT_EQ(5u, iov.AppendIovecAtMostBytes(test_iov, arraysize(test_iov), 5));
   EXPECT_EQ(5u, iov.TotalBufferSize());
   iov.Append(static_cast<char*>(test_iov[1].iov_base) + 2, 1);
   // Make sure the boundary case, where max_bytes == size of block also works.
   EXPECT_EQ(6u, iov.AppendIovecAtMostBytes(&test_iov[2], 1, 6));
-  ASSERT_LE(ARRAYSIZE_UNSAFE(test_iov), static_cast<size_t>(iov.Size()));
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_iov); ++i) {
+  ASSERT_LE(arraysize(test_iov), static_cast<size_t>(iov.Size()));
+  for (size_t i = 0; i < arraysize(test_iov); ++i) {
     EXPECT_EQ(test_iov[i].iov_base, iov.iovec()[i].iov_base);
     EXPECT_EQ(test_iov[i].iov_len, iov.iovec()[i].iov_len);
   }
@@ -117,13 +116,13 @@
   IOVector iov;
   int length = 0;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     const int str_len = strlen(test_data[i]);
     iov.Append(const_cast<char*>(test_data[i]), str_len);
     length += str_len;
   }
   const char* endp = iov.LastBlockEnd();
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     const struct iovec* iov2 = iov.iovec();
     const size_t str_len = strlen(test_data[i]);
     size_t tmp = str_len / 2;
@@ -135,7 +134,7 @@
     // Consume half of the first block.
     size_t consumed = iov.Consume(tmp);
     ASSERT_EQ(tmp, consumed);
-    ASSERT_EQ(ARRAYSIZE_UNSAFE(test_data) - i, static_cast<size_t>(iov.Size()));
+    ASSERT_EQ(arraysize(test_data) - i, static_cast<size_t>(iov.Size()));
     iov2 = iov.iovec();
     ASSERT_TRUE(iov2 != nullptr);
     ASSERT_TRUE(iov2[0].iov_base == test_data[i] + tmp);
@@ -144,8 +143,7 @@
     // Consume the rest of the first block
     consumed = iov.Consume(str_len - tmp);
     ASSERT_EQ(str_len - tmp, consumed);
-    ASSERT_EQ(ARRAYSIZE_UNSAFE(test_data) - i - 1,
-              static_cast<size_t>(iov.Size()));
+    ASSERT_EQ(arraysize(test_data) - i - 1, static_cast<size_t>(iov.Size()));
     iov2 = iov.iovec();
     if (iov.Size() > 0) {
       ASSERT_TRUE(iov2 != nullptr);
@@ -161,12 +159,12 @@
   IOVector iov;
   int length = 0;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     const int str_len = strlen(test_data[i]);
     iov.Append(const_cast<char*>(test_data[i]), str_len);
     length += str_len;
   }
-  const size_t last_len = strlen(test_data[ARRAYSIZE_UNSAFE(test_data) - 1]);
+  const size_t last_len = strlen(test_data[arraysize(test_data) - 1]);
   const size_t half_len = last_len / 2;
 
   const char* endp = iov.LastBlockEnd();
@@ -176,7 +174,7 @@
   ASSERT_TRUE(iov2 != nullptr);
   ASSERT_EQ(1u, iov.Size());
   ASSERT_TRUE(iov2[0].iov_base ==
-              test_data[ARRAYSIZE_UNSAFE(test_data) - 1] + last_len - half_len);
+              test_data[arraysize(test_data) - 1] + last_len - half_len);
   ASSERT_EQ(half_len, iov2[0].iov_len);
   ASSERT_TRUE(iov.LastBlockEnd() == endp);
 
@@ -192,7 +190,7 @@
   IOVector iov;
   int length = 0;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     const int str_len = strlen(test_data[i]);
     iov.Append(const_cast<char*>(test_data[i]), str_len);
     length += str_len;
@@ -217,14 +215,14 @@
   IOVector iov;
   int length = 0;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
+  for (size_t i = 0; i < arraysize(test_data); ++i) {
     const int str_len = strlen(test_data[i]);
     iov.Append(const_cast<char*>(test_data[i]), str_len);
     length += str_len;
   }
   const struct iovec* iov2 = iov.iovec();
   ASSERT_TRUE(iov2 != nullptr);
-  ASSERT_EQ(ARRAYSIZE_UNSAFE(test_data), static_cast<size_t>(iov.Size()));
+  ASSERT_EQ(arraysize(test_data), static_cast<size_t>(iov.Size()));
 
   iov.Clear();
   iov2 = iov.iovec();
diff --git a/net/quic/quic_client_session.cc b/net/quic/quic_client_session.cc
index b7e8185..4495765 100644
--- a/net/quic/quic_client_session.cc
+++ b/net/quic/quic_client_session.cc
@@ -92,6 +92,18 @@
                             NUM_HANDSHAKE_STATES);
 }
 
+base::Value* NetLogQuicClientSessionCallback(
+    const QuicServerId* server_id,
+    bool require_confirmation,
+    NetLog::LogLevel /* log_level */) {
+  base::DictionaryValue* dict = new base::DictionaryValue();
+  dict->SetString("host", server_id->host());
+  dict->SetInteger("port", server_id->port());
+  dict->SetBoolean("is_https", server_id->is_https());
+  dict->SetBoolean("require_confirmation", require_confirmation);
+  return dict;
+}
+
 }  // namespace
 
 QuicClientSession::StreamRequest::StreamRequest() : stream_(nullptr) {}
@@ -174,9 +186,10 @@
                                      crypto_config));
   QuicClientSessionBase::InitializeSession();
   // TODO(rch): pass in full host port proxy pair
-  net_log_.BeginEvent(
-      NetLog::TYPE_QUIC_SESSION,
-      NetLog::StringCallback("host", &server_id.host()));
+  net_log_.BeginEvent(NetLog::TYPE_QUIC_SESSION,
+                      base::Bind(NetLogQuicClientSessionCallback,
+                                 &server_id,
+                                 require_confirmation_));
 }
 
 QuicClientSession::~QuicClientSession() {
diff --git a/net/quic/quic_end_to_end_unittest.cc b/net/quic/quic_end_to_end_unittest.cc
index b589bc6..96833af 100644
--- a/net/quic/quic_end_to_end_unittest.cc
+++ b/net/quic/quic_end_to_end_unittest.cc
@@ -75,7 +75,7 @@
  protected:
   QuicEndToEndTest()
       : host_resolver_impl_(CreateResolverImpl()),
-        host_resolver_(host_resolver_impl_.PassAs<HostResolver>()),
+        host_resolver_(host_resolver_impl_.Pass()),
         ssl_config_service_(new SSLConfigServiceDefaults),
         proxy_service_(ProxyService::CreateDirect()),
         auth_handler_factory_(
diff --git a/net/quic/quic_socket_address_coder_test.cc b/net/quic/quic_socket_address_coder_test.cc
index 56bed58..cbfac2b 100644
--- a/net/quic/quic_socket_address_coder_test.cc
+++ b/net/quic/quic_socket_address_coder_test.cc
@@ -100,7 +100,7 @@
     { "::1", 65534 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_case); i++) {
+  for (size_t i = 0; i < arraysize(test_case); i++) {
     IPAddressNumber ip;
     ASSERT_TRUE(ParseIPLiteralToNumber(test_case[i].ip_literal, &ip));
     QuicSocketAddressCoder encoder(IPEndPoint(ip, test_case[i].port));
diff --git a/net/quic/quic_utils_test.cc b/net/quic/quic_utils_test.cc
index 0a0355f..b7d23ed 100644
--- a/net/quic/quic_utils_test.cc
+++ b/net/quic/quic_utils_test.cc
@@ -53,7 +53,7 @@
       "0x0000:  6f72 6967 696e 616c                      original\n", },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     EXPECT_EQ(tests[i].expected,
               QuicUtils::StringToHexASCIIDump(tests[i].input.c_str()));
     EXPECT_EQ(tests[i].expected,
diff --git a/net/socket/client_socket_pool_base.h b/net/socket/client_socket_pool_base.h
index e2fde00..0378c99 100644
--- a/net/socket/client_socket_pool_base.h
+++ b/net/socket/client_socket_pool_base.h
@@ -741,10 +741,7 @@
                     internal::ClientSocketPoolBaseHelper::NORMAL,
                     params->ignore_limits(),
                     params, net_log));
-    return helper_.RequestSocket(
-        group_name,
-        request.template PassAs<
-            const internal::ClientSocketPoolBaseHelper::Request>());
+    return helper_.RequestSocket(group_name, request.Pass());
   }
 
   // RequestSockets bundles up the parameters into a Request and then forwards
diff --git a/net/socket/socket_test_util.cc b/net/socket/socket_test_util.cc
index a709060..5ae4eee 100644
--- a/net/socket/socket_test_util.cc
+++ b/net/socket/socket_test_util.cc
@@ -683,7 +683,7 @@
   data_provider->set_socket(socket.get());
   if (bind_type == DatagramSocket::RANDOM_BIND)
     socket->set_source_port(rand_int_cb.Run(1025, 65535));
-  return socket.PassAs<DatagramClientSocket>();
+  return socket.Pass();
 }
 
 scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket(
@@ -694,7 +694,7 @@
   scoped_ptr<MockTCPClientSocket> socket(
       new MockTCPClientSocket(addresses, net_log, data_provider));
   data_provider->set_socket(socket.get());
-  return socket.PassAs<StreamSocket>();
+  return socket.Pass();
 }
 
 scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket(
@@ -708,7 +708,7 @@
                               ssl_config,
                               mock_ssl_data_.GetNext()));
   ssl_client_sockets_.push_back(socket.get());
-  return socket.PassAs<SSLClientSocket>();
+  return socket.Pass();
 }
 
 void MockClientSocketFactory::ClearSSLSessionCache() {
@@ -1918,7 +1918,7 @@
   udp_client_sockets().push_back(socket.get());
   if (bind_type == DatagramSocket::RANDOM_BIND)
     socket->set_source_port(rand_int_cb.Run(1025, 65535));
-  return socket.PassAs<DatagramClientSocket>();
+  return socket.Pass();
 }
 
 scoped_ptr<StreamSocket>
@@ -1931,7 +1931,7 @@
       new DeterministicMockTCPClientSocket(net_log, data_provider));
   data_provider->set_delegate(socket->AsWeakPtr());
   tcp_client_sockets().push_back(socket.get());
-  return socket.PassAs<StreamSocket>();
+  return socket.Pass();
 }
 
 scoped_ptr<SSLClientSocket>
@@ -1945,7 +1945,7 @@
                               host_and_port, ssl_config,
                               mock_ssl_data_.GetNext()));
   ssl_client_sockets_.push_back(socket.get());
-  return socket.PassAs<SSLClientSocket>();
+  return socket.Pass();
 }
 
 void DeterministicMockClientSocketFactory::ClearSSLSessionCache() {
diff --git a/net/socket/socks_client_socket_unittest.cc b/net/socket/socks_client_socket_unittest.cc
index e3dc359..84aaf6f 100644
--- a/net/socket/socks_client_socket_unittest.cc
+++ b/net/socket/socks_client_socket_unittest.cc
@@ -214,7 +214,7 @@
 
   //---------------------------------------
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     MockWrite data_writes[] = {
         MockWrite(SYNCHRONOUS, kSOCKSOkRequest, arraysize(kSOCKSOkRequest)) };
     MockRead data_reads[] = {
diff --git a/net/socket/ssl_client_socket_pool.cc b/net/socket/ssl_client_socket_pool.cc
index a866b6c..56df1d8 100644
--- a/net/socket/ssl_client_socket_pool.cc
+++ b/net/socket/ssl_client_socket_pool.cc
@@ -552,7 +552,7 @@
   }
 
   if (result == OK || IsCertificateError(result)) {
-    SetSocket(ssl_socket_.PassAs<StreamSocket>());
+    SetSocket(ssl_socket_.Pass());
   } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
     error_response_info_.cert_request_info = new SSLCertRequestInfo;
     ssl_socket_->GetSSLCertRequestInfo(
diff --git a/net/socket/ssl_client_socket_pool_unittest.cc b/net/socket/ssl_client_socket_pool_unittest.cc
index 54b4ee1..202cd88 100644
--- a/net/socket/ssl_client_socket_pool_unittest.cc
+++ b/net/socket/ssl_client_socket_pool_unittest.cc
@@ -1279,7 +1279,7 @@
   };
 
   host_resolver_.set_synchronous_mode(true);
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_hosts); i++) {
+  for (size_t i = 0; i < arraysize(test_hosts); i++) {
     host_resolver_.rules()->AddIPLiteralRule(
         test_hosts[i].name, test_hosts[i].iplist, std::string());
 
@@ -1339,7 +1339,7 @@
 
   TestCompletionCallback callback;
   int rv;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_hosts); i++) {
+  for (size_t i = 0; i < arraysize(test_hosts); i++) {
     host_resolver_.rules()->AddIPLiteralRule(
         test_hosts[i].name, test_hosts[i].iplist, std::string());
 
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc
index 40a4d3c..7e7bf2c 100644
--- a/net/socket/ssl_client_socket_unittest.cc
+++ b/net/socket/ssl_client_socket_unittest.cc
@@ -858,10 +858,8 @@
     EXPECT_EQ(OK, rv);
 
     FakeBlockingStreamSocket* raw_transport = transport.get();
-    scoped_ptr<SSLClientSocket> sock =
-        CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                              test_server()->host_port_pair(),
-                              client_config);
+    scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
+        transport.Pass(), test_server()->host_port_pair(), client_config);
 
     if (monitor_handshake_callback_) {
       sock->SetHandshakeCompletionCallback(
@@ -1332,10 +1330,8 @@
   ssl_config.false_start_enabled = false;
 
   SynchronousErrorStreamSocket* raw_transport = transport.get();
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), ssl_config));
 
   raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
 
@@ -1370,10 +1366,8 @@
   ssl_config.false_start_enabled = false;
 
   SynchronousErrorStreamSocket* raw_transport = transport.get();
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), ssl_config));
 
   rv = callback.GetResult(sock->Connect(callback.callback()));
   EXPECT_EQ(OK, rv);
@@ -1423,7 +1417,7 @@
       new SynchronousErrorStreamSocket(real_transport.Pass()));
   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
   scoped_ptr<FakeBlockingStreamSocket> transport(
-      new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
+      new FakeBlockingStreamSocket(error_socket.Pass()));
   FakeBlockingStreamSocket* raw_transport = transport.get();
   int rv = callback.GetResult(transport->Connect(callback.callback()));
   EXPECT_EQ(OK, rv);
@@ -1432,10 +1426,8 @@
   SSLConfig ssl_config;
   ssl_config.false_start_enabled = false;
 
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), ssl_config));
 
   rv = callback.GetResult(sock->Connect(callback.callback()));
   EXPECT_EQ(OK, rv);
@@ -1497,7 +1489,7 @@
       new SynchronousErrorStreamSocket(real_transport.Pass()));
   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
   scoped_ptr<CountingStreamSocket> counting_socket(
-      new CountingStreamSocket(error_socket.PassAs<StreamSocket>()));
+      new CountingStreamSocket(error_socket.Pass()));
   CountingStreamSocket* raw_counting_socket = counting_socket.get();
   int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
   ASSERT_EQ(OK, rv);
@@ -1506,10 +1498,8 @@
   SSLConfig ssl_config;
   ssl_config.false_start_enabled = false;
 
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(counting_socket.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      counting_socket.Pass(), test_server.host_port_pair(), ssl_config));
 
   rv = callback.GetResult(sock->Connect(callback.callback()));
   ASSERT_EQ(OK, rv);
@@ -1627,7 +1617,7 @@
       new SynchronousErrorStreamSocket(real_transport.Pass()));
   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
   scoped_ptr<FakeBlockingStreamSocket> transport(
-      new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
+      new FakeBlockingStreamSocket(error_socket.Pass()));
   FakeBlockingStreamSocket* raw_transport = transport.get();
 
   int rv = callback.GetResult(transport->Connect(callback.callback()));
@@ -1637,10 +1627,8 @@
   SSLConfig ssl_config;
   ssl_config.false_start_enabled = false;
 
-  scoped_ptr<SSLClientSocket> sock =
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config);
+  scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), ssl_config);
 
   rv = callback.GetResult(sock->Connect(callback.callback()));
   EXPECT_EQ(OK, rv);
@@ -1743,7 +1731,7 @@
       new SynchronousErrorStreamSocket(real_transport.Pass()));
   SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
   scoped_ptr<FakeBlockingStreamSocket> transport(
-      new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
+      new FakeBlockingStreamSocket(error_socket.Pass()));
   FakeBlockingStreamSocket* raw_transport = transport.get();
 
   int rv = callback.GetResult(transport->Connect(callback.callback()));
@@ -1753,10 +1741,8 @@
   SSLConfig ssl_config;
   ssl_config.false_start_enabled = false;
 
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), ssl_config));
 
   rv = callback.GetResult(sock->Connect(callback.callback()));
   EXPECT_EQ(OK, rv);
@@ -1898,10 +1884,8 @@
   int rv = callback.GetResult(transport->Connect(callback.callback()));
   ASSERT_EQ(OK, rv);
 
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            kDefaultSSLConfig));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
 
   rv = callback.GetResult(sock->Connect(callback.callback()));
   ASSERT_EQ(OK, rv);
@@ -2701,10 +2685,8 @@
   ssl_config.false_start_enabled = false;
 
   SynchronousErrorStreamSocket* raw_transport = transport.get();
-  scoped_ptr<SSLClientSocket> sock(
-      CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
-                            test_server.host_port_pair(),
-                            ssl_config));
+  scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
+      transport.Pass(), test_server.host_port_pair(), ssl_config));
 
   sock->SetHandshakeCompletionCallback(base::Bind(
       &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
diff --git a/net/socket/tcp_listen_socket.cc b/net/socket/tcp_listen_socket.cc
index 223abee..585c412 100644
--- a/net/socket/tcp_listen_socket.cc
+++ b/net/socket/tcp_listen_socket.cc
@@ -107,7 +107,7 @@
 #if defined(OS_POSIX)
   sock->WatchSocket(WAITING_READ);
 #endif
-  socket_delegate_->DidAccept(this, sock.PassAs<StreamListenSocket>());
+  socket_delegate_->DidAccept(this, sock.Pass());
 }
 
 TCPListenSocketFactory::TCPListenSocketFactory(const string& ip, int port)
@@ -119,8 +119,7 @@
 
 scoped_ptr<StreamListenSocket> TCPListenSocketFactory::CreateAndListen(
     StreamListenSocket::Delegate* delegate) const {
-  return TCPListenSocket::CreateAndListen(ip_, port_, delegate)
-      .PassAs<StreamListenSocket>();
+  return TCPListenSocket::CreateAndListen(ip_, port_, delegate);
 }
 
 }  // namespace net
diff --git a/net/socket/transport_client_socket_pool_test_util.cc b/net/socket/transport_client_socket_pool_test_util.cc
index a56c6b1..bfe6922 100644
--- a/net/socket/transport_client_socket_pool_test_util.cc
+++ b/net/socket/transport_client_socket_pool_test_util.cc
@@ -187,7 +187,7 @@
         new MockTriggerableClientSocket(addrlist, should_connect, net_log));
     base::MessageLoop::current()->PostTask(FROM_HERE,
                                            socket->GetConnectCallback());
-    return socket.PassAs<StreamSocket>();
+    return socket.Pass();
   }
 
   static scoped_ptr<StreamSocket> MakeMockDelayedClientSocket(
@@ -199,7 +199,7 @@
         new MockTriggerableClientSocket(addrlist, should_connect, net_log));
     base::MessageLoop::current()->PostDelayedTask(
         FROM_HERE, socket->GetConnectCallback(), delay);
-    return socket.PassAs<StreamSocket>();
+    return socket.Pass();
   }
 
   static scoped_ptr<StreamSocket> MakeMockStalledClientSocket(
@@ -207,7 +207,7 @@
       net::NetLog* net_log) {
     scoped_ptr<MockTriggerableClientSocket> socket(
         new MockTriggerableClientSocket(addrlist, true, net_log));
-    return socket.PassAs<StreamSocket>();
+    return socket.Pass();
   }
 
   // StreamSocket implementation.
@@ -388,7 +388,7 @@
       // single-threaded.
       if (!run_loop_quit_closure_.is_null())
         run_loop_quit_closure_.Run();
-      return rv.PassAs<StreamSocket>();
+      return rv.Pass();
     }
     default:
       NOTREACHED();
diff --git a/net/socket/unix_domain_listen_socket_posix.cc b/net/socket/unix_domain_listen_socket_posix.cc
index dc7c19c..3e46439 100644
--- a/net/socket/unix_domain_listen_socket_posix.cc
+++ b/net/socket/unix_domain_listen_socket_posix.cc
@@ -124,7 +124,7 @@
       new UnixDomainListenSocket(conn, socket_delegate_, auth_callback_));
   // It's up to the delegate to AddRef if it wants to keep it around.
   sock->WatchSocket(WAITING_READ);
-  socket_delegate_->DidAccept(this, sock.PassAs<StreamListenSocket>());
+  socket_delegate_->DidAccept(this, sock.Pass());
 }
 
 UnixDomainListenSocketFactory::UnixDomainListenSocketFactory(
@@ -138,7 +138,7 @@
 scoped_ptr<StreamListenSocket> UnixDomainListenSocketFactory::CreateAndListen(
     StreamListenSocket::Delegate* delegate) const {
   return UnixDomainListenSocket::CreateAndListen(
-      path_, delegate, auth_callback_).PassAs<StreamListenSocket>();
+             path_, delegate, auth_callback_).Pass();
 }
 
 #if defined(SOCKET_ABSTRACT_NAMESPACE_SUPPORTED)
@@ -158,8 +158,7 @@
 UnixDomainListenSocketWithAbstractNamespaceFactory::CreateAndListen(
     StreamListenSocket::Delegate* delegate) const {
   return UnixDomainListenSocket::CreateAndListenWithAbstractNamespace(
-             path_, fallback_path_, delegate, auth_callback_)
-         .PassAs<StreamListenSocket>();
+      path_, fallback_path_, delegate, auth_callback_);
 }
 
 #endif
diff --git a/net/spdy/spdy_network_transaction_unittest.cc b/net/spdy/spdy_network_transaction_unittest.cc
index 92188ac..fc1b165 100644
--- a/net/spdy/spdy_network_transaction_unittest.cc
+++ b/net/spdy/spdy_network_transaction_unittest.cc
@@ -3238,7 +3238,7 @@
     test_cases[2].expected_headers["version"] = "HTTP/1.1";
   }
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     scoped_ptr<SpdyFrame> req(
         spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
     MockWrite writes[] = { CreateMockWrite(*req) };
@@ -3351,7 +3351,7 @@
     }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     // Construct the request.
     scoped_ptr<SpdyFrame> frame_req(
         spdy_util_.ConstructSpdyGet(test_cases[i].extra_headers[0],
@@ -3455,7 +3455,7 @@
     { 0, { NULL }, },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     scoped_ptr<SpdyFrame> req(
         spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
     scoped_ptr<SpdyFrame> rst(
@@ -3511,7 +3511,7 @@
     { syn_reply_wrong_length.get(), },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     scoped_ptr<SpdyFrame> req(
         spdy_util_.ConstructSpdyGet(NULL, 0, false, 1, LOWEST, true));
     scoped_ptr<SpdyFrame> rst(
diff --git a/net/spdy/spdy_session_pool_unittest.cc b/net/spdy/spdy_session_pool_unittest.cc
index ece5d34..0a9903c 100644
--- a/net/spdy/spdy_session_pool_unittest.cc
+++ b/net/spdy/spdy_session_pool_unittest.cc
@@ -339,7 +339,7 @@
   };
 
   session_deps_.host_resolver->set_synchronous_mode(true);
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_hosts); i++) {
+  for (size_t i = 0; i < arraysize(test_hosts); i++) {
     session_deps_.host_resolver->rules()->AddIPLiteralRule(
         test_hosts[i].name, test_hosts[i].iplist, std::string());
 
diff --git a/net/test/android/javatests/src/org/chromium/net/test/util/TestWebServer.java b/net/test/android/javatests/src/org/chromium/net/test/util/TestWebServer.java
index 1622e29..270b821 100644
--- a/net/test/android/javatests/src/org/chromium/net/test/util/TestWebServer.java
+++ b/net/test/android/javatests/src/org/chromium/net/test/util/TestWebServer.java
@@ -522,30 +522,30 @@
          * single self-generated key. The subject name is "Test Server".
          */
         private static final String SERVER_KEYS_BKS =
-            "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
-            "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
-            "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
-            "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
-            "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
-            "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
-            "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
-            "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
-            "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
-            "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
-            "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
-            "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
-            "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
-            "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
-            "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
-            "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
-            "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
-            "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
-            "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
-            "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
-            "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
-            "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
-            "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
-            "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
+                "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
+                "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
+                "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
+                "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
+                "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
+                "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
+                "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
+                "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
+                "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
+                "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
+                "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
+                "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
+                "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
+                "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
+                "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
+                "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
+                "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
+                "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
+                "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
+                "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
+                "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
+                "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
+                "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
+                "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
 
         private static final String PASSWORD = "android";
 
diff --git a/net/test/embedded_test_server/embedded_test_server.cc b/net/test/embedded_test_server/embedded_test_server.cc
index b266c55..98f50b6 100644
--- a/net/test/embedded_test_server/embedded_test_server.cc
+++ b/net/test/embedded_test_server/embedded_test_server.cc
@@ -73,13 +73,13 @@
 
     scoped_ptr<CustomHttpResponse> http_response(
         new CustomHttpResponse(headers_contents, file_contents));
-    return http_response.PassAs<HttpResponse>();
+    return http_response.Pass();
   }
 
   scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse);
   http_response->set_code(HTTP_OK);
   http_response->set_content(file_contents);
-  return http_response.PassAs<HttpResponse>();
+  return http_response.Pass();
 }
 
 }  // namespace
@@ -243,8 +243,7 @@
                  << request->relative_url;
     scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse);
     not_found_response->set_code(HTTP_NOT_FOUND);
-    connection->SendResponse(
-        not_found_response.PassAs<HttpResponse>());
+    connection->SendResponse(not_found_response.Pass());
   }
 
   // Drop the connection, since we do not support multiple requests per
diff --git a/net/test/embedded_test_server/embedded_test_server_unittest.cc b/net/test/embedded_test_server/embedded_test_server_unittest.cc
index 9da982c..6a1df6e 100644
--- a/net/test/embedded_test_server/embedded_test_server_unittest.cc
+++ b/net/test/embedded_test_server/embedded_test_server_unittest.cc
@@ -95,10 +95,10 @@
       http_response->set_code(code);
       http_response->set_content(content);
       http_response->set_content_type(content_type);
-      return http_response.PassAs<HttpResponse>();
+      return http_response.Pass();
     }
 
-    return scoped_ptr<HttpResponse>();
+    return nullptr;
   }
 
  protected:
diff --git a/net/udp/udp_socket_unittest.cc b/net/udp/udp_socket_unittest.cc
index 100692c..83689c7 100644
--- a/net/udp/udp_socket_unittest.cc
+++ b/net/udp/udp_socket_unittest.cc
@@ -441,7 +441,7 @@
     { "2001:db8:0::42", "::1", true },
 #endif
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
+  for (size_t i = 0; i < arraysize(tests); i++) {
     SCOPED_TRACE(std::string("Connecting from ") +  tests[i].local_address +
                  std::string(" to ") + tests[i].remote_address);
 
diff --git a/net/url_request/url_fetcher_response_writer.cc b/net/url_request/url_fetcher_response_writer.cc
index fcc8cbf..3c66dd3 100644
--- a/net/url_request/url_fetcher_response_writer.cc
+++ b/net/url_request/url_fetcher_response_writer.cc
@@ -6,6 +6,7 @@
 
 #include "base/files/file_util.h"
 #include "base/location.h"
+#include "base/profiler/scoped_profile.h"
 #include "base/sequenced_task_runner.h"
 #include "base/task_runner_util.h"
 #include "net/base/file_stream.h"
@@ -173,6 +174,11 @@
 
 void URLFetcherFileWriter::DidOpenFile(const CompletionCallback& callback,
                                        int result) {
+  // TODO(vadimt): Remove ScopedProfile below once crbug.com/423948 is fixed.
+  tracked_objects::ScopedProfile tracking_profile(
+      FROM_HERE_WITH_EXPLICIT_FUNCTION(
+          "423948 URLFetcherFileWriter::DidOpenFile"));
+
   if (result == OK)
     owns_file_ = true;
   else
diff --git a/net/url_request/url_request_file_job.cc b/net/url_request/url_request_file_job.cc
index b139918..6fc4d1c 100644
--- a/net/url_request/url_request_file_job.cc
+++ b/net/url_request/url_request_file_job.cc
@@ -23,6 +23,7 @@
 #include "base/compiler_specific.h"
 #include "base/files/file_util.h"
 #include "base/message_loop/message_loop.h"
+#include "base/profiler/scoped_profile.h"
 #include "base/strings/string_util.h"
 #include "base/synchronization/lock.h"
 #include "base/task_runner.h"
@@ -249,6 +250,10 @@
 }
 
 void URLRequestFileJob::DidOpen(int result) {
+  // TODO(vadimt): Remove ScopedProfile below once crbug.com/423948 is fixed.
+  tracked_objects::ScopedProfile tracking_profile(
+      FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 URLRequestFileJob::DidOpen"));
+
   if (result != OK) {
     NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, result));
     return;
diff --git a/net/url_request/url_request_throttler_simulation_unittest.cc b/net/url_request/url_request_throttler_simulation_unittest.cc
index 2f3abbf..129a776 100644
--- a/net/url_request/url_request_throttler_simulation_unittest.cc
+++ b/net/url_request/url_request_throttler_simulation_unittest.cc
@@ -718,7 +718,7 @@
   // If things don't converge by the time we've done 100K trials, then
   // clearly one or more of the expected intervals are wrong.
   while (global_stats.num_runs < 100000) {
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(trials); ++i) {
+    for (size_t i = 0; i < arraysize(trials); ++i) {
       ++global_stats.num_runs;
       ++trials[i].stats.num_runs;
       double ratio_unprotected = SimulateDowntime(
@@ -746,7 +746,7 @@
 
   // Print individual trial results for optional manual evaluation.
   double max_increase_ratio = 0.0;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(trials); ++i) {
+  for (size_t i = 0; i < arraysize(trials); ++i) {
     double increase_ratio;
     trials[i].stats.DidConverge(&increase_ratio);
     max_increase_ratio = std::max(max_increase_ratio, increase_ratio);
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc
index 0f64a7c..5756801 100644
--- a/net/url_request/url_request_unittest.cc
+++ b/net/url_request/url_request_unittest.cc
@@ -6342,7 +6342,7 @@
                 { "echoheader?Accept-Charset", "None" },
                 { "echoheader?User-Agent", "" } };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
+  for (size_t i = 0; i < arraysize(tests); i++) {
     TestDelegate d;
     scoped_ptr<URLRequest> req(context.CreateRequest(
         test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, NULL));
diff --git a/net/websockets/websocket_channel_test.cc b/net/websockets/websocket_channel_test.cc
index 6535741..c7bfeb0 100644
--- a/net/websockets/websocket_channel_test.cc
+++ b/net/websockets/websocket_channel_test.cc
@@ -780,10 +780,7 @@
   // will have unpleasant compile errors.
   template <class T>
   void set_stream(scoped_ptr<T> stream) {
-    // Since the definition of "PassAs" depends on the type T, the C++ standard
-    // requires the "template" keyword to indicate that "PassAs" should be
-    // parsed as a template method.
-    stream_ = stream.template PassAs<WebSocketStream>();
+    stream_ = stream.Pass();
   }
 
   // A struct containing the data that will be used to connect the channel.
diff --git a/net/websockets/websocket_frame_parser_test.cc b/net/websockets/websocket_frame_parser_test.cc
index 4eb036d..14f7113 100644
--- a/net/websockets/websocket_frame_parser_test.cc
+++ b/net/websockets/websocket_frame_parser_test.cc
@@ -126,7 +126,7 @@
     { "\x81\x05" "Ninth", 7, "Ninth", 5 },
     { "\x81\x05" "Tenth", 7, "Tenth", 5 }
   };
-  static const int kNumInputs = ARRAYSIZE_UNSAFE(kInputs);
+  static const int kNumInputs = arraysize(kInputs);
 
   std::vector<char> input;
   // Concatenate all frames.
@@ -432,7 +432,7 @@
     { "\x81\x7F\x00\x00\x00\x00\x00\x00\x00\x00", 10 },
     { "\x81\x7E\x00\x00\x00\x00\x00\x00\xFF\xFF", 10 },
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     const char* frame_header = kTests[i].frame_header;
@@ -480,7 +480,7 @@
     { "\x8E\x00", 2, 0xE },
     { "\x8F\x00", 2, 0xF }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     const char* frame_header = kTests[i].frame_header;
@@ -533,7 +533,7 @@
     { "\x71\x00", 2, false, true, true, true },
     { "\xF1\x00", 2, true, true, true, true }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     const char* frame_header = kTests[i].frame_header;
diff --git a/net/websockets/websocket_frame_test.cc b/net/websockets/websocket_frame_test.cc
index cd76ccc..104bab5 100644
--- a/net/websockets/websocket_frame_test.cc
+++ b/net/websockets/websocket_frame_test.cc
@@ -31,7 +31,7 @@
     { "\x81\x7F\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 10,
       GG_UINT64_C(0x7FFFFFFFFFFFFFFF) }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
@@ -51,7 +51,7 @@
 
 TEST(WebSocketFrameHeaderTest, FrameLengthsWithMasking) {
   static const char kMaskingKey[] = "\xDE\xAD\xBE\xEF";
-  COMPILE_ASSERT(ARRAYSIZE_UNSAFE(kMaskingKey) - 1 ==
+  COMPILE_ASSERT(arraysize(kMaskingKey) - 1 ==
                      WebSocketFrameHeader::kMaskingKeyLength,
                  incorrect_masking_key_size);
 
@@ -70,7 +70,7 @@
     { "\x81\xFF\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xDE\xAD\xBE\xEF", 14,
       GG_UINT64_C(0x7FFFFFFFFFFFFFFF) }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   WebSocketMaskingKey masking_key;
   std::copy(kMaskingKey,
@@ -119,7 +119,7 @@
     { "\x8E\x00", 2, 0xE },
     { "\x8F\x00", 2, 0xF }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     WebSocketFrameHeader header(kTests[i].opcode);
@@ -155,7 +155,7 @@
     { "\x71\x00", 2, false, true, true, true },
     { "\xF1\x00", 2, true, true, true, true }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
@@ -196,7 +196,7 @@
     { GG_UINT64_C(0x10000), true, 14u },
     { GG_UINT64_C(0x7FFFFFFFFFFFFFFF), true, 14u }
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     WebSocketFrameHeader header(WebSocketFrameHeader::kOpCodeText);
@@ -235,7 +235,7 @@
     { "\x00\x00\x00\x00", 0, "FooBar", "FooBar", 6 },
     { "\xFF\xFF\xFF\xFF", 0, "FooBar", "\xB9\x90\x90\xBD\x9E\x8D", 6 },
   };
-  static const int kNumTests = ARRAYSIZE_UNSAFE(kTests);
+  static const int kNumTests = arraysize(kTests);
 
   for (int i = 0; i < kNumTests; ++i) {
     WebSocketMaskingKey masking_key;
diff --git a/net/websockets/websocket_stream.cc b/net/websockets/websocket_stream.cc
index 90cb7ca..04beb26 100644
--- a/net/websockets/websocket_stream.cc
+++ b/net/websockets/websocket_stream.cc
@@ -316,7 +316,7 @@
                             connect_delegate.Pass(),
                             create_helper.Pass()));
   request->Start(scoped_ptr<base::Timer>(new base::Timer(false, false)));
-  return request.PassAs<WebSocketStreamRequest>();
+  return request.Pass();
 }
 
 // This is declared in websocket_test_util.h.
@@ -335,7 +335,7 @@
                             connect_delegate.Pass(),
                             create_helper.Pass()));
   request->Start(timer.Pass());
-  return request.PassAs<WebSocketStreamRequest>();
+  return request.Pass();
 }
 
 void WebSocketDispatchOnFinishOpeningHandshake(
diff --git a/net/websockets/websocket_stream_test.cc b/net/websockets/websocket_stream_test.cc
index 0b7ae4e..2fd9891 100644
--- a/net/websockets/websocket_stream_test.cc
+++ b/net/websockets/websocket_stream_test.cc
@@ -1121,9 +1121,11 @@
   socket_data->set_connect_data(MockConnect(SYNCHRONOUS, ERR_IO_PENDING));
   scoped_ptr<MockWeakTimer> timer(new MockWeakTimer(false, false));
   base::WeakPtr<MockWeakTimer> weak_timer = timer->AsWeakPtr();
-  CreateAndConnectRawExpectations("ws://localhost/", NoSubProtocols(),
-                                  "http://localhost", socket_data.Pass(),
-                                  timer.PassAs<base::Timer>());
+  CreateAndConnectRawExpectations("ws://localhost/",
+                                  NoSubProtocols(),
+                                  "http://localhost",
+                                  socket_data.Pass(),
+                                  timer.Pass());
   EXPECT_FALSE(has_failed());
   ASSERT_TRUE(weak_timer.get());
   EXPECT_TRUE(weak_timer->IsRunning());
@@ -1142,9 +1144,13 @@
   scoped_ptr<MockWeakTimer> timer(new MockWeakTimer(false, false));
   base::WeakPtr<MockWeakTimer> weak_timer = timer->AsWeakPtr();
 
-  CreateAndConnectStandard(
-      "ws://localhost/", "/", NoSubProtocols(), "http://localhost", "", "",
-      timer.PassAs<base::Timer>());
+  CreateAndConnectStandard("ws://localhost/",
+                           "/",
+                           NoSubProtocols(),
+                           "http://localhost",
+                           "",
+                           "",
+                           timer.Pass());
   ASSERT_TRUE(weak_timer);
   EXPECT_TRUE(weak_timer->IsRunning());
 
@@ -1162,9 +1168,11 @@
       MockConnect(SYNCHRONOUS, ERR_CONNECTION_REFUSED));
   scoped_ptr<MockWeakTimer> timer(new MockWeakTimer(false, false));
   base::WeakPtr<MockWeakTimer> weak_timer = timer->AsWeakPtr();
-  CreateAndConnectRawExpectations("ws://localhost/", NoSubProtocols(),
-                                  "http://localhost", socket_data.Pass(),
-                                  timer.PassAs<base::Timer>());
+  CreateAndConnectRawExpectations("ws://localhost/",
+                                  NoSubProtocols(),
+                                  "http://localhost",
+                                  socket_data.Pass(),
+                                  timer.Pass());
   ASSERT_TRUE(weak_timer.get());
   EXPECT_TRUE(weak_timer->IsRunning());
 
diff --git a/skia/PRESUBMIT.py b/skia/PRESUBMIT.py
index 61472af..6ba31dc 100644
--- a/skia/PRESUBMIT.py
+++ b/skia/PRESUBMIT.py
@@ -13,9 +13,4 @@
     'tryserver.blink': {
       'linux_blink_rel': set(['defaulttests']),
     },
-    'tryserver.chromium.gpu': {
-      'linux_gpu': set(['defaulttests']),
-      'win_gpu': set(['defaulttests']),
-      'mac_gpu': set(['defaulttests']),
-    },
   }
diff --git a/testing/android/java/src/org/chromium/native_test/ChromeNativeTestActivity.java b/testing/android/java/src/org/chromium/native_test/ChromeNativeTestActivity.java
index 4d4839c..7482af8 100644
--- a/testing/android/java/src/org/chromium/native_test/ChromeNativeTestActivity.java
+++ b/testing/android/java/src/org/chromium/native_test/ChromeNativeTestActivity.java
@@ -54,11 +54,11 @@
             // Post a task to run the tests. This allows us to not block
             // onCreate and still run tests on the main thread.
             new Handler().postDelayed(new Runnable() {
-                  @Override
-                  public void run() {
-                      runTests();
-                  }
-              }, RUN_TESTS_DELAY_IN_MS);
+                @Override
+                public void run() {
+                    runTests();
+                }
+            }, RUN_TESTS_DELAY_IN_MS);
         }
     }
 
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json
index d3bc9fb..cb1a8e5 100644
--- a/testing/buildbot/chromium.fyi.json
+++ b/testing/buildbot/chromium.fyi.json
@@ -303,13 +303,13 @@
   "Site Isolation Linux": {
     "gtest_tests": [
       { "test": "content_unittests", "args": ["--site-per-process"] },
-      { "test": "content_browsertests", "args": ["--site-per-process"] }
+      { "test": "content_browsertests", "args": ["--site-per-process --gtest_filter=-RenderFrameHostManagerTest.AllowTargetedNavigationsAfterSwap:-RenderFrameHostManagerTest.SupportCrossProcessPostMessage:-SiteIsolationPolicyBrowserTest.CrossSiteDocumentBlockingForDifferentTargets:-RenderFrameHostManagerTest.DontSwapProcessWithOnlyTargetBlank:-RenderFrameHostManagerTest.DisownOpener:-FrameTreeBrowserTest.NavigateWithLeftoverFrames:-RenderFrameHostManagerTest.DontPreemptNavigationWithFrameTreeUpdate:-RenderFrameHostManagerTest.ProcessExitWithSwappedOutViews:-RenderFrameHostManagerTest.SupportCrossProcessPostMessageWithMessagePort:-RenderFrameHostManagerTest.AllowTargetedNavigationsInOpenerAfterSwap"] }
     ]
   },
   "Site Isolation Win": {
     "gtest_tests": [
       { "test": "content_unittests", "args": ["--site-per-process"] },
-      { "test": "content_browsertests", "args": ["--site-per-process"] }
+      { "test": "content_browsertests", "args": ["--site-per-process --gtest_filter=-RenderFrameHostManagerTest.AllowTargetedNavigationsAfterSwap:-RenderFrameHostManagerTest.SupportCrossProcessPostMessage:-SiteIsolationPolicyBrowserTest.CrossSiteDocumentBlockingForDifferentTargets:-RenderFrameHostManagerTest.DontSwapProcessWithOnlyTargetBlank:-RenderFrameHostManagerTest.DisownOpener:-FrameTreeBrowserTest.NavigateWithLeftoverFrames:-RenderFrameHostManagerTest.DontPreemptNavigationWithFrameTreeUpdate:-RenderFrameHostManagerTest.ProcessExitWithSwappedOutViews:-RenderFrameHostManagerTest.SupportCrossProcessPostMessageWithMessagePort:-RenderFrameHostManagerTest.AllowTargetedNavigationsInOpenerAfterSwap"] }
     ]
   },
   "Linux ChromeOS MSan Tests": {
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json
index 6ba4c8a..1216d6e 100644
--- a/testing/buildbot/chromium.memory.json
+++ b/testing/buildbot/chromium.memory.json
@@ -52,7 +52,8 @@
       {
         "test": "net_unittests",
         "swarming": {
-          "can_use_on_swarming_builders": true
+          "can_use_on_swarming_builders": true,
+          "shards": 4
         }
       },
       "ppapi_unittests",
@@ -65,7 +66,8 @@
       {
         "test": "unit_tests",
         "swarming": {
-          "can_use_on_swarming_builders": true
+          "can_use_on_swarming_builders": true,
+          "shards": 2
         }
       },
       "url_unittests"
@@ -284,7 +286,8 @@
       {
         "test": "net_unittests",
         "swarming": {
-          "can_use_on_swarming_builders": true
+          "can_use_on_swarming_builders": true,
+          "shards": 4
         }
       },
       "ppapi_unittests",
@@ -296,7 +299,8 @@
       {
         "test": "unit_tests",
         "swarming": {
-          "can_use_on_swarming_builders": true
+          "can_use_on_swarming_builders": true,
+          "shards": 2
         }
       },
       "ui_unittests",
diff --git a/testing/buildbot/chromium_trybot.json b/testing/buildbot/chromium_trybot.json
index c11d231..e2fe64d 100644
--- a/testing/buildbot/chromium_trybot.json
+++ b/testing/buildbot/chromium_trybot.json
@@ -174,7 +174,7 @@
     "url_unittests",
     {
       "test": "wm_unittests",
-      "platforms": ["linux"]
+      "platforms": ["linux", "win"]
     },
     {
       "test": "app_shell_browsertests",
@@ -218,6 +218,7 @@
       "test": "athena_unittests",
       "platforms": ["linux"],
       "chromium_configs": [
+        "chromium_chromeos",
         "chromium_chromeos_athena",
         "chromium_chromeos_ozone"
       ]
diff --git a/testing/buildbot/trybot_analyze_config.json b/testing/buildbot/trybot_analyze_config.json
index 4d12f02..d7f445f 100644
--- a/testing/buildbot/trybot_analyze_config.json
+++ b/testing/buildbot/trybot_analyze_config.json
@@ -22,10 +22,17 @@
   "chromium": {
     "exclusions": [
       "chrome/test/data/.*",
+      "components/test/data/.*",
       "content/test/data/.*",
       "content/test/gpu/.*",
+      "extensions/test/data/.*",
       "gpu/gles2_conform_support/gles2_conform_test_expectations.txt",
+      "media/test/data/.*",
       "net/data/.*",
+      "sql/test/data/.*",
+      "third_party/accessibility-audit/axs_testing.js",
+      "third_party/hunspell_dictionaries/.*",
+      "third_party/zlib/google/test/data/.*",
       "tools/clang/scripts/plugin_flags.sh",
       "tools/clang/scripts/update.py",
       "tools/clang/scripts/update.sh",
diff --git a/testing/chromoting/integration_tests.gyp b/testing/chromoting/integration_tests.gyp
index b6c801d..23fcf6f 100644
--- a/testing/chromoting/integration_tests.gyp
+++ b/testing/chromoting/integration_tests.gyp
@@ -12,6 +12,7 @@
           'dependencies': [
             '../../chrome/chrome.gyp:browser_tests',
             '../../remoting/remoting.gyp:remoting_webapp_v1',
+            '../../remoting/remoting.gyp:remoting_webapp_v2',
           ],
           'includes': [
             '../../build/isolate.gypi',
diff --git a/testing/test_env.py b/testing/test_env.py
index 0539309..574aaed 100755
--- a/testing/test_env.py
+++ b/testing/test_env.py
@@ -81,10 +81,7 @@
   extra_env = {}
 
   # Instruct GTK to use malloc while running ASan or LSan tests.
-  # TODO(earthdok): enabling G_SLICE gives these leaks, locally and on swarming
-  #0 0x62c01b in __interceptor_malloc (/tmp/run_tha_testXukBDT/out/Release/browser_tests+0x62c01b)
-  #1 0x7fb64ab64a38 in g_malloc /build/buildd/glib2.0-2.32.4/./glib/gmem.c:159
-  #extra_env['G_SLICE'] = 'always-malloc'
+  extra_env['G_SLICE'] = 'always-malloc'
 
   extra_env['NSS_DISABLE_ARENA_FREE_LIST'] = '1'
   extra_env['NSS_DISABLE_UNLOAD'] = '1'
diff --git a/tools/android/memconsumer/java/src/org/chromium/memconsumer/ResidentService.java b/tools/android/memconsumer/java/src/org/chromium/memconsumer/ResidentService.java
index e40fbfe..4d3d03f 100644
--- a/tools/android/memconsumer/java/src/org/chromium/memconsumer/ResidentService.java
+++ b/tools/android/memconsumer/java/src/org/chromium/memconsumer/ResidentService.java
@@ -38,14 +38,14 @@
             Intent notificationIntent = new Intent(this, MemConsumer.class);
             notificationIntent.setAction(MemConsumer.NOTIFICATION_ACTION);
             PendingIntent pendingIntent =
-                PendingIntent.getActivity(this, 0, notificationIntent, 0);
+                    PendingIntent.getActivity(this, 0, notificationIntent, 0);
             Notification notification =
-                new Notification.Builder(getApplicationContext()).
-                    setContentTitle("MC running (" + memory + "Mb)").
-                    setSmallIcon(R.drawable.notification_icon).
-                    setDeleteIntent(pendingIntent).
-                    setContentIntent(pendingIntent).
-                    build();
+                    new Notification.Builder(getApplicationContext()).
+                            setContentTitle("MC running (" + memory + "Mb)").
+                            setSmallIcon(R.drawable.notification_icon).
+                            setDeleteIntent(pendingIntent).
+                            setContentIntent(pendingIntent).
+                            build();
             startForeground(RESIDENT_NOTIFICATION_ID, notification);
             mIsInForeground = true;
         }
diff --git a/tools/clang/blink_gc_plugin/CMakeLists.txt b/tools/clang/blink_gc_plugin/CMakeLists.txt
index df2bc63..85ce4a9 100644
--- a/tools/clang/blink_gc_plugin/CMakeLists.txt
+++ b/tools/clang/blink_gc_plugin/CMakeLists.txt
@@ -8,6 +8,8 @@
                          RecordInfo.cpp
                         )
 
+add_dependencies("lib${LIBRARYNAME}" clang)
+
 cr_install(TARGETS "lib${LIBRARYNAME}" LIBRARY DESTINATION lib)
 
 cr_add_test(blink_gc_plugin_test
diff --git a/tools/clang/plugins/CMakeLists.txt b/tools/clang/plugins/CMakeLists.txt
index 7dcdb48..d17de19 100644
--- a/tools/clang/plugins/CMakeLists.txt
+++ b/tools/clang/plugins/CMakeLists.txt
@@ -4,6 +4,8 @@
                          FindBadConstructsConsumer.cpp
                         )
 
+add_dependencies(libFindBadConstructs clang)
+
 cr_install(TARGETS libFindBadConstructs LIBRARY DESTINATION lib)
 
 cr_add_test(plugins_test
diff --git a/tools/clang/scripts/update.sh b/tools/clang/scripts/update.sh
index bfd586e..e576cac 100755
--- a/tools/clang/scripts/update.sh
+++ b/tools/clang/scripts/update.sh
@@ -8,7 +8,7 @@
 # Do NOT CHANGE this if you don't know what you're doing -- see
 # https://code.google.com/p/chromium/wiki/UpdatingClang
 # Reverting problematic clang rolls is safe, though.
-CLANG_REVISION=217949
+CLANG_REVISION=218707
 
 THIS_DIR="$(dirname "${0}")"
 LLVM_DIR="${THIS_DIR}/../../../third_party/llvm"
@@ -235,12 +235,19 @@
       "${CLANG_DIR}/unittests/libclang/LibclangTest.cpp" \
       "${COMPILER_RT_DIR}/lib/asan/asan_rtl.cc" \
       "${COMPILER_RT_DIR}/test/asan/TestCases/Linux/new_array_cookie_test.cc" \
+      "${LLVM_DIR}/test/DebugInfo/gmlt.ll" \
+      "${LLVM_DIR}/lib/CodeGen/SpillPlacement.cpp" \
+      "${LLVM_DIR}/lib/CodeGen/SpillPlacement.h" \
       ; do
   if [[ -e "${i}" ]]; then
     svn revert "${i}"
   fi;
 done
 
+echo Remove the Clang tools shim dir
+CHROME_TOOLS_SHIM_DIR=${ABS_LLVM_DIR}/tools/chrometools
+rm -rfv ${CHROME_TOOLS_SHIM_DIR}
+
 echo Getting LLVM r"${CLANG_REVISION}" in "${LLVM_DIR}"
 if ! svn co --force "${LLVM_REPO_URL}/llvm/trunk@${CLANG_REVISION}" \
                     "${LLVM_DIR}"; then
@@ -310,6 +317,180 @@
 patch -p0
 popd
 
+# Apply r218742: test: XFAIL the non-darwin gmlt test on darwin
+# Back-ported becase the test was renamed.
+pushd "${LLVM_DIR}"
+cat << 'EOF' |
+--- a/test/DebugInfo/gmlt.ll
++++ b/test/DebugInfo/gmlt.ll
+@@ -1,2 +1,5 @@
+ ; REQUIRES: object-emission
+ ; RUN: %llc_dwarf -O0 -filetype=obj < %S/Inputs/gmlt.ll | llvm-dwarfdump - | FileCheck %S/Inputs/gmlt.ll
++
++; There's a darwin specific test in X86/gmlt, so it's okay to XFAIL this here.
++; XFAIL: darwin
+EOF
+patch -p1
+popd
+
+# Apply r218921; fixes spill placement compile-time regression.
+pushd "${LLVM_DIR}"
+cat << 'EOF' |
+--- a/lib/CodeGen/SpillPlacement.cpp
++++ b/lib/CodeGen/SpillPlacement.cpp
+@@ -61,27 +61,6 @@ void SpillPlacement::getAnalysisUsage(AnalysisUsage &AU) const {
+   MachineFunctionPass::getAnalysisUsage(AU);
+ }
+ 
+-namespace {
+-static ManagedStatic<BlockFrequency> Threshold;
+-}
+-
+-/// Decision threshold. A node gets the output value 0 if the weighted sum of
+-/// its inputs falls in the open interval (-Threshold;Threshold).
+-static BlockFrequency getThreshold() { return *Threshold; }
+-
+-/// \brief Set the threshold for a given entry frequency.
+-///
+-/// Set the threshold relative to \c Entry.  Since the threshold is used as a
+-/// bound on the open interval (-Threshold;Threshold), 1 is the minimum
+-/// threshold.
+-static void setThreshold(const BlockFrequency &Entry) {
+-  // Apparently 2 is a good threshold when Entry==2^14, but we need to scale
+-  // it.  Divide by 2^13, rounding as appropriate.
+-  uint64_t Freq = Entry.getFrequency();
+-  uint64_t Scaled = (Freq >> 13) + bool(Freq & (1 << 12));
+-  *Threshold = std::max(UINT64_C(1), Scaled);
+-}
+-
+ /// Node - Each edge bundle corresponds to a Hopfield node.
+ ///
+ /// The node contains precomputed frequency data that only depends on the CFG,
+@@ -127,9 +106,9 @@ struct SpillPlacement::Node {
+ 
+   /// clear - Reset per-query data, but preserve frequencies that only depend on
+   // the CFG.
+-  void clear() {
++  void clear(const BlockFrequency &Threshold) {
+     BiasN = BiasP = Value = 0;
+-    SumLinkWeights = getThreshold();
++    SumLinkWeights = Threshold;
+     Links.clear();
+   }
+ 
+@@ -167,7 +146,7 @@ struct SpillPlacement::Node {
+ 
+   /// update - Recompute Value from Bias and Links. Return true when node
+   /// preference changes.
+-  bool update(const Node nodes[]) {
++  bool update(const Node nodes[], const BlockFrequency &Threshold) {
+     // Compute the weighted sum of inputs.
+     BlockFrequency SumN = BiasN;
+     BlockFrequency SumP = BiasP;
+@@ -187,9 +166,9 @@ struct SpillPlacement::Node {
+     //  2. It helps tame rounding errors when the links nominally sum to 0.
+     //
+     bool Before = preferReg();
+-    if (SumN >= SumP + getThreshold())
++    if (SumN >= SumP + Threshold)
+       Value = -1;
+-    else if (SumP >= SumN + getThreshold())
++    else if (SumP >= SumN + Threshold)
+       Value = 1;
+     else
+       Value = 0;
+@@ -228,7 +207,7 @@ void SpillPlacement::activate(unsigned n) {
+   if (ActiveNodes->test(n))
+     return;
+   ActiveNodes->set(n);
+-  nodes[n].clear();
++  nodes[n].clear(Threshold);
+ 
+   // Very large bundles usually come from big switches, indirect branches,
+   // landing pads, or loops with many 'continue' statements. It is difficult to
+@@ -245,6 +224,18 @@ void SpillPlacement::activate(unsigned n) {
+   }
+ }
+ 
++/// \brief Set the threshold for a given entry frequency.
++///
++/// Set the threshold relative to \c Entry.  Since the threshold is used as a
++/// bound on the open interval (-Threshold;Threshold), 1 is the minimum
++/// threshold.
++void SpillPlacement::setThreshold(const BlockFrequency &Entry) {
++  // Apparently 2 is a good threshold when Entry==2^14, but we need to scale
++  // it.  Divide by 2^13, rounding as appropriate.
++  uint64_t Freq = Entry.getFrequency();
++  uint64_t Scaled = (Freq >> 13) + bool(Freq & (1 << 12));
++  Threshold = std::max(UINT64_C(1), Scaled);
++}
+ 
+ /// addConstraints - Compute node biases and weights from a set of constraints.
+ /// Set a bit in NodeMask for each active node.
+@@ -311,7 +302,7 @@ bool SpillPlacement::scanActiveBundles() {
+   Linked.clear();
+   RecentPositive.clear();
+   for (int n = ActiveNodes->find_first(); n>=0; n = ActiveNodes->find_next(n)) {
+-    nodes[n].update(nodes);
++    nodes[n].update(nodes, Threshold);
+     // A node that must spill, or a node without any links is not going to
+     // change its value ever again, so exclude it from iterations.
+     if (nodes[n].mustSpill())
+@@ -331,7 +322,7 @@ void SpillPlacement::iterate() {
+   // First update the recently positive nodes. They have likely received new
+   // negative bias that will turn them off.
+   while (!RecentPositive.empty())
+-    nodes[RecentPositive.pop_back_val()].update(nodes);
++    nodes[RecentPositive.pop_back_val()].update(nodes, Threshold);
+ 
+   if (Linked.empty())
+     return;
+@@ -350,7 +341,7 @@ void SpillPlacement::iterate() {
+            iteration == 0 ? Linked.rbegin() : std::next(Linked.rbegin()),
+            E = Linked.rend(); I != E; ++I) {
+       unsigned n = *I;
+-      if (nodes[n].update(nodes)) {
++      if (nodes[n].update(nodes, Threshold)) {
+         Changed = true;
+         if (nodes[n].preferReg())
+           RecentPositive.push_back(n);
+@@ -364,7 +355,7 @@ void SpillPlacement::iterate() {
+     for (SmallVectorImpl<unsigned>::const_iterator I =
+            std::next(Linked.begin()), E = Linked.end(); I != E; ++I) {
+       unsigned n = *I;
+-      if (nodes[n].update(nodes)) {
++      if (nodes[n].update(nodes, Threshold)) {
+         Changed = true;
+         if (nodes[n].preferReg())
+           RecentPositive.push_back(n);
+diff --git a/lib/CodeGen/SpillPlacement.h b/lib/CodeGen/SpillPlacement.h
+index 03cf5cd..622361e 100644
+--- a/lib/CodeGen/SpillPlacement.h
++++ b/lib/CodeGen/SpillPlacement.h
+@@ -62,6 +62,10 @@ class SpillPlacement : public MachineFunctionPass {
+   // Block frequencies are computed once. Indexed by block number.
+   SmallVector<BlockFrequency, 8> BlockFrequencies;
+ 
++  /// Decision threshold. A node gets the output value 0 if the weighted sum of
++  /// its inputs falls in the open interval (-Threshold;Threshold).
++  BlockFrequency Threshold;
++
+ public:
+   static char ID; // Pass identification, replacement for typeid.
+ 
+@@ -152,6 +156,7 @@ private:
+   void releaseMemory() override;
+ 
+   void activate(unsigned);
++  void setThreshold(const BlockFrequency &Entry);
+ };
+ 
+ } // end namespace llvm
+EOF
+patch -p1
+popd
+
+
 # Echo all commands.
 set -x
 
@@ -438,8 +619,6 @@
 # the real directory for the Chromium tools.
 # Note that the shim directory name intentionally has no _ or _. The implicit
 # tool detection logic munges them in a weird way.
-CHROME_TOOLS_SHIM_DIR=${ABS_LLVM_DIR}/tools/chrometools
-rm -rfv ${CHROME_TOOLS_SHIM_DIR}
 mkdir -v ${CHROME_TOOLS_SHIM_DIR}
 cat > ${CHROME_TOOLS_SHIM_DIR}/CMakeLists.txt << EOF
 # Since tools/clang isn't actually a subdirectory, use the two argument version
@@ -546,7 +725,7 @@
       -DCMAKE_CXX_FLAGS="--target=arm-linux-androideabi --sysroot=${PWD}/../android-toolchain/sysroot -B${PWD}/../android-toolchain" \
       -DANDROID=1 \
       "${ABS_COMPILER_RT_DIR}"
-  ninja clang_rt.asan-arm-android
+  ninja libclang_rt.asan-arm-android.so
 
   # And copy it into the main build tree.
   cp "$(find -name libclang_rt.asan-arm-android.so)" "${ABS_LLVM_CLANG_LIB_DIR}/lib/linux/"
diff --git a/tools/valgrind/memcheck/suppressions.txt b/tools/valgrind/memcheck/suppressions.txt
index b68e69e..20105b9 100644
--- a/tools/valgrind/memcheck/suppressions.txt
+++ b/tools/valgrind/memcheck/suppressions.txt
@@ -2412,19 +2412,6 @@
    fun:_ZN18chrome_browser_net27HttpServerPropertiesManager24UpdatePrefsFromCacheOnIOEv
 }
 {
-   bug_290407
-   Memcheck:Leak
-   fun:calloc
-   fun:_swrast_new_soft_renderbuffer
-   fun:_mesa_BindRenderbufferEXT
-   fun:shared_dispatch_stub_939
-   fun:_ZN3gfx9GLApiBase23glBindRenderbufferEXTFnEjj
-   fun:_ZN3gpu5gles216GLES2DecoderImpl18DoBindRenderbufferEjj
-   fun:_ZN3gpu5gles216GLES2DecoderImpl22HandleBindRenderbufferEjRKNS0_4cmds16BindRenderbufferE
-   fun:_ZN3gpu5gles216GLES2DecoderImpl9DoCommandEjjPKv
-   fun:_ZN3gpu13CommandParser14ProcessCommandEv
-}
-{
    bug_293024_b
    Memcheck:Leak
    fun:malloc
@@ -2541,17 +2528,6 @@
    fun:_ZN3net14URLFetcherCore15StartOnIOThreadEv
 }
 {
-   bug_332328
-   Memcheck:Leak
-   fun:malloc
-   fun:_ZN3WTF10fastMallocEm
-   fun:_ZN5blink14XMLHttpRequestnwEm
-   fun:_ZN5blink14XMLHttpRequest6createEPNS_16ExecutionContextEN3WTF10PassRefPtrINS_14SecurityOriginEEE
-   fun:_ZN5blink16V8XMLHttpRequest17constructorCustomERKN2v820FunctionCallbackInfoINS1_5ValueEEE
-   fun:_ZN5blink16V8XMLHttpRequest19constructorCallbackERKN2v820FunctionCallbackInfoINS1_5ValueEEE
-   fun:_ZN2v88internal25FunctionCallbackArguments4CallEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEE
-}
-{
    bug_332330
    Memcheck:Leak
    fun:malloc
@@ -2798,15 +2774,6 @@
    fun:_ZN7content27ServiceWorkerContextWrapper12InitInternalERKN4base8FilePathEPNS1_19SequencedTaskRunnerEPN5quota17QuotaManagerProxyE
 }
 {
-   bug_370206
-   Memcheck:Leak
-   fun:malloc
-   fun:_ZN3WTF16DefaultAllocator15backingAllocateEm
-   fun:_ZN3WTF16DefaultAllocator13backingMallocIPN7blink14InlineIteratorEvEET_m
-   ...
-   fun:_ZN3WTF17HashMapTranslatorINS_18HashMapValueTraitsINS_10HashTraitsIPN7blink7BidiRun*
-}
-{
   bug_371844
   Memcheck:Uninitialized
   fun:bcmp
@@ -3327,23 +3294,9 @@
    ...
    fun:_ZNK5blink13RootInlineBox13maxLogicalTopEv
    fun:_ZN5blinkL22computeUnderlineOffsetENS_21TextUnderlinePositionERKNS_11FontMetricsEPKNS_13InlineTextBoxEf
-   fun:_ZN5blink13InlineTextBox15paintDecorationEPNS_15GraphicsContextERKNS_10FloatPointENS_14TextDecorationEPKNS_10ShadowListE
+   fun:_ZN5blink20InlineTextBoxPainter15paintDecorationEPNS_15GraphicsContextERKNS_10FloatPointENS_14TextDecorationE
+   fun:_ZN5blink20InlineTextBoxPainter5paintERNS_9PaintInfoERKNS_11LayoutPointE
    fun:_ZN5blink13InlineTextBox5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
-   fun:_ZN5blink13InlineFlowBox5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
-   fun:_ZN5blink13RootInlineBox5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
-   fun:_ZNK5blink17RenderLineBoxList5paintEPNS_20RenderBoxModelObjectERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock13paintContentsERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock11paintObjectERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock5paintERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock10paintChildEPNS_9RenderBoxERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock13paintChildrenERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock13paintContentsERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock11paintObjectERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock5paintERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock10paintChildEPNS_9RenderBoxERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock13paintChildrenERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock13paintContentsERNS_9PaintInfoERKNS_11LayoutPointE
-   fun:_ZN5blink11RenderBlock11paintObjectERNS_9PaintInfoERKNS_11LayoutPointE
 }
 {
    bug_411235
@@ -3388,6 +3341,7 @@
    bug_417048b
    Memcheck:Uninitialized
    fun:_ZN5blink13InlineFlowBox45clearDescendantsHaveSameLineHeightAndBaselineEv
+   ...
    fun:_ZN5blinkL25setLogicalWidthForTextRunEPNS_13RootInlineBoxEPNS_7BidiRunEPNS_10RenderTextEfRKNS*
    fun:_ZN5blink15RenderBlockFlow41computeInlineDirectionPositionsForSegmentEPNS_13RootInlineBoxERKNS*
    fun:_ZN5blink15RenderBlockFlow38computeInlineDirectionPositionsForLineEPNS_13RootInlineBoxERKNS*
@@ -3453,9 +3407,6 @@
    fun:_ZN5blink20InlineFlowBoxPainter28paintBoxDecorationBackgroundERNS_9PaintInfoERKNS_11LayoutPointE
    fun:_ZN5blink20InlineFlowBoxPainter5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
    fun:_ZN5blink13InlineFlowBox5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
-   fun:_ZN5blink20InlineFlowBoxPainter5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
-   fun:_ZN5blink13InlineFlowBox5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
-   fun:_ZN5blink13RootInlineBox5paintERNS_9PaintInfoERKNS_11LayoutPointENS_10LayoutUnitES6_
 }
 {
    bug_422485
@@ -3468,3 +3419,23 @@
    ...
    fun:_ZNK6SkDraw10drawBitmapERK8SkBitmapRK8SkMatrixRK7SkPaint
 }
+{
+   bug_424056a
+   Memcheck:Leak
+   fun:malloc
+   fun:_ZN3WTF13CStringBuffer19createUninitializedEm
+   fun:_ZN3WTF7CString16newUninitializedEmRPc
+   fun:_ZN3WTF15TextCodecLatin112encodeCommonIhEENS_7CStringEPKT_mNS_19UnencodableHandlingE
+   fun:_ZN3WTF15TextCodecLatin16encodeEPKhmNS_19UnencodableHandlingE
+}
+{
+   bug_424056b
+   Memcheck:Leak
+   fun:malloc
+   fun:_ZN3WTF13CStringBuffer19createUninitializedEm
+   fun:_ZN3WTF7CString4initEPKcm
+   fun:_ZN3WTF7CStringC1EPKcm
+   fun:_ZN3WTF13TextCodecUTF812encodeCommonIhEENS_7CStringEPKT_m
+   fun:_ZN3WTF13TextCodecUTF86encodeEPKhmNS_19UnencodableHandlingE
+   fun:_ZNK3WTF12TextEncoding6encodeERKNS_6StringENS_19UnencodableHandlingE
+}
diff --git a/ui/accessibility/ax_enums.idl b/ui/accessibility/ax_enums.idl
index 6557702..27ad04a 100644
--- a/ui/accessibility/ax_enums.idl
+++ b/ui/accessibility/ax_enums.idl
@@ -136,6 +136,7 @@
     menu_list_option,
     menu_list_popup,
     menu,
+    meter,
     navigation,
     note,
     outline,
diff --git a/ui/accessibility/platform/ax_platform_node_mac.mm b/ui/accessibility/platform/ax_platform_node_mac.mm
index 7431c6b..2b450ea 100644
--- a/ui/accessibility/platform/ax_platform_node_mac.mm
+++ b/ui/accessibility/platform/ax_platform_node_mac.mm
@@ -87,6 +87,7 @@
       {ui::AX_ROLE_MENU_ITEM_RADIO, NSAccessibilityMenuItemRole},
       {ui::AX_ROLE_MENU_LIST_OPTION, NSAccessibilityMenuItemRole},
       {ui::AX_ROLE_MENU_LIST_POPUP, NSAccessibilityUnknownRole},
+      {ui::AX_ROLE_METER, NSAccessibilityProgressIndicatorRole},
       {ui::AX_ROLE_NAVIGATION, NSAccessibilityGroupRole},
       {ui::AX_ROLE_NONE, NSAccessibilityGroupRole},
       {ui::AX_ROLE_NOTE, NSAccessibilityGroupRole},
diff --git a/ui/android/java/src/org/chromium/ui/ColorSuggestionListAdapter.java b/ui/android/java/src/org/chromium/ui/ColorSuggestionListAdapter.java
index b237acb..bdf255c 100644
--- a/ui/android/java/src/org/chromium/ui/ColorSuggestionListAdapter.java
+++ b/ui/android/java/src/org/chromium/ui/ColorSuggestionListAdapter.java
@@ -105,7 +105,7 @@
             layout.setOrientation(LinearLayout.HORIZONTAL);
             layout.setBackgroundColor(Color.WHITE);
             int buttonHeight =
-                mContext.getResources().getDimensionPixelOffset(R.dimen.color_button_height);
+                    mContext.getResources().getDimensionPixelOffset(R.dimen.color_button_height);
             for (int i = 0; i < COLORS_PER_ROW; ++i) {
                 View button = new View(mContext);
                 LinearLayout.LayoutParams layoutParams =
diff --git a/ui/android/java/src/org/chromium/ui/DropdownPopupWindow.java b/ui/android/java/src/org/chromium/ui/DropdownPopupWindow.java
index 8b54452..a1b8ee6 100644
--- a/ui/android/java/src/org/chromium/ui/DropdownPopupWindow.java
+++ b/ui/android/java/src/org/chromium/ui/DropdownPopupWindow.java
@@ -160,8 +160,7 @@
     private int measureContentWidth() {
         int maxWidth = 0;
         View itemView = null;
-        if (mAdapter == null)
-          return 0;
+        if (mAdapter == null) return 0;
         final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
         final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
         for (int i = 0; i < mAdapter.getCount(); i++) {
diff --git a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java
index 4f967b7..bc6efb7 100644
--- a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java
+++ b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java
@@ -202,9 +202,13 @@
         if (results == null) {
             // If we have a successful return but no data, then assume this is the camera returning
             // the photo that we requested.
-            nativeOnFileSelected(mNativeSelectFileDialog, mCameraOutputUri.toString(),
+            // If the uri is a file, we need to convert it to the absolute path or otherwise
+            // android cannot handle it correctly on some earlier versions.
+            // http://crbug.com/423338.
+            String path = ContentResolver.SCHEME_FILE.equals(mCameraOutputUri.getScheme()) ?
+                    mCameraOutputUri.getPath() : mCameraOutputUri.toString();
+            nativeOnFileSelected(mNativeSelectFileDialog, path,
                     mCameraOutputUri.getLastPathSegment());
-
             // Broadcast to the media scanner that there's a new photo on the device so it will
             // show up right away in the gallery (rather than waiting until the next time the media
             // scanner runs).
diff --git a/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java b/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java
index 71d3f7e..8f1c58f 100644
--- a/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java
+++ b/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java
@@ -239,7 +239,7 @@
 
     @CalledByNative
     private void requestVSyncUpdate() {
-       mVSyncMonitor.requestUpdate();
+        mVSyncMonitor.requestUpdate();
     }
 
     /**
diff --git a/ui/android/java/src/org/chromium/ui/picker/InputDialogContainer.java b/ui/android/java/src/org/chromium/ui/picker/InputDialogContainer.java
index c59f465..48304d5 100644
--- a/ui/android/java/src/org/chromium/ui/picker/InputDialogContainer.java
+++ b/ui/android/java/src/org/chromium/ui/picker/InputDialogContainer.java
@@ -76,7 +76,7 @@
     }
 
     public void showPickerDialog(final int dialogType, double dialogValue,
-        double min, double max, double step) {
+            double min, double max, double step) {
         Calendar cal;
         // |dialogValue|, |min|, |max| mean different things depending on the |dialogType|.
         // For input type=month is the number of months since 1970.
@@ -139,7 +139,7 @@
             DateTimeSuggestion[] suggestions) {
         ListView suggestionListView = new ListView(mContext);
         final DateTimeSuggestionListAdapter adapter =
-            new DateTimeSuggestionListAdapter(mContext, Arrays.asList(suggestions));
+                new DateTimeSuggestionListAdapter(mContext, Arrays.asList(suggestions));
         suggestionListView.setAdapter(adapter);
         suggestionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
@@ -361,7 +361,7 @@
             mInputActionDelegate.replaceDateTime((year - 1970) * 12 + month);
         } else if (dialogType == sTextInputTypeWeek) {
             mInputActionDelegate.replaceDateTime(
-                  WeekPicker.createDateFromWeek(year, week).getTimeInMillis());
+                    WeekPicker.createDateFromWeek(year, week).getTimeInMillis());
         } else if (dialogType == sTextInputTypeTime) {
             mInputActionDelegate.replaceDateTime(TimeUnit.HOURS.toMillis(hourOfDay) +
                                                  TimeUnit.MINUTES.toMillis(minute) +
diff --git a/ui/android/java/src/org/chromium/ui/picker/MultiFieldTimePickerDialog.java b/ui/android/java/src/org/chromium/ui/picker/MultiFieldTimePickerDialog.java
index 860829f..d03c165 100644
--- a/ui/android/java/src/org/chromium/ui/picker/MultiFieldTimePickerDialog.java
+++ b/ui/android/java/src/org/chromium/ui/picker/MultiFieldTimePickerDialog.java
@@ -146,7 +146,7 @@
             if (minMinute == maxMinute) {
                 // Set this otherwise the box is empty until you stroke it.
                 mMinuteSpinner.setDisplayedValues(
-                    new String[] { twoDigitPaddingFormatter.format(minMinute) });
+                        new String[] { twoDigitPaddingFormatter.format(minMinute) });
                 mMinuteSpinner.setEnabled(false);
                 minute = minMinute;
             }
@@ -179,7 +179,7 @@
             if (minSecond == maxSecond) {
                 // Set this otherwise the box is empty until you stroke it.
                 mSecSpinner.setDisplayedValues(
-                    new String[] { twoDigitPaddingFormatter.format(minSecond) });
+                        new String[] { twoDigitPaddingFormatter.format(minSecond) });
                 mSecSpinner.setEnabled(false);
                 second = minSecond;
             }
@@ -200,8 +200,7 @@
         // Round to the nearest step.
         milli = ((milli + step / 2) / step) * step;
         if (step == 1 || step == 10 || step == 100) {
-            if (minHour == maxHour && minMinute == maxMinute &&
-                minSecond == maxSecond) {
+            if (minHour == maxHour && minMinute == maxMinute && minSecond == maxSecond) {
                 mMilliSpinner.setMinValue(min / step);
                 mMilliSpinner.setMaxValue(max / step);
 
@@ -232,8 +231,7 @@
             mMilliSpinner.setMinValue(0);
             mMilliSpinner.setMaxValue(strValue.size() - 1);
             mMilliSpinner.setValue((milli - min) / step);
-            mMilliSpinner.setDisplayedValues(
-                strValue.toArray(new String[strValue.size()]));
+            mMilliSpinner.setDisplayedValues(strValue.toArray(new String[strValue.size()]));
             mBaseMilli = min;
         } else {
             mBaseMilli = 0;
diff --git a/ui/app_list/app_list_model.cc b/ui/app_list/app_list_model.cc
index b3512c8..0425f4c 100644
--- a/ui/app_list/app_list_model.cc
+++ b/ui/app_list/app_list_model.cc
@@ -339,8 +339,7 @@
       new AppListFolderItem(folder_id, AppListFolderItem::FOLDER_TYPE_NORMAL));
   new_folder->set_position(
       top_level_item_list_->CreatePositionBefore(syncer::StringOrdinal()));
-  AppListItem* new_folder_item =
-      AddItemToItemListAndNotify(new_folder.PassAs<AppListItem>());
+  AppListItem* new_folder_item = AddItemToItemListAndNotify(new_folder.Pass());
   return static_cast<AppListFolderItem*>(new_folder_item);
 }
 
diff --git a/ui/app_list/search/mixer_unittest.cc b/ui/app_list/search/mixer_unittest.cc
index aa3799d..542c98d 100644
--- a/ui/app_list/search/mixer_unittest.cc
+++ b/ui/app_list/search/mixer_unittest.cc
@@ -159,7 +159,7 @@
         {0, 0, 0, ""},
     };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     app_provider()->set_count(kTestCases[i].app_results);
     omnibox_provider()->set_count(kTestCases[i].omnibox_results);
     webstore_provider()->set_count(kTestCases[i].webstore_results);
diff --git a/ui/app_list/search/tokenized_string_match_unittest.cc b/ui/app_list/search/tokenized_string_match_unittest.cc
index d467b9d..e9e959e 100644
--- a/ui/app_list/search/tokenized_string_match_unittest.cc
+++ b/ui/app_list/search/tokenized_string_match_unittest.cc
@@ -44,7 +44,7 @@
   };
 
   TokenizedStringMatch match;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
     EXPECT_FALSE(match.Calculate(base::UTF8ToUTF16(kTestCases[i].query), text))
         << "Test case " << i
@@ -73,7 +73,7 @@
   };
 
   TokenizedStringMatch match;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
     EXPECT_TRUE(match.Calculate(base::UTF8ToUTF16(kTestCases[i].query), text));
     EXPECT_EQ(kTestCases[i].expect, MatchHit(text, match));
@@ -105,7 +105,7 @@
 
   TokenizedStringMatch match_low;
   TokenizedStringMatch match_high;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
     EXPECT_TRUE(
         match_low.Calculate(base::UTF8ToUTF16(kTestCases[i].query_low), text));
diff --git a/ui/app_list/test/app_list_test_model.cc b/ui/app_list/test/app_list_test_model.cc
index 9ec5258..8ab31d4 100644
--- a/ui/app_list/test/app_list_test_model.cc
+++ b/ui/app_list/test/app_list_test_model.cc
@@ -146,7 +146,7 @@
 AppListTestModel::AppListTestItem* AppListTestModel::CreateAndAddItem(
     const std::string& id) {
   scoped_ptr<AppListTestItem> test_item(CreateItem(id));
-  AppListItem* item = AppListModel::AddItem(test_item.PassAs<AppListItem>());
+  AppListItem* item = AppListModel::AddItem(test_item.Pass());
   return static_cast<AppListTestItem*>(item);
 }
 void AppListTestModel::HighlightItemAt(int index) {
diff --git a/ui/aura/BUILD.gn b/ui/aura/BUILD.gn
index 4f9a4a8..8b22fbb 100644
--- a/ui/aura/BUILD.gn
+++ b/ui/aura/BUILD.gn
@@ -142,8 +142,6 @@
   }
 }
 
-if (false) {
-
 source_set("test_support") {
   testonly = true
   sources = [
@@ -305,5 +303,3 @@
     ]
   }
 }
-
-}  # if (false)
diff --git a/ui/aura/window_unittest.cc b/ui/aura/window_unittest.cc
index 937212e..486bc6b 100644
--- a/ui/aura/window_unittest.cc
+++ b/ui/aura/window_unittest.cc
@@ -3365,7 +3365,7 @@
       "21 11 12",
     },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(data); ++i) {
+  for (size_t i = 0; i < arraysize(data); ++i) {
     test::TestWindowDelegate delegate;
     Window root(NULL);
     root.Init(WINDOW_LAYER_NOT_DRAWN);
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn
index 3233de7..3a3cd76 100644
--- a/ui/base/BUILD.gn
+++ b/ui/base/BUILD.gn
@@ -9,7 +9,7 @@
   import("//build/config/android/rules.gni")
 }
 
-build_ime = false
+build_ime = !is_ios
 
 component("base") {
   output_name = "ui_base"
@@ -699,8 +699,6 @@
   }
 }
 
-if (false) {
-
 # TODO(GYP): Make this work on Android and reenable it.
 if (!is_android) {
 # TODO(tfarina): Rename this target to ui_base_unittests.
@@ -902,5 +900,4 @@
   }
 }
 }
-}
 # TODO(GYP) Mac (ui_unittest_bundle) and Android (ui_unittests_apk).
diff --git a/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc b/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc
index b453381..0811e2b 100644
--- a/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc
+++ b/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc
@@ -22,7 +22,7 @@
     { "&foo &&bar", "_foo &bar" },
     { "&foo &bar", "_foo _bar" },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input);
     EXPECT_EQ(cases[i].output, result);
   }
@@ -41,7 +41,7 @@
     { "&foo &&bar", "foo &bar" },
     { "&foo &bar", "foo bar" },
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::string result = RemoveWindowsStyleAccelerators(cases[i].input);
     EXPECT_EQ(cases[i].output, result);
   }
@@ -66,7 +66,7 @@
     { "&_foo_bar_&", "&&_foo_bar_&&" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::string result = EscapeWindowsStyleAccelerators(cases[i].input);
     EXPECT_EQ(cases[i].output, result);
   }
diff --git a/ui/base/clipboard/clipboard_android.cc b/ui/base/clipboard/clipboard_android.cc
index 97b9d16..a6631af 100644
--- a/ui/base/clipboard/clipboard_android.cc
+++ b/ui/base/clipboard/clipboard_android.cc
@@ -178,6 +178,7 @@
 
 }  // namespace
 
+// Clipboard::FormatType implementation.
 Clipboard::FormatType::FormatType() {
 }
 
@@ -202,6 +203,62 @@
   return data_ == other.data_;
 }
 
+// Various predefined FormatTypes.
+// static
+Clipboard::FormatType Clipboard::GetFormatType(
+    const std::string& format_string) {
+  return FormatType::Deserialize(format_string);
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPlainTextFormat));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPlainTextFormat));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebKitSmartPasteFormat));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kHTMLFormat));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kRTFFormat));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kBitmapFormat));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData));
+  return type;
+}
+
+// Clipboard implementation.
 Clipboard::Clipboard() {
   DCHECK(CalledOnValidThread());
 }
@@ -210,17 +267,6 @@
   DCHECK(CalledOnValidThread());
 }
 
-// Main entry point used to write several values in the clipboard.
-void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
-  DCHECK(CalledOnValidThread());
-  DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
-  g_map.Get().Clear();
-  for (ObjectMap::const_iterator iter = objects.begin();
-       iter != objects.end(); ++iter) {
-    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
-  }
-}
-
 uint64 Clipboard::GetSequenceNumber(ClipboardType /* type */) {
   DCHECK(CalledOnValidThread());
   // TODO: implement this. For now this interface will advertise
@@ -333,58 +379,15 @@
   *result = g_map.Get().Get(format.data());
 }
 
-// static
-Clipboard::FormatType Clipboard::GetFormatType(
-    const std::string& format_string) {
-  return FormatType::Deserialize(format_string);
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPlainTextFormat));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPlainTextFormat));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebKitSmartPasteFormat));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kHTMLFormat));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kRTFFormat));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kBitmapFormat));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData));
-  return type;
+// Main entry point used to write several values in the clipboard.
+void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
+  DCHECK(CalledOnValidThread());
+  DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
+  g_map.Get().Clear();
+  for (ObjectMap::const_iterator iter = objects.begin();
+       iter != objects.end(); ++iter) {
+    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
+  }
 }
 
 void Clipboard::WriteText(const char* text_data, size_t text_len) {
diff --git a/ui/base/clipboard/clipboard_aura.cc b/ui/base/clipboard/clipboard_aura.cc
index 30b639a..efd484b 100644
--- a/ui/base/clipboard/clipboard_aura.cc
+++ b/ui/base/clipboard/clipboard_aura.cc
@@ -406,6 +406,7 @@
 
 }  // namespace
 
+// Clipboard FormatType implementation.
 Clipboard::FormatType::FormatType() {
 }
 
@@ -434,6 +435,83 @@
   return data_ == other.data_;
 }
 
+// Various predefined FormatTypes.
+// static
+Clipboard::FormatType Clipboard::GetFormatType(
+    const std::string& format_string) {
+  return FormatType::Deserialize(format_string);
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeURIList));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
+  return GetUrlFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeText));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
+  return GetPlainTextFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeFilename));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
+  return Clipboard::GetFilenameFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeHTML));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeRTF));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeBitmap));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebkitSmartPaste));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData));
+  return type;
+}
+
+// Clipboard implementation.
 Clipboard::Clipboard() {
   DCHECK(CalledOnValidThread());
   // Make sure clipboard is created.
@@ -445,14 +523,9 @@
   DeleteClipboard();
 }
 
-void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
+uint64 Clipboard::GetSequenceNumber(ClipboardType type) {
   DCHECK(CalledOnValidThread());
-  DCHECK(IsSupportedClipboardType(type));
-  for (ObjectMap::const_iterator iter = objects.begin();
-       iter != objects.end(); ++iter) {
-    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
-  }
-  ClipboardDataBuilder::CommitToClipboard();
+  return GetClipboard()->sequence_number();
 }
 
 bool Clipboard::IsFormatAvailable(const FormatType& format,
@@ -559,9 +632,14 @@
   GetClipboard()->ReadData(format.ToString(), result);
 }
 
-uint64 Clipboard::GetSequenceNumber(ClipboardType type) {
+void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
   DCHECK(CalledOnValidThread());
-  return GetClipboard()->sequence_number();
+  DCHECK(IsSupportedClipboardType(type));
+  for (ObjectMap::const_iterator iter = objects.begin();
+       iter != objects.end(); ++iter) {
+    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
+  }
+  ClipboardDataBuilder::CommitToClipboard();
 }
 
 void Clipboard::WriteText(const char* text_data, size_t text_len) {
@@ -600,79 +678,4 @@
   ClipboardDataBuilder::WriteData(format.ToString(), data_data, data_len);
 }
 
-// static
-Clipboard::FormatType Clipboard::GetFormatType(
-    const std::string& format_string) {
-  return FormatType::Deserialize(format_string);
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeURIList));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
-  return GetUrlFormatType();
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeText));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
-  return GetPlainTextFormatType();
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeFilename));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
-  return Clipboard::GetFilenameFormatType();
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeHTML));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeRTF));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeBitmap));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebkitSmartPaste));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData));
-  return type;
-}
-
 }  // namespace ui
diff --git a/ui/base/clipboard/clipboard_aurax11.cc b/ui/base/clipboard/clipboard_aurax11.cc
index 82542e0..e79f28b 100644
--- a/ui/base/clipboard/clipboard_aurax11.cc
+++ b/ui/base/clipboard/clipboard_aurax11.cc
@@ -569,6 +569,83 @@
 }
 
 ///////////////////////////////////////////////////////////////////////////////
+// Various predefined FormatTypes.
+// static
+Clipboard::FormatType Clipboard::GetFormatType(
+    const std::string& format_string) {
+  return FormatType::Deserialize(format_string);
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeURIList));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
+  return GetUrlFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeText));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
+  return GetPlainTextFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeFilename));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
+  return Clipboard::GetFilenameFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeHTML));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeRTF));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePNG));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebkitSmartPaste));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData));
+  return type;
+}
+
+///////////////////////////////////////////////////////////////////////////////
 // Clipboard
 
 Clipboard::Clipboard()
@@ -582,30 +659,12 @@
   aurax11_details_->StoreCopyPasteDataAndWait();
 }
 
-void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
+uint64 Clipboard::GetSequenceNumber(ClipboardType type) {
   DCHECK(CalledOnValidThread());
-  DCHECK(IsSupportedClipboardType(type));
-
-  aurax11_details_->CreateNewClipboardData();
-  for (ObjectMap::const_iterator iter = objects.begin();
-       iter != objects.end(); ++iter) {
-    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
-  }
-  aurax11_details_->TakeOwnershipOfSelection(type);
-
-  if (type == CLIPBOARD_TYPE_COPY_PASTE) {
-    ObjectMap::const_iterator text_iter = objects.find(CBF_TEXT);
-    if (text_iter != objects.end()) {
-      aurax11_details_->CreateNewClipboardData();
-      const ObjectMapParams& params_vector = text_iter->second;
-      if (params_vector.size()) {
-        const ObjectMapParam& char_vector = params_vector[0];
-        if (char_vector.size())
-          WriteText(&char_vector.front(), char_vector.size());
-      }
-      aurax11_details_->TakeOwnershipOfSelection(CLIPBOARD_TYPE_SELECTION);
-    }
-  }
+  if (type == CLIPBOARD_TYPE_COPY_PASTE)
+    return SelectionChangeObserver::GetInstance()->clipboard_sequence_number();
+  else
+    return SelectionChangeObserver::GetInstance()->primary_sequence_number();
 }
 
 bool Clipboard::IsFormatAvailable(const FormatType& format,
@@ -751,12 +810,30 @@
     data.AssignTo(result);
 }
 
-uint64 Clipboard::GetSequenceNumber(ClipboardType type) {
+void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
   DCHECK(CalledOnValidThread());
-  if (type == CLIPBOARD_TYPE_COPY_PASTE)
-    return SelectionChangeObserver::GetInstance()->clipboard_sequence_number();
-  else
-    return SelectionChangeObserver::GetInstance()->primary_sequence_number();
+  DCHECK(IsSupportedClipboardType(type));
+
+  aurax11_details_->CreateNewClipboardData();
+  for (ObjectMap::const_iterator iter = objects.begin();
+       iter != objects.end(); ++iter) {
+    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
+  }
+  aurax11_details_->TakeOwnershipOfSelection(type);
+
+  if (type == CLIPBOARD_TYPE_COPY_PASTE) {
+    ObjectMap::const_iterator text_iter = objects.find(CBF_TEXT);
+    if (text_iter != objects.end()) {
+      aurax11_details_->CreateNewClipboardData();
+      const ObjectMapParams& params_vector = text_iter->second;
+      if (params_vector.size()) {
+        const ObjectMapParam& char_vector = params_vector[0];
+        if (char_vector.size())
+          WriteText(&char_vector.front(), char_vector.size());
+      }
+      aurax11_details_->TakeOwnershipOfSelection(CLIPBOARD_TYPE_SELECTION);
+    }
+  }
 }
 
 void Clipboard::WriteText(const char* text_data, size_t text_len) {
@@ -842,79 +919,4 @@
   aurax11_details_->InsertMapping(format.ToString(), mem);
 }
 
-// static
-Clipboard::FormatType Clipboard::GetFormatType(
-    const std::string& format_string) {
-  return FormatType::Deserialize(format_string);
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeURIList));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
-  return GetUrlFormatType();
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeText));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
-  return GetPlainTextFormatType();
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeFilename));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
-  return Clipboard::GetFilenameFormatType();
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeHTML));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeRTF));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePNG));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebkitSmartPaste));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData));
-  return type;
-}
-
 }  // namespace ui
diff --git a/ui/base/clipboard/clipboard_mac.mm b/ui/base/clipboard/clipboard_mac.mm
index 0b6d3a7..88a9ff1 100644
--- a/ui/base/clipboard/clipboard_mac.mm
+++ b/ui/base/clipboard/clipboard_mac.mm
@@ -50,6 +50,7 @@
 
 }  // namespace
 
+// Clipboard::FormatType implementation.
 Clipboard::FormatType::FormatType() : data_(nil) {
 }
 
@@ -88,6 +89,83 @@
   return FormatType(base::SysUTF8ToNSString(serialization));
 }
 
+// Various predefined FormatTypes.
+// static
+Clipboard::FormatType Clipboard::GetFormatType(
+    const std::string& format_string) {
+  return FormatType::Deserialize(format_string);
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSURLPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
+  return GetUrlFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSStringPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
+  return GetPlainTextFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSFilenamesPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
+  return GetFilenameFormatType();
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSHTMLPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSRTFPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSTIFFPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebSmartPastePboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebCustomDataPboardType));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPepperCustomDataPboardType));
+  return type;
+}
+
+// Clipboard implementation.
 Clipboard::Clipboard() {
   DCHECK(CalledOnValidThread());
 }
@@ -96,103 +174,6 @@
   DCHECK(CalledOnValidThread());
 }
 
-void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
-  DCHECK(CalledOnValidThread());
-  DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
-
-  NSPasteboard* pb = GetPasteboard();
-  [pb declareTypes:[NSArray array] owner:nil];
-
-  for (ObjectMap::const_iterator iter = objects.begin();
-       iter != objects.end(); ++iter) {
-    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
-  }
-}
-
-void Clipboard::WriteText(const char* text_data, size_t text_len) {
-  std::string text_str(text_data, text_len);
-  NSString *text = base::SysUTF8ToNSString(text_str);
-  NSPasteboard* pb = GetPasteboard();
-  [pb addTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
-  [pb setString:text forType:NSStringPboardType];
-}
-
-void Clipboard::WriteHTML(const char* markup_data,
-                          size_t markup_len,
-                          const char* url_data,
-                          size_t url_len) {
-  // We need to mark it as utf-8. (see crbug.com/11957)
-  std::string html_fragment_str("<meta charset='utf-8'>");
-  html_fragment_str.append(markup_data, markup_len);
-  NSString *html_fragment = base::SysUTF8ToNSString(html_fragment_str);
-
-  // TODO(avi): url_data?
-  NSPasteboard* pb = GetPasteboard();
-  [pb addTypes:[NSArray arrayWithObject:NSHTMLPboardType] owner:nil];
-  [pb setString:html_fragment forType:NSHTMLPboardType];
-}
-
-void Clipboard::WriteRTF(const char* rtf_data, size_t data_len) {
-  WriteData(GetRtfFormatType(), rtf_data, data_len);
-}
-
-void Clipboard::WriteBookmark(const char* title_data,
-                              size_t title_len,
-                              const char* url_data,
-                              size_t url_len) {
-  std::string title_str(title_data, title_len);
-  NSString *title =  base::SysUTF8ToNSString(title_str);
-  std::string url_str(url_data, url_len);
-  NSString *url =  base::SysUTF8ToNSString(url_str);
-
-  // TODO(playmobil): In the Windows version of this function, an HTML
-  // representation of the bookmark is also added to the clipboard, to support
-  // drag and drop of web shortcuts.  I don't think we need to do this on the
-  // Mac, but we should double check later on.
-  NSURL* nsurl = [NSURL URLWithString:url];
-
-  NSPasteboard* pb = GetPasteboard();
-  // passing UTIs into the pasteboard methods is valid >= 10.5
-  [pb addTypes:[NSArray arrayWithObjects:NSURLPboardType,
-                                         kUTTypeURLName,
-                                         nil]
-         owner:nil];
-  [nsurl writeToPasteboard:pb];
-  [pb setString:title forType:kUTTypeURLName];
-}
-
-void Clipboard::WriteBitmap(const SkBitmap& bitmap) {
-  NSImage* image = gfx::SkBitmapToNSImageWithColorSpace(
-      bitmap, base::mac::GetSystemColorSpace());
-  // An API to ask the NSImage to write itself to the clipboard comes in 10.6 :(
-  // For now, spit out the image as a TIFF.
-  NSPasteboard* pb = GetPasteboard();
-  [pb addTypes:[NSArray arrayWithObject:NSTIFFPboardType] owner:nil];
-  NSData *tiff_data = [image TIFFRepresentation];
-  LOG_IF(ERROR, tiff_data == NULL) << "Failed to allocate image for clipboard";
-  if (tiff_data) {
-    [pb setData:tiff_data forType:NSTIFFPboardType];
-  }
-}
-
-void Clipboard::WriteData(const FormatType& format,
-                          const char* data_data,
-                          size_t data_len) {
-  NSPasteboard* pb = GetPasteboard();
-  [pb addTypes:[NSArray arrayWithObject:format.ToNSString()] owner:nil];
-  [pb setData:[NSData dataWithBytes:data_data length:data_len]
-      forType:format.ToNSString()];
-}
-
-// Write an extra flavor that signifies WebKit was the last to modify the
-// pasteboard. This flavor has no data.
-void Clipboard::WriteWebSmartPaste() {
-  NSPasteboard* pb = GetPasteboard();
-  NSString* format = GetWebKitSmartPasteFormatType().ToNSString();
-  [pb addTypes:[NSArray arrayWithObject:format] owner:nil];
-  [pb setData:nil forType:format];
-}
-
 uint64 Clipboard::GetSequenceNumber(ClipboardType type) {
   DCHECK(CalledOnValidThread());
   DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
@@ -366,79 +347,101 @@
     result->assign(static_cast<const char*>([data bytes]), [data length]);
 }
 
-// static
-Clipboard::FormatType Clipboard::GetFormatType(
-    const std::string& format_string) {
-  return FormatType::Deserialize(format_string);
+void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
+  DCHECK(CalledOnValidThread());
+  DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
+
+  NSPasteboard* pb = GetPasteboard();
+  [pb declareTypes:[NSArray array] owner:nil];
+
+  for (ObjectMap::const_iterator iter = objects.begin();
+       iter != objects.end(); ++iter) {
+    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
+  }
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSURLPboardType));
-  return type;
+void Clipboard::WriteText(const char* text_data, size_t text_len) {
+  std::string text_str(text_data, text_len);
+  NSString *text = base::SysUTF8ToNSString(text_str);
+  NSPasteboard* pb = GetPasteboard();
+  [pb addTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
+  [pb setString:text forType:NSStringPboardType];
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
-  return GetUrlFormatType();
+void Clipboard::WriteHTML(const char* markup_data,
+                          size_t markup_len,
+                          const char* url_data,
+                          size_t url_len) {
+  // We need to mark it as utf-8. (see crbug.com/11957)
+  std::string html_fragment_str("<meta charset='utf-8'>");
+  html_fragment_str.append(markup_data, markup_len);
+  NSString *html_fragment = base::SysUTF8ToNSString(html_fragment_str);
+
+  // TODO(avi): url_data?
+  NSPasteboard* pb = GetPasteboard();
+  [pb addTypes:[NSArray arrayWithObject:NSHTMLPboardType] owner:nil];
+  [pb setString:html_fragment forType:NSHTMLPboardType];
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSStringPboardType));
-  return type;
+void Clipboard::WriteRTF(const char* rtf_data, size_t data_len) {
+  WriteData(GetRtfFormatType(), rtf_data, data_len);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
-  return GetPlainTextFormatType();
+void Clipboard::WriteBookmark(const char* title_data,
+                              size_t title_len,
+                              const char* url_data,
+                              size_t url_len) {
+  std::string title_str(title_data, title_len);
+  NSString *title =  base::SysUTF8ToNSString(title_str);
+  std::string url_str(url_data, url_len);
+  NSString *url =  base::SysUTF8ToNSString(url_str);
+
+  // TODO(playmobil): In the Windows version of this function, an HTML
+  // representation of the bookmark is also added to the clipboard, to support
+  // drag and drop of web shortcuts.  I don't think we need to do this on the
+  // Mac, but we should double check later on.
+  NSURL* nsurl = [NSURL URLWithString:url];
+
+  NSPasteboard* pb = GetPasteboard();
+  // passing UTIs into the pasteboard methods is valid >= 10.5
+  [pb addTypes:[NSArray arrayWithObjects:NSURLPboardType,
+                                         kUTTypeURLName,
+                                         nil]
+         owner:nil];
+  [nsurl writeToPasteboard:pb];
+  [pb setString:title forType:kUTTypeURLName];
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSFilenamesPboardType));
-  return type;
+void Clipboard::WriteBitmap(const SkBitmap& bitmap) {
+  NSImage* image = gfx::SkBitmapToNSImageWithColorSpace(
+      bitmap, base::mac::GetSystemColorSpace());
+  // An API to ask the NSImage to write itself to the clipboard comes in 10.6 :(
+  // For now, spit out the image as a TIFF.
+  NSPasteboard* pb = GetPasteboard();
+  [pb addTypes:[NSArray arrayWithObject:NSTIFFPboardType] owner:nil];
+  NSData *tiff_data = [image TIFFRepresentation];
+  LOG_IF(ERROR, tiff_data == NULL) << "Failed to allocate image for clipboard";
+  if (tiff_data) {
+    [pb setData:tiff_data forType:NSTIFFPboardType];
+  }
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
-  return GetFilenameFormatType();
+void Clipboard::WriteData(const FormatType& format,
+                          const char* data_data,
+                          size_t data_len) {
+  NSPasteboard* pb = GetPasteboard();
+  [pb addTypes:[NSArray arrayWithObject:format.ToNSString()] owner:nil];
+  [pb setData:[NSData dataWithBytes:data_data length:data_len]
+      forType:format.ToNSString()];
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSHTMLPboardType));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSRTFPboardType));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSTIFFPboardType));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebSmartPastePboardType));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebCustomDataPboardType));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPepperCustomDataPboardType));
-  return type;
+// Write an extra flavor that signifies WebKit was the last to modify the
+// pasteboard. This flavor has no data.
+void Clipboard::WriteWebSmartPaste() {
+  NSPasteboard* pb = GetPasteboard();
+  NSString* format = GetWebKitSmartPasteFormatType().ToNSString();
+  [pb addTypes:[NSArray arrayWithObject:format] owner:nil];
+  [pb setData:nil forType:format];
 }
 
 }  // namespace ui
diff --git a/ui/base/clipboard/clipboard_win.cc b/ui/base/clipboard/clipboard_win.cc
index 36d042d..18a42e2 100644
--- a/ui/base/clipboard/clipboard_win.cc
+++ b/ui/base/clipboard/clipboard_win.cc
@@ -161,6 +161,7 @@
 
 }  // namespace
 
+// Clipboard::FormatType implementation.
 Clipboard::FormatType::FormatType() : data_() {}
 
 Clipboard::FormatType::FormatType(UINT native_format) : data_() {
@@ -207,6 +208,147 @@
   return ToUINT() == other.ToUINT();
 }
 
+// Various predefined FormatTypes.
+// static
+Clipboard::FormatType Clipboard::GetFormatType(
+    const std::string& format_string) {
+  return FormatType(
+      ::RegisterClipboardFormat(base::ASCIIToWide(format_string).c_str()));
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLA)));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLW)));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetMozUrlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(L"text/x-moz-url")));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_TEXT));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_UNICODETEXT));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEA)));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEW)));
+  return type;
+}
+
+// MS HTML Format
+// static
+const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(L"HTML Format")));
+  return type;
+}
+
+// MS RTF Format
+// static
+const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(L"Rich Text Format")));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_BITMAP));
+  return type;
+}
+
+// Firefox text/html
+// static
+const Clipboard::FormatType& Clipboard::GetTextHtmlFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(L"text/html")));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetCFHDropFormatType() {
+  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_HDROP));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFileDescriptorFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR)));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetFileContentZeroFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILECONTENTS), 0));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetIDListFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType, type, (::RegisterClipboardFormat(CFSTR_SHELLIDLIST)));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType,
+      type,
+      (::RegisterClipboardFormat(L"WebKit Smart Paste Format")));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
+  // TODO(dcheng): This name is temporary. See http://crbug.com/106449.
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType,
+      type,
+      (::RegisterClipboardFormat(L"Chromium Web Custom MIME Data Format")));
+  return type;
+}
+
+// static
+const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
+  CR_DEFINE_STATIC_LOCAL(
+      FormatType,
+      type,
+      (::RegisterClipboardFormat(L"Chromium Pepper MIME Data Format")));
+  return type;
+}
+
+// Clipboard implementation.
 Clipboard::Clipboard() {
   if (base::MessageLoopForUI::IsCurrent())
     clipboard_owner_.reset(new base::win::MessageWindow());
@@ -215,169 +357,6 @@
 Clipboard::~Clipboard() {
 }
 
-void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
-  DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
-
-  ScopedClipboard clipboard;
-  if (!clipboard.Acquire(GetClipboardWindow()))
-    return;
-
-  ::EmptyClipboard();
-
-  for (ObjectMap::const_iterator iter = objects.begin();
-       iter != objects.end(); ++iter) {
-    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
-  }
-}
-
-void Clipboard::WriteText(const char* text_data, size_t text_len) {
-  base::string16 text;
-  base::UTF8ToUTF16(text_data, text_len, &text);
-  HGLOBAL glob = CreateGlobalData(text);
-
-  WriteToClipboard(CF_UNICODETEXT, glob);
-}
-
-void Clipboard::WriteHTML(const char* markup_data,
-                          size_t markup_len,
-                          const char* url_data,
-                          size_t url_len) {
-  std::string markup(markup_data, markup_len);
-  std::string url;
-
-  if (url_len > 0)
-    url.assign(url_data, url_len);
-
-  std::string html_fragment = ClipboardUtil::HtmlToCFHtml(markup, url);
-  HGLOBAL glob = CreateGlobalData(html_fragment);
-
-  WriteToClipboard(Clipboard::GetHtmlFormatType().ToUINT(), glob);
-}
-
-void Clipboard::WriteRTF(const char* rtf_data, size_t data_len) {
-  WriteData(GetRtfFormatType(), rtf_data, data_len);
-}
-
-void Clipboard::WriteBookmark(const char* title_data,
-                              size_t title_len,
-                              const char* url_data,
-                              size_t url_len) {
-  std::string bookmark(title_data, title_len);
-  bookmark.append(1, L'\n');
-  bookmark.append(url_data, url_len);
-
-  base::string16 wide_bookmark = base::UTF8ToWide(bookmark);
-  HGLOBAL glob = CreateGlobalData(wide_bookmark);
-
-  WriteToClipboard(GetUrlWFormatType().ToUINT(), glob);
-}
-
-void Clipboard::WriteWebSmartPaste() {
-  DCHECK(clipboard_owner_->hwnd() != NULL);
-  ::SetClipboardData(GetWebKitSmartPasteFormatType().ToUINT(), NULL);
-}
-
-void Clipboard::WriteBitmap(const SkBitmap& bitmap) {
-  HDC dc = ::GetDC(NULL);
-
-  // This doesn't actually cost us a memcpy when the bitmap comes from the
-  // renderer as we load it into the bitmap using setPixels which just sets a
-  // pointer.  Someone has to memcpy it into GDI, it might as well be us here.
-
-  // TODO(darin): share data in gfx/bitmap_header.cc somehow
-  BITMAPINFO bm_info = {0};
-  bm_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-  bm_info.bmiHeader.biWidth = bitmap.width();
-  bm_info.bmiHeader.biHeight = -bitmap.height();  // sets vertical orientation
-  bm_info.bmiHeader.biPlanes = 1;
-  bm_info.bmiHeader.biBitCount = 32;
-  bm_info.bmiHeader.biCompression = BI_RGB;
-
-  // ::CreateDIBSection allocates memory for us to copy our bitmap into.
-  // Unfortunately, we can't write the created bitmap to the clipboard,
-  // (see http://msdn2.microsoft.com/en-us/library/ms532292.aspx)
-  void *bits;
-  HBITMAP source_hbitmap =
-      ::CreateDIBSection(dc, &bm_info, DIB_RGB_COLORS, &bits, NULL, 0);
-
-  if (bits && source_hbitmap) {
-    {
-      SkAutoLockPixels bitmap_lock(bitmap);
-      // Copy the bitmap out of shared memory and into GDI
-      memcpy(bits, bitmap.getPixels(), bitmap.getSize());
-    }
-
-    // Now we have an HBITMAP, we can write it to the clipboard
-    WriteBitmapFromHandle(source_hbitmap,
-                          gfx::Size(bitmap.width(), bitmap.height()));
-  }
-
-  ::DeleteObject(source_hbitmap);
-  ::ReleaseDC(NULL, dc);
-}
-
-void Clipboard::WriteBitmapFromHandle(HBITMAP source_hbitmap,
-                                      const gfx::Size& size) {
-  // We would like to just call ::SetClipboardData on the source_hbitmap,
-  // but that bitmap might not be of a sort we can write to the clipboard.
-  // For this reason, we create a new bitmap, copy the bits over, and then
-  // write that to the clipboard.
-
-  HDC dc = ::GetDC(NULL);
-  HDC compatible_dc = ::CreateCompatibleDC(NULL);
-  HDC source_dc = ::CreateCompatibleDC(NULL);
-
-  // This is the HBITMAP we will eventually write to the clipboard
-  HBITMAP hbitmap = ::CreateCompatibleBitmap(dc, size.width(), size.height());
-  if (!hbitmap) {
-    // Failed to create the bitmap
-    ::DeleteDC(compatible_dc);
-    ::DeleteDC(source_dc);
-    ::ReleaseDC(NULL, dc);
-    return;
-  }
-
-  HBITMAP old_hbitmap = (HBITMAP)SelectObject(compatible_dc, hbitmap);
-  HBITMAP old_source = (HBITMAP)SelectObject(source_dc, source_hbitmap);
-
-  // Now we need to blend it into an HBITMAP we can place on the clipboard
-  BLENDFUNCTION bf = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA};
-  ::GdiAlphaBlend(compatible_dc, 0, 0, size.width(), size.height(),
-                  source_dc, 0, 0, size.width(), size.height(), bf);
-
-  // Clean up all the handles we just opened
-  ::SelectObject(compatible_dc, old_hbitmap);
-  ::SelectObject(source_dc, old_source);
-  ::DeleteObject(old_hbitmap);
-  ::DeleteObject(old_source);
-  ::DeleteDC(compatible_dc);
-  ::DeleteDC(source_dc);
-  ::ReleaseDC(NULL, dc);
-
-  WriteToClipboard(CF_BITMAP, hbitmap);
-}
-
-void Clipboard::WriteData(const FormatType& format,
-                          const char* data_data,
-                          size_t data_len) {
-  HGLOBAL hdata = ::GlobalAlloc(GMEM_MOVEABLE, data_len);
-  if (!hdata)
-    return;
-
-  char* data = static_cast<char*>(::GlobalLock(hdata));
-  memcpy(data, data_data, data_len);
-  ::GlobalUnlock(data);
-  WriteToClipboard(format.ToUINT(), hdata);
-}
-
-void Clipboard::WriteToClipboard(unsigned int format, HANDLE handle) {
-  DCHECK(clipboard_owner_->hwnd() != NULL);
-  if (handle && !::SetClipboardData(format, handle)) {
-    DCHECK(ERROR_CLIPBOARD_NOT_OPEN != GetLastError());
-    FreeData(format, handle);
-  }
-}
-
 uint64 Clipboard::GetSequenceNumber(ClipboardType type) {
   DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
   return ::GetClipboardSequenceNumber();
@@ -680,143 +659,167 @@
   }
 }
 
-// static
-Clipboard::FormatType Clipboard::GetFormatType(
-    const std::string& format_string) {
-  return FormatType(
-      ::RegisterClipboardFormat(base::ASCIIToWide(format_string).c_str()));
+void Clipboard::WriteObjects(ClipboardType type, const ObjectMap& objects) {
+  DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE);
+
+  ScopedClipboard clipboard;
+  if (!clipboard.Acquire(GetClipboardWindow()))
+    return;
+
+  ::EmptyClipboard();
+
+  for (ObjectMap::const_iterator iter = objects.begin();
+       iter != objects.end(); ++iter) {
+    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
+  }
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetUrlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLA)));
-  return type;
+void Clipboard::WriteText(const char* text_data, size_t text_len) {
+  base::string16 text;
+  base::UTF8ToUTF16(text_data, text_len, &text);
+  HGLOBAL glob = CreateGlobalData(text);
+
+  WriteToClipboard(CF_UNICODETEXT, glob);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetUrlWFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLW)));
-  return type;
+void Clipboard::WriteHTML(const char* markup_data,
+                          size_t markup_len,
+                          const char* url_data,
+                          size_t url_len) {
+  std::string markup(markup_data, markup_len);
+  std::string url;
+
+  if (url_len > 0)
+    url.assign(url_data, url_len);
+
+  std::string html_fragment = ClipboardUtil::HtmlToCFHtml(markup, url);
+  HGLOBAL glob = CreateGlobalData(html_fragment);
+
+  WriteToClipboard(Clipboard::GetHtmlFormatType().ToUINT(), glob);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetMozUrlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(L"text/x-moz-url")));
-  return type;
+void Clipboard::WriteRTF(const char* rtf_data, size_t data_len) {
+  WriteData(GetRtfFormatType(), rtf_data, data_len);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_TEXT));
-  return type;
+void Clipboard::WriteBookmark(const char* title_data,
+                              size_t title_len,
+                              const char* url_data,
+                              size_t url_len) {
+  std::string bookmark(title_data, title_len);
+  bookmark.append(1, L'\n');
+  bookmark.append(url_data, url_len);
+
+  base::string16 wide_bookmark = base::UTF8ToWide(bookmark);
+  HGLOBAL glob = CreateGlobalData(wide_bookmark);
+
+  WriteToClipboard(GetUrlWFormatType().ToUINT(), glob);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_UNICODETEXT));
-  return type;
+void Clipboard::WriteWebSmartPaste() {
+  DCHECK(clipboard_owner_->hwnd() != NULL);
+  ::SetClipboardData(GetWebKitSmartPasteFormatType().ToUINT(), NULL);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEA)));
-  return type;
+void Clipboard::WriteBitmap(const SkBitmap& bitmap) {
+  HDC dc = ::GetDC(NULL);
+
+  // This doesn't actually cost us a memcpy when the bitmap comes from the
+  // renderer as we load it into the bitmap using setPixels which just sets a
+  // pointer.  Someone has to memcpy it into GDI, it might as well be us here.
+
+  // TODO(darin): share data in gfx/bitmap_header.cc somehow
+  BITMAPINFO bm_info = {0};
+  bm_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+  bm_info.bmiHeader.biWidth = bitmap.width();
+  bm_info.bmiHeader.biHeight = -bitmap.height();  // sets vertical orientation
+  bm_info.bmiHeader.biPlanes = 1;
+  bm_info.bmiHeader.biBitCount = 32;
+  bm_info.bmiHeader.biCompression = BI_RGB;
+
+  // ::CreateDIBSection allocates memory for us to copy our bitmap into.
+  // Unfortunately, we can't write the created bitmap to the clipboard,
+  // (see http://msdn2.microsoft.com/en-us/library/ms532292.aspx)
+  void *bits;
+  HBITMAP source_hbitmap =
+      ::CreateDIBSection(dc, &bm_info, DIB_RGB_COLORS, &bits, NULL, 0);
+
+  if (bits && source_hbitmap) {
+    {
+      SkAutoLockPixels bitmap_lock(bitmap);
+      // Copy the bitmap out of shared memory and into GDI
+      memcpy(bits, bitmap.getPixels(), bitmap.getSize());
+    }
+
+    // Now we have an HBITMAP, we can write it to the clipboard
+    WriteBitmapFromHandle(source_hbitmap,
+                          gfx::Size(bitmap.width(), bitmap.height()));
+  }
+
+  ::DeleteObject(source_hbitmap);
+  ::ReleaseDC(NULL, dc);
 }
 
-// static
-const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEW)));
-  return type;
+void Clipboard::WriteBitmapFromHandle(HBITMAP source_hbitmap,
+                                      const gfx::Size& size) {
+  // We would like to just call ::SetClipboardData on the source_hbitmap,
+  // but that bitmap might not be of a sort we can write to the clipboard.
+  // For this reason, we create a new bitmap, copy the bits over, and then
+  // write that to the clipboard.
+
+  HDC dc = ::GetDC(NULL);
+  HDC compatible_dc = ::CreateCompatibleDC(NULL);
+  HDC source_dc = ::CreateCompatibleDC(NULL);
+
+  // This is the HBITMAP we will eventually write to the clipboard
+  HBITMAP hbitmap = ::CreateCompatibleBitmap(dc, size.width(), size.height());
+  if (!hbitmap) {
+    // Failed to create the bitmap
+    ::DeleteDC(compatible_dc);
+    ::DeleteDC(source_dc);
+    ::ReleaseDC(NULL, dc);
+    return;
+  }
+
+  HBITMAP old_hbitmap = (HBITMAP)SelectObject(compatible_dc, hbitmap);
+  HBITMAP old_source = (HBITMAP)SelectObject(source_dc, source_hbitmap);
+
+  // Now we need to blend it into an HBITMAP we can place on the clipboard
+  BLENDFUNCTION bf = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA};
+  ::GdiAlphaBlend(compatible_dc, 0, 0, size.width(), size.height(),
+                  source_dc, 0, 0, size.width(), size.height(), bf);
+
+  // Clean up all the handles we just opened
+  ::SelectObject(compatible_dc, old_hbitmap);
+  ::SelectObject(source_dc, old_source);
+  ::DeleteObject(old_hbitmap);
+  ::DeleteObject(old_source);
+  ::DeleteDC(compatible_dc);
+  ::DeleteDC(source_dc);
+  ::ReleaseDC(NULL, dc);
+
+  WriteToClipboard(CF_BITMAP, hbitmap);
 }
 
-// MS HTML Format
-// static
-const Clipboard::FormatType& Clipboard::GetHtmlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(L"HTML Format")));
-  return type;
+void Clipboard::WriteData(const FormatType& format,
+                          const char* data_data,
+                          size_t data_len) {
+  HGLOBAL hdata = ::GlobalAlloc(GMEM_MOVEABLE, data_len);
+  if (!hdata)
+    return;
+
+  char* data = static_cast<char*>(::GlobalLock(hdata));
+  memcpy(data, data_data, data_len);
+  ::GlobalUnlock(data);
+  WriteToClipboard(format.ToUINT(), hdata);
 }
 
-// MS RTF Format
-// static
-const Clipboard::FormatType& Clipboard::GetRtfFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(L"Rich Text Format")));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetBitmapFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_BITMAP));
-  return type;
-}
-
-// Firefox text/html
-// static
-const Clipboard::FormatType& Clipboard::GetTextHtmlFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(L"text/html")));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetCFHDropFormatType() {
-  CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_HDROP));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetFileDescriptorFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR)));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetFileContentZeroFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_FILECONTENTS), 0));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetIDListFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType, type, (::RegisterClipboardFormat(CFSTR_SHELLIDLIST)));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType,
-      type,
-      (::RegisterClipboardFormat(L"WebKit Smart Paste Format")));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() {
-  // TODO(dcheng): This name is temporary. See http://crbug.com/106449.
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType,
-      type,
-      (::RegisterClipboardFormat(L"Chromium Web Custom MIME Data Format")));
-  return type;
-}
-
-// static
-const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() {
-  CR_DEFINE_STATIC_LOCAL(
-      FormatType,
-      type,
-      (::RegisterClipboardFormat(L"Chromium Pepper MIME Data Format")));
-  return type;
+void Clipboard::WriteToClipboard(unsigned int format, HANDLE handle) {
+  DCHECK(clipboard_owner_->hwnd() != NULL);
+  if (handle && !::SetClipboardData(format, handle)) {
+    DCHECK(ERROR_CLIPBOARD_NOT_OPEN != GetLastError());
+    FreeData(format, handle);
+  }
 }
 
 // static
diff --git a/ui/base/ime/chromeos/character_composer.cc b/ui/base/ime/chromeos/character_composer.cc
index b7a8808..fe99fdd 100644
--- a/ui/base/ime/chromeos/character_composer.cc
+++ b/ui/base/ime/chromeos/character_composer.cc
@@ -456,7 +456,7 @@
   compose_buffer_.push_back(keyval);
 
   if (compose_buffer_.size() == 2U) {
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kBlackListedDeadKeys); ++i) {
+    for (size_t i = 0; i < arraysize(kBlackListedDeadKeys); ++i) {
       if (compose_buffer_[0] == kBlackListedDeadKeys[i].first_key &&
           compose_buffer_[1] == kBlackListedDeadKeys[i].second_key ) {
         Reset();
diff --git a/ui/base/l10n/l10n_util.cc b/ui/base/l10n/l10n_util.cc
index 54f4145..9db2206 100644
--- a/ui/base/l10n/l10n_util.cc
+++ b/ui/base/l10n/l10n_util.cc
@@ -387,7 +387,7 @@
       {"en", "en-US"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(alias_map); ++i) {
+  for (size_t i = 0; i < arraysize(alias_map); ++i) {
     if (LowerCaseEqualsASCII(lang, alias_map[i].source)) {
       std::string tmp_locale(alias_map[i].dest);
       if (IsLocaleAvailable(tmp_locale)) {
diff --git a/ui/base/l10n/l10n_util_mac_unittest.mm b/ui/base/l10n/l10n_util_mac_unittest.mm
index cd3e203..adb0c57 100644
--- a/ui/base/l10n/l10n_util_mac_unittest.mm
+++ b/ui/base/l10n/l10n_util_mac_unittest.mm
@@ -36,7 +36,7 @@
     { @"foo(&b)...", @"foo\u2026" },
     { @"(&b)foo", @"foo" },
   };
-  for (size_t idx = 0; idx < ARRAYSIZE_UNSAFE(data); ++idx) {
+  for (size_t idx = 0; idx < arraysize(data); ++idx) {
     base::string16 input16(base::SysNSStringToUTF16(data[idx].input));
 
     NSString* result = l10n_util::FixUpWindowsStyleLabel(input16);
diff --git a/ui/base/text/bytes_formatting_unittest.cc b/ui/base/text/bytes_formatting_unittest.cc
index b2a03f9..308996c 100644
--- a/ui/base/text/bytes_formatting_unittest.cc
+++ b/ui/base/text/bytes_formatting_unittest.cc
@@ -25,7 +25,7 @@
 #endif
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i)
+  for (size_t i = 0; i < arraysize(cases); ++i)
     EXPECT_EQ(cases[i].expected, GetByteDisplayUnits(cases[i].bytes));
 }
 
@@ -68,7 +68,7 @@
 #endif
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     EXPECT_EQ(base::ASCIIToUTF16(cases[i].expected),
               FormatBytesWithUnits(cases[i].bytes, cases[i].units, false));
     EXPECT_EQ(base::ASCIIToUTF16(cases[i].expected_with_units),
diff --git a/ui/chromeos/BUILD.gn b/ui/chromeos/BUILD.gn
index 6a2d637..8e49aa6 100644
--- a/ui/chromeos/BUILD.gn
+++ b/ui/chromeos/BUILD.gn
@@ -27,6 +27,7 @@
     "//ui/chromeos/resources",
     "//ui/chromeos/strings",
     "//ui/events",
+    "//ui/events:gesture_detection",
     "//ui/views",
     "//ui/wm",
   ]
diff --git a/ui/compositor/BUILD.gn b/ui/compositor/BUILD.gn
index f85e773..38b79ad 100644
--- a/ui/compositor/BUILD.gn
+++ b/ui/compositor/BUILD.gn
@@ -77,8 +77,6 @@
   }
 }
 
-if (false) {
-
 source_set("test_support") {
   testonly = true
   sources = [
@@ -135,8 +133,6 @@
   }
 }
 
-}  # if (false)
-
 # TODO(GYP) enable this when all dependencies are complete and it links.
 #test("compositor_unittests") {
 #  sources = [
diff --git a/ui/compositor/compositor.cc b/ui/compositor/compositor.cc
index 41fa0eb..04763a6 100644
--- a/ui/compositor/compositor.cc
+++ b/ui/compositor/compositor.cc
@@ -127,6 +127,9 @@
 #if defined(OS_CHROMEOS)
   settings.per_tile_painting_enabled = true;
 #endif
+#if defined(OS_WIN)
+  settings.disable_hi_res_timer_tasks_on_battery = true;
+#endif
 
   // These flags should be mirrored by renderer versions in content/renderer/.
   settings.initial_debug_state.show_debug_borders =
diff --git a/ui/compositor/float_animation_curve_adapter.cc b/ui/compositor/float_animation_curve_adapter.cc
index 139c7cf..308fc1e 100644
--- a/ui/compositor/float_animation_curve_adapter.cc
+++ b/ui/compositor/float_animation_curve_adapter.cc
@@ -22,12 +22,8 @@
 }
 
 scoped_ptr<cc::AnimationCurve> FloatAnimationCurveAdapter::Clone() const {
-  scoped_ptr<FloatAnimationCurveAdapter> to_return(
-      new FloatAnimationCurveAdapter(tween_type_,
-                                     initial_value_,
-                                     target_value_,
-                                     duration_));
-  return to_return.PassAs<cc::AnimationCurve>();
+  return make_scoped_ptr(new FloatAnimationCurveAdapter(
+      tween_type_, initial_value_, target_value_, duration_));
 }
 
 float FloatAnimationCurveAdapter::GetValue(double t) const {
diff --git a/ui/compositor/transform_animation_curve_adapter.cc b/ui/compositor/transform_animation_curve_adapter.cc
index e0ae5ef..fa73140 100644
--- a/ui/compositor/transform_animation_curve_adapter.cc
+++ b/ui/compositor/transform_animation_curve_adapter.cc
@@ -27,12 +27,8 @@
 }
 
 scoped_ptr<cc::AnimationCurve> TransformAnimationCurveAdapter::Clone() const {
-  scoped_ptr<TransformAnimationCurveAdapter> to_return(
-      new TransformAnimationCurveAdapter(tween_type_,
-                                         initial_value_,
-                                         target_value_,
-                                         duration_));
-  return to_return.PassAs<cc::AnimationCurve>();
+  return make_scoped_ptr(new TransformAnimationCurveAdapter(
+      tween_type_, initial_value_, target_value_, duration_));
 }
 
 gfx::Transform TransformAnimationCurveAdapter::GetValue(
@@ -95,11 +91,8 @@
 }
 
 scoped_ptr<cc::AnimationCurve> InverseTransformCurveAdapter::Clone() const {
-  scoped_ptr<InverseTransformCurveAdapter> to_return(
-      new InverseTransformCurveAdapter(base_curve_,
-                                       initial_value_,
-                                       duration_));
-  return to_return.PassAs<cc::AnimationCurve>();
+  return make_scoped_ptr(
+      new InverseTransformCurveAdapter(base_curve_, initial_value_, duration_));
 }
 
 gfx::Transform InverseTransformCurveAdapter::GetValue(
diff --git a/ui/display/chromeos/display_configurator.cc b/ui/display/chromeos/display_configurator.cc
index a32fd0b..3194636 100644
--- a/ui/display/chromeos/display_configurator.cc
+++ b/ui/display/chromeos/display_configurator.cc
@@ -517,9 +517,10 @@
   // so that time-consuming ConfigureDisplays() won't be called multiple times.
   if (configure_timer_.IsRunning()) {
     // Note: when the timer is running it is possible that a different task
-    // (SetDisplayPower()) is scheduled. In these cases, prefer the already
-    // scheduled task to ConfigureDisplays() since ConfigureDisplays() performs
-    // only basic configuration while SetDisplayPower() will perform additional
+    // (RestoreRequestedPowerStateAfterResume()) is scheduled. In these cases,
+    // prefer the already scheduled task to ConfigureDisplays() since
+    // ConfigureDisplays() performs only basic configuration while
+    // RestoreRequestedPowerStateAfterResume() will perform additional
     // operations.
     configure_timer_.Reset();
   } else {
@@ -557,15 +558,11 @@
 }
 
 void DisplayConfigurator::ResumeDisplays() {
-  // Force probing to ensure that we pick up any changes that were made
-  // while the system was suspended.
   configure_timer_.Start(
       FROM_HERE,
       base::TimeDelta::FromMilliseconds(kResumeDelayMs),
-      base::Bind(base::IgnoreResult(&DisplayConfigurator::SetDisplayPower),
-                 base::Unretained(this),
-                 requested_power_state_,
-                 kSetDisplayPowerForceProbe));
+      base::Bind(&DisplayConfigurator::RestoreRequestedPowerStateAfterResume,
+                 base::Unretained(this)));
 }
 
 void DisplayConfigurator::UpdateCachedDisplays() {
@@ -725,6 +722,12 @@
   NotifyObservers(success, new_state);
 }
 
+void DisplayConfigurator::RestoreRequestedPowerStateAfterResume() {
+  // Force probing to ensure that we pick up any changes that were made while
+  // the system was suspended.
+  SetDisplayPower(requested_power_state_, kSetDisplayPowerForceProbe);
+}
+
 void DisplayConfigurator::NotifyObservers(
     bool success,
     MultipleDisplayState attempted_state) {
diff --git a/ui/display/chromeos/display_configurator.h b/ui/display/chromeos/display_configurator.h
index bbc7b53..f4b10d0 100644
--- a/ui/display/chromeos/display_configurator.h
+++ b/ui/display/chromeos/display_configurator.h
@@ -267,9 +267,13 @@
                       bool try_panel_fitting,
                       bool preserve_aspect);
 
-  // Configures displays.
+  // Configures displays. Invoked by |configure_timer_|.
   void ConfigureDisplays();
 
+  // Restores |requested_power_state_| after the system has resumed,
+  // additionally forcing a probe. Invoked by |configure_timer_|.
+  void RestoreRequestedPowerStateAfterResume();
+
   // Notifies observers about an attempted state change.
   void NotifyObservers(bool success, MultipleDisplayState attempted_state);
 
diff --git a/ui/display/chromeos/display_configurator_unittest.cc b/ui/display/chromeos/display_configurator_unittest.cc
index 7ecb145..aecaddd 100644
--- a/ui/display/chromeos/display_configurator_unittest.cc
+++ b/ui/display/chromeos/display_configurator_unittest.cc
@@ -1338,4 +1338,67 @@
       log_->GetActionsAndClear());
 }
 
+// Tests that the SetDisplayPowerState() task posted by HandleResume() doesn't
+// use a stale state if a new state is requested before it runs:
+// http://crosbug.com/p/32393
+TEST_F(DisplayConfiguratorTest, DontRestoreStalePowerStateAfterResume) {
+  // Start out with two displays in mirrored mode.
+  state_controller_.set_state(MULTIPLE_DISPLAY_STATE_DUAL_MIRROR);
+  configurator_.Init(false);
+  configurator_.ForceInitialConfigure(0);
+  log_->GetActionsAndClear();
+
+  // Turn off the internal display, simulating docked mode.
+  EXPECT_TRUE(configurator_.SetDisplayPower(
+      chromeos::DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON,
+      DisplayConfigurator::kSetDisplayPowerNoFlags));
+  EXPECT_EQ(
+      JoinActions(
+          kGrab,
+          GetFramebufferAction(big_mode_.size(), &outputs_[0], &outputs_[1])
+              .c_str(),
+          GetCrtcAction(outputs_[0], NULL, gfx::Point(0, 0)).c_str(),
+          GetCrtcAction(outputs_[1], &big_mode_, gfx::Point(0, 0)).c_str(),
+          kForceDPMS,
+          kUngrab,
+          NULL),
+      log_->GetActionsAndClear());
+
+  // Suspend and resume the system. Resuming should post a task to restore the
+  // previous power state, additionally forcing a probe.
+  configurator_.SuspendDisplays();
+  configurator_.ResumeDisplays();
+
+  // Before the task runs, exit docked mode.
+  EXPECT_TRUE(configurator_.SetDisplayPower(
+      chromeos::DISPLAY_POWER_ALL_ON,
+      DisplayConfigurator::kSetDisplayPowerNoFlags));
+  EXPECT_EQ(
+      JoinActions(
+          kGrab,
+          GetFramebufferAction(small_mode_.size(), &outputs_[0], &outputs_[1])
+              .c_str(),
+          GetCrtcAction(outputs_[0], &small_mode_, gfx::Point(0, 0)).c_str(),
+          GetCrtcAction(outputs_[1], &small_mode_, gfx::Point(0, 0)).c_str(),
+          kForceDPMS,
+          kUngrab,
+          NULL),
+      log_->GetActionsAndClear());
+
+  // Check that the task doesn't restore the old internal-off-external-on power
+  // state.
+  EXPECT_TRUE(test_api_.TriggerConfigureTimeout());
+  EXPECT_EQ(
+      JoinActions(
+          kGrab,
+          GetFramebufferAction(small_mode_.size(), &outputs_[0], &outputs_[1])
+              .c_str(),
+          GetCrtcAction(outputs_[0], &small_mode_, gfx::Point(0, 0)).c_str(),
+          GetCrtcAction(outputs_[1], &small_mode_, gfx::Point(0, 0)).c_str(),
+          kForceDPMS,
+          kUngrab,
+          NULL),
+      log_->GetActionsAndClear());
+}
+
 }  // namespace ui
diff --git a/ui/events/event_unittest.cc b/ui/events/event_unittest.cc
index 46c2f63..d2a6a69 100644
--- a/ui/events/event_unittest.cc
+++ b/ui/events/event_unittest.cc
@@ -235,7 +235,7 @@
     { VKEY_OEM_3, EF_SHIFT_DOWN, '~' },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestData); ++i) {
+  for (size_t i = 0; i < arraysize(kTestData); ++i) {
     KeyEvent key(ET_KEY_PRESSED,
                  kTestData[i].key_code,
                  kTestData[i].flags);
diff --git a/ui/events/gesture_detection/motion_event_buffer.cc b/ui/events/gesture_detection/motion_event_buffer.cc
index 11d2df7..26fc5ba 100644
--- a/ui/events/gesture_detection/motion_event_buffer.cc
+++ b/ui/events/gesture_detection/motion_event_buffer.cc
@@ -162,7 +162,7 @@
   event->set_action_index(event0.GetActionIndex());
   event->set_button_state(event0.GetButtonState());
 
-  return event.PassAs<MotionEvent>();
+  return event.Pass();
 }
 
 // MotionEvent implementation for storing multiple events, with the most
diff --git a/ui/events/gesture_detection/motion_event_generic.cc b/ui/events/gesture_detection/motion_event_generic.cc
index afda52a..ad853f5 100644
--- a/ui/events/gesture_detection/motion_event_generic.cc
+++ b/ui/events/gesture_detection/motion_event_generic.cc
@@ -153,7 +153,7 @@
 scoped_ptr<MotionEvent> MotionEventGeneric::Cancel() const {
   scoped_ptr<MotionEventGeneric> event(new MotionEventGeneric(*this));
   event->set_action(ACTION_CANCEL);
-  return event.PassAs<MotionEvent>();
+  return event.Pass();
 }
 
 void MotionEventGeneric::PushPointer(const PointerProperties& pointer) {
diff --git a/ui/events/latency_info.cc b/ui/events/latency_info.cc
index fe96055..9987908 100644
--- a/ui/events/latency_info.cc
+++ b/ui/events/latency_info.cc
@@ -130,7 +130,7 @@
     coordinates->Append(coordinate_pair.release());
   }
   record_data->Set("coordinates", coordinates.release());
-  return LatencyInfoTracedValue::FromValue(record_data.PassAs<base::Value>());
+  return LatencyInfoTracedValue::FromValue(record_data.Pass());
 }
 
 }  // namespace
diff --git a/ui/events/ozone/evdev/event_factory_evdev.cc b/ui/events/ozone/evdev/event_factory_evdev.cc
index 0895c0a..5499339 100644
--- a/ui/events/ozone/evdev/event_factory_evdev.cc
+++ b/ui/events/ozone/evdev/event_factory_evdev.cc
@@ -74,13 +74,8 @@
     scoped_ptr<GestureInterpreterLibevdevCros> gesture_interp =
         make_scoped_ptr(new GestureInterpreterLibevdevCros(
             params.modifiers, params.cursor, params.dispatch_callback));
-    scoped_ptr<EventReaderLibevdevCros> libevdev_reader =
-        make_scoped_ptr(new EventReaderLibevdevCros(
-            fd,
-            params.path,
-            params.id,
-            gesture_interp.PassAs<EventReaderLibevdevCros::Delegate>()));
-    return libevdev_reader.PassAs<EventConverterEvdev>();
+    return make_scoped_ptr(new EventReaderLibevdevCros(
+        fd, params.path, params.id, gesture_interp.Pass()));
   }
 #endif
 
diff --git a/ui/events/test/mock_motion_event.cc b/ui/events/test/mock_motion_event.cc
index 24d8159..f3de1dd 100644
--- a/ui/events/test/mock_motion_event.cc
+++ b/ui/events/test/mock_motion_event.cc
@@ -94,7 +94,7 @@
 scoped_ptr<MotionEvent> MockMotionEvent::Cancel() const {
   scoped_ptr<MockMotionEvent> event(new MockMotionEvent(*this));
   event->set_action(MotionEvent::ACTION_CANCEL);
-  return event.PassAs<MotionEvent>();
+  return event.Pass();
 }
 
 void MockMotionEvent::PressPoint(float x, float y) {
diff --git a/ui/events/x/events_x.cc b/ui/events/x/events_x.cc
index 371c8f5..e6fb312 100644
--- a/ui/events/x/events_x.cc
+++ b/ui/events/x/events_x.cc
@@ -312,7 +312,7 @@
     {ui::EF_RIGHT_MOUSE_BUTTON, Button3Mask},
   };
   unsigned int new_x_flags = old_x_flags;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(flags); ++i) {
+  for (size_t i = 0; i < arraysize(flags); ++i) {
     if (ui_flags & flags[i].ui)
       new_x_flags |= flags[i].x;
     else
diff --git a/ui/events/x/events_x_unittest.cc b/ui/events/x/events_x_unittest.cc
index 32b121c..2e33674 100644
--- a/ui/events/x/events_x_unittest.cc
+++ b/ui/events/x/events_x_unittest.cc
@@ -449,7 +449,7 @@
     { false, XK_A },
   };
 
-  for (size_t k = 0; k < ARRAYSIZE_UNSAFE(keys); ++k) {
+  for (size_t k = 0; k < arraysize(keys); ++k) {
     int x_keycode = XKeysymToKeycode(display, keys[k].x_keysym);
     // Exclude keysyms for which the server has no corresponding keycode.
     if (x_keycode) {
@@ -606,7 +606,7 @@
   unsigned int state_to_be_fabricated[] = {
     0, ShiftMask, LockMask, ShiftMask | LockMask,
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(state_to_be_fabricated); ++i) {
+  for (size_t i = 0; i < arraysize(state_to_be_fabricated); ++i) {
     unsigned int state = state_to_be_fabricated[i];
     for (int is_char = 0; is_char < 2; ++is_char) {
       XEvent x_event;
@@ -623,7 +623,7 @@
   unsigned int state_to_be_not_fabricated[] = {
     ControlMask, Mod1Mask, Mod2Mask, ShiftMask | ControlMask,
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(state_to_be_not_fabricated); ++i) {
+  for (size_t i = 0; i < arraysize(state_to_be_not_fabricated); ++i) {
     unsigned int state = state_to_be_not_fabricated[i];
     for (int is_char = 0; is_char < 2; ++is_char) {
       XEvent x_event;
diff --git a/ui/file_manager/file_manager/background/js/app_window_wrapper.js b/ui/file_manager/file_manager/background/js/app_window_wrapper.js
index 6da7e43..6a0cf2b 100644
--- a/ui/file_manager/file_manager/background/js/app_window_wrapper.js
+++ b/ui/file_manager/file_manager/background/js/app_window_wrapper.js
@@ -34,7 +34,7 @@
 
 AppWindowWrapper.prototype = {
   /**
-   * @return {AppWindow} Wrapped application window.
+   * @return {chrome.app.window.AppWindow} Wrapped application window.
    */
   get rawAppWindow() {
     return this.window_;
@@ -59,7 +59,7 @@
 
 /**
  * Focuses the window on the specified desktop.
- * @param {AppWindow} appWindow Application window.
+ * @param {chrome.app.window.AppWindow} appWindow Application window.
  * @param {string=} opt_profileId The profiled ID of the target window. If it is
  *     dropped, the window is focused on the current window.
  */
@@ -281,6 +281,7 @@
  * @param {string} url App window content url.
  * @param {Object|function()} options Options object or a function to return it.
  * @constructor
+ * @extends {AppWindowWrapper}
  */
 function SingletonAppWindowWrapper(url, options) {
   AppWindowWrapper.call(this, url, url, options);
diff --git a/ui/file_manager/file_manager/background/js/background.js b/ui/file_manager/file_manager/background/js/background.js
index 6990c2d..6c16493 100644
--- a/ui/file_manager/file_manager/background/js/background.js
+++ b/ui/file_manager/file_manager/background/js/background.js
@@ -102,7 +102,7 @@
   /**
    * Last time when the background page can close.
    *
-   * @type {number}
+   * @type {?number}
    * @private
    */
   this.lastTimeCanClose_ = null;
@@ -199,7 +199,7 @@
 
 /**
  * Opens the root directory of the volume in Files.app.
- * @param {string} volumeId ID of a volume to be opened.
+ * @param {string} devicePath Device path to a volume to be opened.
  * @private
  */
 FileBrowserBackground.prototype.navigateToVolume = function(devicePath) {
@@ -214,7 +214,7 @@
   }).then(function(entry) {
     launchFileManager(
         {currentDirectoryURL: entry.toURL()},
-        /* App ID */ null,
+        /* App ID */ undefined,
         LaunchType.FOCUS_SAME_OR_CREATE);
   }).catch(function(error) {
     console.error(error.stack || error);
@@ -422,7 +422,7 @@
   // volume will appear on the navigation list.
   launchFileManager(
       appState,
-      /* App ID */ null,
+      /* App ID */ undefined,
       LaunchType.FOCUS_SAME_OR_CREATE);
 };
 
@@ -443,7 +443,7 @@
       }
     });
   }
-  launchFileManager(null, null, LaunchType.FOCUS_ANY_OR_CREATE);
+  launchFileManager(null, undefined, LaunchType.FOCUS_ANY_OR_CREATE);
 };
 
 /**
@@ -459,7 +459,7 @@
         if (match) {
           var id = Number(match[1]);
           try {
-            var appState = JSON.parse(items[key]);
+            var appState = /** @type {Object} */ (JSON.parse(items[key]));
             launchFileManager(appState, id);
           } catch (e) {
             console.error('Corrupt launch data for ' + id);
diff --git a/ui/file_manager/file_manager/background/js/device_handler.js b/ui/file_manager/file_manager/background/js/device_handler.js
index bf79b40..ede5409 100644
--- a/ui/file_manager/file_manager/background/js/device_handler.js
+++ b/ui/file_manager/file_manager/background/js/device_handler.js
@@ -192,7 +192,7 @@
 
 /**
  * Shows the notificaiton without using AsyncQueue.
- * @param {string} notificaitonId Notification ID.
+ * @param {string} notificationId Notification ID.
  * @param {?string} message Message overriding the normal message.
  * @param {function()} callback Callback to be invoked when the notification is
  *     created.
@@ -302,14 +302,13 @@
   // If this is remounting, which happens when resuming ChromeOS, the device has
   // already inserted to the computer. So we suppress the notification.
   var volume = event.volumeMetadata;
-  if (!volume.deviceType || !event.shouldNotify)
+  if (!volume.deviceType || !volume.devicePath || !event.shouldNotify)
     return;
 
   // If the current volume status is succeed and it should be handled in
   // Files.app, show the notification to navigate the volume.
   if (event.eventType === 'mount' && event.status === 'success') {
-    DeviceHandler.Notification.DEVICE_NAVIGATION.show(
-        event.volumeMetadata.devicePath);
+    DeviceHandler.Notification.DEVICE_NAVIGATION.show(volume.devicePath);
   } else if (event.eventType === 'unmount') {
     DeviceHandler.Notification.DEVICE_NAVIGATION.hide(volume.devicePath);
   }
diff --git a/ui/file_manager/file_manager/background/js/drive_sync_handler.js b/ui/file_manager/file_manager/background/js/drive_sync_handler.js
index 7540b79..55a277d 100644
--- a/ui/file_manager/file_manager/background/js/drive_sync_handler.js
+++ b/ui/file_manager/file_manager/background/js/drive_sync_handler.js
@@ -9,6 +9,7 @@
  * @param {ProgressCenter} progressCenter Progress center to submit the
  *     progressing items.
  * @constructor
+ * @extends {cr.EventTarget}
  */
 function DriveSyncHandler(progressCenter) {
   /**
diff --git a/ui/file_manager/file_manager/background/js/file_operation_handler.js b/ui/file_manager/file_manager/background/js/file_operation_handler.js
index 1610bd0..c3dd81b 100644
--- a/ui/file_manager/file_manager/background/js/file_operation_handler.js
+++ b/ui/file_manager/file_manager/background/js/file_operation_handler.js
@@ -6,13 +6,13 @@
 
 /**
  * An event handler of the background page for file operations.
- * @param {Window} background Background page.
+ * @param {FileBrowserBackground} background Background page.
  * @constructor
  */
 var FileOperationHandler = function(background) {
   /**
    * Background page.
-   * @type {Window}
+   * @type {FileBrowserBackground}
    * @private
    */
   this.background_ = background;
@@ -67,7 +67,7 @@
 
 /**
  * Generate a progress message from the event.
- * @param {Event} event Progress event.
+ * @param {FileOperationProgressEvent} event Progress event.
  * @return {string} message.
  * @private
  */
@@ -128,6 +128,7 @@
  * @private
  */
 FileOperationHandler.getDeleteMessage_ = function(event) {
+  event = /** @type {FileOperationProgressEvent} */ (event);
   if (event.reason === 'ERROR') {
     return str('DELETE_ERROR');
   } else if (event.entries.length == 1) {
@@ -164,6 +165,7 @@
  * @private
  */
 FileOperationHandler.prototype.onCopyProgress_ = function(event) {
+  event = /** @type {FileOperationProgressEvent} */ (event);
   // If the copy is finished, may be we can close the background page.
   if (event.reason !== 'BEGIN' && event.reason !== 'PROGRESS')
     this.background_.tryClose();
@@ -230,6 +232,7 @@
  * @private
  */
 FileOperationHandler.prototype.onDeleteProgress_ = function(event) {
+  event = /** @type {FileOperationProgressEvent} */ (event);
   // If the copy is finished, may be we can close the background page.
   if (event.reason !== 'BEGIN' && event.reason !== 'PROGRESS')
     this.background_.tryClose();
diff --git a/ui/file_manager/file_manager/background/js/file_operation_manager.js b/ui/file_manager/file_manager/background/js/file_operation_manager.js
index a4727ca..7bed2f3 100644
--- a/ui/file_manager/file_manager/background/js/file_operation_manager.js
+++ b/ui/file_manager/file_manager/background/js/file_operation_manager.js
@@ -413,7 +413,8 @@
   if (reason === 'SUCCESS' || reason === 'CANCELED')
     this.entryChangedEventRateLimiter_.runImmediately();
 
-  var event = new Event('copy-progress');
+  var event = /** @type {FileOperationProgressEvent} */
+      (new Event('copy-progress'));
   event.reason = reason;
   event.status = status;
   event.taskId = taskId;
@@ -470,7 +471,7 @@
  */
 FileOperationManager.EventRouter.prototype.sendDeleteEvent = function(
     reason, task) {
-  var event = new Event('delete');
+  var event = /** @type {FileOperationProgressEvent} */ (new Event('delete'));
   event.reason = reason;
   event.taskId = task.taskId;
   event.entries = task.entries;
@@ -531,7 +532,7 @@
 
   /**
    * Callback to cancel the running process.
-   * @private {function()}
+   * @private {?function()}
    */
   this.cancelCallback_ = null;
 
@@ -953,7 +954,7 @@
  * Moves the sourceEntry to the targetDirEntry in this task.
  *
  * @param {Entry} sourceEntry An entry to be moved.
- * @param {DirectoryEntry} destinationEntry The entry of the destination
+ * @param {!DirectoryEntry} destinationEntry The entry of the destination
  *     directory.
  * @param {function(util.EntryChangedKind, Entry)} entryChangedCallback
  *     Callback invoked when an entry is changed.
@@ -1457,7 +1458,7 @@
 /**
  * Creates a zip file for the selection of files.
  *
- * @param {Entry} dirEntry The directory containing the selection.
+ * @param {!DirectoryEntry} dirEntry The directory containing the selection.
  * @param {Array.<Entry>} selectionEntries The selected entries.
  */
 FileOperationManager.prototype.zipSelection = function(
diff --git a/ui/file_manager/file_manager/background/js/progress_center.js b/ui/file_manager/file_manager/background/js/progress_center.js
index f19fe9e..a8b1fe2 100644
--- a/ui/file_manager/file_manager/background/js/progress_center.js
+++ b/ui/file_manager/file_manager/background/js/progress_center.js
@@ -11,7 +11,7 @@
 var ProgressCenter = function() {
   /**
    * Current items managed by the progress center.
-   * @type {Array.<ProgressCenterItem>}
+   * @type {Array.<!ProgressCenterItem>}
    * @private
    */
   this.items_ = [];
diff --git a/ui/file_manager/file_manager/background/js/volume_manager.js b/ui/file_manager/file_manager/background/js/volume_manager.js
index 64300d2..1f0704a 100644
--- a/ui/file_manager/file_manager/background/js/volume_manager.js
+++ b/ui/file_manager/file_manager/background/js/volume_manager.js
@@ -11,18 +11,18 @@
  * @param {VolumeManagerCommon.VolumeType} volumeType The type of the volume.
  * @param {string} volumeId ID of the volume.
  * @param {FileSystem} fileSystem The file system object for this volume.
- * @param {string} error The error if an error is found.
- * @param {?string} deviceType The type of device ('usb'|'sd'|'optical'|'mobile'
- *     |'unknown') (as defined in chromeos/disks/disk_mount_manager.cc).
- *     Can be null.
- * @param {?string} devicePath Identifier of the device that the volume belongs
- *     to. Can be null.
+ * @param {(string|undefined)} error The error if an error is found.
+ * @param {(string|undefined)} deviceType The type of device
+ *     ('usb'|'sd'|'optical'|'mobile'|'unknown') (as defined in
+ *     chromeos/disks/disk_mount_manager.cc). Can be undefined.
+ * @param {(string|undefined)} devicePath Identifier of the device that the
+ *     volume belongs to. Can be undefined.
  * @param {boolean} isReadOnly True if the volume is read only.
  * @param {!{displayName:string, isCurrentProfile:boolean}} profile Profile
  *     information.
  * @param {string} label Label of the volume.
- * @param {string} extensionId Id of the extension providing this volume. Empty
- *     for native volumes.
+ * @param {(string|undefined)} extensionId Id of the extension providing this
+ *     volume. Empty for native volumes.
  * @constructor
  */
 function VolumeInfo(
@@ -110,19 +110,19 @@
     return this.fakeEntries_;
   },
   /**
-   * @return {string} Error identifier.
+   * @return {(string|undefined)} Error identifier.
    */
   get error() {
     return this.error_;
   },
   /**
-   * @return {string} Device type identifier.
+   * @return {(string|undefined)} Device type identifier.
    */
   get deviceType() {
     return this.deviceType_;
   },
   /**
-   * @return {string} Device identifier.
+   * @return {(string|undefined)} Device identifier.
    */
   get devicePath() {
     return this.devicePath_;
@@ -146,7 +146,7 @@
     return this.label_;
   },
   /**
-   * @return {string} Id of an extennsion providing this volume.
+   * @return {(string|undefined)} Id of an extennsion providing this volume.
    */
   get extensionId() {
     return this.extensionId_;
@@ -198,8 +198,7 @@
  * Throws an Error when the given error is not in
  * VolumeManagerCommon.VolumeError.
  *
- * @param {VolumeManagerCommon.VolumeError} error Status string usually received
- *     from APIs.
+ * @param {string} error Status string usually received from APIs.
  */
 volumeManagerUtil.validateError = function(error) {
   for (var key in VolumeManagerCommon.VolumeError) {
@@ -239,7 +238,8 @@
         if (!fileSystem) {
           console.error('File system not found: ' + volumeMetadata.volumeId);
           callback(new VolumeInfo(
-              volumeMetadata.volumeType,
+              /** @type {VolumeManagerCommon.VolumeType} */
+              (volumeMetadata.volumeType),
               volumeMetadata.volumeId,
               null,  // File system is not found.
               volumeMetadata.mountCondition,
@@ -266,7 +266,8 @@
               });
         }
         callback(new VolumeInfo(
-            volumeMetadata.volumeType,
+            /** @type {VolumeManagerCommon.VolumeType} */
+            (volumeMetadata.volumeType),
             volumeMetadata.volumeId,
             fileSystem,
             volumeMetadata.mountCondition,
@@ -301,8 +302,8 @@
  * The volumes at first are compared by volume type in the order of
  * volumeListOrder_.  Then they are compared by volume ID.
  *
- * @param {VolumeInfo} volumeInfo1 Volume info to be compared.
- * @param {VolumeInfo} volumeInfo2 Volume info to be compared.
+ * @param {!VolumeInfo} volumeInfo1 Volume info to be compared.
+ * @param {!VolumeInfo} volumeInfo2 Volume info to be compared.
  * @return {number} Returns -1 if volume1 < volume2, returns 1 if volume2 >
  *     volume1, returns 0 if volume1 === volume2.
  * @private
@@ -332,7 +333,9 @@
    * @private
    */
   this.model_ = new cr.ui.ArrayDataModel([]);
-  this.model_.setCompareFunction(field, volumeManagerUtil.compareVolumeInfo_);
+  this.model_.setCompareFunction(field,
+                                 /** @type {function(*, *): number} */
+                                 (volumeManagerUtil.compareVolumeInfo_));
   this.model_.sort(field, 'asc');
 
   Object.freeze(this);
@@ -420,10 +423,10 @@
 
 /**
  * @param {number} index The index of the volume in the list.
- * @return {VolumeInfo} The VolumeInfo instance.
+ * @return {!VolumeInfo} The VolumeInfo instance.
  */
 VolumeInfoList.prototype.item = function(index) {
-  return this.model_.item(index);
+  return /** @type {!VolumeInfo} */ (this.model_.item(index));
 };
 
 /**
@@ -456,6 +459,11 @@
 
   // The status should be merged into VolumeManager.
   // TODO(hidehiko): Remove them after the migration.
+  /**
+   * Connection state of the Drive.
+   * @type {VolumeManagerCommon.DriveConnectionState}
+   * @private
+   */
   this.driveConnectionState_ = {
     type: VolumeManagerCommon.DriveConnectionType.OFFLINE,
     reason: VolumeManagerCommon.DriveConnectionReason.NO_SERVICE
@@ -468,7 +476,7 @@
 
 /**
  * Invoked when the drive connection status is changed.
- * @private_
+ * @private
  */
 VolumeManager.prototype.onDriveConnectionStatusChanged_ = function() {
   chrome.fileManagerPrivate.getDriveConnectionState(function(state) {
@@ -479,7 +487,7 @@
 
 /**
  * Returns the drive connection state.
- * @return {VolumeManagerCommon.DriveConnectionType} Connection type.
+ * @return {VolumeManagerCommon.DriveConnectionState} Connection state.
  */
 VolumeManager.prototype.getDriveConnectionState = function() {
   return this.driveConnectionState_;
@@ -520,11 +528,11 @@
 /**
  * Returns the VolumeManager instance asynchronously. If it is not created or
  * under initialization, it will waits for the finish of the initialization.
- * @param {function(VolumeManager)} callback Called with the VolumeManager
+ * @param {function(VolumeManager)=} opt_callback Called with the VolumeManager
  *     instance. TODO(hirono): Remove the callback and use Promise instead.
  * @return {Promise} Promise to be fulfilled with the volume manager.
  */
-VolumeManager.getInstance = function(callback) {
+VolumeManager.getInstance = function(opt_callback) {
   if (!VolumeManager.instancePromise_) {
     VolumeManager.instance_ = new VolumeManager();
     VolumeManager.instancePromise_ = new Promise(function(fulfill) {
@@ -533,8 +541,8 @@
       });
     });
   }
-  if (callback)
-    VolumeManager.instancePromise_.then(callback);
+  if (opt_callback)
+    VolumeManager.instancePromise_.then(opt_callback);
   return VolumeManager.instancePromise_;
 };
 
diff --git a/ui/file_manager/file_manager/common/js/externs.js b/ui/file_manager/file_manager/common/js/externs.js
new file mode 100644
index 0000000..d5f375e
--- /dev/null
+++ b/ui/file_manager/file_manager/common/js/externs.js
@@ -0,0 +1,45 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @constructor
+ * @extends {Window}
+ */
+var BackgroundWindow = function() {};
+
+/**
+ * @type {FileBrowserBackground}
+ */
+BackgroundWindow.prototype.background;
+
+/**
+ * @param {Window} window
+ */
+BackgroundWindow.prototype.registerDialog = function(window) {};
+
+
+/**
+ * @constructor
+ * @extends {Event}
+ */
+var FileOperationProgressEvent = function() {};
+
+/** @type {string} */
+FileOperationProgressEvent.prototype.reason;
+
+/** @type {(FileOperationManager.Error|undefined)} */
+FileOperationProgressEvent.prototype.error;
+
+
+/**
+ * @constructor
+ * @extends {Event}
+ */
+var EntriesChangedEvent = function() {};
+
+/** @type {util.EntryChangedKind} */
+EntriesChangedEvent.prototype.kind;
+
+/** @type {Array.<!Entry>} */
+EntriesChangedEvent.prototype.entries;
diff --git a/ui/file_manager/file_manager/common/js/progress_center_common.js b/ui/file_manager/file_manager/common/js/progress_center_common.js
index 7e102ef..56ff028 100644
--- a/ui/file_manager/file_manager/common/js/progress_center_common.js
+++ b/ui/file_manager/file_manager/common/js/progress_center_common.js
@@ -64,7 +64,7 @@
 var ProgressCenterItem = function() {
   /**
    * Item ID.
-   * @type {string}
+   * @type {?string}
    * @private
    */
   this.id_ = null;
@@ -95,7 +95,7 @@
 
   /**
    * Type of progress item.
-   * @type {ProgressItemType}
+   * @type {?ProgressItemType}
    */
   this.type = null;
 
@@ -114,7 +114,7 @@
 
   /**
    * Callback function to cancel the item.
-   * @type {function()}
+   * @type {?function()}
    */
   this.cancelCallback = null;
 
@@ -137,7 +137,7 @@
 
   /**
    * Getter of Item ID.
-   * @return {string} Item ID.
+   * @return {?string} Item ID.
    */
   get id() {
     return this.id_;
diff --git a/ui/file_manager/file_manager/common/js/util.js b/ui/file_manager/file_manager/common/js/util.js
index f5bf344..e6dbe42 100644
--- a/ui/file_manager/file_manager/common/js/util.js
+++ b/ui/file_manager/file_manager/common/js/util.js
@@ -206,7 +206,7 @@
  * @param {File} file The file to read.
  * @param {number} begin Starting byte(included).
  * @param {number} end Last byte(excluded).
- * @param {function(File, Uint8Array)} callback Callback to invoke.
+ * @param {function(File, ByteReader)} callback Callback to invoke.
  * @param {function(string)} onError Error handler.
  */
 util.readFileBytes = function(file, begin, end, callback, onError) {
@@ -215,7 +215,8 @@
     onError(event.type);
   };
   fileReader.onloadend = function() {
-    callback(file, new ByteReader(fileReader.result));
+    callback(file, new ByteReader(
+        /** @type {ArrayBuffer} */ (fileReader.result)));
   };
   fileReader.readAsArrayBuffer(file.slice(begin, end));
 };
@@ -235,7 +236,7 @@
 };
 
 /**
- * @param {HTMLElement} element Element to transform.
+ * @param {Element} element Element to transform.
  * @param {Object} transform Transform object,
  *                           contains scaleX, scaleY and rotate90 properties.
  */
@@ -264,7 +265,7 @@
 /**
  * A shortcut function to create a child element with given tag and class.
  *
- * @param {HTMLElement} parent Parent element.
+ * @param {Element} parent Parent element.
  * @param {string=} opt_className Class name.
  * @param {string=} opt_tag Element tag, DIV is omitted.
  * @return {Element} Newly created element.
@@ -318,7 +319,7 @@
  * Equivalent to loadTimeData.getStringF(id, ...).
  *
  * @param {string} id The id of the string to return.
- * @param {...string} var_args The values to replace into the string.
+ * @param {...*} var_args The values to replace into the string.
  * @return {string} The translated string with replaced values.
  */
 function strf(id, var_args) {
@@ -480,7 +481,7 @@
 /**
  * Load an image.
  *
- * @param {Image} image Image element.
+ * @param {HTMLImageElement} image Image element.
  * @param {string} url Source url.
  * @param {Object=} opt_options Hash array of options, eg. width, height,
  *     maxWidth, maxHeight, scale, cache.
@@ -615,7 +616,7 @@
 
 /**
  * Obtains whether an entry is fake or not.
- * @param {!Entry|!Object} entry Entry or a fake entry.
+ * @param {(Entry|Object)} entry Entry or a fake entry.
  * @return {boolean} True if the given entry is fake.
  */
 util.isFakeEntry = function(entry) {
@@ -916,8 +917,9 @@
 /**
  * Returns the localized name of the entry.
  *
- * @param {VolumeManager} volumeManager The volume manager.
- * @param {Entry} entry The entry to be retrieve the name of.
+ * @param {(VolumeManager|VolumeManagerWrapper)} volumeManager The volume
+ *     manager.
+ * @param {!Entry} entry The entry to be retrieve the name of.
  * @return {?string} The localized name.
  */
 util.getEntryLabel = function(volumeManager, entry) {
diff --git a/ui/file_manager/file_manager/common/js/volume_manager_common.js b/ui/file_manager/file_manager/common/js/volume_manager_common.js
index 66fbaf8..2d0f729 100644
--- a/ui/file_manager/file_manager/common/js/volume_manager_common.js
+++ b/ui/file_manager/file_manager/common/js/volume_manager_common.js
@@ -130,3 +130,11 @@
   PROVIDED: 'provided'
 };
 Object.freeze(VolumeManagerCommon.VolumeType);
+
+/**
+ * @typedef {{
+ *   type: VolumeManagerCommon.DriveConnectionType,
+ *   reason: VolumeManagerCommon.DriveConnectionReason
+ * }}
+ */
+VolumeManagerCommon.DriveConnectionState;
diff --git a/ui/file_manager/file_manager/foreground/js/app_installer.js b/ui/file_manager/file_manager/foreground/js/app_installer.js
index 9508676..4b75bea 100644
--- a/ui/file_manager/file_manager/foreground/js/app_installer.js
+++ b/ui/file_manager/file_manager/foreground/js/app_installer.js
@@ -44,8 +44,8 @@
 
 /**
  * Start an installation.
- * @param {function(boolean, string)} callback Called when the installation is
- *     finished.
+ * @param {function(AppInstaller.Result, string)} callback Called when the
+ *     installation is finished.
  */
 AppInstaller.prototype.install = function(callback) {
   this.callback_ = callback;
diff --git a/ui/file_manager/file_manager/foreground/js/compiled_resources.gyp b/ui/file_manager/file_manager/foreground/js/compiled_resources.gyp
index 504f041..0a389d8 100644
--- a/ui/file_manager/file_manager/foreground/js/compiled_resources.gyp
+++ b/ui/file_manager/file_manager/foreground/js/compiled_resources.gyp
@@ -4,23 +4,105 @@
 {
   'targets': [
     {
-      'target_name': 'main_scripts',
+      'target_name': 'main',
       'variables': {
         'depends': [
           '../../../../../third_party/jstemplate/compiled_resources.gyp:jstemplate',
+          '../../../../../ui/webui/resources/js/load_time_data.js',
+          '../../../../../ui/webui/resources/js/cr.js',
+          '../../../../../ui/webui/resources/js/util.js',
+          '../../../../../ui/webui/resources/js/i18n_template_no_process.js',
+          '../../../../../ui/webui/resources/js/event_tracker.js',
+          '../../../../../ui/webui/resources/js/cr/ui.js',
+          '../../../../../ui/webui/resources/js/cr/event_target.js',
+          '../../../../../ui/webui/resources/js/cr/ui/touch_handler.js',
+          '../../../../../ui/webui/resources/js/cr/ui/array_data_model.js',
           '../../../../../ui/webui/resources/js/cr/ui/dialogs.js',
-          '../../common/js/util.js',
+          '../../../../../ui/webui/resources/js/cr/ui/list_item.js',
+          '../../../../../ui/webui/resources/js/cr/ui/list_selection_model.js',
+          '../../../../../ui/webui/resources/js/cr/ui/list_single_selection_model.js',
+          '../../../../../ui/webui/resources/js/cr/ui/list_selection_controller.js',
+          '../../../../../ui/webui/resources/js/cr/ui/list.js',
+          '../../../../../ui/webui/resources/js/cr/ui/tree.js',
+          '../../../../../ui/webui/resources/js/cr/ui/autocomplete_list.js',
+          '../../../../../ui/webui/resources/js/cr/ui/splitter.js',
+          '../../../../../ui/webui/resources/js/cr/ui/table/table_splitter.js',
+          '../../../../../ui/webui/resources/js/cr/ui/table/table_column.js',
+          '../../../../../ui/webui/resources/js/cr/ui/table/table_column_model.js',
+          '../../../../../ui/webui/resources/js/cr/ui/table/table_header.js',
+          '../../../../../ui/webui/resources/js/cr/ui/table/table_list.js',
+          '../../../../../ui/webui/resources/js/cr/ui/table.js',
+          '../../../../../ui/webui/resources/js/cr/ui/grid.js',
+          '../../../../../ui/webui/resources/js/cr/ui/command.js',
+          '../../../../../ui/webui/resources/js/cr/ui/position_util.js',
+          '../../../../../ui/webui/resources/js/cr/ui/menu_item.js',
+          '../../../../../ui/webui/resources/js/cr/ui/menu.js',
+          '../../../../../ui/webui/resources/js/cr/ui/menu_button.js',
+          '../../../../../ui/webui/resources/js/cr/ui/context_menu_handler.js',
+          '../../common/js/error_util.js',
           '../../common/js/async_util.js',
           '../../common/js/volume_manager_common.js',
+          '../../common/js/util.js',
+          '../../common/js/progress_center_common.js',
           '../../background/js/file_operation_manager.js',
+          '../../background/js/file_operation_handler.js',
+          '../../background/js/device_handler.js',
+          '../../background/js/drive_sync_handler.js',
           '../../background/js/volume_manager.js',
           '../../background/js/progress_center.js',
+          '../../background/js/app_window_wrapper.js',
+          '../../background/js/background_base.js',
+          '../../background/js/background.js',
+          '../../../image_loader/image_loader_client.js',
+          './metrics.js',
+          './ui/combobutton.js',
+          './ui/commandbutton.js',
+          './ui/file_manager_dialog_base.js',
+          './app_installer.js',
+          './cws_container_client.js',
+          './directory_contents.js',
+          './directory_model.js',
+          './file_manager.js',
+          './file_manager_commands.js',
+          './file_selection.js',
+          './file_tasks.js',
+          './file_transfer_controller.js',
+          './file_type.js',
+          './file_watcher.js',
+          './folder_shortcuts_data_model.js',
+          './metadata/metadata_cache.js',
+          './navigation_list_model.js',
+          './progress_center_item_group.js',
+          './search_controller.js',
+          './share_client.js',
+          './thumbnail_loader.js',
+          './ui/conflict_dialog.js',
+          './ui/default_action_dialog.js',
+          './ui/directory_tree.js',
+          './ui/drag_selector.js',
+          './ui/drive_banners.js',
+          './ui/error_dialog.js',
+          './ui/file_grid.js',
+          './ui/file_manager_ui.js',
+          './ui/file_table.js',
+          './ui/location_line.js',
+          './ui/multi_profile_share_dialog.js',
+          './ui/preview_panel.js',
+          './ui/progress_center_panel.js',
+          './ui/scrollbar.js',
+          './ui/search_box.js',
+          './ui/share_dialog.js',
+          './ui/suggest_apps_dialog.js',
+          './ui/tree.css.js',
+          './volume_manager_wrapper.js',
+          './metadata/byte_reader.js',
         ],
         'externs': [
           '<(CLOSURE_DIR)/externs/chrome_send_externs.js',
           '<(CLOSURE_DIR)/externs/chrome_extensions.js',
           '<(CLOSURE_DIR)/externs/file_manager_private.js',
           '<(CLOSURE_DIR)/externs/metrics_private.js',
+          '../../common/js/externs.js',
         ],
       },
       'includes': [
diff --git a/ui/file_manager/file_manager/foreground/js/cws_container_client.js b/ui/file_manager/file_manager/foreground/js/cws_container_client.js
index 616617c..612bbe5 100644
--- a/ui/file_manager/file_manager/foreground/js/cws_container_client.js
+++ b/ui/file_manager/file_manager/foreground/js/cws_container_client.js
@@ -14,6 +14,7 @@
  * @param {string} url Share Url for an entry.
  * @param {string} target Target (scheme + host + port) of the widget.
  * @constructor
+ * @extends {cr.EventTarget}
  */
 function CWSContainerClient(
     webView, ext, mime, searchQuery, width, height, url, target) {
diff --git a/ui/file_manager/file_manager/foreground/js/directory_contents.js b/ui/file_manager/file_manager/foreground/js/directory_contents.js
index 4bcbea2..aec6b15 100644
--- a/ui/file_manager/file_manager/foreground/js/directory_contents.js
+++ b/ui/file_manager/file_manager/foreground/js/directory_contents.js
@@ -259,7 +259,7 @@
 
 /**
  * Scanner of the entries for the metadata search on Drive File System.
- * @param {DriveMetadataSearchContentScanner.SearchType} searchType The option
+ * @param {!DriveMetadataSearchContentScanner.SearchType} searchType The option
  *     of the search.
  * @constructor
  * @extends {ContentScanner}
@@ -341,7 +341,8 @@
 
   // Do not show entries marked as 'deleted'.
   this.addFilter('deleted', function(entry) {
-    var internal = this.metadataCache_.getCached(entry, 'internal');
+    var internal = /** @type {{deleted}} */
+        (this.metadataCache_.getCached(entry, 'internal'));
     return !(internal && internal.deleted);
   }.bind(this));
 }
@@ -423,10 +424,14 @@
   this.metadataCache_ = metadataCache;
 
   // Initialize compare functions.
-  this.setCompareFunction('name', util.compareName);
-  this.setCompareFunction('modificationTime', this.compareMtime_.bind(this));
-  this.setCompareFunction('size', this.compareSize_.bind(this));
-  this.setCompareFunction('type', this.compareType_.bind(this));
+  this.setCompareFunction('name',
+      /** @type {function(*, *): number} */ (util.compareName));
+  this.setCompareFunction('modificationTime',
+      /** @type {function(*, *): number} */ (this.compareMtime_.bind(this)));
+  this.setCompareFunction('size',
+      /** @type {function(*, *): number} */ (this.compareSize_.bind(this)));
+  this.setCompareFunction('type',
+      /** @type {function(*, *): number} */ (this.compareType_.bind(this)));
 }
 
 FileListModel.prototype = {
@@ -591,7 +596,7 @@
 
 /**
  * Use a given fileList instead of the fileList from the context.
- * @param {Array|cr.ui.ArrayDataModel} fileList The new file list.
+ * @param {(!Array|!cr.ui.ArrayDataModel)} fileList The new file list.
  */
 DirectoryContents.prototype.setFileList = function(fileList) {
   if (fileList instanceof cr.ui.ArrayDataModel)
@@ -939,7 +944,7 @@
  * @param {DirectoryEntry} fakeDirectoryEntry Fake directory entry representing
  *     the set of result entries. This serves as a top directory for the
  *     search.
- * @param {DriveMetadataSearchContentScanner.SearchType} searchType The type of
+ * @param {!DriveMetadataSearchContentScanner.SearchType} searchType The type of
  *     the search. The scanner will restricts the entries based on the given
  *     type.
  * @return {DirectoryContents} Created DirectoryContents instance.
diff --git a/ui/file_manager/file_manager/foreground/js/directory_model.js b/ui/file_manager/file_manager/foreground/js/directory_model.js
index ec44c1e..ac3751d 100644
--- a/ui/file_manager/file_manager/foreground/js/directory_model.js
+++ b/ui/file_manager/file_manager/foreground/js/directory_model.js
@@ -284,7 +284,7 @@
 DirectoryModel.prototype.setLeadEntry_ = function(value) {
   var fileList = this.getFileList();
   for (var i = 0; i < fileList.length; i++) {
-    if (util.isSameEntry(fileList.item(i), value)) {
+    if (util.isSameEntry(/** @type {Entry} */ (fileList.item(i)), value)) {
       this.fileListSelection_.leadIndex = i;
       return;
     }
@@ -713,7 +713,7 @@
 DirectoryModel.prototype.findIndexByEntry_ = function(entry) {
   var fileList = this.getFileList();
   for (var i = 0; i < fileList.length; i++) {
-    if (util.isSameEntry(fileList.item(i), entry))
+    if (util.isSameEntry(/** @type {Entry} */ (fileList.item(i)), entry))
       return i;
   }
   return -1;
@@ -859,7 +859,7 @@
 
                 // Notify that the current task of this.directoryChangeQueue_
                 // is completed.
-                setTimeout(queueTaskCallback);
+                setTimeout(queueTaskCallback, 0);
               });
 
           // For tests that open the dialog to empty directories, everything
@@ -957,7 +957,7 @@
 };
 
 /**
- * @param {Array.<string>} entries Array of entries.
+ * @param {Array.<Entry>} entries Array of entries.
  */
 DirectoryModel.prototype.selectEntries = function(entries) {
   // URLs are needed here, since we are comparing Entries by URLs.
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager.js b/ui/file_manager/file_manager/foreground/js/file_manager.js
index eebb3ea..4344c58 100644
--- a/ui/file_manager/file_manager/foreground/js/file_manager.js
+++ b/ui/file_manager/file_manager/foreground/js/file_manager.js
@@ -264,7 +264,7 @@
 
   /**
    * Background page.
-   * @type {Window}
+   * @type {BackgroundWindow}
    * @private
    */
   this.backgroundPage_ = null;
@@ -405,21 +405,21 @@
 
   /**
    * Bound function for onCopyProgress_.
-   * @type {function(this:FileManager, Event)}
+   * @type {?function(this:FileManager, Event)}
    * @private
    */
   this.onCopyProgressBound_ = null;
 
   /**
    * Bound function for onEntriesChanged_.
-   * @type {function(this:FileManager, Event)}
+   * @type {?function(this:FileManager, Event)}
    * @private
    */
   this.onEntriesChangedBound_ = null;
 
   /**
    * Bound function for onCancel_.
-   * @type {function(this:FileManager, Event)}
+   * @type {?function(this:FileManager, Event)}
    * @private
    */
   this.onCancelBound_ = null;
@@ -649,7 +649,7 @@
 };
 
 /**
- * @param {string} type Dialog type.
+ * @param {DialogType} type Dialog type.
  * @return {boolean} Whether the type is modal.
  */
 DialogType.isModal = function(type) {
@@ -661,7 +661,7 @@
 };
 
 /**
- * @param {string} type Dialog type.
+ * @param {DialogType} type Dialog type.
  * @return {boolean} Whether the type is open dialog.
  */
 DialogType.isOpenDialog = function(type) {
@@ -672,7 +672,7 @@
 };
 
 /**
- * @param {string} type Dialog type.
+ * @param {DialogType} type Dialog type.
  * @return {boolean} Whether the type is open dialog for file(s).
  */
 DialogType.isOpenFileDialog = function(type) {
@@ -681,7 +681,7 @@
 };
 
 /**
- * @param {string} type Dialog type.
+ * @param {DialogType} type Dialog type.
  * @return {boolean} Whether the type is folder selection dialog.
  */
 DialogType.isFolderDialog = function(type) {
@@ -812,7 +812,7 @@
     // FileListBannerController.
     this.getPreferences_(function(pref) {
       /** @type {boolean} */
-      var showOffers = pref['allowRedeemOffers'];
+      var showOffers = !!pref['allowRedeemOffers'];
       self.bannersController_ = new FileListBannerController(
           self.directoryModel_, self.volumeManager_, self.document_,
           showOffers);
@@ -1217,7 +1217,8 @@
     var driveEnabled =
         !noLocalPathResolution || !this.params_.shouldReturnLocalPath;
     this.volumeManager_ = new VolumeManagerWrapper(
-        driveEnabled, this.backgroundPage_);
+        /** @type {VolumeManagerWrapper.DriveEnabledStatus} */ (driveEnabled),
+        this.backgroundPage_);
     callback();
   };
 
@@ -1344,7 +1345,8 @@
     this.document_.addEventListener('keydown', this.onKeyDown_.bind(this));
     this.document_.addEventListener('keyup', this.onKeyUp_.bind(this));
 
-    this.renameInput_ = this.document_.createElement('input');
+    this.renameInput_ = /** @type {HTMLInputElement} */
+        (this.document_.createElement('input'));
     this.renameInput_.className = 'rename entry-name';
 
     this.renameInput_.addEventListener(
@@ -1360,7 +1362,8 @@
     this.filenameInput_.addEventListener(
         'focus', this.onFilenameInputFocus_.bind(this));
 
-    this.listContainer_ = this.dialogDom_.querySelector('#list-container');
+    this.listContainer_ = /** @type {!HTMLDivElement} */
+        (this.dialogDom_.querySelector('#list-container'));
     this.listContainer_.addEventListener(
         'keydown', this.onListKeyDown_.bind(this));
     this.listContainer_.addEventListener(
@@ -1375,12 +1378,13 @@
     this.decorateSplitter(
         this.dialogDom_.querySelector('#navigation-list-splitter'));
 
-    this.dialogContainer_ = this.dialogDom_.querySelector('.dialog-container');
+    this.dialogContainer_ = /** @type {!HTMLDivElement} */
+        (this.dialogDom_.querySelector('.dialog-container'));
 
-    this.syncButton = this.dialogDom_.querySelector(
-        '#gear-menu-drive-sync-settings');
-    this.hostedButton = this.dialogDom_.querySelector(
-        '#gear-menu-drive-hosted-settings');
+    this.syncButton = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#gear-menu-drive-sync-settings'));
+    this.hostedButton = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#gear-menu-drive-hosted-settings'));
 
     this.ui_.toggleViewButton.addEventListener('click',
         this.onToggleViewButtonClick_.bind(this));
@@ -1398,11 +1402,11 @@
     this.dialogDom_.ownerDocument.defaultView.addEventListener(
         'resize', this.onResize_.bind(this));
 
-    this.defaultActionMenuItem_ =
-        this.dialogDom_.querySelector('#default-action');
+    this.defaultActionMenuItem_ = /** @type {HTMLElement} */
+        (this.dialogDom_.querySelector('#default-action'));
 
-    this.openWithCommand_ =
-        this.dialogDom_.querySelector('#open-with');
+    this.openWithCommand_ = /** @type {cr.ui.Command} */
+        (this.dialogDom_.querySelector('#open-with'));
 
     this.defaultActionMenuItem_.addEventListener('activate',
         this.dispatchSelectionAction_.bind(this));
@@ -1568,7 +1572,8 @@
   FileManager.prototype.initDirectoryTree_ = function() {
     var fakeEntriesVisible =
         this.dialogType !== DialogType.SELECT_SAVEAS_FILE;
-    this.directoryTree_ = this.dialogDom_.querySelector('#directory-tree');
+    this.directoryTree_ = /** @type {DirectoryTree} */
+        (this.dialogDom_.querySelector('#directory-tree'));
     DirectoryTree.decorate(this.directoryTree_,
                            this.directoryModel_,
                            this.volumeManager_,
@@ -1583,7 +1588,8 @@
     var observer = new MutationObserver(
         this.directoryTree_.relayout.bind(this.directoryTree_));
     observer.observe(this.progressCenterPanel_.element,
-                     {subtree: true, attributes: true, childList: true});
+                     /** @type {MutationObserverInit} */
+                     ({subtree: true, attributes: true, childList: true}));
   };
 
   /**
@@ -2256,7 +2262,7 @@
     if (leadIndex < 0)
       return;
 
-    var leadEntry = dm.getFileList().item(leadIndex);
+    var leadEntry = /** @type {Entry} */ (dm.getFileList().item(leadIndex));
     if (!util.isSameEntry(this.renameInput_.currentEntry, leadEntry))
       return;
 
@@ -2715,16 +2721,16 @@
     if (!this.currentVolumeInfo_)
       return;
 
-    var volumeSpaceInfo =
-        this.dialogDom_.querySelector('#volume-space-info');
-    var volumeSpaceInfoSeparator =
-        this.dialogDom_.querySelector('#volume-space-info-separator');
-    var volumeSpaceInfoLabel =
-        this.dialogDom_.querySelector('#volume-space-info-label');
-    var volumeSpaceInnerBar =
-        this.dialogDom_.querySelector('#volume-space-info-bar');
-    var volumeSpaceOuterBar =
-        this.dialogDom_.querySelector('#volume-space-info-bar').parentNode;
+    var volumeSpaceInfo = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#volume-space-info'));
+    var volumeSpaceInfoSeparator = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#volume-space-info-separator'));
+    var volumeSpaceInfoLabel = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#volume-space-info-label'));
+    var volumeSpaceInnerBar = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#volume-space-info-bar'));
+    var volumeSpaceOuterBar = /** @type {!HTMLElement} */
+        (this.dialogDom_.querySelector('#volume-space-info-bar').parentNode);
 
     var currentVolumeInfo = this.currentVolumeInfo_;
 
@@ -2903,7 +2909,7 @@
   };
 
   /**
-   * @type {Event} Key event.
+   * @param {Event} event Key event.
    * @private
    */
   FileManager.prototype.onRenameInputKeyDown_ = function(event) {
@@ -2929,7 +2935,7 @@
   };
 
   /**
-   * @type {Event} Blur event.
+   * @param {Event} event Blur event.
    * @private
    */
   FileManager.prototype.onRenameInputBlur_ = function(event) {
@@ -3512,10 +3518,9 @@
    * Handle a click of the cancel button.  Closes the window.
    * TODO(jamescook): Make unload handler work automatically, crbug.com/104811
    *
-   * @param {Event} event The click event.
    * @private
    */
-  FileManager.prototype.onCancel_ = function(event) {
+  FileManager.prototype.onCancel_ = function() {
     chrome.fileManagerPrivate.cancelDialog();
     window.close();
   };
@@ -3648,10 +3653,9 @@
    * The ok button has different UI labels depending on the type of dialog, but
    * in code it's always referred to as 'ok'.
    *
-   * @param {Event} event The click event.
    * @private
    */
-  FileManager.prototype.onOk_ = function(event) {
+  FileManager.prototype.onOk_ = function() {
     if (this.dialogType == DialogType.SELECT_SAVEAS_FILE) {
       // Save-as doesn't require a valid selection from the list, since
       // we're going to take the filename from the text input.
@@ -3884,7 +3888,8 @@
 
     this.openWithCommand_.canExecuteChange();
     this.openWithCommand_.setHidden(!(defaultItem && isMultiple));
-    this.openWithCommand_.disabled = defaultItem && !!defaultItem.disabled;
+    this.openWithCommand_.disabled =
+        defaultItem ? !!defaultItem.disabled : false;
 
     this.defaultActionMenuItem_.hidden = !defaultItem;
     defaultActionSeparator.hidden = !defaultItem;
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
index 8cfcb24..a1ee73c 100644
--- a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
+++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
@@ -41,8 +41,7 @@
 /**
  * Extracts entry on which command event was dispatched.
  *
- * @param {DirectoryTree|DirectoryItem|HTMLLIElement|cr.ui.List}
- *     element Directory to extract a path from.
+ * @param {EventTarget} element Element which is the command event's target.
  * @return {Entry} Entry of the found node.
  */
 CommandUtil.getCommandEntry = function(element) {
@@ -183,7 +182,7 @@
  * Default command.
  * @type {Command}
  */
-CommandUtil.defaultCommand = {
+CommandUtil.defaultCommand = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.document.execCommand(event.command.id);
   },
@@ -191,7 +190,7 @@
     event.canExecute = fileManager.document.queryCommandEnabled(
         event.command.id);
   }
-};
+});
 
 /**
  * Creates the volume switch command with index.
@@ -199,7 +198,7 @@
  * @return {Command} Volume switch command.
  */
 CommandUtil.createVolumeSwitchCommand = function(index) {
-  return {
+  return /** @type {Command} */ ({
     execute: function(event, fileManager) {
       fileManager.directoryTree.selectByIndex(index - 1);
     },
@@ -207,7 +206,7 @@
       event.canExecute = index > 0 &&
           index <= fileManager.directoryTree.items.length;
     }
-  };
+  });
 };
 
 /**
@@ -294,7 +293,7 @@
   if (this.shouldIgnoreEvents_())
     return;
   var handler = CommandHandler.COMMANDS_[event.command.id];
-  handler.execute.call(this, event, this.fileManager_);
+  handler.execute.call(/** @type {Command} */ (this), event, this.fileManager_);
 };
 
 /**
@@ -306,7 +305,8 @@
   if (this.shouldIgnoreEvents_())
     return;
   var handler = CommandHandler.COMMANDS_[event.command.id];
-  handler.canExecute.call(this, event, this.fileManager_);
+  handler.canExecute.call(/** @type {Command} */ (this), event,
+                          this.fileManager_);
 };
 
 /**
@@ -321,7 +321,7 @@
  * Unmounts external drive.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['unmount'] = {
+CommandHandler.COMMANDS_['unmount'] = /** @type {Command} */ ({
   /**
    * @param {Event} event Command event.
    * @param {FileManager} fileManager The file manager instance.
@@ -348,6 +348,7 @@
   },
   /**
    * @param {Event} event Command event.
+   * @this {CommandHandler}
    */
   canExecute: function(event, fileManager) {
     var root = CommandUtil.getCommandEntry(event.target);
@@ -372,13 +373,13 @@
         break;
     }
   }
-};
+});
 
 /**
  * Formats external drive.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['format'] = {
+CommandHandler.COMMANDS_['format'] = /** @type {Command} */ ({
   /**
    * @param {Event} event Command event.
    * @param {FileManager} fileManager The file manager instance.
@@ -419,13 +420,13 @@
     event.canExecute = removable && !isReadOnly;
     event.command.setHidden(!removable);
   }
-};
+});
 
 /**
  * Initiates new folder creation.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['new-folder'] = {
+CommandHandler.COMMANDS_['new-folder'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.createNewFolder();
   },
@@ -436,13 +437,13 @@
                        !directoryModel.isSearching() &&
                        !directoryModel.isScanning();
   }
-};
+});
 
 /**
  * Initiates new window creation.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['new-window'] = {
+CommandHandler.COMMANDS_['new-window'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.getProfiles(
         function(profiles, currentId, displayedId) {
@@ -458,13 +459,13 @@
         fileManager.getCurrentDirectoryEntry() &&
         (fileManager.dialogType === DialogType.FULL_PAGE);
   }
-};
+});
 
 /**
  * Toggles drive sync settings.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['drive-sync-settings'] = {
+CommandHandler.COMMANDS_['drive-sync-settings'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.toggleDriveSyncSettings();
   },
@@ -472,13 +473,13 @@
     event.canExecute = fileManager.shouldShowDriveSettings();
     event.command.setHidden(!event.canExecute);
   }
-};
+});
 
 /**
  * Toggles drive hosted settings.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['drive-hosted-settings'] = {
+CommandHandler.COMMANDS_['drive-hosted-settings'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.toggleDriveHostedSettings();
   },
@@ -486,13 +487,13 @@
     event.canExecute = fileManager.shouldShowDriveSettings();
     event.command.setHidden(!event.canExecute);
   }
-};
+});
 
 /**
  * Deletes selected files.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['delete'] = {
+CommandHandler.COMMANDS_['delete'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     var entries = fileManager.getSelection().entries;
     var message = entries.length == 1 ?
@@ -508,13 +509,13 @@
                        selection &&
                        selection.totalCount > 0;
   }
-};
+});
 
 /**
  * Pastes files from clipboard.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['paste'] = {
+CommandHandler.COMMANDS_['paste'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.document.execCommand(event.command.id);
   },
@@ -526,13 +527,13 @@
     event.command.setHidden(!!CommandUtil.getOnlyOneSelectedDirectory(
         fileManager.getSelection()));
   }
-};
+});
 
 /**
  * Pastes files from clipboard into the selected folder.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['paste-into-folder'] = {
+CommandHandler.COMMANDS_['paste-into-folder'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     var selection = fileManager.getSelection();
     var dest = CommandUtil.getOnlyOneSelectedDirectory(selection);
@@ -556,7 +557,7 @@
     event.command.setHidden(!CommandUtil.getOnlyOneSelectedDirectory(
         fileManager.getSelection()));
   }
-};
+});
 
 CommandHandler.COMMANDS_['cut'] = CommandUtil.defaultCommand;
 CommandHandler.COMMANDS_['copy'] = CommandUtil.defaultCommand;
@@ -565,7 +566,7 @@
  * Initiates file renaming.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['rename'] = {
+CommandHandler.COMMANDS_['rename'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.initiateRename();
   },
@@ -576,13 +577,13 @@
                        selection &&
                        selection.totalCount == 1;
   }
-};
+});
 
 /**
  * Opens drive help.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['volume-help'] = {
+CommandHandler.COMMANDS_['volume-help'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     if (fileManager.isOnDrive())
       util.visitURL(str('GOOGLE_DRIVE_HELP_URL'));
@@ -599,35 +600,35 @@
     event.command.setHidden(hideHelp);
     fileManager.document_.getElementById('help-separator').hidden = hideHelp;
   }
-};
+});
 
 /**
  * Opens drive buy-more-space url.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['drive-buy-more-space'] = {
+CommandHandler.COMMANDS_['drive-buy-more-space'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     util.visitURL(str('GOOGLE_DRIVE_BUY_STORAGE_URL'));
   },
   canExecute: CommandUtil.canExecuteVisibleOnDriveInNormalAppModeOnly
-};
+});
 
 /**
  * Opens drive.google.com.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['drive-go-to-drive'] = {
+CommandHandler.COMMANDS_['drive-go-to-drive'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     util.visitURL(str('GOOGLE_DRIVE_ROOT_URL'));
   },
   canExecute: CommandUtil.canExecuteVisibleOnDriveInNormalAppModeOnly
-};
+});
 
 /**
  * Displays open with dialog for current selection.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['open-with'] = {
+CommandHandler.COMMANDS_['open-with'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     var tasks = fileManager.getSelection().tasks;
     if (tasks) {
@@ -643,13 +644,13 @@
     var tasks = fileManager.getSelection().tasks;
     event.canExecute = tasks && tasks.size() > 1;
   }
-};
+});
 
 /**
  * Focuses search input box.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['search'] = {
+CommandHandler.COMMANDS_['search'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     var element = fileManager.document.querySelector('#search-box input');
     element.focus();
@@ -658,7 +659,7 @@
   canExecute: function(event, fileManager) {
     event.canExecute = !fileManager.isRenamingInProgress();
   }
-};
+});
 
 /**
  * Activates the n-th volume.
@@ -687,7 +688,7 @@
  * Flips 'available offline' flag on the file.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['toggle-pinned'] = {
+CommandHandler.COMMANDS_['toggle-pinned'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     var pin = !event.command.checked;
     event.command.checked = pin;
@@ -753,13 +754,13 @@
       event.command.setHidden(true);
     }
   }
-};
+});
 
 /**
  * Creates zip file for current selection.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['zip-selection'] = {
+CommandHandler.COMMANDS_['zip-selection'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     var dirEntry = fileManager.getCurrentDirectoryEntry();
     var selectionEntries = fileManager.getSelection().entries;
@@ -774,13 +775,13 @@
         !fileManager.isOnDrive() &&
         selection && selection.totalCount > 0;
   }
-};
+});
 
 /**
  * Shows the share dialog for the current selection (single only).
  * @type {Command}
  */
-CommandHandler.COMMANDS_['share'] = {
+CommandHandler.COMMANDS_['share'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     fileManager.shareSelection();
   },
@@ -794,13 +795,13 @@
         selection && selection.totalCount == 1;
     event.command.setHidden(!fileManager.isOnDrive());
   }
-};
+});
 
 /**
  * Creates a shortcut of the selected folder (single only).
  * @type {Command}
  */
-CommandHandler.COMMANDS_['create-folder-shortcut'] = {
+CommandHandler.COMMANDS_['create-folder-shortcut'] = /** @type {Command} */ ({
   /**
    * @param {Event} event Command event.
    * @param {FileManager} fileManager The file manager instance.
@@ -838,13 +839,13 @@
         eligible && onlyOneFolderSelected && !folderShortcutExists;
     event.command.setHidden(!eligible || !onlyOneFolderSelected);
   }
-};
+});
 
 /**
  * Removes the folder shortcut.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['remove-folder-shortcut'] = {
+CommandHandler.COMMANDS_['remove-folder-shortcut'] = /** @type {Command} */ ({
   /**
    * @param {Event} event Command event.
    * @param {FileManager} fileManager The file manager instance.
@@ -872,81 +873,81 @@
     event.canExecute = isShortcut && eligible;
     event.command.setHidden(!event.canExecute);
   }
-};
+});
 
 /**
  * Zoom in to the Files.app.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['zoom-in'] = {
+CommandHandler.COMMANDS_['zoom-in'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.zoom('in');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
 
 /**
  * Zoom out from the Files.app.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['zoom-out'] = {
+CommandHandler.COMMANDS_['zoom-out'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.zoom('out');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
 
 /**
  * Reset the zoom factor.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['zoom-reset'] = {
+CommandHandler.COMMANDS_['zoom-reset'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.zoom('reset');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
 
 /**
  * Open inspector for foreground page.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['inspect-normal'] = {
+CommandHandler.COMMANDS_['inspect-normal'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.openInspector('normal');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
 
 /**
  * Open inspector for foreground page and bring focus to the console.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['inspect-console'] = {
+CommandHandler.COMMANDS_['inspect-console'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.openInspector('console');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
 
 /**
  * Open inspector for foreground page in inspect element mode.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['inspect-element'] = {
+CommandHandler.COMMANDS_['inspect-element'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.openInspector('element');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
 
 /**
  * Open inspector for background page.
  * @type {Command}
  */
-CommandHandler.COMMANDS_['inspect-background'] = {
+CommandHandler.COMMANDS_['inspect-background'] = /** @type {Command} */ ({
   execute: function(event, fileManager) {
     chrome.fileManagerPrivate.openInspector('background');
   },
   canExecute: CommandUtil.canExecuteAlways
-};
+});
diff --git a/ui/file_manager/file_manager/foreground/js/file_selection.js b/ui/file_manager/file_manager/foreground/js/file_selection.js
index c236acd..ef3ff25 100644
--- a/ui/file_manager/file_manager/foreground/js/file_selection.js
+++ b/ui/file_manager/file_manager/foreground/js/file_selection.js
@@ -29,7 +29,8 @@
 
   // Synchronously compute what we can.
   for (var i = 0; i < this.indexes.length; i++) {
-    var entry = fileManager.getFileList().item(this.indexes[i]);
+    var entry = /** @type {!Entry} */
+        (fileManager.getFileList().item(this.indexes[i]));
     if (!entry)
       continue;
 
@@ -211,10 +212,8 @@
 
 /**
  * Update the UI when the selection model changes.
- *
- * @param {Event} event The change event.
  */
-FileSelectionHandler.prototype.onFileSelectionChanged = function(event) {
+FileSelectionHandler.prototype.onFileSelectionChanged = function() {
   var indexes =
       this.fileManager_.getCurrentList().selectionModel.selectedIndexes;
   if (this.selection) this.selection.cancelComputing_();
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks.js b/ui/file_manager/file_manager/foreground/js/file_tasks.js
index 2c578cc..3f7c5da 100644
--- a/ui/file_manager/file_manager/foreground/js/file_tasks.js
+++ b/ui/file_manager/file_manager/foreground/js/file_tasks.js
@@ -58,8 +58,8 @@
  * Returns URL of the Chrome Web Store which show apps supporting the given
  * file-extension and mime-type.
  *
- * @param {string} extension Extension of the file (with the first dot).
- * @param {string} mimeType Mime type of the file.
+ * @param {?string} extension Extension of the file (with the first dot).
+ * @param {?string} mimeType Mime type of the file.
  * @return {string} URL
  */
 FileTasks.createWebStoreLink = function(extension, mimeType) {
@@ -290,7 +290,7 @@
 /**
  * Executes default task.
  *
- * @param {function(boolean, Array.<string>)=} opt_callback Called when the
+ * @param {function(boolean, Array.<Entry>)=} opt_callback Called when the
  *     default task is executed, or the error is occurred.
  * @private
  */
diff --git a/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js b/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js
index e3b4c2f..ce3df96 100644
--- a/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js
+++ b/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js
@@ -23,6 +23,7 @@
  *     used to share files from another profile.
  * @param {ProgressCenter} progressCenter To notify starting copy operation.
  * @constructor
+ * @extends {cr.EventTarget}
  */
 function FileTransferController(doc,
                                 fileOperationManager,
@@ -470,7 +471,7 @@
    * Renders a drag-and-drop thumbnail.
    *
    * @this {FileTransferController}
-   * @return {HTMLElement} Element containing the thumbnail.
+   * @return {Element} Element containing the thumbnail.
    */
   renderThumbnail_: function() {
     var length = this.selectedEntries_.length;
@@ -600,7 +601,7 @@
    * @this {FileTransferController}
    * @param {boolean} onlyIntoDirectories True if the drag is only into
    *     directories.
-   * @param {cr.ui.List} list Drop target list.
+   * @param {(cr.ui.List|DirectoryTree)} list Drop target list.
    * @param {Event} event A dragover event of DOM.
    */
   onDragOver_: function(onlyIntoDirectories, list, event) {
@@ -613,13 +614,14 @@
 
   /**
    * @this {FileTransferController}
-   * @param {cr.ui.List} list Drop target list.
+   * @param {(cr.ui.List|DirectoryTree)} list Drop target list.
    * @param {Event} event A dragenter event of DOM.
    */
   onDragEnterFileList_: function(list, event) {
     event.preventDefault();  // Required to prevent the cursor flicker.
     this.lastEnteredTarget_ = event.target;
-    var item = list.getListItemAncestor(event.target);
+    var item = list.getListItemAncestor(
+        /** @type {HTMLElement} */ (event.target));
     item = item && list.isItem(item) ? item : null;
     if (item === this.dropTarget_)
       return;
@@ -657,7 +659,7 @@
 
   /**
    * @this {FileTransferController}
-   * @param {cr.ui.List} list Drop target list.
+   * @param {*} list Drop target list.
    * @param {Event} event A dragleave event of DOM.
    */
   onDragLeave_: function(list, event) {
@@ -722,9 +724,10 @@
 
     // Start timer changing the directory.
     this.navigateTimer_ = setTimeout(function() {
-      if (domElement instanceof DirectoryItem)
+      if (domElement instanceof DirectoryItem) {
         // Do custom action.
-        (/** @type {DirectoryItem} */ domElement).doDropTargetAction();
+        /** @type {DirectoryItem} */ (domElement).doDropTargetAction();
+      }
       this.directoryModel_.changeDirectoryEntry(destinationEntry);
     }.bind(this), 2000);
   },
diff --git a/ui/file_manager/file_manager/foreground/js/file_watcher.js b/ui/file_manager/file_manager/foreground/js/file_watcher.js
index 9db0971..dc59e70 100644
--- a/ui/file_manager/file_manager/foreground/js/file_watcher.js
+++ b/ui/file_manager/file_manager/foreground/js/file_watcher.js
@@ -143,7 +143,7 @@
 FileWatcher.prototype.changeWatchedDirectory = function(entry, callback) {
   if (!util.isFakeEntry(entry)) {
     this.changeWatchedEntry_(
-        entry,
+        /** @type {!DirectoryEntry} */ (entry),
         callback,
         function() {
           console.error(
diff --git a/ui/file_manager/file_manager/foreground/js/folder_shortcuts_data_model.js b/ui/file_manager/file_manager/foreground/js/folder_shortcuts_data_model.js
index ca21d09..415cf93 100644
--- a/ui/file_manager/file_manager/foreground/js/folder_shortcuts_data_model.js
+++ b/ui/file_manager/file_manager/foreground/js/folder_shortcuts_data_model.js
@@ -271,7 +271,7 @@
    *
    * @param {Entry} a First entry.
    * @param {Entry} b Second entry.
-   * @return {boolean} Returns -1, if |a| < |b|. Returns 0, if |a| === |b|.
+   * @return {number} Returns -1, if |a| < |b|. Returns 0, if |a| === |b|.
    *     Otherwise, returns 1.
    */
   compare: function(a, b) {
@@ -493,7 +493,7 @@
    * for detail.
    *
    * @param {string} path Path in Drive with the stored drive mount path.
-   * @return {string} URL of the given path.
+   * @return {?string} URL of the given path.
    * @private
    */
   convertStoredPathToUrl_: function(path) {
@@ -511,7 +511,7 @@
    * See the comment of convertStoredPathToUrl_() for further information.
    *
    * @param {string} url URL of the directory in Drive.
-   * @return {string} Path with the stored drive mount path.
+   * @return {?string} Path with the stored drive mount path.
    * @private
    */
   convertUrlToStoredPath_: function(url) {
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/metadata_cache.js b/ui/file_manager/file_manager/foreground/js/metadata/metadata_cache.js
index 0d1b468..8de5921 100644
--- a/ui/file_manager/file_manager/foreground/js/metadata/metadata_cache.js
+++ b/ui/file_manager/file_manager/foreground/js/metadata/metadata_cache.js
@@ -710,6 +710,7 @@
  * This provider returns the following objects:
  * filesystem: { size, modificationTime }
  * @constructor
+ * @extends {MetadataProvider}
  */
 function FilesystemProvider() {
   MetadataProvider.call(this);
@@ -772,6 +773,7 @@
  *     thumbnail: { url, transform }
  * @param {VolumeManagerWrapper} volumeManager Volume manager instance.
  * @constructor
+ * @extends {MetadataProvider}
  */
 function ExternalProvider(volumeManager) {
   MetadataProvider.call(this);
@@ -800,8 +802,10 @@
  */
 ExternalProvider.prototype.supportsEntry = function(entry) {
   var locationInfo = this.volumeManager_.getLocationInfo(entry);
-  return locationInfo && (locationInfo.isDriveBased ||
-      locationInfo.rootType === VolumeManagerCommon.RootType.PROVIDED);
+  if (!locationInfo)
+    return false;
+  return locationInfo.isDriveBased ||
+      locationInfo.rootType === VolumeManagerCommon.RootType.PROVIDED;
 };
 
 /**
@@ -918,6 +922,7 @@
  * media: { artist, album, title, width, height, imageTransform, etc. }
  * fetchedMedia: { same fields here }
  * @constructor
+ * @extends {MetadataProvider}
  */
 function ContentProvider() {
   MetadataProvider.call(this);
@@ -958,7 +963,7 @@
  * @return {boolean} Whether this provider supports the entry.
  */
 ContentProvider.prototype.supportsEntry = function(entry) {
-  return entry.toURL().match(this.urlFilter_);
+  return !!entry.toURL().match(this.urlFilter_);
 };
 
 /**
diff --git a/ui/file_manager/file_manager/foreground/js/metrics.js b/ui/file_manager/file_manager/foreground/js/metrics.js
index 7760483..a59491d 100644
--- a/ui/file_manager/file_manager/foreground/js/metrics.js
+++ b/ui/file_manager/file_manager/foreground/js/metrics.js
@@ -94,8 +94,8 @@
  * Record an enum value.
  *
  * @param {string} name Metric name.
- * @param {Object} value Enum value.
- * @param {Array.<Object>|number} validValues Array of valid values
+ * @param {*} value Enum value.
+ * @param {Array.<*>|number} validValues Array of valid values
  *                                            or a boundary number value.
  */
 metrics.recordEnum = function(name, value, validValues) {
@@ -105,7 +105,7 @@
     index = validValues.indexOf(value);
     boundaryValue = validValues.length;
   } else {
-    index = value;
+    index = /** @type {number} */ (value);
     boundaryValue = validValues;
   }
   // Collect invalid values in the overflow bucket at the end.
diff --git a/ui/file_manager/file_manager/foreground/js/navigation_list_model.js b/ui/file_manager/file_manager/foreground/js/navigation_list_model.js
index 33c6880..62b031d 100644
--- a/ui/file_manager/file_manager/foreground/js/navigation_list_model.js
+++ b/ui/file_manager/file_manager/foreground/js/navigation_list_model.js
@@ -82,7 +82,8 @@
 /**
  * A navigation list model. This model combines the 2 lists.
  * @param {VolumeManagerWrapper} volumeManager VolumeManagerWrapper instance.
- * @param {cr.ui.ArrayDataModel} shortcutListModel The list of folder shortcut.
+ * @param {(cr.ui.ArrayDataModel|FolderShortcutsDataModel)} shortcutListModel
+ *     The list of folder shortcut.
  * @constructor
  * @extends {cr.EventTarget}
  */
@@ -122,7 +123,7 @@
 
   this.shortcutList_ = [];
   for (var i = 0; i < this.shortcutListModel_.length; i++) {
-    var shortcutEntry = this.shortcutListModel_.item(i);
+    var shortcutEntry = /** @type {Entry} */ (this.shortcutListModel_.item(i));
     var volumeInfo = this.volumeManager_.getVolumeInfo(shortcutEntry);
     this.shortcutList_.push(entryToModelItem(shortcutEntry));
   }
diff --git a/ui/file_manager/file_manager/foreground/js/progress_center_item_group.js b/ui/file_manager/file_manager/foreground/js/progress_center_item_group.js
index 21119cb..d556a81 100644
--- a/ui/file_manager/file_manager/foreground/js/progress_center_item_group.js
+++ b/ui/file_manager/file_manager/foreground/js/progress_center_item_group.js
@@ -106,10 +106,10 @@
  * contains is used as a summarized item. But If all the group returns null, the
  * progress center panel generates the summarized item by using the method.
  *
- * @param {Array.<ProgressCenterItemGroup>} var_groups List of groups.
+ * @param {...ProgressCenterItemGroup} var_args List of groups.
  * @return {ProgressCenterItem} Summarized item.
  */
-ProgressCenterItemGroup.getSummarizedErrorItem = function(var_groups) {
+ProgressCenterItemGroup.getSummarizedErrorItem = function(var_args) {
   var groups = Array.prototype.slice.call(arguments);
   var errorItems = [];
   for (var i = 0; i < groups.length; i++) {
diff --git a/ui/file_manager/file_manager/foreground/js/search_controller.js b/ui/file_manager/file_manager/foreground/js/search_controller.js
index faa8172..23c9bd2 100644
--- a/ui/file_manager/file_manager/foreground/js/search_controller.js
+++ b/ui/file_manager/file_manager/foreground/js/search_controller.js
@@ -6,7 +6,7 @@
 
 /**
  * Controller for searching.
- * @param {SearchBox} ui Search box UI element.
+ * @param {SearchBox} searchBox Search box UI element.
  * @param {LocationLine} locationLine Location line UI element.
  * @param {DirectoryModel} directoryModel Directory model.
  * @param {{doAction: function(FileEntry)}} taskController Task controller to
@@ -22,7 +22,7 @@
   this.searchBox_ = searchBox;
 
   /**
-   * @type {FileManagerUI}
+   * @type {LocationLine}
    * @private
    */
   this.locationLine_ = locationLine;
@@ -54,7 +54,7 @@
 SearchController.prototype = {
   /**
    * Obtains current directory's locaiton info.
-   * @type {LocationInfo}
+   * @type {EntryLocation}
    * @private
    */
   get currentLocationInfo_() {
diff --git a/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js b/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js
index 28a15bd..0102947 100644
--- a/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js
+++ b/ui/file_manager/file_manager/foreground/js/thumbnail_loader.js
@@ -9,7 +9,7 @@
  * are attached as <canvas> element, while in IMAGE mode as <img>.
  * <canvas> renders faster than <img>, however has bigger memory overhead.
  *
- * @param {FileEntry} entry File entry.
+ * @param {Entry} entry File entry.
  * @param {ThumbnailLoader.LoaderType=} opt_loaderType Canvas or Image loader,
  *     default: IMAGE.
  * @param {Object=} opt_metadata Metadata object.
@@ -136,7 +136,7 @@
 /**
  * Loads and attaches an image.
  *
- * @param {HTMLElement} box Container element.
+ * @param {Element} box Container element.
  * @param {ThumbnailLoader.FillMode} fillMode Fill mode.
  * @param {ThumbnailLoader.OptimizationMode=} opt_optimizationMode Optimization
  *     for downloading thumbnails. By default optimizations are disabled.
@@ -349,7 +349,7 @@
  * to wait until the image loads and its dimensions are known, then manually
  * position it at the center.
  *
- * @param {HTMLElement} box Containing element.
+ * @param {Element} box Containing element.
  * @param {Image|HTMLCanvasElement} img Element containing an image.
  * @param {ThumbnailLoader.FillMode} fillMode Fill mode.
  * @param {boolean} rotate True if the image should be rotated 90 degrees.
diff --git a/ui/file_manager/file_manager/foreground/js/ui/combobutton.js b/ui/file_manager/file_manager/foreground/js/ui/combobutton.js
index 59ae9f2..85f962d 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/combobutton.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/combobutton.js
@@ -13,7 +13,7 @@
    * Creates a new combobutton element.
    * @param {Object=} opt_propertyBag Optional properties.
    * @constructor
-   * @extends {HTMLUListElement}
+   * @extends {cr.ui.MenuButton}
    */
   var ComboButton = cr.ui.define(cr.ui.MenuButton);
 
@@ -116,7 +116,7 @@
         case 'Down':
         case 'Up':
           if (!this.isMenuShown())
-            this.showMenu();
+            this.showMenu(false);
           e.preventDefault();
           break;
         case 'Esc':
diff --git a/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js b/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js
index 6e5606e..88543c1 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/commandbutton.js
@@ -12,7 +12,7 @@
  * Creates a new button element.
  * @param {Object=} opt_propertyBag Optional properties.
  * @constructor
- * @extends {HTMLDivElement}
+ * @extends {HTMLButtonElement}
  */
 var CommandButton = cr.ui.define('button');
 
@@ -21,7 +21,7 @@
 
 /**
  * Associated command.
- * @type {Command}
+ * @type {cr.ui.Command}
  * @private
  */
 CommandButton.prototype.command_ = null;
@@ -52,13 +52,17 @@
  */
 CommandButton.prototype.setCommand = function(command) {
   if (this.command_) {
-    this.command_.removeEventListener('labelChange', this);
-    this.command_.removeEventListener('disabledChange', this);
-    this.command_.removeEventListener('hiddenChange', this);
+    this.command_.removeEventListener('labelChange',
+                                      /** @type {EventListener} */ (this));
+    this.command_.removeEventListener('disabledChange',
+                                      /** @type {EventListener} */ (this));
+    this.command_.removeEventListener('hiddenChange',
+                                      /** @type {EventListener} */ (this));
   }
 
   if (typeof command == 'string' && command[0] == '#') {
-    command = this.ownerDocument.getElementById(command.slice(1));
+    command = /** @type {!cr.ui.Command} */
+        (this.ownerDocument.getElementById(command.slice(1)));
     cr.ui.decorate(command, cr.ui.Command);
   }
 
@@ -71,9 +75,12 @@
     this.disabled = command.disabled;
     this.hidden = command.hidden;
 
-    this.command_.addEventListener('labelChange', this);
-    this.command_.addEventListener('disabledChange', this);
-    this.command_.addEventListener('hiddenChange', this);
+    this.command_.addEventListener('labelChange',
+                                   /** @type {EventListener} */ (this));
+    this.command_.addEventListener('disabledChange',
+                                   /** @type {EventListener} */ (this));
+    this.command_.addEventListener('hiddenChange',
+                                   /** @type {EventListener} */ (this));
   }
 };
 
diff --git a/ui/file_manager/file_manager/foreground/js/ui/conflict_dialog.js b/ui/file_manager/file_manager/foreground/js/ui/conflict_dialog.js
index 9089394..3c80530 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/conflict_dialog.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/conflict_dialog.js
@@ -19,14 +19,14 @@
    * argument is which button is pressed. The second argument is whether to
    * apply all or not.
    *
-   * @type {function(ConflictDialog.Result, boolean)}
+   * @type {?function(ConflictDialog.Result, boolean)}
    * @private
    */
   this.callback_ = null;
 
   /**
    * Checkbox to specify whether to apply the selection to all entries or not.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.applyAllCheckbox_ = parentNode.ownerDocument.createElement('input');
@@ -40,7 +40,7 @@
 
   /**
    * Element of the keep both button.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.keepBothButton_ = parentNode.ownerDocument.createElement('button');
@@ -51,7 +51,7 @@
 
   /**
    * Element of the replace button.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.replaceButton_ = parentNode.ownerDocument.createElement('button');
diff --git a/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js b/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js
index 2870794..1f01e9e 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js
@@ -22,6 +22,7 @@
  * @param {boolean} recursive True if the all visible sub-directories are
  *     updated recursively including left arrows. If false, the update walks
  *     only immediate child directories without arrows.
+ * @this {DirectoryItem}
  */
 DirectoryItemTreeBaseMethods.updateSubElementsFromList = function(recursive) {
   var index = 0;
@@ -70,6 +71,7 @@
  * @param {DirectoryEntry|Object} entry The entry to be searched for. Can be
  *     a fake.
  * @return {boolean} True if the parent item is found.
+ * @this {(DirectoryItem|VolumeItem|DirectoryTree)}
  */
 DirectoryItemTreeBaseMethods.searchAndSelectByEntry = function(entry) {
   for (var i = 0; i < this.items.length; i++) {
@@ -101,7 +103,8 @@
  *
  * @param {string} label Label for this item.
  * @param {DirectoryEntry} dirEntry DirectoryEntry of this item.
- * @param {DirectoryItem|DirectoryTree} parentDirItem Parent of this item.
+ * @param {DirectoryItem|VolumeItem|ShortcutItem|DirectoryTree} parentDirItem
+ *     Parent of this item.
  * @param {DirectoryTree} tree Current tree, which contains this item.
  * @extends {cr.ui.TreeItem}
  * @constructor
@@ -116,13 +119,14 @@
  * @param {HTMLElement} el Element to be DirectoryItem.
  * @param {string} label Label for this item.
  * @param {DirectoryEntry} dirEntry DirectoryEntry of this item.
- * @param {DirectoryItem|DirectoryTree} parentDirItem Parent of this item.
+ * @param {DirectoryItem|VolumeItem|ShortcutItem|DirectoryTree} parentDirItem
+ *     Parent of this item.
  * @param {DirectoryTree} tree Current tree, which contains this item.
  */
 DirectoryItem.decorate =
     function(el, label, dirEntry, parentDirItem, tree) {
   el.__proto__ = DirectoryItem.prototype;
-  (/** @type {DirectoryItem} */ el).decorate(
+  /** @type {DirectoryItem} */ (el).decorate(
       label, dirEntry, parentDirItem, tree);
 };
 
@@ -173,7 +177,8 @@
 /**
  * @param {string} label Localized label for this item.
  * @param {DirectoryEntry} dirEntry DirectoryEntry of this item.
- * @param {DirectoryItem|DirectoryTree} parentDirItem Parent of this item.
+ * @param {DirectoryItem|VolumeItem|ShortcutItem|DirectoryTree} parentDirItem
+ *     Parent of this item.
  * @param {DirectoryTree} tree Current tree, which contains this item.
  */
 DirectoryItem.prototype.decorate = function(
@@ -238,7 +243,7 @@
 
 /**
  * Invoked when the item is being expanded.
- * @param {!UIEvent} e Event.
+ * @param {!Event} e Event.
  * @private
  **/
 DirectoryItem.prototype.onExpand_ = function(e) {
@@ -384,7 +389,7 @@
 
 /**
  * Sets the context menu for directory tree.
- * @param {cr.ui.Menu} menu Menu to be set.
+ * @param {!cr.ui.Menu} menu Menu to be set.
  */
 DirectoryItem.prototype.setContextMenu = function(menu) {
   var tree = this.parentTree_ || this;  // If no parent, 'this' itself is tree.
@@ -562,7 +567,7 @@
 
 /**
  * Sets the context menu for volume items.
- * @param {cr.ui.Menu} menu Menu to be set.
+ * @param {!cr.ui.Menu} menu Menu to be set.
  */
 VolumeItem.prototype.setContextMenu = function(menu) {
   if (this.isRemovable_())
@@ -613,7 +618,7 @@
 
 /**
  * Set up icon of this volume item.
- * @param {HTMLElement} icon Icon element to be setup.
+ * @param {Element} icon Icon element to be setup.
  * @param {VolumeInfo} volumeInfo VolumeInfo determines the icon type.
  * @private
  */
@@ -631,7 +636,7 @@
         'style', 'background-image: ' + backgroundImage);
   }
   icon.setAttribute('volume-type-icon', volumeInfo.volumeType);
-  icon.setAttribute('volume-subtype', volumeInfo.deviceType);
+  icon.setAttribute('volume-subtype', volumeInfo.deviceType || '');
 };
 
 /**
@@ -747,7 +752,7 @@
 
 /**
  * Sets the context menu for shortcut items.
- * @param {cr.ui.Menu} menu Menu to be set.
+ * @param {!cr.ui.Menu} menu Menu to be set.
  */
 ShortcutItem.prototype.setContextMenu = function(menu) {
   cr.ui.contextMenuHandler.setContextMenu(this, menu);
@@ -802,7 +807,7 @@
 DirectoryTree.decorate = function(
     el, directoryModel, volumeManager, metadataCache, fakeEntriesVisible) {
   el.__proto__ = DirectoryTree.prototype;
-  (/** @type {DirectoryTree} */ el).decorate(
+  /** @type {DirectoryTree} */ (el).decorate(
       directoryModel, volumeManager, metadataCache, fakeEntriesVisible);
 };
 
@@ -993,7 +998,7 @@
       this.privateOnDirectoryChangedBound_);
 
   this.scrollBar_ = new MainPanelScrollBar();
-  this.scrollBar_.initialize(this.parentNode, this);
+  this.scrollBar_.initialize(this.parentElement, this);
 
   /**
    * Flag to show fake entries in the tree.
@@ -1078,7 +1083,7 @@
 
 /**
  * Invoked when a directory is changed.
- * @param {!UIEvent} event Event.
+ * @param {!Event} event Event.
  * @private
  */
 DirectoryTree.prototype.onDirectoryContentChanged_ = function(event) {
@@ -1093,7 +1098,7 @@
 
 /**
  * Invoked when the current directory is changed.
- * @param {!UIEvent} event Event.
+ * @param {!Event} event Event.
  * @private
  */
 DirectoryTree.prototype.onCurrentDirectoryChanged_ = function(event) {
diff --git a/ui/file_manager/file_manager/foreground/js/ui/drag_selector.js b/ui/file_manager/file_manager/foreground/js/ui/drag_selector.js
index 986ccf9..ba145bf 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/drag_selector.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/drag_selector.js
@@ -19,7 +19,7 @@
 
   /**
    * Border element of drag handle.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.border_ = null;
@@ -142,9 +142,10 @@
 /**
  * Handles the mousemove event.
  * @private
- * @param {MouseEvent} event The mousemove event.
+ * @param {Event} event The mousemove event.
  */
 DragSelector.prototype.onMouseMove_ = function(event) {
+  event = /** @type {MouseEvent} */ (event);
   // Get the selection bounds.
   var pos = DragSelector.getScrolledPosition(this.target_, event);
   var borderBounds = {
@@ -183,7 +184,7 @@
   // Update the selection
   this.target_.selectionModel_.beginChange();
   for (var name in selectionFlag) {
-    var index = parseInt(name);
+    var index = parseInt(name, 10);
     var flag = selectionFlag[name];
     // The flag may be one of followings:
     // - IN_LAST_SELECTION | IN_CURRENT_SELECTION
@@ -224,9 +225,10 @@
 /**
  * Handle the mouseup event.
  * @private
- * @param {MouseEvent} event The mouseup event.
+ * @param {Event} event The mouseup event.
  */
 DragSelector.prototype.onMouseUp_ = function(event) {
+  event = /** @type {MouseEvent} */ (event);
   this.onMouseMove_(event);
   this.target_.removeChild(this.border_);
   this.target_.ownerDocument.removeEventListener(
diff --git a/ui/file_manager/file_manager/foreground/js/ui/drive_banners.js b/ui/file_manager/file_manager/foreground/js/ui/drive_banners.js
index ce3cc76..4776e40 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/drive_banners.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/drive_banners.js
@@ -10,9 +10,10 @@
  *  - AuthFailBanner
  * @param {DirectoryModel} directoryModel The model.
  * @param {VolumeManagerWrapper} volumeManager The manager.
- * @param {DOMDocument} document HTML document.
+ * @param {Document} document HTML document.
  * @param {boolean} showOffers True if we should show offer banners.
  * @constructor
+ * @extends {cr.EventTarget}
  */
 function FileListBannerController(
     directoryModel, volumeManager, document, showOffers) {
@@ -45,9 +46,9 @@
       [WELCOME_HEADER_COUNTER_KEY, WARNING_DISMISSED_KEY],
       function(values) {
         this.welcomeHeaderCounter_ =
-            parseInt(values[WELCOME_HEADER_COUNTER_KEY]) || 0;
+            parseInt(values[WELCOME_HEADER_COUNTER_KEY], 10) || 0;
         this.warningDismissedCounter_ =
-            parseInt(values[WARNING_DISMISSED_KEY]) || 0;
+            parseInt(values[WARNING_DISMISSED_KEY], 10) || 0;
       }.bind(this));
 
   this.authFailedBanner_ =
@@ -211,12 +212,12 @@
 /**
  * Show or hide the "Low Google Drive space" warning.
  * @param {boolean} show True if the box need to be shown.
- * @param {Object} sizeStats Size statistics. Should be defined when showing the
- *     warning.
+ * @param {Object=} opt_sizeStats Size statistics. Should be defined when
+ *     showing the warning.
  * @private
  */
 FileListBannerController.prototype.showLowDriveSpaceWarning_ =
-    function(show, sizeStats) {
+    function(show, opt_sizeStats) {
   var box = this.document_.querySelector('#volume-space-warning');
 
   // Avoid showing two banners.
@@ -228,9 +229,10 @@
     return;
 
   if (this.warningDismissedCounter_) {
-    if (this.warningDismissedCounter_ ==
-            sizeStats.totalSize && // Quota had not changed
-        sizeStats.remainingSize / sizeStats.totalSize < 0.15) {
+    if (opt_sizeStats &&
+        // Quota had not changed
+        this.warningDismissedCounter_ == opt_sizeStats.totalSize &&
+        opt_sizeStats.remainingSize / opt_sizeStats.totalSize < 0.15) {
       // Since the last dismissal decision the quota has not changed AND
       // the user did not free up significant space. Obey the dismissal.
       show = false;
@@ -241,7 +243,7 @@
   }
 
   box.textContent = '';
-  if (show) {
+  if (show && opt_sizeStats) {
     var icon = this.document_.createElement('div');
     icon.className = 'drive-icon';
     box.appendChild(icon);
@@ -249,7 +251,7 @@
     var text = this.document_.createElement('div');
     text.className = 'drive-text';
     text.textContent = strf('DRIVE_SPACE_AVAILABLE_LONG',
-        util.bytesToString(sizeStats.remainingSize));
+        util.bytesToString(opt_sizeStats.remainingSize));
     box.appendChild(text);
 
     var link = this.document_.createElement('a');
@@ -268,7 +270,7 @@
       chrome.storage.local.set(values);
       box.hidden = true;
       this.requestRelayout_(100);
-    }.bind(this, sizeStats.totalSize));
+    }.bind(this, opt_sizeStats.totalSize));
   }
 
   if (box.hidden != !show) {
@@ -399,9 +401,10 @@
   if (!entry || util.isFakeEntry(entry))
     return false;
   var locationInfo = this.volumeManager_.getLocationInfo(entry);
-  return locationInfo &&
-      locationInfo.rootType === VolumeManagerCommon.RootType.DRIVE &&
-      locationInfo.volumeInfo.profile.isCurrentProfile;
+  if (!locationInfo)
+    return false;
+  return locationInfo.rootType === VolumeManagerCommon.RootType.DRIVE &&
+         locationInfo.volumeInfo.profile.isCurrentProfile;
 };
 
 /**
@@ -464,10 +467,11 @@
  */
 FileListBannerController.prototype.isLowSpaceWarningTarget_ =
     function(volumeInfo) {
-  return volumeInfo &&
-      volumeInfo.profile.isCurrentProfile &&
-      (volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DOWNLOADS ||
-       volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DRIVE);
+  if (!volumeInfo)
+    return false;
+  return volumeInfo.profile.isCurrentProfile &&
+         (volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DOWNLOADS ||
+          volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DRIVE);
 };
 
 /**
@@ -600,6 +604,14 @@
   if (panel.firstElementChild)
     return;
 
+  /**
+   * Creates an element using given parameters.
+   * @param {!Element} parent Parent element of the new element.
+   * @param {string} tag Tag of the new element.
+   * @param {string} className Class name of the new element.
+   * @param {string=} opt_textContent Text content of the new element.
+   * @return {!Element} The newly created element.
+   */
   var create = function(parent, tag, className, opt_textContent) {
     var div = panel.ownerDocument.createElement(tag);
     div.className = className;
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_grid.js b/ui/file_manager/file_manager/foreground/js/ui/file_grid.js
index d007f5f..d1398d9 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/file_grid.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/file_grid.js
@@ -44,12 +44,12 @@
   self.volumeManager_ = volumeManager;
 
   self.scrollBar_ = new MainPanelScrollBar();
-  self.scrollBar_.initialize(self.parentNode, self);
+  self.scrollBar_.initialize(self.parentElement, self);
   self.setBottomMarginForPanel(0);
 
   self.itemConstructor = function(entry) {
     var item = self.ownerDocument.createElement('LI');
-    FileGrid.Item.decorate(item, entry, self);
+    FileGrid.Item.decorate(item, entry, /** @type {FileGrid} */ (self));
     return item;
   };
 
@@ -102,7 +102,7 @@
 
 /**
  * Decorates thumbnail.
- * @param {HTMLElement} li List item.
+ * @param {cr.ui.ListItem} li List item.
  * @param {Entry} entry Entry to render a thumbnail for.
  * @param {MetadataCache} metadataCache To retrieve metadata.
  * @param {VolumeManagerWrapper} volumeManager Volume manager instance.
@@ -136,14 +136,14 @@
 /**
  * Decorates the box containing a centered thumbnail image.
  *
- * @param {HTMLDivElement} box Box to decorate.
+ * @param {Element} box Box to decorate.
  * @param {Entry} entry Entry which thumbnail is generating for.
  * @param {MetadataCache} metadataCache To retrieve metadata.
  * @param {VolumeManagerWrapper} volumeManager Volume manager instance.
  * @param {ThumbnailLoader.FillMode} fillMode Fill mode.
  * @param {FileGrid.ThumbnailQuality} quality Thumbnail quality.
- * @param {function(HTMLElement)=} opt_imageLoadCallback Callback called when
- *     the image has been loaded before inserting it into the DOM.
+ * @param {function(HTMLImageElement)=} opt_imageLoadCallback Callback called
+ *     when the image has been loaded before inserting it into the DOM.
  */
 FileGrid.decorateThumbnailBox = function(
     box, entry, metadataCache, volumeManager, fillMode, quality,
@@ -199,6 +199,7 @@
 /**
  * Item for the Grid View.
  * @constructor
+ * @extends {cr.ui.ListItem}
  */
 FileGrid.Item = function() {
   throw new Error();
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_manager_dialog_base.js b/ui/file_manager/file_manager/foreground/js/ui/file_manager_dialog_base.js
index 94b40eb..5d56a74 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/file_manager_dialog_base.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/file_manager_dialog_base.js
@@ -46,8 +46,8 @@
 /**
  * @param {string} title Title.
  * @param {string} message Message.
- * @param {function()} onOk Called when the OK button is pressed.
- * @param {function()} onCancel Called when the cancel button is pressed.
+ * @param {?function()} onOk Called when the OK button is pressed.
+ * @param {?function()} onCancel Called when the cancel button is pressed.
  * @return {boolean} True if the dialog can show successfully. False if the
  *     dialog failed to show due to an existing dialog.
  */
@@ -59,8 +59,8 @@
 /**
  * @param {string} title Title.
  * @param {string} message Message.
- * @param {function()} onOk Called when the OK button is pressed.
- * @param {function()} onCancel Called when the cancel button is pressed.
+ * @param {?function()} onOk Called when the OK button is pressed.
+ * @param {?function()} onCancel Called when the cancel button is pressed.
  * @return {boolean} True if the dialog can show successfully. False if the
  *     dialog failed to show due to an existing dialog.
  * @private
@@ -84,7 +84,7 @@
  *     dialog failed to show due to an existing dialog.
  */
 FileManagerDialogBase.prototype.showBlankDialog = function() {
-  return this.showImpl_('', '', null, null, null);
+  return this.showImpl_('', '', null, null);
 };
 
 /**
@@ -93,7 +93,7 @@
  *     dialog failed to show due to an existing dialog.
  */
 FileManagerDialogBase.prototype.showTitleOnlyDialog = function(title) {
-  return this.showImpl_(title, '', null, null, null);
+  return this.showImpl_(title, '', null, null);
 };
 
 /**
@@ -104,11 +104,11 @@
  */
 FileManagerDialogBase.prototype.showTitleAndTextDialog = function(title, text) {
   this.buttons.style.display = 'none';
-  return this.showImpl_(title, text, null, null, null);
+  return this.showImpl_(title, text, null, null);
 };
 
 /**
- * @param {function()=} opt_onHide Called when the dialog is hidden.
+ * @param {Function=} opt_onHide Called when the dialog is hidden.
  */
 FileManagerDialogBase.prototype.hide = function(opt_onHide) {
   cr.ui.dialogs.BaseDialog.prototype.hide.call(
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js b/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js
index 20e6897..59b7c83 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/file_manager_ui.js
@@ -100,25 +100,25 @@
 
   /**
    * Toggle-view button.
-   * @type {HTMLElement}
+   * @type {Element}
    */
   this.toggleViewButton = null;
 
   /**
    * File type selector in the footer.
-   * @type {HTMLElement}
+   * @type {HTMLSelectElement}
    */
   this.fileTypeSelector = null;
 
   /**
    * OK button in the footer.
-   * @type {HTMLElement}
+   * @type {HTMLButtonElement}
    */
   this.okButton = null;
 
   /**
    * Cancel button in the footer.
-   * @type {HTMLElement}
+   * @type {HTMLButtonElement}
    */
   this.cancelButton = null;
 
@@ -151,9 +151,12 @@
   var parentPanelOfButtons = this.element_.ownerDocument.querySelector(
       !hasFooterPanel ? '.preview-panel' : '.dialog-footer');
   parentPanelOfButtons.classList.add('button-panel');
-  this.fileTypeSelector = parentPanelOfButtons.querySelector('.file-type');
-  this.okButton = parentPanelOfButtons.querySelector('.ok');
-  this.cancelButton = parentPanelOfButtons.querySelector('.cancel');
+  this.fileTypeSelector = /** @type {!HTMLSelectElement} */
+      (parentPanelOfButtons.querySelector('.file-type'));
+  this.okButton = /** @type {!HTMLButtonElement} */
+      (parentPanelOfButtons.querySelector('.ok'));
+  this.cancelButton = /** @type {!HTMLButtonElement} */
+      (parentPanelOfButtons.querySelector('.cancel'));
 
   // Set attributes.
   var okLabel = str('OPEN_LABEL');
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_table.js b/ui/file_manager/file_manager/foreground/js/ui/file_table.js
index 1a6e6f6..263ba49 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/file_table.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/file_table.js
@@ -12,7 +12,7 @@
 /**
  * Custom column model for advanced auto-resizing.
  *
- * @param {Array.<cr.ui.table.TableColumn>} tableColumns Table columns.
+ * @param {!Array.<cr.ui.table.TableColumn>} tableColumns Table columns.
  * @extends {cr.ui.table.TableColumnModel}
  * @constructor
  */
@@ -227,7 +227,7 @@
  * Decorates the element.
  * @param {HTMLElement} self Table to decorate.
  * @param {MetadataCache} metadataCache To retrieve metadata.
- * @param {VolumeManager} volumeManager To retrieve volume info.
+ * @param {VolumeManagerWrapper} volumeManager To retrieve volume info.
  * @param {boolean} fullPage True if it's full page File Manager,
  *                           False if a file open/save dialog.
  */
@@ -256,10 +256,7 @@
   columns[3].renderFunction = self.renderDate_.bind(self);
   columns[3].defaultOrder = 'desc';
 
-  var tableColumnModelClass;
-  tableColumnModelClass = FileTableColumnModel;
-
-  var columnModel = Object.create(tableColumnModelClass.prototype, {
+  var columnModel = Object.create(FileTableColumnModel.prototype, {
     /**
      * The number of columns.
      * @type {number}
@@ -309,7 +306,8 @@
     }
   });
 
-  tableColumnModelClass.call(columnModel, columns);
+  FileTableColumnModel.call(
+      /** @type {FileTableColumnModel} */ (columnModel), columns);
   self.columnModel = columnModel;
   self.setDateTimeFormat(true);
   self.setRenderFunction(self.renderTableRow_.bind(self,
@@ -327,6 +325,7 @@
       new AsyncUtil.RateLimiter(self.relayoutImmediately_.bind(self));
 
   // Override header#redraw to use FileTableSplitter.
+  /** @this {cr.ui.table.TableHeader} */
   self.header_.redraw = function() {
     this.__proto__.redraw.call(this);
     // Extend table splitters
@@ -354,6 +353,7 @@
    * @param {number=} opt_width Width of the coordinate.
    * @param {number=} opt_height Height of the coordinate.
    * @return {Array.<number>} Index list of hit elements.
+   * @this {cr.ui.List}
    */
   self.list.getHitElements = function(x, y, opt_width, opt_height) {
     var currentSelection = [];
@@ -497,11 +497,12 @@
  * @param {Entry} entry The Entry object to render.
  * @param {string} columnId The id of the column to be rendered.
  * @param {cr.ui.Table} table The table doing the rendering.
- * @return {HTMLDivElement} Created element.
+ * @return {!HTMLDivElement} Created element.
  * @private
  */
 FileTable.prototype.renderName_ = function(entry, columnId, table) {
-  var label = this.ownerDocument.createElement('div');
+  var label = /** @type {!HTMLDivElement} */
+      (this.ownerDocument.createElement('div'));
   label.appendChild(this.renderIconType_(entry, columnId, table));
   label.entry = entry;
   label.className = 'detail-name';
@@ -515,11 +516,12 @@
  * @param {Entry} entry The Entry object to render.
  * @param {string} columnId The id of the column to be rendered.
  * @param {cr.ui.Table} table The table doing the rendering.
- * @return {HTMLDivElement} Created element.
+ * @return {!HTMLDivElement} Created element.
  * @private
  */
 FileTable.prototype.renderSize_ = function(entry, columnId, table) {
-  var div = this.ownerDocument.createElement('div');
+  var div = /** @type {!HTMLDivElement} */
+      (this.ownerDocument.createElement('div'));
   div.className = 'size';
   this.updateSize_(div, entry);
 
@@ -567,11 +569,12 @@
  * @param {Entry} entry The Entry object to render.
  * @param {string} columnId The id of the column to be rendered.
  * @param {cr.ui.Table} table The table doing the rendering.
- * @return {HTMLDivElement} Created element.
+ * @return {!HTMLDivElement} Created element.
  * @private
  */
 FileTable.prototype.renderType_ = function(entry, columnId, table) {
-  var div = this.ownerDocument.createElement('div');
+  var div = /** @type {!HTMLDivElement} */
+      (this.ownerDocument.createElement('div'));
   div.className = 'type';
   div.textContent = FileType.typeToString(FileType.getType(entry));
   return div;
@@ -641,8 +644,10 @@
  * @param {Entry} entry File entry.
  */
 FileTable.prototype.updateFileMetadata = function(item, entry) {
-  this.updateDate_(item.querySelector('.date'), entry);
-  this.updateSize_(item.querySelector('.size'), entry);
+  this.updateDate_(
+      /** @type {!HTMLDivElement} */ (item.querySelector('.date')), entry);
+  this.updateSize_(
+      /** @type {!HTMLDivElement} */ (item.querySelector('.size')), entry);
 };
 
 /**
@@ -699,11 +704,12 @@
  * @param {Entry} entry The Entry object to render.
  * @param {string} columnId The id of the column to be rendered.
  * @param {cr.ui.Table} table The table doing the rendering.
- * @return {HTMLDivElement} Created element.
+ * @return {!HTMLDivElement} Created element.
  * @private
  */
 FileTable.prototype.renderIconType_ = function(entry, columnId, table) {
-  var icon = this.ownerDocument.createElement('div');
+  var icon = /** @type {!HTMLDivElement} */
+      (this.ownerDocument.createElement('div'));
   icon.className = 'detail-icon';
   icon.setAttribute('file-type-icon', FileType.getIcon(entry));
   return icon;
@@ -778,14 +784,14 @@
 
 /**
  * Render filename label for grid and list view.
- * @param {HTMLDocument} doc Owner document.
+ * @param {Document} doc Owner document.
  * @param {Entry} entry The Entry object to render.
- * @return {HTMLDivElement} The label.
+ * @return {!HTMLDivElement} The label.
  */
 filelist.renderFileNameLabel = function(doc, entry) {
   // Filename need to be in a '.filename-label' container for correct
   // work of inplace renaming.
-  var box = doc.createElement('div');
+  var box = /** @type {!HTMLDivElement} */ (doc.createElement('div'));
   box.className = 'filename-label';
   var fileName = doc.createElement('span');
   fileName.className = 'entry-name';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/location_line.js b/ui/file_manager/file_manager/foreground/js/ui/location_line.js
index 97a8715..9d50a36 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/location_line.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/location_line.js
@@ -59,7 +59,7 @@
     this.volumeIcon_.setAttribute(
         'volume-type-icon', location.volumeInfo.volumeType);
     this.volumeIcon_.setAttribute(
-        'volume-subtype', location.volumeInfo.deviceType);
+        'volume-subtype', location.volumeInfo.deviceType || '');
   }
 
   var queue = new AsyncUtil.Queue();
@@ -144,7 +144,7 @@
 
 /**
  * Updates the breadcrumb display.
- * @param {Array.<Entry>} entries Entries on the target path.
+ * @param {Array.<!Entry>} entries Entries on the target path.
  * @private
  */
 LocationLine.prototype.updateInternal_ = function(entries) {
diff --git a/ui/file_manager/file_manager/foreground/js/ui/preview_panel.js b/ui/file_manager/file_manager/foreground/js/ui/preview_panel.js
index 449bdca..8def6fb 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/preview_panel.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/preview_panel.js
@@ -6,7 +6,7 @@
 
 /**
  * PreviewPanel UI class.
- * @param {HTMLElement} element DOM Element of preview panel.
+ * @param {Element} element DOM Element of preview panel.
  * @param {PreviewPanel.VisibilityType} visibilityType Initial value of the
  *     visibility type.
  * @param {MetadataCache} metadataCache Metadata cache.
@@ -41,7 +41,7 @@
 
   /**
    * Dom element of the preview panel.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.element_ = element;
@@ -55,7 +55,7 @@
       volumeManager);
 
   /**
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.summaryElement_ = element.querySelector('.preview-summary');
@@ -68,7 +68,7 @@
       this.summaryElement_.querySelector('.calculating-size'));
 
   /**
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.previewText_ = element.querySelector('.preview-text');
@@ -78,7 +78,8 @@
    * @type {FileSelection}
    * @private
    */
-  this.selection_ = {entries: [], computeBytes: function() {}};
+  this.selection_ = /** @type {FileSelection} */
+      ({entries: [], computeBytes: function() {}});
 
   /**
    * Sequence value that is incremented by every selection update and is used to
@@ -319,13 +320,13 @@
  *
  * This label shows dots and varying the number of dots every
  * CalculatingSizeLabel.PERIOD milliseconds.
- * @param {HTMLElement} element DOM element of the label.
+ * @param {Element} element DOM element of the label.
  * @constructor
  */
 PreviewPanel.CalculatingSizeLabel = function(element) {
   this.element_ = element;
   this.count_ = 0;
-  this.intervalID_ = null;
+  this.intervalID_ = 0;
   Object.seal(this);
 };
 
@@ -344,7 +345,7 @@
   set hidden(hidden) {
     this.element_.hidden = hidden;
     if (!hidden) {
-      if (this.intervalID_ != null)
+      if (this.intervalID_ !== 0)
         return;
       this.count_ = 2;
       this.intervalID_ =
@@ -352,10 +353,10 @@
                       PreviewPanel.CalculatingSizeLabel.PERIOD);
       this.onStep_();
     } else {
-      if (this.intervalID_ == null)
+      if (this.intervalID_ === 0)
         return;
       clearInterval(this.intervalID_);
-      this.intervalID_ = null;
+      this.intervalID_ = 0;
     }
   }
 };
@@ -376,7 +377,7 @@
 /**
  * Thumbnails on the preview panel.
  *
- * @param {HTMLElement} element DOM Element of thumbnail container.
+ * @param {Element} element DOM Element of thumbnail container.
  * @param {MetadataCache} metadataCache MetadataCache.
  * @param {VolumeManagerWrapper} volumeManager Volume manager instance.
  * @constructor
@@ -410,7 +411,7 @@
 PreviewPanel.Thumbnails.prototype = {
   /**
    * Sets entries to be displayed in the view.
-   * @param {Array.<Entry>} value Entries.
+   * @param {FileSelection} value Entries.
    */
   set selection(value) {
     this.sequence_++;
@@ -447,14 +448,14 @@
 
     // Load the image.
     if (entries[i]) {
-      FileGrid.decorateThumbnailBox(box,
-                                    entries[i],
-                                    this.metadataCache_,
-                                    this.volumeManager_,
-                                    ThumbnailLoader.FillMode.FILL,
-                                    FileGrid.ThumbnailQuality.LOW,
-                                    i == 0 && length == 1 &&
-                                        this.setZoomedImage_.bind(this));
+      FileGrid.decorateThumbnailBox(
+          box,
+          entries[i],
+          this.metadataCache_,
+          this.volumeManager_,
+          ThumbnailLoader.FillMode.FILL,
+          FileGrid.ThumbnailQuality.LOW,
+          i == 0 && length == 1 ? this.setZoomedImage_.bind(this) : undefined);
     }
 
     // Register the click handler.
@@ -470,11 +471,12 @@
  * Create the zoomed version of image and set it to the DOM element to show the
  * zoomed image.
  *
- * @param {Image} image Image to be source of the zoomed image.
- * @param {Object} transform Transformation to be applied to the image.
+ * @param {HTMLImageElement} image Image to be source of the zoomed image.
+ * @param {Object=} opt_transform Transformation to be applied to the image.
  * @private
  */
-PreviewPanel.Thumbnails.prototype.setZoomedImage_ = function(image, transform) {
+PreviewPanel.Thumbnails.prototype.setZoomedImage_ = function(image,
+                                                             opt_transform) {
   if (!image)
     return;
   var width = image.width || 0;
@@ -512,13 +514,14 @@
 
   var boxWidth = Math.max(PreviewPanel.Thumbnails.THUMBNAIL_SIZE, imageWidth);
   var boxHeight = Math.max(PreviewPanel.Thumbnails.THUMBNAIL_SIZE, imageHeight);
-  if (transform && transform.rotate90 % 2 == 1) {
+  if (opt_transform && opt_transform.rotate90 % 2 == 1) {
     var t = boxWidth;
     boxWidth = boxHeight;
     boxHeight = t;
   }
 
-  util.applyTransform(zoomedImage, transform);
+  if (opt_transform)
+    util.applyTransform(zoomedImage, opt_transform);
 
   var zoomedBox = this.element_.ownerDocument.createElement('div');
   zoomedBox.className = 'popup';
diff --git a/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js b/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js
index 698576b..2047e31 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/progress_center_panel.js
@@ -6,8 +6,9 @@
 
 /**
  * Item element of the progress center.
- * @param {HTMLDocument} document Document which the new item belongs to.
+ * @param {Document} document Document which the new item belongs to.
  * @constructor
+ * @extends {HTMLDivElement}
  */
 function ProgressCenterItemElement(document) {
   var label = document.createElement('label');
@@ -68,11 +69,12 @@
 
 /**
  * Decorates the given element as a progress item.
- * @param {HTMLElement} element Item to be decorated.
+ * @param {Element} element Item to be decorated.
  * @return {ProgressCenterItemElement} Decorated item.
  */
 ProgressCenterItemElement.decorate = function(element) {
   element.__proto__ = ProgressCenterItemElement.prototype;
+  element = /** @type {ProgressCenterItemElement} */ (element);
   element.state_ = ProgressItemState.PROGRESSING;
   element.track_ = element.querySelector('.progress-track');
   element.track_.addEventListener('webkitTransitionEnd',
@@ -119,7 +121,7 @@
 
   // Set track width.
   var setWidth = function(nextWidthFrame) {
-    var currentWidthRate = parseInt(this.track_.style.width);
+    var currentWidthRate = parseInt(this.track_.style.width, 10);
     // Prevent assigning the same width to avoid stopping the animation.
     // animated == false may be intended to cancel the animation, so in that
     // case, the assignment should be done.
@@ -172,21 +174,21 @@
 function ProgressCenterPanel(element) {
   /**
    * Root element of the progress center.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.element_ = element;
 
   /**
    * Open view containing multiple progress items.
-   * @type {HTMLElement}
+   * @type {Element}
    * @private
    */
   this.openView_ = this.element_.querySelector('#progress-center-open-view');
 
   /**
    * Close view that is a summarized progress item.
-   * @type {HTMLElement}
+   * @type {ProgressCenterItemElement}
    * @private
    */
   this.closeView_ = ProgressCenterItemElement.decorate(
@@ -253,7 +255,7 @@
 
 /**
  * Obtains the toggle animation keyframes rule from the document.
- * @param {HTMLDocument} document Document containing the rule.
+ * @param {Document} document Document containing the rule.
  * @return {CSSKeyframeRule} Animation rule.
  * @private
  */
@@ -425,12 +427,13 @@
 /**
  * Gets an item element having the specified ID.
  * @param {string} id progress item ID.
- * @return {HTMLElement} Item element having the ID.
+ * @return {ProgressCenterItemElement} Item element having the ID.
  * @private
  */
 ProgressCenterPanel.prototype.getItemElement_ = function(id) {
   var query = 'li[data-progress-id="' + id + '"]';
-  return this.openView_.querySelector(query);
+  return /** @type {ProgressCenterItemElement} */ (
+      this.openView_.querySelector(query));
 };
 
 /**
diff --git a/ui/file_manager/file_manager/foreground/js/ui/scrollbar.js b/ui/file_manager/file_manager/foreground/js/ui/scrollbar.js
index 5a8e42c..755fbec 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/scrollbar.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/scrollbar.js
@@ -13,7 +13,7 @@
 
 /**
  * Mode of the scrollbar. As for now, only vertical scrollbars are supported.
- * @type {number}
+ * @enum {number}
  */
 ScrollBar.Mode = {
   VERTICAL: 0,
@@ -81,7 +81,9 @@
   this.view_.addEventListener('scroll', this.onScroll_.bind(this));
   this.view_.addEventListener('relayout', this.onRelayout_.bind(this));
   this.domObserver_ = new MutationObserver(this.onDomChanged_.bind(this));
-  this.domObserver_.observe(this.view_, {subtree: true, attributes: true});
+  this.domObserver_.observe(
+      this.view_,
+      /** @type {MutationObserverInit} */ ({subtree: true, attributes: true}));
   this.onRelayout_();
 };
 
diff --git a/ui/file_manager/file_manager/foreground/js/ui/search_box.js b/ui/file_manager/file_manager/foreground/js/ui/search_box.js
index 86f4969..a066bfa 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/search_box.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/search_box.js
@@ -7,9 +7,9 @@
 /**
  * Search box.
  *
- * @param {HTMLElement} element Root element of the search box.
- * @param {HTMLElement} searchButton Search button.
- * @param {HTMLElement} noResultMessage Message element for the empty result.
+ * @param {Element} element Root element of the search box.
+ * @param {Element} searchButton Search button.
+ * @param {Element} noResultMessage Message element for the empty result.
  * @extends {cr.EventTarget}
  * @constructor
  */
@@ -18,37 +18,38 @@
 
   /**
    * Autocomplete List.
-   * @type {SearchBox.AutocompleteList}
+   * @type {!SearchBox.AutocompleteList}
    */
   this.autocompleteList = new SearchBox.AutocompleteList(element.ownerDocument);
 
   /**
    * Root element of the search box.
-   * @type {HTMLElement}
+   * @type {Element}
    */
   this.element = element;
 
   /**
    * Search button.
-   * @type {HTMLElement}
+   * @type {Element}
    */
   this.searchButton = searchButton;
 
   /**
    * No result message.
-   * @type {HTMLElement}
+   * @type {Element}
    */
   this.noResultMessage = noResultMessage;
 
   /**
    * Text input of the search box.
-   * @type {HTMLElement}
+   * @type {!HTMLInputElement}
    */
-  this.inputElement = element.querySelector('input');
+  this.inputElement = /** @type {!HTMLInputElement} */ (
+      element.querySelector('input'));
 
   /**
    * Clear button of the search box.
-   * @type {HTMLElement}
+   * @type {Element}
    */
   this.clearButton = element.querySelector('.clear');
 
@@ -96,8 +97,9 @@
 
 /**
  * Autocomplete list for search box.
- * @param {HTMLDocument} document Document.
+ * @param {Document} document Document.
  * @constructor
+ * @extends {cr.ui.AutocompleteList}
  */
 SearchBox.AutocompleteList = function(document) {
   var self = cr.ui.AutocompleteList.call(this);
@@ -141,7 +143,7 @@
 /**
  * ListItem element for autocomplete.
  *
- * @param {HTMLDocument} document Document.
+ * @param {Document} document Document.
  * @param {Object} item An object representing a suggestion.
  * @constructor
  * @private
@@ -210,9 +212,11 @@
 
 /**
  * Handles a keydown event of the search box.
+ * @param {Event} event
  * @private
  */
-SearchBox.prototype.onKeyDown_ = function() {
+SearchBox.prototype.onKeyDown_ = function(event) {
+  event = /** @type {KeyboardEvent} */ (event);
   // Handle only Esc key now.
   if (event.keyCode != 27 || this.inputElement.value)
     return;
@@ -221,10 +225,11 @@
 
 /**
  * Handles a dragenter event and refuses a drag source of files.
- * @param {DragEvent} event The dragenter event.
+ * @param {Event} event The dragenter event.
  * @private
  */
 SearchBox.prototype.onDragEnter_ = function(event) {
+  event = /** @type {DragEvent} */ (event);
   // For normal elements, they does not accept drag drop by default, and accept
   // it by using event.preventDefault. But input elements accept drag drop
   // by default. So disable the input element here to prohibit drag drop.
diff --git a/ui/file_manager/file_manager/foreground/js/ui/share_dialog.js b/ui/file_manager/file_manager/foreground/js/ui/share_dialog.js
index b390fce..cd5831d 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/share_dialog.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/share_dialog.js
@@ -97,8 +97,8 @@
 
 /**
  * Injects headers into the passed request.
- * @param {Event} e Request event.
- * @return {{requestHeaders: HttpHeaders}} Modified headers.
+ * @param {!Object} e Request event.
+ * @return {!{requestHeaders: Array.<!HttpHeader>}} Modified headers.
  * @private
  */
 ShareDialog.WebViewAuthorizer.prototype.authorizeRequest_ = function(e) {
@@ -174,6 +174,7 @@
 };
 
 /**
+ * @param {Function=} opt_onHide Called when the dialog is hidden.
  * @override
  */
 ShareDialog.prototype.hide = function(opt_onHide) {
@@ -183,7 +184,7 @@
 /**
  * Hide the dialog with the result and the callback.
  * @param {ShareDialog.Result} result Result passed to the closing callback.
- * @param {function()=} opt_onHide Callback called at the end of hiding.
+ * @param {Function=} opt_onHide Callback called at the end of hiding.
  */
 ShareDialog.prototype.hideWithResult = function(result, opt_onHide) {
   if (!this.isShowing())
@@ -213,9 +214,9 @@
 /**
  * Shows the dialog.
  * @param {FileEntry} entry Entry to share.
- * @param {function(boolean)} callback Callback to be called when the showing
- *     task is completed. The argument is whether to succeed or not. Note that
- *     cancel is regarded as success.
+ * @param {function(ShareDialog.Result)} callback Callback to be called when the
+ *     showing task is completed. The argument is whether to succeed or not.
+ *     Note that cancel is regarded as success.
  */
 ShareDialog.prototype.show = function(entry, callback) {
   // If the dialog is already showing, return the error.
diff --git a/ui/file_manager/file_manager/foreground/js/ui/suggest_apps_dialog.js b/ui/file_manager/file_manager/foreground/js/ui/suggest_apps_dialog.js
index b6f8085..6f1da8c 100644
--- a/ui/file_manager/file_manager/foreground/js/ui/suggest_apps_dialog.js
+++ b/ui/file_manager/file_manager/foreground/js/ui/suggest_apps_dialog.js
@@ -136,8 +136,8 @@
 /**
  * Injects headers into the passed request.
  *
- * @param {Event} e Request event.
- * @return {{requestHeaders: HttpHeaders}} Modified headers.
+ * @param {!Object} e Request event.
+ * @return {!{requestHeaders: Array.<!HttpHeader>}} Modified headers.
  * @private
  */
 SuggestAppsDialog.prototype.authorizeRequest_ = function(e) {
@@ -217,9 +217,9 @@
  * Internal method to show a dialog. This should be called only from 'Suggest.
  * appDialog.showXxxx()' functions.
  *
- * @param {string} filename Filename (without extension) of the file.
- * @param {string} extension Extension of the file.
- * @param {string} mime Mime of the file.
+ * @param {?string} filename Filename (without extension) of the file.
+ * @param {?string} extension Extension of the file.
+ * @param {?string} mime Mime of the file.
  * @param {function(boolean)} onDialogClosed Called when the dialog is closed.
  *     The argument is the result of installation: true if an app is installed,
  *     false otherwise.
@@ -405,6 +405,8 @@
 };
 
 /**
+ * @param {Function=} opt_originalOnHide Called when the original dialog is
+ *     hidden.
  * @override
  */
 SuggestAppsDialog.prototype.hide = function(opt_originalOnHide) {
@@ -453,7 +455,7 @@
 };
 
 /**
- * @param {function()=} opt_originalOnHide Original onHide function passed to
+ * @param {Function=} opt_originalOnHide Original onHide function passed to
  *     SuggestAppsDialog.hide().
  * @private
  */
@@ -539,7 +541,7 @@
 };
 
 /**
- * @param {number} eason Reason of closing dialog, which must be defined in
+ * @param {number} reason Reason of closing dialog, which must be defined in
  *     SuggestAppsDialog.Metrics.CLOSE_DIALOG.
  */
 SuggestAppsDialog.Metrics.recordCloseDialog = function(reason) {
diff --git a/ui/file_manager/file_manager/foreground/js/volume_manager_wrapper.js b/ui/file_manager/file_manager/foreground/js/volume_manager_wrapper.js
index 6812b86..7754752 100644
--- a/ui/file_manager/file_manager/foreground/js/volume_manager_wrapper.js
+++ b/ui/file_manager/file_manager/foreground/js/volume_manager_wrapper.js
@@ -130,7 +130,7 @@
 /**
  * Called on events sent from VolumeManager. This has responsibility to
  * re-dispatch the event to the listeners.
- * @param {Event} event Event object sent from VolumeManager.
+ * @param {!Event} event Event object sent from VolumeManager.
  * @private
  */
 VolumeManagerWrapper.prototype.onEvent_ = function(event) {
@@ -202,7 +202,7 @@
 };
 
 /**
- * @return {VolumeManagerCommon.DriveConnectionType} Current drive connection
+ * @return {VolumeManagerCommon.DriveConnectionState} Current drive connection
  *     state.
  */
 VolumeManagerWrapper.prototype.getDriveConnectionState = function() {
@@ -258,7 +258,7 @@
 /**
  * Obtains location information from an entry.
  *
- * @param {Entry} entry File or directory entry.
+ * @param {(Entry|Object)} entry File or directory entry.
  * @return {EntryLocation} Location information.
  */
 VolumeManagerWrapper.prototype.getLocationInfo = function(entry) {
diff --git a/ui/file_manager/image_loader/image_loader_client.js b/ui/file_manager/image_loader/image_loader_client.js
index 703a5a0..6dfef8e 100644
--- a/ui/file_manager/image_loader/image_loader_client.js
+++ b/ui/file_manager/image_loader/image_loader_client.js
@@ -141,7 +141,7 @@
     var task = this.tasks_[taskKey];
     if (!task.isValid()) {
       // Cancel this task since it is not valid anymore.
-      this.cancel(taskKey);
+      this.cancel(parseInt(taskKey, 10));
       delete this.tasks_[taskKey];
     }
   }
@@ -343,7 +343,8 @@
  * which are not valid anymore, which will reduce cpu consumption.
  *
  * @param {string} url Url of the requested image.
- * @param {Image} image Image node to load the requested picture into.
+ * @param {HTMLImageElement} image Image node to load the requested picture
+ *     into.
  * @param {Object} options Loader options, such as: orientation, scale,
  *     maxHeight, width, height and/or cache.
  * @param {function()} onSuccess Callback for success.
diff --git a/ui/gfx/OWNERS b/ui/gfx/OWNERS
index dad6c9a..2ac138b 100644
--- a/ui/gfx/OWNERS
+++ b/ui/gfx/OWNERS
@@ -12,7 +12,6 @@
 per-file screen*=oshima@chromium.org
 
 # Transform, interpolated transform and transform util.
-per-file transform*=shawnsingh@chromium.org
 per-file transform*=vollick@chromium.org
 per-file interpolated_transform*=vollick@chromium.org
 
diff --git a/ui/gfx/break_list_unittest.cc b/ui/gfx/break_list_unittest.cc
index 5d4e39b..9d2168d 100644
--- a/ui/gfx/break_list_unittest.cc
+++ b/ui/gfx/break_list_unittest.cc
@@ -156,7 +156,7 @@
   };
 
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     BreakList<bool>::const_iterator it = breaks.GetBreak(cases[i].position);
     EXPECT_EQ(breaks.breaks()[cases[i].break_index], *it);
     EXPECT_EQ(breaks.GetRange(it), cases[i].range);
diff --git a/ui/gfx/font_render_params_linux.cc b/ui/gfx/font_render_params_linux.cc
index 4f9fbc9..4b86f32 100644
--- a/ui/gfx/font_render_params_linux.cc
+++ b/ui/gfx/font_render_params_linux.cc
@@ -29,13 +29,25 @@
 float device_scale_factor_for_internal_display = 1.0f;
 #endif
 
-// Keyed by hashes of FontRenderParamQuery structs from
-// HashFontRenderParamsQuery().
-typedef base::MRUCache<uint32, FontRenderParams> Cache;
-
 // Number of recent GetFontRenderParams() results to cache.
 const size_t kCacheSize = 20;
 
+// Cached result from a call to GetFontRenderParams().
+struct QueryResult {
+  QueryResult(const FontRenderParams& params, const std::string& family)
+      : params(params),
+        family(family) {
+  }
+  ~QueryResult() {}
+
+  FontRenderParams params;
+  std::string family;
+};
+
+// Keyed by hashes of FontRenderParamQuery structs from
+// HashFontRenderParamsQuery().
+typedef base::MRUCache<uint32, QueryResult> Cache;
+
 // A cache and the lock that must be held while accessing it.
 // GetFontRenderParams() is called by both the UI thread and the sandbox IPC
 // thread.
@@ -168,21 +180,24 @@
 FontRenderParams GetFontRenderParams(const FontRenderParamsQuery& query,
                                      std::string* family_out) {
   const uint32 hash = HashFontRenderParamsQuery(query);
-  if (!family_out) {
-    // The family returned by Fontconfig isn't part of FontRenderParams, so we
-    // can only return a value from the cache if it wasn't requested.
-    SynchronizedCache* synchronized_cache = g_synchronized_cache.Pointer();
+  SynchronizedCache* synchronized_cache = g_synchronized_cache.Pointer();
+
+  {
+    // Try to find a cached result so Fontconfig doesn't need to be queried.
     base::AutoLock lock(synchronized_cache->lock);
     Cache::const_iterator it = synchronized_cache->cache.Get(hash);
     if (it != synchronized_cache->cache.end()) {
       DVLOG(1) << "Returning cached params for " << hash;
-      return it->second;
+      const QueryResult& result = it->second;
+      if (family_out)
+        *family_out = result.family;
+      return result.params;
     }
-  } else {
-    family_out->clear();
   }
-  DVLOG(1) << "Computing params for " << hash
-           << (family_out ? " (family requested)" : "");
+
+  DVLOG(1) << "Computing params for " << hash;
+  if (family_out)
+    family_out->clear();
 
   // Start with the delegate's settings, but let Fontconfig have the final say.
   FontRenderParams params;
@@ -215,12 +230,13 @@
   if (family_out && family_out->empty() && !query.families.empty())
     *family_out = query.families[0];
 
-  // Store the computed struct. It's fine if this overwrites a struct that was
-  // cached by a different thread in the meantime; the values should be
-  // identical.
-  SynchronizedCache* synchronized_cache = g_synchronized_cache.Pointer();
-  base::AutoLock lock(synchronized_cache->lock);
-  synchronized_cache->cache.Put(hash, params);
+  {
+    // Store the result. It's fine if this overwrites a result that was cached
+    // by a different thread in the meantime; the values should be identical.
+    base::AutoLock lock(synchronized_cache->lock);
+    synchronized_cache->cache.Put(hash,
+        QueryResult(params, family_out ? *family_out : std::string()));
+  }
 
   return params;
 }
diff --git a/ui/gfx/geometry/BUILD.gn b/ui/gfx/geometry/BUILD.gn
index 8849def..48b26fe 100644
--- a/ui/gfx/geometry/BUILD.gn
+++ b/ui/gfx/geometry/BUILD.gn
@@ -29,8 +29,6 @@
     "quad_f.h",
     "rect.cc",
     "rect.h",
-    "rect_base.h",
-    "rect_base_impl.h",
     "rect_conversions.cc",
     "rect_conversions.h",
     "rect_f.cc",
diff --git a/ui/gfx/geometry/point3_unittest.cc b/ui/gfx/geometry/point3_unittest.cc
index 77f20d7..d8a7f19 100644
--- a/ui/gfx/geometry/point3_unittest.cc
+++ b/ui/gfx/geometry/point3_unittest.cc
@@ -26,7 +26,7 @@
     { gfx::Point3F(-9.6f, 9.5f, -2.8f), a - v1 + v2 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i)
+  for (size_t i = 0; i < arraysize(tests); ++i)
     EXPECT_EQ(tests[i].expected.ToString(),
               tests[i].actual.ToString());
 
diff --git a/ui/gfx/geometry/point_unittest.cc b/ui/gfx/geometry/point_unittest.cc
index 8c5f552..d0cdded 100644
--- a/ui/gfx/geometry/point_unittest.cc
+++ b/ui/gfx/geometry/point_unittest.cc
@@ -66,7 +66,7 @@
     { Point(-10, 9), a - v1 + v2 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i)
+  for (size_t i = 0; i < arraysize(tests); ++i)
     EXPECT_EQ(tests[i].expected.ToString(), tests[i].actual.ToString());
 }
 
diff --git a/ui/gfx/geometry/quad_unittest.cc b/ui/gfx/geometry/quad_unittest.cc
index fc9514f..a5c200d 100644
--- a/ui/gfx/geometry/quad_unittest.cc
+++ b/ui/gfx/geometry/quad_unittest.cc
@@ -150,7 +150,7 @@
     }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     PointF a_off = tests[i].a_off;
     PointF b_off = tests[i].b_off;
     PointF c_off = tests[i].c_off;
diff --git a/ui/gfx/geometry/r_tree_base.cc b/ui/gfx/geometry/r_tree_base.cc
index e93e1d5..fd5deab 100644
--- a/ui/gfx/geometry/r_tree_base.cc
+++ b/ui/gfx/geometry/r_tree_base.cc
@@ -463,7 +463,7 @@
   for (size_t i = 0; i < sibling->children_.size(); ++i)
     sibling->children_[i]->set_parent(sibling.get());
 
-  return sibling.PassAs<NodeBase>();
+  return sibling.Pass();
 }
 
 RTreeBase::Node* RTreeBase::Node::LeastOverlapIncrease(
diff --git a/ui/gfx/geometry/r_tree_unittest.cc b/ui/gfx/geometry/r_tree_unittest.cc
index ba45405..d4da8ef 100644
--- a/ui/gfx/geometry/r_tree_unittest.cc
+++ b/ui/gfx/geometry/r_tree_unittest.cc
@@ -279,14 +279,14 @@
   // Add three children, one each with centers at (0, 0), (10, 10), (-9, -9),
   // around which a bounding box will be centered at (0, 0)
   scoped_ptr<RTreeRecord> center_zero(new RTreeRecord(Rect(-1, -1, 2, 2), 1));
-  parent->AddChild(center_zero.PassAs<RTreeNodeBase>());
+  parent->AddChild(center_zero.Pass());
 
   scoped_ptr<RTreeRecord> center_positive(new RTreeRecord(Rect(9, 9, 2, 2), 2));
-  parent->AddChild(center_positive.PassAs<RTreeNodeBase>());
+  parent->AddChild(center_positive.Pass());
 
   scoped_ptr<RTreeRecord> center_negative(
       new RTreeRecord(Rect(-10, -10, 2, 2), 3));
-  parent->AddChild(center_negative.PassAs<RTreeNodeBase>());
+  parent->AddChild(center_negative.Pass());
 
   ValidateNode(parent.get(), 1U, 5U);
   EXPECT_EQ(Rect(-10, -10, 21, 21), parent->rect());
@@ -511,7 +511,7 @@
   for (int i = 1; i <= 10; ++i) {
     scoped_ptr<RTreeRecord> record(new RTreeRecord(Rect(0, 0, i, i), i));
     sorted_children.push_back(record.get());
-    test_node->AddChild(record.PassAs<RTreeNodeBase>());
+    test_node->AddChild(record.Pass());
     low_bounds.push_back(Rect(0, 0, i, i));
     high_bounds.push_back(Rect(0, 0, 10, 10));
   }
@@ -584,13 +584,13 @@
             new RTreeRecord(Rect(0, 0, id, id), id));
         ++id;
         records.push_back(record.get());
-        level_0_child->AddChild(record.PassAs<RTreeNodeBase>());
+        level_0_child->AddChild(record.Pass());
       }
       level_0_children.push_back(level_0_child.get());
-      level_1_child->AddChild(level_0_child.PassAs<RTreeNodeBase>());
+      level_1_child->AddChild(level_0_child.Pass());
     }
     level_1_children.push_back(level_1_child.get());
-    root->AddChild(level_1_child.PassAs<RTreeNodeBase>());
+    root->AddChild(level_1_child.Pass());
   }
 
   // This should now be a valid tree structure.
@@ -659,8 +659,8 @@
     scoped_ptr<RTreeNode> node(new RTreeNode);
     scoped_ptr<RTreeRecord> record(
         new RTreeRecord(Rect(i * 2, 0, 1, 2), i + 1));
-    node->AddChild(record.PassAs<RTreeNodeBase>());
-    test_parent->AddChild(node.PassAs<RTreeNodeBase>());
+    node->AddChild(record.Pass());
+    test_parent->AddChild(node.Pass());
   }
 
   ValidateNode(test_parent.get(), 1U, 5U);
@@ -710,7 +710,7 @@
   scoped_ptr<RTreeNode> record_parent(new RTreeNode);
   record_parent->AddChild(
       scoped_ptr<RTreeNodeBase>(new RTreeRecord(Rect(4, 0, 2, 2), 9)));
-  test_parent->AddChild(record_parent.PassAs<RTreeNodeBase>());
+  test_parent->AddChild(record_parent.Pass());
   BuildExpandedRects(test_parent.get(), test_rect_inside, &expanded_rects);
   result = NodeLeastOverlapIncrease(
       test_parent.get(), test_rect_inside, expanded_rects);
@@ -728,19 +728,19 @@
   scoped_ptr<RTreeNode> node(new RTreeNode);
   node->AddChild(
       scoped_ptr<RTreeNodeBase>(new RTreeRecord(Rect(1, 0, 1, 1), 1)));
-  test_parent->AddChild(node.PassAs<RTreeNodeBase>());
+  test_parent->AddChild(node.Pass());
   node.reset(new RTreeNode);
   node->AddChild(
       scoped_ptr<RTreeNodeBase>(new RTreeRecord(Rect(0, 1, 1, 1), 2)));
-  test_parent->AddChild(node.PassAs<RTreeNodeBase>());
+  test_parent->AddChild(node.Pass());
   node.reset(new RTreeNode);
   node->AddChild(
       scoped_ptr<RTreeNodeBase>(new RTreeRecord(Rect(2, 1, 1, 1), 3)));
-  test_parent->AddChild(node.PassAs<RTreeNodeBase>());
+  test_parent->AddChild(node.Pass());
   node.reset(new RTreeNode);
   node->AddChild(
       scoped_ptr<RTreeNodeBase>(new RTreeRecord(Rect(1, 2, 1, 1), 4)));
-  test_parent->AddChild(node.PassAs<RTreeNodeBase>());
+  test_parent->AddChild(node.Pass());
 
   ValidateNode(test_parent.get(), 1U, 5U);
 
@@ -779,7 +779,7 @@
   node.reset(new RTreeNode);
   node->AddChild(
       scoped_ptr<RTreeNodeBase>(new RTreeRecord(Rect(0, 1, 3, 1), 7)));
-  test_parent->AddChild(node.PassAs<RTreeNodeBase>());
+  test_parent->AddChild(node.Pass());
 
   ValidateNode(test_parent.get(), 1U, 5U);
 
diff --git a/ui/gfx/geometry/rect.cc b/ui/gfx/geometry/rect.cc
index f418e17..da860d0 100644
--- a/ui/gfx/geometry/rect.cc
+++ b/ui/gfx/geometry/rect.cc
@@ -13,25 +13,17 @@
 #include "base/logging.h"
 #include "base/strings/stringprintf.h"
 #include "ui/gfx/geometry/insets.h"
-#include "ui/gfx/geometry/rect_base_impl.h"
 
 namespace gfx {
 
-template class RectBase<Rect, Point, Size, Insets, Vector2d, int>;
-
-typedef class RectBase<Rect, Point, Size, Insets, Vector2d, int> RectBaseT;
-
 #if defined(OS_WIN)
 Rect::Rect(const RECT& r)
-    : RectBaseT(gfx::Point(r.left, r.top)) {
-  set_width(std::abs(r.right - r.left));
-  set_height(std::abs(r.bottom - r.top));
+    : origin_(r.left, r.top),
+      size_(std::abs(r.right - r.left), std::abs(r.bottom - r.top)) {
 }
 #elif defined(OS_MACOSX)
 Rect::Rect(const CGRect& r)
-    : RectBaseT(gfx::Point(r.origin.x, r.origin.y)) {
-  set_width(r.size.width);
-  set_height(r.size.height);
+    : origin_(r.origin.x, r.origin.y), size_(r.size.width, r.size.height) {
 }
 #endif
 
@@ -50,6 +42,198 @@
 }
 #endif
 
+void AdjustAlongAxis(int dst_origin, int dst_size, int* origin, int* size) {
+  *size = std::min(dst_size, *size);
+  if (*origin < dst_origin)
+    *origin = dst_origin;
+  else
+    *origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
+}
+
+}  // namespace
+
+namespace gfx {
+
+void Rect::Inset(const Insets& insets) {
+  Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
+}
+
+void Rect::Inset(int left, int top, int right, int bottom) {
+  origin_ += Vector2d(left, top);
+  set_width(std::max(width() - left - right, static_cast<int>(0)));
+  set_height(std::max(height() - top - bottom, static_cast<int>(0)));
+}
+
+void Rect::Offset(int horizontal, int vertical) {
+  origin_ += Vector2d(horizontal, vertical);
+}
+
+void Rect::operator+=(const Vector2d& offset) {
+  origin_ += offset;
+}
+
+void Rect::operator-=(const Vector2d& offset) {
+  origin_ -= offset;
+}
+
+Insets Rect::InsetsFrom(const Rect& inner) const {
+  return Insets(inner.y() - y(),
+                inner.x() - x(),
+                bottom() - inner.bottom(),
+                right() - inner.right());
+}
+
+bool Rect::operator<(const Rect& other) const {
+  if (origin_ == other.origin_) {
+    if (width() == other.width()) {
+      return height() < other.height();
+    } else {
+      return width() < other.width();
+    }
+  } else {
+    return origin_ < other.origin_;
+  }
+}
+
+bool Rect::Contains(int point_x, int point_y) const {
+  return (point_x >= x()) && (point_x < right()) && (point_y >= y()) &&
+         (point_y < bottom());
+}
+
+bool Rect::Contains(const Rect& rect) const {
+  return (rect.x() >= x() && rect.right() <= right() && rect.y() >= y() &&
+          rect.bottom() <= bottom());
+}
+
+bool Rect::Intersects(const Rect& rect) const {
+  return !(IsEmpty() || rect.IsEmpty() || rect.x() >= right() ||
+           rect.right() <= x() || rect.y() >= bottom() || rect.bottom() <= y());
+}
+
+void Rect::Intersect(const Rect& rect) {
+  if (IsEmpty() || rect.IsEmpty()) {
+    SetRect(0, 0, 0, 0);
+    return;
+  }
+
+  int rx = std::max(x(), rect.x());
+  int ry = std::max(y(), rect.y());
+  int rr = std::min(right(), rect.right());
+  int rb = std::min(bottom(), rect.bottom());
+
+  if (rx >= rr || ry >= rb)
+    rx = ry = rr = rb = 0;  // non-intersecting
+
+  SetRect(rx, ry, rr - rx, rb - ry);
+}
+
+void Rect::Union(const Rect& rect) {
+  if (IsEmpty()) {
+    *this = rect;
+    return;
+  }
+  if (rect.IsEmpty())
+    return;
+
+  int rx = std::min(x(), rect.x());
+  int ry = std::min(y(), rect.y());
+  int rr = std::max(right(), rect.right());
+  int rb = std::max(bottom(), rect.bottom());
+
+  SetRect(rx, ry, rr - rx, rb - ry);
+}
+
+void Rect::Subtract(const Rect& rect) {
+  if (!Intersects(rect))
+    return;
+  if (rect.Contains(*this)) {
+    SetRect(0, 0, 0, 0);
+    return;
+  }
+
+  int rx = x();
+  int ry = y();
+  int rr = right();
+  int rb = bottom();
+
+  if (rect.y() <= y() && rect.bottom() >= bottom()) {
+    // complete intersection in the y-direction
+    if (rect.x() <= x()) {
+      rx = rect.right();
+    } else if (rect.right() >= right()) {
+      rr = rect.x();
+    }
+  } else if (rect.x() <= x() && rect.right() >= right()) {
+    // complete intersection in the x-direction
+    if (rect.y() <= y()) {
+      ry = rect.bottom();
+    } else if (rect.bottom() >= bottom()) {
+      rb = rect.y();
+    }
+  }
+  SetRect(rx, ry, rr - rx, rb - ry);
+}
+
+void Rect::AdjustToFit(const Rect& rect) {
+  int new_x = x();
+  int new_y = y();
+  int new_width = width();
+  int new_height = height();
+  AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
+  AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
+  SetRect(new_x, new_y, new_width, new_height);
+}
+
+Point Rect::CenterPoint() const {
+  return Point(x() + width() / 2, y() + height() / 2);
+}
+
+void Rect::ClampToCenteredSize(const Size& size) {
+  int new_width = std::min(width(), size.width());
+  int new_height = std::min(height(), size.height());
+  int new_x = x() + (width() - new_width) / 2;
+  int new_y = y() + (height() - new_height) / 2;
+  SetRect(new_x, new_y, new_width, new_height);
+}
+
+void Rect::SplitVertically(Rect* left_half, Rect* right_half) const {
+  DCHECK(left_half);
+  DCHECK(right_half);
+
+  left_half->SetRect(x(), y(), width() / 2, height());
+  right_half->SetRect(
+      left_half->right(), y(), width() - left_half->width(), height());
+}
+
+bool Rect::SharesEdgeWith(const Rect& rect) const {
+  return (y() == rect.y() && height() == rect.height() &&
+          (x() == rect.right() || right() == rect.x())) ||
+         (x() == rect.x() && width() == rect.width() &&
+          (y() == rect.bottom() || bottom() == rect.y()));
+}
+
+int Rect::ManhattanDistanceToPoint(const Point& point) const {
+  int x_distance =
+      std::max<int>(0, std::max(x() - point.x(), point.x() - right()));
+  int y_distance =
+      std::max<int>(0, std::max(y() - point.y(), point.y() - bottom()));
+
+  return x_distance + y_distance;
+}
+
+int Rect::ManhattanInternalDistance(const Rect& rect) const {
+  Rect c(*this);
+  c.Union(rect);
+
+  static const int kEpsilon = std::numeric_limits<int>::is_integer
+                                  ? 1
+                                  : std::numeric_limits<int>::epsilon();
+
+  int x = std::max<int>(0, c.width() - width() - rect.width() + kEpsilon);
+  int y = std::max<int>(0, c.height() - height() - rect.height() + kEpsilon);
+  return x + y;
+}
+
 std::string Rect::ToString() const {
   return base::StringPrintf("%s %s",
                             origin().ToString().c_str(),
diff --git a/ui/gfx/geometry/rect.h b/ui/gfx/geometry/rect.h
index cf386c5..fed202d 100644
--- a/ui/gfx/geometry/rect.h
+++ b/ui/gfx/geometry/rect.h
@@ -17,7 +17,6 @@
 #include <string>
 
 #include "ui/gfx/geometry/point.h"
-#include "ui/gfx/geometry/rect_base.h"
 #include "ui/gfx/geometry/rect_f.h"
 #include "ui/gfx/geometry/size.h"
 #include "ui/gfx/geometry/vector2d.h"
@@ -34,18 +33,14 @@
 
 class Insets;
 
-class GFX_EXPORT Rect
-    : public RectBase<Rect, Point, Size, Insets, Vector2d, int> {
+class GFX_EXPORT Rect {
  public:
-  Rect() : RectBase<Rect, Point, Size, Insets, Vector2d, int>(Point()) {}
-
-  Rect(int width, int height)
-      : RectBase<Rect, Point, Size, Insets, Vector2d, int>
-            (Size(width, height)) {}
-
+  Rect() {}
+  Rect(int width, int height) : size_(width, height) {}
   Rect(int x, int y, int width, int height)
-      : RectBase<Rect, Point, Size, Insets, Vector2d, int>
-            (Point(x, y), Size(width, height)) {}
+      : origin_(x, y), size_(width, height) {}
+  explicit Rect(const Size& size) : size_(size) {}
+  Rect(const Point& origin, const Size& size) : origin_(origin), size_(size) {}
 
 #if defined(OS_WIN)
   explicit Rect(const RECT& r);
@@ -53,12 +48,6 @@
   explicit Rect(const CGRect& r);
 #endif
 
-  explicit Rect(const gfx::Size& size)
-      : RectBase<Rect, Point, Size, Insets, Vector2d, int>(size) {}
-
-  Rect(const gfx::Point& origin, const gfx::Size& size)
-      : RectBase<Rect, Point, Size, Insets, Vector2d, int>(origin, size) {}
-
   ~Rect() {}
 
 #if defined(OS_WIN)
@@ -73,7 +62,132 @@
     return RectF(origin().x(), origin().y(), size().width(), size().height());
   }
 
+  int x() const { return origin_.x(); }
+  void set_x(int x) { origin_.set_x(x); }
+
+  int y() const { return origin_.y(); }
+  void set_y(int y) { origin_.set_y(y); }
+
+  int width() const { return size_.width(); }
+  void set_width(int width) { size_.set_width(width); }
+
+  int height() const { return size_.height(); }
+  void set_height(int height) { size_.set_height(height); }
+
+  const Point& origin() const { return origin_; }
+  void set_origin(const Point& origin) { origin_ = origin; }
+
+  const Size& size() const { return size_; }
+  void set_size(const Size& size) { size_ = size; }
+
+  int right() const { return x() + width(); }
+  int bottom() const { return y() + height(); }
+
+  Point top_right() const { return Point(right(), y()); }
+  Point bottom_left() const { return Point(x(), bottom()); }
+  Point bottom_right() const { return Point(right(), bottom()); }
+
+  Vector2d OffsetFromOrigin() const { return Vector2d(x(), y()); }
+
+  void SetRect(int x, int y, int width, int height) {
+    origin_.SetPoint(x, y);
+    size_.SetSize(width, height);
+  }
+
+  // Shrink the rectangle by a horizontal and vertical distance on all sides.
+  void Inset(int horizontal, int vertical) {
+    Inset(horizontal, vertical, horizontal, vertical);
+  }
+
+  // Shrink the rectangle by the given insets.
+  void Inset(const Insets& insets);
+
+  // Shrink the rectangle by the specified amount on each side.
+  void Inset(int left, int top, int right, int bottom);
+
+  // Move the rectangle by a horizontal and vertical distance.
+  void Offset(int horizontal, int vertical);
+  void Offset(const Vector2d& distance) { Offset(distance.x(), distance.y()); }
+  void operator+=(const Vector2d& offset);
+  void operator-=(const Vector2d& offset);
+
+  Insets InsetsFrom(const Rect& inner) const;
+
+  // Returns true if the area of the rectangle is zero.
+  bool IsEmpty() const { return size_.IsEmpty(); }
+
+  // A rect is less than another rect if its origin is less than
+  // the other rect's origin. If the origins are equal, then the
+  // shortest rect is less than the other. If the origin and the
+  // height are equal, then the narrowest rect is less than.
+  // This comparison is required to use Rects in sets, or sorted
+  // vectors.
+  bool operator<(const Rect& other) const;
+
+  // Returns true if the point identified by point_x and point_y falls inside
+  // this rectangle.  The point (x, y) is inside the rectangle, but the
+  // point (x + width, y + height) is not.
+  bool Contains(int point_x, int point_y) const;
+
+  // Returns true if the specified point is contained by this rectangle.
+  bool Contains(const Point& point) const {
+    return Contains(point.x(), point.y());
+  }
+
+  // Returns true if this rectangle contains the specified rectangle.
+  bool Contains(const Rect& rect) const;
+
+  // Returns true if this rectangle intersects the specified rectangle.
+  // An empty rectangle doesn't intersect any rectangle.
+  bool Intersects(const Rect& rect) const;
+
+  // Computes the intersection of this rectangle with the given rectangle.
+  void Intersect(const Rect& rect);
+
+  // Computes the union of this rectangle with the given rectangle.  The union
+  // is the smallest rectangle containing both rectangles.
+  void Union(const Rect& rect);
+
+  // Computes the rectangle resulting from subtracting |rect| from |*this|,
+  // i.e. the bounding rect of |Region(*this) - Region(rect)|.
+  void Subtract(const Rect& rect);
+
+  // Fits as much of the receiving rectangle into the supplied rectangle as
+  // possible, becoming the result. For example, if the receiver had
+  // a x-location of 2 and a width of 4, and the supplied rectangle had
+  // an x-location of 0 with a width of 5, the returned rectangle would have
+  // an x-location of 1 with a width of 4.
+  void AdjustToFit(const Rect& rect);
+
+  // Returns the center of this rectangle.
+  Point CenterPoint() const;
+
+  // Becomes a rectangle that has the same center point but with a size capped
+  // at given |size|.
+  void ClampToCenteredSize(const Size& size);
+
+  // Splits |this| in two halves, |left_half| and |right_half|.
+  void SplitVertically(Rect* left_half, Rect* right_half) const;
+
+  // Returns true if this rectangle shares an entire edge (i.e., same width or
+  // same height) with the given rectangle, and the rectangles do not overlap.
+  bool SharesEdgeWith(const Rect& rect) const;
+
+  // Returns the manhattan distance from the rect to the point. If the point is
+  // inside the rect, returns 0.
+  int ManhattanDistanceToPoint(const Point& point) const;
+
+  // Returns the manhattan distance between the contents of this rect and the
+  // contents of the given rect. That is, if the intersection of the two rects
+  // is non-empty then the function returns 0. If the rects share a side, it
+  // returns the smallest non-zero value appropriate for int.
+  int ManhattanInternalDistance(const Rect& rect) const;
+
   std::string ToString() const;
+
+ private:
+  gfx::Point origin_;
+  gfx::Size size_;
 };
 
 inline bool operator==(const Rect& lhs, const Rect& rhs) {
@@ -131,10 +245,6 @@
   return ScaleToEnclosedRect(rect, scale, scale);
 }
 
-#if !defined(COMPILER_MSVC) && !defined(__native_client__)
-extern template class RectBase<Rect, Point, Size, Insets, Vector2d, int>;
-#endif
-
 // This is declared here for use in gtest-based unit tests but is defined in
 // the gfx_test_support target. Depend on that to use this in your unit test.
 // This should not be used in production code - call ToString() instead.
diff --git a/ui/gfx/geometry/rect_base.h b/ui/gfx/geometry/rect_base.h
deleted file mode 100644
index b0a9b06..0000000
--- a/ui/gfx/geometry/rect_base.h
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// A template for a simple rectangle class.  The containment semantics
-// are array-like; that is, the coordinate (x, y) is considered to be
-// contained by the rectangle, but the coordinate (x + width, y) is not.
-// The class will happily let you create malformed rectangles (that is,
-// rectangles with negative width and/or height), but there will be assertions
-// in the operations (such as Contains()) to complain in this case.
-
-#ifndef UI_GFX_GEOMETRY_RECT_BASE_H_
-#define UI_GFX_GEOMETRY_RECT_BASE_H_
-
-#include <string>
-
-#include "base/compiler_specific.h"
-
-namespace gfx {
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-class GFX_EXPORT RectBase {
- public:
-  Type x() const { return origin_.x(); }
-  void set_x(Type x) { origin_.set_x(x); }
-
-  Type y() const { return origin_.y(); }
-  void set_y(Type y) { origin_.set_y(y); }
-
-  Type width() const { return size_.width(); }
-  void set_width(Type width) { size_.set_width(width); }
-
-  Type height() const { return size_.height(); }
-  void set_height(Type height) { size_.set_height(height); }
-
-  const PointClass& origin() const { return origin_; }
-  void set_origin(const PointClass& origin) { origin_ = origin; }
-
-  const SizeClass& size() const { return size_; }
-  void set_size(const SizeClass& size) { size_ = size; }
-
-  Type right() const { return x() + width(); }
-  Type bottom() const { return y() + height(); }
-
-  PointClass top_right() const { return PointClass(right(), y()); }
-  PointClass bottom_left() const { return PointClass(x(), bottom()); }
-  PointClass bottom_right() const { return PointClass(right(), bottom()); }
-
-  VectorClass OffsetFromOrigin() const {
-    return VectorClass(x(), y());
-  }
-
-  void SetRect(Type x, Type y, Type width, Type height);
-
-  // Shrink the rectangle by a horizontal and vertical distance on all sides.
-  void Inset(Type horizontal, Type vertical) {
-    Inset(horizontal, vertical, horizontal, vertical);
-  }
-
-  // Shrink the rectangle by the given insets.
-  void Inset(const InsetsClass& insets);
-
-  // Shrink the rectangle by the specified amount on each side.
-  void Inset(Type left, Type top, Type right, Type bottom);
-
-  // Move the rectangle by a horizontal and vertical distance.
-  void Offset(Type horizontal, Type vertical);
-  void Offset(const VectorClass& distance) {
-    Offset(distance.x(), distance.y());
-  }
-  void operator+=(const VectorClass& offset);
-  void operator-=(const VectorClass& offset);
-
-  InsetsClass InsetsFrom(const Class& inner) const {
-    return InsetsClass(inner.y() - y(),
-                       inner.x() - x(),
-                       bottom() - inner.bottom(),
-                       right() - inner.right());
-  }
-
-  // Returns true if the area of the rectangle is zero.
-  bool IsEmpty() const { return size_.IsEmpty(); }
-
-  // A rect is less than another rect if its origin is less than
-  // the other rect's origin. If the origins are equal, then the
-  // shortest rect is less than the other. If the origin and the
-  // height are equal, then the narrowest rect is less than.
-  // This comparison is required to use Rects in sets, or sorted
-  // vectors.
-  bool operator<(const Class& other) const;
-
-  // Returns true if the point identified by point_x and point_y falls inside
-  // this rectangle.  The point (x, y) is inside the rectangle, but the
-  // point (x + width, y + height) is not.
-  bool Contains(Type point_x, Type point_y) const;
-
-  // Returns true if the specified point is contained by this rectangle.
-  bool Contains(const PointClass& point) const {
-    return Contains(point.x(), point.y());
-  }
-
-  // Returns true if this rectangle contains the specified rectangle.
-  bool Contains(const Class& rect) const;
-
-  // Returns true if this rectangle intersects the specified rectangle.
-  // An empty rectangle doesn't intersect any rectangle.
-  bool Intersects(const Class& rect) const;
-
-  // Computes the intersection of this rectangle with the given rectangle.
-  void Intersect(const Class& rect);
-
-  // Computes the union of this rectangle with the given rectangle.  The union
-  // is the smallest rectangle containing both rectangles.
-  void Union(const Class& rect);
-
-  // Computes the rectangle resulting from subtracting |rect| from |*this|,
-  // i.e. the bounding rect of |Region(*this) - Region(rect)|.
-  void Subtract(const Class& rect);
-
-  // Fits as much of the receiving rectangle into the supplied rectangle as
-  // possible, becoming the result. For example, if the receiver had
-  // a x-location of 2 and a width of 4, and the supplied rectangle had
-  // an x-location of 0 with a width of 5, the returned rectangle would have
-  // an x-location of 1 with a width of 4.
-  void AdjustToFit(const Class& rect);
-
-  // Returns the center of this rectangle.
-  PointClass CenterPoint() const;
-
-  // Becomes a rectangle that has the same center point but with a size capped
-  // at given |size|.
-  void ClampToCenteredSize(const SizeClass& size);
-
-  // Splits |this| in two halves, |left_half| and |right_half|.
-  void SplitVertically(Class* left_half, Class* right_half) const;
-
-  // Returns true if this rectangle shares an entire edge (i.e., same width or
-  // same height) with the given rectangle, and the rectangles do not overlap.
-  bool SharesEdgeWith(const Class& rect) const;
-
-  // Returns the manhattan distance from the rect to the point. If the point is
-  // inside the rect, returns 0.
-  Type ManhattanDistanceToPoint(const PointClass& point) const;
-
-  // Returns the manhattan distance between the contents of this rect and the
-  // contents of the given rect. That is, if the intersection of the two rects
-  // is non-empty then the function returns 0. If the rects share a side, it
-  // returns the smallest non-zero value appropriate for Type.
-  Type ManhattanInternalDistance(const Class& rect) const;
-
- protected:
-  RectBase(const PointClass& origin, const SizeClass& size)
-      : origin_(origin), size_(size) {}
-  explicit RectBase(const SizeClass& size)
-      : size_(size) {}
-  explicit RectBase(const PointClass& origin)
-      : origin_(origin) {}
-  // Destructor is intentionally made non virtual and protected.
-  // Do not make this public.
-  ~RectBase() {}
-
- private:
-  PointClass origin_;
-  SizeClass size_;
-};
-
-}  // namespace gfx
-
-#endif  // UI_GFX_GEOMETRY_RECT_BASE_H_
diff --git a/ui/gfx/geometry/rect_base_impl.h b/ui/gfx/geometry/rect_base_impl.h
deleted file mode 100644
index 7720608..0000000
--- a/ui/gfx/geometry/rect_base_impl.h
+++ /dev/null
@@ -1,354 +0,0 @@
-// Copyright (c) 2012 The Chromium 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 <limits>
-
-#include "base/logging.h"
-#include "base/strings/stringprintf.h"
-#include "ui/gfx/geometry/rect_base.h"
-
-// This file provides the implementation for RectBaese template and
-// used to instantiate the base class for Rect and RectF classes.
-#if !defined(GFX_IMPLEMENTATION)
-#error "This file is intended for UI implementation only"
-#endif
-
-namespace {
-
-template<typename Type>
-void AdjustAlongAxis(Type dst_origin, Type dst_size, Type* origin, Type* size) {
-  *size = std::min(dst_size, *size);
-  if (*origin < dst_origin)
-    *origin = dst_origin;
-  else
-    *origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
-}
-
-} // namespace
-
-namespace gfx {
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    SetRect(Type x, Type y, Type width, Type height) {
-  origin_.SetPoint(x, y);
-  set_width(width);
-  set_height(height);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Inset(const InsetsClass& insets) {
-  Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Inset(Type left, Type top, Type right, Type bottom) {
-  origin_ += VectorClass(left, top);
-  set_width(std::max(width() - left - right, static_cast<Type>(0)));
-  set_height(std::max(height() - top - bottom, static_cast<Type>(0)));
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Offset(Type horizontal, Type vertical) {
-  origin_ += VectorClass(horizontal, vertical);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    operator+=(const VectorClass& offset) {
-  origin_ += offset;
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    operator-=(const VectorClass& offset) {
-  origin_ -= offset;
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    operator<(const Class& other) const {
-  if (origin_ == other.origin_) {
-    if (width() == other.width()) {
-      return height() < other.height();
-    } else {
-      return width() < other.width();
-    }
-  } else {
-    return origin_ < other.origin_;
-  }
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Contains(Type point_x, Type point_y) const {
-  return (point_x >= x()) && (point_x < right()) &&
-         (point_y >= y()) && (point_y < bottom());
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Contains(const Class& rect) const {
-  return (rect.x() >= x() && rect.right() <= right() &&
-          rect.y() >= y() && rect.bottom() <= bottom());
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Intersects(const Class& rect) const {
-  return !(IsEmpty() || rect.IsEmpty() ||
-           rect.x() >= right() || rect.right() <= x() ||
-           rect.y() >= bottom() || rect.bottom() <= y());
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Intersect(const Class& rect) {
-  if (IsEmpty() || rect.IsEmpty()) {
-    SetRect(0, 0, 0, 0);
-    return;
-  }
-
-  Type rx = std::max(x(), rect.x());
-  Type ry = std::max(y(), rect.y());
-  Type rr = std::min(right(), rect.right());
-  Type rb = std::min(bottom(), rect.bottom());
-
-  if (rx >= rr || ry >= rb)
-    rx = ry = rr = rb = 0;  // non-intersecting
-
-  SetRect(rx, ry, rr - rx, rb - ry);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Union(const Class& rect) {
-  if (IsEmpty()) {
-    *this = rect;
-    return;
-  }
-  if (rect.IsEmpty())
-    return;
-
-  Type rx = std::min(x(), rect.x());
-  Type ry = std::min(y(), rect.y());
-  Type rr = std::max(right(), rect.right());
-  Type rb = std::max(bottom(), rect.bottom());
-
-  SetRect(rx, ry, rr - rx, rb - ry);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    Subtract(const Class& rect) {
-  if (!Intersects(rect))
-    return;
-  if (rect.Contains(*static_cast<const Class*>(this))) {
-    SetRect(0, 0, 0, 0);
-    return;
-  }
-
-  Type rx = x();
-  Type ry = y();
-  Type rr = right();
-  Type rb = bottom();
-
-  if (rect.y() <= y() && rect.bottom() >= bottom()) {
-    // complete intersection in the y-direction
-    if (rect.x() <= x()) {
-      rx = rect.right();
-    } else if (rect.right() >= right()) {
-      rr = rect.x();
-    }
-  } else if (rect.x() <= x() && rect.right() >= right()) {
-    // complete intersection in the x-direction
-    if (rect.y() <= y()) {
-      ry = rect.bottom();
-    } else if (rect.bottom() >= bottom()) {
-      rb = rect.y();
-    }
-  }
-  SetRect(rx, ry, rr - rx, rb - ry);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    AdjustToFit(const Class& rect) {
-  Type new_x = x();
-  Type new_y = y();
-  Type new_width = width();
-  Type new_height = height();
-  AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
-  AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
-  SetRect(new_x, new_y, new_width, new_height);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-PointClass RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass,
-    Type>::CenterPoint() const {
-  return PointClass(x() + width() / 2, y() + height() / 2);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    ClampToCenteredSize(const SizeClass& size) {
-  Type new_width = std::min(width(), size.width());
-  Type new_height = std::min(height(), size.height());
-  Type new_x = x() + (width() - new_width) / 2;
-  Type new_y = y() + (height() - new_height) / 2;
-  SetRect(new_x, new_y, new_width, new_height);
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    SplitVertically(Class* left_half, Class* right_half) const {
-  DCHECK(left_half);
-  DCHECK(right_half);
-
-  left_half->SetRect(x(), y(), width() / 2, height());
-  right_half->SetRect(left_half->right(),
-                      y(),
-                      width() - left_half->width(),
-                      height());
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    SharesEdgeWith(const Class& rect) const {
-  return (y() == rect.y() && height() == rect.height() &&
-             (x() == rect.right() || right() == rect.x())) ||
-         (x() == rect.x() && width() == rect.width() &&
-             (y() == rect.bottom() || bottom() == rect.y()));
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-Type RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    ManhattanDistanceToPoint(const PointClass& point) const {
-  Type x_distance = std::max<Type>(0, std::max(
-      x() - point.x(), point.x() - right()));
-  Type y_distance = std::max<Type>(0, std::max(
-      y() - point.y(), point.y() - bottom()));
-
-  return x_distance + y_distance;
-}
-
-template<typename Class,
-         typename PointClass,
-         typename SizeClass,
-         typename InsetsClass,
-         typename VectorClass,
-         typename Type>
-Type RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
-    ManhattanInternalDistance(const Class& rect) const {
-  Class c(x(), y(), width(), height());
-  c.Union(rect);
-
-  static const Type kEpsilon = std::numeric_limits<Type>::is_integer
-                                   ? 1
-                                   : std::numeric_limits<Type>::epsilon();
-
-  Type x = std::max<Type>(0, c.width() - width() - rect.width() + kEpsilon);
-  Type y = std::max<Type>(0, c.height() - height() - rect.height() + kEpsilon);
-  return x + y;
-}
-
-}  // namespace gfx
diff --git a/ui/gfx/geometry/rect_f.cc b/ui/gfx/geometry/rect_f.cc
index 44c08aa..c87ea3d 100644
--- a/ui/gfx/geometry/rect_f.cc
+++ b/ui/gfx/geometry/rect_f.cc
@@ -9,15 +9,201 @@
 #include "base/logging.h"
 #include "base/strings/stringprintf.h"
 #include "ui/gfx/geometry/insets_f.h"
-#include "ui/gfx/geometry/rect_base_impl.h"
 #include "ui/gfx/geometry/safe_integer_conversions.h"
 
 namespace gfx {
 
-template class RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>;
+static void AdjustAlongAxis(float dst_origin,
+                            float dst_size,
+                            float* origin,
+                            float* size) {
+  *size = std::min(dst_size, *size);
+  if (*origin < dst_origin)
+    *origin = dst_origin;
+  else
+    *origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
+}
 
-typedef class RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF,
-                       float> RectBaseT;
+void RectF::Inset(const InsetsF& insets) {
+  Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
+}
+
+void RectF::Inset(float left, float top, float right, float bottom) {
+  origin_ += Vector2dF(left, top);
+  set_width(std::max(width() - left - right, static_cast<float>(0)));
+  set_height(std::max(height() - top - bottom, static_cast<float>(0)));
+}
+
+void RectF::Offset(float horizontal, float vertical) {
+  origin_ += Vector2dF(horizontal, vertical);
+}
+
+void RectF::operator+=(const Vector2dF& offset) {
+  origin_ += offset;
+}
+
+void RectF::operator-=(const Vector2dF& offset) {
+  origin_ -= offset;
+}
+
+InsetsF RectF::InsetsFrom(const RectF& inner) const {
+  return InsetsF(inner.y() - y(),
+                 inner.x() - x(),
+                 bottom() - inner.bottom(),
+                 right() - inner.right());
+}
+
+bool RectF::operator<(const RectF& other) const {
+  if (origin_ == other.origin_) {
+    if (width() == other.width()) {
+      return height() < other.height();
+    } else {
+      return width() < other.width();
+    }
+  } else {
+    return origin_ < other.origin_;
+  }
+}
+
+bool RectF::Contains(float point_x, float point_y) const {
+  return (point_x >= x()) && (point_x < right()) && (point_y >= y()) &&
+         (point_y < bottom());
+}
+
+bool RectF::Contains(const RectF& rect) const {
+  return (rect.x() >= x() && rect.right() <= right() && rect.y() >= y() &&
+          rect.bottom() <= bottom());
+}
+
+bool RectF::Intersects(const RectF& rect) const {
+  return !(IsEmpty() || rect.IsEmpty() || rect.x() >= right() ||
+           rect.right() <= x() || rect.y() >= bottom() || rect.bottom() <= y());
+}
+
+void RectF::Intersect(const RectF& rect) {
+  if (IsEmpty() || rect.IsEmpty()) {
+    SetRect(0, 0, 0, 0);
+    return;
+  }
+
+  float rx = std::max(x(), rect.x());
+  float ry = std::max(y(), rect.y());
+  float rr = std::min(right(), rect.right());
+  float rb = std::min(bottom(), rect.bottom());
+
+  if (rx >= rr || ry >= rb)
+    rx = ry = rr = rb = 0;  // non-intersecting
+
+  SetRect(rx, ry, rr - rx, rb - ry);
+}
+
+void RectF::Union(const RectF& rect) {
+  if (IsEmpty()) {
+    *this = rect;
+    return;
+  }
+  if (rect.IsEmpty())
+    return;
+
+  float rx = std::min(x(), rect.x());
+  float ry = std::min(y(), rect.y());
+  float rr = std::max(right(), rect.right());
+  float rb = std::max(bottom(), rect.bottom());
+
+  SetRect(rx, ry, rr - rx, rb - ry);
+}
+
+void RectF::Subtract(const RectF& rect) {
+  if (!Intersects(rect))
+    return;
+  if (rect.Contains(*static_cast<const RectF*>(this))) {
+    SetRect(0, 0, 0, 0);
+    return;
+  }
+
+  float rx = x();
+  float ry = y();
+  float rr = right();
+  float rb = bottom();
+
+  if (rect.y() <= y() && rect.bottom() >= bottom()) {
+    // complete intersection in the y-direction
+    if (rect.x() <= x()) {
+      rx = rect.right();
+    } else if (rect.right() >= right()) {
+      rr = rect.x();
+    }
+  } else if (rect.x() <= x() && rect.right() >= right()) {
+    // complete intersection in the x-direction
+    if (rect.y() <= y()) {
+      ry = rect.bottom();
+    } else if (rect.bottom() >= bottom()) {
+      rb = rect.y();
+    }
+  }
+  SetRect(rx, ry, rr - rx, rb - ry);
+}
+
+void RectF::AdjustToFit(const RectF& rect) {
+  float new_x = x();
+  float new_y = y();
+  float new_width = width();
+  float new_height = height();
+  AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
+  AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
+  SetRect(new_x, new_y, new_width, new_height);
+}
+
+PointF RectF::CenterPoint() const {
+  return PointF(x() + width() / 2, y() + height() / 2);
+}
+
+void RectF::ClampToCenteredSize(const SizeF& size) {
+  float new_width = std::min(width(), size.width());
+  float new_height = std::min(height(), size.height());
+  float new_x = x() + (width() - new_width) / 2;
+  float new_y = y() + (height() - new_height) / 2;
+  SetRect(new_x, new_y, new_width, new_height);
+}
+
+void RectF::SplitVertically(RectF* left_half, RectF* right_half) const {
+  DCHECK(left_half);
+  DCHECK(right_half);
+
+  left_half->SetRect(x(), y(), width() / 2, height());
+  right_half->SetRect(
+      left_half->right(), y(), width() - left_half->width(), height());
+}
+
+bool RectF::SharesEdgeWith(const RectF& rect) const {
+  return (y() == rect.y() && height() == rect.height() &&
+          (x() == rect.right() || right() == rect.x())) ||
+         (x() == rect.x() && width() == rect.width() &&
+          (y() == rect.bottom() || bottom() == rect.y()));
+}
+
+float RectF::ManhattanDistanceToPoint(const PointF& point) const {
+  float x_distance =
+      std::max<float>(0, std::max(x() - point.x(), point.x() - right()));
+  float y_distance =
+      std::max<float>(0, std::max(y() - point.y(), point.y() - bottom()));
+
+  return x_distance + y_distance;
+}
+
+float RectF::ManhattanInternalDistance(const RectF& rect) const {
+  RectF c(*this);
+  c.Union(rect);
+
+  static const float kEpsilon = std::numeric_limits<float>::is_integer
+                                    ? 1
+                                    : std::numeric_limits<float>::epsilon();
+
+  float x = std::max<float>(0, c.width() - width() - rect.width() + kEpsilon);
+  float y =
+      std::max<float>(0, c.height() - height() - rect.height() + kEpsilon);
+  return x + y;
+}
 
 bool RectF::IsExpressibleAsRect() const {
   return IsExpressibleAsInt(x()) && IsExpressibleAsInt(y()) &&
diff --git a/ui/gfx/geometry/rect_f.h b/ui/gfx/geometry/rect_f.h
index fe20965..dc233a7 100644
--- a/ui/gfx/geometry/rect_f.h
+++ b/ui/gfx/geometry/rect_f.h
@@ -9,7 +9,6 @@
 #include <string>
 
 #include "ui/gfx/geometry/point_f.h"
-#include "ui/gfx/geometry/rect_base.h"
 #include "ui/gfx/geometry/size_f.h"
 #include "ui/gfx/geometry/vector2d_f.h"
 
@@ -18,31 +17,139 @@
 class InsetsF;
 
 // A floating version of gfx::Rect.
-class GFX_EXPORT RectF
-    : public RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float> {
+class GFX_EXPORT RectF {
  public:
-  RectF()
-      : RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>
-            (SizeF()) {}
-
-  RectF(float width, float height)
-      : RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>
-            (SizeF(width, height)) {}
-
+  RectF() {}
+  RectF(float width, float height) : size_(width, height) {}
   RectF(float x, float y, float width, float height)
-      : RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>
-            (PointF(x, y), SizeF(width, height)) {}
-
-  explicit RectF(const SizeF& size)
-      : RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>
-            (size) {}
-
+      : origin_(x, y), size_(width, height) {}
+  explicit RectF(const SizeF& size) : size_(size) {}
   RectF(const PointF& origin, const SizeF& size)
-      : RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>
-            (origin, size) {}
+      : origin_(origin), size_(size) {}
 
   ~RectF() {}
 
+  float x() const { return origin_.x(); }
+  void set_x(float x) { origin_.set_x(x); }
+
+  float y() const { return origin_.y(); }
+  void set_y(float y) { origin_.set_y(y); }
+
+  float width() const { return size_.width(); }
+  void set_width(float width) { size_.set_width(width); }
+
+  float height() const { return size_.height(); }
+  void set_height(float height) { size_.set_height(height); }
+
+  const PointF& origin() const { return origin_; }
+  void set_origin(const PointF& origin) { origin_ = origin; }
+
+  const SizeF& size() const { return size_; }
+  void set_size(const SizeF& size) { size_ = size; }
+
+  float right() const { return x() + width(); }
+  float bottom() const { return y() + height(); }
+
+  PointF top_right() const { return PointF(right(), y()); }
+  PointF bottom_left() const { return PointF(x(), bottom()); }
+  PointF bottom_right() const { return PointF(right(), bottom()); }
+
+  Vector2dF OffsetFromOrigin() const { return Vector2dF(x(), y()); }
+
+  void SetRect(float x, float y, float width, float height) {
+    origin_.SetPoint(x, y);
+    size_.SetSize(width, height);
+  }
+
+  // Shrink the rectangle by a horizontal and vertical distance on all sides.
+  void Inset(float horizontal, float vertical) {
+    Inset(horizontal, vertical, horizontal, vertical);
+  }
+
+  // Shrink the rectangle by the given insets.
+  void Inset(const InsetsF& insets);
+
+  // Shrink the rectangle by the specified amount on each side.
+  void Inset(float left, float top, float right, float bottom);
+
+  // Move the rectangle by a horizontal and vertical distance.
+  void Offset(float horizontal, float vertical);
+  void Offset(const Vector2dF& distance) { Offset(distance.x(), distance.y()); }
+  void operator+=(const Vector2dF& offset);
+  void operator-=(const Vector2dF& offset);
+
+  InsetsF InsetsFrom(const RectF& inner) const;
+
+  // Returns true if the area of the rectangle is zero.
+  bool IsEmpty() const { return size_.IsEmpty(); }
+
+  // A rect is less than another rect if its origin is less than
+  // the other rect's origin. If the origins are equal, then the
+  // shortest rect is less than the other. If the origin and the
+  // height are equal, then the narrowest rect is less than.
+  // This comparison is required to use Rects in sets, or sorted
+  // vectors.
+  bool operator<(const RectF& other) const;
+
+  // Returns true if the point identified by point_x and point_y falls inside
+  // this rectangle.  The point (x, y) is inside the rectangle, but the
+  // point (x + width, y + height) is not.
+  bool Contains(float point_x, float point_y) const;
+
+  // Returns true if the specified point is contained by this rectangle.
+  bool Contains(const PointF& point) const {
+    return Contains(point.x(), point.y());
+  }
+
+  // Returns true if this rectangle contains the specified rectangle.
+  bool Contains(const RectF& rect) const;
+
+  // Returns true if this rectangle intersects the specified rectangle.
+  // An empty rectangle doesn't intersect any rectangle.
+  bool Intersects(const RectF& rect) const;
+
+  // Computes the intersection of this rectangle with the given rectangle.
+  void Intersect(const RectF& rect);
+
+  // Computes the union of this rectangle with the given rectangle.  The union
+  // is the smallest rectangle containing both rectangles.
+  void Union(const RectF& rect);
+
+  // Computes the rectangle resulting from subtracting |rect| from |*this|,
+  // i.e. the bounding rect of |Region(*this) - Region(rect)|.
+  void Subtract(const RectF& rect);
+
+  // Fits as much of the receiving rectangle into the supplied rectangle as
+  // possible, becoming the result. For example, if the receiver had
+  // a x-location of 2 and a width of 4, and the supplied rectangle had
+  // an x-location of 0 with a width of 5, the returned rectangle would have
+  // an x-location of 1 with a width of 4.
+  void AdjustToFit(const RectF& rect);
+
+  // Returns the center of this rectangle.
+  PointF CenterPoint() const;
+
+  // Becomes a rectangle that has the same center point but with a size capped
+  // at given |size|.
+  void ClampToCenteredSize(const SizeF& size);
+
+  // Splits |this| in two halves, |left_half| and |right_half|.
+  void SplitVertically(RectF* left_half, RectF* right_half) const;
+
+  // Returns true if this rectangle shares an entire edge (i.e., same width or
+  // same height) with the given rectangle, and the rectangles do not overlap.
+  bool SharesEdgeWith(const RectF& rect) const;
+
+  // Returns the manhattan distance from the rect to the point. If the point is
+  // inside the rect, returns 0.
+  float ManhattanDistanceToPoint(const PointF& point) const;
+
+  // Returns the manhattan distance between the contents of this rect and the
+  // contents of the given rect. That is, if the intersection of the two rects
+  // is non-empty then the function returns 0. If the rects share a side, it
+  // returns the smallest non-zero value appropriate for float.
+  float ManhattanInternalDistance(const RectF& rect) const;
+
   // Scales the rectangle by |scale|.
   void Scale(float scale) {
     Scale(scale, scale);
@@ -60,6 +167,10 @@
   bool IsExpressibleAsRect() const;
 
   std::string ToString() const;
+
+ private:
+  PointF origin_;
+  SizeF size_;
 };
 
 inline bool operator==(const RectF& lhs, const RectF& rhs) {
@@ -105,10 +216,6 @@
 // contained within the rect, because they will appear on one of these edges.
 GFX_EXPORT RectF BoundingRect(const PointF& p1, const PointF& p2);
 
-#if !defined(COMPILER_MSVC) && !defined(__native_client__)
-extern template class RectBase<RectF, PointF, SizeF, InsetsF, Vector2dF, float>;
-#endif
-
 // This is declared here for use in gtest-based unit tests but is defined in
 // the gfx_test_support target. Depend on that to use this in your unit test.
 // This should not be used in production code - call ToString() instead.
diff --git a/ui/gfx/geometry/rect_unittest.cc b/ui/gfx/geometry/rect_unittest.cc
index 83597ec..8c8370b 100644
--- a/ui/gfx/geometry/rect_unittest.cc
+++ b/ui/gfx/geometry/rect_unittest.cc
@@ -37,7 +37,7 @@
     {0, 0, -10, -10, 0, 0, false},
   #endif
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(contains_cases); ++i) {
+  for (size_t i = 0; i < arraysize(contains_cases); ++i) {
     const ContainsCase& value = contains_cases[i];
     Rect rect(value.rect_x, value.rect_y, value.rect_width, value.rect_height);
     EXPECT_EQ(value.contained, rect.Contains(value.point_x, value.point_y));
@@ -67,7 +67,7 @@
     { 10, 10, 10, 10, 20, 15, 10, 10, false },
     { 10, 10, 10, 10, 21, 15, 10, 10, false }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
     EXPECT_EQ(tests[i].intersects, r1.Intersects(r2));
@@ -109,7 +109,7 @@
       0, 0, 2, 2,
       0, 0, 0, 0 }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
     Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3);
@@ -158,7 +158,7 @@
       2, 2, 2, 2,
       2, 2, 2, 2 }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
     Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3);
@@ -210,7 +210,7 @@
       0, 0, 3, 3,
       2, 2, 1, 1 }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
     Rect r3(tests[i].x3, tests[i].y3, tests[i].w3, tests[i].h3);
@@ -454,7 +454,7 @@
       std::numeric_limits<float>::max() }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     RectF r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
 
@@ -504,7 +504,7 @@
       0, 0, 0, 0 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
 
@@ -556,7 +556,7 @@
       0, 0, 0, 0 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
 
@@ -600,7 +600,7 @@
       20000, 20000, 0, 0 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     RectF r1(tests[i].x1, tests[i].y1, tests[i].w1, tests[i].h1);
     Rect r2(tests[i].x2, tests[i].y2, tests[i].w2, tests[i].h2);
 
@@ -649,7 +649,7 @@
     }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect result = ScaleToEnclosedRect(tests[i].input_rect,
                                       tests[i].input_scale);
     EXPECT_EQ(tests[i].expected_rect, result);
@@ -693,7 +693,7 @@
     }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Rect result = ScaleToEnclosingRect(tests[i].input_rect,
                                        tests[i].input_scale);
     EXPECT_EQ(tests[i].expected_rect, result);
@@ -743,7 +743,7 @@
     { Point(-4, 6), Point(6, -4), Rect(-4, -4, 10, 10) },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(int_tests); ++i) {
+  for (size_t i = 0; i < arraysize(int_tests); ++i) {
     Rect actual = BoundingRect(int_tests[i].a, int_tests[i].b);
     EXPECT_EQ(int_tests[i].expected, actual);
   }
@@ -780,7 +780,7 @@
       RectF(-4.2f, -4.2f, 11.0f, 11.0f) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_tests); ++i) {
+  for (size_t i = 0; i < arraysize(float_tests); ++i) {
     RectF actual = BoundingRect(float_tests[i].a, float_tests[i].b);
     EXPECT_RECTF_EQ(float_tests[i].expected, actual);
   }
diff --git a/ui/gfx/geometry/scroll_offset_unittest.cc b/ui/gfx/geometry/scroll_offset_unittest.cc
index 4049b83..72073c1 100644
--- a/ui/gfx/geometry/scroll_offset_unittest.cc
+++ b/ui/gfx/geometry/scroll_offset_unittest.cc
@@ -32,7 +32,7 @@
     { ScrollOffset(3.1 - 4.3, 5.1f + 1.3), f1 - f2 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(scroll_offset_tests); ++i)
+  for (size_t i = 0; i < arraysize(scroll_offset_tests); ++i)
     EXPECT_EQ(scroll_offset_tests[i].expected.ToString(),
               scroll_offset_tests[i].actual.ToString());
 }
@@ -48,7 +48,7 @@
     { ScrollOffset(0.3, -0.3), -ScrollOffset(-0.3, 0.3) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(scroll_offset_tests); ++i)
+  for (size_t i = 0; i < arraysize(scroll_offset_tests); ++i)
     EXPECT_EQ(scroll_offset_tests[i].expected.ToString(),
               scroll_offset_tests[i].actual.ToString());
 }
@@ -66,7 +66,7 @@
     { 0, 1.2, 3.3, 5.6 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(double_values); ++i) {
+  for (size_t i = 0; i < arraysize(double_values); ++i) {
     ScrollOffset v(double_values[i][0], double_values[i][1]);
     v.Scale(double_values[i][2], double_values[i][3]);
     EXPECT_EQ(v.x(), double_values[i][0] * double_values[i][2]);
@@ -85,7 +85,7 @@
     { 0, 1.2, 3.3 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(single_values); ++i) {
+  for (size_t i = 0; i < arraysize(single_values); ++i) {
     ScrollOffset v(single_values[i][0], single_values[i][1]);
     v.Scale(single_values[i][2]);
     EXPECT_EQ(v.x(), single_values[i][0] * single_values[i][2]);
diff --git a/ui/gfx/geometry/vector2d_unittest.cc b/ui/gfx/geometry/vector2d_unittest.cc
index 38af694..b87609f 100644
--- a/ui/gfx/geometry/vector2d_unittest.cc
+++ b/ui/gfx/geometry/vector2d_unittest.cc
@@ -43,7 +43,7 @@
     { Vector2d(3 - 4, 5 + 1), i1 - i2 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(int_tests); ++i)
+  for (size_t i = 0; i < arraysize(int_tests); ++i)
     EXPECT_EQ(int_tests[i].expected.ToString(),
               int_tests[i].actual.ToString());
 
@@ -60,7 +60,7 @@
     { Vector2dF(3.1f - 4.3f, 5.1f + 1.3f), f1 - f2 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_tests); ++i)
+  for (size_t i = 0; i < arraysize(float_tests); ++i)
     EXPECT_EQ(float_tests[i].expected.ToString(),
               float_tests[i].actual.ToString());
 }
@@ -77,7 +77,7 @@
     { Vector2d(3, -3), -Vector2d(-3, 3) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(int_tests); ++i)
+  for (size_t i = 0; i < arraysize(int_tests); ++i)
     EXPECT_EQ(int_tests[i].expected.ToString(),
               int_tests[i].actual.ToString());
 
@@ -92,7 +92,7 @@
     { Vector2dF(0.3f, -0.3f), -Vector2dF(-0.3f, 0.3f) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_tests); ++i)
+  for (size_t i = 0; i < arraysize(float_tests); ++i)
     EXPECT_EQ(float_tests[i].expected.ToString(),
               float_tests[i].actual.ToString());
 }
@@ -110,7 +110,7 @@
     { 0, 1.2f, 3.3f, 5.6f }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(double_values); ++i) {
+  for (size_t i = 0; i < arraysize(double_values); ++i) {
     Vector2dF v(double_values[i][0], double_values[i][1]);
     v.Scale(double_values[i][2], double_values[i][3]);
     EXPECT_EQ(v.x(), double_values[i][0] * double_values[i][2]);
@@ -135,7 +135,7 @@
     { 0, 1.2f, 3.3f }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(single_values); ++i) {
+  for (size_t i = 0; i < arraysize(single_values); ++i) {
     Vector2dF v(single_values[i][0], single_values[i][1]);
     v.Scale(single_values[i][2]);
     EXPECT_EQ(v.x(), single_values[i][0] * single_values[i][2]);
@@ -159,7 +159,7 @@
     { 10, -20 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(int_values); ++i) {
+  for (size_t i = 0; i < arraysize(int_values); ++i) {
     int v0 = int_values[i][0];
     int v1 = int_values[i][1];
     double length_squared =
@@ -183,7 +183,7 @@
       335890352589839028212313231225425134332.38123f },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_values); ++i) {
+  for (size_t i = 0; i < arraysize(float_values); ++i) {
     double v0 = float_values[i][0];
     double v1 = float_values[i][1];
     double length_squared =
diff --git a/ui/gfx/geometry/vector3d_unittest.cc b/ui/gfx/geometry/vector3d_unittest.cc
index d5ec8d6..d058ad1 100644
--- a/ui/gfx/geometry/vector3d_unittest.cc
+++ b/ui/gfx/geometry/vector3d_unittest.cc
@@ -32,7 +32,7 @@
     { gfx::Vector3dF(3.1f - 4.3f, 5.1f + 1.3f, 2.7f - 8.1f), f1 - f2 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_tests); ++i)
+  for (size_t i = 0; i < arraysize(float_tests); ++i)
     EXPECT_EQ(float_tests[i].expected.ToString(),
               float_tests[i].actual.ToString());
 }
@@ -50,7 +50,7 @@
     { gfx::Vector3dF(-0.3f, -0.3f, 0.3f), -gfx::Vector3dF(0.3f, 0.3f, -0.3f) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_tests); ++i)
+  for (size_t i = 0; i < arraysize(float_tests); ++i)
     EXPECT_EQ(float_tests[i].expected.ToString(),
               float_tests[i].actual.ToString());
 }
@@ -83,7 +83,7 @@
     { 0, 1.2f, 1.8f, 3.3f, 5.6f, 4.2f }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(triple_values); ++i) {
+  for (size_t i = 0; i < arraysize(triple_values); ++i) {
     gfx::Vector3dF v(triple_values[i][0],
                      triple_values[i][1],
                      triple_values[i][2]);
@@ -119,7 +119,7 @@
     { 4.5f, 1.2f, 0, 3.3f }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(single_values); ++i) {
+  for (size_t i = 0; i < arraysize(single_values); ++i) {
     gfx::Vector3dF v(single_values[i][0],
                      single_values[i][1],
                      single_values[i][2]);
@@ -161,7 +161,7 @@
       27861786423846742743236423478236784678.236713617231f }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(float_values); ++i) {
+  for (size_t i = 0; i < arraysize(float_values); ++i) {
     double v0 = float_values[i][0];
     double v1 = float_values[i][1];
     double v2 = float_values[i][2];
@@ -195,7 +195,7 @@
       gfx::Vector3dF(1.1f, 2.2f, 3.3f), gfx::Vector3dF(4.4f, 5.5f, 6.6f) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     float actual = gfx::DotProduct(tests[i].input1, tests[i].input2);
     EXPECT_EQ(tests[i].expected, actual);
   }
@@ -223,7 +223,7 @@
     { Vector3dF(0, -1, 1), Vector3dF(1, 0, 0), Vector3dF(1, 1, 1) }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
+  for (size_t i = 0; i < arraysize(tests); ++i) {
     Vector3dF actual = gfx::CrossProduct(tests[i].input1, tests[i].input2);
     EXPECT_EQ(tests[i].expected.ToString(), actual.ToString());
   }
diff --git a/ui/gfx/gfx.gyp b/ui/gfx/gfx.gyp
index edd4394..b385459 100644
--- a/ui/gfx/gfx.gyp
+++ b/ui/gfx/gfx.gyp
@@ -41,8 +41,6 @@
         'geometry/quad_f.h',
         'geometry/rect.cc',
         'geometry/rect.h',
-        'geometry/rect_base.h',
-        'geometry/rect_base_impl.h',
         'geometry/rect_conversions.cc',
         'geometry/rect_conversions.h',
         'geometry/rect_f.cc',
diff --git a/ui/gfx/image/image_skia.cc b/ui/gfx/image/image_skia.cc
index bba6c47..b6d9d8d 100644
--- a/ui/gfx/image/image_skia.cc
+++ b/ui/gfx/image/image_skia.cc
@@ -56,8 +56,7 @@
 };
 
 ImageSkiaRep ScaleImageSkiaRep(const ImageSkiaRep& rep, float target_scale) {
-  DCHECK_NE(rep.scale(), target_scale);
-  if (rep.is_null())
+  if (rep.is_null() || rep.scale() == target_scale)
     return rep;
 
   gfx::Size scaled_size = ToCeiledSize(
diff --git a/ui/gfx/render_text.cc b/ui/gfx/render_text.cc
index d5d4011..8c516c1 100644
--- a/ui/gfx/render_text.cc
+++ b/ui/gfx/render_text.cc
@@ -393,15 +393,20 @@
 }
 
 RenderText* RenderText::CreateInstance() {
-#if defined(OS_MACOSX) && defined(TOOLKIT_VIEWS)
-  // Use the more complete HarfBuzz implementation for Views controls on Mac.
-  return new RenderTextHarfBuzz;
-#else
   if (CommandLine::ForCurrentProcess()->HasSwitch(
           switches::kEnableHarfBuzzRenderText)) {
     return new RenderTextHarfBuzz;
   }
+  if (CommandLine::ForCurrentProcess()->HasSwitch(
+          switches::kDisableHarfBuzzRenderText)) {
+    return CreateNativeInstance();
+  }
+
+// Disable on Chrome OS. Blocked on http://crbug.com/423791
+#if defined(OS_CHROMEOS)
   return CreateNativeInstance();
+#else
+  return new RenderTextHarfBuzz;
 #endif
 }
 
@@ -1255,8 +1260,7 @@
   size_t hi = text.length() - 1;
   const base::i18n::TextDirection text_direction = GetTextDirection();
   for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) {
-    // Restore styles and colors. They will be truncated to size by SetText.
-    render_text->styles_ = styles_;
+    // Restore colors. They will be truncated to size by SetText.
     render_text->colors_ = colors_;
     base::string16 new_text =
         slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL);
@@ -1282,6 +1286,25 @@
       render_text->SetText(new_text);
     }
 
+    // Restore styles. Make sure style ranges don't break new text graphemes.
+    render_text->styles_ = styles_;
+    for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) {
+      BreakList<bool>& break_list = render_text->styles_[style];
+      break_list.SetMax(render_text->text_.length());
+      Range range;
+      while (range.end() < break_list.max()) {
+        BreakList<bool>::const_iterator current_break =
+            break_list.GetBreak(range.end());
+        range = break_list.GetRange(current_break);
+        if (range.end() < break_list.max() &&
+            !render_text->IsValidCursorIndex(range.end())) {
+          range.set_end(render_text->IndexOfAdjacentGrapheme(range.end(),
+                                                             CURSOR_FORWARD));
+          break_list.ApplyValue(current_break->second, range);
+        }
+      }
+    }
+
     // We check the width of the whole desired string at once to ensure we
     // handle kerning/ligatures/etc. correctly.
     const float guess_width = render_text->GetContentWidth();
diff --git a/ui/gfx/render_text.h b/ui/gfx/render_text.h
index 4cc8e49..9dc353a 100644
--- a/ui/gfx/render_text.h
+++ b/ui/gfx/render_text.h
@@ -581,6 +581,7 @@
   FRIEND_TEST_ALL_PREFIXES(RenderTextTest, SameFontForParentheses);
   FRIEND_TEST_ALL_PREFIXES(RenderTextTest, BreakRunsByUnicodeBlocks);
   FRIEND_TEST_ALL_PREFIXES(RenderTextTest, PangoAttributes);
+  FRIEND_TEST_ALL_PREFIXES(RenderTextTest, StringFitsOwnWidth);
 
   // Creates a platform-specific RenderText instance.
   static RenderText* CreateNativeInstance();
diff --git a/ui/gfx/render_text_unittest.cc b/ui/gfx/render_text_unittest.cc
index 5d377e7..10a0a90 100644
--- a/ui/gfx/render_text_unittest.cc
+++ b/ui/gfx/render_text_unittest.cc
@@ -229,7 +229,7 @@
   rt_linux->EnsureLayout();
   PangoAttrList* attributes = pango_layout_get_attributes(rt_linux->layout_);
   PangoAttrIterator* iter = pango_attr_list_get_iterator(attributes);
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     pango_attr_iterator_range(iter, &start, &end);
     EXPECT_EQ(cases[i].start, start);
     EXPECT_EQ(cases[i].end, end);
@@ -468,7 +468,7 @@
   render_text->SetFontList(FontList("serif, Sans serif, 12px"));
   render_text->SetElideBehavior(ELIDE_TAIL);
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     // Compute expected width
     expected_render_text->SetText(WideToUTF16(cases[i].layout_text));
     int expected_width = expected_render_text->GetContentWidth();
@@ -543,7 +543,7 @@
 
   scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
   render_text->set_truncate_length(5);
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     render_text->SetText(WideToUTF16(cases[i].text));
     EXPECT_EQ(WideToUTF16(cases[i].text), render_text->text());
     EXPECT_EQ(WideToUTF16(cases[i].layout_text), render_text->GetLayoutText())
@@ -644,7 +644,7 @@
         base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT;
 
     // Ensure that directionality modes yield the correct text directions.
-    for (size_t j = 0; j < ARRAYSIZE_UNSAFE(cases); j++) {
+    for (size_t j = 0; j < arraysize(cases); j++) {
       render_text->SetText(WideToUTF16(cases[j].text));
       render_text->SetDirectionalityMode(DIRECTIONALITY_FROM_TEXT);
       EXPECT_EQ(render_text->GetTextDirection(), cases[j].text_direction);
@@ -919,7 +919,7 @@
 #endif
 
   scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     SCOPED_TRACE(base::StringPrintf("Testing cases[%" PRIuS "]", i));
     render_text->SetText(cases[i].text);
 
@@ -1016,7 +1016,7 @@
 #endif
 
   scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     render_text->SetText(cases[i].text);
     bool ltr = (cases[i].expected_text_direction == base::i18n::LEFT_TO_RIGHT);
 
@@ -1048,7 +1048,7 @@
     EXPECT_EQ(render_text->selection_model(), SelectionModel());
 
     // Test the weak, LTR, RTL, and Bidi string cases.
-    for (size_t j = 0; j < ARRAYSIZE_UNSAFE(cases); j++) {
+    for (size_t j = 0; j < arraysize(cases); j++) {
       render_text->SetText(WideToUTF16(cases[j]));
       render_text->SelectAll(false);
       EXPECT_EQ(render_text->selection_model(), expected_forwards);
@@ -1454,7 +1454,7 @@
   const FontList& larger_font_list = default_font_list.DeriveWithSizeDelta(24);
   EXPECT_GT(larger_font_list.GetHeight(), default_font_list.GetHeight());
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
     render_text->SetFontList(default_font_list);
     render_text->SetText(cases[i]);
@@ -1589,7 +1589,7 @@
     { ALIGN_CENTER, kEnlargement },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(small_content_cases); i++) {
+  for (size_t i = 0; i < arraysize(small_content_cases); i++) {
     render_text->SetHorizontalAlignment(small_content_cases[i].alignment);
     render_text->SetDisplayOffset(small_content_cases[i].offset);
     EXPECT_EQ(0, render_text->GetUpdatedDisplayOffset().x());
@@ -1624,7 +1624,7 @@
     { ALIGN_CENTER, kEnlargement, (kEnlargement - 1) / 2 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(large_content_cases); i++) {
+  for (size_t i = 0; i < arraysize(large_content_cases); i++) {
     render_text->SetHorizontalAlignment(large_content_cases[i].alignment);
     render_text->SetDisplayOffset(large_content_cases[i].offset);
     EXPECT_EQ(large_content_cases[i].expected_offset,
@@ -1672,14 +1672,14 @@
   };
 
   scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     base::string16 text = cases[i].text;
     const size_t start_paren_char_index = text.find('(');
     ASSERT_NE(base::string16::npos, start_paren_char_index);
     const size_t end_paren_char_index = text.find(')');
     ASSERT_NE(base::string16::npos, end_paren_char_index);
 
-    for (size_t j = 0; j < ARRAYSIZE_UNSAFE(punctuation_pairs); ++j) {
+    for (size_t j = 0; j < arraysize(punctuation_pairs); ++j) {
       text[start_paren_char_index] = punctuation_pairs[j].left_char;
       text[end_paren_char_index] = punctuation_pairs[j].right_char;
       render_text->SetText(text);
@@ -1743,7 +1743,7 @@
     { 16, 13, 16 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     render_text->SetCursorPosition(cases[i].cursor);
     render_text->SelectWord();
     EXPECT_EQ(Range(cases[i].selection_start, cases[i].selection_end),
@@ -1969,7 +1969,7 @@
   render_text->SetMultiline(true);
   Canvas canvas;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestStrings); ++i) {
+  for (size_t i = 0; i < arraysize(kTestStrings); ++i) {
     SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i));
     render_text->SetText(WideToUTF16(kTestStrings[i].text));
     render_text->Draw(&canvas);
@@ -2023,7 +2023,7 @@
   render_text->SetMultiline(true);
   Canvas canvas;
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestStrings); ++i) {
+  for (size_t i = 0; i < arraysize(kTestStrings); ++i) {
     SCOPED_TRACE(base::StringPrintf("kTestStrings[%" PRIuS "]", i));
     render_text->SetText(WideToUTF16(kTestStrings[i].text));
     render_text->Draw(&canvas);
@@ -2112,7 +2112,7 @@
   run.glyph_count = 4;
   run.glyph_to_char.resize(4);
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::copy(cases[i].glyph_to_char, cases[i].glyph_to_char + 4,
               run.glyph_to_char.begin());
     run.is_rtl = cases[i].is_rtl;
@@ -2201,7 +2201,7 @@
       kString, base::i18n::BreakIterator::BREAK_CHARACTER));
   ASSERT_TRUE(iter->Init());
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::copy(cases[i].glyph_to_char, cases[i].glyph_to_char + 2,
               run.glyph_to_char.begin());
     run.is_rtl = cases[i].is_rtl;
@@ -2309,4 +2309,19 @@
   EXPECT_EQ(Range(0, 0), glyphs);
 }
 
+// Ensure a string fits in a display rect with a width equal to the string's.
+TEST_F(RenderTextTest, StringFitsOwnWidth) {
+  scoped_ptr<RenderText> render_text(RenderText::CreateInstance());
+  const base::string16 kString = ASCIIToUTF16("www.example.com");
+
+  render_text->SetText(kString);
+  render_text->ApplyStyle(BOLD, true, Range(0, 3));
+  render_text->SetElideBehavior(ELIDE_TAIL);
+
+  render_text->SetDisplayRect(Rect(0, 0, 500, 100));
+  EXPECT_EQ(kString, render_text->GetLayoutText());
+  render_text->SetDisplayRect(Rect(0, 0, render_text->GetContentWidth(), 100));
+  EXPECT_EQ(kString, render_text->GetLayoutText());
+}
+
 }  // namespace gfx
diff --git a/ui/gfx/shadow_value_unittest.cc b/ui/gfx/shadow_value_unittest.cc
index 57515dc..bf19664 100644
--- a/ui/gfx/shadow_value_unittest.cc
+++ b/ui/gfx/shadow_value_unittest.cc
@@ -51,7 +51,7 @@
     },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestCases); ++i) {
+  for (size_t i = 0; i < arraysize(kTestCases); ++i) {
     Insets margin = ShadowValue::GetMargin(
         ShadowValues(kTestCases[i].shadows,
                      kTestCases[i].shadows + kTestCases[i].shadow_count));
diff --git a/ui/gfx/text_elider_unittest.cc b/ui/gfx/text_elider_unittest.cc
index 72630f2..8bf3f65 100644
--- a/ui/gfx/text_elider_unittest.cc
+++ b/ui/gfx/text_elider_unittest.cc
@@ -223,7 +223,7 @@
     { "Tests", kTestWidth, "Test" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     base::string16 result = ElideText(UTF8ToUTF16(cases[i].input), font_list,
                                       cases[i].width, TRUNCATE);
     EXPECT_EQ(cases[i].output, UTF16ToUTF8(result));
@@ -255,7 +255,7 @@
     { "Test", kTestWidth, "Test" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     base::string16 result = ElideText(UTF8ToUTF16(cases[i].input), font_list,
                                       cases[i].width, ELIDE_TAIL);
     EXPECT_EQ(cases[i].output, UTF16ToUTF8(result));
@@ -290,7 +290,7 @@
     { "Test123", kEllipsis23Width, UTF8ToUTF16(kEllipsisStr + "23") },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     base::string16 result = ElideText(UTF8ToUTF16(cases[i].input), font_list,
                                       cases[i].width, ELIDE_HEAD);
     EXPECT_EQ(cases[i].output, result);
@@ -458,7 +458,7 @@
     { "Hello, my name is Tom", 10, true, "Hell...Tom" },
     { "Hello, my name is Tom", 100, false, "Hello, my name is Tom" }
   };
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     base::string16 output;
     EXPECT_EQ(cases[i].result,
               ElideString(UTF8ToUTF16(cases[i].input),
@@ -512,7 +512,7 @@
     { "Te  Te Test", test_width, 3 * line_height, false, "Te|Te|Test" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::vector<base::string16> lines;
     EXPECT_EQ(cases[i].truncated_y ? INSUFFICIENT_SPACE_VERTICAL : 0,
               ElideRectangleText(UTF8ToUTF16(cases[i].input),
@@ -557,7 +557,7 @@
     { "Test. Test", test_width, line_height * 3, true, false, "Test|.|Test" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::vector<base::string16> lines;
     const WordWrapBehavior wrap_behavior =
         (cases[i].wrap_words ? WRAP_LONG_WORDS : TRUNCATE_LONG_WORDS);
@@ -627,7 +627,7 @@
     { "TestTestTestT", test_width, WRAP_LONG_WORDS, false, "Test|Test|Test|T" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     std::vector<base::string16> lines;
     EXPECT_EQ(cases[i].truncated_x ? INSUFFICIENT_SPACE_HORIZONTAL : 0,
               ElideRectangleText(UTF8ToUTF16(cases[i].input),
@@ -750,7 +750,7 @@
     { "Hi, my name is Tom",  1, 40, false, "Hi, my name is Tom" },
   };
   base::string16 output;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     EXPECT_EQ(cases[i].result,
               ElideRectangleString(UTF8ToUTF16(cases[i].input),
                                    cases[i].max_rows, cases[i].max_cols,
@@ -832,7 +832,7 @@
     { "Hi, my name_is Dick",  1, 40, false, "Hi, my name_is Dick" },
   };
   base::string16 output;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     EXPECT_EQ(cases[i].result,
               ElideRectangleString(UTF8ToUTF16(cases[i].input),
                                    cases[i].max_rows, cases[i].max_cols,
diff --git a/ui/gfx/text_utils_unittest.cc b/ui/gfx/text_utils_unittest.cc
index 0c0127f..8c6c7b0 100644
--- a/ui/gfx/text_utils_unittest.cc
+++ b/ui/gfx/text_utils_unittest.cc
@@ -46,7 +46,7 @@
       "Test\xF0\x9D\x92\x9C\xF0\x9D\x92\x9Cing" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     int accelerated_char_pos;
     int accelerated_char_span;
     base::string16 result = RemoveAcceleratorChar(
diff --git a/ui/gfx/transform_unittest.cc b/ui/gfx/transform_unittest.cc
index 77b28ca..ef801ac 100644
--- a/ui/gfx/transform_unittest.cc
+++ b/ui/gfx/transform_unittest.cc
@@ -228,7 +228,7 @@
   };
 
   Transform xform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     Transform translation;
     translation.Translate(value.tx, value.ty);
@@ -257,7 +257,7 @@
   };
 
   Transform xform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     Transform scale;
     scale.Scale(value.scale, value.scale);
@@ -288,7 +288,7 @@
   };
 
   Transform xform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     Transform rotation;
     rotation.Rotate(value.degrees);
@@ -317,7 +317,7 @@
       0, 0 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     for (int k = 0; k < 3; ++k) {
       Point3F p0, p1, p2;
@@ -364,7 +364,7 @@
     { 1, std::numeric_limits<float>::quiet_NaN(), 0 },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     for (int k = 0; k < 3; ++k) {
       Point3F p0, p1, p2;
@@ -417,7 +417,7 @@
     { 100, 0, 360.0f, 100, 0 }
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(set_rotate_cases); ++i) {
+  for (size_t i = 0; i < arraysize(set_rotate_cases); ++i) {
     const SetRotateCase& value = set_rotate_cases[i];
     Point3F p0;
     Point3F p1(value.x, value.y, 0);
@@ -455,7 +455,7 @@
   };
 
   Transform xform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     Transform translation;
     translation.Translate(value.tx, value.ty);
@@ -485,7 +485,7 @@
   };
 
   Transform xform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     Transform scale;
     scale.Scale(value.scale, value.scale);
@@ -517,7 +517,7 @@
   };
 
   Transform xform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     Transform rotation;
     rotation.Rotate(value.degrees);
@@ -547,7 +547,7 @@
       0, 0}
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     for (int j = -1; j < 2; ++j) {
       for (int k = 0; k < 3; ++k) {
@@ -600,7 +600,7 @@
     { 1, std::numeric_limits<float>::quiet_NaN(), 0},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     for (int j = -1; j < 2; ++j) {
       for (int k = 0; k < 3; ++k) {
@@ -661,7 +661,7 @@
     { 100, 0, 360.0f, 100, 0}
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(set_rotate_cases); ++i) {
+  for (size_t i = 0; i < arraysize(set_rotate_cases); ++i) {
     const SetRotateCase& value = set_rotate_cases[i];
     for (int j = 1; j >= -1; --j) {
       float epsilon = 0.1f;
@@ -720,7 +720,7 @@
     Vector3dF(1, 1, 1)
   };
   Transform from;
-  for (size_t index = 0; index < ARRAYSIZE_UNSAFE(axes); ++index) {
+  for (size_t index = 0; index < arraysize(axes); ++index) {
     for (int i = -5; i < 15; ++i) {
       Transform to;
       to.RotateAbout(axes[index], 90);
@@ -750,7 +750,7 @@
     Vector3dF(0, 0, 1),
     Vector3dF(1, 1, 1)
   };
-  for (size_t index = 0; index < ARRAYSIZE_UNSAFE(axes); ++index) {
+  for (size_t index = 0; index < arraysize(axes); ++index) {
     for (int i = -5; i < 15; ++i) {
       Transform from1;
       from1.RotateAbout(axes[index], 130.0);
@@ -786,7 +786,7 @@
     Vector3dF(1, 1, 1)
   };
   Transform from;
-  for (size_t index = 0; index < ARRAYSIZE_UNSAFE(axes); ++index) {
+  for (size_t index = 0; index < arraysize(axes); ++index) {
     for (int i = -5; i < 15; ++i) {
       Transform to;
       to.RotateAbout(axes[index], 180.0);
@@ -2487,7 +2487,7 @@
   };
 
   Transform transform;
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     transform.MakeIdentity();
     transform.matrix().set(0, 0, value.a);
@@ -2506,7 +2506,7 @@
 
   // Try the same test cases again, but this time make sure that other matrix
   // elements (except perspective) have entries, to test that they are ignored.
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     transform.MakeIdentity();
     transform.matrix().set(0, 0, value.a);
@@ -2534,7 +2534,7 @@
 
   // Try the same test cases again, but this time add perspective which is
   // always assumed to not-preserve axis alignment.
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+  for (size_t i = 0; i < arraysize(test_cases); ++i) {
     const TestCase& value = test_cases[i];
     transform.MakeIdentity();
     transform.matrix().set(0, 0, value.a);
diff --git a/ui/gl/PRESUBMIT.py b/ui/gl/PRESUBMIT.py
deleted file mode 100644
index 67ad991..0000000
--- a/ui/gl/PRESUBMIT.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright (c) 2014 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Top-level presubmit script for ui/gl/.
-
-See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
-for more details about the presubmit API built into depot_tools.
-"""
-
-def GetPreferredTryMasters(project, change):
-  return {
-    'tryserver.chromium.gpu': {
-      'linux_gpu': set(['defaulttests']),
-      'mac_gpu': set(['defaulttests']),
-      'win_gpu': set(['defaulttests']),
-    }
-  }
diff --git a/ui/gl/gl_implementation.cc b/ui/gl/gl_implementation.cc
index 9d6b34e..74b95b8 100644
--- a/ui/gl/gl_implementation.cc
+++ b/ui/gl/gl_implementation.cc
@@ -72,7 +72,7 @@
 #endif
 
 GLImplementation GetNamedGLImplementation(const std::string& name) {
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGLImplementationNamePairs); ++i) {
+  for (size_t i = 0; i < arraysize(kGLImplementationNamePairs); ++i) {
     if (name == kGLImplementationNamePairs[i].name)
       return kGLImplementationNamePairs[i].implementation;
   }
@@ -81,7 +81,7 @@
 }
 
 const char* GetGLImplementationName(GLImplementation implementation) {
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGLImplementationNamePairs); ++i) {
+  for (size_t i = 0; i < arraysize(kGLImplementationNamePairs); ++i) {
     if (implementation == kGLImplementationNamePairs[i].implementation)
       return kGLImplementationNamePairs[i].name;
   }
diff --git a/ui/gl/gl_surface_wgl.cc b/ui/gl/gl_surface_wgl.cc
index 690f4f4..66cef26 100644
--- a/ui/gl/gl_surface_wgl.cc
+++ b/ui/gl/gl_surface_wgl.cc
@@ -99,16 +99,18 @@
       return false;
     }
 
-    window_handle_ = CreateWindow(
-        reinterpret_cast<wchar_t*>(window_class_),
-        L"",
-        WS_OVERLAPPEDWINDOW,
-        0, 0,
-        100, 100,
-        NULL,
-        NULL,
-        NULL,
-        NULL);
+    window_handle_ = CreateWindowEx(WS_EX_NOPARENTNOTIFY,
+                                    reinterpret_cast<wchar_t*>(window_class_),
+                                    L"",
+                                    WS_OVERLAPPEDWINDOW,
+                                    0,
+                                    0,
+                                    100,
+                                    100,
+                                    NULL,
+                                    NULL,
+                                    NULL,
+                                    NULL);
     if (!window_handle_) {
       LOG(ERROR) << "CreateWindow failed.";
       return false;
@@ -175,8 +177,7 @@
 }
 
 NativeViewGLSurfaceWGL::NativeViewGLSurfaceWGL(gfx::AcceleratedWidget window)
-    : window_(window),
-      device_context_(NULL) {
+    : window_(window), child_window_(NULL), device_context_(NULL) {
   DCHECK(window);
 }
 
@@ -187,16 +188,36 @@
 bool NativeViewGLSurfaceWGL::Initialize() {
   DCHECK(!device_context_);
 
-  DWORD process_id;
-  GetWindowThreadProcessId(window_, &process_id);
-  if (process_id != GetCurrentProcessId()) {
-    LOG(ERROR) << "Can't use window created in " << process_id
-               << " with wgl in " << GetCurrentProcessId();
+  RECT rect;
+  if (!GetClientRect(window_, &rect)) {
+    LOG(ERROR) << "GetClientRect failed.\n";
     Destroy();
     return false;
   }
 
-  device_context_ = GetDC(window_);
+  // Create a child window. WGL has problems using a window handle owned by
+  // another process.
+  child_window_ =
+      CreateWindowEx(WS_EX_NOPARENTNOTIFY,
+                     reinterpret_cast<wchar_t*>(g_display->window_class()),
+                     L"",
+                     WS_CHILDWINDOW | WS_DISABLED | WS_VISIBLE,
+                     0,
+                     0,
+                     rect.right - rect.left,
+                     rect.bottom - rect.top,
+                     window_,
+                     NULL,
+                     NULL,
+                     NULL);
+  if (!child_window_) {
+    LOG(ERROR) << "CreateWindow failed.\n";
+    Destroy();
+    return false;
+  }
+
+  // The GL context will render to this window.
+  device_context_ = GetDC(child_window_);
   if (!device_context_) {
     LOG(ERROR) << "Unable to get device context for window.";
     Destroy();
@@ -215,9 +236,13 @@
 }
 
 void NativeViewGLSurfaceWGL::Destroy() {
-  if (window_ && device_context_)
-    ReleaseDC(window_, device_context_);
+  if (child_window_ && device_context_)
+    ReleaseDC(child_window_, device_context_);
 
+  if (child_window_)
+    DestroyWindow(child_window_);
+
+  child_window_ = NULL;
   device_context_ = NULL;
 }
 
@@ -230,13 +255,27 @@
       "width", GetSize().width(),
       "height", GetSize().height());
 
+  // Resize the child window to match the parent before swapping. Do not repaint
+  // it as it moves.
+  RECT rect;
+  if (!GetClientRect(window_, &rect))
+    return false;
+  if (!MoveWindow(child_window_,
+                  0,
+                  0,
+                  rect.right - rect.left,
+                  rect.bottom - rect.top,
+                  FALSE)) {
+    return false;
+  }
+
   DCHECK(device_context_);
   return ::SwapBuffers(device_context_) == TRUE;
 }
 
 gfx::Size NativeViewGLSurfaceWGL::GetSize() {
   RECT rect;
-  BOOL result = GetClientRect(window_, &rect);
+  BOOL result = GetClientRect(child_window_, &rect);
   DCHECK(result);
   return gfx::Size(rect.right - rect.left, rect.bottom - rect.top);
 }
diff --git a/ui/gl/gl_surface_wgl.h b/ui/gl/gl_surface_wgl.h
index 18b7e84..aa32047 100644
--- a/ui/gl/gl_surface_wgl.h
+++ b/ui/gl/gl_surface_wgl.h
@@ -42,6 +42,7 @@
 
  private:
   gfx::AcceleratedWidget window_;
+  gfx::AcceleratedWidget child_window_;
   HDC device_context_;
 
   DISALLOW_COPY_AND_ASSIGN(NativeViewGLSurfaceWGL);
diff --git a/ui/message_center/notification_list.h b/ui/message_center/notification_list.h
index c07df61..7b49994 100644
--- a/ui/message_center/notification_list.h
+++ b/ui/message_center/notification_list.h
@@ -38,7 +38,7 @@
   bool operator()(Notification* n1, Notification* n2);
 };
 
-struct CompareTimestampSerial {
+struct MESSAGE_CENTER_EXPORT CompareTimestampSerial {
   bool operator()(Notification* n1, Notification* n2);
 };
 
diff --git a/ui/ozone/platform/caca/caca_window_manager.cc b/ui/ozone/platform/caca/caca_window_manager.cc
index 247ba28..0c3a43e 100644
--- a/ui/ozone/platform/caca/caca_window_manager.cc
+++ b/ui/ozone/platform/caca/caca_window_manager.cc
@@ -135,7 +135,7 @@
   scoped_ptr<CacaSurface> canvas(new CacaSurface(window));
   bool initialized = canvas->Initialize();
   DCHECK(initialized);
-  return canvas.PassAs<ui::SurfaceOzoneCanvas>();
+  return canvas.Pass();
 }
 
 }  // namespace ui
diff --git a/ui/ozone/platform/caca/ozone_platform_caca.cc b/ui/ozone/platform/caca/ozone_platform_caca.cc
index a34f014..c3b3233 100644
--- a/ui/ozone/platform/caca/ozone_platform_caca.cc
+++ b/ui/ozone/platform/caca/ozone_platform_caca.cc
@@ -39,8 +39,8 @@
     scoped_ptr<CacaWindow> caca_window(new CacaWindow(
         delegate, window_manager_.get(), event_source_.get(), bounds));
     if (!caca_window->Initialize())
-      return scoped_ptr<PlatformWindow>();
-    return caca_window.PassAs<PlatformWindow>();
+      return nullptr;
+    return caca_window.Pass();
   }
   virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate()
       override {
diff --git a/ui/ozone/platform/dri/gbm_surface_factory.cc b/ui/ozone/platform/dri/gbm_surface_factory.cc
index 59f6a4c..e04ae8e 100644
--- a/ui/ozone/platform/dri/gbm_surface_factory.cc
+++ b/ui/ozone/platform/dri/gbm_surface_factory.cc
@@ -153,9 +153,9 @@
 
   scoped_ptr<GbmSurface> surface(new GbmSurface(delegate, device_, drm_));
   if (!surface->Initialize())
-    return scoped_ptr<SurfaceOzoneEGL>();
+    return nullptr;
 
-  return surface.PassAs<SurfaceOzoneEGL>();
+  return surface.Pass();
 }
 
 scoped_ptr<SurfaceOzoneEGL>
diff --git a/ui/ozone/platform/dri/ozone_platform_dri.cc b/ui/ozone/platform/dri/ozone_platform_dri.cc
index 88d6207..63750e2 100644
--- a/ui/ozone/platform/dri/ozone_platform_dri.cc
+++ b/ui/ozone/platform/dri/ozone_platform_dri.cc
@@ -72,7 +72,7 @@
                       event_factory_ozone_.get(),
                       window_manager_.get()));
     platform_window->Initialize();
-    return platform_window.PassAs<PlatformWindow>();
+    return platform_window.Pass();
   }
   virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate()
       override {
diff --git a/ui/ozone/platform/dri/ozone_platform_gbm.cc b/ui/ozone/platform/dri/ozone_platform_gbm.cc
index 737689c..344422b 100644
--- a/ui/ozone/platform/dri/ozone_platform_gbm.cc
+++ b/ui/ozone/platform/dri/ozone_platform_gbm.cc
@@ -104,7 +104,7 @@
                       event_factory_ozone_.get(),
                       window_manager_.get()));
     platform_window->Initialize();
-    return platform_window.PassAs<PlatformWindow>();
+    return platform_window.Pass();
   }
   virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate()
       override {
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn
index 93abc4d..1b1b6bf 100644
--- a/ui/views/BUILD.gn
+++ b/ui/views/BUILD.gn
@@ -104,8 +104,6 @@
   }
 }
 
-if (false) {
-
 static_library("test_support") {
   testonly = true
   sources = gypi_values.views_test_support_sources
@@ -115,6 +113,7 @@
   ]
   deps = [
     "//base",
+    "//ipc:test_support",
     "//skia",
     "//testing/gtest",
     "//ui/aura",
@@ -263,5 +262,3 @@
     ]
   }
 }
-
-}  # if (false)
diff --git a/ui/views/bubble/bubble_delegate_unittest.cc b/ui/views/bubble/bubble_delegate_unittest.cc
index c3ba170..c793f54 100644
--- a/ui/views/bubble/bubble_delegate_unittest.cc
+++ b/ui/views/bubble/bubble_delegate_unittest.cc
@@ -229,7 +229,7 @@
     { 1000,        HTNOWHERE },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     gfx::Point point(cases[i].point, cases[i].point);
     EXPECT_EQ(cases[i].hit, frame->NonClientHitTest(point))
         << " with border: " << border << ", at point " << cases[i].point;
diff --git a/ui/views/bubble/bubble_frame_view.cc b/ui/views/bubble/bubble_frame_view.cc
index 531da17..e3eb3c8 100644
--- a/ui/views/bubble/bubble_frame_view.cc
+++ b/ui/views/bubble/bubble_frame_view.cc
@@ -253,7 +253,7 @@
 
 void BubbleFrameView::SetBubbleBorder(scoped_ptr<BubbleBorder> border) {
   bubble_border_ = border.get();
-  SetBorder(border.PassAs<Border>());
+  SetBorder(border.Pass());
 
   // Update the background, which relies on the border.
   set_background(new views::BubbleBackground(bubble_border_));
diff --git a/ui/views/controls/button/checkbox.cc b/ui/views/controls/button/checkbox.cc
index e67dc64..0a3a8f6 100644
--- a/ui/views/controls/button/checkbox.cc
+++ b/ui/views/controls/button/checkbox.cc
@@ -24,7 +24,7 @@
   button_border->SetPainter(false, STATE_PRESSED, NULL);
   // Inset the trailing side by a couple pixels for the focus border.
   button_border->set_insets(gfx::Insets(0, 0, 0, 2));
-  SetBorder(button_border.PassAs<Border>());
+  SetBorder(button_border.Pass());
   SetFocusable(true);
 
   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
diff --git a/ui/views/controls/button/label_button.cc b/ui/views/controls/button/label_button.cc
index 300c5a7..fe522d9 100644
--- a/ui/views/controls/button/label_button.cc
+++ b/ui/views/controls/button/label_button.cc
@@ -444,7 +444,7 @@
   } else
 #endif
   {
-    SetBorder(label_button_border.PassAs<Border>());
+    SetBorder(label_button_border.Pass());
   }
 
   border_is_themed_border_ = true;
diff --git a/ui/views/controls/combobox/combobox.cc b/ui/views/controls/combobox/combobox.cc
index 62b8ec3..22689c7 100644
--- a/ui/views/controls/combobox/combobox.cc
+++ b/ui/views/controls/combobox/combobox.cc
@@ -636,7 +636,7 @@
     border->SetInsets(5, 10, 5, 10);
   if (invalid_)
     border->SetColor(kWarningColor);
-  SetBorder(border.PassAs<Border>());
+  SetBorder(border.Pass());
 }
 
 void Combobox::AdjustBoundsForRTLUI(gfx::Rect* rect) const {
diff --git a/ui/views/controls/single_split_view_unittest.cc b/ui/views/controls/single_split_view_unittest.cc
index ca48b9a..de24285 100644
--- a/ui/views/controls/single_split_view_unittest.cc
+++ b/ui/views/controls/single_split_view_unittest.cc
@@ -120,7 +120,7 @@
     split.Layout();
 
     // Run all test cases.
-    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
+    for (size_t i = 0; i < arraysize(test_cases); ++i) {
       split.set_resize_leading_on_bounds_change(
           test_cases[i].resize_leading_on_bounds_change);
       if (split.orientation() == SingleSplitView::HORIZONTAL_SPLIT) {
diff --git a/ui/views/touchui/touch_editing_menu.cc b/ui/views/touchui/touch_editing_menu.cc
index 47f2bdb..771bfb3 100644
--- a/ui/views/touchui/touch_editing_menu.cc
+++ b/ui/views/touchui/touch_editing_menu.cc
@@ -154,7 +154,7 @@
   int h_border = (kMenuButtonWidth - gfx::GetStringWidth(label, font_list)) / 2;
   button_border->set_insets(
       gfx::Insets(v_border, h_border, v_border, h_border));
-  button->SetBorder(button_border.PassAs<Border>());
+  button->SetBorder(button_border.Pass());
   button->SetFontList(font_list);
   button->set_tag(tag);
   return button;
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc
index 4eb4958..76a4143 100644
--- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc
+++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc
@@ -12,6 +12,7 @@
 #undef None
 
 #include "base/memory/scoped_ptr.h"
+#include "base/run_loop.h"
 #include "ui/aura/window.h"
 #include "ui/aura/window_tree_host.h"
 #include "ui/base/hit_test.h"
@@ -189,6 +190,12 @@
   return false;
 }
 
+// Flush the message loop.
+void RunAllPendingInMessageLoop() {
+  base::RunLoop run_loop;
+  run_loop.RunUntilIdle();
+}
+
 }  // namespace
 
 class DesktopWindowTreeHostX11Test : public ViewsTestBase {
@@ -263,6 +270,9 @@
       waiter.Wait();
     }
 
+    // Ensure that the task which is posted when a window is resized is run.
+    RunAllPendingInMessageLoop();
+
     // xvfb does not support Xrandr so we cannot check the maximized window's
     // bounds.
     gfx::Rect maximized_bounds;
diff --git a/ui/views/window/dialog_delegate_unittest.cc b/ui/views/window/dialog_delegate_unittest.cc
index bbfa66b..7bbf191 100644
--- a/ui/views/window/dialog_delegate_unittest.cc
+++ b/ui/views/window/dialog_delegate_unittest.cc
@@ -203,7 +203,7 @@
     { 1000,        HTNOWHERE },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
+  for (size_t i = 0; i < arraysize(cases); ++i) {
     gfx::Point point(cases[i].point, cases[i].point);
     EXPECT_EQ(cases[i].hit, frame->NonClientHitTest(point))
         << " with border: " << border << ", at point " << cases[i].point;
diff --git a/ui/webui/resources/js/cr/ui/focus_grid.js b/ui/webui/resources/js/cr/ui/focus_grid.js
index 713a838..862b20a 100644
--- a/ui/webui/resources/js/cr/ui/focus_grid.js
+++ b/ui/webui/resources/js/cr/ui/focus_grid.js
@@ -42,6 +42,14 @@
 
   FocusGrid.prototype = {
     /**
+     * Unregisters event handlers and removes all |this.rows|.
+     */
+    destroy: function() {
+      this.rows.forEach(function(row) { row.destroy(); });
+      this.rows.length = 0;
+    },
+
+    /**
      * @param {EventTarget} target A target item to find in this grid.
      * @return {?{row: number, col: number}} A position or null if not found.
      */
@@ -86,7 +94,7 @@
      * @param {!Array.<!NodeList|!Array.<!Element>>} grid A 2D array of nodes.
      */
     setGrid: function(grid) {
-      this.rows.forEach(function(row) { row.destroy(); });
+      this.destroy();
 
       this.rows = grid.map(function(row) {
         return new cr.ui.FocusRow(row, this.boundary_, this, this.observer_);
diff --git a/ui/wm/BUILD.gn b/ui/wm/BUILD.gn
index e01ee94..67248f4 100644
--- a/ui/wm/BUILD.gn
+++ b/ui/wm/BUILD.gn
@@ -88,8 +88,6 @@
   ]
 }
 
-if (false) {
-
 static_library("test_support") {
   testonly = true
   sources = [
@@ -142,5 +140,3 @@
     "//ui/gl",
   ]
 }
-
-}  # if (false)
diff --git a/url/gurl_unittest.cc b/url/gurl_unittest.cc
index f38d7f9..3e94550 100644
--- a/url/gurl_unittest.cc
+++ b/url/gurl_unittest.cc
@@ -2,18 +2,12 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/macros.h"
 #include "testing/gtest/include/gtest/gtest.h"
 #include "url/gurl.h"
 #include "url/url_canon.h"
 #include "url/url_test_utils.h"
 
-// Some implementations of base/basictypes.h may define ARRAYSIZE.
-// If it's not defined, we define it to the ARRAYSIZE_UNSAFE macro
-// which is in our version of basictypes.h.
-#ifndef ARRAYSIZE
-#define ARRAYSIZE ARRAYSIZE_UNSAFE
-#endif
-
 namespace url {
 
 using test_utils::WStringToUTF16;
@@ -232,7 +226,7 @@
     "http:path",
     "://google.com",
   };
-  for (size_t i = 0; i < ARRAYSIZE(valid_cases); i++) {
+  for (size_t i = 0; i < arraysize(valid_cases); i++) {
     EXPECT_TRUE(GURL(valid_cases[i]).is_valid())
         << "Case: " << valid_cases[i];
   }
@@ -244,7 +238,7 @@
     "http://google.com:12three45",
     "path",
   };
-  for (size_t i = 0; i < ARRAYSIZE(invalid_cases); i++) {
+  for (size_t i = 0; i < arraysize(invalid_cases); i++) {
     EXPECT_FALSE(GURL(invalid_cases[i]).is_valid())
         << "Case: " << invalid_cases[i];
   }
@@ -299,7 +293,7 @@
     {"filesystem:http://www.google.com/type/", "../foo.html", true, "filesystem:http://www.google.com/type/foo.html"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(resolve_cases); i++) {
+  for (size_t i = 0; i < arraysize(resolve_cases); i++) {
     // 8-bit code path.
     GURL input(resolve_cases[i].base);
     GURL output = input.Resolve(resolve_cases[i].relative);
@@ -331,7 +325,7 @@
     {"filesystem:http://www.google.com/temp/foo?q#b", "http://www.google.com/"},
     {"filesystem:http://user:pass@google.com:21/blah#baz", "http://google.com:21/"},
   };
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     GURL url(cases[i].input);
     GURL origin = url.GetOrigin();
     EXPECT_EQ(cases[i].expected, origin.spec());
@@ -350,7 +344,7 @@
     {"http://:@www.google.com", "http://www.google.com/"},
     {"http://www.google.com/temp/foo?q#b", "http://www.google.com/temp/foo?q"},
   };
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     GURL url(cases[i].input);
     GURL origin = url.GetAsReferrer();
     EXPECT_EQ(cases[i].expected, origin.spec());
@@ -369,7 +363,7 @@
     {"filesystem:file:///temporary/bar.html?baz=22", "filesystem:file:///temporary/"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     GURL url(cases[i].input);
     GURL empty_path = url.GetWithEmptyPath();
     EXPECT_EQ(cases[i].expected, empty_path.spec());
@@ -401,7 +395,7 @@
     {"filesystem:http://www.google.com/foo/bar.html?foo#bar", NULL, NULL, NULL, NULL, NULL, "/", "", "", "filesystem:http://www.google.com/foo/"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(replace_cases); i++) {
+  for (size_t i = 0; i < arraysize(replace_cases); i++) {
     const ReplaceCase& cur = replace_cases[i];
     GURL url(cur.base);
     GURL::Replacements repl;
@@ -458,7 +452,7 @@
     {"filesystem:http://www.google.com/temporary/foo/bar.html?query", "/foo/bar.html?query", "/temporary"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     GURL url(cases[i].input);
     std::string path_request = url.PathForRequest();
     EXPECT_EQ(cases[i].expected, path_request);
@@ -506,7 +500,7 @@
     {"filesystem:file:///t/foo", PORT_UNSPECIFIED},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(port_tests); i++) {
+  for (size_t i = 0; i < arraysize(port_tests); i++) {
     GURL url(port_tests[i].spec);
     EXPECT_EQ(port_tests[i].expected_int_port, url.EffectiveIntPort());
   }
@@ -527,7 +521,7 @@
     {"some random input!", false},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(ip_tests); i++) {
+  for (size_t i = 0; i < arraysize(ip_tests); i++) {
     GURL url(ip_tests[i].spec);
     EXPECT_EQ(ip_tests[i].expected_ip, url.HostIsIPAddress());
   }
@@ -552,7 +546,7 @@
     {"http://]/", "]", "]"},
     {"", "", ""},
   };
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     GURL url(cases[i].input);
     EXPECT_EQ(cases[i].expected_host, url.host());
     EXPECT_EQ(cases[i].expected_plainhost, url.HostNoBrackets());
diff --git a/url/third_party/mozilla/url_parse.cc b/url/third_party/mozilla/url_parse.cc
index 6256796..ba842b8 100644
--- a/url/third_party/mozilla/url_parse.cc
+++ b/url/third_party/mozilla/url_parse.cc
@@ -621,23 +621,13 @@
     return;
   }
 
-  // Search backwards for a parameter, which is a normally unused field in a
-  // URL delimited by a semicolon. We parse the parameter as part of the
-  // path, but here, we don't want to count it. The last semicolon is the
-  // parameter. The path should start with a slash, so we don't need to check
-  // the first one.
+  // Extract the filename range from the path which is between
+  // the last slash and the following semicolon.
   int file_end = path.end();
-  for (int i = path.end() - 1; i > path.begin; i--) {
+  for (int i = path.end() - 1; i >= path.begin; i--) {
     if (spec[i] == ';') {
       file_end = i;
-      break;
-    }
-  }
-
-  // Now search backwards from the filename end to the previous slash
-  // to find the beginning of the filename.
-  for (int i = file_end - 1; i >= path.begin; i--) {
-    if (IsURLSlash(spec[i])) {
+    } else if (IsURLSlash(spec[i])) {
       // File name is everything following this character to the end
       *file_name = MakeRange(i + 1, file_end);
       return;
diff --git a/url/url_canon_icu_unittest.cc b/url/url_canon_icu_unittest.cc
index b28c30a..12b7ded 100644
--- a/url/url_canon_icu_unittest.cc
+++ b/url/url_canon_icu_unittest.cc
@@ -10,13 +10,6 @@
 #include "url/url_canon_stdstring.h"
 #include "url/url_test_utils.h"
 
-// Some implementations of base/basictypes.h may define ARRAYSIZE.
-// If it's not defined, we define it to the ARRAYSIZE_UNSAFE macro
-// which is in our version of basictypes.h.
-#ifndef ARRAYSIZE
-#define ARRAYSIZE ARRAYSIZE_UNSAFE
-#endif
-
 namespace url {
 
 using test_utils::WStringToUTF16;
@@ -61,7 +54,7 @@
       "hello\xa7\x41%26%231758%3B\xa6\x6eworld"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(icu_cases); i++) {
+  for (size_t i = 0; i < arraysize(icu_cases); i++) {
     UConvScoper conv(icu_cases[i].encoding);
     ASSERT_TRUE(conv.converter() != NULL);
     ICUCharsetConverter converter(conv.converter());
@@ -118,7 +111,7 @@
       "?q=Chinese%26%2365319%3B"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(query_cases); i++) {
+  for (size_t i = 0; i < arraysize(query_cases); i++) {
     Component out_comp;
 
     UConvScoper conv(query_cases[i].encoding);
diff --git a/url/url_canon_unittest.cc b/url/url_canon_unittest.cc
index 469e8a0..3ab8710 100644
--- a/url/url_canon_unittest.cc
+++ b/url/url_canon_unittest.cc
@@ -12,13 +12,6 @@
 #include "url/url_parse.h"
 #include "url/url_test_utils.h"
 
-// Some implementations of base/basictypes.h may define ARRAYSIZE.
-// If it's not defined, we define it to the ARRAYSIZE_UNSAFE macro
-// which is in our version of basictypes.h.
-#ifndef ARRAYSIZE
-#define ARRAYSIZE ARRAYSIZE_UNSAFE
-#endif
-
 namespace url {
 
 using test_utils::WStringToUTF16;
@@ -123,7 +116,7 @@
     {0x10FFFF, "\xF4\x8F\xBF\xBF"},
   };
   std::string out_str;
-  for (size_t i = 0; i < ARRAYSIZE(utf_cases); i++) {
+  for (size_t i = 0; i < arraysize(utf_cases); i++) {
     out_str.clear();
     StdStringCanonOutput output(&out_str);
     AppendUTF8Value(utf_cases[i].input, &output);
@@ -182,7 +175,7 @@
   };
 
   std::string out_str;
-  for (size_t i = 0; i < ARRAYSIZE(utf_cases); i++) {
+  for (size_t i = 0; i < arraysize(utf_cases); i++) {
     if (utf_cases[i].input8) {
       out_str.clear();
       StdStringCanonOutput output(&out_str);
@@ -899,7 +892,7 @@
     {"ftp://me\\mydomain:pass@foo.com/", "", Component(0, -1), Component(0, -1), true},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(user_info_cases); i++) {
+  for (size_t i = 0; i < arraysize(user_info_cases); i++) {
     int url_len = static_cast<int>(strlen(user_info_cases[i].input));
     Parsed parsed;
     ParseStandardURL(user_info_cases[i].input, url_len, &parsed);
@@ -968,7 +961,7 @@
     {"80", PORT_UNSPECIFIED, ":80", Component(1, 2), true},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(port_cases); i++) {
+  for (size_t i = 0; i < arraysize(port_cases); i++) {
     int url_len = static_cast<int>(strlen(port_cases[i].input));
     Component in_comp(0, url_len);
     Component out_comp;
@@ -1152,7 +1145,7 @@
     {"q=\"asdf\"", L"q=\"asdf\"", "?q=%22asdf%22"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(query_cases); i++) {
+  for (size_t i = 0; i < arraysize(query_cases); i++) {
     Component out_comp;
 
     if (query_cases[i].input8) {
@@ -1309,7 +1302,7 @@
     {"wss://foo:815/", "wss://foo:815/", true},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     int url_len = static_cast<int>(strlen(cases[i].input));
     Parsed parsed;
     ParseStandardURL(cases[i].input, url_len, &parsed);
@@ -1648,7 +1641,7 @@
 #endif  // _WIN32
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     int url_len = static_cast<int>(strlen(cases[i].input));
     Parsed parsed;
     ParseFileURL(cases[i].input, url_len, &parsed);
@@ -1691,7 +1684,7 @@
     {"filesystem:File:///temporary/Bob?qUery#reF", "filesystem:file:///temporary/Bob?qUery#reF", true},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     int url_len = static_cast<int>(strlen(cases[i].input));
     Parsed parsed;
     ParseFileSystemURL(cases[i].input, url_len, &parsed);
@@ -1726,7 +1719,7 @@
     {":\":This /is interesting;?#", ":\":This /is interesting;?#"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(path_cases); i++) {
+  for (size_t i = 0; i < arraysize(path_cases); i++) {
     int url_len = static_cast<int>(strlen(path_cases[i].input));
     Parsed parsed;
     ParsePathURL(path_cases[i].input, url_len, true, &parsed);
@@ -1780,7 +1773,7 @@
   Parsed parsed;
   Parsed out_parsed;
 
-  for (size_t i = 0; i < ARRAYSIZE(cases); i++) {
+  for (size_t i = 0; i < arraysize(cases); i++) {
     int url_len = static_cast<int>(strlen(cases[i].input));
     if (i == 8) {
       // The 9th test case purposely has a '\0' in it -- don't count it
@@ -2043,7 +2036,7 @@
     {"about:blank", false, false, "content://content.Provider/", true, false, true, ""},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(rel_cases); i++) {
+  for (size_t i = 0; i < arraysize(rel_cases); i++) {
     const RelativeCase& cur_case = rel_cases[i];
 
     Parsed parsed;
diff --git a/url/url_parse_unittest.cc b/url/url_parse_unittest.cc
index a8b7f85..71b2438 100644
--- a/url/url_parse_unittest.cc
+++ b/url/url_parse_unittest.cc
@@ -4,17 +4,10 @@
 
 #include "url/url_parse.h"
 
-#include "base/basictypes.h"
+#include "base/macros.h"
 #include "testing/gtest/include/gtest/gtest.h"
 #include "url/url_parse.h"
 
-// Some implementations of base/basictypes.h may define ARRAYSIZE.
-// If it's not defined, we define it to the ARRAYSIZE_UNSAFE macro
-// which is in our version of basictypes.h.
-#ifndef ARRAYSIZE
-#define ARRAYSIZE ARRAYSIZE_UNSAFE
-#endif
-
 // Interesting IE file:isms...
 //
 //  file:/foo/bar              file:///foo/bar
@@ -201,7 +194,7 @@
     {"file:///c:/foo", Parsed::HOST, true, 7},
     {"file:///c:/foo", Parsed::PATH, true, 7},
   };
-  for (size_t i = 0; i < ARRAYSIZE(count_cases); i++) {
+  for (size_t i = 0; i < arraysize(count_cases); i++) {
     int length = static_cast<int>(strlen(count_cases[i].url));
 
     // Simple test to distinguish file and standard URLs.
@@ -505,11 +498,16 @@
     {"http://www.google.com/foo/bar.html#ref", "bar.html"},
     {"http://www.google.com/search/;param", ""},
     {"http://www.google.com/foo/bar.html;param#ref", "bar.html"},
-    {"http://www.google.com/foo/bar.html;foo;param#ref", "bar.html;foo"},
+    {"http://www.google.com/foo/bar.html;foo;param#ref", "bar.html"},
     {"http://www.google.com/foo/bar.html?query#ref", "bar.html"},
+    {"http://www.google.com/foo;/bar.html", "bar.html"},
+    {"http://www.google.com/foo;/", ""},
+    {"http://www.google.com/foo;", "foo"},
+    {"http://www.google.com/;", ""},
+    {"http://www.google.com/foo;bar;html", "foo"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE(file_cases); i++) {
+  for (size_t i = 0; i < arraysize(file_cases); i++) {
     const char* url = file_cases[i].input;
     int len = static_cast<int>(strlen(url));
 
diff --git a/url/url_util_unittest.cc b/url/url_util_unittest.cc
index f84b70d..ea4824f 100644
--- a/url/url_util_unittest.cc
+++ b/url/url_util_unittest.cc
@@ -2,6 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "base/macros.h"
 #include "testing/gtest/include/gtest/gtest.h"
 #include "url/url_canon.h"
 #include "url/url_canon_stdstring.h"
@@ -159,7 +160,7 @@
     {"%e4%bd%a0%e5%a5%bd", "\xe4\xbd\xa0\xe5\xa5\xbd"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(decode_cases); i++) {
+  for (size_t i = 0; i < arraysize(decode_cases); i++) {
     const char* input = decode_cases[i].input;
     RawCanonOutputT<base::char16> output;
     DecodeURLEscapeSequences(input, strlen(input), &output);
@@ -209,7 +210,7 @@
      "pqrstuvwxyz%7B%7C%7D~%7F"},
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(encode_cases); i++) {
+  for (size_t i = 0; i < arraysize(encode_cases); i++) {
     const char* input = encode_cases[i].input;
     RawCanonOutputT<char> buffer;
     EncodeURIComponent(input, strlen(input), &buffer);
@@ -274,7 +275,7 @@
       "javascript:alert('foo#badfrag" },
   };
 
-  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(resolve_non_standard_cases); i++) {
+  for (size_t i = 0; i < arraysize(resolve_non_standard_cases); i++) {
     const ResolveRelativeCase& test_data = resolve_non_standard_cases[i];
     Parsed base_parsed;
     ParsePathURL(test_data.base, strlen(test_data.base), false, &base_parsed);